@atproto/lex-cbor 0.0.16 → 0.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs DELETED
@@ -1,1723 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const lexData = require("@atproto/lex-data");
4
- const objectTypeNames = [
5
- "Object",
6
- // for Object.create(null) and other non-plain objects
7
- "RegExp",
8
- "Date",
9
- "Error",
10
- "Map",
11
- "Set",
12
- "WeakMap",
13
- "WeakSet",
14
- "ArrayBuffer",
15
- "SharedArrayBuffer",
16
- "DataView",
17
- "Promise",
18
- "URL",
19
- "HTMLElement",
20
- "Int8Array",
21
- "Uint8ClampedArray",
22
- "Int16Array",
23
- "Uint16Array",
24
- "Int32Array",
25
- "Uint32Array",
26
- "Float32Array",
27
- "Float64Array",
28
- "BigInt64Array",
29
- "BigUint64Array"
30
- ];
31
- function is(value) {
32
- if (value === null) {
33
- return "null";
34
- }
35
- if (value === void 0) {
36
- return "undefined";
37
- }
38
- if (value === true || value === false) {
39
- return "boolean";
40
- }
41
- const typeOf = typeof value;
42
- if (typeOf === "string" || typeOf === "number" || typeOf === "bigint" || typeOf === "symbol") {
43
- return typeOf;
44
- }
45
- if (typeOf === "function") {
46
- return "Function";
47
- }
48
- if (Array.isArray(value)) {
49
- return "Array";
50
- }
51
- if (value instanceof Uint8Array) {
52
- return "Uint8Array";
53
- }
54
- if (value.constructor === Object) {
55
- return "Object";
56
- }
57
- const objectType = getObjectType(value);
58
- if (objectType) {
59
- return objectType;
60
- }
61
- return "Object";
62
- }
63
- function getObjectType(value) {
64
- const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);
65
- if (objectTypeNames.includes(objectTypeName)) {
66
- return objectTypeName;
67
- }
68
- return void 0;
69
- }
70
- class Type {
71
- /**
72
- * @param {number} major
73
- * @param {string} name
74
- * @param {boolean} terminal
75
- */
76
- constructor(major, name, terminal) {
77
- this.major = major;
78
- this.majorEncoded = major << 5;
79
- this.name = name;
80
- this.terminal = terminal;
81
- }
82
- /* c8 ignore next 3 */
83
- toString() {
84
- return `Type[${this.major}].${this.name}`;
85
- }
86
- /**
87
- * @param {Type} typ
88
- * @returns {number}
89
- */
90
- compare(typ) {
91
- return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;
92
- }
93
- /**
94
- * Check equality between two Type instances. Safe to use across different
95
- * copies of the Type class (e.g., when bundlers duplicate the module).
96
- * (major, name) uniquely identifies a Type; terminal is implied by these.
97
- * @param {Type} a
98
- * @param {Type} b
99
- * @returns {boolean}
100
- */
101
- static equals(a, b) {
102
- return a === b || a.major === b.major && a.name === b.name;
103
- }
104
- }
105
- Type.uint = new Type(0, "uint", true);
106
- Type.negint = new Type(1, "negint", true);
107
- Type.bytes = new Type(2, "bytes", true);
108
- Type.string = new Type(3, "string", true);
109
- Type.array = new Type(4, "array", false);
110
- Type.map = new Type(5, "map", false);
111
- Type.tag = new Type(6, "tag", false);
112
- Type.float = new Type(7, "float", true);
113
- Type.false = new Type(7, "false", true);
114
- Type.true = new Type(7, "true", true);
115
- Type.null = new Type(7, "null", true);
116
- Type.undefined = new Type(7, "undefined", true);
117
- Type.break = new Type(7, "break", true);
118
- class Token {
119
- /**
120
- * @param {Type} type
121
- * @param {any} [value]
122
- * @param {number} [encodedLength]
123
- */
124
- constructor(type, value, encodedLength) {
125
- this.type = type;
126
- this.value = value;
127
- this.encodedLength = encodedLength;
128
- this.encodedBytes = void 0;
129
- this.byteValue = void 0;
130
- }
131
- /* c8 ignore next 3 */
132
- toString() {
133
- return `Token[${this.type}].${this.value}`;
134
- }
135
- }
136
- const useBuffer = globalThis.process && // @ts-ignore
137
- !globalThis.process.browser && // @ts-ignore
138
- globalThis.Buffer && // @ts-ignore
139
- typeof globalThis.Buffer.isBuffer === "function";
140
- const textEncoder = new TextEncoder();
141
- function isBuffer(buf) {
142
- return useBuffer && globalThis.Buffer.isBuffer(buf);
143
- }
144
- function asU8A(buf) {
145
- if (!(buf instanceof Uint8Array)) {
146
- return Uint8Array.from(buf);
147
- }
148
- return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;
149
- }
150
- const FROM_STRING_THRESHOLD_BUFFER = 24;
151
- const FROM_STRING_THRESHOLD_TEXTENCODER = 200;
152
- const fromString = useBuffer ? (
153
- // eslint-disable-line operator-linebreak
154
- /**
155
- * @param {string} string
156
- */
157
- (string) => {
158
- return string.length >= FROM_STRING_THRESHOLD_BUFFER ? (
159
- // eslint-disable-line operator-linebreak
160
- // @ts-ignore
161
- globalThis.Buffer.from(string)
162
- ) : utf8ToBytes(string);
163
- }
164
- ) : (
165
- // eslint-disable-line operator-linebreak
166
- /**
167
- * @param {string} string
168
- */
169
- (string) => {
170
- return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string);
171
- }
172
- );
173
- const fromArray = (arr) => {
174
- return Uint8Array.from(arr);
175
- };
176
- const slice = useBuffer ? (
177
- // eslint-disable-line operator-linebreak
178
- /**
179
- * @param {Uint8Array} bytes
180
- * @param {number} start
181
- * @param {number} end
182
- */
183
- // Buffer.slice() returns a view, not a copy, so we need special handling
184
- (bytes, start, end) => {
185
- if (isBuffer(bytes)) {
186
- return new Uint8Array(bytes.subarray(start, end));
187
- }
188
- return bytes.slice(start, end);
189
- }
190
- ) : (
191
- // eslint-disable-line operator-linebreak
192
- /**
193
- * @param {Uint8Array} bytes
194
- * @param {number} start
195
- * @param {number} end
196
- */
197
- (bytes, start, end) => {
198
- return bytes.slice(start, end);
199
- }
200
- );
201
- const concat = useBuffer ? (
202
- // eslint-disable-line operator-linebreak
203
- /**
204
- * @param {Uint8Array[]} chunks
205
- * @param {number} length
206
- * @returns {Uint8Array}
207
- */
208
- (chunks, length) => {
209
- chunks = chunks.map((c) => c instanceof Uint8Array ? c : (
210
- // eslint-disable-line operator-linebreak
211
- // @ts-ignore
212
- globalThis.Buffer.from(c)
213
- ));
214
- return asU8A(globalThis.Buffer.concat(chunks, length));
215
- }
216
- ) : (
217
- // eslint-disable-line operator-linebreak
218
- /**
219
- * @param {Uint8Array[]} chunks
220
- * @param {number} length
221
- * @returns {Uint8Array}
222
- */
223
- (chunks, length) => {
224
- const out = new Uint8Array(length);
225
- let off = 0;
226
- for (let b of chunks) {
227
- if (off + b.length > out.length) {
228
- b = b.subarray(0, out.length - off);
229
- }
230
- out.set(b, off);
231
- off += b.length;
232
- }
233
- return out;
234
- }
235
- );
236
- const alloc = useBuffer ? (
237
- // eslint-disable-line operator-linebreak
238
- /**
239
- * @param {number} size
240
- * @returns {Uint8Array}
241
- */
242
- (size) => {
243
- return globalThis.Buffer.allocUnsafe(size);
244
- }
245
- ) : (
246
- // eslint-disable-line operator-linebreak
247
- /**
248
- * @param {number} size
249
- * @returns {Uint8Array}
250
- */
251
- (size) => {
252
- return new Uint8Array(size);
253
- }
254
- );
255
- function compare(b1, b2) {
256
- if (isBuffer(b1) && isBuffer(b2)) {
257
- return b1.compare(b2);
258
- }
259
- for (let i = 0; i < b1.length; i++) {
260
- if (b1[i] === b2[i]) {
261
- continue;
262
- }
263
- return b1[i] < b2[i] ? -1 : 1;
264
- }
265
- return 0;
266
- }
267
- function utf8ToBytes(str) {
268
- const out = [];
269
- let p = 0;
270
- for (let i = 0; i < str.length; i++) {
271
- let c = str.charCodeAt(i);
272
- if (c < 128) {
273
- out[p++] = c;
274
- } else if (c < 2048) {
275
- out[p++] = c >> 6 | 192;
276
- out[p++] = c & 63 | 128;
277
- } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) {
278
- c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023);
279
- out[p++] = c >> 18 | 240;
280
- out[p++] = c >> 12 & 63 | 128;
281
- out[p++] = c >> 6 & 63 | 128;
282
- out[p++] = c & 63 | 128;
283
- } else {
284
- if (c >= 55296 && c <= 57343) {
285
- c = 65533;
286
- }
287
- out[p++] = c >> 12 | 224;
288
- out[p++] = c >> 6 & 63 | 128;
289
- out[p++] = c & 63 | 128;
290
- }
291
- }
292
- return out;
293
- }
294
- const defaultChunkSize = 256;
295
- class Bl {
296
- /**
297
- * @param {number} [chunkSize]
298
- */
299
- constructor(chunkSize = defaultChunkSize) {
300
- this.chunkSize = chunkSize;
301
- this.cursor = 0;
302
- this.maxCursor = -1;
303
- this.chunks = [];
304
- this._initReuseChunk = null;
305
- }
306
- reset() {
307
- this.cursor = 0;
308
- this.maxCursor = -1;
309
- if (this.chunks.length) {
310
- this.chunks = [];
311
- }
312
- if (this._initReuseChunk !== null) {
313
- this.chunks.push(this._initReuseChunk);
314
- this.maxCursor = this._initReuseChunk.length - 1;
315
- }
316
- }
317
- /**
318
- * @param {Uint8Array|number[]} bytes
319
- */
320
- push(bytes) {
321
- let topChunk = this.chunks[this.chunks.length - 1];
322
- const newMax = this.cursor + bytes.length;
323
- if (newMax <= this.maxCursor + 1) {
324
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
325
- topChunk.set(bytes, chunkPos);
326
- } else {
327
- if (topChunk) {
328
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
329
- if (chunkPos < topChunk.length) {
330
- this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);
331
- this.maxCursor = this.cursor - 1;
332
- }
333
- }
334
- if (bytes.length < 64 && bytes.length < this.chunkSize) {
335
- topChunk = alloc(this.chunkSize);
336
- this.chunks.push(topChunk);
337
- this.maxCursor += topChunk.length;
338
- if (this._initReuseChunk === null) {
339
- this._initReuseChunk = topChunk;
340
- }
341
- topChunk.set(bytes, 0);
342
- } else {
343
- this.chunks.push(bytes);
344
- this.maxCursor += bytes.length;
345
- }
346
- }
347
- this.cursor += bytes.length;
348
- }
349
- /**
350
- * @param {boolean} [reset]
351
- * @returns {Uint8Array}
352
- */
353
- toBytes(reset = false) {
354
- let byts;
355
- if (this.chunks.length === 1) {
356
- const chunk = this.chunks[0];
357
- if (reset && this.cursor > chunk.length / 2) {
358
- byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);
359
- this._initReuseChunk = null;
360
- this.chunks = [];
361
- } else {
362
- byts = slice(chunk, 0, this.cursor);
363
- }
364
- } else {
365
- byts = concat(this.chunks, this.cursor);
366
- }
367
- if (reset) {
368
- this.reset();
369
- }
370
- return byts;
371
- }
372
- }
373
- class U8Bl {
374
- /**
375
- * @param {Uint8Array} dest
376
- */
377
- constructor(dest) {
378
- this.dest = dest;
379
- this.cursor = 0;
380
- this.chunks = [dest];
381
- }
382
- reset() {
383
- this.cursor = 0;
384
- }
385
- /**
386
- * @param {Uint8Array|number[]} bytes
387
- */
388
- push(bytes) {
389
- if (this.cursor + bytes.length > this.dest.length) {
390
- throw new Error("write out of bounds, destination buffer is too small");
391
- }
392
- this.dest.set(bytes, this.cursor);
393
- this.cursor += bytes.length;
394
- }
395
- /**
396
- * @param {boolean} [reset]
397
- * @returns {Uint8Array}
398
- */
399
- toBytes(reset = false) {
400
- const byts = this.dest.subarray(0, this.cursor);
401
- if (reset) {
402
- this.reset();
403
- }
404
- return byts;
405
- }
406
- }
407
- const decodeErrPrefix = "CBOR decode error:";
408
- const encodeErrPrefix = "CBOR encode error:";
409
- function assertEnoughData(data, pos, need) {
410
- if (data.length - pos < need) {
411
- throw new Error(`${decodeErrPrefix} not enough data for type`);
412
- }
413
- }
414
- const uintBoundaries = [24, 256, 65536, 4294967296, BigInt("18446744073709551616")];
415
- function readUint8(data, offset, options) {
416
- assertEnoughData(data, offset, 1);
417
- const value = data[offset];
418
- if (options.strict === true && value < uintBoundaries[0]) {
419
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
420
- }
421
- return value;
422
- }
423
- function readUint16(data, offset, options) {
424
- assertEnoughData(data, offset, 2);
425
- const value = data[offset] << 8 | data[offset + 1];
426
- if (options.strict === true && value < uintBoundaries[1]) {
427
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
428
- }
429
- return value;
430
- }
431
- function readUint32(data, offset, options) {
432
- assertEnoughData(data, offset, 4);
433
- const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
434
- if (options.strict === true && value < uintBoundaries[2]) {
435
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
436
- }
437
- return value;
438
- }
439
- function readUint64(data, offset, options) {
440
- assertEnoughData(data, offset, 8);
441
- const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
442
- const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];
443
- const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);
444
- if (options.strict === true && value < uintBoundaries[3]) {
445
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
446
- }
447
- if (value <= Number.MAX_SAFE_INTEGER) {
448
- return Number(value);
449
- }
450
- if (options.allowBigInt === true) {
451
- return value;
452
- }
453
- throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
454
- }
455
- function decodeUint8(data, pos, _minor, options) {
456
- return new Token(Type.uint, readUint8(data, pos + 1, options), 2);
457
- }
458
- function decodeUint16(data, pos, _minor, options) {
459
- return new Token(Type.uint, readUint16(data, pos + 1, options), 3);
460
- }
461
- function decodeUint32(data, pos, _minor, options) {
462
- return new Token(Type.uint, readUint32(data, pos + 1, options), 5);
463
- }
464
- function decodeUint64(data, pos, _minor, options) {
465
- return new Token(Type.uint, readUint64(data, pos + 1, options), 9);
466
- }
467
- function encodeUint(writer, token) {
468
- return encodeUintValue(writer, 0, token.value);
469
- }
470
- function encodeUintValue(writer, major, uint) {
471
- if (uint < uintBoundaries[0]) {
472
- const nuint = Number(uint);
473
- writer.push([major | nuint]);
474
- } else if (uint < uintBoundaries[1]) {
475
- const nuint = Number(uint);
476
- writer.push([major | 24, nuint]);
477
- } else if (uint < uintBoundaries[2]) {
478
- const nuint = Number(uint);
479
- writer.push([major | 25, nuint >>> 8, nuint & 255]);
480
- } else if (uint < uintBoundaries[3]) {
481
- const nuint = Number(uint);
482
- writer.push([major | 26, nuint >>> 24 & 255, nuint >>> 16 & 255, nuint >>> 8 & 255, nuint & 255]);
483
- } else {
484
- const buint = BigInt(uint);
485
- if (buint < uintBoundaries[4]) {
486
- const set = [major | 27, 0, 0, 0, 0, 0, 0, 0];
487
- let lo = Number(buint & BigInt(4294967295));
488
- let hi = Number(buint >> BigInt(32) & BigInt(4294967295));
489
- set[8] = lo & 255;
490
- lo = lo >> 8;
491
- set[7] = lo & 255;
492
- lo = lo >> 8;
493
- set[6] = lo & 255;
494
- lo = lo >> 8;
495
- set[5] = lo & 255;
496
- set[4] = hi & 255;
497
- hi = hi >> 8;
498
- set[3] = hi & 255;
499
- hi = hi >> 8;
500
- set[2] = hi & 255;
501
- hi = hi >> 8;
502
- set[1] = hi & 255;
503
- writer.push(set);
504
- } else {
505
- throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`);
506
- }
507
- }
508
- }
509
- encodeUint.encodedSize = function encodedSize(token) {
510
- return encodeUintValue.encodedSize(token.value);
511
- };
512
- encodeUintValue.encodedSize = function encodedSize2(uint) {
513
- if (uint < uintBoundaries[0]) {
514
- return 1;
515
- }
516
- if (uint < uintBoundaries[1]) {
517
- return 2;
518
- }
519
- if (uint < uintBoundaries[2]) {
520
- return 3;
521
- }
522
- if (uint < uintBoundaries[3]) {
523
- return 5;
524
- }
525
- return 9;
526
- };
527
- encodeUint.compareTokens = function compareTokens(tok1, tok2) {
528
- return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : (
529
- /* c8 ignore next */
530
- 0
531
- );
532
- };
533
- function decodeNegint8(data, pos, _minor, options) {
534
- return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2);
535
- }
536
- function decodeNegint16(data, pos, _minor, options) {
537
- return new Token(Type.negint, -1 - readUint16(data, pos + 1, options), 3);
538
- }
539
- function decodeNegint32(data, pos, _minor, options) {
540
- return new Token(Type.negint, -1 - readUint32(data, pos + 1, options), 5);
541
- }
542
- const neg1b$1 = BigInt(-1);
543
- const pos1b$1 = BigInt(1);
544
- function decodeNegint64(data, pos, _minor, options) {
545
- const int = readUint64(data, pos + 1, options);
546
- if (typeof int !== "bigint") {
547
- const value = -1 - int;
548
- if (value >= Number.MIN_SAFE_INTEGER) {
549
- return new Token(Type.negint, value, 9);
550
- }
551
- }
552
- if (options.allowBigInt !== true) {
553
- throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
554
- }
555
- return new Token(Type.negint, neg1b$1 - BigInt(int), 9);
556
- }
557
- function encodeNegint(writer, token) {
558
- const negint = token.value;
559
- const unsigned = typeof negint === "bigint" ? negint * neg1b$1 - pos1b$1 : negint * -1 - 1;
560
- encodeUintValue(writer, token.type.majorEncoded, unsigned);
561
- }
562
- encodeNegint.encodedSize = function encodedSize3(token) {
563
- const negint = token.value;
564
- const unsigned = typeof negint === "bigint" ? negint * neg1b$1 - pos1b$1 : negint * -1 - 1;
565
- if (unsigned < uintBoundaries[0]) {
566
- return 1;
567
- }
568
- if (unsigned < uintBoundaries[1]) {
569
- return 2;
570
- }
571
- if (unsigned < uintBoundaries[2]) {
572
- return 3;
573
- }
574
- if (unsigned < uintBoundaries[3]) {
575
- return 5;
576
- }
577
- return 9;
578
- };
579
- encodeNegint.compareTokens = function compareTokens2(tok1, tok2) {
580
- return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : (
581
- /* c8 ignore next */
582
- 0
583
- );
584
- };
585
- function toToken$3(data, pos, prefix, length) {
586
- assertEnoughData(data, pos, prefix + length);
587
- const buf = data.slice(pos + prefix, pos + prefix + length);
588
- return new Token(Type.bytes, buf, prefix + length);
589
- }
590
- function decodeBytesCompact(data, pos, minor, _options) {
591
- return toToken$3(data, pos, 1, minor);
592
- }
593
- function decodeBytes8(data, pos, _minor, options) {
594
- return toToken$3(data, pos, 2, readUint8(data, pos + 1, options));
595
- }
596
- function decodeBytes16(data, pos, _minor, options) {
597
- return toToken$3(data, pos, 3, readUint16(data, pos + 1, options));
598
- }
599
- function decodeBytes32(data, pos, _minor, options) {
600
- return toToken$3(data, pos, 5, readUint32(data, pos + 1, options));
601
- }
602
- function decodeBytes64(data, pos, _minor, options) {
603
- const l = readUint64(data, pos + 1, options);
604
- if (typeof l === "bigint") {
605
- throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`);
606
- }
607
- return toToken$3(data, pos, 9, l);
608
- }
609
- function tokenBytes(token) {
610
- if (token.encodedBytes === void 0) {
611
- token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value;
612
- }
613
- return token.encodedBytes;
614
- }
615
- function encodeBytes(writer, token) {
616
- const bytes = tokenBytes(token);
617
- encodeUintValue(writer, token.type.majorEncoded, bytes.length);
618
- writer.push(bytes);
619
- }
620
- encodeBytes.encodedSize = function encodedSize4(token) {
621
- const bytes = tokenBytes(token);
622
- return encodeUintValue.encodedSize(bytes.length) + bytes.length;
623
- };
624
- encodeBytes.compareTokens = function compareTokens3(tok1, tok2) {
625
- return compareBytes(tokenBytes(tok1), tokenBytes(tok2));
626
- };
627
- function compareBytes(b1, b2) {
628
- return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
629
- }
630
- const textDecoder = new TextDecoder();
631
- const ASCII_THRESHOLD = 32;
632
- function toStr(bytes, start, end) {
633
- const len = end - start;
634
- if (len < ASCII_THRESHOLD) {
635
- let str = "";
636
- for (let i = start; i < end; i++) {
637
- const c = bytes[i];
638
- if (c & 128) {
639
- return textDecoder.decode(bytes.subarray(start, end));
640
- }
641
- str += String.fromCharCode(c);
642
- }
643
- return str;
644
- }
645
- return textDecoder.decode(bytes.subarray(start, end));
646
- }
647
- function toToken$2(data, pos, prefix, length, options) {
648
- const totLength = prefix + length;
649
- assertEnoughData(data, pos, totLength);
650
- const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength);
651
- if (options.retainStringBytes === true) {
652
- tok.byteValue = data.slice(pos + prefix, pos + totLength);
653
- }
654
- return tok;
655
- }
656
- function decodeStringCompact(data, pos, minor, options) {
657
- return toToken$2(data, pos, 1, minor, options);
658
- }
659
- function decodeString8(data, pos, _minor, options) {
660
- return toToken$2(data, pos, 2, readUint8(data, pos + 1, options), options);
661
- }
662
- function decodeString16(data, pos, _minor, options) {
663
- return toToken$2(data, pos, 3, readUint16(data, pos + 1, options), options);
664
- }
665
- function decodeString32(data, pos, _minor, options) {
666
- return toToken$2(data, pos, 5, readUint32(data, pos + 1, options), options);
667
- }
668
- function decodeString64(data, pos, _minor, options) {
669
- const l = readUint64(data, pos + 1, options);
670
- if (typeof l === "bigint") {
671
- throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`);
672
- }
673
- return toToken$2(data, pos, 9, l, options);
674
- }
675
- const encodeString = encodeBytes;
676
- function toToken$1(_data, _pos, prefix, length) {
677
- return new Token(Type.array, length, prefix);
678
- }
679
- function decodeArrayCompact(data, pos, minor, _options) {
680
- return toToken$1(data, pos, 1, minor);
681
- }
682
- function decodeArray8(data, pos, _minor, options) {
683
- return toToken$1(data, pos, 2, readUint8(data, pos + 1, options));
684
- }
685
- function decodeArray16(data, pos, _minor, options) {
686
- return toToken$1(data, pos, 3, readUint16(data, pos + 1, options));
687
- }
688
- function decodeArray32(data, pos, _minor, options) {
689
- return toToken$1(data, pos, 5, readUint32(data, pos + 1, options));
690
- }
691
- function decodeArray64(data, pos, _minor, options) {
692
- const l = readUint64(data, pos + 1, options);
693
- if (typeof l === "bigint") {
694
- throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`);
695
- }
696
- return toToken$1(data, pos, 9, l);
697
- }
698
- function decodeArrayIndefinite(data, pos, _minor, options) {
699
- if (options.allowIndefinite === false) {
700
- throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
701
- }
702
- return toToken$1(data, pos, 1, Infinity);
703
- }
704
- function encodeArray(writer, token) {
705
- encodeUintValue(writer, Type.array.majorEncoded, token.value);
706
- }
707
- encodeArray.compareTokens = encodeUint.compareTokens;
708
- encodeArray.encodedSize = function encodedSize5(token) {
709
- return encodeUintValue.encodedSize(token.value);
710
- };
711
- function toToken(_data, _pos, prefix, length) {
712
- return new Token(Type.map, length, prefix);
713
- }
714
- function decodeMapCompact(data, pos, minor, _options) {
715
- return toToken(data, pos, 1, minor);
716
- }
717
- function decodeMap8(data, pos, _minor, options) {
718
- return toToken(data, pos, 2, readUint8(data, pos + 1, options));
719
- }
720
- function decodeMap16(data, pos, _minor, options) {
721
- return toToken(data, pos, 3, readUint16(data, pos + 1, options));
722
- }
723
- function decodeMap32(data, pos, _minor, options) {
724
- return toToken(data, pos, 5, readUint32(data, pos + 1, options));
725
- }
726
- function decodeMap64(data, pos, _minor, options) {
727
- const l = readUint64(data, pos + 1, options);
728
- if (typeof l === "bigint") {
729
- throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`);
730
- }
731
- return toToken(data, pos, 9, l);
732
- }
733
- function decodeMapIndefinite(data, pos, _minor, options) {
734
- if (options.allowIndefinite === false) {
735
- throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
736
- }
737
- return toToken(data, pos, 1, Infinity);
738
- }
739
- function encodeMap(writer, token) {
740
- encodeUintValue(writer, Type.map.majorEncoded, token.value);
741
- }
742
- encodeMap.compareTokens = encodeUint.compareTokens;
743
- encodeMap.encodedSize = function encodedSize6(token) {
744
- return encodeUintValue.encodedSize(token.value);
745
- };
746
- function decodeTagCompact(_data, _pos, minor, _options) {
747
- return new Token(Type.tag, minor, 1);
748
- }
749
- function decodeTag8(data, pos, _minor, options) {
750
- return new Token(Type.tag, readUint8(data, pos + 1, options), 2);
751
- }
752
- function decodeTag16(data, pos, _minor, options) {
753
- return new Token(Type.tag, readUint16(data, pos + 1, options), 3);
754
- }
755
- function decodeTag32(data, pos, _minor, options) {
756
- return new Token(Type.tag, readUint32(data, pos + 1, options), 5);
757
- }
758
- function decodeTag64(data, pos, _minor, options) {
759
- return new Token(Type.tag, readUint64(data, pos + 1, options), 9);
760
- }
761
- function encodeTag(writer, token) {
762
- encodeUintValue(writer, Type.tag.majorEncoded, token.value);
763
- }
764
- encodeTag.compareTokens = encodeUint.compareTokens;
765
- encodeTag.encodedSize = function encodedSize7(token) {
766
- return encodeUintValue.encodedSize(token.value);
767
- };
768
- const MINOR_FALSE = 20;
769
- const MINOR_TRUE = 21;
770
- const MINOR_NULL = 22;
771
- const MINOR_UNDEFINED = 23;
772
- function decodeUndefined(_data, _pos, _minor, options) {
773
- if (options.allowUndefined === false) {
774
- throw new Error(`${decodeErrPrefix} undefined values are not supported`);
775
- } else if (options.coerceUndefinedToNull === true) {
776
- return new Token(Type.null, null, 1);
777
- }
778
- return new Token(Type.undefined, void 0, 1);
779
- }
780
- function decodeBreak(_data, _pos, _minor, options) {
781
- if (options.allowIndefinite === false) {
782
- throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
783
- }
784
- return new Token(Type.break, void 0, 1);
785
- }
786
- function createToken(value, bytes, options) {
787
- if (options) {
788
- if (options.allowNaN === false && Number.isNaN(value)) {
789
- throw new Error(`${decodeErrPrefix} NaN values are not supported`);
790
- }
791
- if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
792
- throw new Error(`${decodeErrPrefix} Infinity values are not supported`);
793
- }
794
- }
795
- return new Token(Type.float, value, bytes);
796
- }
797
- function decodeFloat16(data, pos, _minor, options) {
798
- return createToken(readFloat16(data, pos + 1), 3, options);
799
- }
800
- function decodeFloat32(data, pos, _minor, options) {
801
- return createToken(readFloat32(data, pos + 1), 5, options);
802
- }
803
- function decodeFloat64(data, pos, _minor, options) {
804
- return createToken(readFloat64(data, pos + 1), 9, options);
805
- }
806
- function encodeFloat(writer, token, options) {
807
- const float = token.value;
808
- if (float === false) {
809
- writer.push([Type.float.majorEncoded | MINOR_FALSE]);
810
- } else if (float === true) {
811
- writer.push([Type.float.majorEncoded | MINOR_TRUE]);
812
- } else if (float === null) {
813
- writer.push([Type.float.majorEncoded | MINOR_NULL]);
814
- } else if (float === void 0) {
815
- writer.push([Type.float.majorEncoded | MINOR_UNDEFINED]);
816
- } else {
817
- let decoded;
818
- let success = false;
819
- if (!options || options.float64 !== true) {
820
- encodeFloat16(float);
821
- decoded = readFloat16(ui8a, 1);
822
- if (float === decoded || Number.isNaN(float)) {
823
- ui8a[0] = 249;
824
- writer.push(ui8a.slice(0, 3));
825
- success = true;
826
- } else {
827
- encodeFloat32(float);
828
- decoded = readFloat32(ui8a, 1);
829
- if (float === decoded) {
830
- ui8a[0] = 250;
831
- writer.push(ui8a.slice(0, 5));
832
- success = true;
833
- }
834
- }
835
- }
836
- if (!success) {
837
- encodeFloat64(float);
838
- decoded = readFloat64(ui8a, 1);
839
- ui8a[0] = 251;
840
- writer.push(ui8a.slice(0, 9));
841
- }
842
- }
843
- }
844
- encodeFloat.encodedSize = function encodedSize8(token, options) {
845
- const float = token.value;
846
- if (float === false || float === true || float === null || float === void 0) {
847
- return 1;
848
- }
849
- if (!options || options.float64 !== true) {
850
- encodeFloat16(float);
851
- let decoded = readFloat16(ui8a, 1);
852
- if (float === decoded || Number.isNaN(float)) {
853
- return 3;
854
- }
855
- encodeFloat32(float);
856
- decoded = readFloat32(ui8a, 1);
857
- if (float === decoded) {
858
- return 5;
859
- }
860
- }
861
- return 9;
862
- };
863
- const buffer = new ArrayBuffer(9);
864
- const dataView = new DataView(buffer, 1);
865
- const ui8a = new Uint8Array(buffer, 0);
866
- function encodeFloat16(inp) {
867
- if (inp === Infinity) {
868
- dataView.setUint16(0, 31744, false);
869
- } else if (inp === -Infinity) {
870
- dataView.setUint16(0, 64512, false);
871
- } else if (Number.isNaN(inp)) {
872
- dataView.setUint16(0, 32256, false);
873
- } else {
874
- dataView.setFloat32(0, inp);
875
- const valu32 = dataView.getUint32(0);
876
- const exponent = (valu32 & 2139095040) >> 23;
877
- const mantissa = valu32 & 8388607;
878
- if (exponent === 255) {
879
- dataView.setUint16(0, 31744, false);
880
- } else if (exponent === 0) {
881
- dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false);
882
- } else {
883
- const logicalExponent = exponent - 127;
884
- if (logicalExponent < -24) {
885
- dataView.setUint16(0, 0);
886
- } else if (logicalExponent < -14) {
887
- dataView.setUint16(0, (valu32 & 2147483648) >> 16 | /* sign bit */
888
- 1 << 24 + logicalExponent, false);
889
- } else {
890
- dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);
891
- }
892
- }
893
- }
894
- }
895
- function readFloat16(ui8a2, pos) {
896
- if (ui8a2.length - pos < 2) {
897
- throw new Error(`${decodeErrPrefix} not enough data for float16`);
898
- }
899
- const half = (ui8a2[pos] << 8) + ui8a2[pos + 1];
900
- if (half === 31744) {
901
- return Infinity;
902
- }
903
- if (half === 64512) {
904
- return -Infinity;
905
- }
906
- if (half === 32256) {
907
- return NaN;
908
- }
909
- const exp = half >> 10 & 31;
910
- const mant = half & 1023;
911
- let val;
912
- if (exp === 0) {
913
- val = mant * 2 ** -24;
914
- } else if (exp !== 31) {
915
- val = (mant + 1024) * 2 ** (exp - 25);
916
- } else {
917
- val = mant === 0 ? Infinity : NaN;
918
- }
919
- return half & 32768 ? -val : val;
920
- }
921
- function encodeFloat32(inp) {
922
- dataView.setFloat32(0, inp, false);
923
- }
924
- function readFloat32(ui8a2, pos) {
925
- if (ui8a2.length - pos < 4) {
926
- throw new Error(`${decodeErrPrefix} not enough data for float32`);
927
- }
928
- const offset = (ui8a2.byteOffset || 0) + pos;
929
- return new DataView(ui8a2.buffer, offset, 4).getFloat32(0, false);
930
- }
931
- function encodeFloat64(inp) {
932
- dataView.setFloat64(0, inp, false);
933
- }
934
- function readFloat64(ui8a2, pos) {
935
- if (ui8a2.length - pos < 8) {
936
- throw new Error(`${decodeErrPrefix} not enough data for float64`);
937
- }
938
- const offset = (ui8a2.byteOffset || 0) + pos;
939
- return new DataView(ui8a2.buffer, offset, 8).getFloat64(0, false);
940
- }
941
- encodeFloat.compareTokens = encodeUint.compareTokens;
942
- function invalidMinor(data, pos, minor) {
943
- throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`);
944
- }
945
- function errorer(msg) {
946
- return () => {
947
- throw new Error(`${decodeErrPrefix} ${msg}`);
948
- };
949
- }
950
- const jump = [];
951
- for (let i = 0; i <= 23; i++) {
952
- jump[i] = invalidMinor;
953
- }
954
- jump[24] = decodeUint8;
955
- jump[25] = decodeUint16;
956
- jump[26] = decodeUint32;
957
- jump[27] = decodeUint64;
958
- jump[28] = invalidMinor;
959
- jump[29] = invalidMinor;
960
- jump[30] = invalidMinor;
961
- jump[31] = invalidMinor;
962
- for (let i = 32; i <= 55; i++) {
963
- jump[i] = invalidMinor;
964
- }
965
- jump[56] = decodeNegint8;
966
- jump[57] = decodeNegint16;
967
- jump[58] = decodeNegint32;
968
- jump[59] = decodeNegint64;
969
- jump[60] = invalidMinor;
970
- jump[61] = invalidMinor;
971
- jump[62] = invalidMinor;
972
- jump[63] = invalidMinor;
973
- for (let i = 64; i <= 87; i++) {
974
- jump[i] = decodeBytesCompact;
975
- }
976
- jump[88] = decodeBytes8;
977
- jump[89] = decodeBytes16;
978
- jump[90] = decodeBytes32;
979
- jump[91] = decodeBytes64;
980
- jump[92] = invalidMinor;
981
- jump[93] = invalidMinor;
982
- jump[94] = invalidMinor;
983
- jump[95] = errorer("indefinite length bytes/strings are not supported");
984
- for (let i = 96; i <= 119; i++) {
985
- jump[i] = decodeStringCompact;
986
- }
987
- jump[120] = decodeString8;
988
- jump[121] = decodeString16;
989
- jump[122] = decodeString32;
990
- jump[123] = decodeString64;
991
- jump[124] = invalidMinor;
992
- jump[125] = invalidMinor;
993
- jump[126] = invalidMinor;
994
- jump[127] = errorer("indefinite length bytes/strings are not supported");
995
- for (let i = 128; i <= 151; i++) {
996
- jump[i] = decodeArrayCompact;
997
- }
998
- jump[152] = decodeArray8;
999
- jump[153] = decodeArray16;
1000
- jump[154] = decodeArray32;
1001
- jump[155] = decodeArray64;
1002
- jump[156] = invalidMinor;
1003
- jump[157] = invalidMinor;
1004
- jump[158] = invalidMinor;
1005
- jump[159] = decodeArrayIndefinite;
1006
- for (let i = 160; i <= 183; i++) {
1007
- jump[i] = decodeMapCompact;
1008
- }
1009
- jump[184] = decodeMap8;
1010
- jump[185] = decodeMap16;
1011
- jump[186] = decodeMap32;
1012
- jump[187] = decodeMap64;
1013
- jump[188] = invalidMinor;
1014
- jump[189] = invalidMinor;
1015
- jump[190] = invalidMinor;
1016
- jump[191] = decodeMapIndefinite;
1017
- for (let i = 192; i <= 215; i++) {
1018
- jump[i] = decodeTagCompact;
1019
- }
1020
- jump[216] = decodeTag8;
1021
- jump[217] = decodeTag16;
1022
- jump[218] = decodeTag32;
1023
- jump[219] = decodeTag64;
1024
- jump[220] = invalidMinor;
1025
- jump[221] = invalidMinor;
1026
- jump[222] = invalidMinor;
1027
- jump[223] = invalidMinor;
1028
- for (let i = 224; i <= 243; i++) {
1029
- jump[i] = errorer("simple values are not supported");
1030
- }
1031
- jump[244] = invalidMinor;
1032
- jump[245] = invalidMinor;
1033
- jump[246] = invalidMinor;
1034
- jump[247] = decodeUndefined;
1035
- jump[248] = errorer("simple values are not supported");
1036
- jump[249] = decodeFloat16;
1037
- jump[250] = decodeFloat32;
1038
- jump[251] = decodeFloat64;
1039
- jump[252] = invalidMinor;
1040
- jump[253] = invalidMinor;
1041
- jump[254] = invalidMinor;
1042
- jump[255] = decodeBreak;
1043
- const quick = [];
1044
- for (let i = 0; i < 24; i++) {
1045
- quick[i] = new Token(Type.uint, i, 1);
1046
- }
1047
- for (let i = -1; i >= -24; i--) {
1048
- quick[31 - i] = new Token(Type.negint, i, 1);
1049
- }
1050
- quick[64] = new Token(Type.bytes, new Uint8Array(0), 1);
1051
- quick[96] = new Token(Type.string, "", 1);
1052
- quick[128] = new Token(Type.array, 0, 1);
1053
- quick[160] = new Token(Type.map, 0, 1);
1054
- quick[244] = new Token(Type.false, false, 1);
1055
- quick[245] = new Token(Type.true, true, 1);
1056
- quick[246] = new Token(Type.null, null, 1);
1057
- function quickEncodeToken(token) {
1058
- switch (token.type) {
1059
- case Type.false:
1060
- return fromArray([244]);
1061
- case Type.true:
1062
- return fromArray([245]);
1063
- case Type.null:
1064
- return fromArray([246]);
1065
- case Type.bytes:
1066
- if (!token.value.length) {
1067
- return fromArray([64]);
1068
- }
1069
- return;
1070
- case Type.string:
1071
- if (token.value === "") {
1072
- return fromArray([96]);
1073
- }
1074
- return;
1075
- case Type.array:
1076
- if (token.value === 0) {
1077
- return fromArray([128]);
1078
- }
1079
- return;
1080
- case Type.map:
1081
- if (token.value === 0) {
1082
- return fromArray([160]);
1083
- }
1084
- return;
1085
- case Type.uint:
1086
- if (token.value < 24) {
1087
- return fromArray([Number(token.value)]);
1088
- }
1089
- return;
1090
- case Type.negint:
1091
- if (token.value >= -24) {
1092
- return fromArray([31 - Number(token.value)]);
1093
- }
1094
- }
1095
- }
1096
- const defaultEncodeOptions = {
1097
- float64: false,
1098
- mapSorter,
1099
- quickEncodeToken
1100
- };
1101
- function makeCborEncoders() {
1102
- const encoders = [];
1103
- encoders[Type.uint.major] = encodeUint;
1104
- encoders[Type.negint.major] = encodeNegint;
1105
- encoders[Type.bytes.major] = encodeBytes;
1106
- encoders[Type.string.major] = encodeString;
1107
- encoders[Type.array.major] = encodeArray;
1108
- encoders[Type.map.major] = encodeMap;
1109
- encoders[Type.tag.major] = encodeTag;
1110
- encoders[Type.float.major] = encodeFloat;
1111
- return encoders;
1112
- }
1113
- const cborEncoders = makeCborEncoders();
1114
- const defaultWriter = new Bl();
1115
- class Ref {
1116
- /**
1117
- * @param {object|any[]} obj
1118
- * @param {Reference|undefined} parent
1119
- */
1120
- constructor(obj, parent) {
1121
- this.obj = obj;
1122
- this.parent = parent;
1123
- }
1124
- /**
1125
- * @param {object|any[]} obj
1126
- * @returns {boolean}
1127
- */
1128
- includes(obj) {
1129
- let p = this;
1130
- do {
1131
- if (p.obj === obj) {
1132
- return true;
1133
- }
1134
- } while (p = p.parent);
1135
- return false;
1136
- }
1137
- /**
1138
- * @param {Reference|undefined} stack
1139
- * @param {object|any[]} obj
1140
- * @returns {Reference}
1141
- */
1142
- static createCheck(stack, obj) {
1143
- if (stack && stack.includes(obj)) {
1144
- throw new Error(`${encodeErrPrefix} object contains circular references`);
1145
- }
1146
- return new Ref(obj, stack);
1147
- }
1148
- }
1149
- const simpleTokens = {
1150
- null: new Token(Type.null, null),
1151
- undefined: new Token(Type.undefined, void 0),
1152
- true: new Token(Type.true, true),
1153
- false: new Token(Type.false, false),
1154
- emptyArray: new Token(Type.array, 0),
1155
- emptyMap: new Token(Type.map, 0)
1156
- };
1157
- const typeEncoders = {
1158
- /**
1159
- * @param {any} obj
1160
- * @param {string} _typ
1161
- * @param {EncodeOptions} _options
1162
- * @param {Reference} [_refStack]
1163
- * @returns {TokenOrNestedTokens}
1164
- */
1165
- number(obj, _typ, _options, _refStack) {
1166
- if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
1167
- return new Token(Type.float, obj);
1168
- } else if (obj >= 0) {
1169
- return new Token(Type.uint, obj);
1170
- } else {
1171
- return new Token(Type.negint, obj);
1172
- }
1173
- },
1174
- /**
1175
- * @param {any} obj
1176
- * @param {string} _typ
1177
- * @param {EncodeOptions} _options
1178
- * @param {Reference} [_refStack]
1179
- * @returns {TokenOrNestedTokens}
1180
- */
1181
- bigint(obj, _typ, _options, _refStack) {
1182
- if (obj >= BigInt(0)) {
1183
- return new Token(Type.uint, obj);
1184
- } else {
1185
- return new Token(Type.negint, obj);
1186
- }
1187
- },
1188
- /**
1189
- * @param {any} obj
1190
- * @param {string} _typ
1191
- * @param {EncodeOptions} _options
1192
- * @param {Reference} [_refStack]
1193
- * @returns {TokenOrNestedTokens}
1194
- */
1195
- Uint8Array(obj, _typ, _options, _refStack) {
1196
- return new Token(Type.bytes, obj);
1197
- },
1198
- /**
1199
- * @param {any} obj
1200
- * @param {string} _typ
1201
- * @param {EncodeOptions} _options
1202
- * @param {Reference} [_refStack]
1203
- * @returns {TokenOrNestedTokens}
1204
- */
1205
- string(obj, _typ, _options, _refStack) {
1206
- return new Token(Type.string, obj);
1207
- },
1208
- /**
1209
- * @param {any} obj
1210
- * @param {string} _typ
1211
- * @param {EncodeOptions} _options
1212
- * @param {Reference} [_refStack]
1213
- * @returns {TokenOrNestedTokens}
1214
- */
1215
- boolean(obj, _typ, _options, _refStack) {
1216
- return obj ? simpleTokens.true : simpleTokens.false;
1217
- },
1218
- /**
1219
- * @param {any} _obj
1220
- * @param {string} _typ
1221
- * @param {EncodeOptions} _options
1222
- * @param {Reference} [_refStack]
1223
- * @returns {TokenOrNestedTokens}
1224
- */
1225
- null(_obj, _typ, _options, _refStack) {
1226
- return simpleTokens.null;
1227
- },
1228
- /**
1229
- * @param {any} _obj
1230
- * @param {string} _typ
1231
- * @param {EncodeOptions} _options
1232
- * @param {Reference} [_refStack]
1233
- * @returns {TokenOrNestedTokens}
1234
- */
1235
- undefined(_obj, _typ, _options, _refStack) {
1236
- return simpleTokens.undefined;
1237
- },
1238
- /**
1239
- * @param {any} obj
1240
- * @param {string} _typ
1241
- * @param {EncodeOptions} _options
1242
- * @param {Reference} [_refStack]
1243
- * @returns {TokenOrNestedTokens}
1244
- */
1245
- ArrayBuffer(obj, _typ, _options, _refStack) {
1246
- return new Token(Type.bytes, new Uint8Array(obj));
1247
- },
1248
- /**
1249
- * @param {any} obj
1250
- * @param {string} _typ
1251
- * @param {EncodeOptions} _options
1252
- * @param {Reference} [_refStack]
1253
- * @returns {TokenOrNestedTokens}
1254
- */
1255
- DataView(obj, _typ, _options, _refStack) {
1256
- return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));
1257
- },
1258
- /**
1259
- * @param {any} obj
1260
- * @param {string} _typ
1261
- * @param {EncodeOptions} options
1262
- * @param {Reference} [refStack]
1263
- * @returns {TokenOrNestedTokens}
1264
- */
1265
- Array(obj, _typ, options, refStack) {
1266
- if (!obj.length) {
1267
- if (options.addBreakTokens === true) {
1268
- return [simpleTokens.emptyArray, new Token(Type.break)];
1269
- }
1270
- return simpleTokens.emptyArray;
1271
- }
1272
- refStack = Ref.createCheck(refStack, obj);
1273
- const entries = [];
1274
- let i = 0;
1275
- for (const e of obj) {
1276
- entries[i++] = objectToTokens(e, options, refStack);
1277
- }
1278
- if (options.addBreakTokens) {
1279
- return [new Token(Type.array, obj.length), entries, new Token(Type.break)];
1280
- }
1281
- return [new Token(Type.array, obj.length), entries];
1282
- },
1283
- /**
1284
- * @param {any} obj
1285
- * @param {string} typ
1286
- * @param {EncodeOptions} options
1287
- * @param {Reference} [refStack]
1288
- * @returns {TokenOrNestedTokens}
1289
- */
1290
- Object(obj, typ, options, refStack) {
1291
- const isMap = typ !== "Object";
1292
- const keys = isMap ? obj.keys() : Object.keys(obj);
1293
- const maxLength = isMap ? obj.size : keys.length;
1294
- let entries;
1295
- if (maxLength) {
1296
- entries = new Array(maxLength);
1297
- refStack = Ref.createCheck(refStack, obj);
1298
- const skipUndefined = !isMap && options.ignoreUndefinedProperties;
1299
- let i = 0;
1300
- for (const key of keys) {
1301
- const value = isMap ? obj.get(key) : obj[key];
1302
- if (skipUndefined && value === void 0) {
1303
- continue;
1304
- }
1305
- entries[i++] = [
1306
- objectToTokens(key, options, refStack),
1307
- objectToTokens(value, options, refStack)
1308
- ];
1309
- }
1310
- if (i < maxLength) {
1311
- entries.length = i;
1312
- }
1313
- }
1314
- if (!(entries == null ? void 0 : entries.length)) {
1315
- if (options.addBreakTokens === true) {
1316
- return [simpleTokens.emptyMap, new Token(Type.break)];
1317
- }
1318
- return simpleTokens.emptyMap;
1319
- }
1320
- sortMapEntries(entries, options);
1321
- if (options.addBreakTokens) {
1322
- return [new Token(Type.map, entries.length), entries, new Token(Type.break)];
1323
- }
1324
- return [new Token(Type.map, entries.length), entries];
1325
- }
1326
- };
1327
- typeEncoders.Map = typeEncoders.Object;
1328
- typeEncoders.Buffer = typeEncoders.Uint8Array;
1329
- for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")) {
1330
- typeEncoders[`${typ}Array`] = typeEncoders.DataView;
1331
- }
1332
- function objectToTokens(obj, options = {}, refStack) {
1333
- const typ = is(obj);
1334
- const customTypeEncoder = options && options.typeEncoders && /** @type {OptionalTypeEncoder} */
1335
- options.typeEncoders[typ] || typeEncoders[typ];
1336
- if (typeof customTypeEncoder === "function") {
1337
- const tokens = customTypeEncoder(obj, typ, options, refStack);
1338
- if (tokens != null) {
1339
- return tokens;
1340
- }
1341
- }
1342
- const typeEncoder = typeEncoders[typ];
1343
- if (!typeEncoder) {
1344
- throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
1345
- }
1346
- return typeEncoder(obj, typ, options, refStack);
1347
- }
1348
- function sortMapEntries(entries, options) {
1349
- if (options.mapSorter) {
1350
- entries.sort(options.mapSorter);
1351
- }
1352
- }
1353
- function mapSorter(e1, e2) {
1354
- const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];
1355
- const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];
1356
- if (keyToken1.type !== keyToken2.type) {
1357
- return keyToken1.type.compare(keyToken2.type);
1358
- }
1359
- const major = keyToken1.type.major;
1360
- const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2);
1361
- if (tcmp === 0) {
1362
- console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone");
1363
- }
1364
- return tcmp;
1365
- }
1366
- function tokensToEncoded(writer, tokens, encoders, options) {
1367
- if (Array.isArray(tokens)) {
1368
- for (const token of tokens) {
1369
- tokensToEncoded(writer, token, encoders, options);
1370
- }
1371
- } else {
1372
- encoders[tokens.type.major](writer, tokens, options);
1373
- }
1374
- }
1375
- const MAJOR_UINT = Type.uint.majorEncoded;
1376
- const MAJOR_NEGINT = Type.negint.majorEncoded;
1377
- const MAJOR_BYTES = Type.bytes.majorEncoded;
1378
- const MAJOR_STRING = Type.string.majorEncoded;
1379
- const MAJOR_ARRAY = Type.array.majorEncoded;
1380
- const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE;
1381
- const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE;
1382
- const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL;
1383
- const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED;
1384
- const neg1b = BigInt(-1);
1385
- const pos1b = BigInt(1);
1386
- function canDirectEncode(options) {
1387
- return options.addBreakTokens !== true;
1388
- }
1389
- function directEncode(writer, data, options, refStack) {
1390
- const typ = is(data);
1391
- const customEncoder = options.typeEncoders && options.typeEncoders[typ];
1392
- if (customEncoder) {
1393
- const tokens = customEncoder(data, typ, options, refStack);
1394
- if (tokens != null) {
1395
- tokensToEncoded(writer, tokens, cborEncoders, options);
1396
- return;
1397
- }
1398
- }
1399
- switch (typ) {
1400
- case "null":
1401
- writer.push([SIMPLE_NULL]);
1402
- return;
1403
- case "undefined":
1404
- writer.push([SIMPLE_UNDEFINED]);
1405
- return;
1406
- case "boolean":
1407
- writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE]);
1408
- return;
1409
- case "number":
1410
- if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
1411
- encodeFloat(writer, new Token(Type.float, data), options);
1412
- } else if (data >= 0) {
1413
- encodeUintValue(writer, MAJOR_UINT, data);
1414
- } else {
1415
- encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1);
1416
- }
1417
- return;
1418
- case "bigint":
1419
- if (data >= BigInt(0)) {
1420
- encodeUintValue(writer, MAJOR_UINT, data);
1421
- } else {
1422
- encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b);
1423
- }
1424
- return;
1425
- case "string": {
1426
- const bytes = fromString(data);
1427
- encodeUintValue(writer, MAJOR_STRING, bytes.length);
1428
- writer.push(bytes);
1429
- return;
1430
- }
1431
- case "Uint8Array":
1432
- encodeUintValue(writer, MAJOR_BYTES, data.length);
1433
- writer.push(data);
1434
- return;
1435
- case "Array":
1436
- if (!data.length) {
1437
- writer.push([MAJOR_ARRAY]);
1438
- return;
1439
- }
1440
- refStack = Ref.createCheck(refStack, data);
1441
- encodeUintValue(writer, MAJOR_ARRAY, data.length);
1442
- for (const elem of data) {
1443
- directEncode(writer, elem, options, refStack);
1444
- }
1445
- return;
1446
- case "Object":
1447
- case "Map":
1448
- {
1449
- const tokens = typeEncoders.Object(data, typ, options, refStack);
1450
- tokensToEncoded(writer, tokens, cborEncoders, options);
1451
- }
1452
- return;
1453
- default: {
1454
- const typeEncoder = typeEncoders[typ];
1455
- if (!typeEncoder) {
1456
- throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
1457
- }
1458
- const tokens = typeEncoder(data, typ, options, refStack);
1459
- tokensToEncoded(writer, tokens, cborEncoders, options);
1460
- }
1461
- }
1462
- }
1463
- function encodeCustom(data, encoders, options, destination) {
1464
- const hasDest = destination instanceof Uint8Array;
1465
- let writeTo = hasDest ? new U8Bl(destination) : defaultWriter;
1466
- const tokens = objectToTokens(data, options);
1467
- if (!Array.isArray(tokens) && options.quickEncodeToken) {
1468
- const quickBytes = options.quickEncodeToken(tokens);
1469
- if (quickBytes) {
1470
- if (hasDest) {
1471
- writeTo.push(quickBytes);
1472
- return writeTo.toBytes();
1473
- }
1474
- return quickBytes;
1475
- }
1476
- const encoder = encoders[tokens.type.major];
1477
- if (encoder.encodedSize) {
1478
- const size = encoder.encodedSize(tokens, options);
1479
- if (!hasDest) {
1480
- writeTo = new Bl(size);
1481
- }
1482
- encoder(writeTo, tokens, options);
1483
- if (writeTo.chunks.length !== 1) {
1484
- throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`);
1485
- }
1486
- return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0]);
1487
- }
1488
- }
1489
- writeTo.reset();
1490
- tokensToEncoded(writeTo, tokens, encoders, options);
1491
- return writeTo.toBytes(true);
1492
- }
1493
- function encode$1(data, options) {
1494
- options = Object.assign({}, defaultEncodeOptions, options);
1495
- if (canDirectEncode(options)) {
1496
- defaultWriter.reset();
1497
- directEncode(defaultWriter, data, options, void 0);
1498
- return defaultWriter.toBytes(true);
1499
- }
1500
- return encodeCustom(data, cborEncoders, options);
1501
- }
1502
- const defaultDecodeOptions = {
1503
- strict: false,
1504
- allowIndefinite: true,
1505
- allowUndefined: true,
1506
- allowBigInt: true
1507
- };
1508
- class Tokeniser {
1509
- /**
1510
- * @param {Uint8Array} data
1511
- * @param {DecodeOptions} options
1512
- */
1513
- constructor(data, options = {}) {
1514
- this._pos = 0;
1515
- this.data = data;
1516
- this.options = options;
1517
- }
1518
- pos() {
1519
- return this._pos;
1520
- }
1521
- done() {
1522
- return this._pos >= this.data.length;
1523
- }
1524
- next() {
1525
- const byt = this.data[this._pos];
1526
- let token = quick[byt];
1527
- if (token === void 0) {
1528
- const decoder = jump[byt];
1529
- if (!decoder) {
1530
- throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, "0")})`);
1531
- }
1532
- const minor = byt & 31;
1533
- token = decoder(this.data, this._pos, minor, this.options);
1534
- }
1535
- this._pos += token.encodedLength;
1536
- return token;
1537
- }
1538
- }
1539
- const DONE = Symbol.for("DONE");
1540
- const BREAK = Symbol.for("BREAK");
1541
- function tokenToArray(token, tokeniser, options) {
1542
- const arr = [];
1543
- for (let i = 0; i < token.value; i++) {
1544
- const value = tokensToObject(tokeniser, options);
1545
- if (value === BREAK) {
1546
- if (token.value === Infinity) {
1547
- break;
1548
- }
1549
- throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`);
1550
- }
1551
- if (value === DONE) {
1552
- throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`);
1553
- }
1554
- arr[i] = value;
1555
- }
1556
- return arr;
1557
- }
1558
- function tokenToMap(token, tokeniser, options) {
1559
- const useMaps = options.useMaps === true;
1560
- const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true;
1561
- const obj = useMaps ? void 0 : {};
1562
- const m = useMaps ? /* @__PURE__ */ new Map() : void 0;
1563
- for (let i = 0; i < token.value; i++) {
1564
- const key = tokensToObject(tokeniser, options);
1565
- if (key === BREAK) {
1566
- if (token.value === Infinity) {
1567
- break;
1568
- }
1569
- throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`);
1570
- }
1571
- if (key === DONE) {
1572
- throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`);
1573
- }
1574
- if (!useMaps && typeof key !== "string") {
1575
- throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`);
1576
- }
1577
- if (rejectDuplicateMapKeys) {
1578
- if (useMaps && m.has(key) || !useMaps && Object.hasOwn(obj, key)) {
1579
- throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`);
1580
- }
1581
- }
1582
- const value = tokensToObject(tokeniser, options);
1583
- if (value === DONE) {
1584
- throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`);
1585
- }
1586
- if (useMaps) {
1587
- m.set(key, value);
1588
- } else {
1589
- obj[key] = value;
1590
- }
1591
- }
1592
- return useMaps ? m : obj;
1593
- }
1594
- function tokensToObject(tokeniser, options) {
1595
- if (tokeniser.done()) {
1596
- return DONE;
1597
- }
1598
- const token = tokeniser.next();
1599
- if (Type.equals(token.type, Type.break)) {
1600
- return BREAK;
1601
- }
1602
- if (token.type.terminal) {
1603
- return token.value;
1604
- }
1605
- if (Type.equals(token.type, Type.array)) {
1606
- return tokenToArray(token, tokeniser, options);
1607
- }
1608
- if (Type.equals(token.type, Type.map)) {
1609
- return tokenToMap(token, tokeniser, options);
1610
- }
1611
- if (Type.equals(token.type, Type.tag)) {
1612
- if (options.tags && typeof options.tags[token.value] === "function") {
1613
- const tagged = tokensToObject(tokeniser, options);
1614
- return options.tags[token.value](tagged);
1615
- }
1616
- throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`);
1617
- }
1618
- throw new Error("unsupported");
1619
- }
1620
- function decodeFirst(data, options) {
1621
- if (!(data instanceof Uint8Array)) {
1622
- throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`);
1623
- }
1624
- options = Object.assign({}, defaultDecodeOptions, options);
1625
- const u8aData = asU8A(data);
1626
- const tokeniser = options.tokenizer || new Tokeniser(u8aData, options);
1627
- const decoded = tokensToObject(tokeniser, options);
1628
- if (decoded === DONE) {
1629
- throw new Error(`${decodeErrPrefix} did not find any content to decode`);
1630
- }
1631
- if (decoded === BREAK) {
1632
- throw new Error(`${decodeErrPrefix} got unexpected break`);
1633
- }
1634
- return [decoded, data.subarray(tokeniser.pos())];
1635
- }
1636
- function decode$1(data, options) {
1637
- const [decoded, remainder] = decodeFirst(data, options);
1638
- if (remainder.length > 0) {
1639
- throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`);
1640
- }
1641
- return decoded;
1642
- }
1643
- const CID_CBOR_TAG = 42;
1644
- const encodeOptions = Object.freeze({
1645
- float64: true,
1646
- ignoreUndefinedProperties: true,
1647
- typeEncoders: Object.freeze({
1648
- Map: (map) => {
1649
- for (const key of map.keys()) {
1650
- if (typeof key !== "string") {
1651
- throw new Error(
1652
- 'Only string keys are allowed in CBOR "map" by the AT Data Model'
1653
- );
1654
- }
1655
- }
1656
- return null;
1657
- },
1658
- Object: (obj) => {
1659
- const cid = lexData.ifCid(obj);
1660
- if (cid) {
1661
- const bytes = new Uint8Array(cid.bytes.byteLength + 1);
1662
- bytes.set(cid.bytes, 1);
1663
- return [new Token(Type.tag, CID_CBOR_TAG), new Token(Type.bytes, bytes)];
1664
- }
1665
- return null;
1666
- },
1667
- undefined: () => {
1668
- throw new Error("`undefined` is not supported by the AT Data Model");
1669
- },
1670
- number: (num) => {
1671
- if (Number.isSafeInteger(num)) return null;
1672
- throw new Error(
1673
- `Non-integer numbers (${num}) are not supported by the AT Data Model`
1674
- );
1675
- }
1676
- })
1677
- });
1678
- const decodeOptions = /* @__PURE__ */ Object.freeze({
1679
- allowIndefinite: false,
1680
- coerceUndefinedToNull: true,
1681
- allowNaN: false,
1682
- allowInfinity: false,
1683
- allowBigInt: true,
1684
- strict: true,
1685
- useMaps: false,
1686
- rejectDuplicateMapKeys: true,
1687
- tags: /* @__PURE__ */ Object.freeze(
1688
- /* @__PURE__ */ Object.assign([], {
1689
- [CID_CBOR_TAG]: (bytes) => {
1690
- if (bytes[0] !== 0) {
1691
- throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");
1692
- }
1693
- const cibBytes = bytes.subarray(1);
1694
- return lexData.decodeCid(cibBytes);
1695
- }
1696
- })
1697
- )
1698
- });
1699
- function encode(data) {
1700
- return encode$1(data, encodeOptions);
1701
- }
1702
- function decode(bytes) {
1703
- return decode$1(bytes, decodeOptions);
1704
- }
1705
- function* decodeAll(data) {
1706
- do {
1707
- const [result, remainingBytes] = decodeFirst(data, decodeOptions);
1708
- yield result;
1709
- data = remainingBytes;
1710
- } while (data.byteLength > 0);
1711
- }
1712
- async function cidForLex(value) {
1713
- return lexData.cidForCbor(encode(value));
1714
- }
1715
- exports.cborDecode = decode;
1716
- exports.cborDecodeAll = decodeAll;
1717
- exports.cborEncode = encode;
1718
- exports.cidForLex = cidForLex;
1719
- exports.decode = decode;
1720
- exports.decodeAll = decodeAll;
1721
- exports.decodeOptions = decodeOptions;
1722
- exports.encode = encode;
1723
- exports.encodeOptions = encodeOptions;