@qntx/ur 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1500 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { sha256 } from "@noble/hashes/sha2.js";
3
- //#region src/error.ts
4
- const MESSAGES = {
5
- InvalidWord: "invalid bytewords word",
6
- InvalidBytewordsChecksum: "invalid bytewords checksum",
7
- InvalidBytewordsLength: "invalid bytewords length",
8
- NonAscii: "bytewords string is not ASCII",
9
- EmptyMessage: "empty message",
10
- EmptyPart: "empty fountain part",
11
- InvalidFragmentLen: "invalid maximum fragment length",
12
- InvalidSequence: "invalid sequence number",
13
- InconsistentPart: "fountain part inconsistent with previous parts",
14
- InvalidPadding: "invalid fountain part padding",
15
- InvalidMessageChecksum: "invalid fountain message checksum",
16
- InvalidPartCbor: "invalid fountain part CBOR",
17
- DecoderState: "fountain decoder internal state error",
18
- SinglePartExhausted: "single-part fountain encoder exhausted",
19
- ResourceLimit: "resource limit exceeded",
20
- InvalidScheme: "invalid UR scheme",
21
- TypeUnspecified: "UR type unspecified",
22
- InvalidType: "invalid UR type",
23
- InvalidIndices: "invalid multi-part indices",
24
- NotSinglePart: "expected single-part UR",
25
- UnexpectedType: "unexpected UR type",
26
- CborDecode: "dCBOR decode failed",
27
- CborType: "dCBOR type mismatch"
28
- };
29
- /** Structured error thrown by the UR stack. */
30
- var UrError = class extends Error {
31
- code;
32
- expected;
33
- found;
34
- limit;
35
- constructor(code, options) {
36
- let message = MESSAGES[code];
37
- if (code === "ResourceLimit" && options?.limit) message = `${message}: ${options.limit}`;
38
- else if (code === "UnexpectedType" && options?.expected && options.found) message = `${message}: expected ${options.expected}, found ${options.found}`;
39
- super(message, options?.cause !== void 0 ? { cause: options.cause } : void 0);
40
- this.name = "UrError";
41
- this.code = code;
42
- this.expected = options?.expected;
43
- this.found = options?.found;
44
- this.limit = options?.limit;
45
- }
46
- };
47
- /** Throws a {@link UrError} with the given code. */
48
- function fail(code, options) {
49
- throw new UrError(code, options);
50
- }
51
- /** Rethrows the stored poison as a {@link UrError}. */
52
- function failPoison(p) {
53
- if (p.code === "ResourceLimit") fail("ResourceLimit", { limit: p.limit });
54
- fail("DecoderState");
55
- }
56
- //#endregion
57
- //#region src/crc32.ts
58
- /**
59
- * CRC-32 ISO-HDLC (polynomial 0xedb88320), matching bcur / ur-rs.
60
- */
61
- const TABLE = (() => {
62
- const table = /* @__PURE__ */ new Uint32Array(256);
63
- for (let i = 0; i < 256; i++) {
64
- let c = i;
65
- for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
66
- table[i] = c >>> 0;
67
- }
68
- return table;
69
- })();
70
- /** CRC-32 ISO-HDLC checksum of `data`. */
71
- function checksum(data) {
72
- let crc = 4294967295;
73
- for (let i = 0; i < data.length; i++) {
74
- const b = data[i];
75
- crc = TABLE[(crc ^ b) & 255] ^ crc >>> 8;
76
- }
77
- return (crc ^ 4294967295) >>> 0;
78
- }
79
- //#endregion
80
- //#region src/constants.ts
81
- /** BCR-2020-012 bytewords tables. */
82
- /** Four-letter bytewords (index = byte value). */
83
- const WORDS = [
84
- "able",
85
- "acid",
86
- "also",
87
- "apex",
88
- "aqua",
89
- "arch",
90
- "atom",
91
- "aunt",
92
- "away",
93
- "axis",
94
- "back",
95
- "bald",
96
- "barn",
97
- "belt",
98
- "beta",
99
- "bias",
100
- "blue",
101
- "body",
102
- "brag",
103
- "brew",
104
- "bulb",
105
- "buzz",
106
- "calm",
107
- "cash",
108
- "cats",
109
- "chef",
110
- "city",
111
- "claw",
112
- "code",
113
- "cola",
114
- "cook",
115
- "cost",
116
- "crux",
117
- "curl",
118
- "cusp",
119
- "cyan",
120
- "dark",
121
- "data",
122
- "days",
123
- "deli",
124
- "dice",
125
- "diet",
126
- "door",
127
- "down",
128
- "draw",
129
- "drop",
130
- "drum",
131
- "dull",
132
- "duty",
133
- "each",
134
- "easy",
135
- "echo",
136
- "edge",
137
- "epic",
138
- "even",
139
- "exam",
140
- "exit",
141
- "eyes",
142
- "fact",
143
- "fair",
144
- "fern",
145
- "figs",
146
- "film",
147
- "fish",
148
- "fizz",
149
- "flap",
150
- "flew",
151
- "flux",
152
- "foxy",
153
- "free",
154
- "frog",
155
- "fuel",
156
- "fund",
157
- "gala",
158
- "game",
159
- "gear",
160
- "gems",
161
- "gift",
162
- "girl",
163
- "glow",
164
- "good",
165
- "gray",
166
- "grim",
167
- "guru",
168
- "gush",
169
- "gyro",
170
- "half",
171
- "hang",
172
- "hard",
173
- "hawk",
174
- "heat",
175
- "help",
176
- "high",
177
- "hill",
178
- "holy",
179
- "hope",
180
- "horn",
181
- "huts",
182
- "iced",
183
- "idea",
184
- "idle",
185
- "inch",
186
- "inky",
187
- "into",
188
- "iris",
189
- "iron",
190
- "item",
191
- "jade",
192
- "jazz",
193
- "join",
194
- "jolt",
195
- "jowl",
196
- "judo",
197
- "jugs",
198
- "jump",
199
- "junk",
200
- "jury",
201
- "keep",
202
- "keno",
203
- "kept",
204
- "keys",
205
- "kick",
206
- "kiln",
207
- "king",
208
- "kite",
209
- "kiwi",
210
- "knob",
211
- "lamb",
212
- "lava",
213
- "lazy",
214
- "leaf",
215
- "legs",
216
- "liar",
217
- "limp",
218
- "lion",
219
- "list",
220
- "logo",
221
- "loud",
222
- "love",
223
- "luau",
224
- "luck",
225
- "lung",
226
- "main",
227
- "many",
228
- "math",
229
- "maze",
230
- "memo",
231
- "menu",
232
- "meow",
233
- "mild",
234
- "mint",
235
- "miss",
236
- "monk",
237
- "nail",
238
- "navy",
239
- "need",
240
- "news",
241
- "next",
242
- "noon",
243
- "note",
244
- "numb",
245
- "obey",
246
- "oboe",
247
- "omit",
248
- "onyx",
249
- "open",
250
- "oval",
251
- "owls",
252
- "paid",
253
- "part",
254
- "peck",
255
- "play",
256
- "plus",
257
- "poem",
258
- "pool",
259
- "pose",
260
- "puff",
261
- "puma",
262
- "purr",
263
- "quad",
264
- "quiz",
265
- "race",
266
- "ramp",
267
- "real",
268
- "redo",
269
- "rich",
270
- "road",
271
- "rock",
272
- "roof",
273
- "ruby",
274
- "ruin",
275
- "runs",
276
- "rust",
277
- "safe",
278
- "saga",
279
- "scar",
280
- "sets",
281
- "silk",
282
- "skew",
283
- "slot",
284
- "soap",
285
- "solo",
286
- "song",
287
- "stub",
288
- "surf",
289
- "swan",
290
- "taco",
291
- "task",
292
- "taxi",
293
- "tent",
294
- "tied",
295
- "time",
296
- "tiny",
297
- "toil",
298
- "tomb",
299
- "toys",
300
- "trip",
301
- "tuna",
302
- "twin",
303
- "ugly",
304
- "undo",
305
- "unit",
306
- "urge",
307
- "user",
308
- "vast",
309
- "very",
310
- "veto",
311
- "vial",
312
- "vibe",
313
- "view",
314
- "visa",
315
- "void",
316
- "vows",
317
- "wall",
318
- "wand",
319
- "warm",
320
- "wasp",
321
- "wave",
322
- "waxy",
323
- "webs",
324
- "what",
325
- "when",
326
- "whiz",
327
- "wolf",
328
- "work",
329
- "yank",
330
- "yawn",
331
- "yell",
332
- "yoga",
333
- "yurt",
334
- "zaps",
335
- "zero",
336
- "zest",
337
- "zinc",
338
- "zone",
339
- "zoom"
340
- ];
341
- /** First+last letter of each byteword (UR minimal style). */
342
- const MINIMALS = [
343
- "ae",
344
- "ad",
345
- "ao",
346
- "ax",
347
- "aa",
348
- "ah",
349
- "am",
350
- "at",
351
- "ay",
352
- "as",
353
- "bk",
354
- "bd",
355
- "bn",
356
- "bt",
357
- "ba",
358
- "bs",
359
- "be",
360
- "by",
361
- "bg",
362
- "bw",
363
- "bb",
364
- "bz",
365
- "cm",
366
- "ch",
367
- "cs",
368
- "cf",
369
- "cy",
370
- "cw",
371
- "ce",
372
- "ca",
373
- "ck",
374
- "ct",
375
- "cx",
376
- "cl",
377
- "cp",
378
- "cn",
379
- "dk",
380
- "da",
381
- "ds",
382
- "di",
383
- "de",
384
- "dt",
385
- "dr",
386
- "dn",
387
- "dw",
388
- "dp",
389
- "dm",
390
- "dl",
391
- "dy",
392
- "eh",
393
- "ey",
394
- "eo",
395
- "ee",
396
- "ec",
397
- "en",
398
- "em",
399
- "et",
400
- "es",
401
- "ft",
402
- "fr",
403
- "fn",
404
- "fs",
405
- "fm",
406
- "fh",
407
- "fz",
408
- "fp",
409
- "fw",
410
- "fx",
411
- "fy",
412
- "fe",
413
- "fg",
414
- "fl",
415
- "fd",
416
- "ga",
417
- "ge",
418
- "gr",
419
- "gs",
420
- "gt",
421
- "gl",
422
- "gw",
423
- "gd",
424
- "gy",
425
- "gm",
426
- "gu",
427
- "gh",
428
- "go",
429
- "hf",
430
- "hg",
431
- "hd",
432
- "hk",
433
- "ht",
434
- "hp",
435
- "hh",
436
- "hl",
437
- "hy",
438
- "he",
439
- "hn",
440
- "hs",
441
- "id",
442
- "ia",
443
- "ie",
444
- "ih",
445
- "iy",
446
- "io",
447
- "is",
448
- "in",
449
- "im",
450
- "je",
451
- "jz",
452
- "jn",
453
- "jt",
454
- "jl",
455
- "jo",
456
- "js",
457
- "jp",
458
- "jk",
459
- "jy",
460
- "kp",
461
- "ko",
462
- "kt",
463
- "ks",
464
- "kk",
465
- "kn",
466
- "kg",
467
- "ke",
468
- "ki",
469
- "kb",
470
- "lb",
471
- "la",
472
- "ly",
473
- "lf",
474
- "ls",
475
- "lr",
476
- "lp",
477
- "ln",
478
- "lt",
479
- "lo",
480
- "ld",
481
- "le",
482
- "lu",
483
- "lk",
484
- "lg",
485
- "mn",
486
- "my",
487
- "mh",
488
- "me",
489
- "mo",
490
- "mu",
491
- "mw",
492
- "md",
493
- "mt",
494
- "ms",
495
- "mk",
496
- "nl",
497
- "ny",
498
- "nd",
499
- "ns",
500
- "nt",
501
- "nn",
502
- "ne",
503
- "nb",
504
- "oy",
505
- "oe",
506
- "ot",
507
- "ox",
508
- "on",
509
- "ol",
510
- "os",
511
- "pd",
512
- "pt",
513
- "pk",
514
- "py",
515
- "ps",
516
- "pm",
517
- "pl",
518
- "pe",
519
- "pf",
520
- "pa",
521
- "pr",
522
- "qd",
523
- "qz",
524
- "re",
525
- "rp",
526
- "rl",
527
- "ro",
528
- "rh",
529
- "rd",
530
- "rk",
531
- "rf",
532
- "ry",
533
- "rn",
534
- "rs",
535
- "rt",
536
- "se",
537
- "sa",
538
- "sr",
539
- "ss",
540
- "sk",
541
- "sw",
542
- "st",
543
- "sp",
544
- "so",
545
- "sg",
546
- "sb",
547
- "sf",
548
- "sn",
549
- "to",
550
- "tk",
551
- "ti",
552
- "tt",
553
- "td",
554
- "te",
555
- "ty",
556
- "tl",
557
- "tb",
558
- "ts",
559
- "tp",
560
- "ta",
561
- "tn",
562
- "uy",
563
- "uo",
564
- "ut",
565
- "ue",
566
- "ur",
567
- "vt",
568
- "vy",
569
- "vo",
570
- "vl",
571
- "ve",
572
- "vw",
573
- "va",
574
- "vd",
575
- "vs",
576
- "wl",
577
- "wd",
578
- "wm",
579
- "wp",
580
- "we",
581
- "wy",
582
- "ws",
583
- "wt",
584
- "wn",
585
- "wz",
586
- "wf",
587
- "wk",
588
- "yk",
589
- "yn",
590
- "yl",
591
- "ya",
592
- "yt",
593
- "zs",
594
- "zo",
595
- "zt",
596
- "zc",
597
- "ze",
598
- "zm"
599
- ];
600
- //#endregion
601
- //#region src/bytewords/index.ts
602
- var bytewords_exports = /* @__PURE__ */ __exportAll({
603
- MINIMALS: () => MINIMALS,
604
- WORDS: () => WORDS,
605
- canonicalizeByteword: () => canonicalizeByteword,
606
- decode: () => decode$1,
607
- encode: () => encode$1,
608
- encodeRaw: () => encodeRaw
609
- });
610
- const wordByToken = /* @__PURE__ */ new Map();
611
- for (let i = 0; i < 256; i++) {
612
- wordByToken.set(WORDS[i], i);
613
- wordByToken.set(MINIMALS[i], i);
614
- }
615
- /** Encode `data` with trailing CRC-32 as bytewords. Empty data is allowed. */
616
- function encode$1(data, style) {
617
- const crc = checksum(data);
618
- const withCrc = new Uint8Array(data.length + 4);
619
- withCrc.set(data);
620
- withCrc[data.length] = crc >>> 24 & 255;
621
- withCrc[data.length + 1] = crc >>> 16 & 255;
622
- withCrc[data.length + 2] = crc >>> 8 & 255;
623
- withCrc[data.length + 3] = crc & 255;
624
- return encodeWords(withCrc, style);
625
- }
626
- /**
627
- * Encode without CRC trailer.
628
- * Not for UR bodies — identifiers only.
629
- */
630
- function encodeRaw(data, style) {
631
- return encodeWords(data, style);
632
- }
633
- function encodeWords(data, style) {
634
- const parts = [];
635
- for (let i = 0; i < data.length; i++) {
636
- const b = data[i];
637
- parts.push(style === "minimal" ? MINIMALS[b] : WORDS[b]);
638
- }
639
- const sep = style === "standard" ? " " : style === "uri" ? "-" : "";
640
- return parts.join(sep);
641
- }
642
- /** Decode bytewords and verify CRC-32. Case-insensitive. */
643
- function decode$1(encoded, style) {
644
- for (let i = 0; i < encoded.length; i++) if (encoded.charCodeAt(i) > 127) fail("NonAscii");
645
- const lowered = encoded.toLowerCase();
646
- if (style === "minimal") return decodeMinimal(lowered);
647
- const sep = style === "standard" ? " " : "-";
648
- return decodeParts(lowered.length === 0 ? [] : lowered.split(sep), false);
649
- }
650
- function decodeMinimal(encoded) {
651
- if (encoded.length % 2 !== 0) fail("InvalidBytewordsLength");
652
- const parts = [];
653
- for (let i = 0; i < encoded.length; i += 2) parts.push(encoded.slice(i, i + 2));
654
- return decodeParts(parts, true);
655
- }
656
- function decodeParts(parts, minimal) {
657
- const data = new Uint8Array(parts.length);
658
- for (let i = 0; i < parts.length; i++) {
659
- const part = parts[i];
660
- const expectedLen = minimal ? 2 : 4;
661
- if (part.length !== expectedLen) fail("InvalidWord");
662
- const byte = wordByToken.get(part);
663
- if (byte === void 0) fail("InvalidWord");
664
- if (part !== (minimal ? MINIMALS[byte] : WORDS[byte])) fail("InvalidWord");
665
- data[i] = byte;
666
- }
667
- return stripChecksum(data);
668
- }
669
- function stripChecksum(data) {
670
- if (data.length < 4) fail("InvalidBytewordsChecksum");
671
- const split = data.length - 4;
672
- const payload = data.subarray(0, split);
673
- const expected = checksum(payload);
674
- if ((data[split] << 24 | data[split + 1] << 16 | data[split + 2] << 8 | data[split + 3]) >>> 0 !== expected) fail("InvalidBytewordsChecksum");
675
- return payload.slice();
676
- }
677
- /** Canonicalize a 2–4 letter token to the full 4-letter lowercase byteword. */
678
- function canonicalizeByteword(token) {
679
- for (let i = 0; i < token.length; i++) if (token.charCodeAt(i) > 127) return void 0;
680
- const lower = token.toLowerCase();
681
- if (lower.length === 4) {
682
- const b = wordByToken.get(lower);
683
- return b === void 0 ? void 0 : WORDS[b];
684
- }
685
- if (lower.length === 2) {
686
- const b = wordByToken.get(lower);
687
- return b === void 0 ? void 0 : WORDS[b];
688
- }
689
- if (lower.length === 3) {
690
- let found;
691
- for (const word of WORDS) if (word.slice(0, 3) === lower || word.slice(1, 4) === lower) {
692
- if (found !== void 0) return void 0;
693
- found = word;
694
- }
695
- return found;
696
- }
697
- }
698
- //#endregion
699
- //#region src/rng/sampler.ts
700
- /**
701
- * Walker's alias method with reverse-index ordered partition (ur-rs / bcur).
702
- */
703
- var Weighted = class Weighted {
704
- aliases;
705
- probs;
706
- constructor(aliases, probs) {
707
- this.aliases = aliases;
708
- this.probs = probs;
709
- }
710
- static new(weightsIn) {
711
- const weights = weightsIn.slice();
712
- for (const w of weights) if (w < 0) throw new Error("negative probability encountered");
713
- const summed = weights.reduce((a, b) => a + b, 0);
714
- if (!(summed > 0)) throw new Error("probabilities don't sum to a positive value");
715
- const count = weights.length;
716
- for (let i = 0; i < count; i++) weights[i] *= count / summed;
717
- const s = [];
718
- const l = [];
719
- for (let j = count - 1; j >= 0; j--) if (weights[j] < 1) s.push(j);
720
- else l.push(j);
721
- const probs = Array.from({ length: count }, () => 0);
722
- const aliases = Array.from({ length: count }, () => 0);
723
- while (s.length > 0 && l.length > 0) {
724
- const a = s.pop();
725
- const g = l.pop();
726
- probs[a] = weights[a];
727
- aliases[a] = g;
728
- weights[g] += weights[a] - 1;
729
- if (weights[g] < 1) s.push(g);
730
- else l.push(g);
731
- }
732
- while (l.length > 0) probs[l.pop()] = 1;
733
- while (s.length > 0) probs[s.pop()] = 1;
734
- return new Weighted(aliases, probs);
735
- }
736
- next(xoshiro) {
737
- const r1 = xoshiro.nextDouble();
738
- const r2 = xoshiro.nextDouble();
739
- const n = this.probs.length;
740
- const i = Math.trunc(n * r1);
741
- if (r2 < this.probs[i]) return i;
742
- return this.aliases[i];
743
- }
744
- };
745
- //#endregion
746
- //#region src/rng/xoshiro.ts
747
- const MASK64 = (1n << 64n) - 1n;
748
- function rotl(x, k) {
749
- x &= MASK64;
750
- return (x << BigInt(k) | x >> BigInt(64 - k)) & MASK64;
751
- }
752
- function unitInterval(value) {
753
- return Number(value >> 11n) * (1 / 2 ** 53);
754
- }
755
- /**
756
- * Xoshiro256** with SHA-256 seeding matching URKit / ur-rs / bcur.
757
- */
758
- var Xoshiro256 = class Xoshiro256 {
759
- s0;
760
- s1;
761
- s2;
762
- s3;
763
- constructor(s0, s1, s2, s3) {
764
- this.s0 = s0;
765
- this.s1 = s1;
766
- this.s2 = s2;
767
- this.s3 = s3;
768
- }
769
- /** Seed from arbitrary bytes via SHA-256 + BE-limb→LE packing. */
770
- static fromBytes(bytes) {
771
- return Xoshiro256.fromDigest(sha256(bytes));
772
- }
773
- static fromString(value) {
774
- return Xoshiro256.fromBytes(new TextEncoder().encode(value));
775
- }
776
- /** Seed from CRC-32 BE bytes of `bytes` (test helper path). */
777
- static fromCrc(bytes) {
778
- const c = checksum(bytes);
779
- const seed = /* @__PURE__ */ new Uint8Array(4);
780
- seed[0] = c >>> 24 & 255;
781
- seed[1] = c >>> 16 & 255;
782
- seed[2] = c >>> 8 & 255;
783
- seed[3] = c & 255;
784
- return Xoshiro256.fromBytes(seed);
785
- }
786
- static fromDigest(seed32) {
787
- const limbs = [];
788
- for (let i = 0; i < 4; i++) {
789
- let v = 0n;
790
- for (let n = 0; n < 8; n++) v = v << 8n | BigInt(seed32[8 * i + n]);
791
- limbs.push(v & MASK64);
792
- }
793
- return new Xoshiro256(limbs[0], limbs[1], limbs[2], limbs[3]);
794
- }
795
- nextU64() {
796
- const result = rotl(this.s1 * 5n & MASK64, 7) * 9n & MASK64;
797
- const t = this.s1 << 17n & MASK64;
798
- this.s2 = (this.s2 ^ this.s0) & MASK64;
799
- this.s3 = (this.s3 ^ this.s1) & MASK64;
800
- this.s1 = (this.s1 ^ this.s2) & MASK64;
801
- this.s0 = (this.s0 ^ this.s3) & MASK64;
802
- this.s2 = (this.s2 ^ t) & MASK64;
803
- this.s3 = rotl(this.s3, 45);
804
- return result;
805
- }
806
- nextDouble() {
807
- return unitInterval(this.nextU64());
808
- }
809
- /**
810
- * Inclusive `[low, high]` via double scaling (normative float path).
811
- * Truncation toward zero matches Rust `as u64`.
812
- */
813
- nextInt(low, high) {
814
- const span = high - low + 1;
815
- return Math.trunc(this.nextDouble() * span) + low;
816
- }
817
- /** Remove-order shuffle (not Fisher–Yates). */
818
- shuffled(items) {
819
- const pool = items.slice();
820
- const out = [];
821
- while (pool.length > 0) {
822
- const index = this.nextInt(0, pool.length - 1);
823
- out.push(pool.splice(index, 1)[0]);
824
- }
825
- return out;
826
- }
827
- chooseDegree(length) {
828
- const weights = [];
829
- for (let x = 1; x <= length; x++) weights.push(1 / x);
830
- return Weighted.new(weights).next(this) + 1;
831
- }
832
- nextByte() {
833
- return this.nextInt(0, 255);
834
- }
835
- nextBytes(n) {
836
- const out = new Uint8Array(n);
837
- for (let i = 0; i < n; i++) out[i] = this.nextByte();
838
- return out;
839
- }
840
- };
841
- //#endregion
842
- //#region src/fountain/choose.ts
843
- function divCeil(a, b) {
844
- return Math.trunc((a + b - 1) / b);
845
- }
846
- /** Optimal equal fragment length under a max cap. */
847
- function fragmentLength(dataLength, maxFragmentLength) {
848
- return divCeil(dataLength, divCeil(dataLength, maxFragmentLength));
849
- }
850
- /** Pad and split message into equal fragments. */
851
- function partition(data, fragLen) {
852
- const pad = (fragLen - data.length % fragLen) % fragLen;
853
- const padded = new Uint8Array(data.length + pad);
854
- padded.set(data);
855
- const out = [];
856
- for (let i = 0; i < padded.length; i += fragLen) out.push(padded.subarray(i, i + fragLen));
857
- return out;
858
- }
859
- /**
860
- * Fragment indexes mixed into sequence `sequence` (1-based).
861
- * Normative: simple if sequence <= K; else degree + remove-shuffle.
862
- */
863
- function chooseFragments(sequence, fragmentCount, checksum) {
864
- if (sequence <= fragmentCount) return [sequence - 1];
865
- const seed = /* @__PURE__ */ new Uint8Array(8);
866
- seed[0] = sequence >>> 24 & 255;
867
- seed[1] = sequence >>> 16 & 255;
868
- seed[2] = sequence >>> 8 & 255;
869
- seed[3] = sequence & 255;
870
- seed[4] = checksum >>> 24 & 255;
871
- seed[5] = checksum >>> 16 & 255;
872
- seed[6] = checksum >>> 8 & 255;
873
- seed[7] = checksum & 255;
874
- const xoshiro = Xoshiro256.fromBytes(seed);
875
- const degree = xoshiro.chooseDegree(fragmentCount);
876
- const indexes = Array.from({ length: fragmentCount }, (_, i) => i);
877
- return xoshiro.shuffled(indexes).slice(0, degree);
878
- }
879
- //#endregion
880
- //#region src/fountain/limits.ts
881
- /** Production Default; same integers as bcur 1.0. Hosts that need another budget pass `new Decoder({ limits })`. */
882
- const DEFAULT_LIMITS = {
883
- maxMessageLength: 1048576,
884
- maxFragmentCount: 2e3,
885
- maxFragmentDataLength: 8192,
886
- maxBufferParts: 4e3,
887
- maxReceivedParts: 8e3,
888
- maxUriLen: 8192
889
- };
890
- function mergeLimits(partial) {
891
- return {
892
- ...DEFAULT_LIMITS,
893
- ...partial
894
- };
895
- }
896
- //#endregion
897
- //#region src/fountain/part-cbor.ts
898
- /** Encode a part to deterministic fixed-schema CBOR. */
899
- function encodePart(part) {
900
- const data = part.data;
901
- const out = [133];
902
- encodeU32(out, part.sequence);
903
- encodeU32(out, part.sequenceCount);
904
- encodeU32(out, part.messageLength);
905
- encodeU32(out, part.checksum);
906
- encodeBstr(out, data);
907
- return new Uint8Array(out);
908
- }
909
- /** Decode a part from CBOR with data-length and fragment-count caps. */
910
- function decodePart(bytes, maxDataLen, maxFragmentCount) {
911
- const cur = { i: 0 };
912
- if (read(bytes, cur) !== 133) fail("InvalidPartCbor");
913
- const sequence = decodeU32(bytes, cur);
914
- const sequenceCount = decodeU32(bytes, cur);
915
- const messageLength = decodeU32(bytes, cur);
916
- const checksum = decodeU32(bytes, cur);
917
- const data = decodeBstr(bytes, cur, maxDataLen);
918
- if (cur.i !== bytes.length) fail("InvalidPartCbor");
919
- if (sequence === 0) fail("InvalidSequence");
920
- if (sequenceCount === 0 || messageLength === 0 || data.length === 0) fail("EmptyPart");
921
- if (sequenceCount > maxFragmentCount) fail("ResourceLimit", { limit: "fragment_count" });
922
- return Part.fromFields(sequence, sequenceCount, messageLength, checksum, data);
923
- }
924
- function encodeU32(out, v) {
925
- if (v <= 23) out.push(v);
926
- else if (v <= 255) out.push(24, v);
927
- else if (v <= 65535) out.push(25, v >>> 8 & 255, v & 255);
928
- else out.push(26, v >>> 24 & 255, v >>> 16 & 255, v >>> 8 & 255, v & 255);
929
- }
930
- function encodeBstr(out, data) {
931
- const len = data.length;
932
- if (len <= 23) out.push(64 | len);
933
- else if (len <= 255) out.push(88, len);
934
- else if (len <= 65535) out.push(89, len >>> 8 & 255, len & 255);
935
- else out.push(90, len >>> 24 & 255, len >>> 16 & 255, len >>> 8 & 255, len & 255);
936
- for (let i = 0; i < data.length; i++) out.push(data[i]);
937
- }
938
- function decodeU32(bytes, cur) {
939
- const head = read(bytes, cur);
940
- const major = head >> 5;
941
- const ai = head & 31;
942
- if (major !== 0) fail("InvalidPartCbor");
943
- if (ai <= 23) return ai;
944
- if (ai === 24) {
945
- const v = read(bytes, cur);
946
- if (v <= 23) fail("InvalidPartCbor");
947
- return v;
948
- }
949
- if (ai === 25) {
950
- const v = read(bytes, cur) << 8 | read(bytes, cur);
951
- if (v <= 255) fail("InvalidPartCbor");
952
- return v;
953
- }
954
- if (ai === 26) {
955
- const v = (read(bytes, cur) << 24 | read(bytes, cur) << 16 | read(bytes, cur) << 8 | read(bytes, cur)) >>> 0;
956
- if (v <= 65535) fail("InvalidPartCbor");
957
- return v;
958
- }
959
- fail("InvalidPartCbor");
960
- }
961
- function decodeBstr(bytes, cur, maxDataLen) {
962
- const head = read(bytes, cur);
963
- const major = head >> 5;
964
- const ai = head & 31;
965
- if (major !== 2) fail("InvalidPartCbor");
966
- let len;
967
- if (ai <= 23) len = ai;
968
- else if (ai === 24) {
969
- len = read(bytes, cur);
970
- if (len <= 23) fail("InvalidPartCbor");
971
- } else if (ai === 25) {
972
- len = read(bytes, cur) << 8 | read(bytes, cur);
973
- if (len <= 255) fail("InvalidPartCbor");
974
- } else if (ai === 26) {
975
- len = (read(bytes, cur) << 24 | read(bytes, cur) << 16 | read(bytes, cur) << 8 | read(bytes, cur)) >>> 0;
976
- if (len <= 65535) fail("InvalidPartCbor");
977
- } else fail("InvalidPartCbor");
978
- if (len > maxDataLen) fail("ResourceLimit", { limit: "fragment_data" });
979
- if (cur.i + len > bytes.length) fail("InvalidPartCbor");
980
- const data = bytes.slice(cur.i, cur.i + len);
981
- cur.i += len;
982
- return data;
983
- }
984
- function read(bytes, cur) {
985
- if (cur.i >= bytes.length) fail("InvalidPartCbor");
986
- return bytes[cur.i++];
987
- }
988
- //#endregion
989
- //#region src/fountain/part.ts
990
- /** A fountain part (wire metadata + fragment data). */
991
- var Part = class Part {
992
- sequence;
993
- sequenceCount;
994
- messageLength;
995
- checksum;
996
- data;
997
- constructor(sequence, sequenceCount, messageLength, checksum, data) {
998
- this.sequence = sequence;
999
- this.sequenceCount = sequenceCount;
1000
- this.messageLength = messageLength;
1001
- this.checksum = checksum;
1002
- this.data = data;
1003
- }
1004
- static fromFields(sequence, sequenceCount, messageLength, checksum, data) {
1005
- return new Part(sequence, sequenceCount, messageLength, checksum, data);
1006
- }
1007
- indexes() {
1008
- return chooseFragments(this.sequence, this.sequenceCount, this.checksum);
1009
- }
1010
- isSimple() {
1011
- return this.indexes().length === 1;
1012
- }
1013
- toCbor() {
1014
- return encodePart(this);
1015
- }
1016
- static fromCbor(bytes, maxDataLen = DEFAULT_LIMITS.maxFragmentDataLength, maxFragmentCount = DEFAULT_LIMITS.maxFragmentCount) {
1017
- return decodePart(bytes, maxDataLen, maxFragmentCount);
1018
- }
1019
- sequenceId() {
1020
- return `${this.sequence}-${this.sequenceCount}`;
1021
- }
1022
- };
1023
- //#endregion
1024
- //#region src/fountain/decoder.ts
1025
- function keyOf(indexes) {
1026
- return indexes.join(",");
1027
- }
1028
- function xorInto$1(target, src) {
1029
- if (target.length !== src.length) fail("DecoderState");
1030
- for (let i = 0; i < target.length; i++) target[i] ^= src[i];
1031
- }
1032
- /** Fountain decoder with resource limits and fail-closed poison. */
1033
- var FountainDecoder = class {
1034
- decoded = /* @__PURE__ */ new Map();
1035
- received = /* @__PURE__ */ new Set();
1036
- buffer = /* @__PURE__ */ new Map();
1037
- queue = [];
1038
- sequenceCount = 0;
1039
- messageLength = 0;
1040
- messageChecksum = 0;
1041
- fragmentLength = 0;
1042
- limits;
1043
- poisoned;
1044
- constructor(limits) {
1045
- this.limits = mergeLimits(limits);
1046
- }
1047
- get maxFragmentDataLength() {
1048
- return this.limits.maxFragmentDataLength;
1049
- }
1050
- get maxFragmentCount() {
1051
- return this.limits.maxFragmentCount;
1052
- }
1053
- get isPoisoned() {
1054
- return this.poisoned !== void 0;
1055
- }
1056
- get poisonState() {
1057
- return this.poisoned;
1058
- }
1059
- poison(limit) {
1060
- this.poisoned = {
1061
- code: "ResourceLimit",
1062
- limit
1063
- };
1064
- fail("ResourceLimit", { limit });
1065
- }
1066
- escalate(e) {
1067
- if (e instanceof UrError) {
1068
- if (e.code === "ResourceLimit") this.poisoned ??= {
1069
- code: "ResourceLimit",
1070
- limit: e.limit ?? "unknown"
1071
- };
1072
- else if (e.code === "DecoderState") this.poisoned ??= { code: "DecoderState" };
1073
- }
1074
- throw e;
1075
- }
1076
- /**
1077
- * Receive a fountain part.
1078
- * @returns whether the part was newly ingested.
1079
- */
1080
- receive(part) {
1081
- if (this.poisoned) failPoison(this.poisoned);
1082
- if (this.complete) return false;
1083
- if (part.sequenceCount === 0 || part.data.length === 0 || part.messageLength === 0) fail("EmptyPart");
1084
- if (part.sequence === 0) fail("InvalidSequence");
1085
- if (part.data.length > this.limits.maxFragmentDataLength) this.poison("fragment_data");
1086
- if (this.received.size === 0) {
1087
- const sc = part.sequenceCount;
1088
- const ml = part.messageLength;
1089
- if (sc > this.limits.maxFragmentCount) this.poison("fragment_count");
1090
- if (ml > this.limits.maxMessageLength) this.poison("message_length");
1091
- const fragLen = part.data.length;
1092
- const product = fragLen * sc;
1093
- if (!Number.isSafeInteger(product) || product > 4294967295) this.poison("message_length");
1094
- if (product < ml || product - ml >= fragLen) fail("InconsistentPart");
1095
- this.sequenceCount = sc;
1096
- this.messageLength = ml;
1097
- this.messageChecksum = part.checksum;
1098
- this.fragmentLength = fragLen;
1099
- } else if (!this.validate(part)) fail("InconsistentPart");
1100
- const key = keyOf(part.indexes());
1101
- if (this.received.has(key)) return false;
1102
- if (this.received.size >= this.limits.maxReceivedParts) this.poison("received_parts");
1103
- this.received.add(key);
1104
- try {
1105
- if (part.isSimple()) this.enqueueSimple(part);
1106
- else this.processComplex(part);
1107
- this.processQueue();
1108
- } catch (e) {
1109
- this.escalate(e);
1110
- }
1111
- return true;
1112
- }
1113
- enqueueSimple(part) {
1114
- const index = part.indexes()[0];
1115
- if (this.decoded.has(index)) return;
1116
- this.decoded.set(index, part);
1117
- this.queue.push({
1118
- index,
1119
- part
1120
- });
1121
- }
1122
- processQueue() {
1123
- while (this.queue.length > 0) {
1124
- const { index, part: simple } = this.queue.pop();
1125
- const toProcess = [];
1126
- for (const [k, entry] of this.buffer) if (entry.indexes.includes(index)) toProcess.push(k);
1127
- for (const k of toProcess) this.reduceBufferedPart(k, index, simple);
1128
- }
1129
- }
1130
- reduceBufferedPart(key, knownIndex, simple) {
1131
- const entry = this.buffer.get(key);
1132
- if (!entry) fail("DecoderState");
1133
- this.buffer.delete(key);
1134
- const newIndexes = entry.indexes.filter((x) => x !== knownIndex);
1135
- if (newIndexes.length === entry.indexes.length) fail("DecoderState");
1136
- const data = entry.part.data.slice();
1137
- xorInto$1(data, simple.data);
1138
- const reduced = Part.fromFields(entry.part.sequence, entry.part.sequenceCount, entry.part.messageLength, entry.part.checksum, data);
1139
- this.insertReduced(newIndexes, reduced);
1140
- }
1141
- processComplex(part) {
1142
- let indexes = part.indexes().slice();
1143
- const known = indexes.filter((idx) => this.decoded.has(idx));
1144
- if (indexes.length === known.length) return;
1145
- let data = part.data.slice();
1146
- for (const remove of known) {
1147
- indexes = indexes.filter((x) => x !== remove);
1148
- xorInto$1(data, this.decoded.get(remove).data);
1149
- }
1150
- const reduced = Part.fromFields(part.sequence, part.sequenceCount, part.messageLength, part.checksum, data);
1151
- this.insertReduced(indexes, reduced);
1152
- }
1153
- insertReduced(indexes, part) {
1154
- if (indexes.length === 1) {
1155
- const idx = indexes[0];
1156
- if (this.decoded.has(idx)) return;
1157
- this.decoded.set(idx, part);
1158
- this.queue.push({
1159
- index: idx,
1160
- part
1161
- });
1162
- return;
1163
- }
1164
- const key = keyOf(indexes);
1165
- if (!this.buffer.has(key) && this.buffer.size >= this.limits.maxBufferParts) this.poison("buffer_parts");
1166
- this.buffer.set(key, {
1167
- indexes,
1168
- part
1169
- });
1170
- }
1171
- get complete() {
1172
- return this.messageLength !== 0 && this.decoded.size === this.sequenceCount;
1173
- }
1174
- resolvedFragmentCount() {
1175
- return this.messageLength === 0 ? void 0 : this.decoded.size;
1176
- }
1177
- get fragmentCount() {
1178
- return this.sequenceCount;
1179
- }
1180
- validate(part) {
1181
- if (this.received.size === 0) return false;
1182
- return part.sequenceCount === this.sequenceCount && part.messageLength === this.messageLength && part.checksum === this.messageChecksum && part.data.length === this.fragmentLength;
1183
- }
1184
- /** Decoded message if complete; otherwise `undefined`. */
1185
- message() {
1186
- if (this.poisoned) failPoison(this.poisoned);
1187
- if (!this.complete) return void 0;
1188
- const combined = new Uint8Array(this.fragmentLength * this.sequenceCount);
1189
- for (let idx = 0; idx < this.sequenceCount; idx++) {
1190
- const part = this.decoded.get(idx);
1191
- if (!part) fail("DecoderState");
1192
- combined.set(part.data, idx * this.fragmentLength);
1193
- }
1194
- for (let i = this.messageLength; i < combined.length; i++) if (combined[i] !== 0) fail("InvalidPadding");
1195
- const message = combined.subarray(0, this.messageLength);
1196
- if (checksum(message) !== this.messageChecksum) fail("InvalidMessageChecksum");
1197
- return message.slice();
1198
- }
1199
- };
1200
- //#endregion
1201
- //#region src/fountain/encoder.ts
1202
- function xorInto(target, src) {
1203
- if (target.length !== src.length) fail("DecoderState");
1204
- for (let i = 0; i < target.length; i++) target[i] ^= src[i];
1205
- }
1206
- /** Next 1-based fountain seqNum. Does not wrap. */
1207
- function nextSequence(current) {
1208
- if (current === 4294967295) fail("ResourceLimit", { limit: "sequence" });
1209
- return current + 1;
1210
- }
1211
- /** Fountain encoder. */
1212
- var FountainEncoder = class FountainEncoder {
1213
- parts;
1214
- sequenceCount;
1215
- messageLength;
1216
- messageChecksum;
1217
- currentSequence = 0;
1218
- constructor(parts, sequenceCount, messageLength, messageChecksum) {
1219
- this.parts = parts;
1220
- this.sequenceCount = sequenceCount;
1221
- this.messageLength = messageLength;
1222
- this.messageChecksum = messageChecksum;
1223
- }
1224
- static create(message, maxFragmentLength) {
1225
- if (message.length === 0) fail("EmptyMessage");
1226
- if (maxFragmentLength === 0) fail("InvalidFragmentLen");
1227
- if (message.length > 4294967295) fail("ResourceLimit", { limit: "message_length" });
1228
- const fragments = partition(message, fragmentLength(message.length, maxFragmentLength));
1229
- if (fragments.length > 4294967295) fail("ResourceLimit", { limit: "fragment_count" });
1230
- return new FountainEncoder(fragments, fragments.length, message.length, checksum(message));
1231
- }
1232
- get currentSequenceNum() {
1233
- return this.currentSequence;
1234
- }
1235
- get fragmentCount() {
1236
- return this.sequenceCount;
1237
- }
1238
- get complete() {
1239
- return this.currentSequence >= this.sequenceCount;
1240
- }
1241
- nextPart() {
1242
- if (this.sequenceCount === 1 && this.currentSequence >= 1) fail("SinglePartExhausted");
1243
- this.currentSequence = nextSequence(this.currentSequence);
1244
- const indexes = chooseFragments(this.currentSequence, this.parts.length, this.messageChecksum);
1245
- const first = this.parts[0];
1246
- const mixed = new Uint8Array(first.length);
1247
- for (const idx of indexes) xorInto(mixed, this.parts[idx]);
1248
- return Part.fromFields(this.currentSequence, this.sequenceCount, this.messageLength, this.messageChecksum, mixed);
1249
- }
1250
- };
1251
- //#endregion
1252
- //#region src/ur/type.ts
1253
- /** Validated UR type token (stored lowercase, `[a-z0-9-]+`). */
1254
- var UrType = class UrType {
1255
- value;
1256
- constructor(value) {
1257
- this.value = value;
1258
- }
1259
- static parse(s) {
1260
- const lower = s.toLowerCase();
1261
- if (lower.length === 0 || !/^[a-z0-9-]+$/.test(lower)) fail("InvalidType");
1262
- return new UrType(lower);
1263
- }
1264
- static bytes() {
1265
- return new UrType("bytes");
1266
- }
1267
- equals(other) {
1268
- return this.value === other.value;
1269
- }
1270
- };
1271
- //#endregion
1272
- //#region src/ur/parse.ts
1273
- /** Lowercase a UR string for case-insensitive QR transport. */
1274
- function normalizeUr(uri) {
1275
- return uri.toLowerCase();
1276
- }
1277
- /** Parse a UR (full-URI case fold). Does not decode bytewords. */
1278
- function parse(uri) {
1279
- return parseNormalized(normalizeUr(uri));
1280
- }
1281
- /** Parse an already-lowercased (or body-normalized) UR. */
1282
- function parseNormalized(uri) {
1283
- if (!uri.startsWith("ur:")) fail("InvalidScheme");
1284
- const rest0 = uri.slice(3);
1285
- const slash = rest0.indexOf("/");
1286
- if (slash < 0) fail("TypeUnspecified");
1287
- const typeStr = rest0.slice(0, slash);
1288
- const rest = rest0.slice(slash + 1);
1289
- const urType = UrType.parse(typeStr);
1290
- const lastSlash = rest.lastIndexOf("/");
1291
- if (lastSlash < 0) return {
1292
- type: urType,
1293
- kind: "single",
1294
- body: rest.toLowerCase()
1295
- };
1296
- const indicesStr = rest.slice(0, lastSlash);
1297
- const body = rest.slice(lastSlash + 1).toLowerCase();
1298
- return {
1299
- type: urType,
1300
- kind: "multi",
1301
- indices: decodeIndices(indicesStr),
1302
- body
1303
- };
1304
- }
1305
- function decodeIndices(indices) {
1306
- const dash = indices.indexOf("-");
1307
- if (dash < 0) fail("InvalidIndices");
1308
- const a = indices.slice(0, dash);
1309
- const b = indices.slice(dash + 1);
1310
- if (!/^\d+$/.test(a) || !/^\d+$/.test(b)) fail("InvalidIndices");
1311
- const seq = Number(a);
1312
- const count = Number(b);
1313
- if (!Number.isSafeInteger(seq) || !Number.isSafeInteger(count)) fail("InvalidIndices");
1314
- if (seq === 0 || count === 0) fail("InvalidIndices");
1315
- if (seq > 4294967295 || count > 4294967295) fail("InvalidIndices");
1316
- return {
1317
- seq,
1318
- count
1319
- };
1320
- }
1321
- //#endregion
1322
- //#region src/ur/index.ts
1323
- /** Encode a single-part UR. Empty data is allowed. */
1324
- function encode(data, type) {
1325
- const body = encode$1(data, "minimal");
1326
- return `ur:${type.value}/${body}`;
1327
- }
1328
- /**
1329
- * Decode payload from a single- or multi-part UR.
1330
- * Multi-part returns the CBOR-encoded fountain part bytes, not the message.
1331
- */
1332
- function decode(uri) {
1333
- const parsed = parse(uri);
1334
- const payload = decode$1(parsed.body, "minimal");
1335
- return {
1336
- kind: parsed.kind,
1337
- payload
1338
- };
1339
- }
1340
- /** Like {@link decode} but retains the normalized type. */
1341
- function decodeWithType(uri) {
1342
- const parsed = parse(uri);
1343
- const payload = decode$1(parsed.body, "minimal");
1344
- return {
1345
- type: parsed.type,
1346
- kind: parsed.kind,
1347
- payload
1348
- };
1349
- }
1350
- /** Decode a single-part UR payload. Multi-part URIs throw `NotSinglePart`. */
1351
- function decodeMessage(uri) {
1352
- const { kind, payload } = decode(uri);
1353
- if (kind !== "single") fail("NotSinglePart");
1354
- return payload;
1355
- }
1356
- /** Uppercase UR string for denser QR alphanumeric mode. */
1357
- function toQrString(uri) {
1358
- return uri.toUpperCase();
1359
- }
1360
- /** UR encoder. `K == 1` emits single-part; otherwise fountain. */
1361
- var Encoder = class Encoder {
1362
- fountain;
1363
- urType;
1364
- message;
1365
- singleEmitted = false;
1366
- constructor(fountain, urType, message) {
1367
- this.fountain = fountain;
1368
- this.urType = urType;
1369
- this.message = message;
1370
- }
1371
- static create(message, maxFragmentLength, type) {
1372
- return new Encoder(FountainEncoder.create(message, maxFragmentLength), type, message.slice());
1373
- }
1374
- static bytes(message, maxFragmentLength) {
1375
- return Encoder.create(message, maxFragmentLength, UrType.bytes());
1376
- }
1377
- get isSinglePart() {
1378
- return this.fountain.fragmentCount === 1;
1379
- }
1380
- get fragmentCount() {
1381
- return this.fountain.fragmentCount;
1382
- }
1383
- get currentIndex() {
1384
- return this.isSinglePart ? this.singleEmitted ? 1 : 0 : this.fountain.currentSequenceNum;
1385
- }
1386
- get complete() {
1387
- return this.isSinglePart ? this.singleEmitted : this.fountain.complete;
1388
- }
1389
- nextPart() {
1390
- if (this.isSinglePart) {
1391
- this.singleEmitted = true;
1392
- return encode(this.message, this.urType);
1393
- }
1394
- const part = this.fountain.nextPart();
1395
- const body = encode$1(part.toCbor(), "minimal");
1396
- return `ur:${this.urType.value}/${part.sequenceId()}/${body}`;
1397
- }
1398
- };
1399
- /** UR decoder with type stickiness and URI limits. */
1400
- var Decoder = class {
1401
- fountain;
1402
- maxUriLen;
1403
- maxMessageLength;
1404
- expectedType;
1405
- seenType;
1406
- single;
1407
- poisoned;
1408
- constructor(options) {
1409
- const limits = mergeLimits(options?.limits);
1410
- this.fountain = new FountainDecoder(limits);
1411
- this.maxUriLen = limits.maxUriLen;
1412
- this.maxMessageLength = limits.maxMessageLength;
1413
- this.expectedType = options?.expectedType;
1414
- }
1415
- poison(limit) {
1416
- this.poisoned = {
1417
- code: "ResourceLimit",
1418
- limit
1419
- };
1420
- fail("ResourceLimit", { limit });
1421
- }
1422
- escalate(e) {
1423
- if (e instanceof UrError) {
1424
- if (e.code === "ResourceLimit") this.poisoned ??= {
1425
- code: "ResourceLimit",
1426
- limit: e.limit ?? "unknown"
1427
- };
1428
- else if (e.code === "DecoderState") this.poisoned ??= { code: "DecoderState" };
1429
- }
1430
- throw e;
1431
- }
1432
- get poisonState() {
1433
- return this.poisoned ?? this.fountain.poisonState;
1434
- }
1435
- receive(uri) {
1436
- if (this.poisoned) failPoison(this.poisoned);
1437
- if (this.fountain.isPoisoned) {
1438
- this.poisoned ??= this.fountain.poisonState;
1439
- failPoison(this.poisoned);
1440
- }
1441
- if (uri.length > this.maxUriLen) this.poison("uri_len");
1442
- const parsed = parse(uri);
1443
- if (this.expectedType && !parsed.type.equals(this.expectedType)) fail("UnexpectedType", {
1444
- expected: this.expectedType.value,
1445
- found: parsed.type.value
1446
- });
1447
- if (this.seenType && !this.seenType.equals(parsed.type)) fail("UnexpectedType", {
1448
- expected: this.seenType.value,
1449
- found: parsed.type.value
1450
- });
1451
- try {
1452
- if (parsed.kind === "single") this.receiveSingle(parsed);
1453
- else this.receiveFountain(parsed);
1454
- } catch (e) {
1455
- this.escalate(e);
1456
- }
1457
- }
1458
- receiveSingle(parsed) {
1459
- if (this.fountain.resolvedFragmentCount() !== void 0) fail("InconsistentPart");
1460
- if (this.single !== void 0) return;
1461
- const data = decode$1(parsed.body, "minimal");
1462
- if (data.length > this.maxMessageLength) this.poison("message_length");
1463
- this.seenType = parsed.type;
1464
- this.single = data;
1465
- }
1466
- receiveFountain(parsed) {
1467
- if (this.single !== void 0) fail("InconsistentPart");
1468
- const decoded = decode$1(parsed.body, "minimal");
1469
- const part = Part.fromCbor(decoded, this.fountain.maxFragmentDataLength, this.fountain.maxFragmentCount);
1470
- const indices = parsed.indices;
1471
- if (!indices) fail("InvalidIndices");
1472
- if (part.sequence !== indices.seq || part.sequenceCount !== indices.count) fail("InvalidIndices");
1473
- this.fountain.receive(part);
1474
- this.seenType ??= parsed.type;
1475
- }
1476
- get complete() {
1477
- return this.single !== void 0 || this.fountain.complete;
1478
- }
1479
- message() {
1480
- if (this.poisoned) failPoison(this.poisoned);
1481
- if (this.fountain.isPoisoned) failPoison(this.fountain.poisonState);
1482
- if (this.single) return this.single.slice();
1483
- return this.fountain.message();
1484
- }
1485
- resolvedFragmentCount() {
1486
- if (this.single) return 1;
1487
- return this.fountain.resolvedFragmentCount();
1488
- }
1489
- get fragmentCount() {
1490
- return this.single ? 1 : this.fountain.fragmentCount;
1491
- }
1492
- get type() {
1493
- return this.seenType;
1494
- }
1495
- get isPoisoned() {
1496
- return this.poisoned !== void 0 || this.fountain.isPoisoned;
1497
- }
1498
- };
1499
- //#endregion
1500
- export { fail as C, UrError as S, canonicalizeByteword as _, decodeWithType as a, encodeRaw as b, normalizeUr as c, UrType as d, FountainEncoder as f, bytewords_exports as g, DEFAULT_LIMITS as h, decodeMessage as i, parse as l, Part as m, Encoder as n, encode as o, FountainDecoder as p, decode as r, toQrString as s, Decoder as t, parseNormalized as u, decode$1 as v, failPoison as w, checksum as x, encode$1 as y };