@wovin/core 0.0.17 → 0.0.19

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.
Files changed (38) hide show
  1. package/dist/applog.min.js +1 -1
  2. package/dist/{chunk-TEQ4SIKN.min.js → chunk-E4BAQ5JJ.min.js} +2 -2
  3. package/dist/chunk-IHGAJTEQ.min.js +70 -0
  4. package/dist/chunk-IHGAJTEQ.min.js.map +1 -0
  5. package/dist/{chunk-OBMVNVJR.min.js → chunk-KVPEUWWR.min.js} +2 -2
  6. package/dist/chunk-SIIQEX77.min.js +4122 -0
  7. package/dist/chunk-SIIQEX77.min.js.map +1 -0
  8. package/dist/{chunk-NPCVLBCM.min.js → chunk-UZBCM3UI.min.js} +5 -75
  9. package/dist/{chunk-NPCVLBCM.min.js.map → chunk-UZBCM3UI.min.js.map} +1 -1
  10. package/dist/{chunk-FIOA3FZW.min.js → chunk-VDYG5VHX.min.js} +4 -4
  11. package/dist/{chunk-FIOA3FZW.min.js.map → chunk-VDYG5VHX.min.js.map} +1 -1
  12. package/dist/index.min.js +19 -16
  13. package/dist/ipfs/car.d.ts +2 -1
  14. package/dist/ipfs/car.d.ts.map +1 -1
  15. package/dist/ipfs/fetch-snapshot-chain.d.ts +27 -0
  16. package/dist/ipfs/fetch-snapshot-chain.d.ts.map +1 -0
  17. package/dist/ipfs.d.ts +1 -0
  18. package/dist/ipfs.d.ts.map +1 -1
  19. package/dist/ipfs.min.js +7 -4
  20. package/dist/pubsub/pubsub-types.d.ts +7 -7
  21. package/dist/pubsub/pubsub-types.d.ts.map +1 -1
  22. package/dist/pubsub/{pub-push.d.ts → snap-push.d.ts} +7 -7
  23. package/dist/pubsub/snap-push.d.ts.map +1 -0
  24. package/dist/pubsub.d.ts +1 -1
  25. package/dist/pubsub.d.ts.map +1 -1
  26. package/dist/pubsub.min.js +14 -14
  27. package/dist/query/situations.d.ts +77 -0
  28. package/dist/query/situations.d.ts.map +1 -1
  29. package/dist/query.min.js +3 -3
  30. package/dist/thread.min.js +1 -1
  31. package/package.json +1 -1
  32. package/dist/chunk-JEOQUHTK.min.js +0 -1515
  33. package/dist/chunk-JEOQUHTK.min.js.map +0 -1
  34. package/dist/chunk-RPPZKO5L.min.js +0 -1
  35. package/dist/chunk-RPPZKO5L.min.js.map +0 -1
  36. package/dist/pubsub/pub-push.d.ts.map +0 -1
  37. /package/dist/{chunk-TEQ4SIKN.min.js.map → chunk-E4BAQ5JJ.min.js.map} +0 -0
  38. /package/dist/{chunk-OBMVNVJR.min.js.map → chunk-KVPEUWWR.min.js.map} +0 -0
@@ -0,0 +1,4122 @@
1
+ import {
2
+ keepTruthy
3
+ } from "./chunk-QPGEBDMJ.min.js";
4
+ import {
5
+ lastWriteWins
6
+ } from "./chunk-KVPEUWWR.min.js";
7
+ import {
8
+ CID,
9
+ areCidsEqual,
10
+ decode,
11
+ encodeBlockOriginal,
12
+ ensureTsPvAndFinalizeApplog,
13
+ g,
14
+ getLogsFromThread,
15
+ prepareForPub,
16
+ rollingFilter,
17
+ src_exports,
18
+ wrapper_default
19
+ } from "./chunk-UZBCM3UI.min.js";
20
+ import {
21
+ __commonJS,
22
+ __toESM
23
+ } from "./chunk-PHITDXZT.min.js";
24
+
25
+ // ../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/encode.js
26
+ var require_encode = __commonJS({
27
+ "../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/encode.js"(exports, module) {
28
+ "use strict";
29
+ module.exports = encode5;
30
+ var MSB2 = 128;
31
+ var REST2 = 127;
32
+ var MSBALL2 = ~REST2;
33
+ var INT2 = Math.pow(2, 31);
34
+ function encode5(num, out, offset) {
35
+ if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {
36
+ encode5.bytes = 0;
37
+ throw new RangeError("Could not encode varint");
38
+ }
39
+ out = out || [];
40
+ offset = offset || 0;
41
+ var oldOffset = offset;
42
+ while (num >= INT2) {
43
+ out[offset++] = num & 255 | MSB2;
44
+ num /= 128;
45
+ }
46
+ while (num & MSBALL2) {
47
+ out[offset++] = num & 255 | MSB2;
48
+ num >>>= 7;
49
+ }
50
+ out[offset] = num | 0;
51
+ encode5.bytes = offset - oldOffset + 1;
52
+ return out;
53
+ }
54
+ }
55
+ });
56
+
57
+ // ../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/decode.js
58
+ var require_decode = __commonJS({
59
+ "../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/decode.js"(exports, module) {
60
+ "use strict";
61
+ module.exports = read2;
62
+ var MSB2 = 128;
63
+ var REST2 = 127;
64
+ function read2(buf, offset) {
65
+ var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
66
+ do {
67
+ if (counter >= l || shift > 49) {
68
+ read2.bytes = 0;
69
+ throw new RangeError("Could not decode varint");
70
+ }
71
+ b = buf[counter++];
72
+ res += shift < 28 ? (b & REST2) << shift : (b & REST2) * Math.pow(2, shift);
73
+ shift += 7;
74
+ } while (b >= MSB2);
75
+ read2.bytes = counter - offset;
76
+ return res;
77
+ }
78
+ }
79
+ });
80
+
81
+ // ../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/length.js
82
+ var require_length = __commonJS({
83
+ "../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/length.js"(exports, module) {
84
+ "use strict";
85
+ var N12 = Math.pow(2, 7);
86
+ var N22 = Math.pow(2, 14);
87
+ var N32 = Math.pow(2, 21);
88
+ var N42 = Math.pow(2, 28);
89
+ var N52 = Math.pow(2, 35);
90
+ var N62 = Math.pow(2, 42);
91
+ var N72 = Math.pow(2, 49);
92
+ var N82 = Math.pow(2, 56);
93
+ var N92 = Math.pow(2, 63);
94
+ module.exports = function(value) {
95
+ return value < N12 ? 1 : value < N22 ? 2 : value < N32 ? 3 : value < N42 ? 4 : value < N52 ? 5 : value < N62 ? 6 : value < N72 ? 7 : value < N82 ? 8 : value < N92 ? 9 : 10;
96
+ };
97
+ }
98
+ });
99
+
100
+ // ../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/index.js
101
+ var require_varint = __commonJS({
102
+ "../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/index.js"(exports, module) {
103
+ "use strict";
104
+ module.exports = {
105
+ encode: require_encode(),
106
+ decode: require_decode(),
107
+ encodingLength: require_length()
108
+ };
109
+ }
110
+ });
111
+
112
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/is.js
113
+ var objectTypeNames = [
114
+ "Object",
115
+ // for Object.create(null) and other non-plain objects
116
+ "RegExp",
117
+ "Date",
118
+ "Error",
119
+ "Map",
120
+ "Set",
121
+ "WeakMap",
122
+ "WeakSet",
123
+ "ArrayBuffer",
124
+ "SharedArrayBuffer",
125
+ "DataView",
126
+ "Promise",
127
+ "URL",
128
+ "HTMLElement",
129
+ "Int8Array",
130
+ "Uint8ClampedArray",
131
+ "Int16Array",
132
+ "Uint16Array",
133
+ "Int32Array",
134
+ "Uint32Array",
135
+ "Float32Array",
136
+ "Float64Array",
137
+ "BigInt64Array",
138
+ "BigUint64Array"
139
+ ];
140
+ function is(value) {
141
+ if (value === null) {
142
+ return "null";
143
+ }
144
+ if (value === void 0) {
145
+ return "undefined";
146
+ }
147
+ if (value === true || value === false) {
148
+ return "boolean";
149
+ }
150
+ const typeOf = typeof value;
151
+ if (typeOf === "string" || typeOf === "number" || typeOf === "bigint" || typeOf === "symbol") {
152
+ return typeOf;
153
+ }
154
+ if (typeOf === "function") {
155
+ return "Function";
156
+ }
157
+ if (Array.isArray(value)) {
158
+ return "Array";
159
+ }
160
+ if (value instanceof Uint8Array) {
161
+ return "Uint8Array";
162
+ }
163
+ if (value.constructor === Object) {
164
+ return "Object";
165
+ }
166
+ const objectType = getObjectType(value);
167
+ if (objectType) {
168
+ return objectType;
169
+ }
170
+ return "Object";
171
+ }
172
+ function getObjectType(value) {
173
+ const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);
174
+ if (objectTypeNames.includes(objectTypeName)) {
175
+ return objectTypeName;
176
+ }
177
+ return void 0;
178
+ }
179
+
180
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/token.js
181
+ var Type = class {
182
+ /**
183
+ * @param {number} major
184
+ * @param {string} name
185
+ * @param {boolean} terminal
186
+ */
187
+ constructor(major, name, terminal) {
188
+ this.major = major;
189
+ this.majorEncoded = major << 5;
190
+ this.name = name;
191
+ this.terminal = terminal;
192
+ }
193
+ /* c8 ignore next 3 */
194
+ toString() {
195
+ return `Type[${this.major}].${this.name}`;
196
+ }
197
+ /**
198
+ * @param {Type} typ
199
+ * @returns {number}
200
+ */
201
+ compare(typ) {
202
+ return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;
203
+ }
204
+ /**
205
+ * Check equality between two Type instances. Safe to use across different
206
+ * copies of the Type class (e.g., when bundlers duplicate the module).
207
+ * (major, name) uniquely identifies a Type; terminal is implied by these.
208
+ * @param {Type} a
209
+ * @param {Type} b
210
+ * @returns {boolean}
211
+ */
212
+ static equals(a, b) {
213
+ return a === b || a.major === b.major && a.name === b.name;
214
+ }
215
+ };
216
+ Type.uint = new Type(0, "uint", true);
217
+ Type.negint = new Type(1, "negint", true);
218
+ Type.bytes = new Type(2, "bytes", true);
219
+ Type.string = new Type(3, "string", true);
220
+ Type.array = new Type(4, "array", false);
221
+ Type.map = new Type(5, "map", false);
222
+ Type.tag = new Type(6, "tag", false);
223
+ Type.float = new Type(7, "float", true);
224
+ Type.false = new Type(7, "false", true);
225
+ Type.true = new Type(7, "true", true);
226
+ Type.null = new Type(7, "null", true);
227
+ Type.undefined = new Type(7, "undefined", true);
228
+ Type.break = new Type(7, "break", true);
229
+ var Token = class {
230
+ /**
231
+ * @param {Type} type
232
+ * @param {any} [value]
233
+ * @param {number} [encodedLength]
234
+ */
235
+ constructor(type, value, encodedLength) {
236
+ this.type = type;
237
+ this.value = value;
238
+ this.encodedLength = encodedLength;
239
+ this.encodedBytes = void 0;
240
+ this.byteValue = void 0;
241
+ }
242
+ /* c8 ignore next 3 */
243
+ toString() {
244
+ return `Token[${this.type}].${this.value}`;
245
+ }
246
+ };
247
+
248
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/byte-utils.js
249
+ var useBuffer = globalThis.process && // @ts-ignore
250
+ !globalThis.process.browser && // @ts-ignore
251
+ globalThis.Buffer && // @ts-ignore
252
+ typeof globalThis.Buffer.isBuffer === "function";
253
+ var textEncoder = new TextEncoder();
254
+ function isBuffer(buf) {
255
+ return useBuffer && globalThis.Buffer.isBuffer(buf);
256
+ }
257
+ function asU8A(buf) {
258
+ if (!(buf instanceof Uint8Array)) {
259
+ return Uint8Array.from(buf);
260
+ }
261
+ return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;
262
+ }
263
+ var FROM_STRING_THRESHOLD_BUFFER = 24;
264
+ var FROM_STRING_THRESHOLD_TEXTENCODER = 200;
265
+ var fromString = useBuffer ? (
266
+ // eslint-disable-line operator-linebreak
267
+ /**
268
+ * @param {string} string
269
+ */
270
+ (string) => {
271
+ return string.length >= FROM_STRING_THRESHOLD_BUFFER ? (
272
+ // eslint-disable-line operator-linebreak
273
+ // @ts-ignore
274
+ globalThis.Buffer.from(string)
275
+ ) : utf8ToBytes(string);
276
+ }
277
+ ) : (
278
+ // eslint-disable-line operator-linebreak
279
+ /**
280
+ * @param {string} string
281
+ */
282
+ (string) => {
283
+ return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string);
284
+ }
285
+ );
286
+ var fromArray = (arr) => {
287
+ return Uint8Array.from(arr);
288
+ };
289
+ var slice = useBuffer ? (
290
+ // eslint-disable-line operator-linebreak
291
+ /**
292
+ * @param {Uint8Array} bytes
293
+ * @param {number} start
294
+ * @param {number} end
295
+ */
296
+ // Buffer.slice() returns a view, not a copy, so we need special handling
297
+ (bytes, start, end) => {
298
+ if (isBuffer(bytes)) {
299
+ return new Uint8Array(bytes.subarray(start, end));
300
+ }
301
+ return bytes.slice(start, end);
302
+ }
303
+ ) : (
304
+ // eslint-disable-line operator-linebreak
305
+ /**
306
+ * @param {Uint8Array} bytes
307
+ * @param {number} start
308
+ * @param {number} end
309
+ */
310
+ (bytes, start, end) => {
311
+ return bytes.slice(start, end);
312
+ }
313
+ );
314
+ var concat = useBuffer ? (
315
+ // eslint-disable-line operator-linebreak
316
+ /**
317
+ * @param {Uint8Array[]} chunks
318
+ * @param {number} length
319
+ * @returns {Uint8Array}
320
+ */
321
+ (chunks, length2) => {
322
+ chunks = chunks.map((c) => c instanceof Uint8Array ? c : (
323
+ // eslint-disable-line operator-linebreak
324
+ // @ts-ignore
325
+ globalThis.Buffer.from(c)
326
+ ));
327
+ return asU8A(globalThis.Buffer.concat(chunks, length2));
328
+ }
329
+ ) : (
330
+ // eslint-disable-line operator-linebreak
331
+ /**
332
+ * @param {Uint8Array[]} chunks
333
+ * @param {number} length
334
+ * @returns {Uint8Array}
335
+ */
336
+ (chunks, length2) => {
337
+ const out = new Uint8Array(length2);
338
+ let off = 0;
339
+ for (let b of chunks) {
340
+ if (off + b.length > out.length) {
341
+ b = b.subarray(0, out.length - off);
342
+ }
343
+ out.set(b, off);
344
+ off += b.length;
345
+ }
346
+ return out;
347
+ }
348
+ );
349
+ var alloc = useBuffer ? (
350
+ // eslint-disable-line operator-linebreak
351
+ /**
352
+ * @param {number} size
353
+ * @returns {Uint8Array}
354
+ */
355
+ (size) => {
356
+ return globalThis.Buffer.allocUnsafe(size);
357
+ }
358
+ ) : (
359
+ // eslint-disable-line operator-linebreak
360
+ /**
361
+ * @param {number} size
362
+ * @returns {Uint8Array}
363
+ */
364
+ (size) => {
365
+ return new Uint8Array(size);
366
+ }
367
+ );
368
+ function compare(b1, b2) {
369
+ if (isBuffer(b1) && isBuffer(b2)) {
370
+ return b1.compare(b2);
371
+ }
372
+ for (let i = 0; i < b1.length; i++) {
373
+ if (b1[i] === b2[i]) {
374
+ continue;
375
+ }
376
+ return b1[i] < b2[i] ? -1 : 1;
377
+ }
378
+ return 0;
379
+ }
380
+ function utf8ToBytes(str) {
381
+ const out = [];
382
+ let p = 0;
383
+ for (let i = 0; i < str.length; i++) {
384
+ let c = str.charCodeAt(i);
385
+ if (c < 128) {
386
+ out[p++] = c;
387
+ } else if (c < 2048) {
388
+ out[p++] = c >> 6 | 192;
389
+ out[p++] = c & 63 | 128;
390
+ } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) {
391
+ c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023);
392
+ out[p++] = c >> 18 | 240;
393
+ out[p++] = c >> 12 & 63 | 128;
394
+ out[p++] = c >> 6 & 63 | 128;
395
+ out[p++] = c & 63 | 128;
396
+ } else {
397
+ if (c >= 55296 && c <= 57343) {
398
+ c = 65533;
399
+ }
400
+ out[p++] = c >> 12 | 224;
401
+ out[p++] = c >> 6 & 63 | 128;
402
+ out[p++] = c & 63 | 128;
403
+ }
404
+ }
405
+ return out;
406
+ }
407
+
408
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/bl.js
409
+ var defaultChunkSize = 256;
410
+ var Bl = class {
411
+ /**
412
+ * @param {number} [chunkSize]
413
+ */
414
+ constructor(chunkSize = defaultChunkSize) {
415
+ this.chunkSize = chunkSize;
416
+ this.cursor = 0;
417
+ this.maxCursor = -1;
418
+ this.chunks = [];
419
+ this._initReuseChunk = null;
420
+ }
421
+ reset() {
422
+ this.cursor = 0;
423
+ this.maxCursor = -1;
424
+ if (this.chunks.length) {
425
+ this.chunks = [];
426
+ }
427
+ if (this._initReuseChunk !== null) {
428
+ this.chunks.push(this._initReuseChunk);
429
+ this.maxCursor = this._initReuseChunk.length - 1;
430
+ }
431
+ }
432
+ /**
433
+ * @param {Uint8Array|number[]} bytes
434
+ */
435
+ push(bytes) {
436
+ let topChunk = this.chunks[this.chunks.length - 1];
437
+ const newMax = this.cursor + bytes.length;
438
+ if (newMax <= this.maxCursor + 1) {
439
+ const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
440
+ topChunk.set(bytes, chunkPos);
441
+ } else {
442
+ if (topChunk) {
443
+ const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
444
+ if (chunkPos < topChunk.length) {
445
+ this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);
446
+ this.maxCursor = this.cursor - 1;
447
+ }
448
+ }
449
+ if (bytes.length < 64 && bytes.length < this.chunkSize) {
450
+ topChunk = alloc(this.chunkSize);
451
+ this.chunks.push(topChunk);
452
+ this.maxCursor += topChunk.length;
453
+ if (this._initReuseChunk === null) {
454
+ this._initReuseChunk = topChunk;
455
+ }
456
+ topChunk.set(bytes, 0);
457
+ } else {
458
+ this.chunks.push(bytes);
459
+ this.maxCursor += bytes.length;
460
+ }
461
+ }
462
+ this.cursor += bytes.length;
463
+ }
464
+ /**
465
+ * @param {boolean} [reset]
466
+ * @returns {Uint8Array}
467
+ */
468
+ toBytes(reset = false) {
469
+ let byts;
470
+ if (this.chunks.length === 1) {
471
+ const chunk = this.chunks[0];
472
+ if (reset && this.cursor > chunk.length / 2) {
473
+ byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);
474
+ this._initReuseChunk = null;
475
+ this.chunks = [];
476
+ } else {
477
+ byts = slice(chunk, 0, this.cursor);
478
+ }
479
+ } else {
480
+ byts = concat(this.chunks, this.cursor);
481
+ }
482
+ if (reset) {
483
+ this.reset();
484
+ }
485
+ return byts;
486
+ }
487
+ };
488
+ var U8Bl = class {
489
+ /**
490
+ * @param {Uint8Array} dest
491
+ */
492
+ constructor(dest) {
493
+ this.dest = dest;
494
+ this.cursor = 0;
495
+ this.chunks = [dest];
496
+ }
497
+ reset() {
498
+ this.cursor = 0;
499
+ }
500
+ /**
501
+ * @param {Uint8Array|number[]} bytes
502
+ */
503
+ push(bytes) {
504
+ if (this.cursor + bytes.length > this.dest.length) {
505
+ throw new Error("write out of bounds, destination buffer is too small");
506
+ }
507
+ this.dest.set(bytes, this.cursor);
508
+ this.cursor += bytes.length;
509
+ }
510
+ /**
511
+ * @param {boolean} [reset]
512
+ * @returns {Uint8Array}
513
+ */
514
+ toBytes(reset = false) {
515
+ const byts = this.dest.subarray(0, this.cursor);
516
+ if (reset) {
517
+ this.reset();
518
+ }
519
+ return byts;
520
+ }
521
+ };
522
+
523
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/common.js
524
+ var decodeErrPrefix = "CBOR decode error:";
525
+ var encodeErrPrefix = "CBOR encode error:";
526
+ var uintMinorPrefixBytes = [];
527
+ uintMinorPrefixBytes[23] = 1;
528
+ uintMinorPrefixBytes[24] = 2;
529
+ uintMinorPrefixBytes[25] = 3;
530
+ uintMinorPrefixBytes[26] = 5;
531
+ uintMinorPrefixBytes[27] = 9;
532
+ function assertEnoughData(data, pos, need) {
533
+ if (data.length - pos < need) {
534
+ throw new Error(`${decodeErrPrefix} not enough data for type`);
535
+ }
536
+ }
537
+
538
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/0uint.js
539
+ var uintBoundaries = [24, 256, 65536, 4294967296, BigInt("18446744073709551616")];
540
+ function readUint8(data, offset, options) {
541
+ assertEnoughData(data, offset, 1);
542
+ const value = data[offset];
543
+ if (options.strict === true && value < uintBoundaries[0]) {
544
+ throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
545
+ }
546
+ return value;
547
+ }
548
+ function readUint16(data, offset, options) {
549
+ assertEnoughData(data, offset, 2);
550
+ const value = data[offset] << 8 | data[offset + 1];
551
+ if (options.strict === true && value < uintBoundaries[1]) {
552
+ throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
553
+ }
554
+ return value;
555
+ }
556
+ function readUint32(data, offset, options) {
557
+ assertEnoughData(data, offset, 4);
558
+ const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
559
+ if (options.strict === true && value < uintBoundaries[2]) {
560
+ throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
561
+ }
562
+ return value;
563
+ }
564
+ function readUint64(data, offset, options) {
565
+ assertEnoughData(data, offset, 8);
566
+ const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
567
+ const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];
568
+ const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);
569
+ if (options.strict === true && value < uintBoundaries[3]) {
570
+ throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
571
+ }
572
+ if (value <= Number.MAX_SAFE_INTEGER) {
573
+ return Number(value);
574
+ }
575
+ if (options.allowBigInt === true) {
576
+ return value;
577
+ }
578
+ throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
579
+ }
580
+ function decodeUint8(data, pos, _minor, options) {
581
+ return new Token(Type.uint, readUint8(data, pos + 1, options), 2);
582
+ }
583
+ function decodeUint16(data, pos, _minor, options) {
584
+ return new Token(Type.uint, readUint16(data, pos + 1, options), 3);
585
+ }
586
+ function decodeUint32(data, pos, _minor, options) {
587
+ return new Token(Type.uint, readUint32(data, pos + 1, options), 5);
588
+ }
589
+ function decodeUint64(data, pos, _minor, options) {
590
+ return new Token(Type.uint, readUint64(data, pos + 1, options), 9);
591
+ }
592
+ function encodeUint(writer, token) {
593
+ return encodeUintValue(writer, 0, token.value);
594
+ }
595
+ function encodeUintValue(writer, major, uint) {
596
+ if (uint < uintBoundaries[0]) {
597
+ const nuint = Number(uint);
598
+ writer.push([major | nuint]);
599
+ } else if (uint < uintBoundaries[1]) {
600
+ const nuint = Number(uint);
601
+ writer.push([major | 24, nuint]);
602
+ } else if (uint < uintBoundaries[2]) {
603
+ const nuint = Number(uint);
604
+ writer.push([major | 25, nuint >>> 8, nuint & 255]);
605
+ } else if (uint < uintBoundaries[3]) {
606
+ const nuint = Number(uint);
607
+ writer.push([major | 26, nuint >>> 24 & 255, nuint >>> 16 & 255, nuint >>> 8 & 255, nuint & 255]);
608
+ } else {
609
+ const buint = BigInt(uint);
610
+ if (buint < uintBoundaries[4]) {
611
+ const set = [major | 27, 0, 0, 0, 0, 0, 0, 0];
612
+ let lo = Number(buint & BigInt(4294967295));
613
+ let hi = Number(buint >> BigInt(32) & BigInt(4294967295));
614
+ set[8] = lo & 255;
615
+ lo = lo >> 8;
616
+ set[7] = lo & 255;
617
+ lo = lo >> 8;
618
+ set[6] = lo & 255;
619
+ lo = lo >> 8;
620
+ set[5] = lo & 255;
621
+ set[4] = hi & 255;
622
+ hi = hi >> 8;
623
+ set[3] = hi & 255;
624
+ hi = hi >> 8;
625
+ set[2] = hi & 255;
626
+ hi = hi >> 8;
627
+ set[1] = hi & 255;
628
+ writer.push(set);
629
+ } else {
630
+ throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`);
631
+ }
632
+ }
633
+ }
634
+ encodeUint.encodedSize = function encodedSize(token) {
635
+ return encodeUintValue.encodedSize(token.value);
636
+ };
637
+ encodeUintValue.encodedSize = function encodedSize2(uint) {
638
+ if (uint < uintBoundaries[0]) {
639
+ return 1;
640
+ }
641
+ if (uint < uintBoundaries[1]) {
642
+ return 2;
643
+ }
644
+ if (uint < uintBoundaries[2]) {
645
+ return 3;
646
+ }
647
+ if (uint < uintBoundaries[3]) {
648
+ return 5;
649
+ }
650
+ return 9;
651
+ };
652
+ encodeUint.compareTokens = function compareTokens(tok1, tok2) {
653
+ return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : (
654
+ /* c8 ignore next */
655
+ 0
656
+ );
657
+ };
658
+
659
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/1negint.js
660
+ function decodeNegint8(data, pos, _minor, options) {
661
+ return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2);
662
+ }
663
+ function decodeNegint16(data, pos, _minor, options) {
664
+ return new Token(Type.negint, -1 - readUint16(data, pos + 1, options), 3);
665
+ }
666
+ function decodeNegint32(data, pos, _minor, options) {
667
+ return new Token(Type.negint, -1 - readUint32(data, pos + 1, options), 5);
668
+ }
669
+ var neg1b = BigInt(-1);
670
+ var pos1b = BigInt(1);
671
+ function decodeNegint64(data, pos, _minor, options) {
672
+ const int = readUint64(data, pos + 1, options);
673
+ if (typeof int !== "bigint") {
674
+ const value = -1 - int;
675
+ if (value >= Number.MIN_SAFE_INTEGER) {
676
+ return new Token(Type.negint, value, 9);
677
+ }
678
+ }
679
+ if (options.allowBigInt !== true) {
680
+ throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
681
+ }
682
+ return new Token(Type.negint, neg1b - BigInt(int), 9);
683
+ }
684
+ function encodeNegint(writer, token) {
685
+ const negint = token.value;
686
+ const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
687
+ encodeUintValue(writer, token.type.majorEncoded, unsigned);
688
+ }
689
+ encodeNegint.encodedSize = function encodedSize3(token) {
690
+ const negint = token.value;
691
+ const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
692
+ if (unsigned < uintBoundaries[0]) {
693
+ return 1;
694
+ }
695
+ if (unsigned < uintBoundaries[1]) {
696
+ return 2;
697
+ }
698
+ if (unsigned < uintBoundaries[2]) {
699
+ return 3;
700
+ }
701
+ if (unsigned < uintBoundaries[3]) {
702
+ return 5;
703
+ }
704
+ return 9;
705
+ };
706
+ encodeNegint.compareTokens = function compareTokens2(tok1, tok2) {
707
+ return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : (
708
+ /* c8 ignore next */
709
+ 0
710
+ );
711
+ };
712
+
713
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/2bytes.js
714
+ function toToken(data, pos, prefix, length2) {
715
+ assertEnoughData(data, pos, prefix + length2);
716
+ const buf = data.slice(pos + prefix, pos + prefix + length2);
717
+ return new Token(Type.bytes, buf, prefix + length2);
718
+ }
719
+ function decodeBytesCompact(data, pos, minor, _options) {
720
+ return toToken(data, pos, 1, minor);
721
+ }
722
+ function decodeBytes8(data, pos, _minor, options) {
723
+ return toToken(data, pos, 2, readUint8(data, pos + 1, options));
724
+ }
725
+ function decodeBytes16(data, pos, _minor, options) {
726
+ return toToken(data, pos, 3, readUint16(data, pos + 1, options));
727
+ }
728
+ function decodeBytes32(data, pos, _minor, options) {
729
+ return toToken(data, pos, 5, readUint32(data, pos + 1, options));
730
+ }
731
+ function decodeBytes64(data, pos, _minor, options) {
732
+ const l = readUint64(data, pos + 1, options);
733
+ if (typeof l === "bigint") {
734
+ throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`);
735
+ }
736
+ return toToken(data, pos, 9, l);
737
+ }
738
+ function tokenBytes(token) {
739
+ if (token.encodedBytes === void 0) {
740
+ token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value;
741
+ }
742
+ return token.encodedBytes;
743
+ }
744
+ function encodeBytes(writer, token) {
745
+ const bytes = tokenBytes(token);
746
+ encodeUintValue(writer, token.type.majorEncoded, bytes.length);
747
+ writer.push(bytes);
748
+ }
749
+ encodeBytes.encodedSize = function encodedSize4(token) {
750
+ const bytes = tokenBytes(token);
751
+ return encodeUintValue.encodedSize(bytes.length) + bytes.length;
752
+ };
753
+ encodeBytes.compareTokens = function compareTokens3(tok1, tok2) {
754
+ return compareBytes(tokenBytes(tok1), tokenBytes(tok2));
755
+ };
756
+ function compareBytes(b1, b2) {
757
+ return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
758
+ }
759
+
760
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/3string.js
761
+ var textDecoder = new TextDecoder();
762
+ var ASCII_THRESHOLD = 32;
763
+ function toStr(bytes, start, end) {
764
+ const len = end - start;
765
+ if (len < ASCII_THRESHOLD) {
766
+ let str = "";
767
+ for (let i = start; i < end; i++) {
768
+ const c = bytes[i];
769
+ if (c & 128) {
770
+ return textDecoder.decode(bytes.subarray(start, end));
771
+ }
772
+ str += String.fromCharCode(c);
773
+ }
774
+ return str;
775
+ }
776
+ return textDecoder.decode(bytes.subarray(start, end));
777
+ }
778
+ function toToken2(data, pos, prefix, length2, options) {
779
+ const totLength = prefix + length2;
780
+ assertEnoughData(data, pos, totLength);
781
+ const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength);
782
+ if (options.retainStringBytes === true) {
783
+ tok.byteValue = data.slice(pos + prefix, pos + totLength);
784
+ }
785
+ return tok;
786
+ }
787
+ function decodeStringCompact(data, pos, minor, options) {
788
+ return toToken2(data, pos, 1, minor, options);
789
+ }
790
+ function decodeString8(data, pos, _minor, options) {
791
+ return toToken2(data, pos, 2, readUint8(data, pos + 1, options), options);
792
+ }
793
+ function decodeString16(data, pos, _minor, options) {
794
+ return toToken2(data, pos, 3, readUint16(data, pos + 1, options), options);
795
+ }
796
+ function decodeString32(data, pos, _minor, options) {
797
+ return toToken2(data, pos, 5, readUint32(data, pos + 1, options), options);
798
+ }
799
+ function decodeString64(data, pos, _minor, options) {
800
+ const l = readUint64(data, pos + 1, options);
801
+ if (typeof l === "bigint") {
802
+ throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`);
803
+ }
804
+ return toToken2(data, pos, 9, l, options);
805
+ }
806
+ var encodeString = encodeBytes;
807
+
808
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/4array.js
809
+ function toToken3(_data, _pos, prefix, length2) {
810
+ return new Token(Type.array, length2, prefix);
811
+ }
812
+ function decodeArrayCompact(data, pos, minor, _options) {
813
+ return toToken3(data, pos, 1, minor);
814
+ }
815
+ function decodeArray8(data, pos, _minor, options) {
816
+ return toToken3(data, pos, 2, readUint8(data, pos + 1, options));
817
+ }
818
+ function decodeArray16(data, pos, _minor, options) {
819
+ return toToken3(data, pos, 3, readUint16(data, pos + 1, options));
820
+ }
821
+ function decodeArray32(data, pos, _minor, options) {
822
+ return toToken3(data, pos, 5, readUint32(data, pos + 1, options));
823
+ }
824
+ function decodeArray64(data, pos, _minor, options) {
825
+ const l = readUint64(data, pos + 1, options);
826
+ if (typeof l === "bigint") {
827
+ throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`);
828
+ }
829
+ return toToken3(data, pos, 9, l);
830
+ }
831
+ function decodeArrayIndefinite(data, pos, _minor, options) {
832
+ if (options.allowIndefinite === false) {
833
+ throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
834
+ }
835
+ return toToken3(data, pos, 1, Infinity);
836
+ }
837
+ function encodeArray(writer, token) {
838
+ encodeUintValue(writer, Type.array.majorEncoded, token.value);
839
+ }
840
+ encodeArray.compareTokens = encodeUint.compareTokens;
841
+ encodeArray.encodedSize = function encodedSize5(token) {
842
+ return encodeUintValue.encodedSize(token.value);
843
+ };
844
+
845
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/5map.js
846
+ function toToken4(_data, _pos, prefix, length2) {
847
+ return new Token(Type.map, length2, prefix);
848
+ }
849
+ function decodeMapCompact(data, pos, minor, _options) {
850
+ return toToken4(data, pos, 1, minor);
851
+ }
852
+ function decodeMap8(data, pos, _minor, options) {
853
+ return toToken4(data, pos, 2, readUint8(data, pos + 1, options));
854
+ }
855
+ function decodeMap16(data, pos, _minor, options) {
856
+ return toToken4(data, pos, 3, readUint16(data, pos + 1, options));
857
+ }
858
+ function decodeMap32(data, pos, _minor, options) {
859
+ return toToken4(data, pos, 5, readUint32(data, pos + 1, options));
860
+ }
861
+ function decodeMap64(data, pos, _minor, options) {
862
+ const l = readUint64(data, pos + 1, options);
863
+ if (typeof l === "bigint") {
864
+ throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`);
865
+ }
866
+ return toToken4(data, pos, 9, l);
867
+ }
868
+ function decodeMapIndefinite(data, pos, _minor, options) {
869
+ if (options.allowIndefinite === false) {
870
+ throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
871
+ }
872
+ return toToken4(data, pos, 1, Infinity);
873
+ }
874
+ function encodeMap(writer, token) {
875
+ encodeUintValue(writer, Type.map.majorEncoded, token.value);
876
+ }
877
+ encodeMap.compareTokens = encodeUint.compareTokens;
878
+ encodeMap.encodedSize = function encodedSize6(token) {
879
+ return encodeUintValue.encodedSize(token.value);
880
+ };
881
+
882
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/6tag.js
883
+ function decodeTagCompact(_data, _pos, minor, _options) {
884
+ return new Token(Type.tag, minor, 1);
885
+ }
886
+ function decodeTag8(data, pos, _minor, options) {
887
+ return new Token(Type.tag, readUint8(data, pos + 1, options), 2);
888
+ }
889
+ function decodeTag16(data, pos, _minor, options) {
890
+ return new Token(Type.tag, readUint16(data, pos + 1, options), 3);
891
+ }
892
+ function decodeTag32(data, pos, _minor, options) {
893
+ return new Token(Type.tag, readUint32(data, pos + 1, options), 5);
894
+ }
895
+ function decodeTag64(data, pos, _minor, options) {
896
+ return new Token(Type.tag, readUint64(data, pos + 1, options), 9);
897
+ }
898
+ function encodeTag(writer, token) {
899
+ encodeUintValue(writer, Type.tag.majorEncoded, token.value);
900
+ }
901
+ encodeTag.compareTokens = encodeUint.compareTokens;
902
+ encodeTag.encodedSize = function encodedSize7(token) {
903
+ return encodeUintValue.encodedSize(token.value);
904
+ };
905
+
906
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/7float.js
907
+ var MINOR_FALSE = 20;
908
+ var MINOR_TRUE = 21;
909
+ var MINOR_NULL = 22;
910
+ var MINOR_UNDEFINED = 23;
911
+ function decodeUndefined(_data, _pos, _minor, options) {
912
+ if (options.allowUndefined === false) {
913
+ throw new Error(`${decodeErrPrefix} undefined values are not supported`);
914
+ } else if (options.coerceUndefinedToNull === true) {
915
+ return new Token(Type.null, null, 1);
916
+ }
917
+ return new Token(Type.undefined, void 0, 1);
918
+ }
919
+ function decodeBreak(_data, _pos, _minor, options) {
920
+ if (options.allowIndefinite === false) {
921
+ throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
922
+ }
923
+ return new Token(Type.break, void 0, 1);
924
+ }
925
+ function createToken(value, bytes, options) {
926
+ if (options) {
927
+ if (options.allowNaN === false && Number.isNaN(value)) {
928
+ throw new Error(`${decodeErrPrefix} NaN values are not supported`);
929
+ }
930
+ if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
931
+ throw new Error(`${decodeErrPrefix} Infinity values are not supported`);
932
+ }
933
+ }
934
+ return new Token(Type.float, value, bytes);
935
+ }
936
+ function decodeFloat16(data, pos, _minor, options) {
937
+ return createToken(readFloat16(data, pos + 1), 3, options);
938
+ }
939
+ function decodeFloat32(data, pos, _minor, options) {
940
+ return createToken(readFloat32(data, pos + 1), 5, options);
941
+ }
942
+ function decodeFloat64(data, pos, _minor, options) {
943
+ return createToken(readFloat64(data, pos + 1), 9, options);
944
+ }
945
+ function encodeFloat(writer, token, options) {
946
+ const float = token.value;
947
+ if (float === false) {
948
+ writer.push([Type.float.majorEncoded | MINOR_FALSE]);
949
+ } else if (float === true) {
950
+ writer.push([Type.float.majorEncoded | MINOR_TRUE]);
951
+ } else if (float === null) {
952
+ writer.push([Type.float.majorEncoded | MINOR_NULL]);
953
+ } else if (float === void 0) {
954
+ writer.push([Type.float.majorEncoded | MINOR_UNDEFINED]);
955
+ } else {
956
+ let decoded;
957
+ let success = false;
958
+ if (!options || options.float64 !== true) {
959
+ encodeFloat16(float);
960
+ decoded = readFloat16(ui8a, 1);
961
+ if (float === decoded || Number.isNaN(float)) {
962
+ ui8a[0] = 249;
963
+ writer.push(ui8a.slice(0, 3));
964
+ success = true;
965
+ } else {
966
+ encodeFloat32(float);
967
+ decoded = readFloat32(ui8a, 1);
968
+ if (float === decoded) {
969
+ ui8a[0] = 250;
970
+ writer.push(ui8a.slice(0, 5));
971
+ success = true;
972
+ }
973
+ }
974
+ }
975
+ if (!success) {
976
+ encodeFloat64(float);
977
+ decoded = readFloat64(ui8a, 1);
978
+ ui8a[0] = 251;
979
+ writer.push(ui8a.slice(0, 9));
980
+ }
981
+ }
982
+ }
983
+ encodeFloat.encodedSize = function encodedSize8(token, options) {
984
+ const float = token.value;
985
+ if (float === false || float === true || float === null || float === void 0) {
986
+ return 1;
987
+ }
988
+ if (!options || options.float64 !== true) {
989
+ encodeFloat16(float);
990
+ let decoded = readFloat16(ui8a, 1);
991
+ if (float === decoded || Number.isNaN(float)) {
992
+ return 3;
993
+ }
994
+ encodeFloat32(float);
995
+ decoded = readFloat32(ui8a, 1);
996
+ if (float === decoded) {
997
+ return 5;
998
+ }
999
+ }
1000
+ return 9;
1001
+ };
1002
+ var buffer = new ArrayBuffer(9);
1003
+ var dataView = new DataView(buffer, 1);
1004
+ var ui8a = new Uint8Array(buffer, 0);
1005
+ function encodeFloat16(inp) {
1006
+ if (inp === Infinity) {
1007
+ dataView.setUint16(0, 31744, false);
1008
+ } else if (inp === -Infinity) {
1009
+ dataView.setUint16(0, 64512, false);
1010
+ } else if (Number.isNaN(inp)) {
1011
+ dataView.setUint16(0, 32256, false);
1012
+ } else {
1013
+ dataView.setFloat32(0, inp);
1014
+ const valu32 = dataView.getUint32(0);
1015
+ const exponent = (valu32 & 2139095040) >> 23;
1016
+ const mantissa = valu32 & 8388607;
1017
+ if (exponent === 255) {
1018
+ dataView.setUint16(0, 31744, false);
1019
+ } else if (exponent === 0) {
1020
+ dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false);
1021
+ } else {
1022
+ const logicalExponent = exponent - 127;
1023
+ if (logicalExponent < -24) {
1024
+ dataView.setUint16(0, 0);
1025
+ } else if (logicalExponent < -14) {
1026
+ dataView.setUint16(0, (valu32 & 2147483648) >> 16 | /* sign bit */
1027
+ 1 << 24 + logicalExponent, false);
1028
+ } else {
1029
+ dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);
1030
+ }
1031
+ }
1032
+ }
1033
+ }
1034
+ function readFloat16(ui8a2, pos) {
1035
+ if (ui8a2.length - pos < 2) {
1036
+ throw new Error(`${decodeErrPrefix} not enough data for float16`);
1037
+ }
1038
+ const half = (ui8a2[pos] << 8) + ui8a2[pos + 1];
1039
+ if (half === 31744) {
1040
+ return Infinity;
1041
+ }
1042
+ if (half === 64512) {
1043
+ return -Infinity;
1044
+ }
1045
+ if (half === 32256) {
1046
+ return NaN;
1047
+ }
1048
+ const exp = half >> 10 & 31;
1049
+ const mant = half & 1023;
1050
+ let val;
1051
+ if (exp === 0) {
1052
+ val = mant * 2 ** -24;
1053
+ } else if (exp !== 31) {
1054
+ val = (mant + 1024) * 2 ** (exp - 25);
1055
+ } else {
1056
+ val = mant === 0 ? Infinity : NaN;
1057
+ }
1058
+ return half & 32768 ? -val : val;
1059
+ }
1060
+ function encodeFloat32(inp) {
1061
+ dataView.setFloat32(0, inp, false);
1062
+ }
1063
+ function readFloat32(ui8a2, pos) {
1064
+ if (ui8a2.length - pos < 4) {
1065
+ throw new Error(`${decodeErrPrefix} not enough data for float32`);
1066
+ }
1067
+ const offset = (ui8a2.byteOffset || 0) + pos;
1068
+ return new DataView(ui8a2.buffer, offset, 4).getFloat32(0, false);
1069
+ }
1070
+ function encodeFloat64(inp) {
1071
+ dataView.setFloat64(0, inp, false);
1072
+ }
1073
+ function readFloat64(ui8a2, pos) {
1074
+ if (ui8a2.length - pos < 8) {
1075
+ throw new Error(`${decodeErrPrefix} not enough data for float64`);
1076
+ }
1077
+ const offset = (ui8a2.byteOffset || 0) + pos;
1078
+ return new DataView(ui8a2.buffer, offset, 8).getFloat64(0, false);
1079
+ }
1080
+ encodeFloat.compareTokens = encodeUint.compareTokens;
1081
+
1082
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/jump.js
1083
+ function invalidMinor(data, pos, minor) {
1084
+ throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`);
1085
+ }
1086
+ function errorer(msg) {
1087
+ return () => {
1088
+ throw new Error(`${decodeErrPrefix} ${msg}`);
1089
+ };
1090
+ }
1091
+ var jump = [];
1092
+ for (let i = 0; i <= 23; i++) {
1093
+ jump[i] = invalidMinor;
1094
+ }
1095
+ jump[24] = decodeUint8;
1096
+ jump[25] = decodeUint16;
1097
+ jump[26] = decodeUint32;
1098
+ jump[27] = decodeUint64;
1099
+ jump[28] = invalidMinor;
1100
+ jump[29] = invalidMinor;
1101
+ jump[30] = invalidMinor;
1102
+ jump[31] = invalidMinor;
1103
+ for (let i = 32; i <= 55; i++) {
1104
+ jump[i] = invalidMinor;
1105
+ }
1106
+ jump[56] = decodeNegint8;
1107
+ jump[57] = decodeNegint16;
1108
+ jump[58] = decodeNegint32;
1109
+ jump[59] = decodeNegint64;
1110
+ jump[60] = invalidMinor;
1111
+ jump[61] = invalidMinor;
1112
+ jump[62] = invalidMinor;
1113
+ jump[63] = invalidMinor;
1114
+ for (let i = 64; i <= 87; i++) {
1115
+ jump[i] = decodeBytesCompact;
1116
+ }
1117
+ jump[88] = decodeBytes8;
1118
+ jump[89] = decodeBytes16;
1119
+ jump[90] = decodeBytes32;
1120
+ jump[91] = decodeBytes64;
1121
+ jump[92] = invalidMinor;
1122
+ jump[93] = invalidMinor;
1123
+ jump[94] = invalidMinor;
1124
+ jump[95] = errorer("indefinite length bytes/strings are not supported");
1125
+ for (let i = 96; i <= 119; i++) {
1126
+ jump[i] = decodeStringCompact;
1127
+ }
1128
+ jump[120] = decodeString8;
1129
+ jump[121] = decodeString16;
1130
+ jump[122] = decodeString32;
1131
+ jump[123] = decodeString64;
1132
+ jump[124] = invalidMinor;
1133
+ jump[125] = invalidMinor;
1134
+ jump[126] = invalidMinor;
1135
+ jump[127] = errorer("indefinite length bytes/strings are not supported");
1136
+ for (let i = 128; i <= 151; i++) {
1137
+ jump[i] = decodeArrayCompact;
1138
+ }
1139
+ jump[152] = decodeArray8;
1140
+ jump[153] = decodeArray16;
1141
+ jump[154] = decodeArray32;
1142
+ jump[155] = decodeArray64;
1143
+ jump[156] = invalidMinor;
1144
+ jump[157] = invalidMinor;
1145
+ jump[158] = invalidMinor;
1146
+ jump[159] = decodeArrayIndefinite;
1147
+ for (let i = 160; i <= 183; i++) {
1148
+ jump[i] = decodeMapCompact;
1149
+ }
1150
+ jump[184] = decodeMap8;
1151
+ jump[185] = decodeMap16;
1152
+ jump[186] = decodeMap32;
1153
+ jump[187] = decodeMap64;
1154
+ jump[188] = invalidMinor;
1155
+ jump[189] = invalidMinor;
1156
+ jump[190] = invalidMinor;
1157
+ jump[191] = decodeMapIndefinite;
1158
+ for (let i = 192; i <= 215; i++) {
1159
+ jump[i] = decodeTagCompact;
1160
+ }
1161
+ jump[216] = decodeTag8;
1162
+ jump[217] = decodeTag16;
1163
+ jump[218] = decodeTag32;
1164
+ jump[219] = decodeTag64;
1165
+ jump[220] = invalidMinor;
1166
+ jump[221] = invalidMinor;
1167
+ jump[222] = invalidMinor;
1168
+ jump[223] = invalidMinor;
1169
+ for (let i = 224; i <= 243; i++) {
1170
+ jump[i] = errorer("simple values are not supported");
1171
+ }
1172
+ jump[244] = invalidMinor;
1173
+ jump[245] = invalidMinor;
1174
+ jump[246] = invalidMinor;
1175
+ jump[247] = decodeUndefined;
1176
+ jump[248] = errorer("simple values are not supported");
1177
+ jump[249] = decodeFloat16;
1178
+ jump[250] = decodeFloat32;
1179
+ jump[251] = decodeFloat64;
1180
+ jump[252] = invalidMinor;
1181
+ jump[253] = invalidMinor;
1182
+ jump[254] = invalidMinor;
1183
+ jump[255] = decodeBreak;
1184
+ var quick = [];
1185
+ for (let i = 0; i < 24; i++) {
1186
+ quick[i] = new Token(Type.uint, i, 1);
1187
+ }
1188
+ for (let i = -1; i >= -24; i--) {
1189
+ quick[31 - i] = new Token(Type.negint, i, 1);
1190
+ }
1191
+ quick[64] = new Token(Type.bytes, new Uint8Array(0), 1);
1192
+ quick[96] = new Token(Type.string, "", 1);
1193
+ quick[128] = new Token(Type.array, 0, 1);
1194
+ quick[160] = new Token(Type.map, 0, 1);
1195
+ quick[244] = new Token(Type.false, false, 1);
1196
+ quick[245] = new Token(Type.true, true, 1);
1197
+ quick[246] = new Token(Type.null, null, 1);
1198
+ function quickEncodeToken(token) {
1199
+ switch (token.type) {
1200
+ case Type.false:
1201
+ return fromArray([244]);
1202
+ case Type.true:
1203
+ return fromArray([245]);
1204
+ case Type.null:
1205
+ return fromArray([246]);
1206
+ case Type.bytes:
1207
+ if (!token.value.length) {
1208
+ return fromArray([64]);
1209
+ }
1210
+ return;
1211
+ case Type.string:
1212
+ if (token.value === "") {
1213
+ return fromArray([96]);
1214
+ }
1215
+ return;
1216
+ case Type.array:
1217
+ if (token.value === 0) {
1218
+ return fromArray([128]);
1219
+ }
1220
+ return;
1221
+ case Type.map:
1222
+ if (token.value === 0) {
1223
+ return fromArray([160]);
1224
+ }
1225
+ return;
1226
+ case Type.uint:
1227
+ if (token.value < 24) {
1228
+ return fromArray([Number(token.value)]);
1229
+ }
1230
+ return;
1231
+ case Type.negint:
1232
+ if (token.value >= -24) {
1233
+ return fromArray([31 - Number(token.value)]);
1234
+ }
1235
+ }
1236
+ }
1237
+
1238
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/encode.js
1239
+ var defaultEncodeOptions = {
1240
+ float64: false,
1241
+ mapSorter,
1242
+ quickEncodeToken
1243
+ };
1244
+ var rfc8949EncodeOptions = Object.freeze({
1245
+ float64: true,
1246
+ mapSorter: rfc8949MapSorter,
1247
+ quickEncodeToken
1248
+ });
1249
+ function makeCborEncoders() {
1250
+ const encoders = [];
1251
+ encoders[Type.uint.major] = encodeUint;
1252
+ encoders[Type.negint.major] = encodeNegint;
1253
+ encoders[Type.bytes.major] = encodeBytes;
1254
+ encoders[Type.string.major] = encodeString;
1255
+ encoders[Type.array.major] = encodeArray;
1256
+ encoders[Type.map.major] = encodeMap;
1257
+ encoders[Type.tag.major] = encodeTag;
1258
+ encoders[Type.float.major] = encodeFloat;
1259
+ return encoders;
1260
+ }
1261
+ var cborEncoders = makeCborEncoders();
1262
+ var defaultWriter = new Bl();
1263
+ var Ref = class _Ref {
1264
+ /**
1265
+ * @param {object|any[]} obj
1266
+ * @param {Reference|undefined} parent
1267
+ */
1268
+ constructor(obj, parent) {
1269
+ this.obj = obj;
1270
+ this.parent = parent;
1271
+ }
1272
+ /**
1273
+ * @param {object|any[]} obj
1274
+ * @returns {boolean}
1275
+ */
1276
+ includes(obj) {
1277
+ let p = this;
1278
+ do {
1279
+ if (p.obj === obj) {
1280
+ return true;
1281
+ }
1282
+ } while (p = p.parent);
1283
+ return false;
1284
+ }
1285
+ /**
1286
+ * @param {Reference|undefined} stack
1287
+ * @param {object|any[]} obj
1288
+ * @returns {Reference}
1289
+ */
1290
+ static createCheck(stack, obj) {
1291
+ if (stack && stack.includes(obj)) {
1292
+ throw new Error(`${encodeErrPrefix} object contains circular references`);
1293
+ }
1294
+ return new _Ref(obj, stack);
1295
+ }
1296
+ };
1297
+ var simpleTokens = {
1298
+ null: new Token(Type.null, null),
1299
+ undefined: new Token(Type.undefined, void 0),
1300
+ true: new Token(Type.true, true),
1301
+ false: new Token(Type.false, false),
1302
+ emptyArray: new Token(Type.array, 0),
1303
+ emptyMap: new Token(Type.map, 0)
1304
+ };
1305
+ var typeEncoders = {
1306
+ /**
1307
+ * @param {any} obj
1308
+ * @param {string} _typ
1309
+ * @param {EncodeOptions} _options
1310
+ * @param {Reference} [_refStack]
1311
+ * @returns {TokenOrNestedTokens}
1312
+ */
1313
+ number(obj, _typ, _options, _refStack) {
1314
+ if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
1315
+ return new Token(Type.float, obj);
1316
+ } else if (obj >= 0) {
1317
+ return new Token(Type.uint, obj);
1318
+ } else {
1319
+ return new Token(Type.negint, obj);
1320
+ }
1321
+ },
1322
+ /**
1323
+ * @param {any} obj
1324
+ * @param {string} _typ
1325
+ * @param {EncodeOptions} _options
1326
+ * @param {Reference} [_refStack]
1327
+ * @returns {TokenOrNestedTokens}
1328
+ */
1329
+ bigint(obj, _typ, _options, _refStack) {
1330
+ if (obj >= BigInt(0)) {
1331
+ return new Token(Type.uint, obj);
1332
+ } else {
1333
+ return new Token(Type.negint, obj);
1334
+ }
1335
+ },
1336
+ /**
1337
+ * @param {any} obj
1338
+ * @param {string} _typ
1339
+ * @param {EncodeOptions} _options
1340
+ * @param {Reference} [_refStack]
1341
+ * @returns {TokenOrNestedTokens}
1342
+ */
1343
+ Uint8Array(obj, _typ, _options, _refStack) {
1344
+ return new Token(Type.bytes, obj);
1345
+ },
1346
+ /**
1347
+ * @param {any} obj
1348
+ * @param {string} _typ
1349
+ * @param {EncodeOptions} _options
1350
+ * @param {Reference} [_refStack]
1351
+ * @returns {TokenOrNestedTokens}
1352
+ */
1353
+ string(obj, _typ, _options, _refStack) {
1354
+ return new Token(Type.string, obj);
1355
+ },
1356
+ /**
1357
+ * @param {any} obj
1358
+ * @param {string} _typ
1359
+ * @param {EncodeOptions} _options
1360
+ * @param {Reference} [_refStack]
1361
+ * @returns {TokenOrNestedTokens}
1362
+ */
1363
+ boolean(obj, _typ, _options, _refStack) {
1364
+ return obj ? simpleTokens.true : simpleTokens.false;
1365
+ },
1366
+ /**
1367
+ * @param {any} _obj
1368
+ * @param {string} _typ
1369
+ * @param {EncodeOptions} _options
1370
+ * @param {Reference} [_refStack]
1371
+ * @returns {TokenOrNestedTokens}
1372
+ */
1373
+ null(_obj, _typ, _options, _refStack) {
1374
+ return simpleTokens.null;
1375
+ },
1376
+ /**
1377
+ * @param {any} _obj
1378
+ * @param {string} _typ
1379
+ * @param {EncodeOptions} _options
1380
+ * @param {Reference} [_refStack]
1381
+ * @returns {TokenOrNestedTokens}
1382
+ */
1383
+ undefined(_obj, _typ, _options, _refStack) {
1384
+ return simpleTokens.undefined;
1385
+ },
1386
+ /**
1387
+ * @param {any} obj
1388
+ * @param {string} _typ
1389
+ * @param {EncodeOptions} _options
1390
+ * @param {Reference} [_refStack]
1391
+ * @returns {TokenOrNestedTokens}
1392
+ */
1393
+ ArrayBuffer(obj, _typ, _options, _refStack) {
1394
+ return new Token(Type.bytes, new Uint8Array(obj));
1395
+ },
1396
+ /**
1397
+ * @param {any} obj
1398
+ * @param {string} _typ
1399
+ * @param {EncodeOptions} _options
1400
+ * @param {Reference} [_refStack]
1401
+ * @returns {TokenOrNestedTokens}
1402
+ */
1403
+ DataView(obj, _typ, _options, _refStack) {
1404
+ return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));
1405
+ },
1406
+ /**
1407
+ * @param {any} obj
1408
+ * @param {string} _typ
1409
+ * @param {EncodeOptions} options
1410
+ * @param {Reference} [refStack]
1411
+ * @returns {TokenOrNestedTokens}
1412
+ */
1413
+ Array(obj, _typ, options, refStack) {
1414
+ if (!obj.length) {
1415
+ if (options.addBreakTokens === true) {
1416
+ return [simpleTokens.emptyArray, new Token(Type.break)];
1417
+ }
1418
+ return simpleTokens.emptyArray;
1419
+ }
1420
+ refStack = Ref.createCheck(refStack, obj);
1421
+ const entries = [];
1422
+ let i = 0;
1423
+ for (const e of obj) {
1424
+ entries[i++] = objectToTokens(e, options, refStack);
1425
+ }
1426
+ if (options.addBreakTokens) {
1427
+ return [new Token(Type.array, obj.length), entries, new Token(Type.break)];
1428
+ }
1429
+ return [new Token(Type.array, obj.length), entries];
1430
+ },
1431
+ /**
1432
+ * @param {any} obj
1433
+ * @param {string} typ
1434
+ * @param {EncodeOptions} options
1435
+ * @param {Reference} [refStack]
1436
+ * @returns {TokenOrNestedTokens}
1437
+ */
1438
+ Object(obj, typ, options, refStack) {
1439
+ const isMap = typ !== "Object";
1440
+ const keys = isMap ? obj.keys() : Object.keys(obj);
1441
+ const maxLength = isMap ? obj.size : keys.length;
1442
+ let entries;
1443
+ if (maxLength) {
1444
+ entries = new Array(maxLength);
1445
+ refStack = Ref.createCheck(refStack, obj);
1446
+ const skipUndefined = !isMap && options.ignoreUndefinedProperties;
1447
+ let i = 0;
1448
+ for (const key of keys) {
1449
+ const value = isMap ? obj.get(key) : obj[key];
1450
+ if (skipUndefined && value === void 0) {
1451
+ continue;
1452
+ }
1453
+ entries[i++] = [
1454
+ objectToTokens(key, options, refStack),
1455
+ objectToTokens(value, options, refStack)
1456
+ ];
1457
+ }
1458
+ if (i < maxLength) {
1459
+ entries.length = i;
1460
+ }
1461
+ }
1462
+ if (!entries?.length) {
1463
+ if (options.addBreakTokens === true) {
1464
+ return [simpleTokens.emptyMap, new Token(Type.break)];
1465
+ }
1466
+ return simpleTokens.emptyMap;
1467
+ }
1468
+ sortMapEntries(entries, options);
1469
+ if (options.addBreakTokens) {
1470
+ return [new Token(Type.map, entries.length), entries, new Token(Type.break)];
1471
+ }
1472
+ return [new Token(Type.map, entries.length), entries];
1473
+ }
1474
+ };
1475
+ typeEncoders.Map = typeEncoders.Object;
1476
+ typeEncoders.Buffer = typeEncoders.Uint8Array;
1477
+ for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")) {
1478
+ typeEncoders[`${typ}Array`] = typeEncoders.DataView;
1479
+ }
1480
+ function objectToTokens(obj, options = {}, refStack) {
1481
+ const typ = is(obj);
1482
+ const customTypeEncoder = options && options.typeEncoders && /** @type {OptionalTypeEncoder} */
1483
+ options.typeEncoders[typ] || typeEncoders[typ];
1484
+ if (typeof customTypeEncoder === "function") {
1485
+ const tokens = customTypeEncoder(obj, typ, options, refStack);
1486
+ if (tokens != null) {
1487
+ return tokens;
1488
+ }
1489
+ }
1490
+ const typeEncoder = typeEncoders[typ];
1491
+ if (!typeEncoder) {
1492
+ throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
1493
+ }
1494
+ return typeEncoder(obj, typ, options, refStack);
1495
+ }
1496
+ function sortMapEntries(entries, options) {
1497
+ if (options.mapSorter) {
1498
+ entries.sort(options.mapSorter);
1499
+ }
1500
+ }
1501
+ function mapSorter(e1, e2) {
1502
+ const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];
1503
+ const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];
1504
+ if (keyToken1.type !== keyToken2.type) {
1505
+ return keyToken1.type.compare(keyToken2.type);
1506
+ }
1507
+ const major = keyToken1.type.major;
1508
+ const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2);
1509
+ if (tcmp === 0) {
1510
+ console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone");
1511
+ }
1512
+ return tcmp;
1513
+ }
1514
+ function rfc8949MapSorter(e1, e2) {
1515
+ if (e1[0] instanceof Token && e2[0] instanceof Token) {
1516
+ const t1 = (
1517
+ /** @type {TokenEx} */
1518
+ e1[0]
1519
+ );
1520
+ const t2 = (
1521
+ /** @type {TokenEx} */
1522
+ e2[0]
1523
+ );
1524
+ if (!t1._keyBytes) {
1525
+ t1._keyBytes = encodeRfc8949(t1.value);
1526
+ }
1527
+ if (!t2._keyBytes) {
1528
+ t2._keyBytes = encodeRfc8949(t2.value);
1529
+ }
1530
+ return compare(t1._keyBytes, t2._keyBytes);
1531
+ }
1532
+ throw new Error("rfc8949MapSorter: complex key types are not supported yet");
1533
+ }
1534
+ function encodeRfc8949(data) {
1535
+ return encodeCustom(data, cborEncoders, rfc8949EncodeOptions);
1536
+ }
1537
+ function tokensToEncoded(writer, tokens, encoders, options) {
1538
+ if (Array.isArray(tokens)) {
1539
+ for (const token of tokens) {
1540
+ tokensToEncoded(writer, token, encoders, options);
1541
+ }
1542
+ } else {
1543
+ encoders[tokens.type.major](writer, tokens, options);
1544
+ }
1545
+ }
1546
+ var MAJOR_UINT = Type.uint.majorEncoded;
1547
+ var MAJOR_NEGINT = Type.negint.majorEncoded;
1548
+ var MAJOR_BYTES = Type.bytes.majorEncoded;
1549
+ var MAJOR_STRING = Type.string.majorEncoded;
1550
+ var MAJOR_ARRAY = Type.array.majorEncoded;
1551
+ var SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE;
1552
+ var SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE;
1553
+ var SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL;
1554
+ var SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED;
1555
+ var neg1b2 = BigInt(-1);
1556
+ var pos1b2 = BigInt(1);
1557
+ function canDirectEncode(options) {
1558
+ return options.addBreakTokens !== true;
1559
+ }
1560
+ function directEncode(writer, data, options, refStack) {
1561
+ const typ = is(data);
1562
+ const customEncoder = options.typeEncoders && options.typeEncoders[typ];
1563
+ if (customEncoder) {
1564
+ const tokens = customEncoder(data, typ, options, refStack);
1565
+ if (tokens != null) {
1566
+ tokensToEncoded(writer, tokens, cborEncoders, options);
1567
+ return;
1568
+ }
1569
+ }
1570
+ switch (typ) {
1571
+ case "null":
1572
+ writer.push([SIMPLE_NULL]);
1573
+ return;
1574
+ case "undefined":
1575
+ writer.push([SIMPLE_UNDEFINED]);
1576
+ return;
1577
+ case "boolean":
1578
+ writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE]);
1579
+ return;
1580
+ case "number":
1581
+ if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
1582
+ encodeFloat(writer, new Token(Type.float, data), options);
1583
+ } else if (data >= 0) {
1584
+ encodeUintValue(writer, MAJOR_UINT, data);
1585
+ } else {
1586
+ encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1);
1587
+ }
1588
+ return;
1589
+ case "bigint":
1590
+ if (data >= BigInt(0)) {
1591
+ encodeUintValue(writer, MAJOR_UINT, data);
1592
+ } else {
1593
+ encodeUintValue(writer, MAJOR_NEGINT, data * neg1b2 - pos1b2);
1594
+ }
1595
+ return;
1596
+ case "string": {
1597
+ const bytes = fromString(data);
1598
+ encodeUintValue(writer, MAJOR_STRING, bytes.length);
1599
+ writer.push(bytes);
1600
+ return;
1601
+ }
1602
+ case "Uint8Array":
1603
+ encodeUintValue(writer, MAJOR_BYTES, data.length);
1604
+ writer.push(data);
1605
+ return;
1606
+ case "Array":
1607
+ if (!data.length) {
1608
+ writer.push([MAJOR_ARRAY]);
1609
+ return;
1610
+ }
1611
+ refStack = Ref.createCheck(refStack, data);
1612
+ encodeUintValue(writer, MAJOR_ARRAY, data.length);
1613
+ for (const elem of data) {
1614
+ directEncode(writer, elem, options, refStack);
1615
+ }
1616
+ return;
1617
+ case "Object":
1618
+ case "Map":
1619
+ {
1620
+ const tokens = typeEncoders.Object(data, typ, options, refStack);
1621
+ tokensToEncoded(writer, tokens, cborEncoders, options);
1622
+ }
1623
+ return;
1624
+ default: {
1625
+ const typeEncoder = typeEncoders[typ];
1626
+ if (!typeEncoder) {
1627
+ throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
1628
+ }
1629
+ const tokens = typeEncoder(data, typ, options, refStack);
1630
+ tokensToEncoded(writer, tokens, cborEncoders, options);
1631
+ }
1632
+ }
1633
+ }
1634
+ function encodeCustom(data, encoders, options, destination) {
1635
+ const hasDest = destination instanceof Uint8Array;
1636
+ let writeTo = hasDest ? new U8Bl(destination) : defaultWriter;
1637
+ const tokens = objectToTokens(data, options);
1638
+ if (!Array.isArray(tokens) && options.quickEncodeToken) {
1639
+ const quickBytes = options.quickEncodeToken(tokens);
1640
+ if (quickBytes) {
1641
+ if (hasDest) {
1642
+ writeTo.push(quickBytes);
1643
+ return writeTo.toBytes();
1644
+ }
1645
+ return quickBytes;
1646
+ }
1647
+ const encoder = encoders[tokens.type.major];
1648
+ if (encoder.encodedSize) {
1649
+ const size = encoder.encodedSize(tokens, options);
1650
+ if (!hasDest) {
1651
+ writeTo = new Bl(size);
1652
+ }
1653
+ encoder(writeTo, tokens, options);
1654
+ if (writeTo.chunks.length !== 1) {
1655
+ throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`);
1656
+ }
1657
+ return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0]);
1658
+ }
1659
+ }
1660
+ writeTo.reset();
1661
+ tokensToEncoded(writeTo, tokens, encoders, options);
1662
+ return writeTo.toBytes(true);
1663
+ }
1664
+ function encode(data, options) {
1665
+ options = Object.assign({}, defaultEncodeOptions, options);
1666
+ if (canDirectEncode(options)) {
1667
+ defaultWriter.reset();
1668
+ directEncode(defaultWriter, data, options, void 0);
1669
+ return defaultWriter.toBytes(true);
1670
+ }
1671
+ return encodeCustom(data, cborEncoders, options);
1672
+ }
1673
+
1674
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/decode.js
1675
+ var defaultDecodeOptions = {
1676
+ strict: false,
1677
+ allowIndefinite: true,
1678
+ allowUndefined: true,
1679
+ allowBigInt: true
1680
+ };
1681
+ var Tokeniser = class {
1682
+ /**
1683
+ * @param {Uint8Array} data
1684
+ * @param {DecodeOptions} options
1685
+ */
1686
+ constructor(data, options = {}) {
1687
+ this._pos = 0;
1688
+ this.data = data;
1689
+ this.options = options;
1690
+ }
1691
+ pos() {
1692
+ return this._pos;
1693
+ }
1694
+ done() {
1695
+ return this._pos >= this.data.length;
1696
+ }
1697
+ next() {
1698
+ const byt = this.data[this._pos];
1699
+ let token = quick[byt];
1700
+ if (token === void 0) {
1701
+ const decoder = jump[byt];
1702
+ if (!decoder) {
1703
+ throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, "0")})`);
1704
+ }
1705
+ const minor = byt & 31;
1706
+ token = decoder(this.data, this._pos, minor, this.options);
1707
+ }
1708
+ this._pos += token.encodedLength;
1709
+ return token;
1710
+ }
1711
+ };
1712
+ var DONE = Symbol.for("DONE");
1713
+ var BREAK = Symbol.for("BREAK");
1714
+ function tokenToArray(token, tokeniser, options) {
1715
+ const arr = [];
1716
+ for (let i = 0; i < token.value; i++) {
1717
+ const value = tokensToObject(tokeniser, options);
1718
+ if (value === BREAK) {
1719
+ if (token.value === Infinity) {
1720
+ break;
1721
+ }
1722
+ throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`);
1723
+ }
1724
+ if (value === DONE) {
1725
+ throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`);
1726
+ }
1727
+ arr[i] = value;
1728
+ }
1729
+ return arr;
1730
+ }
1731
+ function tokenToMap(token, tokeniser, options) {
1732
+ const useMaps = options.useMaps === true;
1733
+ const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true;
1734
+ const obj = useMaps ? void 0 : {};
1735
+ const m = useMaps ? /* @__PURE__ */ new Map() : void 0;
1736
+ for (let i = 0; i < token.value; i++) {
1737
+ const key = tokensToObject(tokeniser, options);
1738
+ if (key === BREAK) {
1739
+ if (token.value === Infinity) {
1740
+ break;
1741
+ }
1742
+ throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`);
1743
+ }
1744
+ if (key === DONE) {
1745
+ throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`);
1746
+ }
1747
+ if (!useMaps && typeof key !== "string") {
1748
+ throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`);
1749
+ }
1750
+ if (rejectDuplicateMapKeys) {
1751
+ if (useMaps && m.has(key) || !useMaps && Object.hasOwn(obj, key)) {
1752
+ throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`);
1753
+ }
1754
+ }
1755
+ const value = tokensToObject(tokeniser, options);
1756
+ if (value === DONE) {
1757
+ throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`);
1758
+ }
1759
+ if (useMaps) {
1760
+ m.set(key, value);
1761
+ } else {
1762
+ obj[key] = value;
1763
+ }
1764
+ }
1765
+ return useMaps ? m : obj;
1766
+ }
1767
+ function tokensToObject(tokeniser, options) {
1768
+ if (tokeniser.done()) {
1769
+ return DONE;
1770
+ }
1771
+ const token = tokeniser.next();
1772
+ if (Type.equals(token.type, Type.break)) {
1773
+ return BREAK;
1774
+ }
1775
+ if (token.type.terminal) {
1776
+ return token.value;
1777
+ }
1778
+ if (Type.equals(token.type, Type.array)) {
1779
+ return tokenToArray(token, tokeniser, options);
1780
+ }
1781
+ if (Type.equals(token.type, Type.map)) {
1782
+ return tokenToMap(token, tokeniser, options);
1783
+ }
1784
+ if (Type.equals(token.type, Type.tag)) {
1785
+ if (options.tags && typeof options.tags[token.value] === "function") {
1786
+ const tagged = tokensToObject(tokeniser, options);
1787
+ return options.tags[token.value](tagged);
1788
+ }
1789
+ throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`);
1790
+ }
1791
+ throw new Error("unsupported");
1792
+ }
1793
+ function decodeFirst(data, options) {
1794
+ if (!(data instanceof Uint8Array)) {
1795
+ throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`);
1796
+ }
1797
+ options = Object.assign({}, defaultDecodeOptions, options);
1798
+ const u8aData = asU8A(data);
1799
+ const tokeniser = options.tokenizer || new Tokeniser(u8aData, options);
1800
+ const decoded = tokensToObject(tokeniser, options);
1801
+ if (decoded === DONE) {
1802
+ throw new Error(`${decodeErrPrefix} did not find any content to decode`);
1803
+ }
1804
+ if (decoded === BREAK) {
1805
+ throw new Error(`${decodeErrPrefix} got unexpected break`);
1806
+ }
1807
+ return [decoded, data.subarray(tokeniser.pos())];
1808
+ }
1809
+ function decode2(data, options) {
1810
+ const [decoded, remainder] = decodeFirst(data, options);
1811
+ if (remainder.length > 0) {
1812
+ throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`);
1813
+ }
1814
+ return decoded;
1815
+ }
1816
+
1817
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bytes.js
1818
+ var empty = new Uint8Array(0);
1819
+ function equals(aa, bb) {
1820
+ if (aa === bb) {
1821
+ return true;
1822
+ }
1823
+ if (aa.byteLength !== bb.byteLength) {
1824
+ return false;
1825
+ }
1826
+ for (let ii = 0; ii < aa.byteLength; ii++) {
1827
+ if (aa[ii] !== bb[ii]) {
1828
+ return false;
1829
+ }
1830
+ }
1831
+ return true;
1832
+ }
1833
+ function coerce(o) {
1834
+ if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") {
1835
+ return o;
1836
+ }
1837
+ if (o instanceof ArrayBuffer) {
1838
+ return new Uint8Array(o);
1839
+ }
1840
+ if (ArrayBuffer.isView(o)) {
1841
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
1842
+ }
1843
+ throw new Error("Unknown type, must be binary type");
1844
+ }
1845
+
1846
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/vendor/base-x.js
1847
+ function base(ALPHABET, name) {
1848
+ if (ALPHABET.length >= 255) {
1849
+ throw new TypeError("Alphabet too long");
1850
+ }
1851
+ var BASE_MAP = new Uint8Array(256);
1852
+ for (var j = 0; j < BASE_MAP.length; j++) {
1853
+ BASE_MAP[j] = 255;
1854
+ }
1855
+ for (var i = 0; i < ALPHABET.length; i++) {
1856
+ var x = ALPHABET.charAt(i);
1857
+ var xc = x.charCodeAt(0);
1858
+ if (BASE_MAP[xc] !== 255) {
1859
+ throw new TypeError(x + " is ambiguous");
1860
+ }
1861
+ BASE_MAP[xc] = i;
1862
+ }
1863
+ var BASE = ALPHABET.length;
1864
+ var LEADER = ALPHABET.charAt(0);
1865
+ var FACTOR = Math.log(BASE) / Math.log(256);
1866
+ var iFACTOR = Math.log(256) / Math.log(BASE);
1867
+ function encode5(source) {
1868
+ if (source instanceof Uint8Array)
1869
+ ;
1870
+ else if (ArrayBuffer.isView(source)) {
1871
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
1872
+ } else if (Array.isArray(source)) {
1873
+ source = Uint8Array.from(source);
1874
+ }
1875
+ if (!(source instanceof Uint8Array)) {
1876
+ throw new TypeError("Expected Uint8Array");
1877
+ }
1878
+ if (source.length === 0) {
1879
+ return "";
1880
+ }
1881
+ var zeroes = 0;
1882
+ var length2 = 0;
1883
+ var pbegin = 0;
1884
+ var pend = source.length;
1885
+ while (pbegin !== pend && source[pbegin] === 0) {
1886
+ pbegin++;
1887
+ zeroes++;
1888
+ }
1889
+ var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
1890
+ var b58 = new Uint8Array(size);
1891
+ while (pbegin !== pend) {
1892
+ var carry = source[pbegin];
1893
+ var i2 = 0;
1894
+ for (var it1 = size - 1; (carry !== 0 || i2 < length2) && it1 !== -1; it1--, i2++) {
1895
+ carry += 256 * b58[it1] >>> 0;
1896
+ b58[it1] = carry % BASE >>> 0;
1897
+ carry = carry / BASE >>> 0;
1898
+ }
1899
+ if (carry !== 0) {
1900
+ throw new Error("Non-zero carry");
1901
+ }
1902
+ length2 = i2;
1903
+ pbegin++;
1904
+ }
1905
+ var it2 = size - length2;
1906
+ while (it2 !== size && b58[it2] === 0) {
1907
+ it2++;
1908
+ }
1909
+ var str = LEADER.repeat(zeroes);
1910
+ for (; it2 < size; ++it2) {
1911
+ str += ALPHABET.charAt(b58[it2]);
1912
+ }
1913
+ return str;
1914
+ }
1915
+ function decodeUnsafe(source) {
1916
+ if (typeof source !== "string") {
1917
+ throw new TypeError("Expected String");
1918
+ }
1919
+ if (source.length === 0) {
1920
+ return new Uint8Array();
1921
+ }
1922
+ var psz = 0;
1923
+ if (source[psz] === " ") {
1924
+ return;
1925
+ }
1926
+ var zeroes = 0;
1927
+ var length2 = 0;
1928
+ while (source[psz] === LEADER) {
1929
+ zeroes++;
1930
+ psz++;
1931
+ }
1932
+ var size = (source.length - psz) * FACTOR + 1 >>> 0;
1933
+ var b256 = new Uint8Array(size);
1934
+ while (source[psz]) {
1935
+ var carry = BASE_MAP[source.charCodeAt(psz)];
1936
+ if (carry === 255) {
1937
+ return;
1938
+ }
1939
+ var i2 = 0;
1940
+ for (var it3 = size - 1; (carry !== 0 || i2 < length2) && it3 !== -1; it3--, i2++) {
1941
+ carry += BASE * b256[it3] >>> 0;
1942
+ b256[it3] = carry % 256 >>> 0;
1943
+ carry = carry / 256 >>> 0;
1944
+ }
1945
+ if (carry !== 0) {
1946
+ throw new Error("Non-zero carry");
1947
+ }
1948
+ length2 = i2;
1949
+ psz++;
1950
+ }
1951
+ if (source[psz] === " ") {
1952
+ return;
1953
+ }
1954
+ var it4 = size - length2;
1955
+ while (it4 !== size && b256[it4] === 0) {
1956
+ it4++;
1957
+ }
1958
+ var vch = new Uint8Array(zeroes + (size - it4));
1959
+ var j2 = zeroes;
1960
+ while (it4 !== size) {
1961
+ vch[j2++] = b256[it4++];
1962
+ }
1963
+ return vch;
1964
+ }
1965
+ function decode8(string) {
1966
+ var buffer2 = decodeUnsafe(string);
1967
+ if (buffer2) {
1968
+ return buffer2;
1969
+ }
1970
+ throw new Error(`Non-${name} character`);
1971
+ }
1972
+ return {
1973
+ encode: encode5,
1974
+ decodeUnsafe,
1975
+ decode: decode8
1976
+ };
1977
+ }
1978
+ var src = base;
1979
+ var _brrp__multiformats_scope_baseX = src;
1980
+ var base_x_default = _brrp__multiformats_scope_baseX;
1981
+
1982
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base.js
1983
+ var Encoder = class {
1984
+ name;
1985
+ prefix;
1986
+ baseEncode;
1987
+ constructor(name, prefix, baseEncode) {
1988
+ this.name = name;
1989
+ this.prefix = prefix;
1990
+ this.baseEncode = baseEncode;
1991
+ }
1992
+ encode(bytes) {
1993
+ if (bytes instanceof Uint8Array) {
1994
+ return `${this.prefix}${this.baseEncode(bytes)}`;
1995
+ } else {
1996
+ throw Error("Unknown type, must be binary type");
1997
+ }
1998
+ }
1999
+ };
2000
+ var Decoder = class {
2001
+ name;
2002
+ prefix;
2003
+ baseDecode;
2004
+ prefixCodePoint;
2005
+ constructor(name, prefix, baseDecode) {
2006
+ this.name = name;
2007
+ this.prefix = prefix;
2008
+ const prefixCodePoint = prefix.codePointAt(0);
2009
+ if (prefixCodePoint === void 0) {
2010
+ throw new Error("Invalid prefix character");
2011
+ }
2012
+ this.prefixCodePoint = prefixCodePoint;
2013
+ this.baseDecode = baseDecode;
2014
+ }
2015
+ decode(text) {
2016
+ if (typeof text === "string") {
2017
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
2018
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
2019
+ }
2020
+ return this.baseDecode(text.slice(this.prefix.length));
2021
+ } else {
2022
+ throw Error("Can only multibase decode strings");
2023
+ }
2024
+ }
2025
+ or(decoder) {
2026
+ return or(this, decoder);
2027
+ }
2028
+ };
2029
+ var ComposedDecoder = class {
2030
+ decoders;
2031
+ constructor(decoders) {
2032
+ this.decoders = decoders;
2033
+ }
2034
+ or(decoder) {
2035
+ return or(this, decoder);
2036
+ }
2037
+ decode(input) {
2038
+ const prefix = input[0];
2039
+ const decoder = this.decoders[prefix];
2040
+ if (decoder != null) {
2041
+ return decoder.decode(input);
2042
+ } else {
2043
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
2044
+ }
2045
+ }
2046
+ };
2047
+ function or(left, right) {
2048
+ return new ComposedDecoder({
2049
+ ...left.decoders ?? { [left.prefix]: left },
2050
+ ...right.decoders ?? { [right.prefix]: right }
2051
+ });
2052
+ }
2053
+ var Codec = class {
2054
+ name;
2055
+ prefix;
2056
+ baseEncode;
2057
+ baseDecode;
2058
+ encoder;
2059
+ decoder;
2060
+ constructor(name, prefix, baseEncode, baseDecode) {
2061
+ this.name = name;
2062
+ this.prefix = prefix;
2063
+ this.baseEncode = baseEncode;
2064
+ this.baseDecode = baseDecode;
2065
+ this.encoder = new Encoder(name, prefix, baseEncode);
2066
+ this.decoder = new Decoder(name, prefix, baseDecode);
2067
+ }
2068
+ encode(input) {
2069
+ return this.encoder.encode(input);
2070
+ }
2071
+ decode(input) {
2072
+ return this.decoder.decode(input);
2073
+ }
2074
+ };
2075
+ function from({ name, prefix, encode: encode5, decode: decode8 }) {
2076
+ return new Codec(name, prefix, encode5, decode8);
2077
+ }
2078
+ function baseX({ name, prefix, alphabet }) {
2079
+ const { encode: encode5, decode: decode8 } = base_x_default(alphabet, name);
2080
+ return from({
2081
+ prefix,
2082
+ name,
2083
+ encode: encode5,
2084
+ decode: (text) => coerce(decode8(text))
2085
+ });
2086
+ }
2087
+ function decode3(string, alphabetIdx, bitsPerChar, name) {
2088
+ let end = string.length;
2089
+ while (string[end - 1] === "=") {
2090
+ --end;
2091
+ }
2092
+ const out = new Uint8Array(end * bitsPerChar / 8 | 0);
2093
+ let bits = 0;
2094
+ let buffer2 = 0;
2095
+ let written = 0;
2096
+ for (let i = 0; i < end; ++i) {
2097
+ const value = alphabetIdx[string[i]];
2098
+ if (value === void 0) {
2099
+ throw new SyntaxError(`Non-${name} character`);
2100
+ }
2101
+ buffer2 = buffer2 << bitsPerChar | value;
2102
+ bits += bitsPerChar;
2103
+ if (bits >= 8) {
2104
+ bits -= 8;
2105
+ out[written++] = 255 & buffer2 >> bits;
2106
+ }
2107
+ }
2108
+ if (bits >= bitsPerChar || (255 & buffer2 << 8 - bits) !== 0) {
2109
+ throw new SyntaxError("Unexpected end of data");
2110
+ }
2111
+ return out;
2112
+ }
2113
+ function encode2(data, alphabet, bitsPerChar) {
2114
+ const pad = alphabet[alphabet.length - 1] === "=";
2115
+ const mask = (1 << bitsPerChar) - 1;
2116
+ let out = "";
2117
+ let bits = 0;
2118
+ let buffer2 = 0;
2119
+ for (let i = 0; i < data.length; ++i) {
2120
+ buffer2 = buffer2 << 8 | data[i];
2121
+ bits += 8;
2122
+ while (bits > bitsPerChar) {
2123
+ bits -= bitsPerChar;
2124
+ out += alphabet[mask & buffer2 >> bits];
2125
+ }
2126
+ }
2127
+ if (bits !== 0) {
2128
+ out += alphabet[mask & buffer2 << bitsPerChar - bits];
2129
+ }
2130
+ if (pad) {
2131
+ while ((out.length * bitsPerChar & 7) !== 0) {
2132
+ out += "=";
2133
+ }
2134
+ }
2135
+ return out;
2136
+ }
2137
+ function createAlphabetIdx(alphabet) {
2138
+ const alphabetIdx = {};
2139
+ for (let i = 0; i < alphabet.length; ++i) {
2140
+ alphabetIdx[alphabet[i]] = i;
2141
+ }
2142
+ return alphabetIdx;
2143
+ }
2144
+ function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
2145
+ const alphabetIdx = createAlphabetIdx(alphabet);
2146
+ return from({
2147
+ prefix,
2148
+ name,
2149
+ encode(input) {
2150
+ return encode2(input, alphabet, bitsPerChar);
2151
+ },
2152
+ decode(input) {
2153
+ return decode3(input, alphabetIdx, bitsPerChar, name);
2154
+ }
2155
+ });
2156
+ }
2157
+
2158
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base32.js
2159
+ var base32 = rfc4648({
2160
+ prefix: "b",
2161
+ name: "base32",
2162
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567",
2163
+ bitsPerChar: 5
2164
+ });
2165
+ var base32upper = rfc4648({
2166
+ prefix: "B",
2167
+ name: "base32upper",
2168
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
2169
+ bitsPerChar: 5
2170
+ });
2171
+ var base32pad = rfc4648({
2172
+ prefix: "c",
2173
+ name: "base32pad",
2174
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
2175
+ bitsPerChar: 5
2176
+ });
2177
+ var base32padupper = rfc4648({
2178
+ prefix: "C",
2179
+ name: "base32padupper",
2180
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
2181
+ bitsPerChar: 5
2182
+ });
2183
+ var base32hex = rfc4648({
2184
+ prefix: "v",
2185
+ name: "base32hex",
2186
+ alphabet: "0123456789abcdefghijklmnopqrstuv",
2187
+ bitsPerChar: 5
2188
+ });
2189
+ var base32hexupper = rfc4648({
2190
+ prefix: "V",
2191
+ name: "base32hexupper",
2192
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
2193
+ bitsPerChar: 5
2194
+ });
2195
+ var base32hexpad = rfc4648({
2196
+ prefix: "t",
2197
+ name: "base32hexpad",
2198
+ alphabet: "0123456789abcdefghijklmnopqrstuv=",
2199
+ bitsPerChar: 5
2200
+ });
2201
+ var base32hexpadupper = rfc4648({
2202
+ prefix: "T",
2203
+ name: "base32hexpadupper",
2204
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
2205
+ bitsPerChar: 5
2206
+ });
2207
+ var base32z = rfc4648({
2208
+ prefix: "h",
2209
+ name: "base32z",
2210
+ alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
2211
+ bitsPerChar: 5
2212
+ });
2213
+
2214
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base36.js
2215
+ var base36 = baseX({
2216
+ prefix: "k",
2217
+ name: "base36",
2218
+ alphabet: "0123456789abcdefghijklmnopqrstuvwxyz"
2219
+ });
2220
+ var base36upper = baseX({
2221
+ prefix: "K",
2222
+ name: "base36upper",
2223
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2224
+ });
2225
+
2226
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base58.js
2227
+ var base58btc = baseX({
2228
+ name: "base58btc",
2229
+ prefix: "z",
2230
+ alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
2231
+ });
2232
+ var base58flickr = baseX({
2233
+ name: "base58flickr",
2234
+ prefix: "Z",
2235
+ alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
2236
+ });
2237
+
2238
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/vendor/varint.js
2239
+ var encode_1 = encode3;
2240
+ var MSB = 128;
2241
+ var REST = 127;
2242
+ var MSBALL = ~REST;
2243
+ var INT = Math.pow(2, 31);
2244
+ function encode3(num, out, offset) {
2245
+ out = out || [];
2246
+ offset = offset || 0;
2247
+ var oldOffset = offset;
2248
+ while (num >= INT) {
2249
+ out[offset++] = num & 255 | MSB;
2250
+ num /= 128;
2251
+ }
2252
+ while (num & MSBALL) {
2253
+ out[offset++] = num & 255 | MSB;
2254
+ num >>>= 7;
2255
+ }
2256
+ out[offset] = num | 0;
2257
+ encode3.bytes = offset - oldOffset + 1;
2258
+ return out;
2259
+ }
2260
+ var decode4 = read;
2261
+ var MSB$1 = 128;
2262
+ var REST$1 = 127;
2263
+ function read(buf, offset) {
2264
+ var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
2265
+ do {
2266
+ if (counter >= l) {
2267
+ read.bytes = 0;
2268
+ throw new RangeError("Could not decode varint");
2269
+ }
2270
+ b = buf[counter++];
2271
+ res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);
2272
+ shift += 7;
2273
+ } while (b >= MSB$1);
2274
+ read.bytes = counter - offset;
2275
+ return res;
2276
+ }
2277
+ var N1 = Math.pow(2, 7);
2278
+ var N2 = Math.pow(2, 14);
2279
+ var N3 = Math.pow(2, 21);
2280
+ var N4 = Math.pow(2, 28);
2281
+ var N5 = Math.pow(2, 35);
2282
+ var N6 = Math.pow(2, 42);
2283
+ var N7 = Math.pow(2, 49);
2284
+ var N8 = Math.pow(2, 56);
2285
+ var N9 = Math.pow(2, 63);
2286
+ var length = function(value) {
2287
+ return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10;
2288
+ };
2289
+ var varint = {
2290
+ encode: encode_1,
2291
+ decode: decode4,
2292
+ encodingLength: length
2293
+ };
2294
+ var _brrp_varint = varint;
2295
+ var varint_default = _brrp_varint;
2296
+
2297
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/varint.js
2298
+ function decode5(data, offset = 0) {
2299
+ const code = varint_default.decode(data, offset);
2300
+ return [code, varint_default.decode.bytes];
2301
+ }
2302
+ function encodeTo(int, target, offset = 0) {
2303
+ varint_default.encode(int, target, offset);
2304
+ return target;
2305
+ }
2306
+ function encodingLength(int) {
2307
+ return varint_default.encodingLength(int);
2308
+ }
2309
+
2310
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/digest.js
2311
+ function create(code, digest) {
2312
+ const size = digest.byteLength;
2313
+ const sizeOffset = encodingLength(code);
2314
+ const digestOffset = sizeOffset + encodingLength(size);
2315
+ const bytes = new Uint8Array(digestOffset + size);
2316
+ encodeTo(code, bytes, 0);
2317
+ encodeTo(size, bytes, sizeOffset);
2318
+ bytes.set(digest, digestOffset);
2319
+ return new Digest(code, size, digest, bytes);
2320
+ }
2321
+ function decode6(multihash) {
2322
+ const bytes = coerce(multihash);
2323
+ const [code, sizeOffset] = decode5(bytes);
2324
+ const [size, digestOffset] = decode5(bytes.subarray(sizeOffset));
2325
+ const digest = bytes.subarray(sizeOffset + digestOffset);
2326
+ if (digest.byteLength !== size) {
2327
+ throw new Error("Incorrect length");
2328
+ }
2329
+ return new Digest(code, size, digest, bytes);
2330
+ }
2331
+ function equals2(a, b) {
2332
+ if (a === b) {
2333
+ return true;
2334
+ } else {
2335
+ const data = b;
2336
+ return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes);
2337
+ }
2338
+ }
2339
+ var Digest = class {
2340
+ code;
2341
+ size;
2342
+ digest;
2343
+ bytes;
2344
+ /**
2345
+ * Creates a multihash digest.
2346
+ */
2347
+ constructor(code, size, digest, bytes) {
2348
+ this.code = code;
2349
+ this.size = size;
2350
+ this.digest = digest;
2351
+ this.bytes = bytes;
2352
+ }
2353
+ };
2354
+
2355
+ // ../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/cid.js
2356
+ function format(link, base2) {
2357
+ const { bytes, version } = link;
2358
+ switch (version) {
2359
+ case 0:
2360
+ return toStringV0(bytes, baseCache(link), base2 ?? base58btc.encoder);
2361
+ default:
2362
+ return toStringV1(bytes, baseCache(link), base2 ?? base32.encoder);
2363
+ }
2364
+ }
2365
+ var cache = /* @__PURE__ */ new WeakMap();
2366
+ function baseCache(cid) {
2367
+ const baseCache2 = cache.get(cid);
2368
+ if (baseCache2 == null) {
2369
+ const baseCache3 = /* @__PURE__ */ new Map();
2370
+ cache.set(cid, baseCache3);
2371
+ return baseCache3;
2372
+ }
2373
+ return baseCache2;
2374
+ }
2375
+ var CID2 = class _CID {
2376
+ code;
2377
+ version;
2378
+ multihash;
2379
+ bytes;
2380
+ "/";
2381
+ /**
2382
+ * @param version - Version of the CID
2383
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
2384
+ * @param multihash - (Multi)hash of the of the content.
2385
+ */
2386
+ constructor(version, code, multihash, bytes) {
2387
+ this.code = code;
2388
+ this.version = version;
2389
+ this.multihash = multihash;
2390
+ this.bytes = bytes;
2391
+ this["/"] = bytes;
2392
+ }
2393
+ /**
2394
+ * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
2395
+ * please either use `CID.asCID(cid)` or switch to new signalling mechanism
2396
+ *
2397
+ * @deprecated
2398
+ */
2399
+ get asCID() {
2400
+ return this;
2401
+ }
2402
+ // ArrayBufferView
2403
+ get byteOffset() {
2404
+ return this.bytes.byteOffset;
2405
+ }
2406
+ // ArrayBufferView
2407
+ get byteLength() {
2408
+ return this.bytes.byteLength;
2409
+ }
2410
+ toV0() {
2411
+ switch (this.version) {
2412
+ case 0: {
2413
+ return this;
2414
+ }
2415
+ case 1: {
2416
+ const { code, multihash } = this;
2417
+ if (code !== DAG_PB_CODE) {
2418
+ throw new Error("Cannot convert a non dag-pb CID to CIDv0");
2419
+ }
2420
+ if (multihash.code !== SHA_256_CODE) {
2421
+ throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");
2422
+ }
2423
+ return _CID.createV0(multihash);
2424
+ }
2425
+ default: {
2426
+ throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
2427
+ }
2428
+ }
2429
+ }
2430
+ toV1() {
2431
+ switch (this.version) {
2432
+ case 0: {
2433
+ const { code, digest } = this.multihash;
2434
+ const multihash = create(code, digest);
2435
+ return _CID.createV1(this.code, multihash);
2436
+ }
2437
+ case 1: {
2438
+ return this;
2439
+ }
2440
+ default: {
2441
+ throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
2442
+ }
2443
+ }
2444
+ }
2445
+ equals(other) {
2446
+ return _CID.equals(this, other);
2447
+ }
2448
+ static equals(self, other) {
2449
+ const unknown = other;
2450
+ return unknown != null && self.code === unknown.code && self.version === unknown.version && equals2(self.multihash, unknown.multihash);
2451
+ }
2452
+ toString(base2) {
2453
+ return format(this, base2);
2454
+ }
2455
+ toJSON() {
2456
+ return { "/": format(this) };
2457
+ }
2458
+ link() {
2459
+ return this;
2460
+ }
2461
+ [Symbol.toStringTag] = "CID";
2462
+ // Legacy
2463
+ [Symbol.for("nodejs.util.inspect.custom")]() {
2464
+ return `CID(${this.toString()})`;
2465
+ }
2466
+ /**
2467
+ * Takes any input `value` and returns a `CID` instance if it was
2468
+ * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
2469
+ * it will return value back. If `value` is not instance of this CID
2470
+ * class, but is compatible CID it will return new instance of this
2471
+ * `CID` class. Otherwise returns null.
2472
+ *
2473
+ * This allows two different incompatible versions of CID library to
2474
+ * co-exist and interop as long as binary interface is compatible.
2475
+ */
2476
+ static asCID(input) {
2477
+ if (input == null) {
2478
+ return null;
2479
+ }
2480
+ const value = input;
2481
+ if (value instanceof _CID) {
2482
+ return value;
2483
+ } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) {
2484
+ const { version, code, multihash, bytes } = value;
2485
+ return new _CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
2486
+ } else if (value[cidSymbol] === true) {
2487
+ const { version, multihash, code } = value;
2488
+ const digest = decode6(multihash);
2489
+ return _CID.create(version, code, digest);
2490
+ } else {
2491
+ return null;
2492
+ }
2493
+ }
2494
+ /**
2495
+ * @param version - Version of the CID
2496
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
2497
+ * @param digest - (Multi)hash of the of the content.
2498
+ */
2499
+ static create(version, code, digest) {
2500
+ if (typeof code !== "number") {
2501
+ throw new Error("String codecs are no longer supported");
2502
+ }
2503
+ if (!(digest.bytes instanceof Uint8Array)) {
2504
+ throw new Error("Invalid digest");
2505
+ }
2506
+ switch (version) {
2507
+ case 0: {
2508
+ if (code !== DAG_PB_CODE) {
2509
+ throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
2510
+ } else {
2511
+ return new _CID(version, code, digest, digest.bytes);
2512
+ }
2513
+ }
2514
+ case 1: {
2515
+ const bytes = encodeCID(version, code, digest.bytes);
2516
+ return new _CID(version, code, digest, bytes);
2517
+ }
2518
+ default: {
2519
+ throw new Error("Invalid version");
2520
+ }
2521
+ }
2522
+ }
2523
+ /**
2524
+ * Simplified version of `create` for CIDv0.
2525
+ */
2526
+ static createV0(digest) {
2527
+ return _CID.create(0, DAG_PB_CODE, digest);
2528
+ }
2529
+ /**
2530
+ * Simplified version of `create` for CIDv1.
2531
+ *
2532
+ * @param code - Content encoding format code.
2533
+ * @param digest - Multihash of the content.
2534
+ */
2535
+ static createV1(code, digest) {
2536
+ return _CID.create(1, code, digest);
2537
+ }
2538
+ /**
2539
+ * Decoded a CID from its binary representation. The byte array must contain
2540
+ * only the CID with no additional bytes.
2541
+ *
2542
+ * An error will be thrown if the bytes provided do not contain a valid
2543
+ * binary representation of a CID.
2544
+ */
2545
+ static decode(bytes) {
2546
+ const [cid, remainder] = _CID.decodeFirst(bytes);
2547
+ if (remainder.length !== 0) {
2548
+ throw new Error("Incorrect length");
2549
+ }
2550
+ return cid;
2551
+ }
2552
+ /**
2553
+ * Decoded a CID from its binary representation at the beginning of a byte
2554
+ * array.
2555
+ *
2556
+ * Returns an array with the first element containing the CID and the second
2557
+ * element containing the remainder of the original byte array. The remainder
2558
+ * will be a zero-length byte array if the provided bytes only contained a
2559
+ * binary CID representation.
2560
+ */
2561
+ static decodeFirst(bytes) {
2562
+ const specs = _CID.inspectBytes(bytes);
2563
+ const prefixSize = specs.size - specs.multihashSize;
2564
+ const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
2565
+ if (multihashBytes.byteLength !== specs.multihashSize) {
2566
+ throw new Error("Incorrect length");
2567
+ }
2568
+ const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
2569
+ const digest = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
2570
+ const cid = specs.version === 0 ? _CID.createV0(digest) : _CID.createV1(specs.codec, digest);
2571
+ return [cid, bytes.subarray(specs.size)];
2572
+ }
2573
+ /**
2574
+ * Inspect the initial bytes of a CID to determine its properties.
2575
+ *
2576
+ * Involves decoding up to 4 varints. Typically this will require only 4 to 6
2577
+ * bytes but for larger multicodec code values and larger multihash digest
2578
+ * lengths these varints can be quite large. It is recommended that at least
2579
+ * 10 bytes be made available in the `initialBytes` argument for a complete
2580
+ * inspection.
2581
+ */
2582
+ static inspectBytes(initialBytes) {
2583
+ let offset = 0;
2584
+ const next = () => {
2585
+ const [i, length2] = decode5(initialBytes.subarray(offset));
2586
+ offset += length2;
2587
+ return i;
2588
+ };
2589
+ let version = next();
2590
+ let codec = DAG_PB_CODE;
2591
+ if (version === 18) {
2592
+ version = 0;
2593
+ offset = 0;
2594
+ } else {
2595
+ codec = next();
2596
+ }
2597
+ if (version !== 0 && version !== 1) {
2598
+ throw new RangeError(`Invalid CID version ${version}`);
2599
+ }
2600
+ const prefixSize = offset;
2601
+ const multihashCode = next();
2602
+ const digestSize = next();
2603
+ const size = offset + digestSize;
2604
+ const multihashSize = size - prefixSize;
2605
+ return { version, codec, multihashCode, digestSize, multihashSize, size };
2606
+ }
2607
+ /**
2608
+ * Takes cid in a string representation and creates an instance. If `base`
2609
+ * decoder is not provided will use a default from the configuration. It will
2610
+ * throw an error if encoding of the CID is not compatible with supplied (or
2611
+ * a default decoder).
2612
+ */
2613
+ static parse(source, base2) {
2614
+ const [prefix, bytes] = parseCIDtoBytes(source, base2);
2615
+ const cid = _CID.decode(bytes);
2616
+ if (cid.version === 0 && source[0] !== "Q") {
2617
+ throw Error("Version 0 CID string must not include multibase prefix");
2618
+ }
2619
+ baseCache(cid).set(prefix, source);
2620
+ return cid;
2621
+ }
2622
+ };
2623
+ function parseCIDtoBytes(source, base2) {
2624
+ switch (source[0]) {
2625
+ // CIDv0 is parsed differently
2626
+ case "Q": {
2627
+ const decoder = base2 ?? base58btc;
2628
+ return [
2629
+ base58btc.prefix,
2630
+ decoder.decode(`${base58btc.prefix}${source}`)
2631
+ ];
2632
+ }
2633
+ case base58btc.prefix: {
2634
+ const decoder = base2 ?? base58btc;
2635
+ return [base58btc.prefix, decoder.decode(source)];
2636
+ }
2637
+ case base32.prefix: {
2638
+ const decoder = base2 ?? base32;
2639
+ return [base32.prefix, decoder.decode(source)];
2640
+ }
2641
+ case base36.prefix: {
2642
+ const decoder = base2 ?? base36;
2643
+ return [base36.prefix, decoder.decode(source)];
2644
+ }
2645
+ default: {
2646
+ if (base2 == null) {
2647
+ throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");
2648
+ }
2649
+ return [source[0], base2.decode(source)];
2650
+ }
2651
+ }
2652
+ }
2653
+ function toStringV0(bytes, cache2, base2) {
2654
+ const { prefix } = base2;
2655
+ if (prefix !== base58btc.prefix) {
2656
+ throw Error(`Cannot string encode V0 in ${base2.name} encoding`);
2657
+ }
2658
+ const cid = cache2.get(prefix);
2659
+ if (cid == null) {
2660
+ const cid2 = base2.encode(bytes).slice(1);
2661
+ cache2.set(prefix, cid2);
2662
+ return cid2;
2663
+ } else {
2664
+ return cid;
2665
+ }
2666
+ }
2667
+ function toStringV1(bytes, cache2, base2) {
2668
+ const { prefix } = base2;
2669
+ const cid = cache2.get(prefix);
2670
+ if (cid == null) {
2671
+ const cid2 = base2.encode(bytes);
2672
+ cache2.set(prefix, cid2);
2673
+ return cid2;
2674
+ } else {
2675
+ return cid;
2676
+ }
2677
+ }
2678
+ var DAG_PB_CODE = 112;
2679
+ var SHA_256_CODE = 18;
2680
+ function encodeCID(version, code, multihash) {
2681
+ const codeOffset = encodingLength(version);
2682
+ const hashOffset = codeOffset + encodingLength(code);
2683
+ const bytes = new Uint8Array(hashOffset + multihash.byteLength);
2684
+ encodeTo(version, bytes, 0);
2685
+ encodeTo(code, bytes, codeOffset);
2686
+ bytes.set(multihash, hashOffset);
2687
+ return bytes;
2688
+ }
2689
+ var cidSymbol = Symbol.for("@ipld/js-cid/CID");
2690
+
2691
+ // ../../../node_modules/.pnpm/@ipld+dag-cbor@9.2.5/node_modules/@ipld/dag-cbor/src/index.js
2692
+ var CID_CBOR_TAG = 42;
2693
+ function toByteView(buf) {
2694
+ if (buf instanceof ArrayBuffer) {
2695
+ return new Uint8Array(buf, 0, buf.byteLength);
2696
+ }
2697
+ return buf;
2698
+ }
2699
+ function cidEncoder(obj) {
2700
+ if (obj.asCID !== obj && obj["/"] !== obj.bytes) {
2701
+ return null;
2702
+ }
2703
+ const cid = CID2.asCID(obj);
2704
+ if (!cid) {
2705
+ return null;
2706
+ }
2707
+ const bytes = new Uint8Array(cid.bytes.byteLength + 1);
2708
+ bytes.set(cid.bytes, 1);
2709
+ return [
2710
+ new Token(Type.tag, CID_CBOR_TAG),
2711
+ new Token(Type.bytes, bytes)
2712
+ ];
2713
+ }
2714
+ function undefinedEncoder() {
2715
+ throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded");
2716
+ }
2717
+ function numberEncoder(num) {
2718
+ if (Number.isNaN(num)) {
2719
+ throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");
2720
+ }
2721
+ if (num === Infinity || num === -Infinity) {
2722
+ throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");
2723
+ }
2724
+ return null;
2725
+ }
2726
+ function mapEncoder(map) {
2727
+ for (const key of map.keys()) {
2728
+ if (typeof key !== "string" || key.length === 0) {
2729
+ throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");
2730
+ }
2731
+ }
2732
+ return null;
2733
+ }
2734
+ var _encodeOptions = {
2735
+ float64: true,
2736
+ typeEncoders: {
2737
+ Map: mapEncoder,
2738
+ Object: cidEncoder,
2739
+ undefined: undefinedEncoder,
2740
+ number: numberEncoder
2741
+ }
2742
+ };
2743
+ var encodeOptions = {
2744
+ ..._encodeOptions,
2745
+ typeEncoders: {
2746
+ ..._encodeOptions.typeEncoders
2747
+ }
2748
+ };
2749
+ function cidDecoder(bytes) {
2750
+ if (bytes[0] !== 0) {
2751
+ throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");
2752
+ }
2753
+ return CID2.decode(bytes.subarray(1));
2754
+ }
2755
+ var _decodeOptions = {
2756
+ allowIndefinite: false,
2757
+ coerceUndefinedToNull: true,
2758
+ allowNaN: false,
2759
+ allowInfinity: false,
2760
+ allowBigInt: true,
2761
+ // this will lead to BigInt for ints outside of
2762
+ // safe-integer range, which may surprise users
2763
+ strict: true,
2764
+ useMaps: false,
2765
+ rejectDuplicateMapKeys: true,
2766
+ /** @type {import('cborg').TagDecoder[]} */
2767
+ tags: []
2768
+ };
2769
+ _decodeOptions.tags[CID_CBOR_TAG] = cidDecoder;
2770
+ var decodeOptions = {
2771
+ ..._decodeOptions,
2772
+ tags: _decodeOptions.tags.slice()
2773
+ };
2774
+ var encode4 = (node) => encode(node, _encodeOptions);
2775
+ var decode7 = (data) => decode2(toByteView(data), _decodeOptions);
2776
+
2777
+ // ../../../node_modules/.pnpm/@ipld+car@5.4.2/node_modules/@ipld/car/src/decoder-common.js
2778
+ var import_varint2 = __toESM(require_varint(), 1);
2779
+ var CIDV0_BYTES = {
2780
+ SHA2_256: 18,
2781
+ LENGTH: 32,
2782
+ DAG_PB: 112
2783
+ };
2784
+ var V2_HEADER_LENGTH = (
2785
+ /* characteristics */
2786
+ 16 + 8 + 8 + 8
2787
+ );
2788
+ function decodeVarint(bytes, seeker) {
2789
+ if (!bytes.length) {
2790
+ throw new Error("Unexpected end of data");
2791
+ }
2792
+ const i = import_varint2.default.decode(bytes);
2793
+ seeker.seek(
2794
+ /** @type {number} */
2795
+ import_varint2.default.decode.bytes
2796
+ );
2797
+ return i;
2798
+ }
2799
+ function decodeV2Header(bytes) {
2800
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2801
+ let offset = 0;
2802
+ const header = {
2803
+ version: 2,
2804
+ /** @type {[bigint, bigint]} */
2805
+ characteristics: [
2806
+ dv.getBigUint64(offset, true),
2807
+ dv.getBigUint64(offset += 8, true)
2808
+ ],
2809
+ dataOffset: Number(dv.getBigUint64(offset += 8, true)),
2810
+ dataSize: Number(dv.getBigUint64(offset += 8, true)),
2811
+ indexOffset: Number(dv.getBigUint64(offset += 8, true))
2812
+ };
2813
+ return header;
2814
+ }
2815
+ function getMultihashLength(bytes) {
2816
+ import_varint2.default.decode(bytes);
2817
+ const codeLength = (
2818
+ /** @type {number} */
2819
+ import_varint2.default.decode.bytes
2820
+ );
2821
+ const length2 = import_varint2.default.decode(bytes.subarray(import_varint2.default.decode.bytes));
2822
+ const lengthLength = (
2823
+ /** @type {number} */
2824
+ import_varint2.default.decode.bytes
2825
+ );
2826
+ const mhLength = codeLength + lengthLength + length2;
2827
+ return mhLength;
2828
+ }
2829
+
2830
+ // ../../../node_modules/.pnpm/@ipld+car@5.4.2/node_modules/@ipld/car/src/header-validator.js
2831
+ var Kinds = {
2832
+ Null: (
2833
+ /**
2834
+ * @param obj
2835
+ * @returns {undefined|null}
2836
+ */
2837
+ (obj) => obj === null ? obj : void 0
2838
+ ),
2839
+ Int: (
2840
+ /**
2841
+ * @param obj
2842
+ * @returns {undefined|number}
2843
+ */
2844
+ (obj) => Number.isInteger(obj) ? obj : void 0
2845
+ ),
2846
+ Float: (
2847
+ /**
2848
+ * @param obj
2849
+ * @returns {undefined|number}
2850
+ */
2851
+ (obj) => typeof obj === "number" && Number.isFinite(obj) ? obj : void 0
2852
+ ),
2853
+ String: (
2854
+ /**
2855
+ * @param obj
2856
+ * @returns {undefined|string}
2857
+ */
2858
+ (obj) => typeof obj === "string" ? obj : void 0
2859
+ ),
2860
+ Bool: (
2861
+ /**
2862
+ * @param obj
2863
+ * @returns {undefined|boolean}
2864
+ */
2865
+ (obj) => typeof obj === "boolean" ? obj : void 0
2866
+ ),
2867
+ Bytes: (
2868
+ /**
2869
+ * @param obj
2870
+ * @returns {undefined|Uint8Array}
2871
+ */
2872
+ (obj) => obj instanceof Uint8Array ? obj : void 0
2873
+ ),
2874
+ Link: (
2875
+ /**
2876
+ * @param obj
2877
+ * @returns {undefined|object}
2878
+ */
2879
+ (obj) => obj !== null && typeof obj === "object" && obj.asCID === obj ? obj : void 0
2880
+ ),
2881
+ List: (
2882
+ /**
2883
+ * @param obj
2884
+ * @returns {undefined|Array<any>}
2885
+ */
2886
+ (obj) => Array.isArray(obj) ? obj : void 0
2887
+ ),
2888
+ Map: (
2889
+ /**
2890
+ * @param obj
2891
+ * @returns {undefined|object}
2892
+ */
2893
+ (obj) => obj !== null && typeof obj === "object" && obj.asCID !== obj && !Array.isArray(obj) && !(obj instanceof Uint8Array) ? obj : void 0
2894
+ )
2895
+ };
2896
+ var Types = {
2897
+ "CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)": Kinds.Link,
2898
+ "CarV1HeaderOrV2Pragma > roots (anon)": (
2899
+ /**
2900
+ * @param obj
2901
+ * @returns {undefined|any}
2902
+ */
2903
+ (obj) => {
2904
+ if (Kinds.List(obj) === void 0) {
2905
+ return void 0;
2906
+ }
2907
+ for (let i = 0; i < obj.length; i++) {
2908
+ let v = obj[i];
2909
+ v = Types["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v);
2910
+ if (v === void 0) {
2911
+ return void 0;
2912
+ }
2913
+ if (v !== obj[i]) {
2914
+ const ret = obj.slice(0, i);
2915
+ for (let j = i; j < obj.length; j++) {
2916
+ let v2 = obj[j];
2917
+ v2 = Types["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v2);
2918
+ if (v2 === void 0) {
2919
+ return void 0;
2920
+ }
2921
+ ret.push(v2);
2922
+ }
2923
+ return ret;
2924
+ }
2925
+ }
2926
+ return obj;
2927
+ }
2928
+ ),
2929
+ Int: Kinds.Int,
2930
+ CarV1HeaderOrV2Pragma: (
2931
+ /**
2932
+ * @param obj
2933
+ * @returns {undefined|any}
2934
+ */
2935
+ (obj) => {
2936
+ if (Kinds.Map(obj) === void 0) {
2937
+ return void 0;
2938
+ }
2939
+ const entries = Object.entries(obj);
2940
+ let ret = obj;
2941
+ let requiredCount = 1;
2942
+ for (let i = 0; i < entries.length; i++) {
2943
+ const [key, value] = entries[i];
2944
+ switch (key) {
2945
+ case "roots":
2946
+ {
2947
+ const v = Types["CarV1HeaderOrV2Pragma > roots (anon)"](obj[key]);
2948
+ if (v === void 0) {
2949
+ return void 0;
2950
+ }
2951
+ if (v !== value || ret !== obj) {
2952
+ if (ret === obj) {
2953
+ ret = {};
2954
+ for (let j = 0; j < i; j++) {
2955
+ ret[entries[j][0]] = entries[j][1];
2956
+ }
2957
+ }
2958
+ ret.roots = v;
2959
+ }
2960
+ }
2961
+ break;
2962
+ case "version":
2963
+ {
2964
+ requiredCount--;
2965
+ const v = Types.Int(obj[key]);
2966
+ if (v === void 0) {
2967
+ return void 0;
2968
+ }
2969
+ if (v !== value || ret !== obj) {
2970
+ if (ret === obj) {
2971
+ ret = {};
2972
+ for (let j = 0; j < i; j++) {
2973
+ ret[entries[j][0]] = entries[j][1];
2974
+ }
2975
+ }
2976
+ ret.version = v;
2977
+ }
2978
+ }
2979
+ break;
2980
+ default:
2981
+ return void 0;
2982
+ }
2983
+ }
2984
+ if (requiredCount > 0) {
2985
+ return void 0;
2986
+ }
2987
+ return ret;
2988
+ }
2989
+ )
2990
+ };
2991
+ var Reprs = {
2992
+ "CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)": Kinds.Link,
2993
+ "CarV1HeaderOrV2Pragma > roots (anon)": (
2994
+ /**
2995
+ * @param obj
2996
+ * @returns {undefined|any}
2997
+ */
2998
+ (obj) => {
2999
+ if (Kinds.List(obj) === void 0) {
3000
+ return void 0;
3001
+ }
3002
+ for (let i = 0; i < obj.length; i++) {
3003
+ let v = obj[i];
3004
+ v = Reprs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v);
3005
+ if (v === void 0) {
3006
+ return void 0;
3007
+ }
3008
+ if (v !== obj[i]) {
3009
+ const ret = obj.slice(0, i);
3010
+ for (let j = i; j < obj.length; j++) {
3011
+ let v2 = obj[j];
3012
+ v2 = Reprs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v2);
3013
+ if (v2 === void 0) {
3014
+ return void 0;
3015
+ }
3016
+ ret.push(v2);
3017
+ }
3018
+ return ret;
3019
+ }
3020
+ }
3021
+ return obj;
3022
+ }
3023
+ ),
3024
+ Int: Kinds.Int,
3025
+ CarV1HeaderOrV2Pragma: (
3026
+ /**
3027
+ * @param obj
3028
+ * @returns {undefined|any}
3029
+ */
3030
+ (obj) => {
3031
+ if (Kinds.Map(obj) === void 0) {
3032
+ return void 0;
3033
+ }
3034
+ const entries = Object.entries(obj);
3035
+ let ret = obj;
3036
+ let requiredCount = 1;
3037
+ for (let i = 0; i < entries.length; i++) {
3038
+ const [key, value] = entries[i];
3039
+ switch (key) {
3040
+ case "roots":
3041
+ {
3042
+ const v = Reprs["CarV1HeaderOrV2Pragma > roots (anon)"](value);
3043
+ if (v === void 0) {
3044
+ return void 0;
3045
+ }
3046
+ if (v !== value || ret !== obj) {
3047
+ if (ret === obj) {
3048
+ ret = {};
3049
+ for (let j = 0; j < i; j++) {
3050
+ ret[entries[j][0]] = entries[j][1];
3051
+ }
3052
+ }
3053
+ ret.roots = v;
3054
+ }
3055
+ }
3056
+ break;
3057
+ case "version":
3058
+ {
3059
+ requiredCount--;
3060
+ const v = Reprs.Int(value);
3061
+ if (v === void 0) {
3062
+ return void 0;
3063
+ }
3064
+ if (v !== value || ret !== obj) {
3065
+ if (ret === obj) {
3066
+ ret = {};
3067
+ for (let j = 0; j < i; j++) {
3068
+ ret[entries[j][0]] = entries[j][1];
3069
+ }
3070
+ }
3071
+ ret.version = v;
3072
+ }
3073
+ }
3074
+ break;
3075
+ default:
3076
+ return void 0;
3077
+ }
3078
+ }
3079
+ if (requiredCount > 0) {
3080
+ return void 0;
3081
+ }
3082
+ return ret;
3083
+ }
3084
+ )
3085
+ };
3086
+ var CarV1HeaderOrV2Pragma = {
3087
+ toTyped: Types.CarV1HeaderOrV2Pragma,
3088
+ toRepresentation: Reprs.CarV1HeaderOrV2Pragma
3089
+ };
3090
+
3091
+ // ../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/length.js
3092
+ var cborEncoders2 = makeCborEncoders();
3093
+
3094
+ // ../../../node_modules/.pnpm/@ipld+car@5.4.2/node_modules/@ipld/car/src/buffer-writer.js
3095
+ var import_varint3 = __toESM(require_varint(), 1);
3096
+ var headerPreludeTokens = [
3097
+ new Token(Type.map, 2),
3098
+ new Token(Type.string, "version"),
3099
+ new Token(Type.uint, 1),
3100
+ new Token(Type.string, "roots")
3101
+ ];
3102
+ var CID_TAG = new Token(Type.tag, 42);
3103
+
3104
+ // ../../../node_modules/.pnpm/@ipld+car@5.4.2/node_modules/@ipld/car/src/decoder.js
3105
+ async function readHeader(reader, strictVersion) {
3106
+ const length2 = decodeVarint(await reader.upTo(8), reader);
3107
+ if (length2 === 0) {
3108
+ throw new Error("Invalid CAR header (zero length)");
3109
+ }
3110
+ const header = await reader.exactly(length2, true);
3111
+ const block = decode7(header);
3112
+ if (CarV1HeaderOrV2Pragma.toTyped(block) === void 0) {
3113
+ throw new Error("Invalid CAR header format");
3114
+ }
3115
+ if (block.version !== 1 && block.version !== 2 || strictVersion !== void 0 && block.version !== strictVersion) {
3116
+ throw new Error(`Invalid CAR version: ${block.version}${strictVersion !== void 0 ? ` (expected ${strictVersion})` : ""}`);
3117
+ }
3118
+ if (block.version === 1) {
3119
+ if (!Array.isArray(block.roots)) {
3120
+ throw new Error("Invalid CAR header format");
3121
+ }
3122
+ return block;
3123
+ }
3124
+ if (block.roots !== void 0) {
3125
+ throw new Error("Invalid CAR header format");
3126
+ }
3127
+ const v2Header = decodeV2Header(await reader.exactly(V2_HEADER_LENGTH, true));
3128
+ reader.seek(v2Header.dataOffset - reader.pos);
3129
+ const v1Header = await readHeader(reader, 1);
3130
+ return Object.assign(v1Header, v2Header);
3131
+ }
3132
+ async function readCid(reader) {
3133
+ const first = await reader.exactly(2, false);
3134
+ if (first[0] === CIDV0_BYTES.SHA2_256 && first[1] === CIDV0_BYTES.LENGTH) {
3135
+ const bytes2 = await reader.exactly(34, true);
3136
+ const multihash2 = decode6(bytes2);
3137
+ return CID2.create(0, CIDV0_BYTES.DAG_PB, multihash2);
3138
+ }
3139
+ const version = decodeVarint(await reader.upTo(8), reader);
3140
+ if (version !== 1) {
3141
+ throw new Error(`Unexpected CID version (${version})`);
3142
+ }
3143
+ const codec = decodeVarint(await reader.upTo(8), reader);
3144
+ const bytes = await reader.exactly(getMultihashLength(await reader.upTo(8)), true);
3145
+ const multihash = decode6(bytes);
3146
+ return CID2.create(version, codec, multihash);
3147
+ }
3148
+ async function readBlockHead(reader) {
3149
+ const start = reader.pos;
3150
+ let length2 = decodeVarint(await reader.upTo(8), reader);
3151
+ if (length2 === 0) {
3152
+ throw new Error("Invalid CAR section (zero length)");
3153
+ }
3154
+ length2 += reader.pos - start;
3155
+ const cid = await readCid(reader);
3156
+ const blockLength = length2 - Number(reader.pos - start);
3157
+ return { cid, length: length2, blockLength };
3158
+ }
3159
+ async function readBlock(reader) {
3160
+ const { cid, blockLength } = await readBlockHead(reader);
3161
+ const bytes = await reader.exactly(blockLength, true);
3162
+ return { bytes, cid };
3163
+ }
3164
+ async function readBlockIndex(reader) {
3165
+ const offset = reader.pos;
3166
+ const { cid, length: length2, blockLength } = await readBlockHead(reader);
3167
+ const index = { cid, length: length2, blockLength, offset, blockOffset: reader.pos };
3168
+ reader.seek(index.blockLength);
3169
+ return index;
3170
+ }
3171
+ function createDecoder(reader) {
3172
+ const headerPromise = (async () => {
3173
+ const header = await readHeader(reader);
3174
+ if (header.version === 2) {
3175
+ const v1length = reader.pos - header.dataOffset;
3176
+ reader = limitReader(reader, header.dataSize - v1length);
3177
+ }
3178
+ return header;
3179
+ })();
3180
+ return {
3181
+ header: () => headerPromise,
3182
+ async *blocks() {
3183
+ await headerPromise;
3184
+ while ((await reader.upTo(8)).length > 0) {
3185
+ yield await readBlock(reader);
3186
+ }
3187
+ },
3188
+ async *blocksIndex() {
3189
+ await headerPromise;
3190
+ while ((await reader.upTo(8)).length > 0) {
3191
+ yield await readBlockIndex(reader);
3192
+ }
3193
+ }
3194
+ };
3195
+ }
3196
+ function bytesReader(bytes) {
3197
+ let pos = 0;
3198
+ return {
3199
+ async upTo(length2) {
3200
+ const out = bytes.subarray(pos, pos + Math.min(length2, bytes.length - pos));
3201
+ return out;
3202
+ },
3203
+ async exactly(length2, seek = false) {
3204
+ if (length2 > bytes.length - pos) {
3205
+ throw new Error("Unexpected end of data");
3206
+ }
3207
+ const out = bytes.subarray(pos, pos + length2);
3208
+ if (seek) {
3209
+ pos += length2;
3210
+ }
3211
+ return out;
3212
+ },
3213
+ seek(length2) {
3214
+ pos += length2;
3215
+ },
3216
+ get pos() {
3217
+ return pos;
3218
+ }
3219
+ };
3220
+ }
3221
+ function chunkReader(readChunk) {
3222
+ let pos = 0;
3223
+ let have = 0;
3224
+ let offset = 0;
3225
+ let currentChunk = new Uint8Array(0);
3226
+ const read2 = async (length2) => {
3227
+ have = currentChunk.length - offset;
3228
+ const bufa = (
3229
+ /** @type {Uint8Array<ArrayBufferLike>[]} */
3230
+ [currentChunk.subarray(offset)]
3231
+ );
3232
+ while (have < length2) {
3233
+ const chunk = await readChunk();
3234
+ if (chunk == null) {
3235
+ break;
3236
+ }
3237
+ if (have < 0) {
3238
+ if (chunk.length > have) {
3239
+ bufa.push(chunk.subarray(-have));
3240
+ }
3241
+ } else {
3242
+ bufa.push(chunk);
3243
+ }
3244
+ have += chunk.length;
3245
+ }
3246
+ currentChunk = new Uint8Array(bufa.reduce((p, c) => p + c.length, 0));
3247
+ let off = 0;
3248
+ for (const b of bufa) {
3249
+ currentChunk.set(b, off);
3250
+ off += b.length;
3251
+ }
3252
+ offset = 0;
3253
+ };
3254
+ return {
3255
+ async upTo(length2) {
3256
+ if (currentChunk.length - offset < length2) {
3257
+ await read2(length2);
3258
+ }
3259
+ return currentChunk.subarray(offset, offset + Math.min(currentChunk.length - offset, length2));
3260
+ },
3261
+ async exactly(length2, seek = false) {
3262
+ if (currentChunk.length - offset < length2) {
3263
+ await read2(length2);
3264
+ }
3265
+ if (currentChunk.length - offset < length2) {
3266
+ throw new Error("Unexpected end of data");
3267
+ }
3268
+ const out = currentChunk.subarray(offset, offset + length2);
3269
+ if (seek) {
3270
+ pos += length2;
3271
+ offset += length2;
3272
+ }
3273
+ return out;
3274
+ },
3275
+ seek(length2) {
3276
+ pos += length2;
3277
+ offset += length2;
3278
+ },
3279
+ get pos() {
3280
+ return pos;
3281
+ }
3282
+ };
3283
+ }
3284
+ function asyncIterableReader(asyncIterable) {
3285
+ const iterator = asyncIterable[Symbol.asyncIterator]();
3286
+ async function readChunk() {
3287
+ const next = await iterator.next();
3288
+ if (next.done) {
3289
+ return null;
3290
+ }
3291
+ return next.value;
3292
+ }
3293
+ return chunkReader(readChunk);
3294
+ }
3295
+ function limitReader(reader, byteLimit) {
3296
+ let bytesRead = 0;
3297
+ return {
3298
+ async upTo(length2) {
3299
+ let bytes = await reader.upTo(length2);
3300
+ if (bytes.length + bytesRead > byteLimit) {
3301
+ bytes = bytes.subarray(0, byteLimit - bytesRead);
3302
+ }
3303
+ return bytes;
3304
+ },
3305
+ async exactly(length2, seek = false) {
3306
+ const bytes = await reader.exactly(length2, seek);
3307
+ if (bytes.length + bytesRead > byteLimit) {
3308
+ throw new Error("Unexpected end of data");
3309
+ }
3310
+ if (seek) {
3311
+ bytesRead += length2;
3312
+ }
3313
+ return bytes;
3314
+ },
3315
+ seek(length2) {
3316
+ bytesRead += length2;
3317
+ reader.seek(length2);
3318
+ },
3319
+ get pos() {
3320
+ return reader.pos;
3321
+ }
3322
+ };
3323
+ }
3324
+
3325
+ // ../../../node_modules/.pnpm/@ipld+car@5.4.2/node_modules/@ipld/car/src/reader-browser.js
3326
+ var CarReader = class {
3327
+ /**
3328
+ * @constructs CarReader
3329
+ * @param {CarHeader|CarV2Header} header
3330
+ * @param {Block[]} blocks
3331
+ */
3332
+ constructor(header, blocks) {
3333
+ this._header = header;
3334
+ this._blocks = blocks;
3335
+ this._keys = blocks.map((b) => b.cid.toString());
3336
+ }
3337
+ /**
3338
+ * @property
3339
+ * @memberof CarReader
3340
+ * @instance
3341
+ */
3342
+ get version() {
3343
+ return this._header.version;
3344
+ }
3345
+ /**
3346
+ * Get the list of roots defined by the CAR referenced by this reader. May be
3347
+ * zero or more `CID`s.
3348
+ *
3349
+ * @function
3350
+ * @memberof CarReader
3351
+ * @instance
3352
+ * @async
3353
+ * @returns {Promise<CID[]>}
3354
+ */
3355
+ async getRoots() {
3356
+ return this._header.roots;
3357
+ }
3358
+ /**
3359
+ * Check whether a given `CID` exists within the CAR referenced by this
3360
+ * reader.
3361
+ *
3362
+ * @function
3363
+ * @memberof CarReader
3364
+ * @instance
3365
+ * @async
3366
+ * @param {CID} key
3367
+ * @returns {Promise<boolean>}
3368
+ */
3369
+ async has(key) {
3370
+ return this._keys.indexOf(key.toString()) > -1;
3371
+ }
3372
+ /**
3373
+ * Fetch a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) from the CAR
3374
+ * referenced by this reader matching the provided `CID`. In the case where
3375
+ * the provided `CID` doesn't exist within the CAR, `undefined` will be
3376
+ * returned.
3377
+ *
3378
+ * @function
3379
+ * @memberof CarReader
3380
+ * @instance
3381
+ * @async
3382
+ * @param {CID} key
3383
+ * @returns {Promise<Block | undefined>}
3384
+ */
3385
+ async get(key) {
3386
+ const index = this._keys.indexOf(key.toString());
3387
+ return index > -1 ? this._blocks[index] : void 0;
3388
+ }
3389
+ /**
3390
+ * Returns a `BlockIterator` (`AsyncIterable<Block>`) that iterates over all
3391
+ * of the `Block`s (`{ cid:CID, bytes:Uint8Array }` pairs) contained within
3392
+ * the CAR referenced by this reader.
3393
+ *
3394
+ * @function
3395
+ * @memberof CarReader
3396
+ * @instance
3397
+ * @async
3398
+ * @generator
3399
+ * @returns {AsyncGenerator<Block>}
3400
+ */
3401
+ async *blocks() {
3402
+ for (const block of this._blocks) {
3403
+ yield block;
3404
+ }
3405
+ }
3406
+ /**
3407
+ * Returns a `CIDIterator` (`AsyncIterable<CID>`) that iterates over all of
3408
+ * the `CID`s contained within the CAR referenced by this reader.
3409
+ *
3410
+ * @function
3411
+ * @memberof CarReader
3412
+ * @instance
3413
+ * @async
3414
+ * @generator
3415
+ * @returns {AsyncGenerator<CID>}
3416
+ */
3417
+ async *cids() {
3418
+ for (const block of this._blocks) {
3419
+ yield block.cid;
3420
+ }
3421
+ }
3422
+ /**
3423
+ * Instantiate a {@link CarReader} from a `Uint8Array` blob. This performs a
3424
+ * decode fully in memory and maintains the decoded state in memory for full
3425
+ * access to the data via the `CarReader` API.
3426
+ *
3427
+ * @async
3428
+ * @static
3429
+ * @memberof CarReader
3430
+ * @param {Uint8Array} bytes
3431
+ * @returns {Promise<CarReader>}
3432
+ */
3433
+ static async fromBytes(bytes) {
3434
+ if (!(bytes instanceof Uint8Array)) {
3435
+ throw new TypeError("fromBytes() requires a Uint8Array");
3436
+ }
3437
+ return decodeReaderComplete(bytesReader(bytes));
3438
+ }
3439
+ /**
3440
+ * Instantiate a {@link CarReader} from a `AsyncIterable<Uint8Array>`, such as
3441
+ * a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).
3442
+ * This performs a decode fully in memory and maintains the decoded state in
3443
+ * memory for full access to the data via the `CarReader` API.
3444
+ *
3445
+ * Care should be taken for large archives; this API may not be appropriate
3446
+ * where memory is a concern or the archive is potentially larger than the
3447
+ * amount of memory that the runtime can handle.
3448
+ *
3449
+ * @async
3450
+ * @static
3451
+ * @memberof CarReader
3452
+ * @param {AsyncIterable<Uint8Array>} asyncIterable
3453
+ * @returns {Promise<CarReader>}
3454
+ */
3455
+ static async fromIterable(asyncIterable) {
3456
+ if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === "function")) {
3457
+ throw new TypeError("fromIterable() requires an async iterable");
3458
+ }
3459
+ return decodeReaderComplete(asyncIterableReader(asyncIterable));
3460
+ }
3461
+ };
3462
+ async function decodeReaderComplete(reader) {
3463
+ const decoder = createDecoder(reader);
3464
+ const header = await decoder.header();
3465
+ const blocks = [];
3466
+ for await (const block of decoder.blocks()) {
3467
+ blocks.push(block);
3468
+ }
3469
+ return new CarReader(header, blocks);
3470
+ }
3471
+
3472
+ // ../../../node_modules/.pnpm/@ipld+car@5.4.2/node_modules/@ipld/car/src/encoder.js
3473
+ var import_varint4 = __toESM(require_varint(), 1);
3474
+ var CAR_V1_VERSION = 1;
3475
+ function createHeader(roots) {
3476
+ const headerBytes = encode4({ version: CAR_V1_VERSION, roots });
3477
+ const varintBytes = import_varint4.default.encode(headerBytes.length);
3478
+ const header = new Uint8Array(varintBytes.length + headerBytes.length);
3479
+ header.set(varintBytes, 0);
3480
+ header.set(headerBytes, varintBytes.length);
3481
+ return header;
3482
+ }
3483
+ function createEncoder(writer) {
3484
+ return {
3485
+ /**
3486
+ * @param {CID[]} roots
3487
+ * @returns {Promise<void>}
3488
+ */
3489
+ async setRoots(roots) {
3490
+ const bytes = createHeader(roots);
3491
+ await writer.write(bytes);
3492
+ },
3493
+ /**
3494
+ * @param {Block} block
3495
+ * @returns {Promise<void>}
3496
+ */
3497
+ async writeBlock(block) {
3498
+ const { cid, bytes } = block;
3499
+ await writer.write(new Uint8Array(import_varint4.default.encode(cid.bytes.length + bytes.length)));
3500
+ await writer.write(cid.bytes);
3501
+ if (bytes.length) {
3502
+ await writer.write(bytes);
3503
+ }
3504
+ },
3505
+ /**
3506
+ * @returns {Promise<void>}
3507
+ */
3508
+ async close() {
3509
+ await writer.end();
3510
+ },
3511
+ /**
3512
+ * @returns {number}
3513
+ */
3514
+ version() {
3515
+ return CAR_V1_VERSION;
3516
+ }
3517
+ };
3518
+ }
3519
+
3520
+ // ../../../node_modules/.pnpm/@ipld+car@5.4.2/node_modules/@ipld/car/src/iterator-channel.js
3521
+ function noop() {
3522
+ }
3523
+ function create2() {
3524
+ const chunkQueue = [];
3525
+ let drainer = null;
3526
+ let drainerResolver = noop;
3527
+ let ended = false;
3528
+ let outWait = null;
3529
+ let outWaitResolver = noop;
3530
+ const makeDrainer = () => {
3531
+ if (!drainer) {
3532
+ drainer = new Promise((resolve) => {
3533
+ drainerResolver = () => {
3534
+ drainer = null;
3535
+ drainerResolver = noop;
3536
+ resolve();
3537
+ };
3538
+ });
3539
+ }
3540
+ return drainer;
3541
+ };
3542
+ const writer = {
3543
+ /**
3544
+ * @param {T} chunk
3545
+ * @returns {Promise<void>}
3546
+ */
3547
+ write(chunk) {
3548
+ chunkQueue.push(chunk);
3549
+ const drainer2 = makeDrainer();
3550
+ outWaitResolver();
3551
+ return drainer2;
3552
+ },
3553
+ async end() {
3554
+ ended = true;
3555
+ const drainer2 = makeDrainer();
3556
+ outWaitResolver();
3557
+ await drainer2;
3558
+ }
3559
+ };
3560
+ const iterator = {
3561
+ /** @returns {Promise<IteratorResult<T>>} */
3562
+ async next() {
3563
+ const chunk = chunkQueue.shift();
3564
+ if (chunk) {
3565
+ if (chunkQueue.length === 0) {
3566
+ drainerResolver();
3567
+ }
3568
+ return { done: false, value: chunk };
3569
+ }
3570
+ if (ended) {
3571
+ drainerResolver();
3572
+ return { done: true, value: void 0 };
3573
+ }
3574
+ if (!outWait) {
3575
+ outWait = new Promise((resolve) => {
3576
+ outWaitResolver = () => {
3577
+ outWait = null;
3578
+ outWaitResolver = noop;
3579
+ return resolve(iterator.next());
3580
+ };
3581
+ });
3582
+ }
3583
+ return outWait;
3584
+ }
3585
+ };
3586
+ return { writer, iterator };
3587
+ }
3588
+
3589
+ // ../../../node_modules/.pnpm/@ipld+car@5.4.2/node_modules/@ipld/car/src/writer-browser.js
3590
+ var CarWriter = class _CarWriter {
3591
+ /**
3592
+ * @param {CID[]} roots
3593
+ * @param {CarEncoder} encoder
3594
+ */
3595
+ constructor(roots, encoder) {
3596
+ this._encoder = encoder;
3597
+ this._mutex = encoder.setRoots(roots);
3598
+ this._ended = false;
3599
+ }
3600
+ /**
3601
+ * Write a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) to the archive.
3602
+ *
3603
+ * @function
3604
+ * @memberof CarWriter
3605
+ * @instance
3606
+ * @async
3607
+ * @param {Block} block - A `{ cid:CID, bytes:Uint8Array }` pair.
3608
+ * @returns {Promise<void>} The returned promise will only resolve once the
3609
+ * bytes this block generates are written to the `out` iterable.
3610
+ */
3611
+ async put(block) {
3612
+ if (!(block.bytes instanceof Uint8Array) || !block.cid) {
3613
+ throw new TypeError("Can only write {cid, bytes} objects");
3614
+ }
3615
+ if (this._ended) {
3616
+ throw new Error("Already closed");
3617
+ }
3618
+ const cid = CID2.asCID(block.cid);
3619
+ if (!cid) {
3620
+ throw new TypeError("Can only write {cid, bytes} objects");
3621
+ }
3622
+ this._mutex = this._mutex.then(() => this._encoder.writeBlock({ cid, bytes: block.bytes }));
3623
+ return this._mutex;
3624
+ }
3625
+ /**
3626
+ * Finalise the CAR archive and signal that the `out` iterable should end once
3627
+ * any remaining bytes are written.
3628
+ *
3629
+ * @function
3630
+ * @memberof CarWriter
3631
+ * @instance
3632
+ * @async
3633
+ * @returns {Promise<void>}
3634
+ */
3635
+ async close() {
3636
+ if (this._ended) {
3637
+ throw new Error("Already closed");
3638
+ }
3639
+ await this._mutex;
3640
+ this._ended = true;
3641
+ return this._encoder.close();
3642
+ }
3643
+ /**
3644
+ * Returns the version number of the CAR file being written
3645
+ *
3646
+ * @returns {number}
3647
+ */
3648
+ version() {
3649
+ return this._encoder.version();
3650
+ }
3651
+ /**
3652
+ * Create a new CAR writer "channel" which consists of a
3653
+ * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair.
3654
+ *
3655
+ * @async
3656
+ * @static
3657
+ * @memberof CarWriter
3658
+ * @param {CID[] | CID | void} roots
3659
+ * @returns {WriterChannel} The channel takes the form of
3660
+ * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }`.
3661
+ */
3662
+ static create(roots) {
3663
+ roots = toRoots(roots);
3664
+ const { encoder, iterator } = encodeWriter();
3665
+ const writer = new _CarWriter(roots, encoder);
3666
+ const out = new CarWriterOut(iterator);
3667
+ return { writer, out };
3668
+ }
3669
+ /**
3670
+ * Create a new CAR appender "channel" which consists of a
3671
+ * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair.
3672
+ * This appender does not consider roots and does not produce a CAR header.
3673
+ * It is designed to append blocks to an _existing_ CAR archive. It is
3674
+ * expected that `out` will be concatenated onto the end of an existing
3675
+ * archive that already has a properly formatted header.
3676
+ *
3677
+ * @async
3678
+ * @static
3679
+ * @memberof CarWriter
3680
+ * @returns {WriterChannel} The channel takes the form of
3681
+ * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }`.
3682
+ */
3683
+ static createAppender() {
3684
+ const { encoder, iterator } = encodeWriter();
3685
+ encoder.setRoots = () => Promise.resolve();
3686
+ const writer = new _CarWriter([], encoder);
3687
+ const out = new CarWriterOut(iterator);
3688
+ return { writer, out };
3689
+ }
3690
+ /**
3691
+ * Update the list of roots in the header of an existing CAR as represented
3692
+ * in a Uint8Array.
3693
+ *
3694
+ * This operation is an _overwrite_, the total length of the CAR will not be
3695
+ * modified. A rejection will occur if the new header will not be the same
3696
+ * length as the existing header, in which case the CAR will not be modified.
3697
+ * It is the responsibility of the user to ensure that the roots being
3698
+ * replaced encode as the same length as the new roots.
3699
+ *
3700
+ * The byte array passed in an argument will be modified and also returned
3701
+ * upon successful modification.
3702
+ *
3703
+ * @async
3704
+ * @static
3705
+ * @memberof CarWriter
3706
+ * @param {Uint8Array} bytes
3707
+ * @param {CID[]} roots - A new list of roots to replace the existing list in
3708
+ * the CAR header. The new header must take up the same number of bytes as the
3709
+ * existing header, so the roots should collectively be the same byte length
3710
+ * as the existing roots.
3711
+ * @returns {Promise<Uint8Array>}
3712
+ */
3713
+ static async updateRootsInBytes(bytes, roots) {
3714
+ const reader = bytesReader(bytes);
3715
+ await readHeader(reader);
3716
+ const newHeader = createHeader(roots);
3717
+ if (Number(reader.pos) !== newHeader.length) {
3718
+ throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${reader.pos} bytes, new header is ${newHeader.length} bytes)`);
3719
+ }
3720
+ bytes.set(newHeader, 0);
3721
+ return bytes;
3722
+ }
3723
+ };
3724
+ var CarWriterOut = class {
3725
+ /**
3726
+ * @param {AsyncIterator<Uint8Array>} iterator
3727
+ */
3728
+ constructor(iterator) {
3729
+ this._iterator = iterator;
3730
+ }
3731
+ [Symbol.asyncIterator]() {
3732
+ if (this._iterating) {
3733
+ throw new Error("Multiple iterator not supported");
3734
+ }
3735
+ this._iterating = true;
3736
+ return this._iterator;
3737
+ }
3738
+ };
3739
+ function encodeWriter() {
3740
+ const iw = create2();
3741
+ const { writer, iterator } = iw;
3742
+ const encoder = createEncoder(writer);
3743
+ return { encoder, iterator };
3744
+ }
3745
+ function toRoots(roots) {
3746
+ if (roots === void 0) {
3747
+ return [];
3748
+ }
3749
+ if (!Array.isArray(roots)) {
3750
+ const cid = CID2.asCID(roots);
3751
+ if (!cid) {
3752
+ throw new TypeError("roots must be a single CID or an array of CIDs");
3753
+ }
3754
+ return [cid];
3755
+ }
3756
+ const _roots = [];
3757
+ for (const root of roots) {
3758
+ const _root = CID2.asCID(root);
3759
+ if (!_root) {
3760
+ throw new TypeError("roots must be a single CID or an array of CIDs");
3761
+ }
3762
+ _roots.push(_root);
3763
+ }
3764
+ return _roots;
3765
+ }
3766
+
3767
+ // src/ipfs/car.ts
3768
+ var { WARN, LOG, DEBUG, VERBOSE, ERROR } = g.setup(g.INFO);
3769
+ async function decodePubFromCar(car) {
3770
+ const decoded = await getBlocksOfCar(car);
3771
+ return await decodePubFromBlocks(decoded);
3772
+ }
3773
+ async function decodePubFromBlocks({ rootCID, blockStore }, _recursionTrace = [], stopAtCID) {
3774
+ if (!rootCID || !blockStore) {
3775
+ throw ERROR("Empty roots/blocks", { rootCID, blockStore });
3776
+ }
3777
+ let allApplogs = [];
3778
+ let firstInfo = null;
3779
+ let currentCID = rootCID;
3780
+ const visited = /* @__PURE__ */ new Set();
3781
+ let applogsCID = null;
3782
+ while (currentCID) {
3783
+ const cidStr = currentCID.toString();
3784
+ if (visited.has(cidStr)) {
3785
+ throw ERROR("[decodePubFromBlocks] pub chain has a loop", {
3786
+ currentCID: cidStr,
3787
+ visited: [...visited]
3788
+ });
3789
+ }
3790
+ visited.add(cidStr);
3791
+ const root = await getDecodedBlock(blockStore, currentCID);
3792
+ VERBOSE(`[decodePubFromBlocks] root:`, cidStr, root, { blockStore });
3793
+ if (!root) {
3794
+ throw ERROR("[decodePubFromBlocks] root not found in blockStore", { blockStore, currentCID: cidStr });
3795
+ }
3796
+ let pubLogsArray;
3797
+ if (root?.info) {
3798
+ if (!applogsCID) applogsCID = root.applogs;
3799
+ const applogsBlock = await getDecodedBlock(blockStore, root.applogs);
3800
+ pubLogsArray = await unchunkApplogsBlock(applogsBlock, blockStore);
3801
+ if (!firstInfo) {
3802
+ firstInfo = await getDecodedBlock(blockStore, root.info);
3803
+ DEBUG(`new format - infoLogs`, firstInfo.logs.map((l) => ({ [l.toString()]: l })));
3804
+ }
3805
+ } else {
3806
+ pubLogsArray = root.applogs;
3807
+ }
3808
+ const resolveLogFromCidLink = async (cidOrLink) => {
3809
+ const cid = cidOrLink;
3810
+ const applog = await getDecodedBlock(blockStore, cid);
3811
+ if (!applog) {
3812
+ ERROR(`Could not find applog CID in pub blocks:`, cid.toString(), { cid, root, blockStore });
3813
+ throw new Error(`Could not find applog CID in pub blocks: ${cid.toString()}`);
3814
+ }
3815
+ if (applog.pv instanceof CID) applog.pv = applog.pv.toV1().toString();
3816
+ return {
3817
+ ...applog,
3818
+ cid: cid.toV1().toString()
3819
+ };
3820
+ };
3821
+ const snapshotApplogs = await Promise.all(pubLogsArray.map(resolveLogFromCidLink));
3822
+ allApplogs = allApplogs.concat(snapshotApplogs);
3823
+ if (!root.prev) {
3824
+ break;
3825
+ }
3826
+ if (stopAtCID && areCidsEqual(root.prev, stopAtCID)) {
3827
+ DEBUG("[decodePubFromBlocks] stopping at stopAtCID:", stopAtCID.toString());
3828
+ break;
3829
+ }
3830
+ const prevBytes = await blockStore.get(root.prev);
3831
+ if (!prevBytes) {
3832
+ throw ERROR("[decodePubFromBlocks] prev snapshot missing from blockStore", {
3833
+ currentCID: cidStr,
3834
+ prev: root.prev.toString(),
3835
+ stopAtCID: stopAtCID?.toString(),
3836
+ visited: [...visited]
3837
+ });
3838
+ }
3839
+ currentCID = root.prev;
3840
+ }
3841
+ const result = {
3842
+ cid: rootCID,
3843
+ info: firstInfo ? {
3844
+ ...firstInfo,
3845
+ logs: await Promise.all(firstInfo.logs.map(async (cidOrLink) => {
3846
+ const cid = cidOrLink;
3847
+ const applog = await getDecodedBlock(blockStore, cid);
3848
+ if (!applog) {
3849
+ ERROR(`Could not find info log CID in pub blocks:`, cid.toString(), { cid, blockStore });
3850
+ throw new Error(`Could not find info log CID in pub blocks: ${cid.toString()}`);
3851
+ }
3852
+ if (applog.pv instanceof CID) applog.pv = applog.pv.toV1().toString();
3853
+ return {
3854
+ ...applog,
3855
+ cid: cid.toV1().toString()
3856
+ };
3857
+ }))
3858
+ } : null,
3859
+ applogsCID,
3860
+ applogs: allApplogs
3861
+ };
3862
+ DEBUG("[decodePubFromBlocks] result:", result, { rootCID: rootCID.toString(), blockStore, applogs: allApplogs });
3863
+ return result;
3864
+ }
3865
+ async function getBlocksOfCar(car) {
3866
+ const rootsFromCar = await car.getRoots();
3867
+ const roots = rootsFromCar.map((c) => (typeof c.toV1 === "function" ? c : CID.decode(c.bytes)).toV1().toString());
3868
+ const blocks = /* @__PURE__ */ new Map();
3869
+ for await (const { cid: cidFromCarblocks, bytes } of car.blocks()) {
3870
+ const cid = typeof cidFromCarblocks.toV1 === "function" ? cidFromCarblocks : CID.decode(cidFromCarblocks.bytes);
3871
+ VERBOSE({ cidFromCarblocks, cid });
3872
+ blocks.set(cid.toV1().toString(), bytes);
3873
+ }
3874
+ if (roots.length !== 1) {
3875
+ WARN("Unexpected roots count:", roots);
3876
+ }
3877
+ return {
3878
+ rootCID: CID.parse(roots[0]),
3879
+ blockStore: {
3880
+ get: (cid) => blocks.get(cid.toV1().toString())
3881
+ }
3882
+ };
3883
+ }
3884
+ async function getDecodedBlock(blockStore, cid) {
3885
+ try {
3886
+ var blob = await blockStore.get(cid);
3887
+ if (!blob) {
3888
+ WARN("returning null");
3889
+ return null;
3890
+ }
3891
+ } catch (err) {
3892
+ if (err.message === "Not Found") return null;
3893
+ throw err;
3894
+ }
3895
+ return decode(blob);
3896
+ }
3897
+ async function makeCarOut(roots, blocks) {
3898
+ const { writer, out } = CarWriter.create(Array.isArray(roots) ? roots : [roots]);
3899
+ VERBOSE(`Writing ${blocks.length} blocks to CAR`, { roots, blocks });
3900
+ blocks.forEach((b) => writer.put(b));
3901
+ writer.close();
3902
+ return out;
3903
+ }
3904
+ async function makeCarBlob(roots, blocks) {
3905
+ const carOut = await makeCarOut(roots, blocks);
3906
+ const chunks = [];
3907
+ for await (const chunk of carOut) {
3908
+ chunks.push(chunk);
3909
+ }
3910
+ const blob = new Blob(chunks);
3911
+ return blob;
3912
+ }
3913
+ async function carFromBlob(blob) {
3914
+ return CarReader.fromBytes(new Uint8Array(await blob.arrayBuffer()));
3915
+ }
3916
+ function streamReaderToIterable(bodyReader) {
3917
+ return (async function* () {
3918
+ while (true) {
3919
+ const { done, value } = await bodyReader.read();
3920
+ VERBOSE(`[car] chunk`, { done, value });
3921
+ if (done) {
3922
+ break;
3923
+ }
3924
+ yield value;
3925
+ }
3926
+ })();
3927
+ }
3928
+
3929
+ // src/pubsub/snap-push.ts
3930
+ var { WARN: WARN2, LOG: LOG2, DEBUG: DEBUG2, VERBOSE: VERBOSE2, ERROR: ERROR2 } = g.setup(g.INFO);
3931
+ async function prepareSnapshotForPush(agent, appThread, threadToPublish, share, prevSnapCID) {
3932
+ let logsToPublish = getLogsFromThread(threadToPublish);
3933
+ DEBUG2(`[preparePubForPush] Collected ${logsToPublish.length} logs :`, {
3934
+ logsToPublish,
3935
+ threadOrLogsCount: threadToPublish.nameAndSizeUntracked || `[${threadToPublish.length}]`
3936
+ });
3937
+ const { sharedAgents, sharedKeyMap, sharedKey, pubCounter } = share ?? {};
3938
+ const getExistingOrNewLog = (thread, share2, ag, at, vl) => {
3939
+ let logInQuestion = rollingFilter(lastWriteWins(thread), { en: share2.id, at }).latestLog;
3940
+ if (!logInQuestion && vl !== void 0) {
3941
+ logInQuestion = ensureTsPvAndFinalizeApplog({ ag, en: share2.id, at, vl }, thread);
3942
+ }
3943
+ return logInQuestion;
3944
+ };
3945
+ const shareNameLog = getExistingOrNewLog(appThread, share, agent.ag, "share/name", share.name);
3946
+ const shareCounterLog = getExistingOrNewLog(appThread, share, agent.ag, "share/counter", `${agent.did}<::>${pubCounter}`);
3947
+ const encryptApplog = async (applog, keyToUse) => {
3948
+ const { log: eachLog, cid } = prepareForPub(applog);
3949
+ const enc = new TextEncoder();
3950
+ const stringified = wrapper_default(eachLog);
3951
+ const stringifiedEncodedAppLogPayload = enc.encode(stringified);
3952
+ VERBOSE2("[odd]", { eachLog, stringified, stringifiedEncodedAppLogPayload });
3953
+ try {
3954
+ const encPayload = await agent.crypto?.aes.encrypt(stringifiedEncodedAppLogPayload, keyToUse, "AES-GCM");
3955
+ VERBOSE2("[odd] encrypted length:", stringifiedEncodedAppLogPayload.length, { encPayload });
3956
+ return encPayload;
3957
+ } catch (err) {
3958
+ throw ERROR2("FAILED TO ENC payload length:", stringifiedEncodedAppLogPayload.length, { err });
3959
+ }
3960
+ };
3961
+ let maybeEncryptedApplogs;
3962
+ const encryptedApplogs = [];
3963
+ const agentSharedKeyLogs = [];
3964
+ if (sharedAgents) {
3965
+ if (!sharedKey || !sharedKeyMap) {
3966
+ throw ERROR2("sharedAgents but no Keys/Map", { sharedAgents, sharedKeyMap, sharedKey });
3967
+ }
3968
+ VERBOSE2("encrypting", { sharedAgents, sharedKeyMap });
3969
+ for (const [eachAgent, eachEncKey] of Array.from(sharedKeyMap.entries())) {
3970
+ VERBOSE2("adding key", { eachAgent, eachEncKey });
3971
+ agentSharedKeyLogs.push({
3972
+ ag: agent.ag,
3973
+ en: eachAgent,
3974
+ at: "share/sharedKey",
3975
+ vl: eachEncKey
3976
+ // these are encrypted with the derived key from the local agent private and remote agent public keys
3977
+ });
3978
+ }
3979
+ const CIDlist = [];
3980
+ const pubCIDmap = {};
3981
+ for (const eachLog of logsToPublish) {
3982
+ VERBOSE2("[crypto] encrypting ", { eachLog, sharedKey });
3983
+ const encPayload = await encryptApplog(eachLog, sharedKey);
3984
+ DEBUG2("[crypto] encrypted ", { eachLog, encPayload, sharedKey });
3985
+ encryptedApplogs.push({ enc: encPayload });
3986
+ }
3987
+ maybeEncryptedApplogs = encryptedApplogs;
3988
+ } else {
3989
+ maybeEncryptedApplogs = logsToPublish;
3990
+ }
3991
+ DEBUG2("adding all agent info and shareAtoms", {
3992
+ share,
3993
+ agent,
3994
+ logsToPublish,
3995
+ // threadToPublish, - very verbose
3996
+ agentSharedKeyLogs
3997
+ });
3998
+ const infoLogs = [
3999
+ ...rollingFilter(lastWriteWins(appThread), {
4000
+ // TODO: use static filter for performance
4001
+ en: agent.ag,
4002
+ at: ["agent/ecdh", "agent/jwkd", "agent/appAgent"]
4003
+ }).applogs,
4004
+ ...shareNameLog ? [shareNameLog] : [],
4005
+ ...shareCounterLog ? [shareCounterLog] : [],
4006
+ ...agentSharedKeyLogs
4007
+ ];
4008
+ DEBUG2(`[prepareSnapshotForPush] info logs:`, infoLogs);
4009
+ if (!infoLogs.find(({ at }) => at === "agent/appAgent")) throw ERROR2(`[prepareSnapshotForPush] appThread missing agent/appAgent log`);
4010
+ const applogsToEncode = keepTruthy(maybeEncryptedApplogs);
4011
+ const infologsToEncode = keepTruthy(infoLogs);
4012
+ if (!applogsToEncode.length) {
4013
+ throw ERROR2("no valid applogs", { agent, maybeEncryptedApplogs, infoLogs, applogsToEncode, infologsToEncode, prevSnapCID });
4014
+ }
4015
+ if (!infologsToEncode.length) {
4016
+ throw ERROR2("no valid infologs", { agent, maybeEncryptedApplogs, infoLogs, applogsToEncode, infologsToEncode, prevSnapCID });
4017
+ }
4018
+ const encodedSnapshot = await encodeSnapshotAsCar(agent, applogsToEncode, infologsToEncode, prevSnapCID);
4019
+ DEBUG2("inPrepareSnapshotForPush", { encodedSnapshot });
4020
+ return encodedSnapshot;
4021
+ }
4022
+ async function encodeSnapshotAsCar(agent, applogs, infoLogs, prevSnapCID) {
4023
+ DEBUG2(`[encodeSnapshotAsCar] encoding`, { agent, applogs, infoLogs });
4024
+ const { cids: infoLogCids, encodedApplogs: encodedInfoLogs } = await encodeApplogsAsIPLD(infoLogs);
4025
+ const { cids: applogCids, encodedApplogs } = await encodeApplogsAsIPLD(applogs);
4026
+ let blocks = encodedApplogs.concat(encodedInfoLogs);
4027
+ const infoLogsWrap = await encodeBlockOriginal({ logs: infoLogCids });
4028
+ blocks.push(infoLogsWrap);
4029
+ const { rootCID: chunkRootCID, blocks: chunkBlocks } = await chunkApplogs(applogCids);
4030
+ blocks = blocks.concat(chunkBlocks);
4031
+ const infoSignature = await agent.sign(infoLogsWrap.cid.bytes);
4032
+ const applogsSignature = await agent.sign(chunkRootCID.bytes);
4033
+ const root = {
4034
+ info: infoLogsWrap.cid,
4035
+ applogs: chunkRootCID,
4036
+ infoSignature,
4037
+ applogsSignature,
4038
+ prev: prevSnapCID
4039
+ };
4040
+ DEBUG2("[encodeSnapshotAsCar] encoding root", { root, logCids: applogCids, infoLogCids });
4041
+ const encodedRoot = await encodeBlockOriginal(root);
4042
+ blocks.push(encodedRoot);
4043
+ DEBUG2("[encodeSnapshotAsCar] => root", { encodedRoot });
4044
+ return {
4045
+ cid: encodedRoot.cid,
4046
+ blob: await makeCarBlob(encodedRoot.cid, blocks),
4047
+ // TODO: create CarBuilder (incl .encodeAndAdd({...}))
4048
+ blocks,
4049
+ infoLogCids,
4050
+ applogCids
4051
+ };
4052
+ }
4053
+ async function chunkApplogs(applogCids, size = 1e4) {
4054
+ if (!applogCids.length) throw ERROR2(`[chunkApplogs] called with empty array`);
4055
+ const chunks = [];
4056
+ for (let i = 0; i < applogCids.length; i += size) {
4057
+ const chunk = await encodeBlockOriginal({ logs: applogCids.slice(i, Math.min(i + applogCids.length, i + size)) });
4058
+ chunks.push(chunk);
4059
+ }
4060
+ if (chunks.length === 1) return { rootCID: chunks[0].cid, blocks: chunks };
4061
+ const root = await encodeBlockOriginal({ chunks: chunks.map((chunk) => chunk.cid) });
4062
+ const blocks = [root, ...chunks];
4063
+ DEBUG2(`[chunkApplogs] ${applogCids.length} logs chunked into ${chunks.length}`, { applogCids, root, blocks, chunks, dagJson: src_exports });
4064
+ return { rootCID: root.cid, blocks, chunks };
4065
+ }
4066
+ async function unchunkApplogsBlock(block, blockStore) {
4067
+ if (isSnapBlockChunks(block)) {
4068
+ return (await Promise.all(
4069
+ block.chunks.map(async (chunkCid) => {
4070
+ const block2 = await getDecodedBlock(blockStore, chunkCid);
4071
+ if (!block2.logs) throw ERROR2(`Weird chunk`, block2);
4072
+ return block2.logs;
4073
+ })
4074
+ )).flat();
4075
+ } else {
4076
+ return block.logs;
4077
+ }
4078
+ }
4079
+ function isSnapBlockChunks(block) {
4080
+ return block.chunks;
4081
+ }
4082
+ async function encodeSnapshotApplogsAsCar(applogs) {
4083
+ const encoded = await encodeApplogsAsIPLD(applogs);
4084
+ if (!encoded) throw ERROR2("invalid applogs cannot continue", { applogs, encoded });
4085
+ const { cids, encodedApplogs } = encoded;
4086
+ const root = { applogs: cids };
4087
+ const encodedRoot = await encodeBlockOriginal(root);
4088
+ DEBUG2("[encodeSnapshotApplogsAsCar] encoded root", { cids, encodedRoot });
4089
+ return await makeCarBlob(encodedRoot.cid, [encodedRoot, ...encodedApplogs]);
4090
+ }
4091
+ async function encodeApplogsAsIPLD(applogs) {
4092
+ DEBUG2({ applogs });
4093
+ const validApplogs = applogs.filter((eachLog) => !!eachLog);
4094
+ DEBUG2({ validApplogs });
4095
+ if (!validApplogs.length) throw ERROR2("no valid applogs");
4096
+ const preppedLogs = validApplogs.map((log) => prepareForPub(log).log);
4097
+ const encodedApplogs = await Promise.all(preppedLogs.map(encodeBlockOriginal));
4098
+ DEBUG2("[encodeApplogsAsIpld] encoded applogs", { preppedLogs, encodedApplogs });
4099
+ const cids = encodedApplogs.map((b) => {
4100
+ if (!b.cid) throw ERROR2(`[publish] no cid for encoded log:`, b);
4101
+ return b.cid;
4102
+ });
4103
+ return { cids, encodedApplogs };
4104
+ }
4105
+
4106
+ export {
4107
+ prepareSnapshotForPush,
4108
+ encodeSnapshotAsCar,
4109
+ chunkApplogs,
4110
+ unchunkApplogsBlock,
4111
+ isSnapBlockChunks,
4112
+ encodeSnapshotApplogsAsCar,
4113
+ decodePubFromCar,
4114
+ decodePubFromBlocks,
4115
+ getBlocksOfCar,
4116
+ getDecodedBlock,
4117
+ makeCarOut,
4118
+ makeCarBlob,
4119
+ carFromBlob,
4120
+ streamReaderToIterable
4121
+ };
4122
+ //# sourceMappingURL=chunk-SIIQEX77.min.js.map