@multitapio/multitap 0.0.1 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/channel.d.ts +18 -10
- package/dist/channel.d.ts.map +1 -1
- package/dist/diagnostics.js +1354 -92
- package/dist/lib.js +678 -137
- package/dist/react/providers/SessionProvider.d.ts.map +1 -1
- package/dist/session-config.d.ts +1 -1
- package/dist/session.d.ts +2 -5
- package/dist/session.d.ts.map +1 -1
- package/dist/state.d.ts +4 -1
- package/dist/state.d.ts.map +1 -1
- package/dist/types/channel.d.ts +18 -10
- package/dist/types/channel.d.ts.map +1 -1
- package/dist/types/react/providers/SessionProvider.d.ts.map +1 -1
- package/dist/types/session-config.d.ts +1 -1
- package/dist/types/session.d.ts +2 -5
- package/dist/types/session.d.ts.map +1 -1
- package/dist/types/state.d.ts +4 -1
- package/dist/types/state.d.ts.map +1 -1
- package/dist/types/webrtc-channel.d.ts +79 -0
- package/dist/types/webrtc-channel.d.ts.map +1 -0
- package/dist/webrtc-channel.d.ts +79 -0
- package/dist/webrtc-channel.d.ts.map +1 -0
- package/package.json +2 -2
package/dist/diagnostics.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
|
|
1
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
|
|
2
2
|
function isBytes(a) {
|
|
3
3
|
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
4
4
|
}
|
|
@@ -64,7 +64,7 @@ function createHasher(hashCons) {
|
|
|
64
64
|
return hashC;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
|
|
67
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
|
|
68
68
|
function setBigUint64(view, byteOffset, value, isLE) {
|
|
69
69
|
if (typeof view.setBigUint64 === "function")
|
|
70
70
|
return view.setBigUint64(byteOffset, value, isLE);
|
|
@@ -184,7 +184,7 @@ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
|
184
184
|
1541459225
|
|
185
185
|
]);
|
|
186
186
|
|
|
187
|
-
// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
|
|
187
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
|
|
188
188
|
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
189
189
|
1116352408,
|
|
190
190
|
1899447441,
|
|
@@ -324,10 +324,10 @@ var SHA256 = class extends HashMD {
|
|
|
324
324
|
};
|
|
325
325
|
var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
|
|
326
326
|
|
|
327
|
-
// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js
|
|
327
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js
|
|
328
328
|
var sha2562 = sha256;
|
|
329
329
|
|
|
330
|
-
// node_modules/.pnpm/@noble+secp256k1@2.3.0/node_modules/@noble/secp256k1/index.js
|
|
330
|
+
// ../../node_modules/.pnpm/@noble+secp256k1@2.3.0/node_modules/@noble/secp256k1/index.js
|
|
331
331
|
var secp256k1_CURVE = {
|
|
332
332
|
p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,
|
|
333
333
|
n: 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,
|
|
@@ -413,6 +413,12 @@ var invert = (num, md) => {
|
|
|
413
413
|
}
|
|
414
414
|
return b === 1n ? M(x, md) : err("no inverse");
|
|
415
415
|
};
|
|
416
|
+
var callHash = (name) => {
|
|
417
|
+
const fn = etc[name];
|
|
418
|
+
if (typeof fn !== "function")
|
|
419
|
+
err("hashes." + name + " not set");
|
|
420
|
+
return fn;
|
|
421
|
+
};
|
|
416
422
|
var apoint = (p) => p instanceof Point ? p : err("Point expected");
|
|
417
423
|
var koblitz = (x) => M(M(x * x) * x + _b);
|
|
418
424
|
var afield0 = (n) => arange(n, 0n, P);
|
|
@@ -688,6 +694,112 @@ var bits2int = (bytes) => {
|
|
|
688
694
|
return delta > 0 ? num >> big(delta) : num;
|
|
689
695
|
};
|
|
690
696
|
var bits2int_modN = (bytes) => modN(bits2int(abytes2(bytes)));
|
|
697
|
+
var signOpts = { lowS: true };
|
|
698
|
+
var prepSig = (msgh, priv, opts = signOpts) => {
|
|
699
|
+
if (["der", "recovered", "canonical"].some((k) => k in opts))
|
|
700
|
+
err("option not supported");
|
|
701
|
+
let { lowS, extraEntropy } = opts;
|
|
702
|
+
if (lowS == null)
|
|
703
|
+
lowS = true;
|
|
704
|
+
const i2o = numTo32b;
|
|
705
|
+
const h1i = bits2int_modN(toU8(msgh));
|
|
706
|
+
const h1o = i2o(h1i);
|
|
707
|
+
const d = toPrivScalar(priv);
|
|
708
|
+
const seed = [i2o(d), h1o];
|
|
709
|
+
if (extraEntropy)
|
|
710
|
+
seed.push(extraEntropy === true ? randomBytes(L) : toU8(extraEntropy));
|
|
711
|
+
const m = h1i;
|
|
712
|
+
const k2sig = (kBytes) => {
|
|
713
|
+
const k = bits2int(kBytes);
|
|
714
|
+
if (!(1n <= k && k < N))
|
|
715
|
+
return;
|
|
716
|
+
const q = G.multiply(k).toAffine();
|
|
717
|
+
const r = modN(q.x);
|
|
718
|
+
if (r === 0n)
|
|
719
|
+
return;
|
|
720
|
+
const ik = invert(k, N);
|
|
721
|
+
const s = modN(ik * modN(m + modN(d * r)));
|
|
722
|
+
if (s === 0n)
|
|
723
|
+
return;
|
|
724
|
+
let normS = s;
|
|
725
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & 1n);
|
|
726
|
+
if (lowS && highS(s)) {
|
|
727
|
+
normS = modN(-s);
|
|
728
|
+
recovery ^= 1;
|
|
729
|
+
}
|
|
730
|
+
return new Signature(r, normS, recovery);
|
|
731
|
+
};
|
|
732
|
+
return { seed: concatBytes(...seed), k2sig };
|
|
733
|
+
};
|
|
734
|
+
var hmacDrbg = (asynchronous) => {
|
|
735
|
+
let v = u8n(L);
|
|
736
|
+
let k = u8n(L);
|
|
737
|
+
let i = 0;
|
|
738
|
+
const NULL = u8n(0);
|
|
739
|
+
const reset = () => {
|
|
740
|
+
v.fill(1);
|
|
741
|
+
k.fill(0);
|
|
742
|
+
i = 0;
|
|
743
|
+
};
|
|
744
|
+
const max = 1e3;
|
|
745
|
+
const _e = "drbg: tried 1000 values";
|
|
746
|
+
if (asynchronous) {
|
|
747
|
+
const h = (...b) => etc.hmacSha256Async(k, v, ...b);
|
|
748
|
+
const reseed = async (seed = NULL) => {
|
|
749
|
+
k = await h(u8of(0), seed);
|
|
750
|
+
v = await h();
|
|
751
|
+
if (seed.length === 0)
|
|
752
|
+
return;
|
|
753
|
+
k = await h(u8of(1), seed);
|
|
754
|
+
v = await h();
|
|
755
|
+
};
|
|
756
|
+
const gen = async () => {
|
|
757
|
+
if (i++ >= max)
|
|
758
|
+
err(_e);
|
|
759
|
+
v = await h();
|
|
760
|
+
return v;
|
|
761
|
+
};
|
|
762
|
+
return async (seed, pred) => {
|
|
763
|
+
reset();
|
|
764
|
+
await reseed(seed);
|
|
765
|
+
let res = void 0;
|
|
766
|
+
while (!(res = pred(await gen())))
|
|
767
|
+
await reseed();
|
|
768
|
+
reset();
|
|
769
|
+
return res;
|
|
770
|
+
};
|
|
771
|
+
} else {
|
|
772
|
+
const h = (...b) => callHash("hmacSha256Sync")(k, v, ...b);
|
|
773
|
+
const reseed = (seed = NULL) => {
|
|
774
|
+
k = h(u8of(0), seed);
|
|
775
|
+
v = h();
|
|
776
|
+
if (seed.length === 0)
|
|
777
|
+
return;
|
|
778
|
+
k = h(u8of(1), seed);
|
|
779
|
+
v = h();
|
|
780
|
+
};
|
|
781
|
+
const gen = () => {
|
|
782
|
+
if (i++ >= max)
|
|
783
|
+
err(_e);
|
|
784
|
+
v = h();
|
|
785
|
+
return v;
|
|
786
|
+
};
|
|
787
|
+
return (seed, pred) => {
|
|
788
|
+
reset();
|
|
789
|
+
reseed(seed);
|
|
790
|
+
let res = void 0;
|
|
791
|
+
while (!(res = pred(gen())))
|
|
792
|
+
reseed();
|
|
793
|
+
reset();
|
|
794
|
+
return res;
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
var sign = (msgh, priv, opts = signOpts) => {
|
|
799
|
+
const { seed, k2sig } = prepSig(msgh, priv, opts);
|
|
800
|
+
const sig = hmacDrbg(false)(seed, k2sig);
|
|
801
|
+
return sig;
|
|
802
|
+
};
|
|
691
803
|
var recoverPublicKey = (sig, msgh) => {
|
|
692
804
|
const { r, s, recovery } = sig;
|
|
693
805
|
if (![0, 1, 2, 3].includes(recovery))
|
|
@@ -801,7 +913,7 @@ var wNAF = (n) => {
|
|
|
801
913
|
return { p, f };
|
|
802
914
|
};
|
|
803
915
|
|
|
804
|
-
// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
|
|
916
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
|
|
805
917
|
var HMAC = class extends Hash {
|
|
806
918
|
constructor(hash, _key) {
|
|
807
919
|
super();
|
|
@@ -869,7 +981,7 @@ var HMAC = class extends Hash {
|
|
|
869
981
|
var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
|
|
870
982
|
hmac.create = (hash, key) => new HMAC(hash, key);
|
|
871
983
|
|
|
872
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/is.js
|
|
984
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/is.js
|
|
873
985
|
var typeofs = [
|
|
874
986
|
"string",
|
|
875
987
|
"number",
|
|
@@ -952,7 +1064,7 @@ function getObjectType(value) {
|
|
|
952
1064
|
return void 0;
|
|
953
1065
|
}
|
|
954
1066
|
|
|
955
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/token.js
|
|
1067
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/token.js
|
|
956
1068
|
var Type = class {
|
|
957
1069
|
/**
|
|
958
1070
|
* @param {number} major
|
|
@@ -1009,7 +1121,7 @@ var Token = class {
|
|
|
1009
1121
|
}
|
|
1010
1122
|
};
|
|
1011
1123
|
|
|
1012
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/byte-utils.js
|
|
1124
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/byte-utils.js
|
|
1013
1125
|
var useBuffer = globalThis.process && // @ts-ignore
|
|
1014
1126
|
!globalThis.process.browser && // @ts-ignore
|
|
1015
1127
|
globalThis.Buffer && // @ts-ignore
|
|
@@ -1263,7 +1375,7 @@ function decodeCodePointsArray(codePoints) {
|
|
|
1263
1375
|
return res;
|
|
1264
1376
|
}
|
|
1265
1377
|
|
|
1266
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/bl.js
|
|
1378
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/bl.js
|
|
1267
1379
|
var defaultChunkSize = 256;
|
|
1268
1380
|
var Bl = class {
|
|
1269
1381
|
/**
|
|
@@ -1344,7 +1456,7 @@ var Bl = class {
|
|
|
1344
1456
|
}
|
|
1345
1457
|
};
|
|
1346
1458
|
|
|
1347
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/common.js
|
|
1459
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/common.js
|
|
1348
1460
|
var decodeErrPrefix = "CBOR decode error:";
|
|
1349
1461
|
var encodeErrPrefix = "CBOR encode error:";
|
|
1350
1462
|
var uintMinorPrefixBytes = [];
|
|
@@ -1359,7 +1471,7 @@ function assertEnoughData(data, pos, need) {
|
|
|
1359
1471
|
}
|
|
1360
1472
|
}
|
|
1361
1473
|
|
|
1362
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/0uint.js
|
|
1474
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/0uint.js
|
|
1363
1475
|
var uintBoundaries = [24, 256, 65536, 4294967296, BigInt("18446744073709551616")];
|
|
1364
1476
|
function readUint8(data, offset, options) {
|
|
1365
1477
|
assertEnoughData(data, offset, 1);
|
|
@@ -1480,7 +1592,7 @@ encodeUint.compareTokens = function compareTokens(tok1, tok2) {
|
|
|
1480
1592
|
);
|
|
1481
1593
|
};
|
|
1482
1594
|
|
|
1483
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/1negint.js
|
|
1595
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/1negint.js
|
|
1484
1596
|
function decodeNegint8(data, pos, _minor, options) {
|
|
1485
1597
|
return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2);
|
|
1486
1598
|
}
|
|
@@ -1534,7 +1646,7 @@ encodeNegint.compareTokens = function compareTokens2(tok1, tok2) {
|
|
|
1534
1646
|
);
|
|
1535
1647
|
};
|
|
1536
1648
|
|
|
1537
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/2bytes.js
|
|
1649
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/2bytes.js
|
|
1538
1650
|
function toToken(data, pos, prefix, length) {
|
|
1539
1651
|
assertEnoughData(data, pos, prefix + length);
|
|
1540
1652
|
const buf2 = slice(data, pos + prefix, pos + prefix + length);
|
|
@@ -1581,7 +1693,7 @@ function compareBytes(b1, b2) {
|
|
|
1581
1693
|
return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
|
|
1582
1694
|
}
|
|
1583
1695
|
|
|
1584
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/3string.js
|
|
1696
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/3string.js
|
|
1585
1697
|
function toToken2(data, pos, prefix, length, options) {
|
|
1586
1698
|
const totLength = prefix + length;
|
|
1587
1699
|
assertEnoughData(data, pos, totLength);
|
|
@@ -1612,7 +1724,7 @@ function decodeString64(data, pos, _minor, options) {
|
|
|
1612
1724
|
}
|
|
1613
1725
|
var encodeString = encodeBytes;
|
|
1614
1726
|
|
|
1615
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/4array.js
|
|
1727
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/4array.js
|
|
1616
1728
|
function toToken3(_data, _pos, prefix, length) {
|
|
1617
1729
|
return new Token(Type.array, length, prefix);
|
|
1618
1730
|
}
|
|
@@ -1649,7 +1761,7 @@ encodeArray.encodedSize = function encodedSize5(token) {
|
|
|
1649
1761
|
return encodeUintValue.encodedSize(token.value);
|
|
1650
1762
|
};
|
|
1651
1763
|
|
|
1652
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/5map.js
|
|
1764
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/5map.js
|
|
1653
1765
|
function toToken4(_data, _pos, prefix, length) {
|
|
1654
1766
|
return new Token(Type.map, length, prefix);
|
|
1655
1767
|
}
|
|
@@ -1686,7 +1798,7 @@ encodeMap.encodedSize = function encodedSize6(token) {
|
|
|
1686
1798
|
return encodeUintValue.encodedSize(token.value);
|
|
1687
1799
|
};
|
|
1688
1800
|
|
|
1689
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/6tag.js
|
|
1801
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/6tag.js
|
|
1690
1802
|
function decodeTagCompact(_data, _pos, minor, _options) {
|
|
1691
1803
|
return new Token(Type.tag, minor, 1);
|
|
1692
1804
|
}
|
|
@@ -1710,7 +1822,7 @@ encodeTag.encodedSize = function encodedSize7(token) {
|
|
|
1710
1822
|
return encodeUintValue.encodedSize(token.value);
|
|
1711
1823
|
};
|
|
1712
1824
|
|
|
1713
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/7float.js
|
|
1825
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/7float.js
|
|
1714
1826
|
var MINOR_FALSE = 20;
|
|
1715
1827
|
var MINOR_TRUE = 21;
|
|
1716
1828
|
var MINOR_NULL = 22;
|
|
@@ -1886,7 +1998,7 @@ function readFloat64(ui8a2, pos) {
|
|
|
1886
1998
|
}
|
|
1887
1999
|
encodeFloat.compareTokens = encodeUint.compareTokens;
|
|
1888
2000
|
|
|
1889
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/jump.js
|
|
2001
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/jump.js
|
|
1890
2002
|
function invalidMinor(data, pos, minor) {
|
|
1891
2003
|
throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`);
|
|
1892
2004
|
}
|
|
@@ -2042,7 +2154,7 @@ function quickEncodeToken(token) {
|
|
|
2042
2154
|
}
|
|
2043
2155
|
}
|
|
2044
2156
|
|
|
2045
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/encode.js
|
|
2157
|
+
// ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/encode.js
|
|
2046
2158
|
var rfc8949EncodeOptions = Object.freeze({
|
|
2047
2159
|
float64: true,
|
|
2048
2160
|
mapSorter: rfc8949MapSorter,
|
|
@@ -2344,10 +2456,6 @@ function encodeCustom(data, encoders, options) {
|
|
|
2344
2456
|
return buf.toBytes(true);
|
|
2345
2457
|
}
|
|
2346
2458
|
|
|
2347
|
-
// node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/decode.js
|
|
2348
|
-
var DONE = Symbol.for("DONE");
|
|
2349
|
-
var BREAK = Symbol.for("BREAK");
|
|
2350
|
-
|
|
2351
2459
|
// src/utils.ts
|
|
2352
2460
|
function uint8ArrayToBase64(data) {
|
|
2353
2461
|
const dataWithToBase64 = data;
|
|
@@ -2389,10 +2497,19 @@ function base64URLToString(str) {
|
|
|
2389
2497
|
const decoder = new TextDecoder();
|
|
2390
2498
|
return decoder.decode(bytes);
|
|
2391
2499
|
}
|
|
2500
|
+
function arraysEqual(a, b) {
|
|
2501
|
+
if (a.length !== b.length) return false;
|
|
2502
|
+
for (let i = 0; i < a.length; i++) {
|
|
2503
|
+
if (a[i] !== b[i]) return false;
|
|
2504
|
+
}
|
|
2505
|
+
return true;
|
|
2506
|
+
}
|
|
2392
2507
|
|
|
2393
2508
|
// src/crypto.ts
|
|
2394
2509
|
etc.hmacSha256Sync = (k, ...m) => hmac(sha2562, k, etc.concatBytes(...m));
|
|
2395
2510
|
var SIGNATURE_SIZE = 65;
|
|
2511
|
+
var HASH_SIZE = 32;
|
|
2512
|
+
var INPUT_HEADER_SIZE = 5;
|
|
2396
2513
|
var GENESIS_HASH_SIZE = 16;
|
|
2397
2514
|
function generateKeyPair() {
|
|
2398
2515
|
return utils.randomPrivateKey();
|
|
@@ -2400,6 +2517,18 @@ function generateKeyPair() {
|
|
|
2400
2517
|
function pubKeyFromPrivate(privateKey) {
|
|
2401
2518
|
return getPublicKey(privateKey, true);
|
|
2402
2519
|
}
|
|
2520
|
+
function sign2(privateKey, messageHash) {
|
|
2521
|
+
const sig = sign(messageHash, privateKey, { lowS: true });
|
|
2522
|
+
const recovery = sig.recovery;
|
|
2523
|
+
if (recovery === void 0) {
|
|
2524
|
+
throw new Error("Recovery ID not available");
|
|
2525
|
+
}
|
|
2526
|
+
const result = new Uint8Array(SIGNATURE_SIZE);
|
|
2527
|
+
const compactSig = sig.toCompactRawBytes();
|
|
2528
|
+
result.set(compactSig, 0);
|
|
2529
|
+
result[64] = recovery;
|
|
2530
|
+
return result;
|
|
2531
|
+
}
|
|
2403
2532
|
function recoverPubKey(messageHash, signature) {
|
|
2404
2533
|
if (signature.length !== SIGNATURE_SIZE) {
|
|
2405
2534
|
throw new Error(`Signature must be ${SIGNATURE_SIZE} bytes`);
|
|
@@ -2413,6 +2542,14 @@ function recoverPubKey(messageHash, signature) {
|
|
|
2413
2542
|
const pubKey = sig.recoverPublicKey(messageHash);
|
|
2414
2543
|
return pubKey.toRawBytes(true);
|
|
2415
2544
|
}
|
|
2545
|
+
function verifySignature(pubKey, messageHash, signature) {
|
|
2546
|
+
try {
|
|
2547
|
+
const recoveredPubKey = recoverPubKey(messageHash, signature);
|
|
2548
|
+
return arraysEqual(recoveredPubKey, pubKey);
|
|
2549
|
+
} catch {
|
|
2550
|
+
return false;
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2416
2553
|
function sessionCompatibilityHash(data) {
|
|
2417
2554
|
const fullHash = sha2562(data);
|
|
2418
2555
|
return fullHash.slice(0, 8);
|
|
@@ -2425,6 +2562,36 @@ function hashInputMessage(genesisHash, targetTick, payload) {
|
|
|
2425
2562
|
buf2.set(payload, 20);
|
|
2426
2563
|
return sha2562(buf2);
|
|
2427
2564
|
}
|
|
2565
|
+
function hashTickMessage(genesisHash, tickNum, inputsHash, prevTickSig) {
|
|
2566
|
+
const buf2 = new Uint8Array(16 + 4 + HASH_SIZE + SIGNATURE_SIZE);
|
|
2567
|
+
buf2.set(genesisHash, 0);
|
|
2568
|
+
const view = new DataView(buf2.buffer);
|
|
2569
|
+
view.setUint32(16, tickNum, true);
|
|
2570
|
+
buf2.set(inputsHash, 20);
|
|
2571
|
+
buf2.set(prevTickSig, 20 + HASH_SIZE);
|
|
2572
|
+
return sha2562(buf2);
|
|
2573
|
+
}
|
|
2574
|
+
function hashInputs(inputs) {
|
|
2575
|
+
if (inputs.length === 0) {
|
|
2576
|
+
return new Uint8Array(HASH_SIZE);
|
|
2577
|
+
}
|
|
2578
|
+
let totalSize = 0;
|
|
2579
|
+
for (const input of inputs) {
|
|
2580
|
+
totalSize += INPUT_HEADER_SIZE + input.payload.length + SIGNATURE_SIZE;
|
|
2581
|
+
}
|
|
2582
|
+
const data = new Uint8Array(totalSize);
|
|
2583
|
+
const view = new DataView(data.buffer);
|
|
2584
|
+
let offset = 0;
|
|
2585
|
+
for (const input of inputs) {
|
|
2586
|
+
const payloadLen = input.payload.length;
|
|
2587
|
+
view.setUint32(offset, input.targetTick, true);
|
|
2588
|
+
view.setUint8(offset + 4, payloadLen);
|
|
2589
|
+
data.set(input.payload, offset + 5);
|
|
2590
|
+
data.set(input.sig, offset + 5 + payloadLen);
|
|
2591
|
+
offset += INPUT_HEADER_SIZE + payloadLen + SIGNATURE_SIZE;
|
|
2592
|
+
}
|
|
2593
|
+
return sha2562(data);
|
|
2594
|
+
}
|
|
2428
2595
|
|
|
2429
2596
|
// src/session-config.ts
|
|
2430
2597
|
var MAX_APP_ID_LENGTH = 253;
|
|
@@ -2608,7 +2775,7 @@ var SessionConfig = class _SessionConfig {
|
|
|
2608
2775
|
return `multitap://${this.authority}${path}?${params2.toString()}`;
|
|
2609
2776
|
}
|
|
2610
2777
|
/**
|
|
2611
|
-
* Build
|
|
2778
|
+
* Build a connection URL
|
|
2612
2779
|
* @returns HTTPS URL string
|
|
2613
2780
|
*/
|
|
2614
2781
|
toHTTPSURL() {
|
|
@@ -2691,20 +2858,21 @@ var MSG_TYPE_INPUT = 3;
|
|
|
2691
2858
|
var MSG_TYPE_TICK = 4;
|
|
2692
2859
|
var SIGNATURE_SIZE2 = 65;
|
|
2693
2860
|
var MAX_INPUT_PAYLOAD_SIZE = 255;
|
|
2694
|
-
var
|
|
2861
|
+
var INPUT_HEADER_SIZE2 = 4 + 1;
|
|
2695
2862
|
var INPUT_IDX_SIZE = 1;
|
|
2696
|
-
var MIN_INPUT_SIZE =
|
|
2697
|
-
var MAX_INPUT_SIZE =
|
|
2863
|
+
var MIN_INPUT_SIZE = INPUT_HEADER_SIZE2 + SIGNATURE_SIZE2;
|
|
2864
|
+
var MAX_INPUT_SIZE = INPUT_HEADER_SIZE2 + MAX_INPUT_PAYLOAD_SIZE + SIGNATURE_SIZE2;
|
|
2698
2865
|
var TICK_HEADER_SIZE = 4 + SIGNATURE_SIZE2 + 1;
|
|
2699
2866
|
var PONG_PAYLOAD_SIZE = 8;
|
|
2700
2867
|
var REPLAY_PING_SIZE = 11;
|
|
2701
2868
|
var MSG_HEADER_SIZE = 3;
|
|
2702
2869
|
var MAX_INPUTS_PER_TICK = 16;
|
|
2870
|
+
var NULL_INPUT_TARGET_TICK = 4294967295;
|
|
2703
2871
|
function inputWireSize(payloadLen) {
|
|
2704
|
-
return
|
|
2872
|
+
return INPUT_HEADER_SIZE2 + payloadLen + SIGNATURE_SIZE2;
|
|
2705
2873
|
}
|
|
2706
2874
|
function tickInputWireSize(payloadLen) {
|
|
2707
|
-
return
|
|
2875
|
+
return INPUT_HEADER_SIZE2 + payloadLen + SIGNATURE_SIZE2 + INPUT_IDX_SIZE;
|
|
2708
2876
|
}
|
|
2709
2877
|
var messageCodec = {
|
|
2710
2878
|
// Encode INPUT message: [type:1][len:2][targetTick:4][payloadLen:1][payload:0-255][signature:65]
|
|
@@ -2818,7 +2986,7 @@ var messageCodec = {
|
|
|
2818
2986
|
const inputs = [];
|
|
2819
2987
|
let offset = TICK_HEADER_SIZE;
|
|
2820
2988
|
for (let i = 0; i < inputCount; i++) {
|
|
2821
|
-
if (offset +
|
|
2989
|
+
if (offset + INPUT_HEADER_SIZE2 > data.length) {
|
|
2822
2990
|
throw new Error(`Tick payload truncated at input ${i} header`);
|
|
2823
2991
|
}
|
|
2824
2992
|
const targetTick = view.getUint32(offset, true);
|
|
@@ -2859,7 +3027,7 @@ var messageCodec = {
|
|
|
2859
3027
|
const expectedLen = inputWireSize(payloadLen);
|
|
2860
3028
|
if (length < expectedLen) {
|
|
2861
3029
|
throw new Error(
|
|
2862
|
-
`Input payload truncated: claimed ${payloadLen} bytes, only ${length -
|
|
3030
|
+
`Input payload truncated: claimed ${payloadLen} bytes, only ${length - INPUT_HEADER_SIZE2 - SIGNATURE_SIZE2} available`
|
|
2863
3031
|
);
|
|
2864
3032
|
}
|
|
2865
3033
|
return {
|
|
@@ -2871,12 +3039,12 @@ var messageCodec = {
|
|
|
2871
3039
|
}
|
|
2872
3040
|
};
|
|
2873
3041
|
|
|
2874
|
-
// node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs
|
|
2875
|
-
var proxyMarker = Symbol("Comlink.proxy");
|
|
2876
|
-
var createEndpoint = Symbol("Comlink.endpoint");
|
|
2877
|
-
var releaseProxy = Symbol("Comlink.releaseProxy");
|
|
2878
|
-
var finalizer = Symbol("Comlink.finalizer");
|
|
2879
|
-
var throwMarker = Symbol("Comlink.thrown");
|
|
3042
|
+
// ../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs
|
|
3043
|
+
var proxyMarker = /* @__PURE__ */ Symbol("Comlink.proxy");
|
|
3044
|
+
var createEndpoint = /* @__PURE__ */ Symbol("Comlink.endpoint");
|
|
3045
|
+
var releaseProxy = /* @__PURE__ */ Symbol("Comlink.releaseProxy");
|
|
3046
|
+
var finalizer = /* @__PURE__ */ Symbol("Comlink.finalizer");
|
|
3047
|
+
var throwMarker = /* @__PURE__ */ Symbol("Comlink.thrown");
|
|
2880
3048
|
var isObject = (val) => typeof val === "object" && val !== null || typeof val === "function";
|
|
2881
3049
|
var proxyTransferHandler = {
|
|
2882
3050
|
canHandle: (val) => isObject(val) && val[proxyMarker],
|
|
@@ -3193,6 +3361,47 @@ function generateUUID() {
|
|
|
3193
3361
|
return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
|
|
3194
3362
|
}
|
|
3195
3363
|
|
|
3364
|
+
// src/constants.ts
|
|
3365
|
+
var ROLLBACK_WINDOW = 20;
|
|
3366
|
+
var INPUT_VALIDITY_WINDOW = 10;
|
|
3367
|
+
|
|
3368
|
+
// src/debug.ts
|
|
3369
|
+
var enabled = true;
|
|
3370
|
+
var noop = () => {
|
|
3371
|
+
};
|
|
3372
|
+
var debug = {
|
|
3373
|
+
log: (...args) => {
|
|
3374
|
+
if (enabled) console.log(...args);
|
|
3375
|
+
},
|
|
3376
|
+
warn: (...args) => {
|
|
3377
|
+
if (enabled) console.warn(...args);
|
|
3378
|
+
},
|
|
3379
|
+
error: (...args) => {
|
|
3380
|
+
if (enabled) console.error(...args);
|
|
3381
|
+
},
|
|
3382
|
+
info: (...args) => {
|
|
3383
|
+
if (enabled) console.info(...args);
|
|
3384
|
+
},
|
|
3385
|
+
debug: (...args) => {
|
|
3386
|
+
if (enabled) console.debug(...args);
|
|
3387
|
+
},
|
|
3388
|
+
/** Returns a group function; if disabled, returns noop */
|
|
3389
|
+
group: (label) => {
|
|
3390
|
+
if (enabled) console.group(label);
|
|
3391
|
+
},
|
|
3392
|
+
groupEnd: () => {
|
|
3393
|
+
if (enabled) console.groupEnd();
|
|
3394
|
+
},
|
|
3395
|
+
/** Table output for structured data */
|
|
3396
|
+
table: (data) => {
|
|
3397
|
+
if (enabled) console.table(data);
|
|
3398
|
+
},
|
|
3399
|
+
/** Get the underlying console method (for advanced use) */
|
|
3400
|
+
get raw() {
|
|
3401
|
+
return enabled ? console : { log: noop, warn: noop, error: noop, info: noop, debug: noop };
|
|
3402
|
+
}
|
|
3403
|
+
};
|
|
3404
|
+
|
|
3196
3405
|
// src/helpers.ts
|
|
3197
3406
|
function hexToBytes2(hex) {
|
|
3198
3407
|
const bytes = new Uint8Array(hex.length / 2);
|
|
@@ -3205,6 +3414,1093 @@ function bytesToHex2(bytes) {
|
|
|
3205
3414
|
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
3206
3415
|
}
|
|
3207
3416
|
|
|
3417
|
+
// src/input-graph.ts
|
|
3418
|
+
var InputGraph = class {
|
|
3419
|
+
debug;
|
|
3420
|
+
// the genesis hash this graph represents
|
|
3421
|
+
genesisHash;
|
|
3422
|
+
// the graph root
|
|
3423
|
+
genesis;
|
|
3424
|
+
// map of all nodes in the graph keyed by id
|
|
3425
|
+
syncNodesById = /* @__PURE__ */ new Map();
|
|
3426
|
+
// the highest confirmed tick with a relay-verified chain back to the genesis node
|
|
3427
|
+
syncHead;
|
|
3428
|
+
// the highest tick we have seen with a chain back to the genesis node
|
|
3429
|
+
// this chain may contain predicted ticks that have not yet been confirmed by the relay
|
|
3430
|
+
predictedHead;
|
|
3431
|
+
// incoming sync ticks waiting to be attached to the graph
|
|
3432
|
+
pendingSyncMessages = /* @__PURE__ */ new Map();
|
|
3433
|
+
// sequence for node ids
|
|
3434
|
+
nodeIdSequence = 0;
|
|
3435
|
+
// optimistic messages look like ticks, but only contain an input from a single player
|
|
3436
|
+
// they are kept in arrival order and re-processed each time a new predicted branch forms
|
|
3437
|
+
// optimistic messages are removed from this list when they are seen in the sync chain
|
|
3438
|
+
optimisticInputs = [];
|
|
3439
|
+
// all joined participants by slot index
|
|
3440
|
+
participantBySlot = /* @__PURE__ */ new Map();
|
|
3441
|
+
// fn to execute when predicting participant input
|
|
3442
|
+
inputPayloadPredictor = null;
|
|
3443
|
+
// optional relay pubkey for signature verification (33-byte compressed secp256k1)
|
|
3444
|
+
verificationPubKey = null;
|
|
3445
|
+
// the maximum number of ticks the graph will track
|
|
3446
|
+
maxTicks;
|
|
3447
|
+
// log each sync tick to the console - very noisey, used by e2e tests, you don't want this
|
|
3448
|
+
logSyncTicks;
|
|
3449
|
+
// on participant joined callback
|
|
3450
|
+
onParticipantJoined = null;
|
|
3451
|
+
constructor(config2) {
|
|
3452
|
+
this.genesisHash = config2.genesisHash;
|
|
3453
|
+
this.genesis = {
|
|
3454
|
+
id: this.generateNodeId(),
|
|
3455
|
+
parent: null,
|
|
3456
|
+
syncPrev: null,
|
|
3457
|
+
syncNext: null,
|
|
3458
|
+
tick: 0,
|
|
3459
|
+
sig: new Uint8Array(SIGNATURE_SIZE2),
|
|
3460
|
+
payloads: [],
|
|
3461
|
+
sync: true
|
|
3462
|
+
};
|
|
3463
|
+
this.syncHead = this.genesis;
|
|
3464
|
+
this.predictedHead = this.syncHead;
|
|
3465
|
+
this.syncNodesById.set(this.genesis.id, this.genesis);
|
|
3466
|
+
this.maxTicks = config2.maxTicks;
|
|
3467
|
+
this.inputPayloadPredictor = config2.inputPayloadPredictor ?? null;
|
|
3468
|
+
this.verificationPubKey = config2.verificationPubKey || null;
|
|
3469
|
+
this.debug = config2.debug ?? false;
|
|
3470
|
+
this.logSyncTicks = config2.logSyncTicks ?? false;
|
|
3471
|
+
this.logSyncNodeForTests(this.genesis);
|
|
3472
|
+
}
|
|
3473
|
+
// set the on participant joined callback
|
|
3474
|
+
setOnParticipantJoined(fn) {
|
|
3475
|
+
this.onParticipantJoined = fn;
|
|
3476
|
+
}
|
|
3477
|
+
// return the tip of the immutable sync chain
|
|
3478
|
+
getSyncHead() {
|
|
3479
|
+
return this.syncHead;
|
|
3480
|
+
}
|
|
3481
|
+
// return the tip of the ephemeral predicted chain
|
|
3482
|
+
getPredictedHead() {
|
|
3483
|
+
return this.predictedHead;
|
|
3484
|
+
}
|
|
3485
|
+
// adds a sync message (from relay) to the graph
|
|
3486
|
+
addSyncTick(msg) {
|
|
3487
|
+
if (msg.tick <= this.syncHead.tick) {
|
|
3488
|
+
if (this.debug) {
|
|
3489
|
+
debug.warn("skipping sync tick that is older than the sync head (duplicate?)", msg.tick, this.syncHead.tick);
|
|
3490
|
+
}
|
|
3491
|
+
return;
|
|
3492
|
+
}
|
|
3493
|
+
this.pendingSyncMessages.set(msg.tick, msg);
|
|
3494
|
+
this.optimisticInputs = this.optimisticInputs.filter((optimisticInput) => {
|
|
3495
|
+
for (const input of msg.inputs) {
|
|
3496
|
+
if (arraysEqual(input.sig, optimisticInput.sig)) {
|
|
3497
|
+
return false;
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
return true;
|
|
3501
|
+
});
|
|
3502
|
+
this.updateHeads();
|
|
3503
|
+
}
|
|
3504
|
+
// extract the pubkey from the signed input
|
|
3505
|
+
recoverInputPubKey(input) {
|
|
3506
|
+
const msgHash = hashInputMessage(this.genesisHash, input.targetTick, input.payload);
|
|
3507
|
+
return recoverPubKey(msgHash, input.sig);
|
|
3508
|
+
}
|
|
3509
|
+
// adds an optimistic message to the queue and updates the graph. optimistic
|
|
3510
|
+
// messages are not expected to be signed or validated by the relay they are
|
|
3511
|
+
// expected to only contain a single input as they either come from ourselves
|
|
3512
|
+
// or a peer directly connected to us
|
|
3513
|
+
addOptimisticInput(input, preVerifiedSigner) {
|
|
3514
|
+
if (input.targetTick >= this.maxTicks) {
|
|
3515
|
+
return;
|
|
3516
|
+
}
|
|
3517
|
+
if (!isWithinValidityWindow(input.targetTick, this.syncHead.tick)) {
|
|
3518
|
+
return;
|
|
3519
|
+
}
|
|
3520
|
+
const currentGap = this.predictedHead.tick - this.syncHead.tick;
|
|
3521
|
+
if (currentGap >= ROLLBACK_WINDOW) {
|
|
3522
|
+
if (this.debug) {
|
|
3523
|
+
debug.warn(`unable to add optimistic input as we are already ${currentGap} ticks ahead of the sync chain`);
|
|
3524
|
+
}
|
|
3525
|
+
return;
|
|
3526
|
+
}
|
|
3527
|
+
const signer = preVerifiedSigner ?? this.recoverInputPubKey(input);
|
|
3528
|
+
const participant = Array.from(this.participantBySlot.values()).find(
|
|
3529
|
+
(participant2) => participant2.id === bytesToHex2(signer)
|
|
3530
|
+
);
|
|
3531
|
+
if (!participant) {
|
|
3532
|
+
if (this.debug) {
|
|
3533
|
+
debug.warn("skipping optimistic tick from unknown participant", input.targetTick, bytesToHex2(signer));
|
|
3534
|
+
}
|
|
3535
|
+
return;
|
|
3536
|
+
}
|
|
3537
|
+
this.optimisticInputs.push({ ...input, idx: participant.slot });
|
|
3538
|
+
this.updateHeads();
|
|
3539
|
+
}
|
|
3540
|
+
// returns the confirmed joined participant set at the given tick. the set is ordered by the
|
|
3541
|
+
// relay confirmed payload index.
|
|
3542
|
+
getParticipantSlots(tick) {
|
|
3543
|
+
const slots = Array.from(this.participantBySlot.values()).filter((participant) => participant.joined <= tick).sort((a, b) => a.slot - b.slot);
|
|
3544
|
+
for (let i = 0; i < slots.length; i++) {
|
|
3545
|
+
const s = slots[i];
|
|
3546
|
+
if (s === void 0) {
|
|
3547
|
+
throw new Error(`invariant: participant slot ${i} is undefined`);
|
|
3548
|
+
}
|
|
3549
|
+
if (s.slot !== i) {
|
|
3550
|
+
throw new Error(`invariant: participant slot ${i} is not sequential`);
|
|
3551
|
+
}
|
|
3552
|
+
}
|
|
3553
|
+
return slots;
|
|
3554
|
+
}
|
|
3555
|
+
// getTicksAfter: takes the given nodeId and returns all ticks from
|
|
3556
|
+
// the fork point preceeding nodeIdto the predicted head.
|
|
3557
|
+
// a null nodeId will return the whole predicted chain from genesis.
|
|
3558
|
+
// we assume that the original predicted branch is gone.
|
|
3559
|
+
// this is because at high frequency it is actually more efficient to just
|
|
3560
|
+
// resend the new predicted branch from the fork point that to calculate if
|
|
3561
|
+
// it's safe to use the stale data. It is expected that the state system has an efficient way
|
|
3562
|
+
// to skip recalculating states for recent ticks.
|
|
3563
|
+
// ---
|
|
3564
|
+
getTicksAfter(nodeId, options) {
|
|
3565
|
+
const forkPoint = this.getSyncChainForkPointFromNodeId(nodeId);
|
|
3566
|
+
const maxBatchSize = options?.limit;
|
|
3567
|
+
const res = [];
|
|
3568
|
+
let current = this.predictedHead;
|
|
3569
|
+
let lags = options?.lag ?? 0;
|
|
3570
|
+
while (current) {
|
|
3571
|
+
if (current.sync) {
|
|
3572
|
+
lags = 0;
|
|
3573
|
+
}
|
|
3574
|
+
if (lags > 0) {
|
|
3575
|
+
lags--;
|
|
3576
|
+
} else {
|
|
3577
|
+
if (options?.sync && !current.sync) {
|
|
3578
|
+
} else {
|
|
3579
|
+
res.push({
|
|
3580
|
+
id: current.id,
|
|
3581
|
+
tick: current.tick,
|
|
3582
|
+
payloads: current.payloads,
|
|
3583
|
+
sync: current.sync
|
|
3584
|
+
});
|
|
3585
|
+
}
|
|
3586
|
+
}
|
|
3587
|
+
if (current === forkPoint) {
|
|
3588
|
+
break;
|
|
3589
|
+
}
|
|
3590
|
+
current = current.parent;
|
|
3591
|
+
}
|
|
3592
|
+
if (maxBatchSize && res.length >= maxBatchSize) {
|
|
3593
|
+
return res.reverse().slice(0, maxBatchSize);
|
|
3594
|
+
}
|
|
3595
|
+
return res.reverse();
|
|
3596
|
+
}
|
|
3597
|
+
// returns the number of holes between syncHead and predictedHead that were
|
|
3598
|
+
// filled with optimistic predictions messages
|
|
3599
|
+
getPredictionCount() {
|
|
3600
|
+
let count = 0;
|
|
3601
|
+
let current = this.predictedHead;
|
|
3602
|
+
while (current && !current.sync) {
|
|
3603
|
+
if (!current.pending) {
|
|
3604
|
+
count++;
|
|
3605
|
+
}
|
|
3606
|
+
current = current.parent;
|
|
3607
|
+
}
|
|
3608
|
+
return count;
|
|
3609
|
+
}
|
|
3610
|
+
// returns the nodes from the sync head to the given tickId
|
|
3611
|
+
// if nodeId is null, returns the whole sync chain INCLUDING genesis
|
|
3612
|
+
// if tickId is not on the sync chain, throws an error
|
|
3613
|
+
getSyncTicksAfter(nodeId) {
|
|
3614
|
+
const node = !nodeId ? this.genesis : this.syncNodesById.get(nodeId);
|
|
3615
|
+
if (!node) {
|
|
3616
|
+
throw new Error(`invalid nodeId ${nodeId} not found in graph`);
|
|
3617
|
+
}
|
|
3618
|
+
if (!node.sync) {
|
|
3619
|
+
throw new Error(`node ${nodeId} is not on the sync chain`);
|
|
3620
|
+
}
|
|
3621
|
+
const res = [];
|
|
3622
|
+
let current = this.syncHead;
|
|
3623
|
+
while (current) {
|
|
3624
|
+
if (current === node) {
|
|
3625
|
+
if (nodeId === null) {
|
|
3626
|
+
res.push(current);
|
|
3627
|
+
}
|
|
3628
|
+
break;
|
|
3629
|
+
}
|
|
3630
|
+
res.push(current);
|
|
3631
|
+
current = current.parent;
|
|
3632
|
+
}
|
|
3633
|
+
return res.reverse();
|
|
3634
|
+
}
|
|
3635
|
+
// due to the way we generate node ids, we can work out the point of a fork
|
|
3636
|
+
// from the id alone, which gives us a quick way to jump back to the fork point
|
|
3637
|
+
// Sync node IDs: "1", "2", "3" (no slash)
|
|
3638
|
+
// Predicted node IDs: "1/4", "1/5" (forkPoint.id / sequence)
|
|
3639
|
+
getSyncChainForkPointFromNodeId(nodeId) {
|
|
3640
|
+
if (!nodeId) {
|
|
3641
|
+
return this.genesis;
|
|
3642
|
+
}
|
|
3643
|
+
if (nodeId.includes("/")) {
|
|
3644
|
+
const forkId = nodeId.split("/")[0];
|
|
3645
|
+
return this.syncNodesById.get(forkId) ?? this.genesis;
|
|
3646
|
+
}
|
|
3647
|
+
return this.syncNodesById.get(nodeId) ?? this.genesis;
|
|
3648
|
+
}
|
|
3649
|
+
getPendingSyncMessages() {
|
|
3650
|
+
return Array.from(this.pendingSyncMessages.entries()).sort((a, b) => a[0] - b[0]);
|
|
3651
|
+
}
|
|
3652
|
+
// Verify a tick's signature against the relay pubkey if verification is enabled.
|
|
3653
|
+
// Returns true if verification was performed and succeeded, false if verification is disabled.
|
|
3654
|
+
// Throws an error if verification fails.
|
|
3655
|
+
verifyTickSignature(tickNum, inputs, tickSig, prevTickSig) {
|
|
3656
|
+
if (!this.verificationPubKey) return false;
|
|
3657
|
+
const inputsHash = hashInputs(
|
|
3658
|
+
inputs.map((input) => ({
|
|
3659
|
+
targetTick: input.targetTick,
|
|
3660
|
+
payload: input.payload,
|
|
3661
|
+
sig: input.sig,
|
|
3662
|
+
idx: input.idx
|
|
3663
|
+
}))
|
|
3664
|
+
);
|
|
3665
|
+
const tickHash = hashTickMessage(this.genesisHash, tickNum, inputsHash, prevTickSig);
|
|
3666
|
+
if (!verifySignature(this.verificationPubKey, tickHash, tickSig)) {
|
|
3667
|
+
throw new Error(`Invalid relay signature for tick ${tickNum}. `);
|
|
3668
|
+
}
|
|
3669
|
+
return true;
|
|
3670
|
+
}
|
|
3671
|
+
getOrderedPayloadsAtTick(tick, inputs) {
|
|
3672
|
+
return this.getParticipantSlots(tick).map((participant) => {
|
|
3673
|
+
if (!participant) {
|
|
3674
|
+
return new Uint8Array(0);
|
|
3675
|
+
}
|
|
3676
|
+
const input = inputs.find((i) => i.idx === participant.slot);
|
|
3677
|
+
return input?.payload ?? new Uint8Array(0);
|
|
3678
|
+
});
|
|
3679
|
+
}
|
|
3680
|
+
// update the graph using data from the pending queue and the optimistic messages
|
|
3681
|
+
// must be called when new data is added to update the syncHead and predictedHead
|
|
3682
|
+
updateHeads() {
|
|
3683
|
+
let maxTick = this.syncHead.tick;
|
|
3684
|
+
for (const [pendingAtTick, msg] of this.getPendingSyncMessages()) {
|
|
3685
|
+
if (pendingAtTick <= this.syncHead.tick) {
|
|
3686
|
+
this.pendingSyncMessages.delete(pendingAtTick);
|
|
3687
|
+
continue;
|
|
3688
|
+
}
|
|
3689
|
+
if (pendingAtTick > maxTick) {
|
|
3690
|
+
maxTick = pendingAtTick;
|
|
3691
|
+
}
|
|
3692
|
+
if (pendingAtTick === this.syncHead.tick + 1) {
|
|
3693
|
+
const verified = this.verifyTickSignature(msg.tick, msg.inputs, msg.sig, this.syncHead.sig);
|
|
3694
|
+
for (const input of msg.inputs) {
|
|
3695
|
+
this.ensureParticipantJoined(msg.tick, input);
|
|
3696
|
+
}
|
|
3697
|
+
const node = {
|
|
3698
|
+
id: this.generateNodeId(),
|
|
3699
|
+
parent: this.syncHead,
|
|
3700
|
+
syncPrev: this.syncHead,
|
|
3701
|
+
syncNext: null,
|
|
3702
|
+
tick: msg.tick,
|
|
3703
|
+
sig: msg.sig,
|
|
3704
|
+
payloads: this.getOrderedPayloadsAtTick(msg.tick, msg.inputs),
|
|
3705
|
+
sync: true,
|
|
3706
|
+
verified
|
|
3707
|
+
};
|
|
3708
|
+
this.syncHead.syncNext = node;
|
|
3709
|
+
this.syncHead = node;
|
|
3710
|
+
this.pendingSyncMessages.delete(pendingAtTick);
|
|
3711
|
+
this.syncNodesById.set(node.id, node);
|
|
3712
|
+
this.logSyncNodeForTests(node);
|
|
3713
|
+
continue;
|
|
3714
|
+
} else {
|
|
3715
|
+
break;
|
|
3716
|
+
}
|
|
3717
|
+
}
|
|
3718
|
+
this.optimisticInputs = this.optimisticInputs.filter((input) => input.targetTick > this.syncHead.tick);
|
|
3719
|
+
maxTick = Math.max(
|
|
3720
|
+
maxTick,
|
|
3721
|
+
this.optimisticInputs.reduce(
|
|
3722
|
+
(max, input) => input.targetTick > max ? input.targetTick : max,
|
|
3723
|
+
this.syncHead.tick
|
|
3724
|
+
)
|
|
3725
|
+
);
|
|
3726
|
+
this.predictedHead = this.syncHead;
|
|
3727
|
+
if (maxTick > this.syncHead.tick) {
|
|
3728
|
+
const queue = this.optimisticInputs.slice().sort((a, b) => a.targetTick - b.targetTick);
|
|
3729
|
+
const forkPoint = this.syncHead;
|
|
3730
|
+
for (let t = this.syncHead.tick + 1; t <= maxTick; t++) {
|
|
3731
|
+
let isPendingSync = false;
|
|
3732
|
+
let msg = this.pendingSyncMessages.get(t);
|
|
3733
|
+
if (msg) {
|
|
3734
|
+
isPendingSync = true;
|
|
3735
|
+
} else {
|
|
3736
|
+
msg = this.dequeuePrediction(t, queue, this.predictedHead);
|
|
3737
|
+
}
|
|
3738
|
+
const node = {
|
|
3739
|
+
id: this.generateNodeId(forkPoint),
|
|
3740
|
+
parent: this.predictedHead,
|
|
3741
|
+
syncPrev: forkPoint,
|
|
3742
|
+
syncNext: null,
|
|
3743
|
+
tick: t,
|
|
3744
|
+
sig: msg.sig,
|
|
3745
|
+
payloads: this.getOrderedPayloadsAtTick(t, msg.inputs),
|
|
3746
|
+
sync: false,
|
|
3747
|
+
pending: isPendingSync
|
|
3748
|
+
// indicates a very strong prediction as it's from relay
|
|
3749
|
+
};
|
|
3750
|
+
this.predictedHead = node;
|
|
3751
|
+
}
|
|
3752
|
+
}
|
|
3753
|
+
}
|
|
3754
|
+
ensureParticipantJoined(tick, input) {
|
|
3755
|
+
if (input.idx < 0) {
|
|
3756
|
+
throw new Error(`invariant: participant slot ${input.idx} is invalid`);
|
|
3757
|
+
}
|
|
3758
|
+
const participant = this.participantBySlot.get(input.idx);
|
|
3759
|
+
if (!participant) {
|
|
3760
|
+
const signer = this.recoverInputPubKey(input);
|
|
3761
|
+
const participant2 = {
|
|
3762
|
+
id: bytesToHex2(signer),
|
|
3763
|
+
pubKey: signer,
|
|
3764
|
+
slot: input.idx,
|
|
3765
|
+
joined: tick
|
|
3766
|
+
};
|
|
3767
|
+
this.participantBySlot.set(input.idx, participant2);
|
|
3768
|
+
if (this.onParticipantJoined) {
|
|
3769
|
+
this.onParticipantJoined(participant2);
|
|
3770
|
+
}
|
|
3771
|
+
}
|
|
3772
|
+
}
|
|
3773
|
+
// the e2e conformance test expects the sync nodes to be logged to console
|
|
3774
|
+
logSyncNodeForTests(node) {
|
|
3775
|
+
if (this.logSyncTicks) {
|
|
3776
|
+
console.log(
|
|
3777
|
+
`SYNC ${JSON.stringify({
|
|
3778
|
+
tick: node.tick,
|
|
3779
|
+
sig: bytesToHex2(node.sig),
|
|
3780
|
+
payloads: node.payloads.map((p) => bytesToHex2(p)),
|
|
3781
|
+
participants: this.getParticipantSlots(node.tick).map((p) => p?.id ?? ""),
|
|
3782
|
+
sync: true
|
|
3783
|
+
})}`
|
|
3784
|
+
);
|
|
3785
|
+
}
|
|
3786
|
+
}
|
|
3787
|
+
// plucks one input per participant from the given queue to create a prediction for the given tick
|
|
3788
|
+
// acts on a copy of the queue as we reuse for each prediction branch.
|
|
3789
|
+
// dequeue logic should roughly match the Relay's DequeueInputs function for best chance of predicting
|
|
3790
|
+
// NOTE: dequeuePrediction modifies the queue in place as it drains it by design
|
|
3791
|
+
dequeuePrediction(tick, queue, parent) {
|
|
3792
|
+
const inputs = this.getParticipantSlots(tick).map((participant) => {
|
|
3793
|
+
if (!participant || participant.slot < 0) {
|
|
3794
|
+
throw new Error(`invariant: participant slot "${participant?.slot}" invalid`);
|
|
3795
|
+
}
|
|
3796
|
+
return {
|
|
3797
|
+
targetTick: tick,
|
|
3798
|
+
payload: this.inputPayloadPredictor ? this.inputPayloadPredictor(tick, participant.slot, parent) : new Uint8Array(0),
|
|
3799
|
+
sig: new Uint8Array(0),
|
|
3800
|
+
// no signature required for optimistic tick container
|
|
3801
|
+
idx: participant.slot
|
|
3802
|
+
// assign stable participant slot
|
|
3803
|
+
};
|
|
3804
|
+
});
|
|
3805
|
+
let inputCount = 0;
|
|
3806
|
+
const consumed = [];
|
|
3807
|
+
for (const prediction of queue.slice()) {
|
|
3808
|
+
if (inputCount >= inputs.length) {
|
|
3809
|
+
break;
|
|
3810
|
+
}
|
|
3811
|
+
if (prediction.targetTick > tick) {
|
|
3812
|
+
continue;
|
|
3813
|
+
}
|
|
3814
|
+
if (!isWithinValidityWindow(prediction.targetTick, tick)) {
|
|
3815
|
+
continue;
|
|
3816
|
+
}
|
|
3817
|
+
const slot = inputs[prediction.idx];
|
|
3818
|
+
if (!slot) {
|
|
3819
|
+
throw new Error(`invariant: participant slot ${prediction.idx} not found in inputs`);
|
|
3820
|
+
}
|
|
3821
|
+
if (slot.payload.length > 0) {
|
|
3822
|
+
continue;
|
|
3823
|
+
}
|
|
3824
|
+
slot.payload = prediction.payload;
|
|
3825
|
+
consumed.push(prediction);
|
|
3826
|
+
inputCount++;
|
|
3827
|
+
break;
|
|
3828
|
+
}
|
|
3829
|
+
for (const msg of consumed) {
|
|
3830
|
+
queue.splice(queue.indexOf(msg), 1);
|
|
3831
|
+
}
|
|
3832
|
+
return {
|
|
3833
|
+
type: "tick",
|
|
3834
|
+
tick,
|
|
3835
|
+
inputs,
|
|
3836
|
+
sig: new Uint8Array(SIGNATURE_SIZE2)
|
|
3837
|
+
};
|
|
3838
|
+
}
|
|
3839
|
+
// generates a unique id for a node
|
|
3840
|
+
// encodes the forkPoint as part of the id as a shortcut to jump back to
|
|
3841
|
+
// safety from a pruned predicted branch
|
|
3842
|
+
generateNodeId(forkPoint) {
|
|
3843
|
+
this.nodeIdSequence++;
|
|
3844
|
+
return forkPoint ? `${forkPoint.id}/${this.nodeIdSequence}` : `${this.nodeIdSequence}`;
|
|
3845
|
+
}
|
|
3846
|
+
};
|
|
3847
|
+
function isWithinValidityWindow(tick, currentTick) {
|
|
3848
|
+
const minTick = Math.max(0, currentTick - INPUT_VALIDITY_WINDOW);
|
|
3849
|
+
const maxTick = currentTick + INPUT_VALIDITY_WINDOW;
|
|
3850
|
+
return tick >= minTick && tick <= maxTick;
|
|
3851
|
+
}
|
|
3852
|
+
|
|
3853
|
+
// src/stats.ts
|
|
3854
|
+
var RollingCounter = class {
|
|
3855
|
+
buffer;
|
|
3856
|
+
windowMs;
|
|
3857
|
+
head = 0;
|
|
3858
|
+
tail = 0;
|
|
3859
|
+
size = 0;
|
|
3860
|
+
constructor(windowMs = 1e3, maxEvents = 1024) {
|
|
3861
|
+
this.windowMs = windowMs;
|
|
3862
|
+
this.buffer = new Float64Array(maxEvents);
|
|
3863
|
+
}
|
|
3864
|
+
/**
|
|
3865
|
+
* Record a single event at the given timestamp
|
|
3866
|
+
*/
|
|
3867
|
+
inc() {
|
|
3868
|
+
const now = performance.now();
|
|
3869
|
+
this.buffer[this.head] = now;
|
|
3870
|
+
this.head = (this.head + 1) % this.buffer.length;
|
|
3871
|
+
if (this.size < this.buffer.length) {
|
|
3872
|
+
this.size++;
|
|
3873
|
+
} else {
|
|
3874
|
+
this.tail = (this.tail + 1) % this.buffer.length;
|
|
3875
|
+
}
|
|
3876
|
+
}
|
|
3877
|
+
/**
|
|
3878
|
+
* Returns number of events within the rolling window
|
|
3879
|
+
*/
|
|
3880
|
+
count(now = performance.now()) {
|
|
3881
|
+
const cutoff = now - this.windowMs;
|
|
3882
|
+
while (this.size > 0) {
|
|
3883
|
+
if (this.buffer[this.tail] >= cutoff) {
|
|
3884
|
+
break;
|
|
3885
|
+
}
|
|
3886
|
+
this.tail = (this.tail + 1) % this.buffer.length;
|
|
3887
|
+
this.size--;
|
|
3888
|
+
}
|
|
3889
|
+
return this.size;
|
|
3890
|
+
}
|
|
3891
|
+
/**
|
|
3892
|
+
* Returns the rate of events per second
|
|
3893
|
+
*/
|
|
3894
|
+
rate(now = performance.now()) {
|
|
3895
|
+
return this.count(now) * (1e3 / this.windowMs);
|
|
3896
|
+
}
|
|
3897
|
+
};
|
|
3898
|
+
|
|
3899
|
+
// src/channel.ts
|
|
3900
|
+
var DEFAULT_ICE_SERVERS = [
|
|
3901
|
+
{ urls: "stun:stun.l.google.com:19302" },
|
|
3902
|
+
{ urls: "stun:stun1.l.google.com:19302" }
|
|
3903
|
+
];
|
|
3904
|
+
var Channel = class {
|
|
3905
|
+
connectionURL;
|
|
3906
|
+
serverCertHash;
|
|
3907
|
+
connectionTimeoutMs;
|
|
3908
|
+
// Signing keys - player identity is derived from public key
|
|
3909
|
+
privateKey;
|
|
3910
|
+
publicKey;
|
|
3911
|
+
genesisHash;
|
|
3912
|
+
sessionConfig;
|
|
3913
|
+
peerConnection;
|
|
3914
|
+
dataChannels;
|
|
3915
|
+
replayChannels;
|
|
3916
|
+
roundRobinIndex;
|
|
3917
|
+
connectionGeneration;
|
|
3918
|
+
iceServers;
|
|
3919
|
+
connected;
|
|
3920
|
+
stopped;
|
|
3921
|
+
debug;
|
|
3922
|
+
logSyncTicks;
|
|
3923
|
+
outbox;
|
|
3924
|
+
stateListeners;
|
|
3925
|
+
flushingOutbox;
|
|
3926
|
+
tickRate;
|
|
3927
|
+
inputGraph;
|
|
3928
|
+
// tick deadline tracking
|
|
3929
|
+
tickDeadlineWants = 0;
|
|
3930
|
+
tickDeadlineTimer = null;
|
|
3931
|
+
tickDeadlineGrace = 33;
|
|
3932
|
+
// is a tick is later than this, we trigger a deadline exceeded
|
|
3933
|
+
// stats
|
|
3934
|
+
stats;
|
|
3935
|
+
constructor(config2) {
|
|
3936
|
+
this.debug = config2.debug ?? false;
|
|
3937
|
+
this.connectionURL = config2.connectionURL;
|
|
3938
|
+
this.serverCertHash = config2.serverCertHash;
|
|
3939
|
+
this.connectionTimeoutMs = config2.connectionTimeoutMs ?? 5e3;
|
|
3940
|
+
this.privateKey = config2.privateKey ?? generateKeyPair();
|
|
3941
|
+
this.publicKey = pubKeyFromPrivate(this.privateKey);
|
|
3942
|
+
this.logSyncTicks = config2.logSyncTicks ?? false;
|
|
3943
|
+
this.iceServers = config2.iceServers ?? DEFAULT_ICE_SERVERS;
|
|
3944
|
+
this.sessionConfig = SessionConfig.fromConnectionURL(config2.connectionURL);
|
|
3945
|
+
this.genesisHash = this.sessionConfig.toGenesisHash();
|
|
3946
|
+
this.peerConnection = null;
|
|
3947
|
+
this.dataChannels = [];
|
|
3948
|
+
this.replayChannels = /* @__PURE__ */ new Set();
|
|
3949
|
+
this.roundRobinIndex = 0;
|
|
3950
|
+
this.connectionGeneration = 0;
|
|
3951
|
+
this.connected = false;
|
|
3952
|
+
this.stopped = false;
|
|
3953
|
+
this.outbox = [];
|
|
3954
|
+
this.stateListeners = /* @__PURE__ */ new Set();
|
|
3955
|
+
this.flushingOutbox = false;
|
|
3956
|
+
this.tickRate = 0;
|
|
3957
|
+
this.inputGraph = new InputGraph({
|
|
3958
|
+
genesisHash: this.genesisHash,
|
|
3959
|
+
maxTicks: this.sessionConfig.maxTicks,
|
|
3960
|
+
inputPayloadPredictor: config2.inputPayloadPredictor,
|
|
3961
|
+
verificationPubKey: config2.relayPubKey,
|
|
3962
|
+
debug: this.debug,
|
|
3963
|
+
logSyncTicks: this.logSyncTicks
|
|
3964
|
+
});
|
|
3965
|
+
this.stats = {
|
|
3966
|
+
messagesRecv: new RollingCounter(),
|
|
3967
|
+
messagesSent: new RollingCounter(),
|
|
3968
|
+
reconnections: 0
|
|
3969
|
+
};
|
|
3970
|
+
if (config2.autoConnect !== false) {
|
|
3971
|
+
this._connectLoop().catch(warnUnexpected);
|
|
3972
|
+
}
|
|
3973
|
+
}
|
|
3974
|
+
// Manually start the connection loop (use when autoConnect: false)
|
|
3975
|
+
async connect() {
|
|
3976
|
+
if (this.stopped) {
|
|
3977
|
+
throw new Error("Channel has been stopped");
|
|
3978
|
+
}
|
|
3979
|
+
if (!this.peerConnection && !this.connected) {
|
|
3980
|
+
this._connectLoop().catch(warnUnexpected);
|
|
3981
|
+
}
|
|
3982
|
+
}
|
|
3983
|
+
// Get the player's public key (identity)
|
|
3984
|
+
async getPublicKey() {
|
|
3985
|
+
return this.publicKey;
|
|
3986
|
+
}
|
|
3987
|
+
// Get the genesis hash (16 bytes)
|
|
3988
|
+
async getGenesisHash() {
|
|
3989
|
+
return this.genesisHash;
|
|
3990
|
+
}
|
|
3991
|
+
onStateChange(fn) {
|
|
3992
|
+
this.stateListeners.add(fn);
|
|
3993
|
+
fn(this.connected);
|
|
3994
|
+
return () => {
|
|
3995
|
+
this.stateListeners.delete(fn);
|
|
3996
|
+
};
|
|
3997
|
+
}
|
|
3998
|
+
getStats() {
|
|
3999
|
+
return {
|
|
4000
|
+
activeStreams: this.dataChannels.length,
|
|
4001
|
+
totalStreams: this.dataChannels.length,
|
|
4002
|
+
messagesRecv: this.stats.messagesRecv.rate(),
|
|
4003
|
+
messagesSent: this.stats.messagesSent.rate(),
|
|
4004
|
+
reconnections: this.stats.reconnections
|
|
4005
|
+
};
|
|
4006
|
+
}
|
|
4007
|
+
// Get tick rate (Hz) received from server, 0 if unknown
|
|
4008
|
+
async getTickRate() {
|
|
4009
|
+
return this.tickRate;
|
|
4010
|
+
}
|
|
4011
|
+
// Get participants who joined on or before the given tick, in join order
|
|
4012
|
+
async getParticipantSlots(tick) {
|
|
4013
|
+
return this.inputGraph.getParticipantSlots(tick);
|
|
4014
|
+
}
|
|
4015
|
+
async getSyncHead() {
|
|
4016
|
+
return this.inputGraph.getSyncHead();
|
|
4017
|
+
}
|
|
4018
|
+
async getPredictedHead() {
|
|
4019
|
+
return this.inputGraph.getPredictedHead();
|
|
4020
|
+
}
|
|
4021
|
+
async addSyncTick(msg) {
|
|
4022
|
+
this.inputGraph.addSyncTick(msg);
|
|
4023
|
+
}
|
|
4024
|
+
async addOptimisticInput(input, preVerifiedSigner) {
|
|
4025
|
+
this.inputGraph.addOptimisticInput(input, preVerifiedSigner);
|
|
4026
|
+
}
|
|
4027
|
+
async getPredictionCount() {
|
|
4028
|
+
return this.inputGraph.getPredictionCount();
|
|
4029
|
+
}
|
|
4030
|
+
async getTicksAfter(nodeId, options) {
|
|
4031
|
+
return this.inputGraph.getTicksAfter(nodeId, options);
|
|
4032
|
+
}
|
|
4033
|
+
async setOnParticipantJoined(fn) {
|
|
4034
|
+
this.inputGraph.setOnParticipantJoined(fn);
|
|
4035
|
+
}
|
|
4036
|
+
async expose(port) {
|
|
4037
|
+
expose(this, port);
|
|
4038
|
+
}
|
|
4039
|
+
// shutdown
|
|
4040
|
+
async close() {
|
|
4041
|
+
this.stopped = true;
|
|
4042
|
+
if (this.tickDeadlineTimer) {
|
|
4043
|
+
clearTimeout(this.tickDeadlineTimer);
|
|
4044
|
+
this.tickDeadlineTimer = null;
|
|
4045
|
+
}
|
|
4046
|
+
if (this.peerConnection) {
|
|
4047
|
+
try {
|
|
4048
|
+
this.peerConnection.close();
|
|
4049
|
+
} catch {
|
|
4050
|
+
}
|
|
4051
|
+
}
|
|
4052
|
+
}
|
|
4053
|
+
_setConnected(value) {
|
|
4054
|
+
if (this.connected === value) return;
|
|
4055
|
+
this.connected = value;
|
|
4056
|
+
for (const fn of this.stateListeners) {
|
|
4057
|
+
try {
|
|
4058
|
+
fn(value);
|
|
4059
|
+
} catch {
|
|
4060
|
+
}
|
|
4061
|
+
}
|
|
4062
|
+
}
|
|
4063
|
+
// Send raw bytes (Uint8Array) via DataChannel
|
|
4064
|
+
async _send(data) {
|
|
4065
|
+
if (!(data instanceof Uint8Array)) {
|
|
4066
|
+
throw new Error("send() requires Uint8Array");
|
|
4067
|
+
}
|
|
4068
|
+
if (this.connected && this.dataChannels.length > 0) {
|
|
4069
|
+
for (let i = 0; i < this.dataChannels.length; i++) {
|
|
4070
|
+
const handle = this._nextChannel();
|
|
4071
|
+
if (!handle) break;
|
|
4072
|
+
try {
|
|
4073
|
+
handle.dc.send(data);
|
|
4074
|
+
this.stats.messagesSent.inc();
|
|
4075
|
+
return;
|
|
4076
|
+
} catch {
|
|
4077
|
+
this._dropChannel(handle);
|
|
4078
|
+
if (!this.connected) break;
|
|
4079
|
+
}
|
|
4080
|
+
}
|
|
4081
|
+
}
|
|
4082
|
+
this.outbox.push(data);
|
|
4083
|
+
}
|
|
4084
|
+
// Generate a null input for participant registration (join message)
|
|
4085
|
+
// Null inputs have TargetTick = NULL_INPUT_TARGET_TICK (0xFFFFFFFF) and empty payload.
|
|
4086
|
+
// They bypass the validity window check and are used to register players on connect.
|
|
4087
|
+
_generateNullInput() {
|
|
4088
|
+
const payload = new Uint8Array(0);
|
|
4089
|
+
const msgHash = hashInputMessage(this.genesisHash, NULL_INPUT_TARGET_TICK, payload);
|
|
4090
|
+
const signature = sign2(this.privateKey, msgHash);
|
|
4091
|
+
return messageCodec.encodeInput(NULL_INPUT_TARGET_TICK, payload, signature);
|
|
4092
|
+
}
|
|
4093
|
+
// Send a signed input message
|
|
4094
|
+
// The payload is variable-length (0-255 bytes) and signed with the player's private key
|
|
4095
|
+
// targetTick defaults to predictedHead + 1
|
|
4096
|
+
// Returns the encoded input bytes (for P2P broadcast by Session)
|
|
4097
|
+
async sendSignedInput(payload, targetTick) {
|
|
4098
|
+
if (payload.length > MAX_INPUT_PAYLOAD_SIZE) {
|
|
4099
|
+
throw new Error(`Payload must be ${MAX_INPUT_PAYLOAD_SIZE} bytes or less, got ${payload.length}`);
|
|
4100
|
+
}
|
|
4101
|
+
let tick = targetTick;
|
|
4102
|
+
if (tick === void 0) {
|
|
4103
|
+
tick = this.inputGraph.getPredictedHead().tick + 1;
|
|
4104
|
+
}
|
|
4105
|
+
const msgHash = hashInputMessage(this.genesisHash, tick, payload);
|
|
4106
|
+
const signature = sign2(this.privateKey, msgHash);
|
|
4107
|
+
const selfId = bytesToHex2(this.publicKey);
|
|
4108
|
+
const selfParticipant = this.inputGraph.getParticipantSlots(tick).find((participant) => participant.id === selfId);
|
|
4109
|
+
if (selfParticipant) {
|
|
4110
|
+
this.inputGraph.addOptimisticInput(
|
|
4111
|
+
{ targetTick: tick, payload, sig: signature, idx: selfParticipant.slot },
|
|
4112
|
+
this.publicKey
|
|
4113
|
+
);
|
|
4114
|
+
}
|
|
4115
|
+
const encoded = messageCodec.encodeInput(tick, payload, signature);
|
|
4116
|
+
await this._send(encoded);
|
|
4117
|
+
return encoded;
|
|
4118
|
+
}
|
|
4119
|
+
_nextChannel() {
|
|
4120
|
+
if (this.dataChannels.length === 0) return null;
|
|
4121
|
+
if (this.roundRobinIndex >= this.dataChannels.length) {
|
|
4122
|
+
this.roundRobinIndex = 0;
|
|
4123
|
+
}
|
|
4124
|
+
return this.dataChannels[this.roundRobinIndex++] ?? null;
|
|
4125
|
+
}
|
|
4126
|
+
async _connectLoop() {
|
|
4127
|
+
let consecutiveFailures = 0;
|
|
4128
|
+
while (!this.stopped) {
|
|
4129
|
+
try {
|
|
4130
|
+
const joinInput = this._generateNullInput();
|
|
4131
|
+
const joinParam = uint8ArrayToBase64URL(joinInput);
|
|
4132
|
+
const configWithCreds = new SessionConfig({
|
|
4133
|
+
...this.sessionConfig,
|
|
4134
|
+
credentials: joinParam
|
|
4135
|
+
});
|
|
4136
|
+
const sessionParam = configWithCreds.toBase64EncodedConnectionURL();
|
|
4137
|
+
const base = "https://" + this.sessionConfig.authority;
|
|
4138
|
+
const pc = new RTCPeerConnection({
|
|
4139
|
+
iceServers: this.iceServers
|
|
4140
|
+
});
|
|
4141
|
+
this.peerConnection = pc;
|
|
4142
|
+
this.connectionGeneration++;
|
|
4143
|
+
const generation = this.connectionGeneration;
|
|
4144
|
+
let firstDataChannelResolver = null;
|
|
4145
|
+
const firstDataChannelPromise = new Promise((resolve) => {
|
|
4146
|
+
firstDataChannelResolver = resolve;
|
|
4147
|
+
});
|
|
4148
|
+
pc.ondatachannel = (event) => {
|
|
4149
|
+
if (generation === this.connectionGeneration) {
|
|
4150
|
+
this._handleDataChannel(event.channel, generation, firstDataChannelResolver);
|
|
4151
|
+
firstDataChannelResolver = null;
|
|
4152
|
+
}
|
|
4153
|
+
};
|
|
4154
|
+
const handleConnectionState = () => {
|
|
4155
|
+
if (generation !== this.connectionGeneration) return;
|
|
4156
|
+
const state = pc.connectionState;
|
|
4157
|
+
if (state === "failed" || state === "closed") {
|
|
4158
|
+
this._setConnected(false);
|
|
4159
|
+
this._cleanupPeerConnection();
|
|
4160
|
+
}
|
|
4161
|
+
};
|
|
4162
|
+
pc.addEventListener("connectionstatechange", handleConnectionState);
|
|
4163
|
+
pc.createDataChannel("negotiation");
|
|
4164
|
+
const offer = await pc.createOffer();
|
|
4165
|
+
await pc.setLocalDescription(offer);
|
|
4166
|
+
await this._waitForIceGathering(pc);
|
|
4167
|
+
const localDesc = pc.localDescription;
|
|
4168
|
+
if (!localDesc) {
|
|
4169
|
+
throw new Error("Failed to get local description");
|
|
4170
|
+
}
|
|
4171
|
+
const pubKeyHex = bytesToHex2(this.publicKey);
|
|
4172
|
+
const sseURL = `${base}/rtc/events?session=${sessionParam}&pubkey=${pubKeyHex}`;
|
|
4173
|
+
const sseController = new AbortController();
|
|
4174
|
+
const ssePromise = this._listenForAnswer(sseURL, sseController.signal);
|
|
4175
|
+
const offerURL = `${base}/rtc/offer?session=${sessionParam}&from=${pubKeyHex}&to=relay`;
|
|
4176
|
+
const offerResponse = await fetch(offerURL, {
|
|
4177
|
+
method: "POST",
|
|
4178
|
+
headers: { "Content-Type": "application/json" },
|
|
4179
|
+
body: JSON.stringify({
|
|
4180
|
+
sdp: localDesc.sdp,
|
|
4181
|
+
type: localDesc.type
|
|
4182
|
+
})
|
|
4183
|
+
});
|
|
4184
|
+
if (!offerResponse.ok) {
|
|
4185
|
+
sseController.abort();
|
|
4186
|
+
throw new Error(`Offer rejected: ${offerResponse.status}`);
|
|
4187
|
+
}
|
|
4188
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
4189
|
+
setTimeout(() => reject(new Error("SSE timeout")), this.connectionTimeoutMs);
|
|
4190
|
+
});
|
|
4191
|
+
const answerSDP = await Promise.race([ssePromise, timeoutPromise]);
|
|
4192
|
+
sseController.abort();
|
|
4193
|
+
await pc.setRemoteDescription({
|
|
4194
|
+
type: "answer",
|
|
4195
|
+
sdp: answerSDP
|
|
4196
|
+
});
|
|
4197
|
+
this.dataChannels = [];
|
|
4198
|
+
this.replayChannels.clear();
|
|
4199
|
+
this.roundRobinIndex = 0;
|
|
4200
|
+
const dataChannelTimeout = new Promise((_, reject) => {
|
|
4201
|
+
setTimeout(() => reject(new Error("DataChannel timeout")), this.connectionTimeoutMs);
|
|
4202
|
+
});
|
|
4203
|
+
await Promise.race([firstDataChannelPromise, dataChannelTimeout]);
|
|
4204
|
+
this.stats.reconnections++;
|
|
4205
|
+
this._setConnected(true);
|
|
4206
|
+
consecutiveFailures = 0;
|
|
4207
|
+
await new Promise((resolve) => {
|
|
4208
|
+
const checkDisconnect = () => {
|
|
4209
|
+
const state = pc.connectionState;
|
|
4210
|
+
if (state === "failed" || state === "closed" || state === "disconnected") {
|
|
4211
|
+
pc.removeEventListener("connectionstatechange", checkDisconnect);
|
|
4212
|
+
resolve();
|
|
4213
|
+
}
|
|
4214
|
+
};
|
|
4215
|
+
pc.addEventListener("connectionstatechange", checkDisconnect);
|
|
4216
|
+
});
|
|
4217
|
+
} catch (e) {
|
|
4218
|
+
if (this.debug) {
|
|
4219
|
+
console.warn("connect loop error", e);
|
|
4220
|
+
}
|
|
4221
|
+
consecutiveFailures++;
|
|
4222
|
+
}
|
|
4223
|
+
this._setConnected(false);
|
|
4224
|
+
this._cleanupPeerConnection();
|
|
4225
|
+
if (this.stopped) break;
|
|
4226
|
+
const delay = Math.min(consecutiveFailures * 250, 1e3);
|
|
4227
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
4228
|
+
}
|
|
4229
|
+
if (this.debug) {
|
|
4230
|
+
console.log("connect loop exited");
|
|
4231
|
+
}
|
|
4232
|
+
}
|
|
4233
|
+
// Wait for ICE gathering to complete (with timeout)
|
|
4234
|
+
async _waitForIceGathering(pc) {
|
|
4235
|
+
if (pc.iceGatheringState === "complete") {
|
|
4236
|
+
return;
|
|
4237
|
+
}
|
|
4238
|
+
return new Promise((resolve) => {
|
|
4239
|
+
const checkState = () => {
|
|
4240
|
+
if (pc.iceGatheringState === "complete") {
|
|
4241
|
+
pc.removeEventListener("icegatheringstatechange", checkState);
|
|
4242
|
+
resolve();
|
|
4243
|
+
}
|
|
4244
|
+
};
|
|
4245
|
+
pc.addEventListener("icegatheringstatechange", checkState);
|
|
4246
|
+
setTimeout(() => {
|
|
4247
|
+
pc.removeEventListener("icegatheringstatechange", checkState);
|
|
4248
|
+
resolve();
|
|
4249
|
+
}, 5e3);
|
|
4250
|
+
});
|
|
4251
|
+
}
|
|
4252
|
+
// Listen for answer from SSE
|
|
4253
|
+
async _listenForAnswer(url, signal) {
|
|
4254
|
+
const response = await fetch(url, {
|
|
4255
|
+
headers: { Accept: "text/event-stream", "Cache-Control": "no-cache" },
|
|
4256
|
+
signal
|
|
4257
|
+
});
|
|
4258
|
+
if (!response.ok) {
|
|
4259
|
+
throw new Error(`SSE connection failed: ${response.status}`);
|
|
4260
|
+
}
|
|
4261
|
+
const reader = response.body?.getReader();
|
|
4262
|
+
if (!reader) {
|
|
4263
|
+
throw new Error("SSE response has no body");
|
|
4264
|
+
}
|
|
4265
|
+
const decoder = new TextDecoder();
|
|
4266
|
+
let buffer2 = "";
|
|
4267
|
+
let eventType = "";
|
|
4268
|
+
let eventData = "";
|
|
4269
|
+
try {
|
|
4270
|
+
while (true) {
|
|
4271
|
+
const { value, done } = await reader.read();
|
|
4272
|
+
if (done) break;
|
|
4273
|
+
buffer2 += decoder.decode(value, { stream: true });
|
|
4274
|
+
const lines = buffer2.split("\n");
|
|
4275
|
+
buffer2 = lines.pop() ?? "";
|
|
4276
|
+
for (const line of lines) {
|
|
4277
|
+
if (line.startsWith("event:")) {
|
|
4278
|
+
eventType = line.slice(6).trim();
|
|
4279
|
+
} else if (line.startsWith("data:")) {
|
|
4280
|
+
eventData = line.slice(5).trim();
|
|
4281
|
+
} else if (line === "" && eventData) {
|
|
4282
|
+
if (eventType === "answer") {
|
|
4283
|
+
const answerMsg = JSON.parse(eventData);
|
|
4284
|
+
if (answerMsg.from === "relay" && answerMsg.sdp) {
|
|
4285
|
+
return answerMsg.sdp;
|
|
4286
|
+
}
|
|
4287
|
+
}
|
|
4288
|
+
eventType = "";
|
|
4289
|
+
eventData = "";
|
|
4290
|
+
}
|
|
4291
|
+
}
|
|
4292
|
+
}
|
|
4293
|
+
} finally {
|
|
4294
|
+
reader.releaseLock();
|
|
4295
|
+
}
|
|
4296
|
+
throw new Error("SSE stream closed without receiving answer");
|
|
4297
|
+
}
|
|
4298
|
+
_handleDataChannel(dc, generation, onFirstOpen) {
|
|
4299
|
+
const handle = {
|
|
4300
|
+
dc,
|
|
4301
|
+
index: this.dataChannels.length,
|
|
4302
|
+
isReplay: false,
|
|
4303
|
+
generation
|
|
4304
|
+
};
|
|
4305
|
+
dc.binaryType = "arraybuffer";
|
|
4306
|
+
dc.onopen = () => {
|
|
4307
|
+
if (generation === this.connectionGeneration) {
|
|
4308
|
+
this.dataChannels.push(handle);
|
|
4309
|
+
if (onFirstOpen) {
|
|
4310
|
+
onFirstOpen();
|
|
4311
|
+
}
|
|
4312
|
+
if (this.outbox.length > 0) {
|
|
4313
|
+
this._flushOutbox().catch(warnUnexpected);
|
|
4314
|
+
}
|
|
4315
|
+
}
|
|
4316
|
+
};
|
|
4317
|
+
dc.onmessage = (event) => {
|
|
4318
|
+
if (generation === this.connectionGeneration) {
|
|
4319
|
+
this._handleMessage(handle, new Uint8Array(event.data));
|
|
4320
|
+
}
|
|
4321
|
+
};
|
|
4322
|
+
dc.onclose = () => {
|
|
4323
|
+
this._dropChannel(handle);
|
|
4324
|
+
};
|
|
4325
|
+
dc.onerror = () => {
|
|
4326
|
+
this._dropChannel(handle);
|
|
4327
|
+
};
|
|
4328
|
+
}
|
|
4329
|
+
_handleMessage(handle, data) {
|
|
4330
|
+
if (data.length < 3) return;
|
|
4331
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
4332
|
+
const msgType = view.getUint8(0);
|
|
4333
|
+
const msgLen = view.getUint16(1, true);
|
|
4334
|
+
const totalLen = 3 + msgLen;
|
|
4335
|
+
if (data.length < totalLen) return;
|
|
4336
|
+
const msg = data.slice(0, totalLen);
|
|
4337
|
+
this.stats.messagesRecv.inc();
|
|
4338
|
+
if (msgType === MSG_TYPE_PING) {
|
|
4339
|
+
const pingData = messageCodec.decode(msg);
|
|
4340
|
+
this.tickRate = pingData.tickRate;
|
|
4341
|
+
if (pingData.isReplay) {
|
|
4342
|
+
handle.isReplay = true;
|
|
4343
|
+
const idx = this.dataChannels.indexOf(handle);
|
|
4344
|
+
if (idx >= 0 && handle.generation === this.connectionGeneration) {
|
|
4345
|
+
this.dataChannels.splice(idx, 1);
|
|
4346
|
+
if (this.roundRobinIndex > idx) {
|
|
4347
|
+
this.roundRobinIndex--;
|
|
4348
|
+
}
|
|
4349
|
+
this.replayChannels.add(handle);
|
|
4350
|
+
}
|
|
4351
|
+
handle.pongInterval = setInterval(() => {
|
|
4352
|
+
const syncHead2 = this.inputGraph.getSyncHead();
|
|
4353
|
+
const latestHead2 = this.inputGraph.getPredictedHead();
|
|
4354
|
+
const pongData2 = messageCodec.encodePong(syncHead2.tick, latestHead2.tick);
|
|
4355
|
+
try {
|
|
4356
|
+
handle.dc.send(pongData2);
|
|
4357
|
+
} catch {
|
|
4358
|
+
if (handle.pongInterval) {
|
|
4359
|
+
clearInterval(handle.pongInterval);
|
|
4360
|
+
}
|
|
4361
|
+
}
|
|
4362
|
+
}, 1e3);
|
|
4363
|
+
}
|
|
4364
|
+
const syncHead = this.inputGraph.getSyncHead();
|
|
4365
|
+
const latestHead = this.inputGraph.getPredictedHead();
|
|
4366
|
+
const pongData = messageCodec.encodePong(syncHead.tick, latestHead.tick);
|
|
4367
|
+
try {
|
|
4368
|
+
handle.dc.send(pongData);
|
|
4369
|
+
} catch {
|
|
4370
|
+
this._dropChannel(handle);
|
|
4371
|
+
}
|
|
4372
|
+
} else if (msgType === MSG_TYPE_TICK) {
|
|
4373
|
+
const tickData = messageCodec.decode(msg);
|
|
4374
|
+
try {
|
|
4375
|
+
this.inputGraph.addSyncTick(tickData);
|
|
4376
|
+
this._maybeResetDeadline();
|
|
4377
|
+
} catch (err2) {
|
|
4378
|
+
if (this.debug) {
|
|
4379
|
+
console.warn("Failed to process tick message:", err2 instanceof Error ? err2.message : err2, tickData);
|
|
4380
|
+
}
|
|
4381
|
+
}
|
|
4382
|
+
}
|
|
4383
|
+
}
|
|
4384
|
+
_dropChannel(handle) {
|
|
4385
|
+
if (handle.generation !== this.connectionGeneration) {
|
|
4386
|
+
this._cleanupHandle(handle);
|
|
4387
|
+
return;
|
|
4388
|
+
}
|
|
4389
|
+
if (handle.isReplay) {
|
|
4390
|
+
this.replayChannels.delete(handle);
|
|
4391
|
+
this._cleanupHandle(handle);
|
|
4392
|
+
return;
|
|
4393
|
+
}
|
|
4394
|
+
const idx = this.dataChannels.indexOf(handle);
|
|
4395
|
+
if (idx >= 0) {
|
|
4396
|
+
this.dataChannels.splice(idx, 1);
|
|
4397
|
+
if (this.roundRobinIndex > idx) {
|
|
4398
|
+
this.roundRobinIndex--;
|
|
4399
|
+
}
|
|
4400
|
+
}
|
|
4401
|
+
this._cleanupHandle(handle);
|
|
4402
|
+
}
|
|
4403
|
+
_cleanupHandle(handle) {
|
|
4404
|
+
if (handle.pongInterval) {
|
|
4405
|
+
clearInterval(handle.pongInterval);
|
|
4406
|
+
handle.pongInterval = null;
|
|
4407
|
+
}
|
|
4408
|
+
try {
|
|
4409
|
+
handle.dc.close();
|
|
4410
|
+
} catch {
|
|
4411
|
+
}
|
|
4412
|
+
}
|
|
4413
|
+
async _flushOutbox() {
|
|
4414
|
+
if (this.flushingOutbox) return;
|
|
4415
|
+
this.flushingOutbox = true;
|
|
4416
|
+
try {
|
|
4417
|
+
while (this.outbox.length > 0 && this.dataChannels.length > 0 && this.connected && !this.stopped) {
|
|
4418
|
+
const data = this.outbox.shift();
|
|
4419
|
+
if (!data) break;
|
|
4420
|
+
const handle = this._nextChannel();
|
|
4421
|
+
if (!handle) {
|
|
4422
|
+
this.outbox.unshift(data);
|
|
4423
|
+
break;
|
|
4424
|
+
}
|
|
4425
|
+
try {
|
|
4426
|
+
handle.dc.send(data);
|
|
4427
|
+
this.stats.messagesSent.inc();
|
|
4428
|
+
} catch {
|
|
4429
|
+
this._dropChannel(handle);
|
|
4430
|
+
this.outbox.unshift(data);
|
|
4431
|
+
break;
|
|
4432
|
+
}
|
|
4433
|
+
}
|
|
4434
|
+
} finally {
|
|
4435
|
+
this.flushingOutbox = false;
|
|
4436
|
+
}
|
|
4437
|
+
}
|
|
4438
|
+
_cleanupPeerConnection() {
|
|
4439
|
+
const handles = [...this.dataChannels, ...this.replayChannels];
|
|
4440
|
+
this.dataChannels = [];
|
|
4441
|
+
this.replayChannels.clear();
|
|
4442
|
+
this.roundRobinIndex = 0;
|
|
4443
|
+
for (const h of handles) {
|
|
4444
|
+
this._cleanupHandle(h);
|
|
4445
|
+
}
|
|
4446
|
+
const pc = this.peerConnection;
|
|
4447
|
+
this.peerConnection = null;
|
|
4448
|
+
if (pc) {
|
|
4449
|
+
try {
|
|
4450
|
+
pc.close();
|
|
4451
|
+
} catch {
|
|
4452
|
+
}
|
|
4453
|
+
}
|
|
4454
|
+
}
|
|
4455
|
+
_maybeResetDeadline() {
|
|
4456
|
+
const syncHead = this.inputGraph.getSyncHead();
|
|
4457
|
+
if (syncHead.tick >= this.tickDeadlineWants) {
|
|
4458
|
+
this._resetDeadline(syncHead.tick + 1);
|
|
4459
|
+
}
|
|
4460
|
+
}
|
|
4461
|
+
_resetDeadline(wants) {
|
|
4462
|
+
this.tickDeadlineWants = wants;
|
|
4463
|
+
if (this.tickDeadlineTimer) {
|
|
4464
|
+
clearTimeout(this.tickDeadlineTimer);
|
|
4465
|
+
}
|
|
4466
|
+
if (!this.tickRate) {
|
|
4467
|
+
return;
|
|
4468
|
+
}
|
|
4469
|
+
this.tickDeadlineTimer = setTimeout(
|
|
4470
|
+
this._onTickDeadlineExceeded.bind(this),
|
|
4471
|
+
1e3 / this.tickRate + this.tickDeadlineGrace
|
|
4472
|
+
);
|
|
4473
|
+
}
|
|
4474
|
+
_onTickDeadlineExceeded() {
|
|
4475
|
+
const selfParticipant = this.inputGraph.getParticipantSlots(this.tickDeadlineWants).find((participant) => participant.id === bytesToHex2(this.publicKey));
|
|
4476
|
+
if (selfParticipant) {
|
|
4477
|
+
try {
|
|
4478
|
+
this.inputGraph.addOptimisticInput(
|
|
4479
|
+
{
|
|
4480
|
+
targetTick: this.tickDeadlineWants,
|
|
4481
|
+
payload: new Uint8Array(0),
|
|
4482
|
+
sig: new Uint8Array(0),
|
|
4483
|
+
idx: selfParticipant.slot
|
|
4484
|
+
},
|
|
4485
|
+
this.publicKey
|
|
4486
|
+
);
|
|
4487
|
+
} catch (err2) {
|
|
4488
|
+
if (this.debug) {
|
|
4489
|
+
console.error("failed to add empty optimistic input:", err2 instanceof Error ? err2.message : err2);
|
|
4490
|
+
}
|
|
4491
|
+
}
|
|
4492
|
+
} else {
|
|
4493
|
+
if (this.debug) {
|
|
4494
|
+
console.warn("unable to add empty optimistic input as we do not have a slot assigned yet");
|
|
4495
|
+
}
|
|
4496
|
+
}
|
|
4497
|
+
this._resetDeadline(this.tickDeadlineWants + 1);
|
|
4498
|
+
}
|
|
4499
|
+
};
|
|
4500
|
+
function warnUnexpected(err2) {
|
|
4501
|
+
console.warn("channel unexpected:", err2);
|
|
4502
|
+
}
|
|
4503
|
+
|
|
3208
4504
|
// src/schema.ts
|
|
3209
4505
|
var MAGIC = 1297367376;
|
|
3210
4506
|
var NULL_ENTITY = 4294967295;
|
|
@@ -4083,7 +5379,7 @@ function ensureCompiled(schema) {
|
|
|
4083
5379
|
return ensureCompiledStateSchema(schema);
|
|
4084
5380
|
}
|
|
4085
5381
|
function computeGenesisStateId(genesisHash) {
|
|
4086
|
-
return
|
|
5382
|
+
return sha256(genesisHash);
|
|
4087
5383
|
}
|
|
4088
5384
|
function createState(schema, genesisHash, tickRate) {
|
|
4089
5385
|
const buffer2 = new ArrayBuffer(schema.totalSize);
|
|
@@ -4701,8 +5997,8 @@ function createStoreApi(schemaDef) {
|
|
|
4701
5997
|
return storeApi;
|
|
4702
5998
|
}
|
|
4703
5999
|
|
|
4704
|
-
// src/
|
|
4705
|
-
var workerCode = 'var Wr=Object.defineProperty;var jr=(e,t,n)=>t in e?Wr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var y=(e,t,n)=>jr(e,typeof t!="symbol"?t+"":t,n);var Ge=Symbol("Comlink.proxy"),Yr=Symbol("Comlink.endpoint"),qr=Symbol("Comlink.releaseProxy"),me=Symbol("Comlink.finalizer"),Ft=Symbol("Comlink.thrown"),Oe=e=>typeof e=="object"&&e!==null||typeof e=="function",Xr={canHandle:e=>Oe(e)&&e[Ge],serialize(e){let{port1:t,port2:n}=new MessageChannel;return ht(e,t),[n,[n]]},deserialize(e){return e.start(),ei(e)}},Jr={canHandle:e=>Oe(e)&&Ft in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},$e=new Map([["proxy",Xr],["throw",Jr]]);function Qr(e,t){for(let n of e)if(t===n||n==="*"||n instanceof RegExp&&n.test(t))return!0;return!1}function ht(e,t=globalThis,n=["*"]){t.addEventListener("message",function r(i){if(!i||!i.data)return;if(!Qr(n,i.origin)){console.warn(`Invalid origin \'${i.origin}\' for comlink proxy`);return}let{id:s,type:o,path:a}=Object.assign({path:[]},i.data),u=(i.data.argumentList||[]).map(et),f;try{let d=a.slice(0,-1).reduce((m,x)=>m[x],e),l=a.reduce((m,x)=>m[x],e);switch(o){case"GET":f=l;break;case"SET":d[a.slice(-1)[0]]=et(i.data.value),f=!0;break;case"APPLY":f=l.apply(d,u);break;case"CONSTRUCT":{let m=new l(...u);f=oi(m)}break;case"ENDPOINT":{let{port1:m,port2:x}=new MessageChannel;ht(e,x),f=si(m,[m])}break;case"RELEASE":f=void 0;break;default:return}}catch(d){f={value:d,[Ft]:0}}Promise.resolve(f).catch(d=>({value:d,[Ft]:0})).then(d=>{let[l,m]=Zt(d);t.postMessage(Object.assign(Object.assign({},l),{id:s}),m),o==="RELEASE"&&(t.removeEventListener("message",r),Fe(t),me in e&&typeof e[me]=="function"&&e[me]())}).catch(d=>{let[l,m]=Zt({value:new TypeError("Unserializable return value"),[Ft]:0});t.postMessage(Object.assign(Object.assign({},l),{id:s}),m)})}),t.start&&t.start()}function ti(e){return e.constructor.name==="MessagePort"}function Fe(e){ti(e)&&e.close()}function ei(e,t){let n=new Map;return e.addEventListener("message",function(i){let{data:s}=i;if(!s||!s.id)return;let o=n.get(s.id);if(o)try{o(s)}finally{n.delete(s.id)}}),xe(e,n,[],t)}function $t(e){if(e)throw new Error("Proxy has been released and is not useable")}function Ke(e){return lt(e,new Map,{type:"RELEASE"}).then(()=>{Fe(e)})}var Kt=new WeakMap,zt="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(Kt.get(e)||0)-1;Kt.set(e,t),t===0&&Ke(e)});function ni(e,t){let n=(Kt.get(t)||0)+1;Kt.set(t,n),zt&&zt.register(e,t,e)}function ri(e){zt&&zt.unregister(e)}function xe(e,t,n=[],r=function(){}){let i=!1,s=new Proxy(r,{get(o,a){if($t(i),a===qr)return()=>{ri(s),Ke(e),t.clear(),i=!0};if(a==="then"){if(n.length===0)return{then:()=>s};let u=lt(e,t,{type:"GET",path:n.map(f=>f.toString())}).then(et);return u.then.bind(u)}return xe(e,t,[...n,a])},set(o,a,u){$t(i);let[f,d]=Zt(u);return lt(e,t,{type:"SET",path:[...n,a].map(l=>l.toString()),value:f},d).then(et)},apply(o,a,u){$t(i);let f=n[n.length-1];if(f===Yr)return lt(e,t,{type:"ENDPOINT"}).then(et);if(f==="bind")return xe(e,t,n.slice(0,-1));let[d,l]=De(u);return lt(e,t,{type:"APPLY",path:n.map(m=>m.toString()),argumentList:d},l).then(et)},construct(o,a){$t(i);let[u,f]=De(a);return lt(e,t,{type:"CONSTRUCT",path:n.map(d=>d.toString()),argumentList:u},f).then(et)}});return ni(s,e),s}function ii(e){return Array.prototype.concat.apply([],e)}function De(e){let t=e.map(Zt);return[t.map(n=>n[0]),ii(t.map(n=>n[1]))]}var ze=new WeakMap;function si(e,t){return ze.set(e,t),e}function oi(e){return Object.assign(e,{[Ge]:!0})}function Zt(e){for(let[t,n]of $e)if(n.canHandle(e)){let[r,i]=n.serialize(e);return[{type:"HANDLER",name:t,value:r},i]}return[{type:"RAW",value:e},ze.get(e)||[]]}function et(e){switch(e.type){case"HANDLER":return $e.get(e.name).deserialize(e.value);case"RAW":return e.value}}function lt(e,t,n,r){return new Promise(i=>{let s=ai();t.set(s,i),e.start&&e.start(),e.postMessage(Object.assign({id:s},n),r)})}function ai(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function ci(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ze(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function yt(e,...t){if(!ci(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ve(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ze(e.outputLen),Ze(e.blockLen)}function gt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function We(e,t){yt(e);let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function nt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Vt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function L(e,t){return e<<32-t|e>>>t}function ui(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Ut(e){return typeof e=="string"&&(e=ui(e)),yt(e),e}var pt=class{};function je(e){let t=r=>e().update(Ut(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function fi(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);let i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),u=r?4:0,f=r?0:4;e.setUint32(t+u,o,r),e.setUint32(t+f,a,r)}function Ye(e,t,n){return e&t^~e&n}function qe(e,t,n){return e&t^e&n^t&n}var Wt=class extends pt{constructor(t,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Vt(this.buffer)}update(t){gt(this),t=Ut(t),yt(t);let{view:n,buffer:r,blockLen:i}=this,s=t.length;for(let o=0;o<s;){let a=Math.min(i-this.pos,s-o);if(a===i){let u=Vt(t);for(;i<=s-o;o+=i)this.process(u,o);continue}r.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){gt(this),We(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:s}=this,{pos:o}=this;n[o++]=128,nt(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let l=o;l<i;l++)n[l]=0;fi(r,i-8,BigInt(this.length*8),s),this.process(r,0);let a=Vt(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let f=u/4,d=this.get();if(f>d.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)a.setUint32(4*l,d[l],s)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}},K=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var di=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),q=new Uint32Array(64),jt=class extends Wt{constructor(t=32){super(64,t,8,!1),this.A=K[0]|0,this.B=K[1]|0,this.C=K[2]|0,this.D=K[3]|0,this.E=K[4]|0,this.F=K[5]|0,this.G=K[6]|0,this.H=K[7]|0}get(){let{A:t,B:n,C:r,D:i,E:s,F:o,G:a,H:u}=this;return[t,n,r,i,s,o,a,u]}set(t,n,r,i,s,o,a,u){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=u|0}process(t,n){for(let l=0;l<16;l++,n+=4)q[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){let m=q[l-15],x=q[l-2],b=L(m,7)^L(m,18)^m>>>3,A=L(x,17)^L(x,19)^x>>>10;q[l]=A+q[l-7]+b+q[l-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:u,G:f,H:d}=this;for(let l=0;l<64;l++){let m=L(a,6)^L(a,11)^L(a,25),x=d+m+Ye(a,u,f)+di[l]+q[l]|0,A=(L(r,2)^L(r,13)^L(r,22))+qe(r,i,s)|0;d=f,f=u,u=a,a=o+x|0,o=s,s=i,i=r,r=x+A|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,u=u+this.F|0,f=f+this.G|0,d=d+this.H|0,this.set(r,i,s,o,a,u,f,d)}roundClean(){nt(q)}destroy(){this.set(0,0,0,0,0,0,0,0),nt(this.buffer)}};var Xe=je(()=>new jt);var rt=Xe;var li={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:st,n:V,Gx:hi,Gy:pi,b:rn}=li,P=32,xt=64,S=(e="")=>{throw new Error(e)},sn=e=>typeof e=="bigint",on=e=>typeof e=="string",yi=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",at=(e,t)=>!yi(e)||typeof t=="number"&&t>0&&e.length!==t?S("Uint8Array expected"):e,ot=e=>new Uint8Array(e),gi=e=>Uint8Array.from(e),an=(e,t)=>e.toString(16).padStart(t,"0"),Xt=e=>Array.from(at(e)).map(t=>an(t,2)).join(""),z={_0:48,_9:57,A:65,F:70,a:97,f:102},Je=e=>{if(e>=z._0&&e<=z._9)return e-z._0;if(e>=z.A&&e<=z.F)return e-(z.A-10);if(e>=z.a&&e<=z.f)return e-(z.a-10)},ke=e=>{let t="hex invalid";if(!on(e))return S(t);let n=e.length,r=n/2;if(n%2)return S(t);let i=ot(r);for(let s=0,o=0;s<r;s++,o+=2){let a=Je(e.charCodeAt(o)),u=Je(e.charCodeAt(o+1));if(a===void 0||u===void 0)return S(t);i[s]=a*16+u}return i},ct=(e,t)=>at(on(e)?ke(e):gi(at(e)),t),cn=()=>globalThis?.crypto,mi=()=>cn()?.subtle??S("crypto.subtle must be defined"),ut=(...e)=>{let t=ot(e.reduce((r,i)=>r+at(i).length,0)),n=0;return e.forEach(r=>{t.set(r,n),n+=r.length}),t},Se=(e=P)=>cn().getRandomValues(ot(e)),bt=BigInt,Pt=(e,t,n,r="bad number: out of range")=>sn(e)&&t<=e&&e<n?e:S(r),g=(e,t=st)=>{let n=e%t;return n>=0n?n:t+n},Z=e=>g(e,V),Jt=(e,t)=>{(e===0n||t<=0n)&&S("no inverse n="+e+" mod="+t);let n=g(e,t),r=t,i=0n,s=1n,o=1n,a=0n;for(;n!==0n;){let u=r/n,f=r%n,d=i-o*u,l=s-a*u;r=n,n=f,i=o,s=a,o=d,a=l}return r===1n?g(i,t):S("no inverse")},xi=e=>{let t=Bt[e];return typeof t!="function"&&S("hashes."+e+" not set"),t},Qe=e=>e instanceof X?e:S("Point expected"),un=e=>g(g(e*e)*e+rn),tn=e=>Pt(e,0n,st),It=e=>Pt(e,1n,st),be=e=>Pt(e,1n,V),we=e=>(e&1n)===0n,mt=e=>Uint8Array.of(e),fn=e=>mt(we(e)?2:3),bi=e=>{let t=un(It(e)),n=1n;for(let r=t,i=(st+1n)/4n;i>0n;i>>=1n)i&1n&&(n=n*r%st),r=r*r%st;return g(n*n)===t?n:S("sqrt invalid")},G=class G{constructor(t,n,r){y(this,"px");y(this,"py");y(this,"pz");this.px=tn(t),this.py=It(n),this.pz=tn(r),Object.freeze(this)}static fromBytes(t){at(t);let n,r=t[0],i=t.subarray(1),s=Yt(i,0,P),o=t.length;if(o===P+1&&[2,3].includes(r)){let a=bi(s),u=we(a);we(bt(r))!==u&&(a=g(-a)),n=new G(s,a,1n)}return o===xt+1&&r===4&&(n=new G(s,Yt(i,P,xt),1n)),n?n.assertValidity():S("bad point: not on curve")}equals(t){let{px:n,py:r,pz:i}=this,{px:s,py:o,pz:a}=Qe(t),u=g(n*a),f=g(s*i),d=g(r*a),l=g(o*i);return u===f&&d===l}is0(){return this.equals(it)}negate(){return new G(this.px,g(-this.py),this.pz)}double(){return this.add(this)}add(t){let{px:n,py:r,pz:i}=this,{px:s,py:o,pz:a}=Qe(t),u=0n,f=rn,d=0n,l=0n,m=0n,x=g(f*3n),b=g(n*s),A=g(r*o),I=g(i*a),E=g(n+r),k=g(s+o);E=g(E*k),k=g(b+A),E=g(E-k),k=g(n+i);let _=g(s+a);return k=g(k*_),_=g(b+I),k=g(k-_),_=g(r+i),d=g(o+a),_=g(_*d),d=g(A+I),_=g(_-d),m=g(u*k),d=g(x*I),m=g(d+m),d=g(A-m),m=g(A+m),l=g(d*m),A=g(b+b),A=g(A+b),I=g(u*I),k=g(x*k),A=g(A+I),I=g(b-I),I=g(u*I),k=g(k+I),b=g(A*k),l=g(l+b),b=g(_*k),d=g(E*d),d=g(d-b),b=g(E*A),m=g(_*m),m=g(m+b),new G(d,l,m)}multiply(t,n=!0){if(!n&&t===0n)return it;if(be(t),t===1n)return this;if(this.equals(O))return _i(t).p;let r=it,i=O;for(let s=this;t>0n;s=s.double(),t>>=1n)t&1n?r=r.add(s):n&&(i=i.add(s));return r}toAffine(){let{px:t,py:n,pz:r}=this;if(this.equals(it))return{x:0n,y:0n};if(r===1n)return{x:t,y:n};let i=Jt(r,st);return g(r*i)!==1n&&S("inverse invalid"),{x:g(t*i),y:g(n*i)}}assertValidity(){let{x:t,y:n}=this.toAffine();return It(t),It(n),g(n*n)===un(t)?this:S("bad point: not on curve")}toBytes(t=!0){let{x:n,y:r}=this.assertValidity().toAffine(),i=J(n);return t?ut(fn(r),i):ut(mt(4),i,J(r))}static fromAffine(t){let{x:n,y:r}=t;return n===0n&&r===0n?it:new G(n,r,1n)}toHex(t){return Xt(this.toBytes(t))}static fromPrivateKey(t){return O.multiply(vt(t))}static fromHex(t){return G.fromBytes(ct(t))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}toRawBytes(t){return this.toBytes(t)}};y(G,"BASE"),y(G,"ZERO");var X=G,O=new X(hi,pi,1n),it=new X(0n,1n,0n);X.BASE=O;X.ZERO=it;var wi=(e,t,n)=>O.multiply(t,!1).add(e.multiply(n,!1)).assertValidity(),Ht=e=>bt("0x"+(Xt(e)||"0")),Yt=(e,t,n)=>Ht(e.subarray(t,n)),Ti=2n**256n,J=e=>ke(an(Pt(e,0n,Ti),xt)),vt=e=>{let t=sn(e)?e:Ht(ct(e,P));return Pt(t,1n,V,"private key invalid 3")},Te=e=>e>V>>1n,dn=(e,t=!0)=>O.multiply(vt(e)).toBytes(t),_t=class e{constructor(t,n,r){y(this,"r");y(this,"s");y(this,"recovery");this.r=be(t),this.s=be(n),r!=null&&(this.recovery=r),Object.freeze(this)}static fromBytes(t){at(t,xt);let n=Yt(t,0,P),r=Yt(t,P,xt);return new e(n,r)}toBytes(){let{r:t,s:n}=this;return ut(J(t),J(n))}addRecoveryBit(t){return new e(this.r,this.s,t)}hasHighS(){return Te(this.s)}toCompactRawBytes(){return this.toBytes()}toCompactHex(){return Xt(this.toBytes())}recoverPublicKey(t){return Si(this,t)}static fromCompact(t){return e.fromBytes(ct(t,xt))}assertValidity(){return this}normalizeS(){let{r:t,s:n,recovery:r}=this;return Te(n)?new e(t,Z(-n),r):this}},ln=e=>{let t=e.length*8-256;t>1024&&S("msg invalid");let n=Ht(e);return t>0?n>>bt(t):n},hn=e=>Z(ln(at(e))),pn={lowS:!0};var Ai=(e,t,n=pn)=>{["der","recovered","canonical"].some(m=>m in n)&&S("option not supported");let{lowS:r,extraEntropy:i}=n;r==null&&(r=!0);let s=J,o=hn(ct(e)),a=s(o),u=vt(t),f=[s(u),a];i&&f.push(i===!0?Se(P):ct(i));let d=o,l=m=>{let x=ln(m);if(!(1n<=x&&x<V))return;let b=O.multiply(x).toAffine(),A=Z(b.x);if(A===0n)return;let I=Jt(x,V),E=Z(I*Z(d+Z(u*A)));if(E===0n)return;let k=E,_=(b.x===A?0:2)|Number(b.y&1n);return r&&Te(E)&&(k=Z(-E),_^=1),new _t(A,k,_)};return{seed:ut(...f),k2sig:l}},ki=e=>{let t=ot(P),n=ot(P),r=0,i=ot(0),s=()=>{t.fill(1),n.fill(0),r=0},o=1e3,a="drbg: tried 1000 values";if(e){let u=(...l)=>Bt.hmacSha256Async(n,t,...l),f=async(l=i)=>{n=await u(mt(0),l),t=await u(),l.length!==0&&(n=await u(mt(1),l),t=await u())},d=async()=>(r++>=o&&S(a),t=await u(),t);return async(l,m)=>{s(),await f(l);let x;for(;!(x=m(await d()));)await f();return s(),x}}else{let u=(...l)=>xi("hmacSha256Sync")(n,t,...l),f=(l=i)=>{n=u(mt(0),l),t=u(),l.length!==0&&(n=u(mt(1),l),t=u())},d=()=>(r++>=o&&S(a),t=u(),t);return(l,m)=>{s(),f(l);let x;for(;!(x=m(d()));)f();return s(),x}}};var yn=(e,t,n=pn)=>{let{seed:r,k2sig:i}=Ai(e,t,n);return ki(!1)(r,i)};var Si=(e,t)=>{let{r:n,s:r,recovery:i}=e;[0,1,2,3].includes(i)||S("recovery id invalid");let s=hn(ct(t,P)),o=i===2||i===3?n+V:n;It(o);let a=fn(bt(i)),u=ut(a,J(o)),f=X.fromBytes(u),d=Jt(o,V),l=Z(-s*d),m=Z(r*d);return wi(f,l,m)};var gn=e=>{e=ct(e),(e.length<P+8||e.length>1024)&&S("expected 40-1024b");let t=g(Ht(e),V-1n);return J(t+1n)},Ei=()=>gn(Se(P+16)),Ui="SHA-256",Bt={hexToBytes:ke,bytesToHex:Xt,concatBytes:ut,bytesToNumberBE:Ht,numberToBytesBE:J,mod:g,invert:Jt,hmacSha256Async:async(e,...t)=>{let n=mi(),r="HMAC",i=await n.importKey("raw",e,{name:r,hash:{name:Ui}},!1,["sign"]);return ot(await n.sign(r,i,ut(...t)))},hmacSha256Sync:void 0,hashToPrivateKey:gn,randomBytes:Se},mn={normPrivateKeyToScalar:vt,isValidPrivateKey:e=>{try{return!!vt(e)}catch{return!1}},randomPrivateKey:Ei,precompute:(e=8,t=O)=>(t.multiply(3n),t)},qt=8,Ii=256,xn=Math.ceil(Ii/qt)+1,Ae=2**(qt-1),vi=()=>{let e=[],t=O,n=t;for(let r=0;r<xn;r++){n=t,e.push(n);for(let i=1;i<Ae;i++)n=n.add(t),e.push(n);t=n.double()}return e},en,nn=(e,t)=>{let n=t.negate();return e?n:t},_i=e=>{let t=en||(en=vi()),n=it,r=O,i=2**qt,s=i,o=bt(i-1),a=bt(qt);for(let u=0;u<xn;u++){let f=Number(e&o);e>>=a,f>Ae&&(f-=s,e+=1n);let d=u*Ae,l=d,m=d+Math.abs(f)-1,x=u%2!==0,b=f<0;f===0?r=r.add(nn(x,t[l])):n=n.add(nn(b,t[m]))}return{p:n,f:r}};var Qt=class extends pt{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Ve(t);let r=Ut(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),nt(s)}update(t){return gt(this),this.iHash.update(t),this}digestInto(t){gt(this),yt(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ee=(e,t,n)=>new Qt(e,t).update(n).digest();Ee.create=(e,t)=>new Qt(e,t);var Hi=["string","number","bigint","symbol"],Bi=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function bn(e){if(e===null)return"null";if(e===void 0)return"undefined";if(e===!0||e===!1)return"boolean";let t=typeof e;if(Hi.includes(t))return t;if(t==="function")return"Function";if(Array.isArray(e))return"Array";if(Ni(e))return"Buffer";let n=Ri(e);return n||"Object"}function Ni(e){return e&&e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer.call(null,e)}function Ri(e){let t=Object.prototype.toString.call(e).slice(8,-1);if(Bi.includes(t))return t}var c=class{constructor(t,n,r){this.major=t,this.majorEncoded=t<<5,this.name=n,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}};c.uint=new c(0,"uint",!0);c.negint=new c(1,"negint",!0);c.bytes=new c(2,"bytes",!0);c.string=new c(3,"string",!0);c.array=new c(4,"array",!1);c.map=new c(5,"map",!1);c.tag=new c(6,"tag",!1);c.float=new c(7,"float",!0);c.false=new c(7,"false",!0);c.true=new c(7,"true",!0);c.null=new c(7,"null",!0);c.undefined=new c(7,"undefined",!0);c.break=new c(7,"break",!0);var p=class{constructor(t,n,r){this.type=t,this.value=n,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var wt=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Ci=new TextDecoder,Mi=new TextEncoder;function te(e){return wt&&globalThis.Buffer.isBuffer(e)}function Ue(e){return e instanceof Uint8Array?te(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var kn=wt?(e,t,n)=>n-t>64?globalThis.Buffer.from(e.subarray(t,n)).toString("utf8"):Tn(e,t,n):(e,t,n)=>n-t>64?Ci.decode(e.subarray(t,n)):Tn(e,t,n),Sn=wt?e=>e.length>64?globalThis.Buffer.from(e):wn(e):e=>e.length>64?Mi.encode(e):wn(e),$=e=>Uint8Array.from(e),Tt=wt?(e,t,n)=>te(e)?new Uint8Array(e.subarray(t,n)):e.slice(t,n):(e,t,n)=>e.slice(t,n),En=wt?(e,t)=>(e=e.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),Ue(globalThis.Buffer.concat(e,t))):(e,t)=>{let n=new Uint8Array(t),r=0;for(let i of e)r+i.length>n.length&&(i=i.subarray(0,n.length-r)),n.set(i,r),r+=i.length;return n},Un=wt?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function ee(e,t){if(te(e)&&te(t))return e.compare(t);for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}function wn(e){let t=[],n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=i&63|128):(i&64512)===55296&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(e.charCodeAt(++r)&1023),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}function Tn(e,t,n){let r=[];for(;t<n;){let i=e[t],s=null,o=i>239?4:i>223?3:i>191?2:1;if(t+o<=n){let a,u,f,d;switch(o){case 1:i<128&&(s=i);break;case 2:a=e[t+1],(a&192)===128&&(d=(i&31)<<6|a&63,d>127&&(s=d));break;case 3:a=e[t+1],u=e[t+2],(a&192)===128&&(u&192)===128&&(d=(i&15)<<12|(a&63)<<6|u&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:a=e[t+1],u=e[t+2],f=e[t+3],(a&192)===128&&(u&192)===128&&(f&192)===128&&(d=(i&15)<<18|(a&63)<<12|(u&63)<<6|f&63,d>65535&&d<1114112&&(s=d))}}s===null?(s=65533,o=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|s&1023),r.push(s),t+=o}return Li(r)}var An=4096;function Li(e){let t=e.length;if(t<=An)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=An));return n}var Di=256,Nt=class{constructor(t=Di){this.chunkSize=t,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(t){let n=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let i=n.length-(this.maxCursor-this.cursor)-1;n.set(t,i)}else{if(n){let i=n.length-(this.maxCursor-this.cursor)-1;i<n.length&&(this.chunks[this.chunks.length-1]=n.subarray(0,i),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(n=Un(this.chunkSize),this.chunks.push(n),this.maxCursor+=n.length,this._initReuseChunk===null&&(this._initReuseChunk=n),n.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let n;if(this.chunks.length===1){let r=this.chunks[0];t&&this.cursor>r.length/2?(n=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):n=Tt(r,0,this.cursor)}else n=En(this.chunks,this.cursor);return t&&this.reset(),n}};var w="CBOR decode error:",Ie="CBOR encode error:",Rt=[];Rt[23]=1;Rt[24]=2;Rt[25]=3;Rt[26]=5;Rt[27]=9;function W(e,t,n){if(e.length-t<n)throw new Error(`${w} not enough data for type`)}var U=[24,256,65536,4294967296,BigInt("18446744073709551616")];function H(e,t,n){W(e,t,1);let r=e[t];if(n.strict===!0&&r<U[0])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return r}function B(e,t,n){W(e,t,2);let r=e[t]<<8|e[t+1];if(n.strict===!0&&r<U[1])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return r}function N(e,t,n){W(e,t,4);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(n.strict===!0&&r<U[2])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return r}function R(e,t,n){W(e,t,8);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3],i=e[t+4]*16777216+(e[t+5]<<16)+(e[t+6]<<8)+e[t+7],s=(BigInt(r)<<BigInt(32))+BigInt(i);if(n.strict===!0&&s<U[3])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(n.allowBigInt===!0)return s;throw new Error(`${w} integers outside of the safe integer range are not supported`)}function In(e,t,n,r){return new p(c.uint,H(e,t+1,r),2)}function vn(e,t,n,r){return new p(c.uint,B(e,t+1,r),3)}function _n(e,t,n,r){return new p(c.uint,N(e,t+1,r),5)}function Pn(e,t,n,r){return new p(c.uint,R(e,t+1,r),9)}function C(e,t){return v(e,0,t.value)}function v(e,t,n){if(n<U[0]){let r=Number(n);e.push([t|r])}else if(n<U[1]){let r=Number(n);e.push([t|24,r])}else if(n<U[2]){let r=Number(n);e.push([t|25,r>>>8,r&255])}else if(n<U[3]){let r=Number(n);e.push([t|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<U[4]){let i=[t|27,0,0,0,0,0,0,0],s=Number(r&BigInt(4294967295)),o=Number(r>>BigInt(32)&BigInt(4294967295));i[8]=s&255,s=s>>8,i[7]=s&255,s=s>>8,i[6]=s&255,s=s>>8,i[5]=s&255,i[4]=o&255,o=o>>8,i[3]=o&255,o=o>>8,i[2]=o&255,o=o>>8,i[1]=o&255,e.push(i)}else throw new Error(`${w} encountered BigInt larger than allowable range`)}}C.encodedSize=function(t){return v.encodedSize(t.value)};v.encodedSize=function(t){return t<U[0]?1:t<U[1]?2:t<U[2]?3:t<U[3]?5:9};C.compareTokens=function(t,n){return t.value<n.value?-1:t.value>n.value?1:0};function Hn(e,t,n,r){return new p(c.negint,-1-H(e,t+1,r),2)}function Bn(e,t,n,r){return new p(c.negint,-1-B(e,t+1,r),3)}function Nn(e,t,n,r){return new p(c.negint,-1-N(e,t+1,r),5)}var ve=BigInt(-1),Rn=BigInt(1);function Cn(e,t,n,r){let i=R(e,t+1,r);if(typeof i!="bigint"){let s=-1-i;if(s>=Number.MIN_SAFE_INTEGER)return new p(c.negint,s,9)}if(r.allowBigInt!==!0)throw new Error(`${w} integers outside of the safe integer range are not supported`);return new p(c.negint,ve-BigInt(i),9)}function ne(e,t){let n=t.value,r=typeof n=="bigint"?n*ve-Rn:n*-1-1;v(e,t.type.majorEncoded,r)}ne.encodedSize=function(t){let n=t.value,r=typeof n=="bigint"?n*ve-Rn:n*-1-1;return r<U[0]?1:r<U[1]?2:r<U[2]?3:r<U[3]?5:9};ne.compareTokens=function(t,n){return t.value<n.value?1:t.value>n.value?-1:0};function Ct(e,t,n,r){W(e,t,n+r);let i=Tt(e,t+n,t+n+r);return new p(c.bytes,i,n+r)}function Mn(e,t,n,r){return Ct(e,t,1,n)}function Ln(e,t,n,r){return Ct(e,t,2,H(e,t+1,r))}function Dn(e,t,n,r){return Ct(e,t,3,B(e,t+1,r))}function Gn(e,t,n,r){return Ct(e,t,5,N(e,t+1,r))}function On(e,t,n,r){let i=R(e,t+1,r);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer bytes lengths not supported`);return Ct(e,t,9,i)}function re(e){return e.encodedBytes===void 0&&(e.encodedBytes=e.type===c.string?Sn(e.value):e.value),e.encodedBytes}function At(e,t){let n=re(t);v(e,t.type.majorEncoded,n.length),e.push(n)}At.encodedSize=function(t){let n=re(t);return v.encodedSize(n.length)+n.length};At.compareTokens=function(t,n){return Oi(re(t),re(n))};function Oi(e,t){return e.length<t.length?-1:e.length>t.length?1:ee(e,t)}function Mt(e,t,n,r,i){let s=n+r;W(e,t,s);let o=new p(c.string,kn(e,t+n,t+s),s);return i.retainStringBytes===!0&&(o.byteValue=Tt(e,t+n,t+s)),o}function $n(e,t,n,r){return Mt(e,t,1,n,r)}function Fn(e,t,n,r){return Mt(e,t,2,H(e,t+1,r),r)}function Kn(e,t,n,r){return Mt(e,t,3,B(e,t+1,r),r)}function zn(e,t,n,r){return Mt(e,t,5,N(e,t+1,r),r)}function Zn(e,t,n,r){let i=R(e,t+1,r);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer string lengths not supported`);return Mt(e,t,9,i,r)}var Vn=At;function kt(e,t,n,r){return new p(c.array,r,n)}function Wn(e,t,n,r){return kt(e,t,1,n)}function jn(e,t,n,r){return kt(e,t,2,H(e,t+1,r))}function Yn(e,t,n,r){return kt(e,t,3,B(e,t+1,r))}function qn(e,t,n,r){return kt(e,t,5,N(e,t+1,r))}function Xn(e,t,n,r){let i=R(e,t+1,r);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer array lengths not supported`);return kt(e,t,9,i)}function Jn(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return kt(e,t,1,1/0)}function ie(e,t){v(e,c.array.majorEncoded,t.value)}ie.compareTokens=C.compareTokens;ie.encodedSize=function(t){return v.encodedSize(t.value)};function St(e,t,n,r){return new p(c.map,r,n)}function Qn(e,t,n,r){return St(e,t,1,n)}function tr(e,t,n,r){return St(e,t,2,H(e,t+1,r))}function er(e,t,n,r){return St(e,t,3,B(e,t+1,r))}function nr(e,t,n,r){return St(e,t,5,N(e,t+1,r))}function rr(e,t,n,r){let i=R(e,t+1,r);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer map lengths not supported`);return St(e,t,9,i)}function ir(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return St(e,t,1,1/0)}function se(e,t){v(e,c.map.majorEncoded,t.value)}se.compareTokens=C.compareTokens;se.encodedSize=function(t){return v.encodedSize(t.value)};function sr(e,t,n,r){return new p(c.tag,n,1)}function or(e,t,n,r){return new p(c.tag,H(e,t+1,r),2)}function ar(e,t,n,r){return new p(c.tag,B(e,t+1,r),3)}function cr(e,t,n,r){return new p(c.tag,N(e,t+1,r),5)}function ur(e,t,n,r){return new p(c.tag,R(e,t+1,r),9)}function oe(e,t){v(e,c.tag.majorEncoded,t.value)}oe.compareTokens=C.compareTokens;oe.encodedSize=function(t){return v.encodedSize(t.value)};var Vi=20,Wi=21,ji=22,Yi=23;function fr(e,t,n,r){if(r.allowUndefined===!1)throw new Error(`${w} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new p(c.null,null,1):new p(c.undefined,void 0,1)}function dr(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return new p(c.break,void 0,1)}function _e(e,t,n){if(n){if(n.allowNaN===!1&&Number.isNaN(e))throw new Error(`${w} NaN values are not supported`);if(n.allowInfinity===!1&&(e===1/0||e===-1/0))throw new Error(`${w} Infinity values are not supported`)}return new p(c.float,e,t)}function lr(e,t,n,r){return _e(Pe(e,t+1),3,r)}function hr(e,t,n,r){return _e(He(e,t+1),5,r)}function pr(e,t,n,r){return _e(xr(e,t+1),9,r)}function ae(e,t,n){let r=t.value;if(r===!1)e.push([c.float.majorEncoded|Vi]);else if(r===!0)e.push([c.float.majorEncoded|Wi]);else if(r===null)e.push([c.float.majorEncoded|ji]);else if(r===void 0)e.push([c.float.majorEncoded|Yi]);else{let i,s=!1;(!n||n.float64!==!0)&&(gr(r),i=Pe(D,1),r===i||Number.isNaN(r)?(D[0]=249,e.push(D.slice(0,3)),s=!0):(mr(r),i=He(D,1),r===i&&(D[0]=250,e.push(D.slice(0,5)),s=!0))),s||(qi(r),i=xr(D,1),D[0]=251,e.push(D.slice(0,9)))}}ae.encodedSize=function(t,n){let r=t.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!n||n.float64!==!0){gr(r);let i=Pe(D,1);if(r===i||Number.isNaN(r))return 3;if(mr(r),i=He(D,1),r===i)return 5}return 9};var yr=new ArrayBuffer(9),M=new DataView(yr,1),D=new Uint8Array(yr,0);function gr(e){if(e===1/0)M.setUint16(0,31744,!1);else if(e===-1/0)M.setUint16(0,64512,!1);else if(Number.isNaN(e))M.setUint16(0,32256,!1);else{M.setFloat32(0,e);let t=M.getUint32(0),n=(t&2139095040)>>23,r=t&8388607;if(n===255)M.setUint16(0,31744,!1);else if(n===0)M.setUint16(0,(e&2147483648)>>16|r>>13,!1);else{let i=n-127;i<-24?M.setUint16(0,0):i<-14?M.setUint16(0,(t&2147483648)>>16|1<<24+i,!1):M.setUint16(0,(t&2147483648)>>16|i+15<<10|r>>13,!1)}}}function Pe(e,t){if(e.length-t<2)throw new Error(`${w} not enough data for float16`);let n=(e[t]<<8)+e[t+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,i=n&1023,s;return r===0?s=i*2**-24:r!==31?s=(i+1024)*2**(r-25):s=i===0?1/0:NaN,n&32768?-s:s}function mr(e){M.setFloat32(0,e,!1)}function He(e,t){if(e.length-t<4)throw new Error(`${w} not enough data for float32`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,4).getFloat32(0,!1)}function qi(e){M.setFloat64(0,e,!1)}function xr(e,t){if(e.length-t<8)throw new Error(`${w} not enough data for float64`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,8).getFloat64(0,!1)}ae.compareTokens=C.compareTokens;function T(e,t,n){throw new Error(`${w} encountered invalid minor (${n}) for major ${e[t]>>>5}`)}function ce(e){return()=>{throw new Error(`${w} ${e}`)}}var h=[];for(let e=0;e<=23;e++)h[e]=T;h[24]=In;h[25]=vn;h[26]=_n;h[27]=Pn;h[28]=T;h[29]=T;h[30]=T;h[31]=T;for(let e=32;e<=55;e++)h[e]=T;h[56]=Hn;h[57]=Bn;h[58]=Nn;h[59]=Cn;h[60]=T;h[61]=T;h[62]=T;h[63]=T;for(let e=64;e<=87;e++)h[e]=Mn;h[88]=Ln;h[89]=Dn;h[90]=Gn;h[91]=On;h[92]=T;h[93]=T;h[94]=T;h[95]=ce("indefinite length bytes/strings are not supported");for(let e=96;e<=119;e++)h[e]=$n;h[120]=Fn;h[121]=Kn;h[122]=zn;h[123]=Zn;h[124]=T;h[125]=T;h[126]=T;h[127]=ce("indefinite length bytes/strings are not supported");for(let e=128;e<=151;e++)h[e]=Wn;h[152]=jn;h[153]=Yn;h[154]=qn;h[155]=Xn;h[156]=T;h[157]=T;h[158]=T;h[159]=Jn;for(let e=160;e<=183;e++)h[e]=Qn;h[184]=tr;h[185]=er;h[186]=nr;h[187]=rr;h[188]=T;h[189]=T;h[190]=T;h[191]=ir;for(let e=192;e<=215;e++)h[e]=sr;h[216]=or;h[217]=ar;h[218]=cr;h[219]=ur;h[220]=T;h[221]=T;h[222]=T;h[223]=T;for(let e=224;e<=243;e++)h[e]=ce("simple values are not supported");h[244]=T;h[245]=T;h[246]=T;h[247]=fr;h[248]=ce("simple values are not supported");h[249]=lr;h[250]=hr;h[251]=pr;h[252]=T;h[253]=T;h[254]=T;h[255]=dr;var F=[];for(let e=0;e<24;e++)F[e]=new p(c.uint,e,1);for(let e=-1;e>=-24;e--)F[31-e]=new p(c.negint,e,1);F[64]=new p(c.bytes,new Uint8Array(0),1);F[96]=new p(c.string,"",1);F[128]=new p(c.array,0,1);F[160]=new p(c.map,0,1);F[244]=new p(c.false,!1,1);F[245]=new p(c.true,!0,1);F[246]=new p(c.null,null,1);function br(e){switch(e.type){case c.false:return $([244]);case c.true:return $([245]);case c.null:return $([246]);case c.bytes:return e.value.length?void 0:$([64]);case c.string:return e.value===""?$([96]):void 0;case c.array:return e.value===0?$([128]):void 0;case c.map:return e.value===0?$([160]):void 0;case c.uint:return e.value<24?$([Number(e.value)]):void 0;case c.negint:if(e.value>=-24)return $([31-Number(e.value)])}}var Tr=Object.freeze({float64:!0,mapSorter:es,quickEncodeToken:br});function Ji(){let e=[];return e[c.uint.major]=C,e[c.negint.major]=ne,e[c.bytes.major]=At,e[c.string.major]=Vn,e[c.array.major]=ie,e[c.map.major]=se,e[c.tag.major]=oe,e[c.float.major]=ae,e}var Qi=Ji(),Be=new Nt,fe=class e{constructor(t,n){this.obj=t,this.parent=n}includes(t){let n=this;do if(n.obj===t)return!0;while(n=n.parent);return!1}static createCheck(t,n){if(t&&t.includes(n))throw new Error(`${Ie} object contains circular references`);return new e(n,t)}},Q={null:new p(c.null,null),undefined:new p(c.undefined,void 0),true:new p(c.true,!0),false:new p(c.false,!1),emptyArray:new p(c.array,0),emptyMap:new p(c.map,0)},tt={number(e,t,n,r){return!Number.isInteger(e)||!Number.isSafeInteger(e)?new p(c.float,e):e>=0?new p(c.uint,e):new p(c.negint,e)},bigint(e,t,n,r){return e>=BigInt(0)?new p(c.uint,e):new p(c.negint,e)},Uint8Array(e,t,n,r){return new p(c.bytes,e)},string(e,t,n,r){return new p(c.string,e)},boolean(e,t,n,r){return e?Q.true:Q.false},null(e,t,n,r){return Q.null},undefined(e,t,n,r){return Q.undefined},ArrayBuffer(e,t,n,r){return new p(c.bytes,new Uint8Array(e))},DataView(e,t,n,r){return new p(c.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))},Array(e,t,n,r){if(!e.length)return n.addBreakTokens===!0?[Q.emptyArray,new p(c.break)]:Q.emptyArray;r=fe.createCheck(r,e);let i=[],s=0;for(let o of e)i[s++]=ue(o,n,r);return n.addBreakTokens?[new p(c.array,e.length),i,new p(c.break)]:[new p(c.array,e.length),i]},Object(e,t,n,r){let i=t!=="Object",s=i?e.keys():Object.keys(e),o=i?e.size:s.length;if(!o)return n.addBreakTokens===!0?[Q.emptyMap,new p(c.break)]:Q.emptyMap;r=fe.createCheck(r,e);let a=[],u=0;for(let f of s)a[u++]=[ue(f,n,r),ue(i?e.get(f):e[f],n,r)];return ts(a,n),n.addBreakTokens?[new p(c.map,o),a,new p(c.break)]:[new p(c.map,o),a]}};tt.Map=tt.Object;tt.Buffer=tt.Uint8Array;for(let e of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))tt[`${e}Array`]=tt.DataView;function ue(e,t={},n){let r=bn(e),i=t&&t.typeEncoders&&t.typeEncoders[r]||tt[r];if(typeof i=="function"){let o=i(e,r,t,n);if(o!=null)return o}let s=tt[r];if(!s)throw new Error(`${Ie} unsupported type: ${r}`);return s(e,r,t,n)}function ts(e,t){t.mapSorter&&e.sort(t.mapSorter)}function es(e,t){if(e[0]instanceof p&&t[0]instanceof p){let n=e[0],r=t[0];return n._keyBytes||(n._keyBytes=wr(n.value)),r._keyBytes||(r._keyBytes=wr(r.value)),ee(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function wr(e){return ns(e,Qi,Tr)}function Ar(e,t,n,r){if(Array.isArray(t))for(let i of t)Ar(e,i,n,r);else n[t.type.major](e,t,r)}function ns(e,t,n){let r=ue(e,n);if(!Array.isArray(r)&&n.quickEncodeToken){let i=n.quickEncodeToken(r);if(i)return i;let s=t[r.type.major];if(s.encodedSize){let o=s.encodedSize(r,n),a=new Nt(o);if(s(a,r,n),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${r} was wrong`);return Ue(a.chunks[0])}}return Be.reset(),Ar(Be,r,t,n),Be.toBytes(!0)}var ko=Symbol.for("DONE"),So=Symbol.for("BREAK");function is(e){let t=e;if(typeof t.toBase64=="function")return t.toBase64();let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return btoa(n)}function Ne(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function de(e){return is(e).replace(/\\+/g,"-").replace(/\\//g,"_").replace(/=+$/,"")}function kr(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";return Ne(t)}function Sr(e){let n=new TextEncoder().encode(e);return de(n)}function Er(e){let t=kr(e);return new TextDecoder().decode(t)}function le(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}Bt.hmacSha256Sync=(e,...t)=>Ee(rt,e,Bt.concatBytes(...t));var Et=65;var Re=32,Ur=5,Ir=16;function vr(){return mn.randomPrivateKey()}function _r(e){return dn(e,!0)}function Ce(e,t){let n=yn(t,e,{lowS:!0}),r=n.recovery;if(r===void 0)throw new Error("Recovery ID not available");let i=new Uint8Array(Et),s=n.toCompactRawBytes();return i.set(s,0),i[64]=r,i}function Me(e,t){if(t.length!==Et)throw new Error(`Signature must be ${Et} bytes`);let n=t[64];if(n===void 0||n>3)throw new Error(`Invalid recovery ID: ${n}, must be 0-3`);let r=t.subarray(0,64);return _t.fromCompact(r).addRecoveryBit(n).recoverPublicKey(e).toRawBytes(!0)}function Pr(e,t,n){try{let r=Me(t,n);return le(r,e)}catch{return!1}}function Lt(e,t,n){let r=new Uint8Array(20+n.length);return r.set(e,0),new DataView(r.buffer).setUint32(16,t,!0),r.set(n,20),rt(r)}function Hr(e,t,n,r){let i=new Uint8Array(20+Re+Et);return i.set(e,0),new DataView(i.buffer).setUint32(16,t,!0),i.set(n,20),i.set(r,20+Re),rt(i)}function Br(e){if(e.length===0)return new Uint8Array(Re);let t=0;for(let s of e)t+=Ur+s.payload.length+Et;let n=new Uint8Array(t),r=new DataView(n.buffer),i=0;for(let s of e){let o=s.payload.length;r.setUint32(i,s.targetTick,!0),r.setUint8(i+4,o),n.set(s.payload,i+5),n.set(s.sig,i+5+o),i+=Ur+o+Et}return rt(n)}var Nr=253,Rr=8,Cr=32,Mr=1,Lr=60,Dr=1,Gr=255,ss=/^[a-z0-9.-]+$/,os=/^[a-z0-9-]+$/,as=/^[a-zA-Z0-9.-]+(:[0-9]+)?$/;var Dt=class e{constructor(t){y(this,"version");y(this,"authority");y(this,"appID");y(this,"path");y(this,"tickRate");y(this,"maxParticipants");y(this,"maxTicks");y(this,"startTime");y(this,"credentials");if(this.version=t.version,this.authority=t.authority??"",this.appID=t.appID,typeof t.path=="string"){let n=t.path.replace(/^\\/+|\\/+$/g,"");this.path=n===""?[]:n.split("/")}else this.path=t.path;this.tickRate=t.tickRate,this.maxParticipants=t.maxParticipants,this.maxTicks=t.maxTicks,this.startTime=t.startTime,this.credentials=t.credentials??"",this.validate()}validate(){if(this.version!=="v1")throw new Error(`Invalid version: must be "v1", got "${this.version}"`);if(!this.appID)throw new Error("AppID is required");if(this.appID.length>Nr)throw new Error(`AppID too long: ${this.appID.length} chars (max ${Nr})`);if(!ss.test(this.appID))throw new Error(`Invalid appID format: "${this.appID}" (must be lowercase DNS-style)`);if(this.path.length>Rr)throw new Error(`Too many path segments: ${this.path.length} (max ${Rr})`);for(let t=0;t<this.path.length;t++){let n=this.path[t];if(n==="")throw new Error(`Path segment ${t} is empty`);if(n.length>Cr)throw new Error(`Path segment ${t} too long: ${n.length} chars (max ${Cr})`);if(!os.test(n))throw new Error(`Invalid path segment ${t}: "${n}" (must be [a-z0-9-]+)`)}if(!Number.isInteger(this.tickRate))throw new Error(`Invalid tickRate: must be an integer, got ${this.tickRate}`);if(this.tickRate<Mr||this.tickRate>Lr)throw new Error(`Invalid tickRate: must be ${Mr}-${Lr}, got ${this.tickRate}`);if(!Number.isInteger(this.maxParticipants))throw new Error(`Invalid maxParticipants: must be an integer, got ${this.maxParticipants}`);if(this.maxParticipants<Dr||this.maxParticipants>Gr)throw new Error(`Invalid maxParticipants: must be ${Dr}-${Gr}, got ${this.maxParticipants}`);if(!Number.isInteger(this.maxTicks))throw new Error(`Invalid maxTicks: must be an integer, got ${this.maxTicks}`);if(this.maxTicks<1||this.maxTicks>864e3)throw new Error(`Invalid maxTicks: must be 1-864000, got ${this.maxTicks}`);if(this.maxTicks<this.tickRate)throw new Error(`Invalid maxTicks: must be >= tickRate (${this.tickRate}) for at least 1 second duration, got ${this.maxTicks}`);if(!Number.isInteger(this.startTime))throw new Error(`Invalid startTime: must be an integer, got ${this.startTime}`);if(this.startTime<=0)throw new Error(`Invalid startTime: must be > 0, got ${this.startTime}`)}toGenesisHash(){this.validate();let t=new TextEncoder,n=t.encode("multitap:genesis:v1:"),r=t.encode(this.appID),i=n.length+r.length+1;for(let d of this.path)i+=t.encode(d).length+1;i+=6,i+=8;let s=new Uint8Array(i),o=0;s.set(n,o),o+=n.length,s.set(r,o),o+=r.length,s[o++]=0;for(let d of this.path){let l=t.encode(d);s.set(l,o),o+=l.length,s[o++]=0}s[o++]=this.tickRate,s[o++]=this.maxParticipants,s[o++]=this.maxTicks>>24&255,s[o++]=this.maxTicks>>16&255,s[o++]=this.maxTicks>>8&255,s[o++]=this.maxTicks&255;let a=Math.floor(this.startTime/4294967296),u=this.startTime>>>0;return s[o++]=a>>24&255,s[o++]=a>>16&255,s[o++]=a>>8&255,s[o++]=a&255,s[o++]=u>>24&255,s[o++]=u>>16&255,s[o++]=u>>8&255,s[o++]=u&255,rt(s).slice(0,Ir)}toConnectionURL(){if(this.validate(),!this.authority)throw new Error("Authority is required for connection URL");if(!as.test(this.authority))throw new Error(`Invalid authority format: "${this.authority}"`);let n="/"+["s",this.appID,...this.path].join("/"),r=new URLSearchParams;return this.credentials&&r.set("join",this.credentials),r.set("max",this.maxParticipants.toString()),r.set("rate",this.tickRate.toString()),this.startTime!==0&&r.set("start",this.startTime.toString()),r.set("ticks",this.maxTicks.toString()),`multitap://${this.authority}${n}?${r.toString()}`}toHTTPSURL(){return this.toConnectionURL().replace("multitap://","https://")}toBase64EncodedConnectionURL(){let t=this.toConnectionURL();return Sr(t)}static fromBase64EncodedConnectionURL(t){let n=Er(t);return e.fromConnectionURL(n)}static fromConnectionURL(t){let n=new URL(t);if(n.protocol!=="multitap:"&&n.protocol!=="https:")throw new Error(`Invalid URL scheme: must be multitap:// or https://, got ${n.protocol}`);let r=n.pathname.replace(/^\\/+|\\/+$/g,""),i=r===""?[]:r.split("/");if(i.length<2||i[0]!=="s")throw new Error("Invalid URL path: must start with /s/{appID}");let s=i[1],o=i.slice(2),a=n.searchParams,u=a.get("rate"),f=a.get("max");if(!u)throw new Error("Missing required query parameter: rate");if(!f)throw new Error("Missing required query parameter: max");let d=parseInt(u,10),l=parseInt(f,10),m=a.get("ticks");if(!m)throw new Error("Missing required query parameter: ticks");let x=parseInt(m,10),b=a.get("start"),A=b?parseInt(b,10):0,I=a.get("join")??"",E=new e({version:"v1",authority:n.host,appID:s,path:o,tickRate:d,maxParticipants:l,maxTicks:x,startTime:A,credentials:I});return E.validate(),E}};function Or(e){return 5+e+65}function Le(e){return 5+e+65+1}var dt={encodeInput(e,t,n){if(t.length>255)throw new Error(`Payload must be 255 bytes or less, got ${t.length}`);if(n.length!==65)throw new Error(`Signature must be 65 bytes, got ${n.length}`);let r=Or(t.length),i=new ArrayBuffer(3+r),s=new DataView(i),o=new Uint8Array(i);return s.setUint8(0,3),s.setUint16(1,r,!0),s.setUint32(3,e,!0),s.setUint8(7,t.length),o.set(t,8),o.set(n,8+t.length),o},encodePong(e,t){let n=new ArrayBuffer(11),r=new DataView(n);return r.setUint8(0,2),r.setUint16(1,8,!0),r.setUint32(3,e,!0),r.setUint32(7,t,!0),new Uint8Array(n)},encodeTick(e){let t=Math.min(e.inputs.length,16),n=0;for(let u=0;u<t;u++)n+=Le(e.inputs[u].payload.length);let r=70+n,i=new ArrayBuffer(3+r),s=new DataView(i),o=new Uint8Array(i);s.setUint8(0,4),s.setUint16(1,r,!0),s.setUint32(3,e.tick,!0),o.set(e.sig,7),s.setUint8(72,t);let a=73;for(let u=0;u<t;u++){let f=e.inputs[u],d=f.payload.length;s.setUint32(a,f.targetTick,!0),s.setUint8(a+4,d),o.set(f.payload,a+5),o.set(f.sig,a+5+d),s.setUint8(a+5+d+65,f.idx),a+=Le(d)}return o},decode(e){if(e.length<3)throw new Error("Message too short");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint8(0),r=t.getUint16(1,!0);if(e.length<3+r)throw new Error("Message truncated");switch(n){case 1:{let i={type:"ping",tickRate:t.getUint16(3,!0),isReplay:!1,replayStart:0,replayEnd:0};return r>=11&&(i.isReplay=t.getUint8(5)===1,i.isReplay&&(i.replayStart=t.getUint32(6,!0),i.replayEnd=t.getUint32(10,!0))),i}case 4:return this.decodeTick(e.subarray(3,3+r));case 3:return this.decodeInput(e);default:throw new Error(`Unknown message type: ${n}`)}},decodeTick(e){if(e.length<70)throw new Error("Tick payload too short");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0),r=e.subarray(4,69),i=Math.min(t.getUint8(69),16),s=[],o=70;for(let a=0;a<i;a++){if(o+5>e.length)throw new Error(`Tick payload truncated at input ${a} header`);let u=t.getUint32(o,!0),f=t.getUint8(o+4),d=Le(f);if(o+d>e.length)throw new Error(`Tick payload truncated at input ${a} (need ${d} bytes)`);let l=t.getUint8(o+5+f+65);s.push({targetTick:u,payload:e.subarray(o+5,o+5+f),sig:e.subarray(o+5+f,o+5+f+65),idx:l}),o+=d}return{type:"tick",tick:n,sig:r,inputs:s}},decodeInput(e){if(e.length<73)throw new Error("Input message too short");let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t.getUint8(0)!==3)throw new Error(`Not an input message: type=${t.getUint8(0)}`);let n=t.getUint16(1,!0);if(n<70)throw new Error(`Input message too short: ${n} bytes, minimum 70`);if(e.length<3+n)throw new Error("Input message truncated");let r=t.getUint32(3,!0),i=t.getUint8(7),s=Or(i);if(n<s)throw new Error(`Input payload truncated: claimed ${i} bytes, only ${n-5-65} available`);return{type:"input",targetTick:r,payload:e.subarray(8,8+i),signature:e.subarray(8+i,8+i+65)}}};var j=!0;var Gt=()=>{},he={log:(...e)=>{j&&console.log(...e)},warn:(...e)=>{j&&console.warn(...e)},error:(...e)=>{j&&console.error(...e)},info:(...e)=>{j&&console.info(...e)},debug:(...e)=>{j&&console.debug(...e)},group:e=>{j&&console.group(e)},groupEnd:()=>{j&&console.groupEnd()},table:e=>{j&&console.table(e)},get raw(){return j?console:{log:Gt,warn:Gt,error:Gt,info:Gt,debug:Gt}}};function Y(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var pe=class{constructor(t){y(this,"debug");y(this,"genesisHash");y(this,"genesis");y(this,"syncNodesById",new Map);y(this,"syncHead");y(this,"predictedHead");y(this,"pendingSyncMessages",new Map);y(this,"nodeIdSequence",0);y(this,"optimisticInputs",[]);y(this,"participantBySlot",new Map);y(this,"inputPayloadPredictor",null);y(this,"verificationPubKey",null);y(this,"maxTicks");y(this,"logSyncTicks");y(this,"onParticipantJoined",null);this.genesisHash=t.genesisHash,this.genesis={id:this.generateNodeId(),parent:null,syncPrev:null,syncNext:null,tick:0,sig:new Uint8Array(65),payloads:[],sync:!0},this.syncHead=this.genesis,this.predictedHead=this.syncHead,this.syncNodesById.set(this.genesis.id,this.genesis),this.maxTicks=t.maxTicks,this.inputPayloadPredictor=t.inputPayloadPredictor??null,this.verificationPubKey=t.verificationPubKey||null,this.debug=t.debug??!1,this.logSyncTicks=t.logSyncTicks??!1,this.logSyncNodeForTests(this.genesis)}setOnParticipantJoined(t){this.onParticipantJoined=t}getSyncHead(){return this.syncHead}getPredictedHead(){return this.predictedHead}addSyncTick(t){if(t.tick<=this.syncHead.tick){this.debug&&he.warn("skipping sync tick that is older than the sync head (duplicate?)",t.tick,this.syncHead.tick);return}this.pendingSyncMessages.set(t.tick,t),this.optimisticInputs=this.optimisticInputs.filter(n=>{for(let r of t.inputs)if(le(r.sig,n.sig))return!1;return!0}),this.updateHeads()}recoverInputPubKey(t){let n=Lt(this.genesisHash,t.targetTick,t.payload);return Me(n,t.sig)}addOptimisticInput(t,n){if(t.targetTick>=this.maxTicks||!Kr(t.targetTick,this.syncHead.tick))return;let r=this.predictedHead.tick-this.syncHead.tick;if(r>=20){this.debug&&he.warn(`unable to add optimistic input as we are already ${r} ticks ahead of the sync chain`);return}let i=n??this.recoverInputPubKey(t),s=Array.from(this.participantBySlot.values()).find(o=>o.id===Y(i));if(!s){this.debug&&he.warn("skipping optimistic tick from unknown participant",t.targetTick,Y(i));return}this.optimisticInputs.push({...t,idx:s.slot}),this.updateHeads()}getParticipantSlots(t){let n=Array.from(this.participantBySlot.values()).filter(r=>r.joined<=t).sort((r,i)=>r.slot-i.slot);for(let r=0;r<n.length;r++){let i=n[r];if(i===void 0)throw new Error(`invariant: participant slot ${r} is undefined`);if(i.slot!==r)throw new Error(`invariant: participant slot ${r} is not sequential`)}return n}getTicksAfter(t,n){let r=this.getSyncChainForkPointFromNodeId(t),i=n?.limit,s=[],o=this.predictedHead,a=n?.lag??0;for(;o&&(o.sync&&(a=0),a>0?a--:n?.sync&&!o.sync||s.push({id:o.id,tick:o.tick,payloads:o.payloads,sync:o.sync}),o!==r);)o=o.parent;return i&&s.length>=i?s.reverse().slice(0,i):s.reverse()}getPredictionCount(){let t=0,n=this.predictedHead;for(;n&&!n.sync;)n.pending||t++,n=n.parent;return t}getSyncTicksAfter(t){let n=t?this.syncNodesById.get(t):this.genesis;if(!n)throw new Error(`invalid nodeId ${t} not found in graph`);if(!n.sync)throw new Error(`node ${t} is not on the sync chain`);let r=[],i=this.syncHead;for(;i;){if(i===n){t===null&&r.push(i);break}r.push(i),i=i.parent}return r.reverse()}getSyncChainForkPointFromNodeId(t){if(!t)return this.genesis;if(t.includes("/")){let n=t.split("/")[0];return this.syncNodesById.get(n)??this.genesis}return this.syncNodesById.get(t)??this.genesis}getPendingSyncMessages(){return Array.from(this.pendingSyncMessages.entries()).sort((t,n)=>t[0]-n[0])}verifyTickSignature(t,n,r,i){if(!this.verificationPubKey)return!1;let s=Br(n.map(a=>({targetTick:a.targetTick,payload:a.payload,sig:a.sig,idx:a.idx}))),o=Hr(this.genesisHash,t,s,i);if(!Pr(this.verificationPubKey,o,r))throw new Error(`Invalid relay signature for tick ${t}. `);return!0}getOrderedPayloadsAtTick(t,n){return this.getParticipantSlots(t).map(r=>r?n.find(s=>s.idx===r.slot)?.payload??new Uint8Array(0):new Uint8Array(0))}updateHeads(){let t=this.syncHead.tick;for(let[n,r]of this.getPendingSyncMessages()){if(n<=this.syncHead.tick){this.pendingSyncMessages.delete(n);continue}if(n>t&&(t=n),n===this.syncHead.tick+1){let i=this.verifyTickSignature(r.tick,r.inputs,r.sig,this.syncHead.sig);for(let o of r.inputs)this.ensureParticipantJoined(r.tick,o);let s={id:this.generateNodeId(),parent:this.syncHead,syncPrev:this.syncHead,syncNext:null,tick:r.tick,sig:r.sig,payloads:this.getOrderedPayloadsAtTick(r.tick,r.inputs),sync:!0,verified:i};this.syncHead.syncNext=s,this.syncHead=s,this.pendingSyncMessages.delete(n),this.syncNodesById.set(s.id,s),this.logSyncNodeForTests(s);continue}else break}if(this.optimisticInputs=this.optimisticInputs.filter(n=>n.targetTick>this.syncHead.tick),t=Math.max(t,this.optimisticInputs.reduce((n,r)=>r.targetTick>n?r.targetTick:n,this.syncHead.tick)),this.predictedHead=this.syncHead,t>this.syncHead.tick){let n=this.optimisticInputs.slice().sort((i,s)=>i.targetTick-s.targetTick),r=this.syncHead;for(let i=this.syncHead.tick+1;i<=t;i++){let s=!1,o=this.pendingSyncMessages.get(i);o?s=!0:o=this.dequeuePrediction(i,n,this.predictedHead);let a={id:this.generateNodeId(r),parent:this.predictedHead,syncPrev:r,syncNext:null,tick:i,sig:o.sig,payloads:this.getOrderedPayloadsAtTick(i,o.inputs),sync:!1,pending:s};this.predictedHead=a}}}ensureParticipantJoined(t,n){if(n.idx<0)throw new Error(`invariant: participant slot ${n.idx} is invalid`);if(!this.participantBySlot.get(n.idx)){let i=this.recoverInputPubKey(n),s={id:Y(i),pubKey:i,slot:n.idx,joined:t};this.participantBySlot.set(n.idx,s),this.onParticipantJoined&&this.onParticipantJoined(s)}}logSyncNodeForTests(t){this.logSyncTicks&&console.log(`SYNC ${JSON.stringify({tick:t.tick,sig:Y(t.sig),payloads:t.payloads.map(n=>Y(n)),participants:this.getParticipantSlots(t.tick).map(n=>n?.id??""),sync:!0})}`)}dequeuePrediction(t,n,r){let i=this.getParticipantSlots(t).map(a=>{if(!a||a.slot<0)throw new Error(`invariant: participant slot "${a?.slot}" invalid`);return{targetTick:t,payload:this.inputPayloadPredictor?this.inputPayloadPredictor(t,a.slot,r):new Uint8Array(0),sig:new Uint8Array(0),idx:a.slot}}),s=0,o=[];for(let a of n.slice()){if(s>=i.length)break;if(a.targetTick>t||!Kr(a.targetTick,t))continue;let u=i[a.idx];if(!u)throw new Error(`invariant: participant slot ${a.idx} not found in inputs`);if(!(u.payload.length>0)){u.payload=a.payload,o.push(a),s++;break}}for(let a of o)n.splice(n.indexOf(a),1);return{type:"tick",tick:t,inputs:i,sig:new Uint8Array(65)}}generateNodeId(t){return this.nodeIdSequence++,t?`${t.id}/${this.nodeIdSequence}`:`${this.nodeIdSequence}`}};function Kr(e,t){let n=Math.max(0,t-10),r=t+10;return e>=n&&e<=r}var Ot=class{constructor(t=1e3,n=1024){y(this,"buffer");y(this,"windowMs");y(this,"head",0);y(this,"tail",0);y(this,"size",0);this.windowMs=t,this.buffer=new Float64Array(n)}inc(){let t=performance.now();this.buffer[this.head]=t,this.head=(this.head+1)%this.buffer.length,this.size<this.buffer.length?this.size++:this.tail=(this.tail+1)%this.buffer.length}count(t=performance.now()){let n=t-this.windowMs;for(;this.size>0&&!(this.buffer[this.tail]>=n);)this.tail=(this.tail+1)%this.buffer.length,this.size--;return this.size}rate(t=performance.now()){return this.count(t)*(1e3/this.windowMs)}};var ge=class{constructor(t){y(this,"connectionURL");y(this,"serverCertHash");y(this,"connectionTimeoutMs");y(this,"privateKey");y(this,"publicKey");y(this,"genesisHash");y(this,"sessionConfig");y(this,"transport");y(this,"streams");y(this,"replayStreams");y(this,"roundRobinIndex");y(this,"connectionGeneration");y(this,"connected");y(this,"stopped");y(this,"debug");y(this,"logSyncTicks");y(this,"outbox");y(this,"stateListeners");y(this,"flushingOutbox");y(this,"tickRate");y(this,"inputGraph");y(this,"tickDeadlineWants",0);y(this,"tickDeadlineTimer",null);y(this,"tickDeadlineGrace",33);y(this,"stats");this.debug=t.debug??!1,this.connectionURL=t.connectionURL,this.serverCertHash=t.serverCertHash,this.connectionTimeoutMs=t.connectionTimeoutMs??5e3,this.privateKey=t.privateKey??vr(),this.publicKey=_r(this.privateKey),this.logSyncTicks=t.logSyncTicks??!1,this.sessionConfig=Dt.fromConnectionURL(t.connectionURL),this.genesisHash=this.sessionConfig.toGenesisHash(),this.transport=null,this.streams=[],this.replayStreams=new Set,this.roundRobinIndex=0,this.connectionGeneration=0,this.connected=!1,this.stopped=!1,this.outbox=[],this.stateListeners=new Set,this.flushingOutbox=!1,this.tickRate=0,this.inputGraph=new pe({genesisHash:this.genesisHash,maxTicks:this.sessionConfig.maxTicks,inputPayloadPredictor:t.inputPayloadPredictor,verificationPubKey:t.relayPubKey,debug:this.debug,logSyncTicks:this.logSyncTicks}),this.stats={messagesRecv:new Ot,messagesSent:new Ot,reconnections:0},t.autoConnect!==!1&&this._connectLoop().catch(ye)}async connect(){if(this.stopped)throw new Error("Channel has been stopped");!this.transport&&!this.connected&&this._connectLoop().catch(ye)}async getPublicKey(){return this.publicKey}async getGenesisHash(){return this.genesisHash}onStateChange(t){return this.stateListeners.add(t),t(this.connected),()=>{this.stateListeners.delete(t)}}getStats(){return{activeStreams:this.streams.length,totalStreams:this.streams.length,messagesRecv:this.stats.messagesRecv.rate(),messagesSent:this.stats.messagesSent.rate(),reconnections:this.stats.reconnections}}async getTickRate(){return this.tickRate}async getParticipantSlots(t){return this.inputGraph.getParticipantSlots(t)}async getSyncHead(){return this.inputGraph.getSyncHead()}async getPredictedHead(){return this.inputGraph.getPredictedHead()}async addSyncTick(t){this.inputGraph.addSyncTick(t)}async addOptimisticInput(t,n){this.inputGraph.addOptimisticInput(t,n)}async getPredictionCount(){return this.inputGraph.getPredictionCount()}async getTicksAfter(t,n){return this.inputGraph.getTicksAfter(t,n)}async setOnParticipantJoined(t){this.inputGraph.setOnParticipantJoined(t)}async expose(t){ht(this,t)}async close(){if(this.stopped=!0,this.tickDeadlineTimer&&(clearTimeout(this.tickDeadlineTimer),this.tickDeadlineTimer=null),this.transport)try{this.transport.close({closeCode:0,reason:"stopped"})}catch{}}_setConnected(t){if(this.connected!==t){this.connected=t;for(let n of this.stateListeners)try{n(t)}catch{}}}async _send(t){if(!(t instanceof Uint8Array))throw new Error("send() requires Uint8Array");if(this.connected&&this.streams.length>0)for(let n=0;n<this.streams.length;n++){let r=this._nextStream();if(!r)break;try{await r.writer.write(t),this.stats.messagesSent.inc();return}catch{if(this._dropStream(r),!this.connected)break}}this.outbox.push(t)}_generateNullInput(){let t=new Uint8Array(0),n=Lt(this.genesisHash,4294967295,t),r=Ce(this.privateKey,n);return dt.encodeInput(4294967295,t,r)}async sendSignedInput(t,n){if(t.length>255)throw new Error(`Payload must be ${255} bytes or less, got ${t.length}`);let r=n;r===void 0&&(r=this.inputGraph.getPredictedHead().tick+1);let i=Lt(this.genesisHash,r,t),s=Ce(this.privateKey,i),o=Y(this.publicKey),a=this.inputGraph.getParticipantSlots(r).find(f=>f.id===o);a&&this.inputGraph.addOptimisticInput({targetTick:r,payload:t,sig:s,idx:a.slot},this.publicKey);let u=dt.encodeInput(r,t,s);return await this._send(u),u}_nextStream(){return this.streams.length===0?null:(this.roundRobinIndex>=this.streams.length&&(this.roundRobinIndex=0),this.streams[this.roundRobinIndex++]??null)}async _connectLoop(){let t=0;for(;!this.stopped;){try{let r=this._generateNullInput(),i=de(r),o=new Dt({...this.sessionConfig,credentials:i}).toBase64EncodedConnectionURL(),a="https://"+this.sessionConfig.authority,u=new URL(`${a}/connect?session=${o}`),f={};if(this.serverCertHash){let b=Ne(this.serverCertHash);f.serverCertificateHashes=[{algorithm:"sha-256",value:b.buffer}]}let d=new AbortController,l=setTimeout(()=>d.abort(),this.connectionTimeoutMs),m=await fetch(u.toString(),{method:"HEAD",signal:d.signal});if(clearTimeout(l),!m.ok){console.warn("server not reachable, retry in 1s"),await new Promise(b=>setTimeout(b,1e3));continue}let x=new WebTransport(u.toString(),f);await x.ready,this.transport=x,this.stats.reconnections++,this._setConnected(!0),this.connectionGeneration++,this.streams=[],this.replayStreams.clear(),this.roundRobinIndex=0,t=0,this._acceptStreamsLoop(x,this.connectionGeneration).catch(ye),await x.closed}catch(r){console.warn("connect loop error",r),t++}if(this._setConnected(!1),this._cleanupTransport(),this.stopped)break;let n=Math.min(t*250,1e3);await new Promise(r=>setTimeout(r,n))}console.log("connect loop exited")}async _acceptStreamsLoop(t,n){let r=t.incomingBidirectionalStreams.getReader(),i=0;try{for(;;){let{value:s,done:o}=await r.read();if(o)break;let a=s;if(a){if(this.connectionGeneration!==n||this.transport!==t||this.stopped){try{a.readable.cancel().catch(()=>{})}catch{}try{a.writable.getWriter().close().catch(()=>{})}catch{}break}this._addStream(a,i++,n)}}}catch{try{t.close()}catch{}}finally{try{r.releaseLock()}catch{}}}_addStream(t,n,r){let i=t.writable.getWriter(),s=t.readable.getReader(),o={stream:t,writer:i,reader:s,index:n,isReplay:!1,generation:r};this.streams.push(o),this._readLoop(o).catch(()=>{this._dropStream(o)}),this.outbox.length>0&&this._flushOutbox().catch(ye)}_dropStream(t){if(t.generation!==this.connectionGeneration){this._cleanupHandle(t);return}if(t.isReplay){this.replayStreams.delete(t),this._cleanupHandle(t);return}let n=this.streams.indexOf(t);n>=0&&(this.streams.splice(n,1),this.roundRobinIndex>n&&this.roundRobinIndex--),this._cleanupHandle(t)}_cleanupHandle(t){t.pongInterval&&(clearInterval(t.pongInterval),t.pongInterval=null);try{t.reader.cancel().catch(()=>{})}catch{}try{t.writer.releaseLock()}catch{}}async _flushOutbox(){if(!this.flushingOutbox){this.flushingOutbox=!0;try{for(;this.outbox.length>0&&this.streams.length>0&&this.connected&&!this.stopped;){let t=this.outbox.shift();if(!t)break;let n=this._nextStream();if(!n){this.outbox.unshift(t);break}try{await n.writer.write(t),this.stats.messagesSent.inc()}catch{this._dropStream(n),this.outbox.unshift(t);break}}}finally{this.flushingOutbox=!1}}}_cleanupTransport(){let t=[...this.streams,...this.replayStreams];this.streams=[],this.replayStreams.clear(),this.roundRobinIndex=0;for(let r of t)this._cleanupHandle(r);let n=this.transport;if(this.transport=null,n)try{n.close({closeCode:0,reason:"cleanup"})}catch{}}async _readLoop(t){let r=new Uint8Array(0);for(;;){let i=await t.reader.read(),{value:s,done:o}=i;if(o)break;if(!s)continue;r=this._concatBuffers(r,s);let a=0;for(;r.length>=3;){let u=new DataView(r.buffer,r.byteOffset,r.byteLength),f=u.getUint8(0),l=3+u.getUint16(1,!0);if(r.length<l)break;let m=r.slice(0,l);if(r=r.slice(l),a++,this.stats.messagesRecv.inc(),f===1){let x=dt.decode(m);if(this.tickRate=x.tickRate,x.isReplay){t.isReplay=!0;let E=this.streams.indexOf(t);E>=0&&t.generation===this.connectionGeneration&&(this.streams.splice(E,1),this.roundRobinIndex>E&&this.roundRobinIndex--,this.replayStreams.add(t)),t.pongInterval=setInterval(()=>{let k=this.inputGraph.getSyncHead(),_=this.inputGraph.getPredictedHead(),Vr=dt.encodePong(k.tick,_.tick);t.writer.write(Vr).catch(()=>{t.pongInterval&&clearInterval(t.pongInterval)})},1e3)}let b=this.inputGraph.getSyncHead(),A=this.inputGraph.getPredictedHead(),I=dt.encodePong(b.tick,A.tick);t.writer.write(I).catch(()=>{this._dropStream(t)})}else if(f===4){let x=dt.decode(m);try{this.inputGraph.addSyncTick(x),this._maybeResetDeadline()}catch(b){this.debug&&console.warn("Failed to process tick message:",b instanceof Error?b.message:b,x)}}else this.debug&&console.warn("dropped unknown message type:",f);if(a>=256&&(await new Promise(x=>setTimeout(x,0)),a=0,t.generation!==this.connectionGeneration))return}}}_maybeResetDeadline(){let t=this.inputGraph.getSyncHead();t.tick>=this.tickDeadlineWants&&this._resetDeadline(t.tick+1)}_resetDeadline(t){this.tickDeadlineWants=t,this.tickDeadlineTimer&&clearTimeout(this.tickDeadlineTimer),this.tickRate&&(this.tickDeadlineTimer=setTimeout(this._onTickDeadlineExceeded.bind(this),1e3/this.tickRate+this.tickDeadlineGrace))}_onTickDeadlineExceeded(){let t=this.inputGraph.getParticipantSlots(this.tickDeadlineWants).find(n=>n.id===Y(this.publicKey));if(t)try{this.inputGraph.addOptimisticInput({targetTick:this.tickDeadlineWants,payload:new Uint8Array(0),sig:new Uint8Array(0),idx:t.slot},this.publicKey)}catch(n){this.debug&&console.error("failed to add empty optimistic input:",n instanceof Error?n.message:n)}else this.debug&&console.warn("unable to add empty optimistic input as we do not have a slot assigned yet");this._resetDeadline(this.tickDeadlineWants+1)}_concatBuffers(t,n){let r=new Uint8Array(t.length+n.length);return r.set(t,0),r.set(n,t.length),r}};function ye(e){console.warn("channel unexpected:",e)}ht(ge);var ma=null;globalThis.onerror=e=>(console.error("\\u{1F534} FATAL CHANNEL WORKER ERROR (Uncaught Exception):",e),!0);export{ma as default};\n/*! Bundled license information:\n\ncomlink/dist/esm/comlink.mjs:\n (**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n *)\n\n@noble/hashes/esm/utils.js:\n (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)\n\n@noble/secp256k1/index.js:\n (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)\n*/\n';
|
|
6000
|
+
// src/rollback.worker.ts
|
|
6001
|
+
var workerCode = 'var Or=Object.defineProperty;var Fr=(t,e,n)=>e in t?Or(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var y=(t,e,n)=>Fr(t,typeof e!="symbol"?e+"":e,n);var Dt=Symbol("Comlink.proxy"),Nr=Symbol("Comlink.endpoint"),Rr=Symbol("Comlink.releaseProxy"),ut=Symbol("Comlink.finalizer"),ve=Symbol("Comlink.thrown"),Lt=t=>typeof t=="object"&&t!==null||typeof t=="function",Dr={canHandle:t=>Lt(t)&&t[Dt],serialize(t){let{port1:e,port2:n}=new MessageChannel;return Be(t,e),[n,[n]]},deserialize(t){return t.start(),lt(t)}},Lr={canHandle:t=>Lt(t)&&ve in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},Ht=new Map([["proxy",Dr],["throw",Lr]]);function Hr(t,e){for(let n of t)if(e===n||n==="*"||n instanceof RegExp&&n.test(e))return!0;return!1}function Be(t,e=globalThis,n=["*"]){e.addEventListener("message",function r(i){if(!i||!i.data)return;if(!Hr(n,i.origin)){console.warn(`Invalid origin \'${i.origin}\' for comlink proxy`);return}let{id:o,type:s,path:a}=Object.assign({path:[]},i.data),c=(i.data.argumentList||[]).map(W),u;try{let f=a.slice(0,-1).reduce((g,S)=>g[S],t),p=a.reduce((g,S)=>g[S],t);switch(s){case"GET":u=p;break;case"SET":f[a.slice(-1)[0]]=W(i.data.value),u=!0;break;case"APPLY":u=p.apply(f,c);break;case"CONSTRUCT":{let g=new p(...c);u=qr(g)}break;case"ENDPOINT":{let{port1:g,port2:S}=new MessageChannel;Be(t,S),u=Zr(g,[g])}break;case"RELEASE":u=void 0;break;default:return}}catch(f){u={value:f,[ve]:0}}Promise.resolve(u).catch(f=>({value:f,[ve]:0})).then(f=>{let[p,g]=Ie(f);e.postMessage(Object.assign(Object.assign({},p),{id:o}),g),s==="RELEASE"&&(e.removeEventListener("message",r),Mt(e),ut in t&&typeof t[ut]=="function"&&t[ut]())}).catch(f=>{let[p,g]=Ie({value:new TypeError("Unserializable return value"),[ve]:0});e.postMessage(Object.assign(Object.assign({},p),{id:o}),g)})}),e.start&&e.start()}function Mr(t){return t.constructor.name==="MessagePort"}function Mt(t){Mr(t)&&t.close()}function lt(t,e){let n=new Map;return t.addEventListener("message",function(i){let{data:o}=i;if(!o||!o.id)return;let s=n.get(o.id);if(s)try{s(o)}finally{n.delete(o.id)}}),ft(t,n,[],e)}function Ae(t){if(t)throw new Error("Proxy has been released and is not useable")}function zt(t){return te(t,new Map,{type:"RELEASE"}).then(()=>{Mt(t)})}var Ue=new WeakMap,Ce="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{let e=(Ue.get(t)||0)-1;Ue.set(t,e),e===0&&zt(t)});function zr(t,e){let n=(Ue.get(e)||0)+1;Ue.set(e,n),Ce&&Ce.register(t,e,t)}function Vr(t){Ce&&Ce.unregister(t)}function ft(t,e,n=[],r=function(){}){let i=!1,o=new Proxy(r,{get(s,a){if(Ae(i),a===Rr)return()=>{Vr(o),zt(t),e.clear(),i=!0};if(a==="then"){if(n.length===0)return{then:()=>o};let c=te(t,e,{type:"GET",path:n.map(u=>u.toString())}).then(W);return c.then.bind(c)}return ft(t,e,[...n,a])},set(s,a,c){Ae(i);let[u,f]=Ie(c);return te(t,e,{type:"SET",path:[...n,a].map(p=>p.toString()),value:u},f).then(W)},apply(s,a,c){Ae(i);let u=n[n.length-1];if(u===Nr)return te(t,e,{type:"ENDPOINT"}).then(W);if(u==="bind")return ft(t,e,n.slice(0,-1));let[f,p]=Rt(c);return te(t,e,{type:"APPLY",path:n.map(g=>g.toString()),argumentList:f},p).then(W)},construct(s,a){Ae(i);let[c,u]=Rt(a);return te(t,e,{type:"CONSTRUCT",path:n.map(f=>f.toString()),argumentList:c},u).then(W)}});return zr(o,t),o}function Gr(t){return Array.prototype.concat.apply([],t)}function Rt(t){let e=t.map(Ie);return[e.map(n=>n[0]),Gr(e.map(n=>n[1]))]}var Vt=new WeakMap;function Zr(t,e){return Vt.set(t,e),t}function qr(t){return Object.assign(t,{[Dt]:!0})}function Ie(t){for(let[e,n]of Ht)if(n.canHandle(t)){let[r,i]=n.serialize(t);return[{type:"HANDLER",name:e,value:r},i]}return[{type:"RAW",value:t},Vt.get(t)||[]]}function W(t){switch(t.type){case"HANDLER":return Ht.get(t.name).deserialize(t.value);case"RAW":return t.value}}function te(t,e,n,r){return new Promise(i=>{let o=Kr();e.set(o,i),t.start&&t.start(),t.postMessage(Object.assign({id:o},n),r)})}function Kr(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var Wr={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:Y,n:ht,Gx:jr,Gy:Yr,b:Yt}=Wr,ne=32,dt=64,U=(t="")=>{throw new Error(t)},Xt=t=>typeof t=="bigint",Jt=t=>typeof t=="string",Xr=t=>t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array",me=(t,e)=>!Xr(t)||typeof e=="number"&&e>0&&t.length!==e?U("Uint8Array expected"):t,Ne=t=>new Uint8Array(t),Jr=t=>Uint8Array.from(t),Qt=(t,e)=>t.toString(16).padStart(e,"0"),yt=t=>Array.from(me(t)).map(e=>Qt(e,2)).join(""),z={_0:48,_9:57,A:65,F:70,a:97,f:102},Gt=t=>{if(t>=z._0&&t<=z._9)return t-z._0;if(t>=z.A&&t<=z.F)return t-(z.A-10);if(t>=z.a&&t<=z.f)return t-(z.a-10)},gt=t=>{let e="hex invalid";if(!Jt(t))return U(e);let n=t.length,r=n/2;if(n%2)return U(e);let i=Ne(r);for(let o=0,s=0;o<r;o++,s+=2){let a=Gt(t.charCodeAt(s)),c=Gt(t.charCodeAt(s+1));if(a===void 0||c===void 0)return U(e);i[o]=a*16+c}return i},bt=(t,e)=>me(Jt(t)?gt(t):Jr(me(t)),e),en=()=>globalThis?.crypto,Qr=()=>en()?.subtle??U("crypto.subtle must be defined"),Pe=(...t)=>{let e=Ne(t.reduce((r,i)=>r+me(i).length,0)),n=0;return t.forEach(r=>{e.set(r,n),n+=r.length}),e},ei=(t=ne)=>en().getRandomValues(Ne(t)),$e=BigInt,he=(t,e,n,r="bad number: out of range")=>Xt(t)&&e<=t&&t<n?t:U(r),h=(t,e=Y)=>{let n=t%e;return n>=0n?n:e+n};var tn=(t,e)=>{(t===0n||e<=0n)&&U("no inverse n="+t+" mod="+e);let n=h(t,e),r=e,i=0n,o=1n,s=1n,a=0n;for(;n!==0n;){let c=r/n,u=r%n,f=i-s*c,p=o-a*c;r=n,n=u,i=s,o=a,s=f,a=p}return r===1n?h(i,e):U("no inverse")};var Zt=t=>t instanceof X?t:U("Point expected"),nn=t=>h(h(t*t)*t+Yt),qt=t=>he(t,0n,Y),_e=t=>he(t,1n,Y),ti=t=>he(t,1n,ht),pt=t=>(t&1n)===0n,rn=t=>Uint8Array.of(t),ni=t=>rn(pt(t)?2:3),ri=t=>{let e=nn(_e(t)),n=1n;for(let r=e,i=(Y+1n)/4n;i>0n;i>>=1n)i&1n&&(n=n*r%Y),r=r*r%Y;return h(n*n)===e?n:U("sqrt invalid")},D=class D{constructor(e,n,r){y(this,"px");y(this,"py");y(this,"pz");this.px=qt(e),this.py=_e(n),this.pz=qt(r),Object.freeze(this)}static fromBytes(e){me(e);let n,r=e[0],i=e.subarray(1),o=Kt(i,0,ne),s=e.length;if(s===ne+1&&[2,3].includes(r)){let a=ri(o),c=pt(a);pt($e(r))!==c&&(a=h(-a)),n=new D(o,a,1n)}return s===dt+1&&r===4&&(n=new D(o,Kt(i,ne,dt),1n)),n?n.assertValidity():U("bad point: not on curve")}equals(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Zt(e),c=h(n*a),u=h(o*i),f=h(r*a),p=h(s*i);return c===u&&f===p}is0(){return this.equals(j)}negate(){return new D(this.px,h(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Zt(e),c=0n,u=Yt,f=0n,p=0n,g=0n,S=h(u*3n),k=h(n*o),A=h(r*s),O=h(i*a),ee=h(n+r),v=h(o+s);ee=h(ee*v),v=h(k+A),ee=h(ee-v),v=h(n+i);let R=h(o+a);return v=h(v*R),R=h(k+O),v=h(v-R),R=h(r+i),f=h(s+a),R=h(R*f),f=h(A+O),R=h(R-f),g=h(c*v),f=h(S*O),g=h(f+g),f=h(A-g),g=h(A+g),p=h(f*g),A=h(k+k),A=h(A+k),O=h(c*O),v=h(S*v),A=h(A+O),O=h(k-O),O=h(c*O),v=h(v+O),k=h(A*v),p=h(p+k),k=h(R*v),f=h(ee*f),f=h(f-k),k=h(ee*A),g=h(R*g),g=h(g+k),new D(f,p,g)}multiply(e,n=!0){if(!n&&e===0n)return j;if(ti(e),e===1n)return this;if(this.equals(re))return fi(e).p;let r=j,i=re;for(let o=this;e>0n;o=o.double(),e>>=1n)e&1n?r=r.add(o):n&&(i=i.add(o));return r}toAffine(){let{px:e,py:n,pz:r}=this;if(this.equals(j))return{x:0n,y:0n};if(r===1n)return{x:e,y:n};let i=tn(r,Y);return h(r*i)!==1n&&U("inverse invalid"),{x:h(e*i),y:h(n*i)}}assertValidity(){let{x:e,y:n}=this.toAffine();return _e(e),_e(n),h(n*n)===nn(e)?this:U("bad point: not on curve")}toBytes(e=!0){let{x:n,y:r}=this.assertValidity().toAffine(),i=Oe(n);return e?Pe(ni(r),i):Pe(rn(4),i,Oe(r))}static fromAffine(e){let{x:n,y:r}=e;return n===0n&&r===0n?j:new D(n,r,1n)}toHex(e){return yt(this.toBytes(e))}static fromPrivateKey(e){return re.multiply(oi(e))}static fromHex(e){return D.fromBytes(bt(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}toRawBytes(e){return this.toBytes(e)}};y(D,"BASE"),y(D,"ZERO");var X=D,re=new X(jr,Yr,1n),j=new X(0n,1n,0n);X.BASE=re;X.ZERO=j;var Re=t=>$e("0x"+(yt(t)||"0")),Kt=(t,e,n)=>Re(t.subarray(e,n)),ii=2n**256n,Oe=t=>gt(Qt(he(t,0n,ii),dt)),oi=t=>{let e=Xt(t)?t:Re(bt(t,ne));return he(e,1n,ht,"private key invalid 3")};var si=t=>{t=bt(t),(t.length<ne+8||t.length>1024)&&U("expected 40-1024b");let e=h(Re(t),ht-1n);return Oe(e+1n)};var ai="SHA-256",xt={hexToBytes:gt,bytesToHex:yt,concatBytes:Pe,bytesToNumberBE:Re,numberToBytesBE:Oe,mod:h,invert:tn,hmacSha256Async:async(t,...e)=>{let n=Qr(),r="HMAC",i=await n.importKey("raw",t,{name:r,hash:{name:ai}},!1,["sign"]);return Ne(await n.sign(r,i,Pe(...e)))},hmacSha256Sync:void 0,hashToPrivateKey:si,randomBytes:ei};var Fe=8,ci=256,on=Math.ceil(ci/Fe)+1,mt=2**(Fe-1),ui=()=>{let t=[],e=re,n=e;for(let r=0;r<on;r++){n=e,t.push(n);for(let i=1;i<mt;i++)n=n.add(e),t.push(n);e=n.double()}return t},Wt,jt=(t,e)=>{let n=e.negate();return t?n:e},fi=t=>{let e=Wt||(Wt=ui()),n=j,r=re,i=2**Fe,o=i,s=$e(i-1),a=$e(Fe);for(let c=0;c<on;c++){let u=Number(t&s);t>>=a,u>mt&&(u-=o,t+=1n);let f=c*mt,p=f,g=f+Math.abs(u)-1,S=c%2!==0,k=u<0;u===0?r=r.add(jt(S,e[p])):n=n.add(jt(k,e[g]))}return{p:n,f:r}};function di(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function sn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function oe(t,...e){if(!di(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function an(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");sn(t.outputLen),sn(t.blockLen)}function se(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function cn(t,e){oe(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function J(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function De(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function F(t,e){return t<<32-e|t>>>e}function pi(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ye(t){return typeof t=="string"&&(t=pi(t)),oe(t),t}var ie=class{};function un(t){let e=r=>t().update(ye(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function mi(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);let i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,u=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+u,a,r)}function fn(t,e,n){return t&e^~t&n}function ln(t,e,n){return t&e^t&n^e&n}var Le=class extends ie{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=De(this.buffer)}update(e){se(this),e=ye(e),oe(e);let{view:n,buffer:r,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=De(e);for(;i<=o-s;s+=i)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){se(this),cn(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;n[s++]=128,J(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let p=s;p<i;p++)n[p]=0;mi(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=De(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)a.setUint32(4*p,f[p],o)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},V=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var hi=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Z=new Uint32Array(64),He=class extends Le{constructor(e=32){super(64,e,8,!1),this.A=V[0]|0,this.B=V[1]|0,this.C=V[2]|0,this.D=V[3]|0,this.E=V[4]|0,this.F=V[5]|0,this.G=V[6]|0,this.H=V[7]|0}get(){let{A:e,B:n,C:r,D:i,E:o,F:s,G:a,H:c}=this;return[e,n,r,i,o,s,a,c]}set(e,n,r,i,o,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let p=0;p<16;p++,n+=4)Z[p]=e.getUint32(n,!1);for(let p=16;p<64;p++){let g=Z[p-15],S=Z[p-2],k=F(g,7)^F(g,18)^g>>>3,A=F(S,17)^F(S,19)^S>>>10;Z[p]=A+Z[p-7]+k+Z[p-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:u,H:f}=this;for(let p=0;p<64;p++){let g=F(a,6)^F(a,11)^F(a,25),S=f+g+fn(a,c,u)+hi[p]+Z[p]|0,A=(F(r,2)^F(r,13)^F(r,22))+ln(r,i,o)|0;f=u,u=c,c=a,a=s+S|0,s=o,o=i,i=r,r=S+A|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,i,o,s,a,c,u,f)}roundClean(){J(Z)}destroy(){this.set(0,0,0,0,0,0,0,0),J(this.buffer)}};var ge=un(()=>new He);var wt=ge;var Me=class extends ie{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,an(e);let r=ye(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),J(o)}update(e){return se(this),this.iHash.update(e),this}digestInto(e){se(this),oe(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},St=(t,e,n)=>new Me(t,e).update(n).digest();St.create=(t,e)=>new Me(t,e);var yi=["string","number","bigint","symbol"],gi=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function dn(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(yi.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(bi(t))return"Buffer";let n=xi(t);return n||"Object"}function bi(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function xi(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(gi.includes(e))return e}var l=class{constructor(e,n,r){this.major=e,this.majorEncoded=e<<5,this.name=n,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};l.uint=new l(0,"uint",!0);l.negint=new l(1,"negint",!0);l.bytes=new l(2,"bytes",!0);l.string=new l(3,"string",!0);l.array=new l(4,"array",!1);l.map=new l(5,"map",!1);l.tag=new l(6,"tag",!1);l.float=new l(7,"float",!0);l.false=new l(7,"false",!0);l.true=new l(7,"true",!0);l.null=new l(7,"null",!0);l.undefined=new l(7,"undefined",!0);l.break=new l(7,"break",!0);var m=class{constructor(e,n,r){this.type=e,this.value=n,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var ae=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",wi=new TextDecoder,Si=new TextEncoder;function ze(t){return ae&&globalThis.Buffer.isBuffer(t)}function Et(t){return t instanceof Uint8Array?ze(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var yn=ae?(t,e,n)=>n-e>64?globalThis.Buffer.from(t.subarray(e,n)).toString("utf8"):mn(t,e,n):(t,e,n)=>n-e>64?wi.decode(t.subarray(e,n)):mn(t,e,n),gn=ae?t=>t.length>64?globalThis.Buffer.from(t):pn(t):t=>t.length>64?Si.encode(t):pn(t),L=t=>Uint8Array.from(t),ce=ae?(t,e,n)=>ze(t)?new Uint8Array(t.subarray(e,n)):t.slice(e,n):(t,e,n)=>t.slice(e,n),bn=ae?(t,e)=>(t=t.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),Et(globalThis.Buffer.concat(t,e))):(t,e)=>{let n=new Uint8Array(e),r=0;for(let i of t)r+i.length>n.length&&(i=i.subarray(0,n.length-r)),n.set(i,r),r+=i.length;return n},xn=ae?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Ve(t,e){if(ze(t)&&ze(e))return t.compare(e);for(let n=0;n<t.length;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return 0}function pn(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e}function mn(t,e,n){let r=[];for(;e<n;){let i=t[e],o=null,s=i>239?4:i>223?3:i>191?2:1;if(e+s<=n){let a,c,u,f;switch(s){case 1:i<128&&(o=i);break;case 2:a=t[e+1],(a&192)===128&&(f=(i&31)<<6|a&63,f>127&&(o=f));break;case 3:a=t[e+1],c=t[e+2],(a&192)===128&&(c&192)===128&&(f=(i&15)<<12|(a&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:a=t[e+1],c=t[e+2],u=t[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(f=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),e+=s}return Ei(r)}var hn=4096;function Ei(t){let e=t.length;if(e<=hn)return String.fromCharCode.apply(String,t);let n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=hn));return n}var ki=256,be=class{constructor(e=ki){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let n=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=n.length-(this.maxCursor-this.cursor)-1;n.set(e,i)}else{if(n){let i=n.length-(this.maxCursor-this.cursor)-1;i<n.length&&(this.chunks[this.chunks.length-1]=n.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(n=xn(this.chunkSize),this.chunks.push(n),this.maxCursor+=n.length,this._initReuseChunk===null&&(this._initReuseChunk=n),n.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let n;if(this.chunks.length===1){let r=this.chunks[0];e&&this.cursor>r.length/2?(n=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):n=ce(r,0,this.cursor)}else n=bn(this.chunks,this.cursor);return e&&this.reset(),n}};var b="CBOR decode error:",kt="CBOR encode error:",xe=[];xe[23]=1;xe[24]=2;xe[25]=3;xe[26]=5;xe[27]=9;function G(t,e,n){if(t.length-e<n)throw new Error(`${b} not enough data for type`)}var E=[24,256,65536,4294967296,BigInt("18446744073709551616")];function C(t,e,n){G(t,e,1);let r=t[e];if(n.strict===!0&&r<E[0])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function I(t,e,n){G(t,e,2);let r=t[e]<<8|t[e+1];if(n.strict===!0&&r<E[1])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function B(t,e,n){G(t,e,4);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(n.strict===!0&&r<E[2])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function _(t,e,n){G(t,e,8);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],i=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],o=(BigInt(r)<<BigInt(32))+BigInt(i);if(n.strict===!0&&o<E[3])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(n.allowBigInt===!0)return o;throw new Error(`${b} integers outside of the safe integer range are not supported`)}function wn(t,e,n,r){return new m(l.uint,C(t,e+1,r),2)}function Sn(t,e,n,r){return new m(l.uint,I(t,e+1,r),3)}function En(t,e,n,r){return new m(l.uint,B(t,e+1,r),5)}function kn(t,e,n,r){return new m(l.uint,_(t,e+1,r),9)}function P(t,e){return T(t,0,e.value)}function T(t,e,n){if(n<E[0]){let r=Number(n);t.push([e|r])}else if(n<E[1]){let r=Number(n);t.push([e|24,r])}else if(n<E[2]){let r=Number(n);t.push([e|25,r>>>8,r&255])}else if(n<E[3]){let r=Number(n);t.push([e|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<E[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(r&BigInt(4294967295)),s=Number(r>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,t.push(i)}else throw new Error(`${b} encountered BigInt larger than allowable range`)}}P.encodedSize=function(e){return T.encodedSize(e.value)};T.encodedSize=function(e){return e<E[0]?1:e<E[1]?2:e<E[2]?3:e<E[3]?5:9};P.compareTokens=function(e,n){return e.value<n.value?-1:e.value>n.value?1:0};function Tn(t,e,n,r){return new m(l.negint,-1-C(t,e+1,r),2)}function An(t,e,n,r){return new m(l.negint,-1-I(t,e+1,r),3)}function vn(t,e,n,r){return new m(l.negint,-1-B(t,e+1,r),5)}var Tt=BigInt(-1),Un=BigInt(1);function Cn(t,e,n,r){let i=_(t,e+1,r);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new m(l.negint,o,9)}if(r.allowBigInt!==!0)throw new Error(`${b} integers outside of the safe integer range are not supported`);return new m(l.negint,Tt-BigInt(i),9)}function Ge(t,e){let n=e.value,r=typeof n=="bigint"?n*Tt-Un:n*-1-1;T(t,e.type.majorEncoded,r)}Ge.encodedSize=function(e){let n=e.value,r=typeof n=="bigint"?n*Tt-Un:n*-1-1;return r<E[0]?1:r<E[1]?2:r<E[2]?3:r<E[3]?5:9};Ge.compareTokens=function(e,n){return e.value<n.value?1:e.value>n.value?-1:0};function we(t,e,n,r){G(t,e,n+r);let i=ce(t,e+n,e+n+r);return new m(l.bytes,i,n+r)}function In(t,e,n,r){return we(t,e,1,n)}function Bn(t,e,n,r){return we(t,e,2,C(t,e+1,r))}function _n(t,e,n,r){return we(t,e,3,I(t,e+1,r))}function Pn(t,e,n,r){return we(t,e,5,B(t,e+1,r))}function $n(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer bytes lengths not supported`);return we(t,e,9,i)}function Ze(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===l.string?gn(t.value):t.value),t.encodedBytes}function ue(t,e){let n=Ze(e);T(t,e.type.majorEncoded,n.length),t.push(n)}ue.encodedSize=function(e){let n=Ze(e);return T.encodedSize(n.length)+n.length};ue.compareTokens=function(e,n){return Ai(Ze(e),Ze(n))};function Ai(t,e){return t.length<e.length?-1:t.length>e.length?1:Ve(t,e)}function Se(t,e,n,r,i){let o=n+r;G(t,e,o);let s=new m(l.string,yn(t,e+n,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=ce(t,e+n,e+o)),s}function On(t,e,n,r){return Se(t,e,1,n,r)}function Fn(t,e,n,r){return Se(t,e,2,C(t,e+1,r),r)}function Nn(t,e,n,r){return Se(t,e,3,I(t,e+1,r),r)}function Rn(t,e,n,r){return Se(t,e,5,B(t,e+1,r),r)}function Dn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer string lengths not supported`);return Se(t,e,9,i,r)}var Ln=ue;function fe(t,e,n,r){return new m(l.array,r,n)}function Hn(t,e,n,r){return fe(t,e,1,n)}function Mn(t,e,n,r){return fe(t,e,2,C(t,e+1,r))}function zn(t,e,n,r){return fe(t,e,3,I(t,e+1,r))}function Vn(t,e,n,r){return fe(t,e,5,B(t,e+1,r))}function Gn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer array lengths not supported`);return fe(t,e,9,i)}function Zn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return fe(t,e,1,1/0)}function qe(t,e){T(t,l.array.majorEncoded,e.value)}qe.compareTokens=P.compareTokens;qe.encodedSize=function(e){return T.encodedSize(e.value)};function le(t,e,n,r){return new m(l.map,r,n)}function qn(t,e,n,r){return le(t,e,1,n)}function Kn(t,e,n,r){return le(t,e,2,C(t,e+1,r))}function Wn(t,e,n,r){return le(t,e,3,I(t,e+1,r))}function jn(t,e,n,r){return le(t,e,5,B(t,e+1,r))}function Yn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer map lengths not supported`);return le(t,e,9,i)}function Xn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return le(t,e,1,1/0)}function Ke(t,e){T(t,l.map.majorEncoded,e.value)}Ke.compareTokens=P.compareTokens;Ke.encodedSize=function(e){return T.encodedSize(e.value)};function Jn(t,e,n,r){return new m(l.tag,n,1)}function Qn(t,e,n,r){return new m(l.tag,C(t,e+1,r),2)}function er(t,e,n,r){return new m(l.tag,I(t,e+1,r),3)}function tr(t,e,n,r){return new m(l.tag,B(t,e+1,r),5)}function nr(t,e,n,r){return new m(l.tag,_(t,e+1,r),9)}function We(t,e){T(t,l.tag.majorEncoded,e.value)}We.compareTokens=P.compareTokens;We.encodedSize=function(e){return T.encodedSize(e.value)};var _i=20,Pi=21,$i=22,Oi=23;function rr(t,e,n,r){if(r.allowUndefined===!1)throw new Error(`${b} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new m(l.null,null,1):new m(l.undefined,void 0,1)}function ir(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return new m(l.break,void 0,1)}function At(t,e,n){if(n){if(n.allowNaN===!1&&Number.isNaN(t))throw new Error(`${b} NaN values are not supported`);if(n.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${b} Infinity values are not supported`)}return new m(l.float,t,e)}function or(t,e,n,r){return At(vt(t,e+1),3,r)}function sr(t,e,n,r){return At(Ut(t,e+1),5,r)}function ar(t,e,n,r){return At(lr(t,e+1),9,r)}function je(t,e,n){let r=e.value;if(r===!1)t.push([l.float.majorEncoded|_i]);else if(r===!0)t.push([l.float.majorEncoded|Pi]);else if(r===null)t.push([l.float.majorEncoded|$i]);else if(r===void 0)t.push([l.float.majorEncoded|Oi]);else{let i,o=!1;(!n||n.float64!==!0)&&(ur(r),i=vt(N,1),r===i||Number.isNaN(r)?(N[0]=249,t.push(N.slice(0,3)),o=!0):(fr(r),i=Ut(N,1),r===i&&(N[0]=250,t.push(N.slice(0,5)),o=!0))),o||(Fi(r),i=lr(N,1),N[0]=251,t.push(N.slice(0,9)))}}je.encodedSize=function(e,n){let r=e.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!n||n.float64!==!0){ur(r);let i=vt(N,1);if(r===i||Number.isNaN(r))return 3;if(fr(r),i=Ut(N,1),r===i)return 5}return 9};var cr=new ArrayBuffer(9),$=new DataView(cr,1),N=new Uint8Array(cr,0);function ur(t){if(t===1/0)$.setUint16(0,31744,!1);else if(t===-1/0)$.setUint16(0,64512,!1);else if(Number.isNaN(t))$.setUint16(0,32256,!1);else{$.setFloat32(0,t);let e=$.getUint32(0),n=(e&2139095040)>>23,r=e&8388607;if(n===255)$.setUint16(0,31744,!1);else if(n===0)$.setUint16(0,(t&2147483648)>>16|r>>13,!1);else{let i=n-127;i<-24?$.setUint16(0,0):i<-14?$.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):$.setUint16(0,(e&2147483648)>>16|i+15<<10|r>>13,!1)}}}function vt(t,e){if(t.length-e<2)throw new Error(`${b} not enough data for float16`);let n=(t[e]<<8)+t[e+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,i=n&1023,o;return r===0?o=i*2**-24:r!==31?o=(i+1024)*2**(r-25):o=i===0?1/0:NaN,n&32768?-o:o}function fr(t){$.setFloat32(0,t,!1)}function Ut(t,e){if(t.length-e<4)throw new Error(`${b} not enough data for float32`);let n=(t.byteOffset||0)+e;return new DataView(t.buffer,n,4).getFloat32(0,!1)}function Fi(t){$.setFloat64(0,t,!1)}function lr(t,e){if(t.length-e<8)throw new Error(`${b} not enough data for float64`);let n=(t.byteOffset||0)+e;return new DataView(t.buffer,n,8).getFloat64(0,!1)}je.compareTokens=P.compareTokens;function x(t,e,n){throw new Error(`${b} encountered invalid minor (${n}) for major ${t[e]>>>5}`)}function Ye(t){return()=>{throw new Error(`${b} ${t}`)}}var d=[];for(let t=0;t<=23;t++)d[t]=x;d[24]=wn;d[25]=Sn;d[26]=En;d[27]=kn;d[28]=x;d[29]=x;d[30]=x;d[31]=x;for(let t=32;t<=55;t++)d[t]=x;d[56]=Tn;d[57]=An;d[58]=vn;d[59]=Cn;d[60]=x;d[61]=x;d[62]=x;d[63]=x;for(let t=64;t<=87;t++)d[t]=In;d[88]=Bn;d[89]=_n;d[90]=Pn;d[91]=$n;d[92]=x;d[93]=x;d[94]=x;d[95]=Ye("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)d[t]=On;d[120]=Fn;d[121]=Nn;d[122]=Rn;d[123]=Dn;d[124]=x;d[125]=x;d[126]=x;d[127]=Ye("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)d[t]=Hn;d[152]=Mn;d[153]=zn;d[154]=Vn;d[155]=Gn;d[156]=x;d[157]=x;d[158]=x;d[159]=Zn;for(let t=160;t<=183;t++)d[t]=qn;d[184]=Kn;d[185]=Wn;d[186]=jn;d[187]=Yn;d[188]=x;d[189]=x;d[190]=x;d[191]=Xn;for(let t=192;t<=215;t++)d[t]=Jn;d[216]=Qn;d[217]=er;d[218]=tr;d[219]=nr;d[220]=x;d[221]=x;d[222]=x;d[223]=x;for(let t=224;t<=243;t++)d[t]=Ye("simple values are not supported");d[244]=x;d[245]=x;d[246]=x;d[247]=rr;d[248]=Ye("simple values are not supported");d[249]=or;d[250]=sr;d[251]=ar;d[252]=x;d[253]=x;d[254]=x;d[255]=ir;var H=[];for(let t=0;t<24;t++)H[t]=new m(l.uint,t,1);for(let t=-1;t>=-24;t--)H[31-t]=new m(l.negint,t,1);H[64]=new m(l.bytes,new Uint8Array(0),1);H[96]=new m(l.string,"",1);H[128]=new m(l.array,0,1);H[160]=new m(l.map,0,1);H[244]=new m(l.false,!1,1);H[245]=new m(l.true,!0,1);H[246]=new m(l.null,null,1);function dr(t){switch(t.type){case l.false:return L([244]);case l.true:return L([245]);case l.null:return L([246]);case l.bytes:return t.value.length?void 0:L([64]);case l.string:return t.value===""?L([96]):void 0;case l.array:return t.value===0?L([128]):void 0;case l.map:return t.value===0?L([160]):void 0;case l.uint:return t.value<24?L([Number(t.value)]):void 0;case l.negint:if(t.value>=-24)return L([31-Number(t.value)])}}var mr=Object.freeze({float64:!0,mapSorter:Hi,quickEncodeToken:dr});function Ri(){let t=[];return t[l.uint.major]=P,t[l.negint.major]=Ge,t[l.bytes.major]=ue,t[l.string.major]=Ln,t[l.array.major]=qe,t[l.map.major]=Ke,t[l.tag.major]=We,t[l.float.major]=je,t}var Di=Ri(),Ct=new be,Je=class t{constructor(e,n){this.obj=e,this.parent=n}includes(e){let n=this;do if(n.obj===e)return!0;while(n=n.parent);return!1}static createCheck(e,n){if(e&&e.includes(n))throw new Error(`${kt} object contains circular references`);return new t(n,e)}},q={null:new m(l.null,null),undefined:new m(l.undefined,void 0),true:new m(l.true,!0),false:new m(l.false,!1),emptyArray:new m(l.array,0),emptyMap:new m(l.map,0)},K={number(t,e,n,r){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new m(l.float,t):t>=0?new m(l.uint,t):new m(l.negint,t)},bigint(t,e,n,r){return t>=BigInt(0)?new m(l.uint,t):new m(l.negint,t)},Uint8Array(t,e,n,r){return new m(l.bytes,t)},string(t,e,n,r){return new m(l.string,t)},boolean(t,e,n,r){return t?q.true:q.false},null(t,e,n,r){return q.null},undefined(t,e,n,r){return q.undefined},ArrayBuffer(t,e,n,r){return new m(l.bytes,new Uint8Array(t))},DataView(t,e,n,r){return new m(l.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,n,r){if(!t.length)return n.addBreakTokens===!0?[q.emptyArray,new m(l.break)]:q.emptyArray;r=Je.createCheck(r,t);let i=[],o=0;for(let s of t)i[o++]=Xe(s,n,r);return n.addBreakTokens?[new m(l.array,t.length),i,new m(l.break)]:[new m(l.array,t.length),i]},Object(t,e,n,r){let i=e!=="Object",o=i?t.keys():Object.keys(t),s=i?t.size:o.length;if(!s)return n.addBreakTokens===!0?[q.emptyMap,new m(l.break)]:q.emptyMap;r=Je.createCheck(r,t);let a=[],c=0;for(let u of o)a[c++]=[Xe(u,n,r),Xe(i?t.get(u):t[u],n,r)];return Li(a,n),n.addBreakTokens?[new m(l.map,s),a,new m(l.break)]:[new m(l.map,s),a]}};K.Map=K.Object;K.Buffer=K.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))K[`${t}Array`]=K.DataView;function Xe(t,e={},n){let r=dn(t),i=e&&e.typeEncoders&&e.typeEncoders[r]||K[r];if(typeof i=="function"){let s=i(t,r,e,n);if(s!=null)return s}let o=K[r];if(!o)throw new Error(`${kt} unsupported type: ${r}`);return o(t,r,e,n)}function Li(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Hi(t,e){if(t[0]instanceof m&&e[0]instanceof m){let n=t[0],r=e[0];return n._keyBytes||(n._keyBytes=pr(n.value)),r._keyBytes||(r._keyBytes=pr(r.value)),Ve(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function pr(t){return Mi(t,Di,mr)}function hr(t,e,n,r){if(Array.isArray(e))for(let i of e)hr(t,i,n,r);else n[e.type.major](t,e,r)}function Mi(t,e,n){let r=Xe(t,n);if(!Array.isArray(r)&&n.quickEncodeToken){let i=n.quickEncodeToken(r);if(i)return i;let o=e[r.type.major];if(o.encodedSize){let s=o.encodedSize(r,n),a=new be(s);if(o(a,r,n),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${r} was wrong`);return Et(a.chunks[0])}}return Ct.reset(),hr(Ct,r,e,n),Ct.toBytes(!0)}xt.hmacSha256Sync=(t,...e)=>St(wt,t,xt.concatBytes(...e));var Gi=32;function Qe(t){if(t.length===0)return new Uint8Array(Gi);let e=t.length,n=e*4,r=t.reduce((c,u)=>c+u.length,0),i=4+n+r,o=new Uint8Array(i),s=new DataView(o.buffer,o.byteOffset,o.byteLength);s.setUint32(0,e,!0);let a=4;for(let c of t)s.setUint32(a,c.length,!0),a+=4;for(let c of t)o.set(c,a),a+=c.length;return wt(o)}var It={bool:1,uint8:1,int8:1,uint16:2,int16:2,uint32:4,int32:4,entityRef:4,f32:4,vec2:8,vec3:12,quat:16,enum:1},Ee={bool:1,uint8:1,int8:1,uint16:2,int16:2,uint32:4,int32:4,f32:4,flags8:1,flags16:2,flags32:4,vec2:8,vec3:12,quat:16};var yr=new Set(["bool","uint8","int8","uint16","int16","uint32","int32","f32"]);function Pt(t){let e=t.match(/^(\\w+)\\[(\\d+)\\]$/);if(!e||!e[1]||!e[2])return null;let n=e[1],r=parseInt(e[2],10);if(!yr.has(n))throw new Error(`Invalid array element type \'${n}\': arrays only support primitive scalar types (bool, uint8, int8, uint16, int16, uint32, int32, f32)`);return{elementType:n,length:r}}function gr(t){let e=Pt(t);if(e){let r=Ee[e.elementType];if(r===void 0)throw new Error(`Unknown element type: ${e.elementType}`);return r*e.length}let n=Ee[t];if(n===void 0)throw new Error(`Unknown type: ${t}`);return n}function Zi(t){let e=[],n=[],r=new Map,i=new Map,o=0;for(let s of t.controls){let a=gr(s.type),c=Pt(s.type),u={name:s.name,type:s.type,size:a,offset:0,options:s.options};c&&(u.arrayLength=c.length,u.arrayElementType=c.elementType);let f={name:s.name,index:o++,field:u,hint:s.hint,retain:s.retain==="always"?"always":"tick"};e.push(f),r.set(s.name,f)}for(let s of t.commands){let a=[],c=0;for(let f of s.args){let p=gr(f.type),g=Pt(f.type),S={name:f.name,type:f.type,size:p,offset:c};g&&(S.arrayLength=g.length,S.arrayElementType=g.elementType),a.push(S),c+=p}let u={name:s.name,index:o++,args:a,totalSize:c};n.push(u),i.set(s.name,u)}return{controls:e,commands:n,controlByName:r,commandByName:i}}function Bt(t,e,n,r){switch(n){case"bool":t.setUint8(e,r?1:0);break;case"uint8":case"flags8":t.setUint8(e,r);break;case"int8":t.setInt8(e,r);break;case"uint16":case"flags16":t.setUint16(e,r,!0);break;case"int16":t.setInt16(e,r,!0);break;case"uint32":case"flags32":t.setUint32(e,r,!0);break;case"int32":t.setInt32(e,r,!0);break;case"f32":t.setFloat32(e,r,!0);break;default:throw new Error(`Cannot write primitive type: ${n}`)}}function _t(t,e,n){switch(n){case"bool":return t.getUint8(e)!==0;case"uint8":case"flags8":return t.getUint8(e);case"int8":return t.getInt8(e);case"uint16":case"flags16":return t.getUint16(e,!0);case"int16":return t.getInt16(e,!0);case"uint32":case"flags32":return t.getUint32(e,!0);case"int32":return t.getInt32(e,!0);case"f32":return t.getFloat32(e,!0);default:throw new Error(`Cannot read primitive type: ${n}`)}}var et=class t{constructor(e){y(this,"schema");y(this,"fields",new Map);y(this,"commandList",[]);this.schema=e}setControl(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);let i=new Uint8Array(r.field.size),o=new DataView(i.buffer);this.encodeValue(o,0,r.field,n),this.fields.set(r.index,i)}setFlags(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(!r.field.options)throw new Error(`Control ${e} is not a flags type`);let i=0;for(let a=0;a<r.field.options.length;a++){let c=r.field.options[a];n[c]&&(i|=1<<a)}let o=new Uint8Array(r.field.size),s=new DataView(o.buffer);Bt(s,0,r.field.type,i),this.fields.set(r.index,o)}setVec2(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="vec2")throw new Error(`Control ${e} is not a vec2`);let i=new Uint8Array(8),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),this.fields.set(r.index,i)}setVec3(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="vec3")throw new Error(`Control ${e} is not a vec3`);let i=new Uint8Array(12),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),o.setFloat32(8,n[2],!0),this.fields.set(r.index,i)}setQuat(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="quat")throw new Error(`Control ${e} is not a quat`);let i=new Uint8Array(16),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),o.setFloat32(8,n[2],!0),o.setFloat32(12,n[3],!0),this.fields.set(r.index,i)}getControl(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);let r=this.fields.get(n.index);if(!r)return this.getDefaultValue(n.field);let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return this.decodeValue(i,0,n.field)}getFlags(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(!n.field.options)throw new Error(`Control ${e} is not a flags type`);let r=this.fields.get(n.index),i=0;if(r){let s=new DataView(r.buffer,r.byteOffset,r.byteLength);i=_t(s,0,n.field.type)}let o={};for(let s=0;s<n.field.options.length;s++)o[n.field.options[s]]=(i&1<<s)!==0;return o}getVec2(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="vec2")throw new Error(`Control ${e} is not a vec2`);let r=this.fields.get(n.index);if(!r)return[0,0];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0)]}getVec3(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="vec3")throw new Error(`Control ${e} is not a vec3`);let r=this.fields.get(n.index);if(!r)return[0,0,0];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0),i.getFloat32(8,!0)]}getQuat(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="quat")throw new Error(`Control ${e} is not a quat`);let r=this.fields.get(n.index);if(!r)return[0,0,0,1];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0),i.getFloat32(8,!0),i.getFloat32(12,!0)]}hasControl(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);return this.fields.has(n.index)}addCommand(e,n){let r=this.schema.commandByName.get(e);if(!r)throw new Error(`Unknown command: ${e}`);let i=new Uint8Array(r.totalSize),o=new DataView(i.buffer);for(let s of r.args){let a=n[s.name];if(a===void 0)throw new Error(`Missing required argument: ${s.name}`);this.encodeValue(o,s.offset,s,a)}this.commandList.push({index:r.index,data:i})}getCommands(){let e=[];for(let{index:n,data:r}of this.commandList){let i=this.schema.commands.find(a=>a.index===n);if(!i)continue;let o=new DataView(r.buffer,r.byteOffset,r.byteLength),s={name:i.name};for(let a of i.args)s[a.name]=this.decodeValue(o,a.offset,a);e.push(s)}return e}encode(){let e=[];for(let[o,s]of this.fields){let a=new Uint8Array(2+s.length);a[0]=o,a[1]=s.length,a.set(s,2),e.push(a)}for(let o of this.commandList){let s=new Uint8Array(2+o.data.length);s[0]=o.index,s[1]=o.data.length,s.set(o.data,2),e.push(s)}let n=e.reduce((o,s)=>o+s.length,0),r=new Uint8Array(n),i=0;for(let o of e)r.set(o,i),i+=o.length;return r}static decode(e,n){let r=new t(e),i=0;for(;i<n.length;){if(i+2>n.length)throw new Error("Truncated TLV field header");let o=n[i],s=n[i+1];if(i+2+s>n.length)throw new Error(`Truncated TLV field data at index ${o}`);let a=n.subarray(i+2,i+2+s);e.controls.find(u=>u.index===o)?r.fields.set(o,new Uint8Array(a)):e.commands.find(f=>f.index===o)&&r.commandList.push({index:o,data:new Uint8Array(a)}),i+=2+s}return r}clear(){this.fields.clear(),this.commandList.length=0}encodeValue(e,n,r,i){if(r.type==="vec2"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0)}else if(r.type==="vec3"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0),e.setFloat32(n+8,o[2],!0)}else if(r.type==="quat"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0),e.setFloat32(n+8,o[2],!0),e.setFloat32(n+12,o[3],!0)}else if(r.arrayLength!==void 0&&r.arrayElementType!==void 0){let o=i,s=Ee[r.arrayElementType];for(let a=0;a<Math.min(o.length,r.arrayLength);a++)Bt(e,n+a*s,r.arrayElementType,o[a])}else Bt(e,n,r.type,i)}decodeValue(e,n,r){if(r.type==="vec2")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0)];if(r.type==="vec3")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0),e.getFloat32(n+8,!0)];if(r.type==="quat")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0),e.getFloat32(n+8,!0),e.getFloat32(n+12,!0)];if(r.arrayLength!==void 0&&r.arrayElementType!==void 0){let i=[],o=Ee[r.arrayElementType];for(let s=0;s<r.arrayLength;s++)i.push(_t(e,n+s*o,r.arrayElementType));return i}else return _t(e,n,r.type)}getDefaultValue(e){return e.type==="vec2"?[0,0]:e.type==="vec3"?[0,0,0]:e.type==="quat"?[0,0,0,1]:e.arrayLength!==void 0?new Array(e.arrayLength).fill(0):e.type==="bool"?!1:0}};function br(t){let e=Zi(t);return{create(){return new et(e)},decode(n){return et.decode(e,n)},get schema(){return e}}}function xr(t,e){return((e&65535)<<16|t&65535)>>>0}function ke(t){return t&65535}function Yi(t){return t>>>16&65535}function de(t){return t.subarray(8,40)}function $t(t,e){if(e.length!==32)throw new Error(`stateId must be ${32} bytes, got ${e.length}`);t.set(e,8)}function wr(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint32(40,e,!0)}function rt(t,e,n){let r=new Uint8Array(68);return r.set(t,0),new DataView(r.buffer).setUint32(32,e,!0),r.set(n,36),ge(r)}function Sr(t,e,n){return rt(t,e,Qe(n))}function Ot(t){return ge(t)}function Er(t,e,n){let r=new ArrayBuffer(t.totalSize),i=new Uint8Array(r),o=new DataView(r);if(o.setUint32(0,1297367376,!0),o.setUint16(4,0,!0),i[6]=n??0,i[7]=0,e){let a=Ot(e);i.set(a,8)}let s=t.freeStackOffset;o.setUint16(s,t.maxEntities,!0);for(let a=0;a<t.maxEntities;a++){let c=t.freeStackOffset+2+a*2;o.setUint16(c,a,!0)}return i}function kr(t,e){return t.entityTableOffset+e*t.entityRecordSize}function Ft(t,e,n){let r=kr(t,n);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(r,!0)}function Xi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(4,!0)}function Ji(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(4,e,!0)}function Qi(t,e){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t.freeStackOffset,!0)}function eo(t,e,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t.freeStackOffset,n,!0)}function to(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Qi(t,e);if(r===0)throw new Error(`No free entity slots available (max: ${t.maxEntities})`);let i=t.freeStackOffset+2+(r-1)*2,o=n.getUint16(i,!0);return eo(t,e,r-1),o}function Tr(t,e){let n=to(t,e),r=Ft(t,e,n);return Ji(e,Xi(e)+1),xr(n,r)}function it(t,e,n){if(n===4294967295)return!1;let r=ke(n);if(r>=t.maxEntities)return!1;let i=Yi(n);return Ft(t,e,r)===i}function Nt(t,e,n){if(n<0)throw new Error("Singleton components do not have component bitmask entries");let r=kr(t,e)+2,i=Math.floor(n/8),o=n%8;return{byteOffset:r+i,bitIndex:o}}function Ar(t,e,n,r){if(!it(t,e,n))return!1;let i=t.componentByName.get(r);if(!i)throw new Error(`Unknown component: \'${r}\'`);if(i.isSingleton)throw new Error(`Component \'${r}\' is a singleton and is always present`);let o=ke(n),{byteOffset:s,bitIndex:a}=Nt(t,o,i.index);return(e[s]&1<<a)!==0}function vr(t,e,n,r){if(!it(t,e,n)){let c=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${c} is not alive`)}let i=t.componentByName.get(r);if(!i)throw new Error(`Unknown component: \'${r}\'`);if(i.isSingleton)throw new Error(`Component \'${r}\' is a singleton and cannot be added to entities`);let o=ke(n),{byteOffset:s,bitIndex:a}=Nt(t,o,i.index);e[s]=(e[s]??0)|1<<a}function Ur(t,e,n,r){let i=ke(e);return n.storageOffset+i*n.size+r.offset}function no(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(n){case"bool":return(t[e]??0)!==0;case"uint8":return t[e]??0;case"int8":return r.getInt8(e);case"uint16":return r.getUint16(e,!0);case"int16":return r.getInt16(e,!0);case"uint32":return r.getUint32(e,!0);case"int32":return r.getInt32(e,!0);case"entityRef":return r.getUint32(e,!0);case"f32":return r.getFloat32(e,!0);default:throw new Error(`Cannot read primitive type: ${n}`)}}function Cr(t,e,n,r){let i=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(n){case"bool":t[e]=r?1:0;break;case"uint8":t[e]=r&255;break;case"int8":i.setInt8(e,r);break;case"uint16":i.setUint16(e,r,!0);break;case"int16":i.setInt16(e,r,!0);break;case"uint32":i.setUint32(e,r,!0);break;case"int32":i.setInt32(e,r,!0);break;case"entityRef":i.setUint32(e,r,!0);break;case"f32":i.setFloat32(e,r,!0);break;default:throw new Error(`Cannot write primitive type: ${n}`)}}function ro(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0)}function io(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0),r.setFloat32(e+8,n[2],!0)}function oo(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0),r.setFloat32(e+8,n[2],!0),r.setFloat32(e+12,n[3],!0)}function Ir(t,e,n,r,i,o){if(!it(t,e,n))return;let s=t.componentByName.get(r);if(!s)throw new Error(`Unknown component: \'${r}\'`);if(s.isSingleton)throw new Error(`Component \'${r}\' is a singleton; use singleton accessors instead`);if(!nt(t,e,n,s))return;let a=s.fields.find(f=>f.name===i);if(!a)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let c=Ur(t,n,s,a),u=a.type;if(a.arrayLength!==void 0&&a.arrayElementType!==void 0){if(o===void 0)throw new Error(`Field \'${r}.${i}\' is an array, index required`);if(o<0||o>=a.arrayLength)throw new Error(`Array index ${o} out of bounds for ${r}.${i} (length: ${a.arrayLength})`);let f=It[a.arrayElementType];if(f===void 0)throw new Error(`Unknown array element type: ${a.arrayElementType}`);c+=o*f,u=a.arrayElementType}return no(e,c,u)}function w(t,e,n,r,i,o,s){if(!it(t,e,n)){let p=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${p} is not alive`)}let a=t.componentByName.get(r);if(!a)throw new Error(`Unknown component: \'${r}\'`);if(!nt(t,e,n,a)){let p=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${p} does not have component \'${r}\'`)}let c=a.fields.find(p=>p.name===i);if(!c)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let u=Ur(t,n,a,c),f=c.type;if(c.arrayLength!==void 0&&c.arrayElementType!==void 0){if(s===void 0)throw new Error(`Field \'${r}.${i}\' is an array, index required`);if(s<0||s>=c.arrayLength)throw new Error(`Array index ${s} out of bounds for ${r}.${i} (length: ${c.arrayLength})`);let p=It[c.arrayElementType];if(p===void 0)throw new Error(`Unknown array element type: ${c.arrayElementType}`);u+=s*p,f=c.arrayElementType}Cr(e,u,f,o)}function nt(t,e,n,r){if(r.isSingleton)throw new Error(`Component \'${r.name}\' is a singleton and cannot be queried per entity`);let i=ke(n),{byteOffset:o,bitIndex:s}=Nt(t,i,r.index);return(e[o]&1<<s)!==0}function Br(t,e,n,r){if(n.length===0)throw new Error("Query must include at least one component");let i=[];for(let a of n){let c=t.componentByName.get(a);if(!c)throw new Error(`Unknown component: \'${a}\'`);if(c.isSingleton)throw new Error(`Singleton component \'${a}\' cannot be used in queries`);i.push(c)}let o=[];if(r)for(let a of r){let c=t.componentByName.get(a);if(!c)throw new Error(`Unknown component: \'${a}\'`);if(c.isSingleton)throw new Error(`Singleton component \'${a}\' cannot be used in queries`);o.push(c)}function*s(){for(let a=0;a<t.maxEntities;a++){let c=Ft(t,e,a),u=xr(a,c),f=!0;for(let p of i)if(!nt(t,e,u,p)){f=!1;break}if(f){for(let p of o)if(nt(t,e,u,p)){f=!1;break}f&&(yield u)}}}return s()}function _r(t,e){if(!t.events||!t.eventByName)throw new Error("Schema has no events");let n=t.eventByName.get(e);if(!n)throw new Error(`Unknown event: \'${e}\'`);return n}function Pr(t,e,n){let r=_r(t,n);new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(r.storageOffset,0,!0)}function $r(t,e,n,r){let i=_r(t,n),o=new DataView(e.buffer,e.byteOffset,e.byteLength),s=o.getUint16(i.storageOffset,!0);if(s>=i.maxEvents)return!1;let a=i.storageOffset+2+s*i.recordSize;for(let c of i.fields){let u=r[c.name];if(u===void 0)throw new Error(`Missing required field \'${c.name}\' for event \'${n}\'`);let f=a+c.offset;c.type==="vec2"?ro(e,f,u):c.type==="vec3"?io(e,f,u):c.type==="quat"?oo(e,f,u):Cr(e,f,c.type,u)}return o.setUint16(i.storageOffset,s+1,!0),!0}function ot(t){if(t.length!==32)throw new Error(`stateId must be ${32} bytes, got ${t.length}`);return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var st=class{constructor(e={}){y(this,"cache");y(this,"maxSize");this.cache=new Map,this.maxSize=e.maxSize??100}store(e){let n=de(e),r=ot(n);if(this.cache.size>=this.maxSize&&!this.cache.has(r)){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}this.cache.set(r,e.slice())}getByStateId(e){let n=ot(e),r=this.cache.get(n);return r?r.slice():void 0}getCached(e,n,r){let i=de(e),o=rt(i,n,r);return this.getByStateId(o)}has(e){let n=ot(e);return this.cache.has(n)}hasCached(e,n,r){let i=de(e),o=rt(i,n,r);return this.has(o)}delete(e){let n=ot(e);return this.cache.delete(n)}clear(){this.cache.clear()}get size(){return this.cache.size}keys(){return this.cache.keys()}};var Te=65536,at=class{constructor(e){y(this,"memory",null);y(this,"plugins",[]);y(this,"options");y(this,"stateSize",null);y(this,"statePtr",null);y(this,"heapPos",0);y(this,"arenaResetMark",0);y(this,"inputCodec",null);y(this,"playerEntities",new Map);y(this,"hostAlloc",(e,n)=>{let r=this.memory;if(!r)throw new Error("Memory not initialized for host_alloc");let i=this.heapPos+n-1&~(n-1),o=i+e,s=r.buffer.byteLength;if(o>s){let c=Math.ceil((o-s)/Te);if(this.options.debug){let u=(s+c*Te)/1048576;console.warn(`[mt] WASM memory grew to ${u.toFixed(1)}MB`)}r.grow(c)}return new Uint8Array(r.buffer).fill(0,i,o),this.heapPos=o,i});this.options=e}markArenaReset(){this.arenaResetMark=this.heapPos}resetArena(){this.heapPos=this.arenaResetMark}async init(){if(this.stateSize=this.options.stateSchema.totalSize,!this.stateSize)throw new Error("State schema total size is required");this.options.inputSchema&&(this.inputCodec=br(this.options.inputSchema));let e=4*1024*1024,n=this.options.plugins??(this.options.moduleBytes?[{name:"main",wasmBytes:this.options.moduleBytes,reservedBytes:e}]:[]);for(let c of n)if(typeof c.reservedBytes!="number"||c.reservedBytes<=0)throw new Error(`Plugin "${c.name}" requires reservedBytes > 0`);let r=n.reduce((c,u)=>{let f=Math.ceil(u.reservedBytes/Te)*Te;return c+f},0),i=1024*1024*5,o=this.stateSize+i+r,s=Math.ceil(o/Te);this.memory=new WebAssembly.Memory({initial:s}),this.heapPos=r;let a={env:{memory:this.memory,host_alloc:this.hostAlloc,abort:()=>{throw new Error("WASM abort called")}}};for(let c of n){let u=c.wasmBytes.slice().buffer,f=await WebAssembly.compile(u),p=await WebAssembly.instantiate(f,a);if(typeof p.exports.apply!="function")throw new Error(`Plugin "${c.name}" missing required apply() export`);this.plugins.push({name:c.name,instance:p,exports:p.exports})}return this.statePtr=this.hostAlloc(this.stateSize,8),this.markArenaReset(),this}findPlayerEntity(e,n){let r=this.options.stateSchema,i=this.playerEntities.get(n);if(i!==void 0){if(Ar(r,e,i,"Player"))return i;this.playerEntities.delete(n)}for(let o of Br(r,e,["Player"]))if(Ir(r,e,o,"Player","index")===n)return this.playerEntities.set(n,o),o}spawnPlayerEntity(e,n){let r=this.options.stateSchema,i=Tr(r,e);return vr(r,e,i,"Player"),w(r,e,i,"Player","index",n),this.playerEntities.set(n,i),i}findOrSpawnPlayerEntity(e,n){let r=this.findPlayerEntity(e,n);return r!==void 0?r:this.spawnPlayerEntity(e,n)}resetPlayerControls(e,n){let r=this.options.stateSchema;if(this.inputCodec)for(let i of this.inputCodec.schema.controls){if(i.retain==="always")continue;let o=i.field.type,s=i.name;if(o==="vec2")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0);else if(o==="vec3")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0),w(r,e,n,"Player",`${s}_z`,0);else if(o==="quat")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0),w(r,e,n,"Player",`${s}_z`,0),w(r,e,n,"Player",`${s}_w`,1);else if(o.startsWith("flags"))w(r,e,n,"Player",s,0);else if(o.includes("[")){let a=o.match(/\\[(\\d+)\\]/);if(a?.[1]){let c=parseInt(a[1],10);for(let u=0;u<c;u++)w(r,e,n,"Player",s,0,u)}}else w(r,e,n,"Player",s,o==="bool"?!1:0)}}writeControlsToPlayer(e,n,r){let i=this.options.stateSchema,o=this.options.inputSchema;if(o)for(let s of o.controls){if(!r.hasControl(s.name))continue;let a=s.type,c=s.name;if(a==="vec2"){let[u,f]=r.getVec2(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f)}else if(a==="vec3"){let[u,f,p]=r.getVec3(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f),w(i,e,n,"Player",`${c}_z`,p)}else if(a==="quat"){let[u,f,p,g]=r.getQuat(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f),w(i,e,n,"Player",`${c}_z`,p),w(i,e,n,"Player",`${c}_w`,g)}else if(a.startsWith("flags")){let u=r.getControl(c);w(i,e,n,"Player",c,u)}else if(a.includes("[")){let u=r.getControl(c);for(let f=0;f<u.length;f++)w(i,e,n,"Player",c,u[f],f)}else{let u=r.getControl(c);w(i,e,n,"Player",c,u)}}}pushCommands(e,n,r){let i=this.options.stateSchema,o=r.getCommands();for(let s of o){let a=s.name.charAt(0).toUpperCase()+s.name.slice(1)+"Command",c={player_index:n};for(let[u,f]of Object.entries(s))u!=="name"&&(Array.isArray(f)?f.length===2?(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1]):f.length===3?(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1],c[`${u}_z`]=f[2]):f.length===4&&(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1],c[`${u}_z`]=f[2],c[`${u}_w`]=f[3]):c[u]=f);$r(i,e,a,c)}}clearCommandEvents(e){let n=this.options.stateSchema,r=this.options.inputSchema;if(!(!r||!n.events))for(let i of r.commands){let o=i.name.charAt(0).toUpperCase()+i.name.slice(1)+"Command";n.eventByName?.has(o)&&Pr(n,e,o)}}decodePayloadsToState(e,n){if(this.inputCodec)for(let r=0;r<n.length;r++){let i=n[r];if(i===void 0)continue;let o=this.findOrSpawnPlayerEntity(e,r);if(this.resetPlayerControls(e,o),i.length===0)continue;let s=this.inputCodec.decode(i);this.writeControlsToPlayer(e,o,s),this.pushCommands(e,r,s)}}transition(e,n){let r=this.stateSize;if(r===null||e.length!==r)throw new Error(`State size mismatch: expected ${this.stateSize}, got ${e.length}`);if(this.plugins.length===0||n.length===0)return e.slice();let i=this.memory;if(!i)throw new Error("WASM memory not initialized");let o=this.statePtr;if(o===null||o<0)throw new Error("State pointer not initialized");let s=new Uint8Array(i.buffer);s.set(e,o);for(let a of n){this.resetArena();let c=new Uint8Array(i.buffer,o,r);wr(c,a.tick),this.clearCommandEvents(c),this.decodePayloadsToState(c,a.payloads);for(let u of this.plugins)u.exports.apply(o),s=new Uint8Array(i.buffer)}return s.slice(o,o+r)}close(){}getStateSize(){let e=this.stateSize;if(e===null||e<0)throw new Error("State size not initialized");return e}};var pe=class{constructor(e=1e3,n=1024){y(this,"buffer");y(this,"windowMs");y(this,"head",0);y(this,"tail",0);y(this,"size",0);this.windowMs=e,this.buffer=new Float64Array(n)}inc(){let e=performance.now();this.buffer[this.head]=e,this.head=(this.head+1)%this.buffer.length,this.size<this.buffer.length?this.size++:this.tail=(this.tail+1)%this.buffer.length}count(e=performance.now()){let n=e-this.windowMs;for(;this.size>0&&!(this.buffer[this.tail]>=n);)this.tail=(this.tail+1)%this.buffer.length,this.size--;return this.size}rate(e=performance.now()){return this.count(e)*(1e3/this.windowMs)}};function so(t){return("moduleBytes"in t||"plugins"in t)&&"stateSchema"in t}function ao(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var ct=class{constructor(e){y(this,"debug");y(this,"stateSchema");y(this,"inputs",null);y(this,"cache");y(this,"executor",null);y(this,"genesisStateId");y(this,"options");y(this,"ticking",!1);y(this,"tickGraceMs");y(this,"tickLag");y(this,"maxBatchSize");y(this,"currentState");y(this,"currentTick");y(this,"currentNodeId");y(this,"prevOnStateUpdateState",null);y(this,"onStateUpdate");y(this,"syncCheckpoint");y(this,"stateHistory",[]);y(this,"maxHistory",64);y(this,"stats");y(this,"loop",()=>{this._loop().catch(co)});y(this,"_loop",async()=>{if(this.ticking)try{let e=await this.tick();if(this.onStateUpdate&&this.currentState!==this.prevOnStateUpdateState&&(this.onStateUpdate(this.currentState),this.prevOnStateUpdateState=this.currentState,this.stats.updates.inc()),e.rolledBack&&this.stats.rollbacks.inc(),e.ticksComputed>0)for(let n=0;n<e.ticksComputed;n++)this.stats.executions.inc()}catch(e){console.error("Error in tick loop:",e)}finally{setTimeout(this.loop,this.tickGraceMs)}});e.log&&(this.inputs=e.log),this.debug=e.debug??!1,this.options=e,this.stateSchema=e.stateSchema,this.cache=e.cache??new st,this.genesisStateId=Ot(e.genesisHash),this.tickGraceMs=e.tickGraceMs??10,this.tickLag=e.tickLag??1,this.maxBatchSize=e.maxBatchSize??200,this.stats={rollbacks:new pe,executions:new pe,updates:new pe},this.currentState=Er(this.stateSchema,e.genesisHash,e.tickRate),this.currentNodeId=null,this.syncCheckpoint=null,this.currentTick=null,this.cache.store(this.currentState)}setLog(e){this.inputs=lt(e)}setOnStateUpdate(e){e===null&&(this.prevOnStateUpdateState=null),this.onStateUpdate=e}async init(){if(!this.inputs)throw new Error("Rollback.init() called before log was configured. Call setLog() first or pass log in options.");let e=this.options.executor;if(so(e)){let r=new at(e);await r.init(),this.executor=r}else this.executor=e;if((await this.tick(0)).ticksComputed===0||this.currentTick===null)throw new Error("Failed to record genesis snapshot");return this.options.disableTicking||(this.ticking=!0,this.loop()),this.getState()}async tick(e){if(!this.inputs)throw new Error("Rollback.tick() called before log was configured. Call setLog() and init() first.");let n=await this.inputs.getTicksAfter(this.currentNodeId,{limit:this.maxBatchSize,lag:this.tickLag});if(e&&(n=n.filter(s=>s.tick<=e)),n.length===0)return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:!1,ticksComputed:0};let r=!1;this.currentTick!==null&&n[0].tick<this.currentTick&&(r=!0,this.rollbackTo(n[0]));let i=n.filter(s=>this.currentTick===null||s.tick>this.currentTick);if(i.length===0)return this.currentNodeId=n[n.length-1].id,{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId,rolledBack:r,ticksComputed:0};let o=this.processTicks(i);return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:r,ticksComputed:o}}async getStats(){return{rollbacks:this.stats.rollbacks.rate(),executions:this.stats.executions.rate(),updates:this.stats.updates.rate()}}processTicks(e){if(!this.executor)throw new Error("Executor not initialized");let n=0,r=0;for(let a=0;a<e.length;a++){let c=e[a],u=Qe(c.payloads),f=this.cache.getCached(this.currentState,c.tick,u);if(f)this.currentState=f,this.currentTick=c.tick,this.currentNodeId=c.id,r=a+1,c.sync&&this.updateSyncCheckpoint(c);else break}let i=e.slice(r);if(i.length===0)return 0;let o=ao(i,a=>a.sync);if(o>=0){let a=i.slice(0,o+1),c=this.executor.transition(this.currentState,a),u=this.computeBatchStateId(this.currentState,a);$t(c,u);let f=a[a.length-1];this.currentState=c,this.currentTick=f.tick,this.currentNodeId=f.id,n+=a.length,this.cache.store(c),this.recordStateSnapshot(this.currentTick,this.currentNodeId,u),this.updateSyncCheckpoint(f)}let s=o>=0?i.slice(o+1):i;if(s.length>0){let a=this.executor.transition(this.currentState,s),c=this.computeBatchStateId(this.currentState,s);$t(a,c);let u=s[s.length-1];this.currentState=a,this.currentTick=u.tick,this.currentNodeId=u.id,n+=s.length,this.cache.store(a),this.recordStateSnapshot(this.currentTick,this.currentNodeId,c)}return n}computeBatchStateId(e,n){let r=de(e);for(let i of n)r=Sr(r,i.tick,i.payloads);return r}getState(){return this.currentState.slice()}getTick(){return this.currentTick}reset(){this.currentTick=0,this.currentNodeId=null,this.syncCheckpoint=null}close(){this.ticking=!1,this.setOnStateUpdate(null),this.executor&&(this.executor.close(),this.executor=null)}rollbackTo(e){if(this.syncCheckpoint&&this.syncCheckpoint.tick>=e.tick){this.currentState=this.syncCheckpoint.state.slice(),this.currentTick=this.syncCheckpoint.tick,this.currentNodeId=this.syncCheckpoint.nodeId;return}if(this.syncCheckpoint&&this.syncCheckpoint.tick<e.tick){this.currentState=this.syncCheckpoint.state.slice(),this.currentTick=this.syncCheckpoint.tick,this.currentNodeId=this.syncCheckpoint.nodeId;return}let n=e.tick-1,r=this.findSnapshotAtOrBefore(n);if(r){let o=this.cache.getByStateId(r.stateId);if(o){this.currentState=o,this.currentTick=r.tick,this.currentNodeId=r.nodeId;return}}let i=this.cache.getByStateId(this.genesisStateId);if(i){this.currentState=i,this.currentTick=0,this.currentNodeId=null;return}}updateSyncCheckpoint(e){this.syncCheckpoint={state:this.currentState.slice(),tick:e.tick,nodeId:e.id}}recordStateSnapshot(e,n,r){this.stateHistory.push({tick:e,nodeId:n,stateId:r.slice()}),this.stateHistory.length>this.maxHistory&&this.stateHistory.shift()}findSnapshotAtOrBefore(e){for(let n=this.stateHistory.length-1;n>=0;n--){let r=this.stateHistory[n];if(r.tick<=e)return r}return null}};function co(t){console.warn("rollback unexpected:",t)}Be(ct);var Ga=null;globalThis.onerror=t=>(console.error("\\u{1F534} FATAL ROLLBACK WORKER ERROR (Uncaught Exception):",t),!0);export{Ga as default};\n/*! Bundled license information:\n\ncomlink/dist/esm/comlink.mjs:\n (**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n *)\n\n@noble/secp256k1/index.js:\n (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)\n\n@noble/hashes/esm/utils.js:\n (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)\n*/\n';
|
|
4706
6002
|
function Worker() {
|
|
4707
6003
|
const blob = new Blob([workerCode], { type: "text/javascript" });
|
|
4708
6004
|
const url = URL.createObjectURL(blob);
|
|
@@ -4711,16 +6007,6 @@ function Worker() {
|
|
|
4711
6007
|
return worker;
|
|
4712
6008
|
}
|
|
4713
6009
|
|
|
4714
|
-
// src/rollback.worker.ts
|
|
4715
|
-
var workerCode2 = 'var Or=Object.defineProperty;var Fr=(t,e,n)=>e in t?Or(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var y=(t,e,n)=>Fr(t,typeof e!="symbol"?e+"":e,n);var Rt=Symbol("Comlink.proxy"),Nr=Symbol("Comlink.endpoint"),Rr=Symbol("Comlink.releaseProxy"),ut=Symbol("Comlink.finalizer"),ve=Symbol("Comlink.thrown"),Dt=t=>typeof t=="object"&&t!==null||typeof t=="function",Dr={canHandle:t=>Dt(t)&&t[Rt],serialize(t){let{port1:e,port2:n}=new MessageChannel;return Be(t,e),[n,[n]]},deserialize(t){return t.start(),lt(t)}},Lr={canHandle:t=>Dt(t)&&ve in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},Lt=new Map([["proxy",Dr],["throw",Lr]]);function Hr(t,e){for(let n of t)if(e===n||n==="*"||n instanceof RegExp&&n.test(e))return!0;return!1}function Be(t,e=globalThis,n=["*"]){e.addEventListener("message",function r(i){if(!i||!i.data)return;if(!Hr(n,i.origin)){console.warn(`Invalid origin \'${i.origin}\' for comlink proxy`);return}let{id:o,type:s,path:a}=Object.assign({path:[]},i.data),c=(i.data.argumentList||[]).map(W),u;try{let f=a.slice(0,-1).reduce((g,S)=>g[S],t),p=a.reduce((g,S)=>g[S],t);switch(s){case"GET":u=p;break;case"SET":f[a.slice(-1)[0]]=W(i.data.value),u=!0;break;case"APPLY":u=p.apply(f,c);break;case"CONSTRUCT":{let g=new p(...c);u=qr(g)}break;case"ENDPOINT":{let{port1:g,port2:S}=new MessageChannel;Be(t,S),u=Zr(g,[g])}break;case"RELEASE":u=void 0;break;default:return}}catch(f){u={value:f,[ve]:0}}Promise.resolve(u).catch(f=>({value:f,[ve]:0})).then(f=>{let[p,g]=Ie(f);e.postMessage(Object.assign(Object.assign({},p),{id:o}),g),s==="RELEASE"&&(e.removeEventListener("message",r),Ht(e),ut in t&&typeof t[ut]=="function"&&t[ut]())}).catch(f=>{let[p,g]=Ie({value:new TypeError("Unserializable return value"),[ve]:0});e.postMessage(Object.assign(Object.assign({},p),{id:o}),g)})}),e.start&&e.start()}function Mr(t){return t.constructor.name==="MessagePort"}function Ht(t){Mr(t)&&t.close()}function lt(t,e){let n=new Map;return t.addEventListener("message",function(i){let{data:o}=i;if(!o||!o.id)return;let s=n.get(o.id);if(s)try{s(o)}finally{n.delete(o.id)}}),ft(t,n,[],e)}function Ae(t){if(t)throw new Error("Proxy has been released and is not useable")}function Mt(t){return te(t,new Map,{type:"RELEASE"}).then(()=>{Ht(t)})}var Ue=new WeakMap,Ce="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{let e=(Ue.get(t)||0)-1;Ue.set(t,e),e===0&&Mt(t)});function zr(t,e){let n=(Ue.get(e)||0)+1;Ue.set(e,n),Ce&&Ce.register(t,e,t)}function Vr(t){Ce&&Ce.unregister(t)}function ft(t,e,n=[],r=function(){}){let i=!1,o=new Proxy(r,{get(s,a){if(Ae(i),a===Rr)return()=>{Vr(o),Mt(t),e.clear(),i=!0};if(a==="then"){if(n.length===0)return{then:()=>o};let c=te(t,e,{type:"GET",path:n.map(u=>u.toString())}).then(W);return c.then.bind(c)}return ft(t,e,[...n,a])},set(s,a,c){Ae(i);let[u,f]=Ie(c);return te(t,e,{type:"SET",path:[...n,a].map(p=>p.toString()),value:u},f).then(W)},apply(s,a,c){Ae(i);let u=n[n.length-1];if(u===Nr)return te(t,e,{type:"ENDPOINT"}).then(W);if(u==="bind")return ft(t,e,n.slice(0,-1));let[f,p]=Nt(c);return te(t,e,{type:"APPLY",path:n.map(g=>g.toString()),argumentList:f},p).then(W)},construct(s,a){Ae(i);let[c,u]=Nt(a);return te(t,e,{type:"CONSTRUCT",path:n.map(f=>f.toString()),argumentList:c},u).then(W)}});return zr(o,t),o}function Gr(t){return Array.prototype.concat.apply([],t)}function Nt(t){let e=t.map(Ie);return[e.map(n=>n[0]),Gr(e.map(n=>n[1]))]}var zt=new WeakMap;function Zr(t,e){return zt.set(t,e),t}function qr(t){return Object.assign(t,{[Rt]:!0})}function Ie(t){for(let[e,n]of Lt)if(n.canHandle(t)){let[r,i]=n.serialize(t);return[{type:"HANDLER",name:e,value:r},i]}return[{type:"RAW",value:t},zt.get(t)||[]]}function W(t){switch(t.type){case"HANDLER":return Lt.get(t.name).deserialize(t.value);case"RAW":return t.value}}function te(t,e,n,r){return new Promise(i=>{let o=Kr();e.set(o,i),t.start&&t.start(),t.postMessage(Object.assign({id:o},n),r)})}function Kr(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var Wr={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:Y,n:ht,Gx:jr,Gy:Yr,b:jt}=Wr,ne=32,dt=64,U=(t="")=>{throw new Error(t)},Yt=t=>typeof t=="bigint",Xt=t=>typeof t=="string",Xr=t=>t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array",he=(t,e)=>!Xr(t)||typeof e=="number"&&e>0&&t.length!==e?U("Uint8Array expected"):t,Ne=t=>new Uint8Array(t),Jr=t=>Uint8Array.from(t),Jt=(t,e)=>t.toString(16).padStart(e,"0"),yt=t=>Array.from(he(t)).map(e=>Jt(e,2)).join(""),z={_0:48,_9:57,A:65,F:70,a:97,f:102},Vt=t=>{if(t>=z._0&&t<=z._9)return t-z._0;if(t>=z.A&&t<=z.F)return t-(z.A-10);if(t>=z.a&&t<=z.f)return t-(z.a-10)},gt=t=>{let e="hex invalid";if(!Xt(t))return U(e);let n=t.length,r=n/2;if(n%2)return U(e);let i=Ne(r);for(let o=0,s=0;o<r;o++,s+=2){let a=Vt(t.charCodeAt(s)),c=Vt(t.charCodeAt(s+1));if(a===void 0||c===void 0)return U(e);i[o]=a*16+c}return i},bt=(t,e)=>he(Xt(t)?gt(t):Jr(he(t)),e),Qt=()=>globalThis?.crypto,Qr=()=>Qt()?.subtle??U("crypto.subtle must be defined"),Pe=(...t)=>{let e=Ne(t.reduce((r,i)=>r+he(i).length,0)),n=0;return t.forEach(r=>{e.set(r,n),n+=r.length}),e},ei=(t=ne)=>Qt().getRandomValues(Ne(t)),$e=BigInt,ye=(t,e,n,r="bad number: out of range")=>Yt(t)&&e<=t&&t<n?t:U(r),h=(t,e=Y)=>{let n=t%e;return n>=0n?n:e+n};var en=(t,e)=>{(t===0n||e<=0n)&&U("no inverse n="+t+" mod="+e);let n=h(t,e),r=e,i=0n,o=1n,s=1n,a=0n;for(;n!==0n;){let c=r/n,u=r%n,f=i-s*c,p=o-a*c;r=n,n=u,i=s,o=a,s=f,a=p}return r===1n?h(i,e):U("no inverse")};var Gt=t=>t instanceof X?t:U("Point expected"),tn=t=>h(h(t*t)*t+jt),Zt=t=>ye(t,0n,Y),_e=t=>ye(t,1n,Y),ti=t=>ye(t,1n,ht),pt=t=>(t&1n)===0n,nn=t=>Uint8Array.of(t),ni=t=>nn(pt(t)?2:3),ri=t=>{let e=tn(_e(t)),n=1n;for(let r=e,i=(Y+1n)/4n;i>0n;i>>=1n)i&1n&&(n=n*r%Y),r=r*r%Y;return h(n*n)===e?n:U("sqrt invalid")},D=class D{constructor(e,n,r){y(this,"px");y(this,"py");y(this,"pz");this.px=Zt(e),this.py=_e(n),this.pz=Zt(r),Object.freeze(this)}static fromBytes(e){he(e);let n,r=e[0],i=e.subarray(1),o=qt(i,0,ne),s=e.length;if(s===ne+1&&[2,3].includes(r)){let a=ri(o),c=pt(a);pt($e(r))!==c&&(a=h(-a)),n=new D(o,a,1n)}return s===dt+1&&r===4&&(n=new D(o,qt(i,ne,dt),1n)),n?n.assertValidity():U("bad point: not on curve")}equals(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Gt(e),c=h(n*a),u=h(o*i),f=h(r*a),p=h(s*i);return c===u&&f===p}is0(){return this.equals(j)}negate(){return new D(this.px,h(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Gt(e),c=0n,u=jt,f=0n,p=0n,g=0n,S=h(u*3n),k=h(n*o),A=h(r*s),O=h(i*a),ee=h(n+r),v=h(o+s);ee=h(ee*v),v=h(k+A),ee=h(ee-v),v=h(n+i);let R=h(o+a);return v=h(v*R),R=h(k+O),v=h(v-R),R=h(r+i),f=h(s+a),R=h(R*f),f=h(A+O),R=h(R-f),g=h(c*v),f=h(S*O),g=h(f+g),f=h(A-g),g=h(A+g),p=h(f*g),A=h(k+k),A=h(A+k),O=h(c*O),v=h(S*v),A=h(A+O),O=h(k-O),O=h(c*O),v=h(v+O),k=h(A*v),p=h(p+k),k=h(R*v),f=h(ee*f),f=h(f-k),k=h(ee*A),g=h(R*g),g=h(g+k),new D(f,p,g)}multiply(e,n=!0){if(!n&&e===0n)return j;if(ti(e),e===1n)return this;if(this.equals(re))return fi(e).p;let r=j,i=re;for(let o=this;e>0n;o=o.double(),e>>=1n)e&1n?r=r.add(o):n&&(i=i.add(o));return r}toAffine(){let{px:e,py:n,pz:r}=this;if(this.equals(j))return{x:0n,y:0n};if(r===1n)return{x:e,y:n};let i=en(r,Y);return h(r*i)!==1n&&U("inverse invalid"),{x:h(e*i),y:h(n*i)}}assertValidity(){let{x:e,y:n}=this.toAffine();return _e(e),_e(n),h(n*n)===tn(e)?this:U("bad point: not on curve")}toBytes(e=!0){let{x:n,y:r}=this.assertValidity().toAffine(),i=Oe(n);return e?Pe(ni(r),i):Pe(nn(4),i,Oe(r))}static fromAffine(e){let{x:n,y:r}=e;return n===0n&&r===0n?j:new D(n,r,1n)}toHex(e){return yt(this.toBytes(e))}static fromPrivateKey(e){return re.multiply(oi(e))}static fromHex(e){return D.fromBytes(bt(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}toRawBytes(e){return this.toBytes(e)}};y(D,"BASE"),y(D,"ZERO");var X=D,re=new X(jr,Yr,1n),j=new X(0n,1n,0n);X.BASE=re;X.ZERO=j;var Re=t=>$e("0x"+(yt(t)||"0")),qt=(t,e,n)=>Re(t.subarray(e,n)),ii=2n**256n,Oe=t=>gt(Jt(ye(t,0n,ii),dt)),oi=t=>{let e=Yt(t)?t:Re(bt(t,ne));return ye(e,1n,ht,"private key invalid 3")};var si=t=>{t=bt(t),(t.length<ne+8||t.length>1024)&&U("expected 40-1024b");let e=h(Re(t),ht-1n);return Oe(e+1n)};var ai="SHA-256",xt={hexToBytes:gt,bytesToHex:yt,concatBytes:Pe,bytesToNumberBE:Re,numberToBytesBE:Oe,mod:h,invert:en,hmacSha256Async:async(t,...e)=>{let n=Qr(),r="HMAC",i=await n.importKey("raw",t,{name:r,hash:{name:ai}},!1,["sign"]);return Ne(await n.sign(r,i,Pe(...e)))},hmacSha256Sync:void 0,hashToPrivateKey:si,randomBytes:ei};var Fe=8,ci=256,rn=Math.ceil(ci/Fe)+1,mt=2**(Fe-1),ui=()=>{let t=[],e=re,n=e;for(let r=0;r<rn;r++){n=e,t.push(n);for(let i=1;i<mt;i++)n=n.add(e),t.push(n);e=n.double()}return t},Kt,Wt=(t,e)=>{let n=e.negate();return t?n:e},fi=t=>{let e=Kt||(Kt=ui()),n=j,r=re,i=2**Fe,o=i,s=$e(i-1),a=$e(Fe);for(let c=0;c<rn;c++){let u=Number(t&s);t>>=a,u>mt&&(u-=o,t+=1n);let f=c*mt,p=f,g=f+Math.abs(u)-1,S=c%2!==0,k=u<0;u===0?r=r.add(Wt(S,e[p])):n=n.add(Wt(k,e[g]))}return{p:n,f:r}};function di(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function on(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function oe(t,...e){if(!di(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function sn(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");on(t.outputLen),on(t.blockLen)}function se(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function an(t,e){oe(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function J(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function De(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function F(t,e){return t<<32-e|t>>>e}function pi(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ge(t){return typeof t=="string"&&(t=pi(t)),oe(t),t}var ie=class{};function cn(t){let e=r=>t().update(ge(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function mi(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);let i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,u=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+u,a,r)}function un(t,e,n){return t&e^~t&n}function fn(t,e,n){return t&e^t&n^e&n}var Le=class extends ie{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=De(this.buffer)}update(e){se(this),e=ge(e),oe(e);let{view:n,buffer:r,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=De(e);for(;i<=o-s;s+=i)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){se(this),an(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;n[s++]=128,J(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let p=s;p<i;p++)n[p]=0;mi(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=De(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)a.setUint32(4*p,f[p],o)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},V=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var hi=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Z=new Uint32Array(64),He=class extends Le{constructor(e=32){super(64,e,8,!1),this.A=V[0]|0,this.B=V[1]|0,this.C=V[2]|0,this.D=V[3]|0,this.E=V[4]|0,this.F=V[5]|0,this.G=V[6]|0,this.H=V[7]|0}get(){let{A:e,B:n,C:r,D:i,E:o,F:s,G:a,H:c}=this;return[e,n,r,i,o,s,a,c]}set(e,n,r,i,o,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let p=0;p<16;p++,n+=4)Z[p]=e.getUint32(n,!1);for(let p=16;p<64;p++){let g=Z[p-15],S=Z[p-2],k=F(g,7)^F(g,18)^g>>>3,A=F(S,17)^F(S,19)^S>>>10;Z[p]=A+Z[p-7]+k+Z[p-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:u,H:f}=this;for(let p=0;p<64;p++){let g=F(a,6)^F(a,11)^F(a,25),S=f+g+un(a,c,u)+hi[p]+Z[p]|0,A=(F(r,2)^F(r,13)^F(r,22))+fn(r,i,o)|0;f=u,u=c,c=a,a=s+S|0,s=o,o=i,i=r,r=S+A|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,i,o,s,a,c,u,f)}roundClean(){J(Z)}destroy(){this.set(0,0,0,0,0,0,0,0),J(this.buffer)}};var ln=cn(()=>new He);var ae=ln;var Me=class extends ie{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,sn(e);let r=ge(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),J(o)}update(e){return se(this),this.iHash.update(e),this}digestInto(e){se(this),oe(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wt=(t,e,n)=>new Me(t,e).update(n).digest();wt.create=(t,e)=>new Me(t,e);var yi=["string","number","bigint","symbol"],gi=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function dn(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(yi.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(bi(t))return"Buffer";let n=xi(t);return n||"Object"}function bi(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function xi(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(gi.includes(e))return e}var l=class{constructor(e,n,r){this.major=e,this.majorEncoded=e<<5,this.name=n,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};l.uint=new l(0,"uint",!0);l.negint=new l(1,"negint",!0);l.bytes=new l(2,"bytes",!0);l.string=new l(3,"string",!0);l.array=new l(4,"array",!1);l.map=new l(5,"map",!1);l.tag=new l(6,"tag",!1);l.float=new l(7,"float",!0);l.false=new l(7,"false",!0);l.true=new l(7,"true",!0);l.null=new l(7,"null",!0);l.undefined=new l(7,"undefined",!0);l.break=new l(7,"break",!0);var m=class{constructor(e,n,r){this.type=e,this.value=n,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var ce=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",wi=new TextDecoder,Si=new TextEncoder;function ze(t){return ce&&globalThis.Buffer.isBuffer(t)}function St(t){return t instanceof Uint8Array?ze(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var yn=ce?(t,e,n)=>n-e>64?globalThis.Buffer.from(t.subarray(e,n)).toString("utf8"):mn(t,e,n):(t,e,n)=>n-e>64?wi.decode(t.subarray(e,n)):mn(t,e,n),gn=ce?t=>t.length>64?globalThis.Buffer.from(t):pn(t):t=>t.length>64?Si.encode(t):pn(t),L=t=>Uint8Array.from(t),ue=ce?(t,e,n)=>ze(t)?new Uint8Array(t.subarray(e,n)):t.slice(e,n):(t,e,n)=>t.slice(e,n),bn=ce?(t,e)=>(t=t.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),St(globalThis.Buffer.concat(t,e))):(t,e)=>{let n=new Uint8Array(e),r=0;for(let i of t)r+i.length>n.length&&(i=i.subarray(0,n.length-r)),n.set(i,r),r+=i.length;return n},xn=ce?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Ve(t,e){if(ze(t)&&ze(e))return t.compare(e);for(let n=0;n<t.length;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return 0}function pn(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e}function mn(t,e,n){let r=[];for(;e<n;){let i=t[e],o=null,s=i>239?4:i>223?3:i>191?2:1;if(e+s<=n){let a,c,u,f;switch(s){case 1:i<128&&(o=i);break;case 2:a=t[e+1],(a&192)===128&&(f=(i&31)<<6|a&63,f>127&&(o=f));break;case 3:a=t[e+1],c=t[e+2],(a&192)===128&&(c&192)===128&&(f=(i&15)<<12|(a&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:a=t[e+1],c=t[e+2],u=t[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(f=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),e+=s}return Ei(r)}var hn=4096;function Ei(t){let e=t.length;if(e<=hn)return String.fromCharCode.apply(String,t);let n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=hn));return n}var ki=256,be=class{constructor(e=ki){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let n=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=n.length-(this.maxCursor-this.cursor)-1;n.set(e,i)}else{if(n){let i=n.length-(this.maxCursor-this.cursor)-1;i<n.length&&(this.chunks[this.chunks.length-1]=n.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(n=xn(this.chunkSize),this.chunks.push(n),this.maxCursor+=n.length,this._initReuseChunk===null&&(this._initReuseChunk=n),n.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let n;if(this.chunks.length===1){let r=this.chunks[0];e&&this.cursor>r.length/2?(n=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):n=ue(r,0,this.cursor)}else n=bn(this.chunks,this.cursor);return e&&this.reset(),n}};var b="CBOR decode error:",Et="CBOR encode error:",xe=[];xe[23]=1;xe[24]=2;xe[25]=3;xe[26]=5;xe[27]=9;function G(t,e,n){if(t.length-e<n)throw new Error(`${b} not enough data for type`)}var E=[24,256,65536,4294967296,BigInt("18446744073709551616")];function C(t,e,n){G(t,e,1);let r=t[e];if(n.strict===!0&&r<E[0])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function I(t,e,n){G(t,e,2);let r=t[e]<<8|t[e+1];if(n.strict===!0&&r<E[1])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function B(t,e,n){G(t,e,4);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(n.strict===!0&&r<E[2])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function _(t,e,n){G(t,e,8);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],i=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],o=(BigInt(r)<<BigInt(32))+BigInt(i);if(n.strict===!0&&o<E[3])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(n.allowBigInt===!0)return o;throw new Error(`${b} integers outside of the safe integer range are not supported`)}function wn(t,e,n,r){return new m(l.uint,C(t,e+1,r),2)}function Sn(t,e,n,r){return new m(l.uint,I(t,e+1,r),3)}function En(t,e,n,r){return new m(l.uint,B(t,e+1,r),5)}function kn(t,e,n,r){return new m(l.uint,_(t,e+1,r),9)}function P(t,e){return T(t,0,e.value)}function T(t,e,n){if(n<E[0]){let r=Number(n);t.push([e|r])}else if(n<E[1]){let r=Number(n);t.push([e|24,r])}else if(n<E[2]){let r=Number(n);t.push([e|25,r>>>8,r&255])}else if(n<E[3]){let r=Number(n);t.push([e|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<E[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(r&BigInt(4294967295)),s=Number(r>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,t.push(i)}else throw new Error(`${b} encountered BigInt larger than allowable range`)}}P.encodedSize=function(e){return T.encodedSize(e.value)};T.encodedSize=function(e){return e<E[0]?1:e<E[1]?2:e<E[2]?3:e<E[3]?5:9};P.compareTokens=function(e,n){return e.value<n.value?-1:e.value>n.value?1:0};function Tn(t,e,n,r){return new m(l.negint,-1-C(t,e+1,r),2)}function An(t,e,n,r){return new m(l.negint,-1-I(t,e+1,r),3)}function vn(t,e,n,r){return new m(l.negint,-1-B(t,e+1,r),5)}var kt=BigInt(-1),Un=BigInt(1);function Cn(t,e,n,r){let i=_(t,e+1,r);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new m(l.negint,o,9)}if(r.allowBigInt!==!0)throw new Error(`${b} integers outside of the safe integer range are not supported`);return new m(l.negint,kt-BigInt(i),9)}function Ge(t,e){let n=e.value,r=typeof n=="bigint"?n*kt-Un:n*-1-1;T(t,e.type.majorEncoded,r)}Ge.encodedSize=function(e){let n=e.value,r=typeof n=="bigint"?n*kt-Un:n*-1-1;return r<E[0]?1:r<E[1]?2:r<E[2]?3:r<E[3]?5:9};Ge.compareTokens=function(e,n){return e.value<n.value?1:e.value>n.value?-1:0};function we(t,e,n,r){G(t,e,n+r);let i=ue(t,e+n,e+n+r);return new m(l.bytes,i,n+r)}function In(t,e,n,r){return we(t,e,1,n)}function Bn(t,e,n,r){return we(t,e,2,C(t,e+1,r))}function _n(t,e,n,r){return we(t,e,3,I(t,e+1,r))}function Pn(t,e,n,r){return we(t,e,5,B(t,e+1,r))}function $n(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer bytes lengths not supported`);return we(t,e,9,i)}function Ze(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===l.string?gn(t.value):t.value),t.encodedBytes}function fe(t,e){let n=Ze(e);T(t,e.type.majorEncoded,n.length),t.push(n)}fe.encodedSize=function(e){let n=Ze(e);return T.encodedSize(n.length)+n.length};fe.compareTokens=function(e,n){return Ai(Ze(e),Ze(n))};function Ai(t,e){return t.length<e.length?-1:t.length>e.length?1:Ve(t,e)}function Se(t,e,n,r,i){let o=n+r;G(t,e,o);let s=new m(l.string,yn(t,e+n,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=ue(t,e+n,e+o)),s}function On(t,e,n,r){return Se(t,e,1,n,r)}function Fn(t,e,n,r){return Se(t,e,2,C(t,e+1,r),r)}function Nn(t,e,n,r){return Se(t,e,3,I(t,e+1,r),r)}function Rn(t,e,n,r){return Se(t,e,5,B(t,e+1,r),r)}function Dn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer string lengths not supported`);return Se(t,e,9,i,r)}var Ln=fe;function le(t,e,n,r){return new m(l.array,r,n)}function Hn(t,e,n,r){return le(t,e,1,n)}function Mn(t,e,n,r){return le(t,e,2,C(t,e+1,r))}function zn(t,e,n,r){return le(t,e,3,I(t,e+1,r))}function Vn(t,e,n,r){return le(t,e,5,B(t,e+1,r))}function Gn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer array lengths not supported`);return le(t,e,9,i)}function Zn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return le(t,e,1,1/0)}function qe(t,e){T(t,l.array.majorEncoded,e.value)}qe.compareTokens=P.compareTokens;qe.encodedSize=function(e){return T.encodedSize(e.value)};function de(t,e,n,r){return new m(l.map,r,n)}function qn(t,e,n,r){return de(t,e,1,n)}function Kn(t,e,n,r){return de(t,e,2,C(t,e+1,r))}function Wn(t,e,n,r){return de(t,e,3,I(t,e+1,r))}function jn(t,e,n,r){return de(t,e,5,B(t,e+1,r))}function Yn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer map lengths not supported`);return de(t,e,9,i)}function Xn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return de(t,e,1,1/0)}function Ke(t,e){T(t,l.map.majorEncoded,e.value)}Ke.compareTokens=P.compareTokens;Ke.encodedSize=function(e){return T.encodedSize(e.value)};function Jn(t,e,n,r){return new m(l.tag,n,1)}function Qn(t,e,n,r){return new m(l.tag,C(t,e+1,r),2)}function er(t,e,n,r){return new m(l.tag,I(t,e+1,r),3)}function tr(t,e,n,r){return new m(l.tag,B(t,e+1,r),5)}function nr(t,e,n,r){return new m(l.tag,_(t,e+1,r),9)}function We(t,e){T(t,l.tag.majorEncoded,e.value)}We.compareTokens=P.compareTokens;We.encodedSize=function(e){return T.encodedSize(e.value)};var _i=20,Pi=21,$i=22,Oi=23;function rr(t,e,n,r){if(r.allowUndefined===!1)throw new Error(`${b} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new m(l.null,null,1):new m(l.undefined,void 0,1)}function ir(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return new m(l.break,void 0,1)}function Tt(t,e,n){if(n){if(n.allowNaN===!1&&Number.isNaN(t))throw new Error(`${b} NaN values are not supported`);if(n.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${b} Infinity values are not supported`)}return new m(l.float,t,e)}function or(t,e,n,r){return Tt(At(t,e+1),3,r)}function sr(t,e,n,r){return Tt(vt(t,e+1),5,r)}function ar(t,e,n,r){return Tt(lr(t,e+1),9,r)}function je(t,e,n){let r=e.value;if(r===!1)t.push([l.float.majorEncoded|_i]);else if(r===!0)t.push([l.float.majorEncoded|Pi]);else if(r===null)t.push([l.float.majorEncoded|$i]);else if(r===void 0)t.push([l.float.majorEncoded|Oi]);else{let i,o=!1;(!n||n.float64!==!0)&&(ur(r),i=At(N,1),r===i||Number.isNaN(r)?(N[0]=249,t.push(N.slice(0,3)),o=!0):(fr(r),i=vt(N,1),r===i&&(N[0]=250,t.push(N.slice(0,5)),o=!0))),o||(Fi(r),i=lr(N,1),N[0]=251,t.push(N.slice(0,9)))}}je.encodedSize=function(e,n){let r=e.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!n||n.float64!==!0){ur(r);let i=At(N,1);if(r===i||Number.isNaN(r))return 3;if(fr(r),i=vt(N,1),r===i)return 5}return 9};var cr=new ArrayBuffer(9),$=new DataView(cr,1),N=new Uint8Array(cr,0);function ur(t){if(t===1/0)$.setUint16(0,31744,!1);else if(t===-1/0)$.setUint16(0,64512,!1);else if(Number.isNaN(t))$.setUint16(0,32256,!1);else{$.setFloat32(0,t);let e=$.getUint32(0),n=(e&2139095040)>>23,r=e&8388607;if(n===255)$.setUint16(0,31744,!1);else if(n===0)$.setUint16(0,(t&2147483648)>>16|r>>13,!1);else{let i=n-127;i<-24?$.setUint16(0,0):i<-14?$.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):$.setUint16(0,(e&2147483648)>>16|i+15<<10|r>>13,!1)}}}function At(t,e){if(t.length-e<2)throw new Error(`${b} not enough data for float16`);let n=(t[e]<<8)+t[e+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,i=n&1023,o;return r===0?o=i*2**-24:r!==31?o=(i+1024)*2**(r-25):o=i===0?1/0:NaN,n&32768?-o:o}function fr(t){$.setFloat32(0,t,!1)}function vt(t,e){if(t.length-e<4)throw new Error(`${b} not enough data for float32`);let n=(t.byteOffset||0)+e;return new DataView(t.buffer,n,4).getFloat32(0,!1)}function Fi(t){$.setFloat64(0,t,!1)}function lr(t,e){if(t.length-e<8)throw new Error(`${b} not enough data for float64`);let n=(t.byteOffset||0)+e;return new DataView(t.buffer,n,8).getFloat64(0,!1)}je.compareTokens=P.compareTokens;function x(t,e,n){throw new Error(`${b} encountered invalid minor (${n}) for major ${t[e]>>>5}`)}function Ye(t){return()=>{throw new Error(`${b} ${t}`)}}var d=[];for(let t=0;t<=23;t++)d[t]=x;d[24]=wn;d[25]=Sn;d[26]=En;d[27]=kn;d[28]=x;d[29]=x;d[30]=x;d[31]=x;for(let t=32;t<=55;t++)d[t]=x;d[56]=Tn;d[57]=An;d[58]=vn;d[59]=Cn;d[60]=x;d[61]=x;d[62]=x;d[63]=x;for(let t=64;t<=87;t++)d[t]=In;d[88]=Bn;d[89]=_n;d[90]=Pn;d[91]=$n;d[92]=x;d[93]=x;d[94]=x;d[95]=Ye("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)d[t]=On;d[120]=Fn;d[121]=Nn;d[122]=Rn;d[123]=Dn;d[124]=x;d[125]=x;d[126]=x;d[127]=Ye("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)d[t]=Hn;d[152]=Mn;d[153]=zn;d[154]=Vn;d[155]=Gn;d[156]=x;d[157]=x;d[158]=x;d[159]=Zn;for(let t=160;t<=183;t++)d[t]=qn;d[184]=Kn;d[185]=Wn;d[186]=jn;d[187]=Yn;d[188]=x;d[189]=x;d[190]=x;d[191]=Xn;for(let t=192;t<=215;t++)d[t]=Jn;d[216]=Qn;d[217]=er;d[218]=tr;d[219]=nr;d[220]=x;d[221]=x;d[222]=x;d[223]=x;for(let t=224;t<=243;t++)d[t]=Ye("simple values are not supported");d[244]=x;d[245]=x;d[246]=x;d[247]=rr;d[248]=Ye("simple values are not supported");d[249]=or;d[250]=sr;d[251]=ar;d[252]=x;d[253]=x;d[254]=x;d[255]=ir;var H=[];for(let t=0;t<24;t++)H[t]=new m(l.uint,t,1);for(let t=-1;t>=-24;t--)H[31-t]=new m(l.negint,t,1);H[64]=new m(l.bytes,new Uint8Array(0),1);H[96]=new m(l.string,"",1);H[128]=new m(l.array,0,1);H[160]=new m(l.map,0,1);H[244]=new m(l.false,!1,1);H[245]=new m(l.true,!0,1);H[246]=new m(l.null,null,1);function dr(t){switch(t.type){case l.false:return L([244]);case l.true:return L([245]);case l.null:return L([246]);case l.bytes:return t.value.length?void 0:L([64]);case l.string:return t.value===""?L([96]):void 0;case l.array:return t.value===0?L([128]):void 0;case l.map:return t.value===0?L([160]):void 0;case l.uint:return t.value<24?L([Number(t.value)]):void 0;case l.negint:if(t.value>=-24)return L([31-Number(t.value)])}}var mr=Object.freeze({float64:!0,mapSorter:Hi,quickEncodeToken:dr});function Ri(){let t=[];return t[l.uint.major]=P,t[l.negint.major]=Ge,t[l.bytes.major]=fe,t[l.string.major]=Ln,t[l.array.major]=qe,t[l.map.major]=Ke,t[l.tag.major]=We,t[l.float.major]=je,t}var Di=Ri(),Ut=new be,Je=class t{constructor(e,n){this.obj=e,this.parent=n}includes(e){let n=this;do if(n.obj===e)return!0;while(n=n.parent);return!1}static createCheck(e,n){if(e&&e.includes(n))throw new Error(`${Et} object contains circular references`);return new t(n,e)}},q={null:new m(l.null,null),undefined:new m(l.undefined,void 0),true:new m(l.true,!0),false:new m(l.false,!1),emptyArray:new m(l.array,0),emptyMap:new m(l.map,0)},K={number(t,e,n,r){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new m(l.float,t):t>=0?new m(l.uint,t):new m(l.negint,t)},bigint(t,e,n,r){return t>=BigInt(0)?new m(l.uint,t):new m(l.negint,t)},Uint8Array(t,e,n,r){return new m(l.bytes,t)},string(t,e,n,r){return new m(l.string,t)},boolean(t,e,n,r){return t?q.true:q.false},null(t,e,n,r){return q.null},undefined(t,e,n,r){return q.undefined},ArrayBuffer(t,e,n,r){return new m(l.bytes,new Uint8Array(t))},DataView(t,e,n,r){return new m(l.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,n,r){if(!t.length)return n.addBreakTokens===!0?[q.emptyArray,new m(l.break)]:q.emptyArray;r=Je.createCheck(r,t);let i=[],o=0;for(let s of t)i[o++]=Xe(s,n,r);return n.addBreakTokens?[new m(l.array,t.length),i,new m(l.break)]:[new m(l.array,t.length),i]},Object(t,e,n,r){let i=e!=="Object",o=i?t.keys():Object.keys(t),s=i?t.size:o.length;if(!s)return n.addBreakTokens===!0?[q.emptyMap,new m(l.break)]:q.emptyMap;r=Je.createCheck(r,t);let a=[],c=0;for(let u of o)a[c++]=[Xe(u,n,r),Xe(i?t.get(u):t[u],n,r)];return Li(a,n),n.addBreakTokens?[new m(l.map,s),a,new m(l.break)]:[new m(l.map,s),a]}};K.Map=K.Object;K.Buffer=K.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))K[`${t}Array`]=K.DataView;function Xe(t,e={},n){let r=dn(t),i=e&&e.typeEncoders&&e.typeEncoders[r]||K[r];if(typeof i=="function"){let s=i(t,r,e,n);if(s!=null)return s}let o=K[r];if(!o)throw new Error(`${Et} unsupported type: ${r}`);return o(t,r,e,n)}function Li(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Hi(t,e){if(t[0]instanceof m&&e[0]instanceof m){let n=t[0],r=e[0];return n._keyBytes||(n._keyBytes=pr(n.value)),r._keyBytes||(r._keyBytes=pr(r.value)),Ve(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function pr(t){return Mi(t,Di,mr)}function hr(t,e,n,r){if(Array.isArray(e))for(let i of e)hr(t,i,n,r);else n[e.type.major](t,e,r)}function Mi(t,e,n){let r=Xe(t,n);if(!Array.isArray(r)&&n.quickEncodeToken){let i=n.quickEncodeToken(r);if(i)return i;let o=e[r.type.major];if(o.encodedSize){let s=o.encodedSize(r,n),a=new be(s);if(o(a,r,n),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${r} was wrong`);return St(a.chunks[0])}}return Ut.reset(),hr(Ut,r,e,n),Ut.toBytes(!0)}var Ss=Symbol.for("DONE"),Es=Symbol.for("BREAK");xt.hmacSha256Sync=(t,...e)=>wt(ae,t,xt.concatBytes(...e));var Gi=32;function Qe(t){if(t.length===0)return new Uint8Array(Gi);let e=t.length,n=e*4,r=t.reduce((c,u)=>c+u.length,0),i=4+n+r,o=new Uint8Array(i),s=new DataView(o.buffer,o.byteOffset,o.byteLength);s.setUint32(0,e,!0);let a=4;for(let c of t)s.setUint32(a,c.length,!0),a+=4;for(let c of t)o.set(c,a),a+=c.length;return ae(o)}var Ct={bool:1,uint8:1,int8:1,uint16:2,int16:2,uint32:4,int32:4,entityRef:4,f32:4,vec2:8,vec3:12,quat:16,enum:1},Ee={bool:1,uint8:1,int8:1,uint16:2,int16:2,uint32:4,int32:4,f32:4,flags8:1,flags16:2,flags32:4,vec2:8,vec3:12,quat:16};var yr=new Set(["bool","uint8","int8","uint16","int16","uint32","int32","f32"]);function _t(t){let e=t.match(/^(\\w+)\\[(\\d+)\\]$/);if(!e||!e[1]||!e[2])return null;let n=e[1],r=parseInt(e[2],10);if(!yr.has(n))throw new Error(`Invalid array element type \'${n}\': arrays only support primitive scalar types (bool, uint8, int8, uint16, int16, uint32, int32, f32)`);return{elementType:n,length:r}}function gr(t){let e=_t(t);if(e){let r=Ee[e.elementType];if(r===void 0)throw new Error(`Unknown element type: ${e.elementType}`);return r*e.length}let n=Ee[t];if(n===void 0)throw new Error(`Unknown type: ${t}`);return n}function Zi(t){let e=[],n=[],r=new Map,i=new Map,o=0;for(let s of t.controls){let a=gr(s.type),c=_t(s.type),u={name:s.name,type:s.type,size:a,offset:0,options:s.options};c&&(u.arrayLength=c.length,u.arrayElementType=c.elementType);let f={name:s.name,index:o++,field:u,hint:s.hint,retain:s.retain==="always"?"always":"tick"};e.push(f),r.set(s.name,f)}for(let s of t.commands){let a=[],c=0;for(let f of s.args){let p=gr(f.type),g=_t(f.type),S={name:f.name,type:f.type,size:p,offset:c};g&&(S.arrayLength=g.length,S.arrayElementType=g.elementType),a.push(S),c+=p}let u={name:s.name,index:o++,args:a,totalSize:c};n.push(u),i.set(s.name,u)}return{controls:e,commands:n,controlByName:r,commandByName:i}}function It(t,e,n,r){switch(n){case"bool":t.setUint8(e,r?1:0);break;case"uint8":case"flags8":t.setUint8(e,r);break;case"int8":t.setInt8(e,r);break;case"uint16":case"flags16":t.setUint16(e,r,!0);break;case"int16":t.setInt16(e,r,!0);break;case"uint32":case"flags32":t.setUint32(e,r,!0);break;case"int32":t.setInt32(e,r,!0);break;case"f32":t.setFloat32(e,r,!0);break;default:throw new Error(`Cannot write primitive type: ${n}`)}}function Bt(t,e,n){switch(n){case"bool":return t.getUint8(e)!==0;case"uint8":case"flags8":return t.getUint8(e);case"int8":return t.getInt8(e);case"uint16":case"flags16":return t.getUint16(e,!0);case"int16":return t.getInt16(e,!0);case"uint32":case"flags32":return t.getUint32(e,!0);case"int32":return t.getInt32(e,!0);case"f32":return t.getFloat32(e,!0);default:throw new Error(`Cannot read primitive type: ${n}`)}}var et=class t{constructor(e){y(this,"schema");y(this,"fields",new Map);y(this,"commandList",[]);this.schema=e}setControl(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);let i=new Uint8Array(r.field.size),o=new DataView(i.buffer);this.encodeValue(o,0,r.field,n),this.fields.set(r.index,i)}setFlags(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(!r.field.options)throw new Error(`Control ${e} is not a flags type`);let i=0;for(let a=0;a<r.field.options.length;a++){let c=r.field.options[a];n[c]&&(i|=1<<a)}let o=new Uint8Array(r.field.size),s=new DataView(o.buffer);It(s,0,r.field.type,i),this.fields.set(r.index,o)}setVec2(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="vec2")throw new Error(`Control ${e} is not a vec2`);let i=new Uint8Array(8),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),this.fields.set(r.index,i)}setVec3(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="vec3")throw new Error(`Control ${e} is not a vec3`);let i=new Uint8Array(12),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),o.setFloat32(8,n[2],!0),this.fields.set(r.index,i)}setQuat(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="quat")throw new Error(`Control ${e} is not a quat`);let i=new Uint8Array(16),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),o.setFloat32(8,n[2],!0),o.setFloat32(12,n[3],!0),this.fields.set(r.index,i)}getControl(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);let r=this.fields.get(n.index);if(!r)return this.getDefaultValue(n.field);let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return this.decodeValue(i,0,n.field)}getFlags(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(!n.field.options)throw new Error(`Control ${e} is not a flags type`);let r=this.fields.get(n.index),i=0;if(r){let s=new DataView(r.buffer,r.byteOffset,r.byteLength);i=Bt(s,0,n.field.type)}let o={};for(let s=0;s<n.field.options.length;s++)o[n.field.options[s]]=(i&1<<s)!==0;return o}getVec2(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="vec2")throw new Error(`Control ${e} is not a vec2`);let r=this.fields.get(n.index);if(!r)return[0,0];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0)]}getVec3(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="vec3")throw new Error(`Control ${e} is not a vec3`);let r=this.fields.get(n.index);if(!r)return[0,0,0];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0),i.getFloat32(8,!0)]}getQuat(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="quat")throw new Error(`Control ${e} is not a quat`);let r=this.fields.get(n.index);if(!r)return[0,0,0,1];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0),i.getFloat32(8,!0),i.getFloat32(12,!0)]}hasControl(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);return this.fields.has(n.index)}addCommand(e,n){let r=this.schema.commandByName.get(e);if(!r)throw new Error(`Unknown command: ${e}`);let i=new Uint8Array(r.totalSize),o=new DataView(i.buffer);for(let s of r.args){let a=n[s.name];if(a===void 0)throw new Error(`Missing required argument: ${s.name}`);this.encodeValue(o,s.offset,s,a)}this.commandList.push({index:r.index,data:i})}getCommands(){let e=[];for(let{index:n,data:r}of this.commandList){let i=this.schema.commands.find(a=>a.index===n);if(!i)continue;let o=new DataView(r.buffer,r.byteOffset,r.byteLength),s={name:i.name};for(let a of i.args)s[a.name]=this.decodeValue(o,a.offset,a);e.push(s)}return e}encode(){let e=[];for(let[o,s]of this.fields){let a=new Uint8Array(2+s.length);a[0]=o,a[1]=s.length,a.set(s,2),e.push(a)}for(let o of this.commandList){let s=new Uint8Array(2+o.data.length);s[0]=o.index,s[1]=o.data.length,s.set(o.data,2),e.push(s)}let n=e.reduce((o,s)=>o+s.length,0),r=new Uint8Array(n),i=0;for(let o of e)r.set(o,i),i+=o.length;return r}static decode(e,n){let r=new t(e),i=0;for(;i<n.length;){if(i+2>n.length)throw new Error("Truncated TLV field header");let o=n[i],s=n[i+1];if(i+2+s>n.length)throw new Error(`Truncated TLV field data at index ${o}`);let a=n.subarray(i+2,i+2+s);e.controls.find(u=>u.index===o)?r.fields.set(o,new Uint8Array(a)):e.commands.find(f=>f.index===o)&&r.commandList.push({index:o,data:new Uint8Array(a)}),i+=2+s}return r}clear(){this.fields.clear(),this.commandList.length=0}encodeValue(e,n,r,i){if(r.type==="vec2"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0)}else if(r.type==="vec3"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0),e.setFloat32(n+8,o[2],!0)}else if(r.type==="quat"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0),e.setFloat32(n+8,o[2],!0),e.setFloat32(n+12,o[3],!0)}else if(r.arrayLength!==void 0&&r.arrayElementType!==void 0){let o=i,s=Ee[r.arrayElementType];for(let a=0;a<Math.min(o.length,r.arrayLength);a++)It(e,n+a*s,r.arrayElementType,o[a])}else It(e,n,r.type,i)}decodeValue(e,n,r){if(r.type==="vec2")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0)];if(r.type==="vec3")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0),e.getFloat32(n+8,!0)];if(r.type==="quat")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0),e.getFloat32(n+8,!0),e.getFloat32(n+12,!0)];if(r.arrayLength!==void 0&&r.arrayElementType!==void 0){let i=[],o=Ee[r.arrayElementType];for(let s=0;s<r.arrayLength;s++)i.push(Bt(e,n+s*o,r.arrayElementType));return i}else return Bt(e,n,r.type)}getDefaultValue(e){return e.type==="vec2"?[0,0]:e.type==="vec3"?[0,0,0]:e.type==="quat"?[0,0,0,1]:e.arrayLength!==void 0?new Array(e.arrayLength).fill(0):e.type==="bool"?!1:0}};function br(t){let e=Zi(t);return{create(){return new et(e)},decode(n){return et.decode(e,n)},get schema(){return e}}}function xr(t,e){return((e&65535)<<16|t&65535)>>>0}function ke(t){return t&65535}function Yi(t){return t>>>16&65535}function pe(t){return t.subarray(8,40)}function Pt(t,e){if(e.length!==32)throw new Error(`stateId must be ${32} bytes, got ${e.length}`);t.set(e,8)}function wr(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint32(40,e,!0)}function rt(t,e,n){let r=new Uint8Array(68);return r.set(t,0),new DataView(r.buffer).setUint32(32,e,!0),r.set(n,36),ae(r)}function Sr(t,e,n){return rt(t,e,Qe(n))}function $t(t){return ae(t)}function Er(t,e,n){let r=new ArrayBuffer(t.totalSize),i=new Uint8Array(r),o=new DataView(r);if(o.setUint32(0,1297367376,!0),o.setUint16(4,0,!0),i[6]=n??0,i[7]=0,e){let a=$t(e);i.set(a,8)}let s=t.freeStackOffset;o.setUint16(s,t.maxEntities,!0);for(let a=0;a<t.maxEntities;a++){let c=t.freeStackOffset+2+a*2;o.setUint16(c,a,!0)}return i}function kr(t,e){return t.entityTableOffset+e*t.entityRecordSize}function Ot(t,e,n){let r=kr(t,n);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(r,!0)}function Xi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(4,!0)}function Ji(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(4,e,!0)}function Qi(t,e){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t.freeStackOffset,!0)}function eo(t,e,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t.freeStackOffset,n,!0)}function to(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Qi(t,e);if(r===0)throw new Error(`No free entity slots available (max: ${t.maxEntities})`);let i=t.freeStackOffset+2+(r-1)*2,o=n.getUint16(i,!0);return eo(t,e,r-1),o}function Tr(t,e){let n=to(t,e),r=Ot(t,e,n);return Ji(e,Xi(e)+1),xr(n,r)}function it(t,e,n){if(n===4294967295)return!1;let r=ke(n);if(r>=t.maxEntities)return!1;let i=Yi(n);return Ot(t,e,r)===i}function Ft(t,e,n){if(n<0)throw new Error("Singleton components do not have component bitmask entries");let r=kr(t,e)+2,i=Math.floor(n/8),o=n%8;return{byteOffset:r+i,bitIndex:o}}function Ar(t,e,n,r){if(!it(t,e,n))return!1;let i=t.componentByName.get(r);if(!i)throw new Error(`Unknown component: \'${r}\'`);if(i.isSingleton)throw new Error(`Component \'${r}\' is a singleton and is always present`);let o=ke(n),{byteOffset:s,bitIndex:a}=Ft(t,o,i.index);return(e[s]&1<<a)!==0}function vr(t,e,n,r){if(!it(t,e,n)){let c=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${c} is not alive`)}let i=t.componentByName.get(r);if(!i)throw new Error(`Unknown component: \'${r}\'`);if(i.isSingleton)throw new Error(`Component \'${r}\' is a singleton and cannot be added to entities`);let o=ke(n),{byteOffset:s,bitIndex:a}=Ft(t,o,i.index);e[s]=(e[s]??0)|1<<a}function Ur(t,e,n,r){let i=ke(e);return n.storageOffset+i*n.size+r.offset}function no(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(n){case"bool":return(t[e]??0)!==0;case"uint8":return t[e]??0;case"int8":return r.getInt8(e);case"uint16":return r.getUint16(e,!0);case"int16":return r.getInt16(e,!0);case"uint32":return r.getUint32(e,!0);case"int32":return r.getInt32(e,!0);case"entityRef":return r.getUint32(e,!0);case"f32":return r.getFloat32(e,!0);default:throw new Error(`Cannot read primitive type: ${n}`)}}function Cr(t,e,n,r){let i=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(n){case"bool":t[e]=r?1:0;break;case"uint8":t[e]=r&255;break;case"int8":i.setInt8(e,r);break;case"uint16":i.setUint16(e,r,!0);break;case"int16":i.setInt16(e,r,!0);break;case"uint32":i.setUint32(e,r,!0);break;case"int32":i.setInt32(e,r,!0);break;case"entityRef":i.setUint32(e,r,!0);break;case"f32":i.setFloat32(e,r,!0);break;default:throw new Error(`Cannot write primitive type: ${n}`)}}function ro(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0)}function io(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0),r.setFloat32(e+8,n[2],!0)}function oo(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0),r.setFloat32(e+8,n[2],!0),r.setFloat32(e+12,n[3],!0)}function Ir(t,e,n,r,i,o){if(!it(t,e,n))return;let s=t.componentByName.get(r);if(!s)throw new Error(`Unknown component: \'${r}\'`);if(s.isSingleton)throw new Error(`Component \'${r}\' is a singleton; use singleton accessors instead`);if(!nt(t,e,n,s))return;let a=s.fields.find(f=>f.name===i);if(!a)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let c=Ur(t,n,s,a),u=a.type;if(a.arrayLength!==void 0&&a.arrayElementType!==void 0){if(o===void 0)throw new Error(`Field \'${r}.${i}\' is an array, index required`);if(o<0||o>=a.arrayLength)throw new Error(`Array index ${o} out of bounds for ${r}.${i} (length: ${a.arrayLength})`);let f=Ct[a.arrayElementType];if(f===void 0)throw new Error(`Unknown array element type: ${a.arrayElementType}`);c+=o*f,u=a.arrayElementType}return no(e,c,u)}function w(t,e,n,r,i,o,s){if(!it(t,e,n)){let p=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${p} is not alive`)}let a=t.componentByName.get(r);if(!a)throw new Error(`Unknown component: \'${r}\'`);if(!nt(t,e,n,a)){let p=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${p} does not have component \'${r}\'`)}let c=a.fields.find(p=>p.name===i);if(!c)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let u=Ur(t,n,a,c),f=c.type;if(c.arrayLength!==void 0&&c.arrayElementType!==void 0){if(s===void 0)throw new Error(`Field \'${r}.${i}\' is an array, index required`);if(s<0||s>=c.arrayLength)throw new Error(`Array index ${s} out of bounds for ${r}.${i} (length: ${c.arrayLength})`);let p=Ct[c.arrayElementType];if(p===void 0)throw new Error(`Unknown array element type: ${c.arrayElementType}`);u+=s*p,f=c.arrayElementType}Cr(e,u,f,o)}function nt(t,e,n,r){if(r.isSingleton)throw new Error(`Component \'${r.name}\' is a singleton and cannot be queried per entity`);let i=ke(n),{byteOffset:o,bitIndex:s}=Ft(t,i,r.index);return(e[o]&1<<s)!==0}function Br(t,e,n,r){if(n.length===0)throw new Error("Query must include at least one component");let i=[];for(let a of n){let c=t.componentByName.get(a);if(!c)throw new Error(`Unknown component: \'${a}\'`);if(c.isSingleton)throw new Error(`Singleton component \'${a}\' cannot be used in queries`);i.push(c)}let o=[];if(r)for(let a of r){let c=t.componentByName.get(a);if(!c)throw new Error(`Unknown component: \'${a}\'`);if(c.isSingleton)throw new Error(`Singleton component \'${a}\' cannot be used in queries`);o.push(c)}function*s(){for(let a=0;a<t.maxEntities;a++){let c=Ot(t,e,a),u=xr(a,c),f=!0;for(let p of i)if(!nt(t,e,u,p)){f=!1;break}if(f){for(let p of o)if(nt(t,e,u,p)){f=!1;break}f&&(yield u)}}}return s()}function _r(t,e){if(!t.events||!t.eventByName)throw new Error("Schema has no events");let n=t.eventByName.get(e);if(!n)throw new Error(`Unknown event: \'${e}\'`);return n}function Pr(t,e,n){let r=_r(t,n);new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(r.storageOffset,0,!0)}function $r(t,e,n,r){let i=_r(t,n),o=new DataView(e.buffer,e.byteOffset,e.byteLength),s=o.getUint16(i.storageOffset,!0);if(s>=i.maxEvents)return!1;let a=i.storageOffset+2+s*i.recordSize;for(let c of i.fields){let u=r[c.name];if(u===void 0)throw new Error(`Missing required field \'${c.name}\' for event \'${n}\'`);let f=a+c.offset;c.type==="vec2"?ro(e,f,u):c.type==="vec3"?io(e,f,u):c.type==="quat"?oo(e,f,u):Cr(e,f,c.type,u)}return o.setUint16(i.storageOffset,s+1,!0),!0}function ot(t){if(t.length!==32)throw new Error(`stateId must be ${32} bytes, got ${t.length}`);return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var st=class{constructor(e={}){y(this,"cache");y(this,"maxSize");this.cache=new Map,this.maxSize=e.maxSize??100}store(e){let n=pe(e),r=ot(n);if(this.cache.size>=this.maxSize&&!this.cache.has(r)){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}this.cache.set(r,e.slice())}getByStateId(e){let n=ot(e),r=this.cache.get(n);return r?r.slice():void 0}getCached(e,n,r){let i=pe(e),o=rt(i,n,r);return this.getByStateId(o)}has(e){let n=ot(e);return this.cache.has(n)}hasCached(e,n,r){let i=pe(e),o=rt(i,n,r);return this.has(o)}delete(e){let n=ot(e);return this.cache.delete(n)}clear(){this.cache.clear()}get size(){return this.cache.size}keys(){return this.cache.keys()}};var Te=65536,at=class{constructor(e){y(this,"memory",null);y(this,"plugins",[]);y(this,"options");y(this,"stateSize",null);y(this,"statePtr",null);y(this,"heapPos",0);y(this,"arenaResetMark",0);y(this,"inputCodec",null);y(this,"playerEntities",new Map);y(this,"hostAlloc",(e,n)=>{let r=this.memory;if(!r)throw new Error("Memory not initialized for host_alloc");let i=this.heapPos+n-1&~(n-1),o=i+e,s=r.buffer.byteLength;if(o>s){let c=Math.ceil((o-s)/Te);if(this.options.debug){let u=(s+c*Te)/1048576;console.warn(`[mt] WASM memory grew to ${u.toFixed(1)}MB`)}r.grow(c)}return new Uint8Array(r.buffer).fill(0,i,o),this.heapPos=o,i});this.options=e}markArenaReset(){this.arenaResetMark=this.heapPos}resetArena(){this.heapPos=this.arenaResetMark}async init(){if(this.stateSize=this.options.stateSchema.totalSize,!this.stateSize)throw new Error("State schema total size is required");this.options.inputSchema&&(this.inputCodec=br(this.options.inputSchema));let e=4*1024*1024,n=this.options.plugins??(this.options.moduleBytes?[{name:"main",wasmBytes:this.options.moduleBytes,reservedBytes:e}]:[]);for(let c of n)if(typeof c.reservedBytes!="number"||c.reservedBytes<=0)throw new Error(`Plugin "${c.name}" requires reservedBytes > 0`);let r=n.reduce((c,u)=>{let f=Math.ceil(u.reservedBytes/Te)*Te;return c+f},0),i=1024*1024*5,o=this.stateSize+i+r,s=Math.ceil(o/Te);this.memory=new WebAssembly.Memory({initial:s}),this.heapPos=r;let a={env:{memory:this.memory,host_alloc:this.hostAlloc,abort:()=>{throw new Error("WASM abort called")}}};for(let c of n){let u=c.wasmBytes.slice().buffer,f=await WebAssembly.compile(u),p=await WebAssembly.instantiate(f,a);if(typeof p.exports.apply!="function")throw new Error(`Plugin "${c.name}" missing required apply() export`);this.plugins.push({name:c.name,instance:p,exports:p.exports})}return this.statePtr=this.hostAlloc(this.stateSize,8),this.markArenaReset(),this}findPlayerEntity(e,n){let r=this.options.stateSchema,i=this.playerEntities.get(n);if(i!==void 0){if(Ar(r,e,i,"Player"))return i;this.playerEntities.delete(n)}for(let o of Br(r,e,["Player"]))if(Ir(r,e,o,"Player","index")===n)return this.playerEntities.set(n,o),o}spawnPlayerEntity(e,n){let r=this.options.stateSchema,i=Tr(r,e);return vr(r,e,i,"Player"),w(r,e,i,"Player","index",n),this.playerEntities.set(n,i),i}findOrSpawnPlayerEntity(e,n){let r=this.findPlayerEntity(e,n);return r!==void 0?r:this.spawnPlayerEntity(e,n)}resetPlayerControls(e,n){let r=this.options.stateSchema;if(this.inputCodec)for(let i of this.inputCodec.schema.controls){if(i.retain==="always")continue;let o=i.field.type,s=i.name;if(o==="vec2")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0);else if(o==="vec3")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0),w(r,e,n,"Player",`${s}_z`,0);else if(o==="quat")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0),w(r,e,n,"Player",`${s}_z`,0),w(r,e,n,"Player",`${s}_w`,1);else if(o.startsWith("flags"))w(r,e,n,"Player",s,0);else if(o.includes("[")){let a=o.match(/\\[(\\d+)\\]/);if(a?.[1]){let c=parseInt(a[1],10);for(let u=0;u<c;u++)w(r,e,n,"Player",s,0,u)}}else w(r,e,n,"Player",s,o==="bool"?!1:0)}}writeControlsToPlayer(e,n,r){let i=this.options.stateSchema,o=this.options.inputSchema;if(o)for(let s of o.controls){if(!r.hasControl(s.name))continue;let a=s.type,c=s.name;if(a==="vec2"){let[u,f]=r.getVec2(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f)}else if(a==="vec3"){let[u,f,p]=r.getVec3(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f),w(i,e,n,"Player",`${c}_z`,p)}else if(a==="quat"){let[u,f,p,g]=r.getQuat(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f),w(i,e,n,"Player",`${c}_z`,p),w(i,e,n,"Player",`${c}_w`,g)}else if(a.startsWith("flags")){let u=r.getControl(c);w(i,e,n,"Player",c,u)}else if(a.includes("[")){let u=r.getControl(c);for(let f=0;f<u.length;f++)w(i,e,n,"Player",c,u[f],f)}else{let u=r.getControl(c);w(i,e,n,"Player",c,u)}}}pushCommands(e,n,r){let i=this.options.stateSchema,o=r.getCommands();for(let s of o){let a=s.name.charAt(0).toUpperCase()+s.name.slice(1)+"Command",c={player_index:n};for(let[u,f]of Object.entries(s))u!=="name"&&(Array.isArray(f)?f.length===2?(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1]):f.length===3?(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1],c[`${u}_z`]=f[2]):f.length===4&&(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1],c[`${u}_z`]=f[2],c[`${u}_w`]=f[3]):c[u]=f);$r(i,e,a,c)}}clearCommandEvents(e){let n=this.options.stateSchema,r=this.options.inputSchema;if(!(!r||!n.events))for(let i of r.commands){let o=i.name.charAt(0).toUpperCase()+i.name.slice(1)+"Command";n.eventByName?.has(o)&&Pr(n,e,o)}}decodePayloadsToState(e,n){if(this.inputCodec)for(let r=0;r<n.length;r++){let i=n[r];if(i===void 0)continue;let o=this.findOrSpawnPlayerEntity(e,r);if(this.resetPlayerControls(e,o),i.length===0)continue;let s=this.inputCodec.decode(i);this.writeControlsToPlayer(e,o,s),this.pushCommands(e,r,s)}}transition(e,n){let r=this.stateSize;if(r===null||e.length!==r)throw new Error(`State size mismatch: expected ${this.stateSize}, got ${e.length}`);if(this.plugins.length===0||n.length===0)return e.slice();let i=this.memory;if(!i)throw new Error("WASM memory not initialized");let o=this.statePtr;if(o===null||o<0)throw new Error("State pointer not initialized");let s=new Uint8Array(i.buffer);s.set(e,o);for(let a of n){this.resetArena();let c=new Uint8Array(i.buffer,o,r);wr(c,a.tick),this.clearCommandEvents(c),this.decodePayloadsToState(c,a.payloads);for(let u of this.plugins)u.exports.apply(o),s=new Uint8Array(i.buffer)}return s.slice(o,o+r)}close(){}getStateSize(){let e=this.stateSize;if(e===null||e<0)throw new Error("State size not initialized");return e}};var me=class{constructor(e=1e3,n=1024){y(this,"buffer");y(this,"windowMs");y(this,"head",0);y(this,"tail",0);y(this,"size",0);this.windowMs=e,this.buffer=new Float64Array(n)}inc(){let e=performance.now();this.buffer[this.head]=e,this.head=(this.head+1)%this.buffer.length,this.size<this.buffer.length?this.size++:this.tail=(this.tail+1)%this.buffer.length}count(e=performance.now()){let n=e-this.windowMs;for(;this.size>0&&!(this.buffer[this.tail]>=n);)this.tail=(this.tail+1)%this.buffer.length,this.size--;return this.size}rate(e=performance.now()){return this.count(e)*(1e3/this.windowMs)}};function so(t){return("moduleBytes"in t||"plugins"in t)&&"stateSchema"in t}function ao(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var ct=class{constructor(e){y(this,"debug");y(this,"stateSchema");y(this,"inputs",null);y(this,"cache");y(this,"executor",null);y(this,"genesisStateId");y(this,"options");y(this,"ticking",!1);y(this,"tickGraceMs");y(this,"tickLag");y(this,"maxBatchSize");y(this,"currentState");y(this,"currentTick");y(this,"currentNodeId");y(this,"prevOnStateUpdateState",null);y(this,"onStateUpdate");y(this,"syncCheckpoint");y(this,"stateHistory",[]);y(this,"maxHistory",64);y(this,"stats");y(this,"loop",()=>{this._loop().catch(co)});y(this,"_loop",async()=>{if(this.ticking)try{let e=await this.tick();if(this.onStateUpdate&&this.currentState!==this.prevOnStateUpdateState&&(this.onStateUpdate(this.currentState),this.prevOnStateUpdateState=this.currentState,this.stats.updates.inc()),e.rolledBack&&this.stats.rollbacks.inc(),e.ticksComputed>0)for(let n=0;n<e.ticksComputed;n++)this.stats.executions.inc()}catch(e){console.error("Error in tick loop:",e)}finally{setTimeout(this.loop,this.tickGraceMs)}});e.log&&(this.inputs=e.log),this.debug=e.debug??!1,this.options=e,this.stateSchema=e.stateSchema,this.cache=e.cache??new st,this.genesisStateId=$t(e.genesisHash),this.tickGraceMs=e.tickGraceMs??10,this.tickLag=e.tickLag??1,this.maxBatchSize=e.maxBatchSize??200,this.stats={rollbacks:new me,executions:new me,updates:new me},this.currentState=Er(this.stateSchema,e.genesisHash,e.tickRate),this.currentNodeId=null,this.syncCheckpoint=null,this.currentTick=null,this.cache.store(this.currentState)}setLog(e){this.inputs=lt(e)}setOnStateUpdate(e){e===null&&(this.prevOnStateUpdateState=null),this.onStateUpdate=e}async init(){if(!this.inputs)throw new Error("Rollback.init() called before log was configured. Call setLog() first or pass log in options.");let e=this.options.executor;if(so(e)){let r=new at(e);await r.init(),this.executor=r}else this.executor=e;if((await this.tick(0)).ticksComputed===0||this.currentTick===null)throw new Error("Failed to record genesis snapshot");return this.options.disableTicking||(this.ticking=!0,this.loop()),this.getState()}async tick(e){if(!this.inputs)throw new Error("Rollback.tick() called before log was configured. Call setLog() and init() first.");let n=await this.inputs.getTicksAfter(this.currentNodeId,{limit:this.maxBatchSize,lag:this.tickLag});if(e&&(n=n.filter(s=>s.tick<=e)),n.length===0)return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:!1,ticksComputed:0};let r=!1;this.currentTick!==null&&n[0].tick<this.currentTick&&(r=!0,this.rollbackTo(n[0]));let i=n.filter(s=>this.currentTick===null||s.tick>this.currentTick);if(i.length===0)return this.currentNodeId=n[n.length-1].id,{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId,rolledBack:r,ticksComputed:0};let o=this.processTicks(i);return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:r,ticksComputed:o}}async getStats(){return{rollbacks:this.stats.rollbacks.rate(),executions:this.stats.executions.rate(),updates:this.stats.updates.rate()}}processTicks(e){if(!this.executor)throw new Error("Executor not initialized");let n=0,r=0;for(let a=0;a<e.length;a++){let c=e[a],u=Qe(c.payloads),f=this.cache.getCached(this.currentState,c.tick,u);if(f)this.currentState=f,this.currentTick=c.tick,this.currentNodeId=c.id,r=a+1,c.sync&&this.updateSyncCheckpoint(c);else break}let i=e.slice(r);if(i.length===0)return 0;let o=ao(i,a=>a.sync);if(o>=0){let a=i.slice(0,o+1),c=this.executor.transition(this.currentState,a),u=this.computeBatchStateId(this.currentState,a);Pt(c,u);let f=a[a.length-1];this.currentState=c,this.currentTick=f.tick,this.currentNodeId=f.id,n+=a.length,this.cache.store(c),this.recordStateSnapshot(this.currentTick,this.currentNodeId,u),this.updateSyncCheckpoint(f)}let s=o>=0?i.slice(o+1):i;if(s.length>0){let a=this.executor.transition(this.currentState,s),c=this.computeBatchStateId(this.currentState,s);Pt(a,c);let u=s[s.length-1];this.currentState=a,this.currentTick=u.tick,this.currentNodeId=u.id,n+=s.length,this.cache.store(a),this.recordStateSnapshot(this.currentTick,this.currentNodeId,c)}return n}computeBatchStateId(e,n){let r=pe(e);for(let i of n)r=Sr(r,i.tick,i.payloads);return r}getState(){return this.currentState.slice()}getTick(){return this.currentTick}reset(){this.currentTick=0,this.currentNodeId=null,this.syncCheckpoint=null}close(){this.ticking=!1,this.setOnStateUpdate(null),this.executor&&(this.executor.close(),this.executor=null)}rollbackTo(e){if(this.syncCheckpoint&&this.syncCheckpoint.tick>=e.tick){this.currentState=this.syncCheckpoint.state.slice(),this.currentTick=this.syncCheckpoint.tick,this.currentNodeId=this.syncCheckpoint.nodeId;return}if(this.syncCheckpoint&&this.syncCheckpoint.tick<e.tick){this.currentState=this.syncCheckpoint.state.slice(),this.currentTick=this.syncCheckpoint.tick,this.currentNodeId=this.syncCheckpoint.nodeId;return}let n=e.tick-1,r=this.findSnapshotAtOrBefore(n);if(r){let o=this.cache.getByStateId(r.stateId);if(o){this.currentState=o,this.currentTick=r.tick,this.currentNodeId=r.nodeId;return}}let i=this.cache.getByStateId(this.genesisStateId);if(i){this.currentState=i,this.currentTick=0,this.currentNodeId=null;return}}updateSyncCheckpoint(e){this.syncCheckpoint={state:this.currentState.slice(),tick:e.tick,nodeId:e.id}}recordStateSnapshot(e,n,r){this.stateHistory.push({tick:e,nodeId:n,stateId:r.slice()}),this.stateHistory.length>this.maxHistory&&this.stateHistory.shift()}findSnapshotAtOrBefore(e){for(let n=this.stateHistory.length-1;n>=0;n--){let r=this.stateHistory[n];if(r.tick<=e)return r}return null}};function co(t){console.warn("rollback unexpected:",t)}Be(ct);var qa=null;globalThis.onerror=t=>(console.error("\\u{1F534} FATAL ROLLBACK WORKER ERROR (Uncaught Exception):",t),!0);export{qa as default};\n/*! Bundled license information:\n\ncomlink/dist/esm/comlink.mjs:\n (**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n *)\n\n@noble/secp256k1/index.js:\n (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)\n\n@noble/hashes/esm/utils.js:\n (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)\n*/\n';
|
|
4716
|
-
function Worker2() {
|
|
4717
|
-
const blob = new Blob([workerCode2], { type: "text/javascript" });
|
|
4718
|
-
const url = URL.createObjectURL(blob);
|
|
4719
|
-
const worker = new globalThis.Worker(url, { type: "module" });
|
|
4720
|
-
URL.revokeObjectURL(url);
|
|
4721
|
-
return worker;
|
|
4722
|
-
}
|
|
4723
|
-
|
|
4724
6010
|
// src/peer-mesh.ts
|
|
4725
6011
|
var ICE_SERVERS = [
|
|
4726
6012
|
{ urls: "stun:stun.l.google.com:19302" },
|
|
@@ -4825,7 +6111,7 @@ var PeerMesh = class {
|
|
|
4825
6111
|
try {
|
|
4826
6112
|
const data = JSON.parse(event.data);
|
|
4827
6113
|
console.log("[PeerMesh]", `SSE: received offer from ${data.from.slice(0, 8)}`);
|
|
4828
|
-
this.handleOffer(data.from, { sdp: data.sdp, type: data.type }).catch(
|
|
6114
|
+
this.handleOffer(data.from, { sdp: data.sdp, type: data.type }).catch(warnUnexpected2);
|
|
4829
6115
|
} catch (err2) {
|
|
4830
6116
|
console.log("[PeerMesh]", "SSE: failed to handle offer", err2);
|
|
4831
6117
|
}
|
|
@@ -4834,7 +6120,7 @@ var PeerMesh = class {
|
|
|
4834
6120
|
try {
|
|
4835
6121
|
const data = JSON.parse(event.data);
|
|
4836
6122
|
console.log("[PeerMesh]", `SSE: received answer from ${data.from.slice(0, 8)}`);
|
|
4837
|
-
this.handleAnswer(data.from, { sdp: data.sdp, type: data.type }).catch(
|
|
6123
|
+
this.handleAnswer(data.from, { sdp: data.sdp, type: data.type }).catch(warnUnexpected2);
|
|
4838
6124
|
} catch (err2) {
|
|
4839
6125
|
console.log("[PeerMesh]", "SSE: failed to handle answer", err2);
|
|
4840
6126
|
}
|
|
@@ -4870,7 +6156,7 @@ var PeerMesh = class {
|
|
|
4870
6156
|
}
|
|
4871
6157
|
if (this.myPubKeyHex < peerPubKey) {
|
|
4872
6158
|
console.log("[PeerMesh]", `I should offer to ${peerPubKey.slice(0, 8)}`);
|
|
4873
|
-
this.createOffer(peerPubKey).catch(
|
|
6159
|
+
this.createOffer(peerPubKey).catch(warnUnexpected2);
|
|
4874
6160
|
}
|
|
4875
6161
|
}
|
|
4876
6162
|
}
|
|
@@ -5096,7 +6382,7 @@ var PeerMesh = class {
|
|
|
5096
6382
|
});
|
|
5097
6383
|
}
|
|
5098
6384
|
};
|
|
5099
|
-
function
|
|
6385
|
+
function warnUnexpected2(err2) {
|
|
5100
6386
|
console.warn("PeerMesh:", err2);
|
|
5101
6387
|
}
|
|
5102
6388
|
|
|
@@ -5109,10 +6395,8 @@ var Session = class {
|
|
|
5109
6395
|
initialized = false;
|
|
5110
6396
|
playerKey;
|
|
5111
6397
|
compiledStateSchema;
|
|
5112
|
-
channelWorkerUrl = null;
|
|
5113
6398
|
rollbackWorkerUrl = null;
|
|
5114
6399
|
rollbackWorker = null;
|
|
5115
|
-
channelWorker = null;
|
|
5116
6400
|
maxTicksPerBatch;
|
|
5117
6401
|
serverCertHash;
|
|
5118
6402
|
validatorKeys;
|
|
@@ -5175,12 +6459,12 @@ var Session = class {
|
|
|
5175
6459
|
async init() {
|
|
5176
6460
|
if (this.initializing || this.initialized) return;
|
|
5177
6461
|
this.initializing = true;
|
|
5178
|
-
const
|
|
5179
|
-
const channelPort1 =
|
|
5180
|
-
const channelPort2 =
|
|
6462
|
+
const messageChannel = new MessageChannel();
|
|
6463
|
+
const channelPort1 = messageChannel.port1;
|
|
6464
|
+
const channelPort2 = messageChannel.port2;
|
|
5181
6465
|
const connectionURL2 = this.config.toConnectionURL();
|
|
5182
6466
|
const genesisHash = this.config.toGenesisHash();
|
|
5183
|
-
this.channel =
|
|
6467
|
+
this.channel = new Channel({
|
|
5184
6468
|
connectionURL: connectionURL2,
|
|
5185
6469
|
serverCertHash: this.serverCertHash,
|
|
5186
6470
|
privateKey: this.playerKey,
|
|
@@ -5190,8 +6474,8 @@ var Session = class {
|
|
|
5190
6474
|
connectionTimeoutMs: this.connectionTimeoutMs,
|
|
5191
6475
|
logSyncTicks: this.logSyncTicks
|
|
5192
6476
|
});
|
|
5193
|
-
await this.channel.expose(
|
|
5194
|
-
await this.channel.setOnParticipantJoined(
|
|
6477
|
+
await this.channel.expose(channelPort1);
|
|
6478
|
+
await this.channel.setOnParticipantJoined(this.onParticipantJoined);
|
|
5195
6479
|
this.rollback = await this.createRollbackWorker({
|
|
5196
6480
|
stateSchema: this.compiledStateSchema,
|
|
5197
6481
|
genesisHash,
|
|
@@ -5217,10 +6501,10 @@ var Session = class {
|
|
|
5217
6501
|
publicKey,
|
|
5218
6502
|
genesisHash,
|
|
5219
6503
|
onPeerInput: (input, signerPubKey) => {
|
|
5220
|
-
this.channel?.addOptimisticInput(input, signerPubKey).catch(
|
|
6504
|
+
this.channel?.addOptimisticInput(input, signerPubKey).catch(warnUnexpected3);
|
|
5221
6505
|
}
|
|
5222
6506
|
});
|
|
5223
|
-
this.peerMesh.start().catch(
|
|
6507
|
+
this.peerMesh.start().catch(warnUnexpected3);
|
|
5224
6508
|
}
|
|
5225
6509
|
this.initialized = true;
|
|
5226
6510
|
this.initializing = false;
|
|
@@ -5313,22 +6597,10 @@ var Session = class {
|
|
|
5313
6597
|
await this.rollback.close();
|
|
5314
6598
|
this.rollback = null;
|
|
5315
6599
|
}
|
|
5316
|
-
if (this.channelWorker) {
|
|
5317
|
-
this.channelWorker.terminate();
|
|
5318
|
-
this.channelWorker = null;
|
|
5319
|
-
}
|
|
5320
6600
|
if (this.rollbackWorker) {
|
|
5321
6601
|
this.rollbackWorker.terminate();
|
|
5322
6602
|
this.rollbackWorker = null;
|
|
5323
6603
|
}
|
|
5324
|
-
if (this.channelWorkerUrl) {
|
|
5325
|
-
try {
|
|
5326
|
-
URL.revokeObjectURL(this.channelWorkerUrl);
|
|
5327
|
-
} catch {
|
|
5328
|
-
console.warn("failed to revoke channel worker url", this.channelWorkerUrl);
|
|
5329
|
-
}
|
|
5330
|
-
this.channelWorkerUrl = null;
|
|
5331
|
-
}
|
|
5332
6604
|
if (this.rollbackWorkerUrl) {
|
|
5333
6605
|
try {
|
|
5334
6606
|
URL.revokeObjectURL(this.rollbackWorkerUrl);
|
|
@@ -5340,12 +6612,12 @@ var Session = class {
|
|
|
5340
6612
|
this.closed = true;
|
|
5341
6613
|
}
|
|
5342
6614
|
_collectStats = () => {
|
|
5343
|
-
this.collectStats().catch(
|
|
6615
|
+
this.collectStats().catch(warnUnexpected3);
|
|
5344
6616
|
};
|
|
5345
6617
|
collectStats = async () => {
|
|
5346
6618
|
this.statsTimer = null;
|
|
5347
6619
|
this.stats = {
|
|
5348
|
-
inputs: this.channel ?
|
|
6620
|
+
inputs: this.channel ? this.channel.getStats() : {},
|
|
5349
6621
|
simulation: this.rollback ? await this.rollback.getStats() : {},
|
|
5350
6622
|
renderer: this.renderer.getStats?.() ?? {}
|
|
5351
6623
|
};
|
|
@@ -5356,7 +6628,7 @@ var Session = class {
|
|
|
5356
6628
|
};
|
|
5357
6629
|
// create blob url for rollback worker bytes and load it into a worker
|
|
5358
6630
|
async createRollbackWorker(options) {
|
|
5359
|
-
this.rollbackWorker = new
|
|
6631
|
+
this.rollbackWorker = new Worker();
|
|
5360
6632
|
this.rollbackWorker.onerror = (event) => {
|
|
5361
6633
|
console.error("\u{1F534} FATAL ROLLBACK WORKER ERROR (Script/Init Failed):", event);
|
|
5362
6634
|
return true;
|
|
@@ -5364,16 +6636,6 @@ var Session = class {
|
|
|
5364
6636
|
const Klass = wrap(this.rollbackWorker);
|
|
5365
6637
|
return await new Klass(options);
|
|
5366
6638
|
}
|
|
5367
|
-
// create blob url for channel worker bytes and load it into a worker
|
|
5368
|
-
async createChannelWorker(options) {
|
|
5369
|
-
this.channelWorker = new Worker();
|
|
5370
|
-
this.channelWorker.onerror = (event) => {
|
|
5371
|
-
console.error("\u{1F534} FATAL CHANNEL WORKER ERROR (Script/Init Failed):", event);
|
|
5372
|
-
return true;
|
|
5373
|
-
};
|
|
5374
|
-
const Klass = wrap(this.channelWorker);
|
|
5375
|
-
return await new Klass(options);
|
|
5376
|
-
}
|
|
5377
6639
|
};
|
|
5378
6640
|
async function createSession(options) {
|
|
5379
6641
|
const session = new Session(options);
|
|
@@ -5390,7 +6652,7 @@ function concatPluginWasm(plugins) {
|
|
|
5390
6652
|
}
|
|
5391
6653
|
return result;
|
|
5392
6654
|
}
|
|
5393
|
-
function
|
|
6655
|
+
function warnUnexpected3(err2) {
|
|
5394
6656
|
console.warn("unexpected:", err2);
|
|
5395
6657
|
}
|
|
5396
6658
|
|