@solarpunkltd/swarm-chat-js 6.0.0 → 6.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.esm.js +56092 -0
  3. package/dist/index.js +85 -4
  4. package/dist/interfaces/chat.d.ts +2 -2
  5. package/dist/lib/history.d.ts +1 -1
  6. package/dist/lib/utils.d.ts +1 -1
  7. package/dist/swarm-chat-umd.js +85 -0
  8. package/dist/utils/bee.d.ts +1 -1
  9. package/dist/waku/Waku.d.ts +1 -1
  10. package/package.json +2 -2
  11. package/dist/index.js.map +0 -1
  12. package/dist/interfaces/chat.js +0 -2
  13. package/dist/interfaces/chat.js.map +0 -1
  14. package/dist/interfaces/index.js +0 -3
  15. package/dist/interfaces/index.js.map +0 -1
  16. package/dist/interfaces/message.js +0 -7
  17. package/dist/interfaces/message.js.map +0 -1
  18. package/dist/lib/constants.js +0 -11
  19. package/dist/lib/constants.js.map +0 -1
  20. package/dist/lib/core.js +0 -225
  21. package/dist/lib/core.js.map +0 -1
  22. package/dist/lib/history.js +0 -140
  23. package/dist/lib/history.js.map +0 -1
  24. package/dist/lib/utils.js +0 -205
  25. package/dist/lib/utils.js.map +0 -1
  26. package/dist/scripts/mine.js +0 -13
  27. package/dist/scripts/mine.js.map +0 -1
  28. package/dist/utils/bee.js +0 -64
  29. package/dist/utils/bee.js.map +0 -1
  30. package/dist/utils/common.js +0 -33
  31. package/dist/utils/common.js.map +0 -1
  32. package/dist/utils/error.js +0 -20
  33. package/dist/utils/error.js.map +0 -1
  34. package/dist/utils/eventEmitter.js +0 -32
  35. package/dist/utils/eventEmitter.js.map +0 -1
  36. package/dist/utils/logger.js +0 -31
  37. package/dist/utils/logger.js.map +0 -1
  38. package/dist/utils/validation.js +0 -187
  39. package/dist/utils/validation.js.map +0 -1
  40. package/dist/waku/ProtoMessage.js +0 -35
  41. package/dist/waku/ProtoMessage.js.map +0 -1
  42. package/dist/waku/Waku.js +0 -84
  43. package/dist/waku/Waku.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,4 +1,85 @@
1
- export { SwarmChat } from './lib/core';
2
- export { EVENTS } from './lib/constants';
3
- export { MessageType } from './interfaces';
4
- //# sourceMappingURL=index.js.map
1
+ "use strict";var am=Object.defineProperty;var Vd=y=>{throw TypeError(y)};var cm=(y,u,h)=>u in y?am(y,u,{enumerable:!0,configurable:!0,writable:!0,value:h}):y[u]=h;var Z=(y,u,h)=>cm(y,typeof u!="symbol"?u+"":u,h),Ul=(y,u,h)=>u.has(y)||Vd("Cannot "+h);var je=(y,u,h)=>(Ul(y,u,"read from private field"),h?h.call(y):u.get(y)),ur=(y,u,h)=>u.has(y)?Vd("Cannot add the same private member more than once"):u instanceof WeakSet?u.add(y):u.set(y,h),Ft=(y,u,h,b)=>(Ul(y,u,"write to private field"),b?b.call(y,h):u.set(y,h),h),$t=(y,u,h)=>(Ul(y,u,"access private method"),h);var Ls=(y,u,h,b)=>({set _(v){Ft(y,u,v,h)},get _(){return je(y,u,b)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const beeJs=require("@ethersphere/bee-js");function _mergeNamespaces(y,u){for(var h=0;h<u.length;h++){const b=u[h];if(typeof b!="string"&&!Array.isArray(b)){for(const v in b)if(v!=="default"&&!(v in y)){const w=Object.getOwnPropertyDescriptor(b,v);w&&Object.defineProperty(y,v,w.get?w:{enumerable:!0,get:()=>b[v]})}}}return Object.freeze(Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}))}const byteToHex$1=[];for(let y=0;y<256;++y)byteToHex$1.push((y+256).toString(16).slice(1));function unsafeStringify$1(y,u=0){return(byteToHex$1[y[u+0]]+byteToHex$1[y[u+1]]+byteToHex$1[y[u+2]]+byteToHex$1[y[u+3]]+"-"+byteToHex$1[y[u+4]]+byteToHex$1[y[u+5]]+"-"+byteToHex$1[y[u+6]]+byteToHex$1[y[u+7]]+"-"+byteToHex$1[y[u+8]]+byteToHex$1[y[u+9]]+"-"+byteToHex$1[y[u+10]]+byteToHex$1[y[u+11]]+byteToHex$1[y[u+12]]+byteToHex$1[y[u+13]]+byteToHex$1[y[u+14]]+byteToHex$1[y[u+15]]).toLowerCase()}let getRandomValues$1;const rnds8$1=new Uint8Array(16);function rng$1(){if(!getRandomValues$1){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");getRandomValues$1=crypto.getRandomValues.bind(crypto)}return getRandomValues$1(rnds8$1)}const randomUUID$1=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),native$1={randomUUID:randomUUID$1};function v4$1(y,u,h){if(native$1.randomUUID&&!u&&!y)return native$1.randomUUID();y=y||{};const b=y.random||(y.rng||rng$1)();return b[6]=b[6]&15|64,b[8]=b[8]&63|128,unsafeStringify$1(b)}var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs$1(y){return y&&y.__esModule&&Object.prototype.hasOwnProperty.call(y,"default")?y.default:y}var cafeUtility={};(function(y){var u;Object.defineProperty(y,"__esModule",{value:!0}),y.Vector=y.Cache=y.Assertions=y.Strings=y.Types=y.Objects=y.Dates=y.Promises=y.Numbers=y.System=y.Arrays=y.Random=y.Elliptic=y.Binary=y.AsyncQueue=y.PubSubChannel=y.FixedPointNumber=y.MerkleTree=y.Chunk=y.Uint8ArrayWriter=y.Uint8ArrayReader=y.AsyncLazy=y.Lazy=y.Optional=void 0;async function h(A){return new Promise((P,L)=>A.then(L,P))}async function b(A){return h(Promise.all(A.map(h)))}async function v(A,P=1){const L=Yc(A,P),Y=[],pe=L.map(async Ce=>{for(const ze of Ce)Y.push(await ze())});return await Promise.all(pe),Y}async function w(A){return new Promise(P=>setTimeout(()=>{P(!0)},A))}function _(A,P=Math.random){for(let L=A.length-1;L>0;L--){const Y=Math.floor(P()*(L+1)),pe=A[L];A[L]=A[Y],A[Y]=pe}return A}function E(A){if(A.length===1)return A[0];throw Error(`Expected exactly one element, actual: ${A.length}`)}function S(A){return A.length===1?A[0]:null}function x(A){return A.length>0?A[0]:null}function T(A){if(!A.length)throw Error("Received empty array");return A[0]}function C(A,P){const L=[];for(let Y=0;Y<A;Y++)L.push(P(Y));return L}function O(A){const P=[];for(let L=0;L<A[0].length;L++){P.push([]);for(let Y=0;Y<A.length;Y++)P[L].push(A[Y][L])}return P}function D(A,P,L){const Y=[];for(let pe=0;pe<A;pe++){Y.push([]);for(let Ce=0;Ce<P;Ce++)Y[pe].push(L)}return Y}function U(A,P,L,Y){if(L<0||Y<0||Y+P[0].length>A[0].length||L+P.length>A.length)return!1;for(let pe=0;pe<P.length;pe++)for(let Ce=0;Ce<P[pe].length;Ce++)if(P[pe][Ce]!==void 0&&A[L+pe][Y+Ce]!==P[pe][Ce])return!1;return!0}function te(A,P,L=Math.random){return _(pi(0,A.length-1),L).slice(0,P)}function X(A,P){return A.map(L=>L[P])}function ie(A){let P=A,L=3405648695,Y=3735928559;return function(){return P+=L,L^=P<<7,P*=Y,Y^=P<<13,P^=L^Y,(P>>>0)/4294967296}}function ee(A,P,L=Math.random){return Math.floor(L()*(P-A+1))+A}function ae(A,P,L=Math.random){return L()*(P-A)+A}function de(){return Math.random()*2-1}function Se(A,P,L){return P>=A.x&&P<A.x+A.width&&L>=A.y&&L<A.y+A.height}function ve(A,P,L,Y=Math.random){let pe,Ce;do pe=ee(0,A-1,Y),Ce=ee(0,P-1,Y);while(L&&Se(L,pe,Ce));return[pe,Ce]}function Pe(A,P=Math.random){const L=Math.floor(A),Y=A-L;return Ie(Y,P)?L+1:L}function Ie(A,P=Math.random){return P()<A}function Ee(A,P=Math.random){return A[Math.floor(A.length*P())]}function De(A,P,L=Math.random){if(P>A.length)throw new Error(`Count (${P}) is greater than array length (${A.length})`);return te(A,P,L).map(Y=>A[Y])}function be(A,P,L,Y=Math.random){if(P>A.length)throw new Error(`Count (${P}) is greater than array length (${A.length})`);const pe=[];for(;pe.length<P;){const Ce=Ee(A,Y);pe.some(ze=>L(ze,Ce))||pe.push(Ce)}return pe}function B(A,P,L,Y,pe,Ce=Math.random){const ze=A.filter(Xe=>Xe!==P&&Xe!==L),Je=[];for(P!==null&&Je.push(P);ze.length&&Je.length<Y;){const Xe=y.Random.intBetween(0,ze.length-1,Ce);pe(ze[Xe],Je)&&Je.push(ze[Xe]),ze.splice(Xe,1)}return _(Je,Ce),{values:Je,indexOfGuaranteed:P!==null?Je.indexOf(P):-1}}function F(A){if(!A.length)throw Error("Received empty array");return A[A.length-1]}function M(A,P,L){return L(P.reduce((Y,pe)=>pe(Y),A))}function N(A,P){return L=>M(L,A,P)}function Q(A,P,L){if(L===void 0&&(L=Math.random()),A.length!==P.length)throw new Error("Array length mismatch");let Y=P.reduce((Ce,ze)=>Ce+ze,0);const pe=L*Y;for(let Ce=0;Ce<A.length-1;Ce++)if(Y-=P[Ce],pe>=Y)return A[Ce];return F(A)}function j(A,P,L=Math.random){const Y=P.map(Ce=>L()*Ce),pe=[];for(let Ce=0;Ce<A.length;Ce++)pe.push([A[Ce],Y[Ce]]);return pe.sort((Ce,ze)=>ze[1]-Ce[1]).map(Ce=>Ce[0])}function ne(A,P){if(A==null)return null;const L=P.split(".");let Y=A;for(const pe of L){if(Y[pe]===null||Y[pe]===void 0)return null;Y=Y[pe]}return Y}function J(A,P,L){const Y=P.split(/\.|\[/);let pe=A;for(let Ce=0;Ce<Y.length;Ce++){const ze=Y[Ce],Je=Ce<Y.length-1&&Y[Ce+1].includes("]"),Xe=ze.includes("]")?ze.replace(/\[|\]/g,""):ze;if(Ce===Y.length-1)return pe[Xe]=L,L;qe(pe[Xe])||(Je?pe[Xe]=[]:pe[Xe]={}),pe=pe[Xe]}return L}function q(A,P,L=1){const Y=ne(A,P)||0;return J(A,P,Y+L),Y}function re(A,P,L){return ne(A,P)||J(A,P,L)}function H(A,P){const L=jo(P,"."),Y=_c(P,".");if(!L||!Y)return;const pe=ne(A,L);delete pe[Y]}function he(A,P,L){const Y=ne(A,P);if(!Y)throw new Error("Key '"+P+"' does not exist.");return J(A,P,L),Y}function Oe(A,P,L){for(const Y of P){const pe=ne(A,Y);if(pe)return pe}if(L){const Y=Object.values(A);if(Y.length)return Y[0]}return null}async function Ne(A,P,L){for(;;){try{await A()}catch(Y){L&&L("Error in forever",Y)}await w(P)}}function Ae(A,P){A();const L=setInterval(()=>{A()},P);return()=>clearInterval(L)}function le(A){return A/1024/1024}function me(A){return A>=1024*1024*1024*1024?(A/1024/1024/1024/1024).toFixed(3)+" TB":A>=1024*1024*1024?(A/1024/1024/1024).toFixed(3)+" GB":A>=1024*1024?(A/1024/1024).toFixed(3)+" MB":A>=1024?(A/1024).toFixed(3)+" KB":A+" B"}function Me(A){const P=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(A.toLowerCase());if(!P)throw new Error("Invalid hex color: "+A);return[parseInt(P[1],16),parseInt(P[2],16),parseInt(P[3],16)]}function fe(A){return"#"+A.map(P=>P.toString(16).padStart(2,"0")).join("")}function ge(A,P,L,Y){const pe=A*Math.PI/180,Ce=L*Math.PI/180,ze=(L-A)*Math.PI/180,Je=(Y-P)*Math.PI/180,Xe=Math.sin(ze/2)*Math.sin(ze/2)+Math.cos(pe)*Math.cos(Ce)*Math.sin(Je/2)*Math.sin(Je/2);return 6371e3*(2*Math.atan2(Math.sqrt(Xe),Math.sqrt(1-Xe)))}function ce(A,P){return Math.round(A/P)*P}function _e(A){return A>1e3?(A/1e3).toFixed(0)+" km":A>=500?ce(A,100)+" m":A>=100?ce(A,50)+" m":ce(A,10)+" m"}function Re(A){return A*(A+1)/2}function Ue(A){const P=A.match(/-?\d+(\.\d+)?/);if(!P)throw Error("No float found in "+A);return parseFloat(P[0])}function qe(A,P=!0){return!A||P&&!nt(A._readableState)||P&&A.constructor&&(A.constructor.isBuffer||A.constructor.name=="Uint8Array"||A.constructor.name==="ArrayBuffer"||A.constructor.name==="ReadableStream")?!1:typeof A=="object"}function Ze(A){return qe(A)&&!Array.isArray(A)}function tt(A){return Array.isArray(A)&&A.length===0}function Fe(A){return Ze(A)&&Object.keys(A).length===0}function nt(A){return A===void 0}function it(A){return Object.prototype.toString.call(A)==="[object Function]"||Object.prototype.toString.call(A)==="[object AsyncFunction]"}function at(A){return Object.prototype.toString.call(A)==="[object String]"}function ct(A){return typeof A=="number"&&isFinite(A)}function ht(A){return A===!0||A===!1}function xt(A){return Object.prototype.toString.call(A)==="[object Date]"}function Ot(A){return!at(A)||A.trim().length===0}function dt(A){return ct(A)&&Number.isInteger(A)&&A>=1}function Rt(A){return at(A)&&A.match(/^-?\d+$/)!==null}function Nt(A){return at(A)&&A.match(/^(0x)?[0-9a-f]+$/i)!==null}const yt="!@#$%^&*()_+-=[]{}|;:<>?,./",zt="!@#$%^&*()_+-=[]{}|;:<>?,./".split(""),Vt="abcdefghijklmnopqrstuvwxyz",vt="ABCDEFGHIJKLMNOPQRSTUVWXYZ",Ut="1234567890",Lt=Vt+vt+Ut,wt=Lt+yt,Wt=["—","\\","東","京","都","𝖆","𝖇","𝖈","👾","🙇","💁","🙅","ᚠ","ᛇ","ᚻ","ᛦ"],Gt="0123456789abcdef";function At(A,P=Math.random){let L="";for(let Y=0;Y<A;Y++)L+=Vt[Math.floor(P()*Vt.length)];return L}function tr(A,P=Math.random){let L="";for(let Y=0;Y<A;Y++)L+=Lt[Math.floor(P()*Lt.length)];return L}function Xt(A,P=Math.random){let L="";for(let Y=0;Y<A;Y++)L+=wt[Math.floor(P()*wt.length)];return L}function bt(A,P=Math.random){let L="";for(let Y=0;Y<A;Y++)L+=Wt[Math.floor(P()*Wt.length)];return L}function Bt(A,P){const L=new RegExp(`[0-9a-f]{${P}}`,"i"),Y=A.match(L);return Y?Y[0]:null}function Yt(A,P,L=zt){const Y=gr(A,L);for(const pe of Y)if(P(pe))return pe;return null}function Tt(A,P=Math.random){let L="";for(let Y=0;Y<A;Y++)L+=Gt[Math.floor(P()*Gt.length)];return L}function qt(A,P){if(!Rt(A))throw new TypeError(`Expected integer string${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);const L=BigInt(A);if(P&&(P.min&&L<P.min||P.max&&L>P.max))throw RangeError(`Expected integer string${P!=null&&P.name?` for ${P.name}`:""} in range: ${P.min??"-inf"}..${P.max??"inf"}; got: `+L);return A}function Jt(A,P){if(Ot(A))throw new TypeError(`Expected string${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);if(P&&(P.min!==void 0&&A.length<P.min||P.max!==void 0&&A.length>P.max))throw RangeError(`Expected string${P!=null&&P.name?` for ${P.name}`:""} length in range: ${P.min??"-inf"}..${P.max??"inf"}; got: ${A.length}`);return A}function we(A,P){if(!Nt(A))throw new TypeError(`Expected hex string${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);const L=A.replace(/^0x/,"");if(P&&P.byteLength&&L.length!==P.byteLength*2)throw RangeError(`Expected hex string${P!=null&&P.name?` for ${P.name}`:""} of byte length ${P.byteLength}; got: `+L);return L}function se(A,P){if(!Jt(A,P).split("").every(L=>L==="_"||gi(L)))throw new TypeError(`Expected safe string${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return A}function ue(A,P){if(P.min!==void 0&&A<P.min||P.max!==void 0&&A>P.max)throw RangeError(`Expected value${P!=null&&P.name?` for ${P.name}`:""} in range: ${P.min??"-inf"}..${P.max??"inf"}; got: ${A}`)}function xe(A,P){if(!it(A))throw new TypeError(`Expected function${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return A}function ke(A,P){if(ct(A))return P&&ue(A,P),A;if(!at(A)||!A.match(/^-?\d+(\.\d+)?$/))throw new TypeError(`Expected number${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);const L=parseFloat(A);return P&&ue(L,P),L}function Ke(A,P){return ke(A,P)|0}function We(A,P){if(A==="true")return!0;if(A==="false")return!1;if(!ht(A))throw new TypeError(`Expected boolean${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return A}function ut(A,P){if(!xt(A))throw new TypeError(`Expected date${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return A}function _t(A){return Ot(A)?null:A}function st(A,P){if(!at(A))throw new TypeError(`Expected string${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return A}function Et(A,P){if(dt(A))return A;const L=parseInt(A,10);if(!dt(L))throw new TypeError(`Expected id${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return L}function gt(A,P){if(!at(A))throw new TypeError(`Expected time${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);const L=A.split(":");if(L.length!==2)throw new TypeError(`Expected time${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);const Y=parseInt(L[0],10),pe=parseInt(L[1],10);if(!ct(Y)||!ct(pe)||Y<0||Y>23||pe<0||pe>59)throw new TypeError(`Expected time, got${P!=null&&P.name?` for ${P.name}`:""}: `+A);return`${String(Y).padStart(2,"0")}:${String(pe).padStart(2,"0")}`}function It(A,P){if(!Array.isArray(A))throw new TypeError(`Expected array${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return A}function Qt(A,P){if(!Ze(A))throw new TypeError(`Expected object${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return A}function rr(A,P){return A===null?null:Qt(A,P)}function ar(A,P){const L=Qt(A,P);for(const Y of Object.keys(L))if(!at(L[Y]))throw new TypeError(`Expected string map${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return L}function Gr(A,P){const L=Qt(A),Y=Object.keys(L),pe=Object.values(L);if(!Y.every(at)||!pe.every(ct))throw new TypeError(`Expected numeric dictionary${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return L}function Hr(A){return at(A)&&A.match(/^https?:\/\/.+/)!==null}function jr(A,P){if(!Hr(A))throw new TypeError(`Expected url${P!=null&&P.name?` for ${P.name}`:""}, got: `+A);return A}function Xr(A,P){return P==null?!0:A(P)}function Yr(A,P){return P==null?null:A(P)}function Br(A,P){return P==null?void 0:A(P)}function Kr(A,P){for(const[L,Y]of Object.entries(P))if(!Y(A[L]))throw TypeError(`${L} in value does not exist or match shape`);for(const L of Object.keys(A))if(!P[L])throw TypeError(`${L} exists in value but not in shape`);return!0}function kr(A,P){return A.every(L=>Kr(L,P))}function Mr(A,P="json",L=0){if(qe(A,!1)){if(L>1)return"[object Object]";if(P==="json"){if(Array.isArray(A)){const pe=A.map(Ce=>Mr(Ce,"json",L+1));return L===0?JSON.stringify(pe):pe}const Y={};A.message&&(Y.message=Mr(A.message,"json",L+1));for(const[pe,Ce]of Object.entries(A))Y[pe]=Mr(Ce,"json",L+1);return L===0?JSON.stringify(Y):Y}else if(P==="key-value"){const Y=Object.keys(A);return A.message&&!Y.includes("message")&&Y.unshift("message"),Y.map(pe=>`${pe}=${JSON.stringify(Mr(A[pe],"json",L+1))}`).join(" ")}}return nt(A)&&(A="undefined"),L===0?JSON.stringify(A):A}function Jr(A,P){if(at(A))return A;const L=Object.keys(A);A.message&&!L.includes("message")&&L.push("message");const Y=L.map(pe=>`${pe}: ${A[pe]}`).join("; ");return P&&A.stack?Y+`
2
+ `+A.stack:Y}function Vr(A,P){if(Ze(A)&&Ze(P))for(const L in P)Ze(P[L])?(A[L]||(A[L]={}),Vr(A[L],P[L])):Array.isArray(P[L])?A[L]=[...P[L]]:(P[L]!==null&&P[L]!==void 0||A[L]===null||A[L]===void 0)&&(A[L]=P[L]);return A}function Tn(A,P){const L={};return Vr(L,A),Vr(L,P),L}function In(A,P,L){const Y={};return Vr(Y,A),Vr(Y,P),Vr(Y,L),Y}function pn(A,P){const L={};for(const Y of A)for(const pe of Object.keys(Y))L[pe]?L[pe]=P(L[pe],Y[pe]):L[pe]=Y[pe];return L}function Fn(A){return pn(A,(P,L)=>P+L)}function Un(A,P,L){A[P]||(A[P]=[]),A[P].push(L)}function qn(A,P,L){for(A.unshift(P);A.length>L;)A.pop()}function Qi(A,P){let L=P%A.length;return L<0&&(L+=A.length),A[L]}function Hn(A,P){Array.prototype.push.apply(A,P)}function cc(A,P){Array.prototype.unshift.apply(A,P)}async function uc(A,P){const L=[];for(const Y of A)L.push(await P(Y));return L}function Ko(A,P){const L=[];for(let Y=0;Y<A.length;Y++)L.push(A[Y]),Y<A.length-1&&(it(P)?L.push(P()):L.push(P));return L}function zu(A,P){if(A!==P)throw Error(`Expected [${A}] to equal [${P}]`);return[A,P]}function fc(A){if(A!==!0)throw Error(`Expected [true], got: [${A}]`);return A}function qs(A){if(!A)throw Error(`Expected truthy value, got: [${A}]`);return A}function lc(A){if(A!==!1)throw Error(`Expected [false], got: [${A}]`);return A}function Wu(A){if(A)throw Error(`Expected falsy value, got: [${A}]`);return A}function dc(A,P){if(!P.includes(A))throw Error(`Expected any of [${P.join(", ")}], got: [${A}]`);return A}function hc(A,P){for(let L=0;L<A.length;L++){const Y=A[L],pe=P[L],Ce=Math.max(0,pe.getTime()-Date.now());setTimeout(Y,Ce)}}function Vo(A,P,L){return A+(P-A)*L}function Gu(A){return A.reduce((P,L)=>P+L,0)}function pc(A){return A.reduce((P,L)=>P+L,0)/A.length}function Zo(A){const P=[...A].sort((Y,pe)=>Y-pe),L=Math.floor(P.length/2);return P.length%2===0?(P[L]+P[L-1])/2:P[L]}function zo(A,P){return A-(P-1)/2}function pi(A,P){const L=[];for(let Y=A;Y<=P;Y++)L.push(Y);return L}function gc(A,P){return P.some(L=>A.includes(L))}function mc(A){return/^[\u4E00-\u9FA5]+$/.test(A)}function Wo(A,P=()=>!1){return A.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").split("").map(L=>/[a-z0-9]/.test(L)||P(L)?L:"-").join("").replace(/-+/g,"-").replace(/^-|-$/g,"")}function yc(A){return Wo(A).replaceAll("-","")}function bc(A){return xr(A.replace(/([A-Z])/g," $1"))}function vc(A){return A.split("-").map(xr).join(" ")}function wc(A){return Ks(A.split("-").map(xr).join(""))}function ju(A,P=", ",L=" and "){return!A||!A.length?"":A.length===1?A[0]:A.length===2?`${A[0]}${L}${A[1]}`:`${A.slice(0,A.length-1).join(P)}${L}${A[A.length-1]}`}function Xu(A,P){return P+A.split("").join(P)+P}function Yu(A){return Wo(A).replace(/-/g,"_").toUpperCase()}function es(A,P){if(P.length===0)return 0;const L=A.toLowerCase(),Y=P.toLowerCase();return A===P?1e4:L.startsWith(Y)?1e4-A.length:L.includes(Y)?5e3-A.length:new RegExp(".*"+Y.split("").join(".*")+".*").test(L)?1e3-A.length:0}function Ju(A,P){return A.filter(L=>es(L,P)).sort((L,Y)=>es(Y,P)-es(L,P))}function Qu(A){return A.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}const ef={"&amp;":"&","&quot;":'"',"&apos;":"'","&gt;":">","&lt;":"<"};function tf(A){let P=A.replace(/&#(\d+);/g,(L,Y)=>String.fromCharCode(Y)).replace(/&#x(\d+);/g,(L,Y)=>String.fromCharCode(parseInt(Y,16)));for(const[L,Y]of Object.entries(ef))P=P.replaceAll(L,Y);return P}function Hs(A,P){const L=A.indexOf(P);return L===-1?null:A.slice(0,L)}function Go(A,P){const L=A.indexOf(P);return L===-1?null:A.slice(L+P.length)}function jo(A,P){const L=A.lastIndexOf(P);return L===-1?null:A.slice(0,L)}function _c(A,P){const L=A.lastIndexOf(P);return L===-1?null:A.slice(L+P.length)}function rf(A,P,L){const Y=jo(A,L);return Y?Go(Y,P):null}function nf(A,P,L){const Y=Go(A,P);return Y?Hs(Y,L):null}function pr(A,P,L=!1){const Y=L?A.lastIndexOf(P):A.indexOf(P);return Y===-1?L?[null,A]:[A,null]:[A.slice(0,Y),A.slice(Y+P.length)]}function gr(A,P){let L=[A];for(const Y of P)L=L.flatMap(pe=>pe.split(Y));return L.filter(Y=>Y)}function Xo(A){const P=F(A.split(/\\|\//g)),L=P.lastIndexOf(".",P.length-1);return L<=0?"":P.slice(L+1)}function Yo(A){const P=F(A.split(/\\|\//g)),L=P.lastIndexOf(".",P.length-1);return L<=0?P:P.slice(0,L)}function sf(A){let[P,L]=A.split("@");P=ts(P.replaceAll(".","").toLowerCase()).replaceAll(" ","");const[Y]=P.split("+");if(!Y||!L||L.indexOf(".")===-1||L.indexOf(".")===L.length-1)throw new Error("Invalid email");return L=ts(L.toLowerCase()).replaceAll(" ",""),`${Y}@${L}`}function of(A){const P=Yo(A),L=Xo(A);return L?`${P}.${L}`:P}function af(A){const P=Yo(A),L=Xo(A);return{basename:P,extension:L,filename:L?`${P}.${L}`:P}}function cf(A,P=Math.random){return A.replace(/\{(.+?)\}/g,(L,Y)=>Ee(Y.split("|"),P))}function Jo(A){const P=/\{(.+?)\}/,L=A.match(P);if(!L||!L.index)return[A];const Y=L[1].split(","),pe=A.slice(0,L.index),Ce=A.slice(L.index+L[0].length);let ze=[];for(const Je of Y){const Xe=Jo(pe+Je+Ce);ze=ze.concat(Xe)}return ze}function ts(A){return A.split(`
3
+ `).map(P=>P.trim().replace(/\s+/g," ")).filter(P=>P.length>0).join(`
4
+ `)}function xr(A){return A.charAt(0).toUpperCase()+A.slice(1)}function Ks(A){return A.charAt(0).toLowerCase()+A.slice(1)}function Qn(A){if(!A)return!1;const P=A.charCodeAt(0);return P>=65&&P<=90||P>=97&&P<=122}function Qo(A){if(!A)return!1;const P=A.charCodeAt(0);return P>=48&&P<=57}function gi(A){return Qn(A)||Qo(A)}const sn=`
5
+ \r.,?!:;"'\`(){}[]~@#$%^&*-+=|<>/\\`.split("");function Ec(A){return sn.includes(A)}function Sc(A){return gi(A)||A==="."||A==="["||A==="]"||A==="_"}function $c(A,P,L,Y,pe){return A.slice(0,P)+Y+A.slice(P,P+L)+pe+A.slice(P+L)}function ea(A,P,L=0){const Y=P.exec(A.slice(L));return Y?{index:Y.index,match:Y[0]}:null}function ta(A,P,L=!0){if(!L)return P.every(pe=>pe instanceof RegExp?pe.test(A):A.indexOf(pe,0)!==-1);let Y=0;for(const pe of P)if(pe instanceof RegExp){const Ce=ea(A,pe,Y);if(!Ce)return!1;Y=Ce.index+Ce.match.length}else{const Ce=A.indexOf(pe,Y);if(Ce===-1)return!1;Y=Ce+pe.length}return!0}function xc(A,P,L=!0){let Y=0;for(const pe of P){let Ce=!1;for(;!Ce&&Y<A.length;)ta(A[Y],pe,L)&&(Ce=!0),Y++;if(!Ce)return!1}return!0}function Qr(A){return A.match(/"|,/)?`"${A.replace(/"/g,'""')}"`:A}function Oi(A,P,L=0){let Y=-1;for(const pe of P){const Ce=A.indexOf(pe,L);Ce!==-1&&(Y===-1||Ce<Y)&&(Y=Ce)}return Y}function on(A,P=0){for(let L=P;L<A.length;L++)if(Ec(A[L]))return L;return-1}function uf(A,P=0){for(let L=P;L<A.length;L++)if(A[L]==="#"&&gi(A[L+1]))return L;return-1}function ra(A,P,L=0){return A.slice(0,L).lastIndexOf(P)}function Kn(A,P=0,L="{",Y="}"){let pe=1;for(let Ce=P;Ce<A.length;Ce++)if(A.slice(Ce,Ce+Y.length)===Y){if(--pe===0)return Ce}else A.slice(Ce,Ce+L.length)===L&&pe++;return-1}function rs(A,P){const L=P.wordBoundary?Oi(A,[`${P.opening} `,`${P.opening}
6
+ `],P.start||0):A.indexOf(P.opening,P.start||0);if(L===-1)return null;const Y=Kn(A,L+P.opening.length,P.opening,P.closing);return Y===-1?null:P.exclusive?A.slice(L+P.opening.length,Y):A.slice(L,Y+P.closing.length)}function na(A,P){const L=[];let Y=P.wordBoundary?Oi(A,[`${P.opening} `,`${P.opening}
7
+ `],P.start||0):A.indexOf(P.opening,P.start||0);for(;;){if(Y===-1)return L;const pe=rs(A,{...P,start:Y});if(!pe)return L;L.push(pe),Y=P.wordBoundary?Oi(A,[`${P.opening} `,`${P.opening}
8
+ `],Y+pe.length):A.indexOf(P.opening,Y+pe.length)}}function wr(A,P,L){let Y=0;for(;;){const pe=y.Strings.extractBlock(A,{...L,start:Y});if(!pe)return A;const Ce=P(pe);Y=A.indexOf(pe,Y)+Ce.length,A=A.replace(pe,Ce)}}function ei(A,P){const L=[];let Y=0;for(;Y<A.length;){const pe=A.indexOf(P,Y);if(pe===-1){L.push({string:A.slice(Y),symbol:null});break}const Ce=A.indexOf(P,pe+P.length);if(pe>Y&&Ce!==-1&&L.push({string:A.slice(Y,pe),symbol:null}),Ce===-1){L.push({string:A.slice(Y),symbol:null});break}L.push({string:A.slice(pe+P.length,Ce),symbol:P}),Y=Ce+P.length}return L}function ia(A){const P=[];let L=0;for(;L<A.length;){const Y=uf(A,L);if(Y===-1){P.push({string:A.slice(L),symbol:null});break}const pe=on(A,Y+1);if(pe===-1){P.push({string:A.slice(L,Y),symbol:null}),P.push({string:A.slice(Y+1),symbol:"#"});break}Y>L&&P.push({string:A.slice(L,Y),symbol:null}),P.push({string:A.slice(Y+1,pe),symbol:"#"}),L=pe}return P}function ff(A){const P=[];let L=0;for(;L<A.length;){const Y=Oi(A,["http://","https://"],L);if(Y===-1){P.push({string:A.slice(L),symbol:null});break}const pe=Oi(A,[" ",`
9
+ `],Y);if(pe===-1){Y>L&&P.push({string:A.slice(L,Y),symbol:null}),P.push({string:A.slice(Y),symbol:"http"});break}Y>L&&P.push({string:A.slice(L,Y),symbol:null}),P.push({string:A.slice(Y,pe),symbol:"http"}),L=pe}return P}const Vs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ac="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function lf(A){return mi(A,Vs)}function df(A){return Ic(A,Vs)}function Tc(A){return mi(A,Ac)}function Zs(A){return Ic(A,Ac)}function mi(A,P){const L="=",Y=P.length;let pe=0,Ce=0;const ze=[];for(let Je=0;Je<A.length;Je++){const Xe=A[Je];if(Xe===L)break;const pt=P.indexOf(Xe);if(pt===-1)throw new Error(`Invalid character: ${Xe}`);Ce=Ce<<Math.log2(Y)|pt,pe+=Math.log2(Y),pe>=8&&(pe-=8,ze.push(Ce>>pe&255))}return new Uint8Array(ze)}function Ic(A,P){const L=P.length;let Y=0,pe=0,Ce="";for(let ze=0;ze<A.length;ze++)for(pe=pe<<8|A[ze],Y+=8;Y>=Math.log2(L);)Y-=Math.log2(L),Ce+=P[pe>>Y&L-1];return Y>0&&(Ce+=P[pe<<Math.log2(L)-Y&L-1]),Ce.length%4!==0&&(Ce+="=".repeat(4-Ce.length%4)),Ce}function Cc(A){A.startsWith("0x")&&(A=A.slice(2));const P=A.length/2,L=new Uint8Array(P);for(let Y=0;Y<P;Y++){const pe=parseInt(A.slice(Y*2,Y*2+2),16);L[Y]=pe}return L}function Pc(A){return Array.from(A).map(P=>P.toString(16).padStart(2,"0")).join("")}function sa(A,P){const L=A.split("/").filter(Ce=>Ce),Y=P.split("/").filter(Ce=>Ce);if(L.length!==Y.length)return null;const pe={};for(let Ce=0;Ce<L.length;Ce++){const ze=L[Ce];if(ze.startsWith(":"))pe[ze.slice(1)]=Y[Ce];else if(ze!==Y[Ce])return null}return pe}function ns(A,P,L){const Y=[];for(const pe of L)pe!==P&&Y.push(A.replace(P,pe));return Y}function Rc(A,P,L,Y=Math.random){const pe=y.Arrays.shuffle(P.map(ze=>({variants:y.Arrays.shuffle(ze.variants.map(Je=>Je),Y),avoid:ze.avoid})),Y),Ce=[];for(const ze of pe){const Je=ze.variants.filter(pt=>pt!==ze.avoid),Xe=Je.find(pt=>A.includes(pt));if(Xe&&(Hn(Ce,ns(A,Xe,Je)),Ce.length>=L))break}if(Ce.length<L)for(const ze of pe){const Je=ze.variants.find(Xe=>A.includes(Xe));if(Je&&(Hn(Ce,ns(A,Je,ze.variants)),Ce.length>=L))break}return Ce.slice(0,L)}function hf(A,P,L,Y=!1){const pe=new RegExp(Y?`(?<=\\s|^)${P}(?=\\s|$)`:`\\b${P}\\b`,"g");return A.replace(pe,L)}function oa(A,P){const L=/\b[A-Z][a-zA-Z0-9]*\b/g;return A.replace(L,Y=>Y.toUpperCase()===Y?Y:P(Y))}function aa(A){return A.replace(/<[^>]*>/g,"")}function Mc(A){const P=A.lastIndexOf(" ");if(P===-1)return{line:A,rest:""};const L=A.slice(0,P),Y=A.slice(P+1);return{line:L,rest:Y}}function Oc(A,P={}){return[...A].reduce((L,Y)=>L+(P[Y]||1),0)}function en(A,P,L={}){const Y=[];let pe="",Ce=0;for(let ze=0;ze<A.length;ze++){const Je=A[ze],Xe=L[Je]||1;if(pe+=Je,Ce+=Xe,Ce>P){const{line:pt,rest:lr}=Mc(pe);Y.push(pt),pe=lr,Ce=lr.split("").map(Sr=>L[Sr]||1).reduce((Sr,vn)=>Sr+vn,0)}}return pe&&Y.push(pe),Y}function ca(A,P){const L=[];for(let Y=0;Y<=A.length;Y++)L[Y]=[Y];for(let Y=0;Y<=P.length;Y++)L[0][Y]=Y;for(let Y=1;Y<=A.length;Y++)for(let pe=1;pe<=P.length;pe++){const Ce=A[Y-1]===P[pe-1]?0:1;L[Y][pe]=Math.min(L[Y-1][pe]+1,L[Y][pe-1]+1,L[Y-1][pe-1]+Ce)}return L[A.length][P.length]}function yi(A,P){return new RegExp(`\\b${P}\\b`).test(A)}function Dc(A,P,L){return L==="any"?P.some(Y=>yi(A,Y)):P.every(Y=>yi(A,Y))}function Bc(A){const P={},L=A.match(/([a-z\-]+)="([^"]+)"/g);if(L)for(const Y of L){const[pe,Ce]=pr(Y,"=");P[pe]=Ce.slice(1,Ce.length-1)}return P}function zs(A,P,L=[]){let Y="";for(;P<A.length&&(gi(A[P])||L.includes(A[P]));)Y+=A[P++];return Y}function pf(A,P,L="$",Y=":"){for(const pe in P)A=kc(A,pe,P[pe],L,Y);return A=Nc(A),A}function kc(A,P,L,Y="$",pe=":"){if(L==="")return A;let Ce=A.indexOf(`${Y}${P}`);for(;Ce!==-1;){if(A[Ce+P.length+1]===pe)if(A[Ce+P.length+2]===pe)A=A.replace(`${Y}${P}${pe}${pe}`,L);else{const ze=zs(A,Ce+P.length+2,["_"]);A=A.replace(`${Y}${P}${pe}${ze}`,L)}else A=A.replace(`${Y}${P}`,L);Ce=A.indexOf(`${Y}${P}`,Ce+L.length)}return A}function Nc(A,P="$",L=":"){let Y=A.indexOf(P);for(;Y!==-1;){const pe=zs(A,Y+1);if(A[Y+pe.length+1]===L)if(A[Y+pe.length+2]===L)A=A.replace(`${P}${pe}${L}${L}`,"");else{const Ce=zs(A,Y+pe.length+2);A=A.replace(`${P}${pe}${L}${Ce}`,Ce)}Y=A.indexOf(P,Y+1)}return A}function gf(A,P){let L=A.indexOf("](");for(;L!==-1;){const Y=ra(A,"[",L),pe=A.indexOf(")",L);if(Y!==-1&&pe!==-1){const[Ce,ze]=A.slice(Y+1,pe).split("]("),Je=P(Ce,ze);A=A.slice(0,Y)+Je+A.slice(pe+1)}L=A.indexOf("](",L+1)}return A}function bi(A,P=!0){const L=Object.entries(A).filter(([Y,pe])=>pe!=null).map(([Y,pe])=>`${Y}=${encodeURIComponent(pe)}`).join("&");return L?(P?"?":"")+L:""}function mf(A){const P={},L=A.split("&");for(const Y of L){const[pe,Ce]=Y.split("=");pe&&Ce&&(P[pe]=decodeURIComponent(Ce))}return P}function yf(A,P){return Object.prototype.hasOwnProperty.call(A,P)}function ua(A,P){let L=null,Y=-1/0;for(const[pe,Ce]of Object.entries(A)){const ze=P(Ce);ze>Y&&(Y=ze,L=pe)}return L?[L,A[L]]:null}function Lc(A,P,L,Y){const pe=A.find(ze=>ze[P]===L),Ce=A.find(ze=>ze[P]===L+Y);pe&&Ce?(pe[P]=L+Y,Ce[P]=L):pe&&(pe[P]=L+Y),A.sort((ze,Je)=>ke(ze[P])-ke(Je[P])),A.forEach((ze,Je)=>ze[P]=Je+1)}function ti(A){const P=Object.keys(A);if(P.length===1)return A[P[0]];throw new Error("Expected object to have a single key")}function Ws(A,P=":"){return Object.fromEntries(A.map(L=>pr(L,P)).map(L=>L[0]&&L[1]?[ts(L[0]),ts(L[1])]:null).filter(L=>L))}function bf(A,P,L){return ss(A,P)+bi(L||{})}function vf(A,P=",",L='"'){const Y=[];let pe="",Ce=!1;const ze=A.split("");for(const Je of ze)Je===P&&!Ce?(Y.push(pe),pe=""):Je===L&&(!pe&&!Ce||Ce)?Ce=!Ce:pe+=Je;return Y.push(pe),Y}function wf(A){return`[${Math.floor(A.progress*100)}%] ${Ye(A.deltaMs)} out of ${Ye(A.totalTimeMs)} (${Ye(A.remainingTimeMs)} left) [${Math.round(A.baseTimeMs)} ms each]`}async function Di(A,P,L){for(let Y=0;Y<L;Y++){try{if(await A())return!0}catch{}Y<L-1&&await w(P)}return!1}function gn(A,P){const L=[];for(let Y=A.length-1;Y>=0;Y--)P(A[Y])&&L.push(A.splice(Y,1)[0]);return L}function Fc(A){return JSON.parse(JSON.stringify(A))}function _f(A){return Math.ceil((A||Date.now())/1e3)}function Ef(A){return(A||new Date).toISOString().slice(0,10)}function Sf(A){return(A||new Date).toISOString().slice(0,19).replace(/T|:/g,"-")}function $f(A){const P=new Date(A);return new Date(P.getTime()-P.getTimezoneOffset()*6e4)}function xf(A){return new Date(A)}function Zr(A){return String(Math.floor(A)).padStart(2,"0")}function He(A){let[P,L]=A.split(":");ct(parseInt(P,10))||(P="0"),ct(parseInt(L,10))||(L="0");let Y=_i(Ke(P),0,23),pe=_i(Ke(L),0,59);return`${Zr(Y)}:${Zr(pe)}`}function Ye(A){const P=Math.floor(A/36e5);A=A%36e5;const L=Math.floor(A/6e4);A=A%6e4;const Y=Math.floor(A/1e3);return P?`${Zr(P)}:${Zr(L)}:${Zr(Y)}`:`${Zr(L)}:${Zr(Y)}`}function Ge(A){return Math.floor((xt(A)?A.getTime():A)/864e5)}const lt={today:(A,P)=>Zr(A)+":"+Zr(P),yesterday:()=>"Yesterday",monday:()=>"Mon",tuesday:()=>"Tue",wednesday:()=>"Wed",thursday:()=>"Thu",friday:()=>"Fri",saturday:()=>"Sat",sunday:()=>"Sun",weeks:A=>`${A}w`};function Mt(A,P){const L=new Date((P==null?void 0:P.now)||Date.now()),Y=(P==null?void 0:P.labels)||lt,pe=xt(A)?A:new Date(A);if(Ge(L)===Ge(pe))return Y.today(pe.getUTCHours(),pe.getUTCMinutes(),pe.getUTCHours()>12);if(Ge(L)-Ge(pe)===1)return Y.yesterday();const Ce=cr(pe);return Ge(L)-Ge(pe)<7?Y[Ce.day]():Y.weeks(Math.round((L.getTime()-pe.getTime())/6048e5))}const nr={now:()=>"A few seconds",seconds:A=>`${A} seconds`,minutes:A=>`${A} minutes`,hours:A=>`${A} hours`,days:A=>`${A} days`,weeks:A=>`${A} weeks`};function Ar(A,P){const L=(P==null?void 0:P.now)??Date.now(),Y=(P==null?void 0:P.labels)||nr,pe=y.Types.isDate(A)?A.getTime():A;let Ce=(L-pe)/1e3;return Ce<10?Y.now():Ce<120?Y.seconds(Math.floor(Ce)):(Ce/=60,Ce<120?Y.minutes(Math.floor(Ce)):(Ce/=60,Ce<48?Y.hours(Math.floor(Ce)):(Ce/=24,Ce<14?Y.days(Math.floor(Ce)):(Ce/=7,Y.weeks(Math.floor(Ce))))))}function yr(A,P=nr){return Ar(0,{now:A*1e3,labels:P})}function fa(A,P,L){const Y=((L==null?void 0:L.now)??Date.now())-A,pe=Math.floor(Y/P),Ce=P/((L==null?void 0:L.precision)??1)-Math.ceil(Y%P/((L==null?void 0:L.precision)??1));return{cycles:pe,remaining:Ce}}const la={};function an(A,P){return!la[A]||Date.now()>la[A]?(la[A]=Date.now()+P,!0):!1}const Gs={s:1e3,m:6e4,h:36e5,d:864e5};function Af(A,P,L){return P=xt(P)?P.getTime():P,L=L?xt(L)?L.getTime():L:Date.now(),(L-P)/Gs[A]}function Bi(A,P,L,Y){Y||(Y=Date.now());const pe=P/L,Ce=Y-A,ze=Ce/P,Je=ze*L,Xe=Je-Ce;return{deltaMs:Ce,progress:pe,baseTimeMs:ze,totalTimeMs:Je,remainingTimeMs:Xe}}const js={0:"sunday",1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday"};function is(A){return{zeroBasedIndex:A,day:js[A]}}function cr(A){return is(A.getDay())}function Tf(A){return cr(new Date(A))}function Uc(A){return A*1e3}function Xs(A){return A*6e4}function If(A){return A*36e5}function Cf(A){return A*864e5}const Pf={ms:1,milli:1,millis:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:6e4,min:6e4,minute:6e4,minutes:6e4,h:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,week:6048e5,weeks:6048e5,month:2592e6,months:2592e6,y:31536e6,year:31536e6,years:31536e6};function Ys(A){const P=parseFloat(A);if(isNaN(P))throw Error("makeDate got NaN for input");const L=A.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),Y=Pf[L];if(!Y)throw Error(`Unknown unit: "${L}"`);return P*Y}const ri={b:1,byte:1,bytes:1,kb:1024,kilobyte:1024,kilobytes:1024,mb:1024**2,megabyte:1024**2,megabytes:1024**2,gb:1024**3,gigabyte:1024**3,gigabytes:1024**3,tb:1024**4,terabyte:1024**4,terabytes:1024**4};function Js(A){const P=parseFloat(A);if(isNaN(P))throw Error("makeDate got NaN for input");const L=A.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),Y=ri[L];if(!Y)throw Error(`Unknown unit: "${L}"`);return P*Y}function qc(A){return A.replace(/ +/g," ").replace(/^ /gm,"")}const ki={};async function Hc(A,P,L){const Y=Date.now(),pe=ki[A];if(pe&&pe.validUntil>Y)return pe.value;const Ce=await L(),ze=Y+P;return ki[A]={value:Ce,validUntil:ze},Ce}function Kc(A){delete ki[A]}function ss(...A){return A.filter(P=>P).join("/").replace(new RegExp("(?<!:)\\/+","g"),"/")}function Vc(A,P,L,Y,pe=!0){const Ce=A.indexOf(P),ze=A.indexOf(L,Ce+P.length);if(Ce===-1||ze===-1)throw Error("Start or end not found");return pe?A.substring(0,Ce+P.length)+Y+A.substring(ze):A.substring(0,Ce)+Y+A.substring(ze+L.length)}function os(A){let P="p";A.startsWith("#")?(P="h1",A=A.slice(1).trim()):A.startsWith("-")&&(P="li",A=A.slice(1).trim());const L=A[0]===A[0].toUpperCase(),Y=/[.?!]$/.test(A),pe=/:$/.test(A);return{type:P,isCapitalized:L,hasPunctuation:Y,endsWithColon:pe}}function vi(A,P="(",L=")"){let Y=0,pe=0;for(;pe<A.length;)if(A.startsWith(P,pe)?(Y++,pe+=P.length):A.startsWith(L,pe)?(Y--,pe+=L.length):pe++,Y<0)return!1;return P===L?Y%2===0:Y===0}function Qs(A){A=A.normalize("NFD").replace(/[\u0300-\u036f]/g,"");let P=A.length;for(;A=A.replace(/(\w+)[\s,']+\w+/g,"$1"),A.length!==P;)P=A.length;return A=A.replaceAll(/[A-Z][a-zA-Z0-9]*/g,"A"),A=A.replaceAll(/[a-z][a-zA-Z0-9]*/g,"a"),A=A.replaceAll(/[\u4E00-\u9FA5]+/g,"Z"),A}function Zc(A){const P=Object.keys(A).sort((Y,pe)=>Y.localeCompare(pe)),L={};for(const Y of P)L[Y]=wi(A[Y]);return L}function zc(A){const P=[];return A.sort((L,Y)=>JSON.stringify(wi(L)).localeCompare(JSON.stringify(wi(Y)))).forEach(L=>P.push(wi(L))),P}function wi(A){return Array.isArray(A)?zc(A):qe(A)?Zc(A):A}function as(A,P){return JSON.stringify(wi(A))===JSON.stringify(wi(P))}function eo(...A){for(let P=1;P<A.length;P++)if(!as(A[P-1],A[P]))return!1;return!0}function da(A){try{return JSON.parse(A)}catch{return null}}function Rf(){let A=0;return{next:()=>A++}}function Wc(A){let P=0;return{next:()=>A[P++%A.length]}}function Mf(A){let P;return L=>{const Y=L===A&&P!==A;return P=L,Y}}function Of(A,P,L,Y,pe){const Ce={};for(const ze of Object.keys(P))Ce[ze]=[];Ce[Y]=[],pe&&(A=A.sort(pe));for(const ze of A){const Je=ze[L],Xe=P[Je]?Je:Y;Ce[Xe].length>=P[Xe]?Ce[Y].push(ze):Ce[Xe].push(ze)}return Ce}function Ir(A,P){const L=Object.keys(A),Y=Object.keys(P);return{uniqueToA:L.filter(pe=>!Y.includes(pe)),uniqueToB:Y.filter(pe=>!L.includes(pe))}}function Nr(A){const P=Object.keys(A);return P[Math.floor(Math.random()*P.length)]}function Df(A,P){const L=Nr(A);return A[L]=P(A[L]),L}function Bf(A){return A=A.replace(/\r\n/g,`
10
+ `),A=A.replace(/(\w+)\((.+)\)/g,(P,L,Y)=>`${L}(${Y.replaceAll(",","&comma;")})`),A=A.replace(/(,)(\s+})/g,"$2"),A=A.replace(/\.\.\..+?,/g,""),A=A.replace(/({\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),A=A.replace(/(,\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),A=A.replace(/:(.+)\?(.+):/g,(P,L,Y)=>`: (${L.trim()} && ${Y.trim()}) ||`),A=A.replace(/([a-zA-Z0-9]+)( ?: ?{)/g,'"$1"$2'),A=A.replace(/([a-zA-Z0-9]+) ?: ?(.+?)(,|\n|})/g,(P,L,Y,pe)=>`"${L}":"${Y.trim()}"${pe}`),A=A.replace(/("'|'")/g,'"'),A=A.replaceAll("&comma;",","),JSON.parse(A)}const Vn=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],kf=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],to=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function cs(A,P,L){let Y=A.length-P;if(Y<=0)return"0."+"0".repeat(-Y)+A+(L?" "+L:"");let pe=A.substring(0,Y),Ce=A.substring(Y);return pe===""&&(pe="0"),pe+"."+Ce+(L?" "+L:"")}function ha(A,P){const L=(P==null?void 0:P.longForm)??!1,Y=P!=null&&P.unit?` ${P.unit}`:"",pe=L?kf:to,Ce=(P==null?void 0:P.precision)??1;if(A<Vn[0])return`${A}${Y}`;for(let ze=0;ze<Vn.length-1;ze++)if(A<Vn[ze+1])return`${(A/Vn[ze]).toFixed(Ce)}${L?" ":""}${pe[ze]}${Y}`;return`${(A/Vn[Vn.length-1]).toFixed(Ce)}${L?" ":""}${pe[Vn.length-1]}${Y}`}function ni(A){const P=parseFloat(A);if(isNaN(P))throw Error("makeNumber got NaN for input");const L=A.replace(/^-?[0-9.]+/,"").trim(),Y=to.findIndex(pe=>pe.toLowerCase()===L.toLowerCase());return Y===-1?P:P*Vn[Y]}function _i(A,P,L){return A<P?P:A>L?L:A}function us(A,P,L){const Y=A+P;return Y>L?L:Y}function ro(A,P,L){const Y=A-P;return Y<L?L:Y}function Ni(A,P){return P(A),A}function Nf(A,P){A&&P(A)}function Lf(A,P){const L=Object.keys(P);for(const Y of L)Array.isArray(P[Y])&&Array.isArray(A[Y])&&Hn(A[Y],P[Y])}function Ff(A){return A.splice(0,A.length),A}function Uf(A){for(const P of Object.keys(A))(tt(A[P])||Array.isArray(A[P])&&A[P].every(L=>L==null))&&delete A[P];return A}function qf(A){for(const P of Object.entries(A))(P[1]===null||P[1]===void 0||at(P[1])&&Ot(P[1]))&&delete A[P[0]];return A}function no(A,P){const L={};for(const[Y,pe]of Object.entries(A))P(Y)&&(L[Y]=pe);return L}function ls(A,P){const L={};for(const[Y,pe]of Object.entries(A))P(pe)&&(L[Y]=pe);return L}function Gc(A,P){const L={};for(const Y of Object.entries(A))L[Y[0]]=P(Y[1]);return L}function $e(A,P){const L=[];let Y=0;for(const pe of A)L.push(P(pe,Y++));return L}async function Li(A,P){try{return await A()}catch{throw P}}function io(A,P,L){L!=null&&(A[P]=L)}function cn(A,P,L,Y){const pe=ne(L,Y);pe!=null&&J(A,P,pe)}function Zt(A){const P={};for(const[L,Y]of Object.entries(A))P[Y]=L;return P}function Hf(A){const P=Object.keys(A),L=P.map(Je=>A[Je].length),Y=L.reduce((Je,Xe)=>Je*=Xe);let pe=1;const Ce=[1];for(let Je=0;Je<L.length-1;Je++)pe*=L[Je],Ce.push(pe);const ze=[];for(let Je=0;Je<Y;Je++){const Xe={};for(let pt=0;pt<P.length;pt++){const lr=A[P[pt]],Sr=Math.floor(Je/Ce[pt])%lr.length;Xe[P[pt]]=lr[Sr]}ze.push(Xe)}return ze}function Kf(A){return Object.values(A).filter(P=>P).length}function Vf(A,P,L){return A+(L?"["+P+"]":(A.length?".":"")+P)}function Cn(A,P,L,Y,pe){if(!qe(P))return P;for(const[Ce,ze]of Object.entries(P)){const Je=Vf(L,Ce,Y);Array.isArray(ze)?pe?Cn(A,ze,Je,!0,pe):A[Je]=ze.map(Xe=>Cn(Array.isArray(Xe)?[]:{},Xe,"",!1,pe)):qe(ze)?Cn(A,ze,Je,!1,pe):A[Je]=ze}return A}function Zf(A,P=!1,L){return Cn({},A,L||"",!1,P)}function jc(A){if(!qe(A))return A;const P=Array.isArray(A)?[]:{};for(const[L,Y]of Object.entries(A))Array.isArray(Y)?J(P,L,Y.map(pe=>jc(pe))):J(P,L,Y);return P}function zf(A,P,L){return P[A]?P[A]:L}function Xc(A,P){const L={};for(const Y of A){const pe=P(Y);L[pe]=Y}return L}function Wf(A,P){const L={};for(const Y of A){const pe=P(Y);L[pe]||(L[pe]=[]),L[pe].push(Y)}return L}function Zn(A,P){const L=[];for(let Y=0;Y<A.length;Y+=P)L.push(A.slice(Y,Y+P));return L}function Yc(A,P){const L=Math.ceil(A.length/P),Y=[];for(let pe=0;pe<A.length;pe+=L)Y.push(A.slice(pe,pe+L));return Y}function Jc(A,P){const L=[],Y=Math.ceil(A.length/P);for(let pe=0;pe<Y;pe++)L.push(A.slice(pe*P,pe*P+P));return L}function Gf(A,P){const L=Math.ceil(A.length/P);return Jc(A,L)}function jf(A,P){return Object.values(Xc(A,P))}function Xf(A,P,L,Y,pe){const Ce=P?A.map(P):A,ze={};for(const Xe of Ce)ze[Xe]=(ze[Xe]||0)+1;const Je=Y?Pn(ze,pe?(Xe,pt)=>Xe[1]-pt[1]:(Xe,pt)=>pt[1]-Xe[1]):ze;return L?Object.keys(Je):Je}function Pn(A,P){return Object.fromEntries(Object.entries(A).sort(P))}function Yf(A){const P=[],L=Object.keys(A),Y=A[L[0]].length;for(let pe=0;pe<Y;pe++){const Ce={};for(const ze of L)Ce[ze]=A[ze][pe];P.push(Ce)}return P}function Jf(A,P,L=1){for(const Y of A)Y[P]+=L}function Qf(A,P,L){for(const Y of A)Y[P]=L}function pa(A,P){const L=[];let Y=[];return A.forEach((pe,Ce)=>{(Ce===0||!P(pe,A[Ce-1]))&&(Y=[],L.push(Y)),Y.push(pe)}),L}function el(){return{map:new Map,keys:[]}}function Ei(){return{map:new Map,keys:[]}}function Qc(A,P,L,Y=100){if(A.map.has(P)){const pe=A.keys.indexOf(P);A.keys.splice(pe,1)}if(A.map.set(P,L),A.keys.push(P),A.keys.length>Y){const pe=A.keys.shift();pe&&A.map.delete(pe)}}function tl(A,P,L,Y=100){if(A.map.has(P)){const pe=A.keys.indexOf(P);A.keys.splice(pe,1)}if(A.map.set(P,L),A.keys.unshift(P),A.keys.length>Y){const pe=A.keys.shift();pe&&A.map.delete(pe)}}function mn(A,P,L,Y,pe=100){Qc(A,P,{validUntil:Date.now()+Y,data:L},pe)}function rl(A,P){const L=A.map.get(P);return L&&L.validUntil>Date.now()?L.data:null}class ii{constructor(P){this.value=P}static of(P){return new ii(P)}static empty(){return new ii(null)}map(P){return new ii(this.value!==null&&this.value!==void 0?P(this.value):null)}mapAsync(P){return this.value!==null&&this.value!==void 0?P(this.value).then(L=>ii.of(L)):Promise.resolve(ii.empty())}ifPresent(P){return this.value!==null&&this.value!==void 0&&P(this.value),this}ifPresentAsync(P){return this.value!==null&&this.value!==void 0?P(this.value).then(()=>this):Promise.resolve(this)}ifAbsent(P){return(this.value===null||this.value===void 0)&&P(),this}ifAbsentAsync(P){return this.value===null||this.value===void 0?P().then(()=>this):Promise.resolve(this)}getOrFallback(P){return this.value??P()}getOrFallbackAsync(P){return this.value!==null&&this.value!==void 0?Promise.resolve(this.value):P()}getOrThrow(){if(this.value===null||this.value===void 0)throw Error("Optional.value is empty");return this.value}}y.Optional=ii;class nl{constructor(P){this.supplier=P,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}}y.Lazy=nl;class il{constructor(P){this.supplier=P,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}}y.AsyncLazy=il;function ol(A){return()=>A.forEach(P=>P())}function eu(A,P){return A.reduce((L,Y)=>P(L)>P(Y)?L:Y)}function tu(A,P){const L=A.find(Y=>Y instanceof P);return ii.of(L)}function al(A,P){return A.filter(L=>L instanceof P)}function cl(A,P){const L=[],Y=Math.max(A.length,P.length);for(let pe=0;pe<Y;pe++)A[pe]&&L.push(A[pe]),P[pe]&&L.push(P[pe]);return L}function ga(A,P){return A.includes(P)?A.filter(L=>L!==P):[...A,P]}class ds{constructor(P){this.value=P,this.children=[]}}function so(A,P,L,Y,pe=!1){const Ce=new Map,ze=[];A.forEach(Xe=>{const pt=new ds(Xe);Ce.set(Xe[P],pt)}),A.forEach(Xe=>{const pt=Ce.get(Xe[P]);if(!pt)return;const lr=Xe[L];if(lr){const Sr=Ce.get(lr);Sr&&Sr.children.push(pt)}else ze.push(pt)});const Je=Xe=>{Xe.children.sort((pt,lr)=>{const Sr=pt.value[Y],vn=lr.value[Y];return pe?vn-Sr:Sr-vn}),Xe.children.forEach(Je)};return ze.forEach(Je),ze}function ru(A,P){if(Math.log2(A.length)%1!==0)throw new Error("Array length must be a power of 2");let L=[...A];for(;L.length>1;){const Y=[];for(let pe=0;pe<L.length;pe+=2){const Ce=L[pe+1];Y.push(P(L[pe],Ce))}L=Y}return L[0]}function Si(...A){const P=A.reduce((pe,Ce)=>pe+Ce.length,0),L=new Uint8Array(P);let Y=0;return A.forEach(pe=>{L.set(pe,Y),Y+=pe.length}),L}function nu(A){return A[0]===137&&A[1]===80&&A[2]===78&&A[3]===71}function Rn(A){return A[0]===255&&A[1]===216}function oo(A){return A[8]===87&&A[9]===69&&A[10]===66&&A[11]===80}function $i(A){return nu(A)||Rn(A)||oo(A)}function un(A){return new Uint8Array([A])}function ul(A){return A[0]}function iu(A,P){const L=new ArrayBuffer(2);return new DataView(L).setUint16(0,A,P==="LE"),new Uint8Array(L)}function su(A,P){return new DataView(A.buffer).getUint16(A.byteOffset,P==="LE")}function hs(A,P){const L=new ArrayBuffer(4);return new DataView(L).setUint32(0,A,P==="LE"),new Uint8Array(L)}function si(A,P){return new DataView(A.buffer).getUint32(A.byteOffset,P==="LE")}function ao(A,P){const L=new ArrayBuffer(8);return new DataView(L).setBigUint64(0,BigInt(A),P==="LE"),new Uint8Array(L)}function fl(A,P){return new DataView(A.buffer).getBigUint64(A.byteOffset,P==="LE")}function zn(A,P){const L=new Uint8Array(32);let Y=A;if(P==="LE"){for(let pe=0;pe<32;pe++)L[pe]=Number(Y&0xffn),Y>>=8n;return L}for(let pe=31;pe>=0;pe--)L[pe]=Number(Y&0xffn),Y>>=8n;return L}function Fi(A,P){let L=0n;if(P==="LE"){for(let Y=31;Y>=0;Y--)L=L<<8n|BigInt(A[Y]);return L}for(let Y=0;Y<32;Y++)L=L<<8n|BigInt(A[Y]);return L}function ou(A,P){const L=[];let Y=0;for(const pe of P)L.push(A.subarray(Y,Y+pe)),Y+=pe;return L}function Cr(A,P){const L=[];for(let Y=0;Y<A.length;Y+=P)L.push(A.subarray(Y,Y+P));return L}const co=[0,1,0,32898,2147483648,32906,2147483648,2147516416,0,32907,0,2147483649,2147483648,2147516545,2147483648,32777,0,138,0,136,0,2147516425,0,2147483658,0,2147516555,2147483648,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,0,32778,2147483648,2147483658,2147483648,2147516545,2147483648,32896,0,2147483649,2147483648,2147516424];function au(A){for(let P=0;P<24;P++){const L=A[0]^A[10]^A[20]^A[30]^A[40],Y=A[1]^A[11]^A[21]^A[31]^A[41],pe=A[2]^A[12]^A[22]^A[32]^A[42],Ce=A[3]^A[13]^A[23]^A[33]^A[43],ze=A[4]^A[14]^A[24]^A[34]^A[44],Je=A[5]^A[15]^A[25]^A[35]^A[45],Xe=A[6]^A[16]^A[26]^A[36]^A[46],pt=A[7]^A[17]^A[27]^A[37]^A[47],lr=A[8]^A[18]^A[28]^A[38]^A[48],Sr=A[9]^A[19]^A[29]^A[39]^A[49],vn=pe<<1|Ce>>>31,vu=Ce<<1|pe>>>31,Hi=lr^vn,xs=Sr^vu,wu=ze<<1|Je>>>31,Ki=Je<<1|ze>>>31,Gn=L^wu,As=Y^Ki,_u=Xe<<1|pt>>>31,Eu=pt<<1|Xe>>>31,ui=pe^_u,Vi=Ce^Eu,yo=lr<<1|Sr>>>31,Ma=Sr<<1|lr>>>31,fi=ze^yo,Ts=Je^Ma,Su=L<<1|Y>>>31,bo=Y<<1|L>>>31,Zi=Xe^Su,Ai=pt^bo;A[0]^=Hi,A[1]^=xs,A[2]^=Gn,A[3]^=As,A[4]^=ui,A[5]^=Vi,A[6]^=fi,A[7]^=Ts,A[8]^=Zi,A[9]^=Ai,A[10]^=Hi,A[11]^=xs,A[12]^=Gn,A[13]^=As,A[14]^=ui,A[15]^=Vi,A[16]^=fi,A[17]^=Ts,A[18]^=Zi,A[19]^=Ai,A[20]^=Hi,A[21]^=xs,A[22]^=Gn,A[23]^=As,A[24]^=ui,A[25]^=Vi,A[26]^=fi,A[27]^=Ts,A[28]^=Zi,A[29]^=Ai,A[30]^=Hi,A[31]^=xs,A[32]^=Gn,A[33]^=As,A[34]^=ui,A[35]^=Vi,A[36]^=fi,A[37]^=Ts,A[38]^=Zi,A[39]^=Ai,A[40]^=Hi,A[41]^=xs,A[42]^=Gn,A[43]^=As,A[44]^=ui,A[45]^=Vi,A[46]^=fi,A[47]^=Ts,A[48]^=Zi,A[49]^=Ai;const Oa=A[0],vo=A[1],wn=A[2]<<1|A[3]>>>31,wo=A[3]<<1|A[2]>>>31,_o=A[5]<<30|A[4]>>>2,Da=A[4]<<30|A[5]>>>2,Eo=A[6]<<28|A[7]>>>4,Ba=A[7]<<28|A[6]>>>4,ka=A[8]<<27|A[9]>>>5,_n=A[9]<<27|A[8]>>>5,Is=A[11]<<4|A[10]>>>28,Cs=A[10]<<4|A[11]>>>28,Ps=A[13]<<12|A[12]>>>20,zi=A[12]<<12|A[13]>>>20,li=A[14]<<6|A[15]>>>26,St=A[15]<<6|A[14]>>>26,Wi=A[17]<<23|A[16]>>>9,Rs=A[16]<<23|A[17]>>>9,jn=A[18]<<20|A[19]>>>12,Na=A[19]<<20|A[18]>>>12,Ms=A[20]<<3|A[21]>>>29,So=A[21]<<3|A[20]>>>29,Dr=A[22]<<10|A[23]>>>22,La=A[23]<<10|A[22]>>>22,Fa=A[25]<<11|A[24]>>>21,$o=A[24]<<11|A[25]>>>21,Ua=A[26]<<25|A[27]>>>7,xo=A[27]<<25|A[26]>>>7,qa=A[29]<<7|A[28]>>>25,Ha=A[28]<<7|A[29]>>>25,Ka=A[31]<<9|A[30]>>>23,En=A[30]<<9|A[31]>>>23,Fr=A[33]<<13|A[32]>>>19,Os=A[32]<<13|A[33]>>>19,Va=A[34]<<15|A[35]>>>17,Ds=A[35]<<15|A[34]>>>17,Za=A[36]<<21|A[37]>>>11,za=A[37]<<21|A[36]>>>11,Ti=A[38]<<8|A[39]>>>24,Ao=A[39]<<8|A[38]>>>24,To=A[40]<<18|A[41]>>>14,Wa=A[41]<<18|A[40]>>>14,Ga=A[42]<<2|A[43]>>>30,ja=A[43]<<2|A[42]>>>30,Xa=A[45]<<29|A[44]>>>3,Io=A[44]<<29|A[45]>>>3,Co=A[47]<<24|A[46]>>>8,Ya=A[46]<<24|A[47]>>>8,Bs=A[48]<<14|A[49]>>>18,Po=A[49]<<14|A[48]>>>18;A[0]=Oa^~Ps&Fa,A[1]=vo^~zi&$o,A[2]=Ps^~Fa&Za,A[3]=zi^~$o&za,A[4]=Fa^~Za&Bs,A[5]=$o^~za&Po,A[6]=Za^~Bs&Oa,A[7]=za^~Po&vo,A[8]=Bs^~Oa&Ps,A[9]=Po^~vo&zi,A[10]=Eo^~jn&Ms,A[11]=Ba^~Na&So,A[12]=jn^~Ms&Fr,A[13]=Na^~So&Os,A[14]=Ms^~Fr&Xa,A[15]=So^~Os&Io,A[16]=Fr^~Xa&Eo,A[17]=Os^~Io&Ba,A[18]=Xa^~Eo&jn,A[19]=Io^~Ba&Na,A[20]=wn^~li&Ua,A[21]=wo^~St&xo,A[22]=li^~Ua&Ti,A[23]=St^~xo&Ao,A[24]=Ua^~Ti&To,A[25]=xo^~Ao&Wa,A[26]=Ti^~To&wn,A[27]=Ao^~Wa&wo,A[28]=To^~wn&li,A[29]=Wa^~wo&St,A[30]=ka^~Is&Dr,A[31]=_n^~Cs&La,A[32]=Is^~Dr&Va,A[33]=Cs^~La&Ds,A[34]=Dr^~Va&Co,A[35]=La^~Ds&Ya,A[36]=Va^~Co&ka,A[37]=Ds^~Ya&_n,A[38]=Co^~ka&Is,A[39]=Ya^~_n&Cs,A[40]=_o^~Wi&qa,A[41]=Da^~Rs&Ha,A[42]=Wi^~qa&Ka,A[43]=Rs^~Ha&En,A[44]=qa^~Ka&Ga,A[45]=Ha^~En&ja,A[46]=Ka^~Ga&_o,A[47]=En^~ja&Da,A[48]=Ga^~_o&Wi,A[49]=ja^~Da&Rs,A[0]^=co[P*2],A[1]^=co[P*2+1]}}function yn(A){const P=[];for(let L=0;L<A.length;L+=4)P.push(A[L]|A[L+1]<<8|A[L+2]<<16|A[L+3]<<24);return P}function uo(A,P){if(!A.length){const pe=new Uint8Array(136);return pe[0]=P,pe[135]=128,[yn(pe)]}const L=Cr(A,136),Y=L[L.length-1];if(Y.length<136){const pe=new Uint8Array(136);pe.set(Y),pe[Y.length]=P,pe[135]|=128,L[L.length-1]=pe}if(Y.length===136){const pe=new Uint8Array(136);pe[0]=P,pe[135]=128,L.push(pe)}return L.map(yn)}function ps(A,P){for(const L of P){for(let Y=0;Y<34;Y+=2)A[Y]^=L[Y+1],A[Y+1]^=L[Y];au(A)}return A}function oi(A){return new Uint8Array([A[1],A[1]>>-24,A[1]>>-16,A[1]>>-8,A[0],A[0]>>8,A[0]>>16,A[0]>>24,A[3],A[3]>>-24,A[3]>>-16,A[3]>>-8,A[2],A[2]>>8,A[2]>>16,A[2]>>24,A[5],A[5]>>-24,A[5]>>-16,A[5]>>-8,A[4],A[4]>>8,A[4]>>16,A[4]>>24,A[7],A[7]>>-24,A[7]>>-16,A[7]>>-8,A[6],A[6]>>8,A[6]>>16,A[6]>>24])}function Mn(A){return oi(ps(new Array(50).fill(0),uo(A,1)))}function Wr(A){return oi(ps(new Array(50).fill(0),uo(A,6)))}function ma(A,P,L){const Y=Math.min(A.length,P.length,L/8+1);for(let pe=0;pe<Y;pe++){const Ce=A[pe]^P[pe];for(let ze=0;ze<8;ze++)if(Ce>>7-ze&1)return pe*8+ze}return L}function ll(A,P){const L=Math.min(A.length,P.length);for(let Y=0;Y<L;Y++)if(A[Y]!==P[Y])return A.subarray(0,Y);return A.subarray(0,L)}function dl(A,P,L,Y){const pe=Math.floor(P/8),Ce=P%8;L===1?A[pe]|=1<<(Y==="BE"?7-Ce:Ce):A[pe]&=~(1<<(Y==="BE"?7-Ce:Ce))}function pl(A,P,L){const Y=Math.floor(P/8),pe=P%8;return A[Y]>>(L==="BE"?7-pe:pe)&1}function ya(A,P,L=0){for(let Y=L;Y<A.length;Y++)for(let pe=0;pe<P.length&&A[Y+pe]===P[pe];pe++)if(pe===P.length-1)return Y;return-1}function cu(A,P,L=0){if(A.length>=P)return A;const Y=new Uint8Array(P);return Y.fill(L),Y.set(A,P-A.length),Y}function gs(A,P,L=0){const Y=A.length%P;return Y===0?A:cu(A,A.length+P-Y,L)}function ba(A,P,L=0){if(A.length>=P)return A;const Y=new Uint8Array(P);return Y.fill(L),Y.set(A,0),Y}function gl(A,P,L=0){const Y=A.length%P;return Y===0?A:ba(A,A.length+P-Y,L)}function ml(A,P){const L=new Uint8Array(A.length);for(let Y=0;Y<A.length;Y++)L[Y]=A[Y]^P[Y%P.length];return L}function ys(A,P){if(A.length!==P.length)return!1;for(let L=0;L<A.length;L++)if(A[L]!==P[L])return!1;return!0}function br(A,P){return(A%P+P)%P}function bs(A,P){A=br(A,P);let[L,Y]=[0n,1n],[pe,Ce]=[P,A];for(;Ce!==0n;){const ze=pe/Ce;[L,Y]=[Y,L-ze*Y],[pe,Ce]=[Ce,pe-ze*Ce]}if(pe>1n)throw new Error("a is not invertible");return L<0n&&(L+=P),L}function va(A,P,L){let Y=1n;for(A=br(A,L);P>0;)P%2n===1n&&(Y=br(Y*A,L)),A=br(A*A,L),P=P/2n;return Y}function wa(A,P){return br(A,P)===0n?0n:P%4n===3n?va(A,(P+1n)/4n,P):null}const Ur=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Or=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,fo=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,vs=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function ws(A,P,L){if(P===0n)return[0n,0n];const Y=br(3n*A*A*bs(2n*P,L),L),pe=br(Y*Y-2n*A,L),Ce=br(Y*(A-pe)-P,L);return[pe,Ce]}function lo(A,P,L,Y,pe){if(A===0n&&P===0n)return[L,Y];if(L===0n&&Y===0n)return[A,P];if(A===L&&P===br(-Y,pe))return[0n,0n];if(A===L&&P===Y)return ws(A,P,pe);const Ce=br((Y-P)*bs(L-A,pe),pe),ze=br(Ce*Ce-A-L,pe),Je=br(Ce*(A-ze)-P,pe);return[ze,Je]}function _a(A){if(A<=0n||A>=Or)throw new Error("Invalid private key");return xi(fo,vs,A,Ur)}function uu(A){const P=A[1]%2n===0n?2:3;return new Uint8Array([P,...zn(A[0],"BE")])}function fu(A){if(A.length!==33||A[0]!==2&&A[0]!==3)throw new Error("Invalid compressed public key");const P=Fi(A.slice(1),"BE"),L=wa(br(P**3n+7n,Ur),Ur);if(!L)throw Error("Invalid x: does not correspond to a valid curve point");const Y=br(-L,Ur),pe=L%2n===0n;return[P,A[0]===2?pe?L:Y:pe?Y:L]}function lu(A){const P=new Uint8Array(20),L=Mn(Si(zn(A[0],"BE"),zn(A[1],"BE")));return P.set(L.subarray(12)),P}function ho(A){const P=y.Binary.uint8ArrayToHex(A),L=y.Binary.uint8ArrayToHex(y.Binary.keccak256(new Uint8Array([...P].map(pe=>pe.charCodeAt(0)))));let Y="0x";for(let pe=0;pe<P.length;pe++)parseInt(L[pe],16)>7?Y+=P[pe].toUpperCase():Y+=P[pe];return Y}function xi(A,P,L,Y){let pe=[0n,0n],Ce=[A,P];const ze=L.toString(2);for(const Je of ze)Je==="0"?(Ce=lo(pe[0],pe[1],Ce[0],Ce[1],Y),pe=ws(pe[0],pe[1],Y)):(pe=lo(pe[0],pe[1],Ce[0],Ce[1],Y),Ce=ws(Ce[0],Ce[1],Y));return pe}function du(A,P,L){return Ea(Fi(Mn(A),"BE"),P,L)}function Ea(A,P,L){if(P<=0n||P>=Or)throw new Error("Invalid private key");if(L||(L=br(Fi(Mn(Si(Mn(zn(P,"BE")),zn(A,"BE"))),"BE"),Or)),L<=0n||L>=Or)throw new Error("Invalid nonce");const Y=br(A,Or),pe=xi(fo,vs,L,Ur),Ce=br(pe[0],Or);let ze=br((Y+br(Ce,Or)*P)*bs(L,Or),Or);if(Ce===0n||ze===0n)throw new Error("Invalid r or s value");let Je=pe[1]%2n===0n?27n:28n;return ze>Or/2n&&(ze=Or-ze,Je=Je===27n?28n:27n),[Ce,ze,Je]}function yl(A,P,L,Y){const pe=wa(br(P**3n+7n,Ur),Ur);if(!pe)throw new Error("Invalid r: does not correspond to a valid curve point");const Ce=Y===27n?0n:1n,ze=pe%2n===Ce?pe:Ur-pe,Je=br(Fi(Mn(A),"BE"),Or),Xe=xi(P,ze,L,Ur),pt=xi(fo,vs,Je,Ur),lr=lo(Xe[0],Xe[1],pt[0],br(-pt[1],Ur),Ur);return xi(lr[0],lr[1],bs(P,Or),Ur)}function hu(A,P,L,Y){const pe=br(Fi(Mn(A),"BE"),Or),Ce=bs(Y,Or),ze=br(pe*Ce,Or),Je=br(L*Ce,Or),Xe=xi(fo,vs,ze,Ur),pt=xi(P[0],P[1],Je,Ur),lr=lo(Xe[0],Xe[1],pt[0],pt[1],Ur);return L===br(lr[0],Or)}class pu{constructor(P){this.cursor=0,this.buffer=P}read(P){const L=this.buffer.subarray(this.cursor,this.cursor+P);return this.cursor+=P,L}max(){return this.buffer.length-this.cursor}}y.Uint8ArrayReader=pu;class po{constructor(P){this.buffer=P,this.cursor=0}write(P){const L=Math.min(this.max(),P.max());return this.buffer.set(P.read(L),this.cursor),this.cursor+=L,L}max(){return this.buffer.length-this.cursor}}y.Uint8ArrayWriter=po;class _s{constructor(P,L=0n){this.span=L,this.writer=new po(new Uint8Array(P))}build(){return Si(ao(this.span,"LE"),this.writer.buffer)}hash(){const P=ru(Cr(this.writer.buffer,32),(L,Y)=>Mn(Si(L,Y)));return Mn(Si(ao(this.span,"LE"),P))}}y.Chunk=_s;class Es{constructor(P,L=4096){this.counters=[1],this.capacity=L,this.chunks=[new _s(L)],this.onChunk=P}static async root(P,L=4096){const Y=new u(u.NOOP,L);return await Y.append(P),Y.finalize()}async append(P,L=0,Y=0n){const pe=new pu(P);for(;pe.max()>0;){this.chunks[L].writer.max()===0&&await this.elevate(L);const Ce=this.chunks[L].writer.write(pe);Y?this.chunks[L].span+=Y:this.chunks[0].span+=BigInt(Ce)}}async elevate(P){this.counters[P]=++this.counters[P]%(this.capacity/32),this.chunks[P+1]||(this.chunks.push(new _s(this.capacity)),this.counters.push(1)),await this.append(this.chunks[P].hash(),P+1,this.chunks[P].span),await this.onChunk(this.chunks[P]),this.chunks[P]=new _s(this.capacity)}async finalize(P=0){return this.chunks[P+1]?this.counters[P]===1?(await this.elevate(P+1),this.chunks[P+1]=this.chunks[P],this.finalize(P+1)):(await this.elevate(P),this.finalize(P+1)):(await this.onChunk(this.chunks[P]),this.chunks[P])}}y.MerkleTree=Es,u=Es,Es.NOOP=async A=>{};class On{constructor(P,L){if(L<0)throw Error("Scale must be non-negative");this.value=BigInt(P),this.scale=L}static fromDecimalString(P,L){let[Y,pe]=P.split(".");return pe=(pe||"").padEnd(L,"0").slice(0,L),new On(BigInt(Y+pe),L)}add(P){return this.assertSameScale(P),new On(this.value+P.value,this.scale)}subtract(P){return this.assertSameScale(P),new On(this.value-P.value,this.scale)}multiply(P){return new On(this.value*P,this.scale)}divmod(P){if(P===0n)throw new Error("Division by zero is not allowed");const L=this.value/P,Y=this.value%P;return[new On(L,this.scale),new On(Y,this.scale)]}exchange(P,L,Y){if(P==="*"){const Ce=this.value*L.value/10n**BigInt(this.scale);return new On(Ce,Y)}this.assertSameScale(L);const pe=this.value*10n**BigInt(Y)/L.value;return new On(pe,Y)}compare(P){return this.assertSameScale(P),this.value>P.value?1:this.value<P.value?-1:0}toDecimalString(){if(this.scale===0)return this.value.toString();const P=this.value.toString(),L=P.slice(0,-this.scale)||"0",Y=P.slice(-this.scale).padStart(this.scale,"0");return`${L}.${Y}`}toString(){return this.value.toString()}toJSON(){return this.toString()}assertSameScale(P){if(this.scale!==P.scale)throw new Error(`Scale mismatch: expected ${this.scale}, but got ${P.scale}`)}}y.FixedPointNumber=On;function Sa(A){if(A.length===0)return null;const P=A[0];return P.ttlMax?--P.ttl<=0&&A.shift():P.ttlMax=P.ttl,{progress:(P.ttlMax-P.ttl)/P.ttlMax,data:P.data}}function Dt(A,P,L,Y){const pe=A.findIndex(Je=>Je===`--${P}`||Je.startsWith(`--${P}=`)),Ce=A[pe];if(!Ce)return(L||{})[Y||P||""]||null;if(Ce.includes("="))return Ce.split("=")[1];const ze=A[pe+1];return ze&&!ze.startsWith("-")?ze:(L||{})[Y||P||""]||null}function bl(A,P,L,Y){const pe=Dt(A,P,L,Y);if(!pe)return null;try{return ni(pe)}catch{throw new Error(`Invalid number argument ${P}: ${pe}`)}}function vl(A,P,L,Y){const pe=A.some(Xe=>Xe.endsWith("-"+P)),Ce=Dt(A,P,L,Y);if(!Ce&&pe)return!0;if(!Ce&&!pe)return null;const ze=["true","1","yes","y","on"],Je=["false","0","no","n","off"];if(ze.includes(Ce.toLowerCase()))return!0;if(Je.includes(Ce.toLowerCase()))return!1;throw Error(`Invalid boolean argument ${P}: ${Ce}`)}function Ui(A,P,L,Y){const pe=Dt(A,P,L,Y);if(!pe)throw new Error(`Missing argument ${P}`);return pe}function gu(A,P,L,Y){const pe=Ui(A,P,L,Y);try{return ni(pe)}catch{throw new Error(`Invalid argument ${P}: ${pe}`)}}function mu(A,P){const L=A[P];A.splice(P,1),A.unshift(L)}function wl(A,P){const L=[...A];return mu(L,P),L}function tn(A,P){return{x:A.x+P.x,y:A.y+P.y}}function _l(A,P){return{x:A.x-P.x,y:A.y-P.y}}function qi(A,P){return{x:A.x*P,y:A.y*P}}function $a(A){const P=Math.sqrt(A.x*A.x+A.y*A.y);return{x:A.x/P,y:A.y/P}}function xa(A,P,L){return{x:A.x+Math.cos(P)*L,y:A.y+Math.sin(P)*L}}function Aa(A,P){return Math.sqrt((A.x-P.x)**2+(A.y-P.y)**2)}function Lr(A,P,L="row-first"){const Y=[];if(L==="column-first")for(let pe=0;pe<A.length;pe++)for(let Ce=0;Ce<A[0].length;Ce++)P(pe,Ce)&&Y.push({x:pe,y:Ce});else for(let pe=0;pe<A[0].length;pe++)for(let Ce=0;Ce<A.length;Ce++)P(Ce,pe)&&Y.push({x:Ce,y:pe});return Y}function ai(A,P,L){var Y,pe;return((Y=A[P+1])==null?void 0:Y[L])&&((pe=A[P-1])==null?void 0:pe[L])&&!A[P][L-1]&&!A[P][L+1]}function Ta(A,P,L){var Y,pe;return A[P][L+1]&&A[P][L-1]&&!((Y=A[P-1])!=null&&Y[L])&&!((pe=A[P+1])!=null&&pe[L])}function Ia(A,P,L){var Y;return!((Y=A[P-1])!=null&&Y[L])}function Ss(A,P,L){var Y;return!((Y=A[P+1])!=null&&Y[L])}function Ca(A,P,L){return!A[P][L-1]}function go(A,P,L){return!A[P][L+1]}function yu(A,P,L){var pe,Ce,ze,Je,Xe,pt,lr,Sr;const Y=[];return A[P][L]?ai(A,P,L)||Ta(A,P,L)?[]:(!((pe=A[P-1])!=null&&pe[L-1])&&Ia(A,P,L)&&Ca(A,P,L)&&Y.push({x:P,y:L}),!((Ce=A[P+1])!=null&&Ce[L-1])&&Ss(A,P,L)&&Ca(A,P,L)&&Y.push({x:P+1,y:L}),!((ze=A[P-1])!=null&&ze[L+1])&&Ia(A,P,L)&&go(A,P,L)&&Y.push({x:P,y:L+1}),!((Je=A[P+1])!=null&&Je[L+1])&&Ss(A,P,L)&&go(A,P,L)&&Y.push({x:P+1,y:L+1}),Y):((Xe=A[P-1])!=null&&Xe[L]&&A[P][L-1]&&Y.push({x:P,y:L}),(pt=A[P+1])!=null&&pt[L]&&A[P][L-1]&&Y.push({x:P+1,y:L}),(lr=A[P-1])!=null&&lr[L]&&A[P][L+1]&&Y.push({x:P,y:L+1}),(Sr=A[P+1])!=null&&Sr[L]&&A[P][L+1]&&Y.push({x:P+1,y:L+1}),Y)}function Pa(A,P,L,Y){const pe=[{x:0,y:0},{x:L,y:0},{x:0,y:Y},{x:L,y:Y}];for(let Ce=0;Ce<A.length;Ce++)for(let ze=0;ze<A[0].length;ze++){const Je=yu(A,Ce,ze);for(const Xe of Je)pe.some(pt=>pt.x===Xe.x&&pt.y===Xe.y)||pe.push(Xe)}return pe.map(Ce=>({x:Ce.x*P,y:Ce.y*P}))}function Ra(A,P){const L=Lr(A,(Xe,pt)=>A[Xe][pt]===0&&A[Xe][pt+1]!==0,"row-first").map(Xe=>({...Xe,dx:1,dy:0})),Y=Lr(A,(Xe,pt)=>A[Xe][pt]===0&&A[Xe][pt-1]!==0,"row-first").map(Xe=>({...Xe,dx:1,dy:0})),pe=Lr(A,(Xe,pt)=>{var lr;return A[Xe][pt]===0&&((lr=A[Xe-1])==null?void 0:lr[pt])!==0},"column-first").map(Xe=>({...Xe,dx:0,dy:1})),Ce=Lr(A,(Xe,pt)=>{var lr;return A[Xe][pt]===0&&((lr=A[Xe+1])==null?void 0:lr[pt])!==0},"column-first").map(Xe=>({...Xe,dx:0,dy:1}));L.forEach(Xe=>Xe.y++),Ce.forEach(Xe=>Xe.x++);const ze=pa([...pe,...Ce],(Xe,pt)=>Xe.x===pt.x&&Xe.y-1===pt.y),Je=pa([...Y,...L],(Xe,pt)=>Xe.y===pt.y&&Xe.x-1===pt.x);return[...ze,...Je].map(Xe=>({start:Xe[0],end:F(Xe)})).map(Xe=>({start:qi(Xe.start,P),end:qi(tn(Xe.end,{x:Xe.start.dx,y:Xe.start.dy}),P)}))}function ci(A,P){return Math.atan2(P.y-A.y,P.x-A.x)}function El(A,P){return P.map(L=>ci(A,L)).sort((L,Y)=>L-Y)}function Wn(A,P,L,Y){const pe=(Y.y-L.y)*(P.x-A.x)-(Y.x-L.x)*(P.y-A.y);if(pe===0)return null;let Ce=A.y-L.y,ze=A.x-L.x;const Je=(Y.x-L.x)*Ce-(Y.y-L.y)*ze,Xe=(P.x-A.x)*Ce-(P.y-A.y)*ze;return Ce=Je/pe,ze=Xe/pe,Ce>0&&Ce<1&&ze>0&&ze<1?{x:A.x+Ce*(P.x-A.x),y:A.y+Ce*(P.y-A.y)}:null}function mo(A,P,L){const Y=[],pe=xa(A,L,1e4);for(const Ce of P){const ze=Wn(A,pe,Ce.start,Ce.end);ze&&Y.push(ze)}return Y.length?Y.reduce((Ce,ze)=>{const Je=Aa(A,ze),Xe=Aa(A,Ce);return Je<Xe?ze:Ce}):null}function bu(A,P,L){const Y=El(A,L),pe=[];for(const Ce of Y){const ze=mo(A,P,Ce-.001),Je=mo(A,P,Ce+.001);ze&&pe.push(ze),Je&&pe.push(Je)}return pe}class $s{constructor(){this.subscribers=[]}subscribe(P){return this.subscribers.push(P),()=>{this.subscribers=this.subscribers.filter(L=>L!==P)}}publish(P){this.subscribers.forEach(L=>L(P))}clear(){this.subscribers=[]}getSubscriberCount(){return this.subscribers.length}}y.PubSubChannel=$s;class Sl{constructor(P,L){this.queue=[],this.running=0,this.onProcessed=new $s,this.onDrained=new $s,this.concurrency=P,this.capacity=L}process(){if(this.running>=this.concurrency)return;const P=this.queue.shift();P&&(this.running++,P().finally(()=>{this.running--,this.process(),this.onProcessed.publish(),this.running===0&&this.onDrained.publish()}))}enqueue(P){if(this.queue.length<this.capacity)return this.queue.push(P),this.process(),Promise.resolve();if(this.onProcessed.getSubscriberCount())throw Error("Queue capacity is full");return new Promise(L=>{this.onProcessed.subscribe(()=>{this.queue.length<this.capacity&&(this.queue.push(P),this.process(),this.onProcessed.clear(),L())})})}drain(){if(this.running===0)return Promise.resolve();if(this.onDrained.getSubscriberCount())throw Error("Already draining");return new Promise(P=>{this.onDrained.subscribe(()=>{this.onDrained.clear(),P()})})}}y.AsyncQueue=Sl,y.Binary={hexToUint8Array:Cc,uint8ArrayToHex:Pc,base64ToUint8Array:lf,uint8ArrayToBase64:df,base32ToUint8Array:Tc,uint8ArrayToBase32:Zs,log2Reduce:ru,partition:Cr,concatBytes:Si,numberToUint8:un,uint8ToNumber:ul,numberToUint16:iu,uint16ToNumber:su,numberToUint32:hs,uint32ToNumber:si,numberToUint64:ao,uint64ToNumber:fl,numberToUint256:zn,uint256ToNumber:Fi,sliceBytes:ou,keccak256:Mn,sha3_256:Wr,proximity:ma,commonPrefix:ll,setBit:dl,getBit:pl,indexOf:ya,equals:ys,padStart:cu,padStartToMultiple:gs,padEnd:ba,padEndToMultiple:gl,xorCypher:ml},y.Elliptic={privateKeyToPublicKey:_a,compressPublicKey:uu,publicKeyFromCompressed:fu,publicKeyToAddress:lu,signMessage:du,signHash:Ea,verifySignature:hu,recoverPublicKey:yl,checksumEncode:ho},y.Random={intBetween:ee,floatBetween:ae,chance:Ie,signed:de,makeSeededRng:ie,point:ve,procs:Pe},y.Arrays={countUnique:Xf,makeUnique:jf,splitBySize:Zn,splitByCount:Yc,index:Xc,indexCollection:Wf,onlyOrThrow:E,onlyOrNull:S,firstOrThrow:T,firstOrNull:x,shuffle:_,initialize:C,initialize2D:D,rotate2D:O,containsShape:U,glue:Ko,pluck:X,pick:Ee,pickMany:De,pickManyUnique:be,pickWeighted:Q,pickRandomIndices:te,pickGuaranteed:B,last:F,pipe:M,makePipe:N,sortWeighted:j,pushAll:Hn,unshiftAll:cc,filterAndRemove:gn,merge:Lf,empty:Ff,pushToBucket:Un,unshiftAndLimit:qn,atRolling:Qi,group:pa,createOscillator:Wc,organiseWithLimits:Of,tickPlaybook:Sa,getArgument:Dt,getBooleanArgument:vl,getNumberArgument:bl,requireStringArgument:Ui,requireNumberArgument:gu,bringToFront:wl,bringToFrontInPlace:mu,findInstance:tu,filterInstances:al,interleave:cl,toggle:ga,createHierarchy:so,multicall:ol,maxBy:eu},y.System={sleepMillis:w,forever:Ne,scheduleMany:hc,waitFor:Di,expandError:Jr,runAndSetInterval:Ae},y.Numbers={make:ni,sum:Gu,average:pc,median:Zo,getDistanceFromMidpoint:zo,clamp:_i,range:pi,interpolate:Vo,createSequence:Rf,increment:us,decrement:ro,format:ha,fromDecimals:cs,makeStorage:Js,asMegabytes:le,convertBytes:me,hexToRgb:Me,rgbToHex:fe,haversineDistanceToMeters:ge,roundToNearest:ce,formatDistance:_e,triangularNumber:Re,searchFloat:Ue},y.Promises={raceFulfilled:b,invert:h,runInParallelBatches:v},y.Dates={getTimestamp:Mt,getTimeDelta:Ar,secondsToHumanTime:yr,countCycles:fa,isoDate:Ef,throttle:an,timeSince:Af,dateTimeSlug:Sf,unixTimestamp:_f,fromUtcString:$f,fromMillis:xf,getProgress:Bi,humanizeTime:Ye,humanizeProgress:wf,createTimeDigits:Zr,mapDayNumber:is,getDayInfoFromDate:cr,getDayInfoFromDateTimeString:Tf,seconds:Uc,minutes:Xs,hours:If,days:Cf,make:Ys,normalizeTime:He,absoluteDays:Ge},y.Objects={safeParse:da,deleteDeep:H,getDeep:ne,setDeep:J,incrementDeep:q,ensureDeep:re,replaceDeep:he,getFirstDeep:Oe,deepMergeInPlace:Vr,deepMerge2:Tn,deepMerge3:In,mapAllAsync:uc,cloneWithJson:Fc,sortObject:Zc,sortArray:zc,sortAny:wi,deepEquals:as,deepEqualsEvery:eo,runOn:Ni,ifPresent:Nf,zip:pn,zipSum:Fn,removeEmptyArrays:Uf,removeEmptyValues:qf,flatten:Zf,unflatten:jc,match:zf,sort:Pn,map:Gc,mapIterable:$e,filterKeys:no,filterValues:ls,rethrow:Li,setSomeOnObject:io,setSomeDeep:cn,flip:Zt,getAllPermutations:Hf,countTruthyValues:Kf,transformToArray:Yf,setMulti:Qf,incrementMulti:Jf,createBidirectionalMap:el,createTemporalBidirectionalMap:Ei,pushToBidirectionalMap:Qc,unshiftToBidirectionalMap:tl,addToTemporalBidirectionalMap:mn,getFromTemporalBidirectionalMap:rl,createStatefulToggle:Mf,diffKeys:Ir,pickRandomKey:Nr,mapRandomKey:Df,fromObjectString:Bf,toQueryString:bi,parseQueryString:mf,hasKey:yf,selectMax:ua,reposition:Lc,unwrapSingleKey:ti,parseKeyValues:Ws},y.Types={isFunction:it,isObject:qe,isStrictlyObject:Ze,isEmptyArray:tt,isEmptyObject:Fe,isUndefined:nt,isString:at,isNumber:ct,isBoolean:ht,isDate:xt,isBlank:Ot,isId:dt,isIntegerString:Rt,isHexString:Nt,isUrl:Hr,isNullable:Xr,asString:Jt,asHexString:we,asSafeString:se,asIntegerString:qt,asNumber:ke,asFunction:xe,asInteger:Ke,asBoolean:We,asDate:ut,asNullableString:_t,asEmptiableString:st,asId:Et,asTime:gt,asArray:It,asObject:Qt,asNullableObject:rr,asStringMap:ar,asNumericDictionary:Gr,asUrl:jr,asNullable:Yr,asOptional:Br,enforceObjectShape:Kr,enforceArrayShape:kr,isPng:nu,isJpg:Rn,isWebp:oo,isImage:$i},y.Strings={tokenizeByCount:Gf,tokenizeByLength:Jc,searchHex:Bt,searchSubstring:Yt,randomHex:Tt,randomLetter:At,randomAlphanumeric:tr,randomRichAscii:Xt,randomUnicode:bt,includesAny:gc,slugify:Wo,normalForm:yc,enumify:Yu,escapeHtml:Qu,decodeHtmlEntities:tf,after:Go,afterLast:_c,before:Hs,beforeLast:jo,betweenWide:rf,betweenNarrow:nf,getPreLine:qc,containsWord:yi,containsWords:Dc,joinUrl:ss,getFuzzyMatchScore:es,sortByFuzzyScore:Ju,splitOnce:pr,splitAll:gr,randomize:cf,expand:Jo,shrinkTrim:ts,capitalize:xr,decapitalize:Ks,csvEscape:Qr,parseCsv:vf,surroundInOut:Xu,getExtension:Xo,getBasename:Yo,normalizeEmail:sf,normalizeFilename:of,parseFilename:af,camelToTitle:bc,slugToTitle:vc,slugToCamel:wc,joinHumanly:ju,findWeightedPair:Kn,extractBlock:rs,extractAllBlocks:na,replaceBlocks:wr,indexOfEarliest:Oi,lastIndexOfBefore:ra,parseHtmlAttributes:Bc,readNextWord:zs,resolveVariables:pf,resolveVariableWithDefaultSyntax:kc,resolveRemainingVariablesWithDefaults:Nc,isLetter:Qn,isDigit:Qo,isLetterOrDigit:gi,isValidObjectPathCharacter:Sc,insert:$c,indexOfRegex:ea,lineMatches:ta,linesMatchInOrder:xc,represent:Mr,resolveMarkdownLinks:gf,buildUrl:bf,isChinese:mc,replaceBetweenStrings:Vc,describeMarkdown:os,isBalanced:vi,textToFormat:Qs,splitFormatting:ei,splitHashtags:ia,splitUrls:ff,route:sa,explodeReplace:ns,generateVariants:Rc,replaceWord:hf,replacePascalCaseWords:oa,stripHtml:aa,breakLine:Mc,measureTextWidth:Oc,toLines:en,levenshteinDistance:ca},y.Assertions={asEqual:zu,asTrue:fc,asTruthy:qs,asFalse:lc,asFalsy:Wu,asEither:dc},y.Cache={get:Hc,invalidate:Kc},y.Vector={addPoint:tn,subtractPoint:_l,multiplyPoint:qi,normalizePoint:$a,pushPoint:xa,filterCoordinates:Lr,findCorners:Pa,findLines:Ra,raycast:mo,raycastCircle:bu,getLineIntersectionPoint:Wn}})(cafeUtility);const utility=getDefaultExportFromCjs$1(cafeUtility);utility.Arrays;utility.Assertions;const Binary=utility.Binary;utility.Cache;utility.Dates;utility.Elliptic;utility.Numbers;utility.Objects;utility.Pagination;utility.Promises;utility.Random;utility.Strings;utility.System;utility.Types;utility.Optional;utility.Vector;utility.PubSubChannel;utility.Chunk;const MerkleTree=utility.MerkleTree;utility.FixedPointNumber;utility.Lazy;utility.AsyncLazy;utility.AsyncQueue;utility.Uint8ArrayReader;utility.Uint8ArrayWriter;const ENCODER=new TextEncoder,MIN_PAYLOAD_SIZE=1,MAX_PAYLOAD_SIZE=4096,MAX_CHUNK_PAYLOAD_SIZE=4096,SEGMENT_SIZE=32;function makeFeedIdentifier(y,u){return u=typeof u=="number"?beeJs.FeedIndex.fromBigInt(BigInt(u)):u,new beeJs.Identifier(Binary.keccak256(Binary.concatBytes(y.toUint8Array(),u.toUint8Array())))}function calculateChunkAddress(y){const u=y.slice(0,beeJs.Span.LENGTH),h=y.slice(beeJs.Span.LENGTH),b=calculateBmtRootHash(h),v=Binary.keccak256(Binary.concatBytes(u,b));return new beeJs.Reference(v)}function calculateBmtRootHash(y){if(y.length>MAX_CHUNK_PAYLOAD_SIZE)throw new beeJs.BeeArgumentError(`payload size ${y.length} exceeds maximum chunk payload size ${MAX_CHUNK_PAYLOAD_SIZE}`,y);const u=new Uint8Array(MAX_CHUNK_PAYLOAD_SIZE);return u.set(y),Binary.log2Reduce(Binary.partition(u,SEGMENT_SIZE),(h,b)=>Binary.keccak256(Binary.concatBytes(h,b)))}function makeContentAddressedChunk(y){if(y instanceof Uint8Array||(y=ENCODER.encode(y)),y.length<MIN_PAYLOAD_SIZE||y.length>MAX_PAYLOAD_SIZE)throw new RangeError(`payload size ${y.length} exceeds limits [${MIN_PAYLOAD_SIZE}, ${MAX_PAYLOAD_SIZE}]`);const u=beeJs.Span.fromBigInt(BigInt(y.length)),h=Binary.concatBytes(u.toUint8Array(),y);return{data:h,span:u,payload:beeJs.Bytes.fromSlice(h,beeJs.Span.LENGTH),address:calculateChunkAddress(h)}}function makeSOCAddress(y,u){return new beeJs.Reference(Binary.keccak256(Binary.concatBytes(y.toUint8Array(),u.toUint8Array())))}function makeSingleOwnerChunk(y,u,h){u=new beeJs.Identifier(u),h=new beeJs.PrivateKey(h);const b=makeSOCAddress(u,h.publicKey().address()),v=h.sign(Binary.concatBytes(u.toUint8Array(),y.address.toUint8Array())),w=Binary.concatBytes(u.toUint8Array(),v.toUint8Array(),y.data),_=beeJs.Span.fromSlice(y.data,0),E=beeJs.Bytes.fromSlice(y.data,beeJs.Span.LENGTH);return{data:w,identifier:u,signature:v,span:_,payload:E,address:b,owner:h.publicKey().address()}}let Logger$2=class tc{constructor(){}static getInstance(){return tc.instance||(tc.instance=new tc),tc.instance}formatMessage(u,...h){return`[${new Date().toISOString()}] [${u.toUpperCase()}] - ${h.map(v=>typeof v=="object"?JSON.stringify(v):v).join(" ")}`}log(...u){console.log(this.formatMessage("log",...u))}info(...u){console.info(this.formatMessage("info",...u))}warn(...u){console.warn(this.formatMessage("warn",...u))}error(...u){console.error(this.formatMessage("error",...u))}debug(...u){console.debug(this.formatMessage("debug",...u))}};class ErrorHandler{constructor(){this.logger=Logger$2.getInstance()}static getInstance(){return ErrorHandler.instance||(ErrorHandler.instance=new ErrorHandler),ErrorHandler.instance}handleError(u,h){const b=u instanceof Error?u.message:"Unknown error occurred",v=u instanceof Error?u.stack:null;this.logger.error(`Error in ${h||"unknown context"}: ${b}`,{stack:v})}}const logger$4=Logger$2.getInstance(),errorHandler=ErrorHandler.getInstance();function sleep(y){return new Promise(u=>{setTimeout(u,y)})}function remove0x(y){return(y.startsWith("0x")?y.slice(2):y).toLowerCase()}async function retryAwaitableAsync(y,u=3,h=250){return new Promise((b,v)=>{y().then(b).catch(w=>{u>0?(logger$4.info(`Retrying... Attempts left: ${u}. Error: ${w.message}`),setTimeout(()=>{retryAwaitableAsync(y,u-1,h).then(b).catch(v)},h)):(errorHandler.handleError(w,"Utils.retryAwaitableAsync"),v(w))})})}let EventEmitter$3=class{constructor(){this.events={},this.on=this.on.bind(this),this.off=this.off.bind(this),this.cleanAll=this.cleanAll.bind(this),this.emit=this.emit.bind(this)}on(u,h){this.events[u]||(this.events[u]=[]),this.events[u].push(h)}off(u,h){if(!this.events[u])return;const b=this.events[u].indexOf(h);b>-1&&this.events[u].splice(b,1)}cleanAll(){this.events={}}emit(u,h){this.events[u]&&this.events[u].forEach(b=>b(h))}};var util$c;(function(y){y.assertEqual=v=>v;function u(v){}y.assertIs=u;function h(v){throw new Error}y.assertNever=h,y.arrayToEnum=v=>{const w={};for(const _ of v)w[_]=_;return w},y.getValidEnumValues=v=>{const w=y.objectKeys(v).filter(E=>typeof v[v[E]]!="number"),_={};for(const E of w)_[E]=v[E];return y.objectValues(_)},y.objectValues=v=>y.objectKeys(v).map(function(w){return v[w]}),y.objectKeys=typeof Object.keys=="function"?v=>Object.keys(v):v=>{const w=[];for(const _ in v)Object.prototype.hasOwnProperty.call(v,_)&&w.push(_);return w},y.find=(v,w)=>{for(const _ of v)if(w(_))return _},y.isInteger=typeof Number.isInteger=="function"?v=>Number.isInteger(v):v=>typeof v=="number"&&isFinite(v)&&Math.floor(v)===v;function b(v,w=" | "){return v.map(_=>typeof _=="string"?`'${_}'`:_).join(w)}y.joinValues=b,y.jsonStringifyReplacer=(v,w)=>typeof w=="bigint"?w.toString():w})(util$c||(util$c={}));var objectUtil;(function(y){y.mergeShapes=(u,h)=>({...u,...h})})(objectUtil||(objectUtil={}));const ZodParsedType=util$c.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=y=>{switch(typeof y){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return isNaN(y)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(y)?ZodParsedType.array:y===null?ZodParsedType.null:y.then&&typeof y.then=="function"&&y.catch&&typeof y.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&y instanceof Map?ZodParsedType.map:typeof Set<"u"&&y instanceof Set?ZodParsedType.set:typeof Date<"u"&&y instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util$c.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=y=>JSON.stringify(y,null,2).replace(/"([^"]+)":/g,"$1:");class ZodError extends Error{get errors(){return this.issues}constructor(u){super(),this.issues=[],this.addIssue=b=>{this.issues=[...this.issues,b]},this.addIssues=(b=[])=>{this.issues=[...this.issues,...b]};const h=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,h):this.__proto__=h,this.name="ZodError",this.issues=u}format(u){const h=u||function(w){return w.message},b={_errors:[]},v=w=>{for(const _ of w.issues)if(_.code==="invalid_union")_.unionErrors.map(v);else if(_.code==="invalid_return_type")v(_.returnTypeError);else if(_.code==="invalid_arguments")v(_.argumentsError);else if(_.path.length===0)b._errors.push(h(_));else{let E=b,S=0;for(;S<_.path.length;){const x=_.path[S];S===_.path.length-1?(E[x]=E[x]||{_errors:[]},E[x]._errors.push(h(_))):E[x]=E[x]||{_errors:[]},E=E[x],S++}}};return v(this),b}static assert(u){if(!(u instanceof ZodError))throw new Error(`Not a ZodError: ${u}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util$c.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(u=h=>h.message){const h={},b=[];for(const v of this.issues)v.path.length>0?(h[v.path[0]]=h[v.path[0]]||[],h[v.path[0]].push(u(v))):b.push(u(v));return{formErrors:b,fieldErrors:h}}get formErrors(){return this.flatten()}}ZodError.create=y=>new ZodError(y);const errorMap=(y,u)=>{let h;switch(y.code){case ZodIssueCode.invalid_type:y.received===ZodParsedType.undefined?h="Required":h=`Expected ${y.expected}, received ${y.received}`;break;case ZodIssueCode.invalid_literal:h=`Invalid literal value, expected ${JSON.stringify(y.expected,util$c.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:h=`Unrecognized key(s) in object: ${util$c.joinValues(y.keys,", ")}`;break;case ZodIssueCode.invalid_union:h="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:h=`Invalid discriminator value. Expected ${util$c.joinValues(y.options)}`;break;case ZodIssueCode.invalid_enum_value:h=`Invalid enum value. Expected ${util$c.joinValues(y.options)}, received '${y.received}'`;break;case ZodIssueCode.invalid_arguments:h="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:h="Invalid function return type";break;case ZodIssueCode.invalid_date:h="Invalid date";break;case ZodIssueCode.invalid_string:typeof y.validation=="object"?"includes"in y.validation?(h=`Invalid input: must include "${y.validation.includes}"`,typeof y.validation.position=="number"&&(h=`${h} at one or more positions greater than or equal to ${y.validation.position}`)):"startsWith"in y.validation?h=`Invalid input: must start with "${y.validation.startsWith}"`:"endsWith"in y.validation?h=`Invalid input: must end with "${y.validation.endsWith}"`:util$c.assertNever(y.validation):y.validation!=="regex"?h=`Invalid ${y.validation}`:h="Invalid";break;case ZodIssueCode.too_small:y.type==="array"?h=`Array must contain ${y.exact?"exactly":y.inclusive?"at least":"more than"} ${y.minimum} element(s)`:y.type==="string"?h=`String must contain ${y.exact?"exactly":y.inclusive?"at least":"over"} ${y.minimum} character(s)`:y.type==="number"?h=`Number must be ${y.exact?"exactly equal to ":y.inclusive?"greater than or equal to ":"greater than "}${y.minimum}`:y.type==="date"?h=`Date must be ${y.exact?"exactly equal to ":y.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(y.minimum))}`:h="Invalid input";break;case ZodIssueCode.too_big:y.type==="array"?h=`Array must contain ${y.exact?"exactly":y.inclusive?"at most":"less than"} ${y.maximum} element(s)`:y.type==="string"?h=`String must contain ${y.exact?"exactly":y.inclusive?"at most":"under"} ${y.maximum} character(s)`:y.type==="number"?h=`Number must be ${y.exact?"exactly":y.inclusive?"less than or equal to":"less than"} ${y.maximum}`:y.type==="bigint"?h=`BigInt must be ${y.exact?"exactly":y.inclusive?"less than or equal to":"less than"} ${y.maximum}`:y.type==="date"?h=`Date must be ${y.exact?"exactly":y.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(y.maximum))}`:h="Invalid input";break;case ZodIssueCode.custom:h="Invalid input";break;case ZodIssueCode.invalid_intersection_types:h="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:h=`Number must be a multiple of ${y.multipleOf}`;break;case ZodIssueCode.not_finite:h="Number must be finite";break;default:h=u.defaultError,util$c.assertNever(y)}return{message:h}};let overrideErrorMap=errorMap;function setErrorMap(y){overrideErrorMap=y}function getErrorMap(){return overrideErrorMap}const makeIssue=y=>{const{data:u,path:h,errorMaps:b,issueData:v}=y,w=[...h,...v.path||[]],_={...v,path:w};if(v.message!==void 0)return{...v,path:w,message:v.message};let E="";const S=b.filter(x=>!!x).slice().reverse();for(const x of S)E=x(_,{data:u,defaultError:E}).message;return{...v,path:w,message:E}},EMPTY_PATH=[];function addIssueToContext(y,u){const h=getErrorMap(),b=makeIssue({issueData:u,data:y.data,path:y.path,errorMaps:[y.common.contextualErrorMap,y.schemaErrorMap,h,h===errorMap?void 0:errorMap].filter(v=>!!v)});y.common.issues.push(b)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(u,h){const b=[];for(const v of h){if(v.status==="aborted")return INVALID;v.status==="dirty"&&u.dirty(),b.push(v.value)}return{status:u.value,value:b}}static async mergeObjectAsync(u,h){const b=[];for(const v of h){const w=await v.key,_=await v.value;b.push({key:w,value:_})}return ParseStatus.mergeObjectSync(u,b)}static mergeObjectSync(u,h){const b={};for(const v of h){const{key:w,value:_}=v;if(w.status==="aborted"||_.status==="aborted")return INVALID;w.status==="dirty"&&u.dirty(),_.status==="dirty"&&u.dirty(),w.value!=="__proto__"&&(typeof _.value<"u"||v.alwaysSet)&&(b[w.value]=_.value)}return{status:u.value,value:b}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=y=>({status:"dirty",value:y}),OK=y=>({status:"valid",value:y}),isAborted=y=>y.status==="aborted",isDirty=y=>y.status==="dirty",isValid=y=>y.status==="valid",isAsync=y=>typeof Promise<"u"&&y instanceof Promise;function __classPrivateFieldGet(y,u,h,b){if(typeof u=="function"?y!==u||!b:!u.has(y))throw new TypeError("Cannot read private member from an object whose class did not declare it");return u.get(y)}function __classPrivateFieldSet(y,u,h,b,v){if(typeof u=="function"?y!==u||!v:!u.has(y))throw new TypeError("Cannot write private member to an object whose class did not declare it");return u.set(y,h),h}typeof SuppressedError=="function"&&SuppressedError;var errorUtil;(function(y){y.errToObj=u=>typeof u=="string"?{message:u}:u||{},y.toString=u=>typeof u=="string"?u:u==null?void 0:u.message})(errorUtil||(errorUtil={}));var _ZodEnum_cache,_ZodNativeEnum_cache;class ParseInputLazyPath{constructor(u,h,b,v){this._cachedPath=[],this.parent=u,this.data=h,this._path=b,this._key=v}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(y,u)=>{if(isValid(u))return{success:!0,data:u.value};if(!y.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const h=new ZodError(y.common.issues);return this._error=h,this._error}}};function processCreateParams(y){if(!y)return{};const{errorMap:u,invalid_type_error:h,required_error:b,description:v}=y;if(u&&(h||b))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return u?{errorMap:u,description:v}:{errorMap:(_,E)=>{var S,x;const{message:T}=y;return _.code==="invalid_enum_value"?{message:T??E.defaultError}:typeof E.data>"u"?{message:(S=T??b)!==null&&S!==void 0?S:E.defaultError}:_.code!=="invalid_type"?{message:E.defaultError}:{message:(x=T??h)!==null&&x!==void 0?x:E.defaultError}},description:v}}class ZodType{get description(){return this._def.description}_getType(u){return getParsedType(u.data)}_getOrReturnCtx(u,h){return h||{common:u.parent.common,data:u.data,parsedType:getParsedType(u.data),schemaErrorMap:this._def.errorMap,path:u.path,parent:u.parent}}_processInputParams(u){return{status:new ParseStatus,ctx:{common:u.parent.common,data:u.data,parsedType:getParsedType(u.data),schemaErrorMap:this._def.errorMap,path:u.path,parent:u.parent}}}_parseSync(u){const h=this._parse(u);if(isAsync(h))throw new Error("Synchronous parse encountered promise.");return h}_parseAsync(u){const h=this._parse(u);return Promise.resolve(h)}parse(u,h){const b=this.safeParse(u,h);if(b.success)return b.data;throw b.error}safeParse(u,h){var b;const v={common:{issues:[],async:(b=h==null?void 0:h.async)!==null&&b!==void 0?b:!1,contextualErrorMap:h==null?void 0:h.errorMap},path:(h==null?void 0:h.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:u,parsedType:getParsedType(u)},w=this._parseSync({data:u,path:v.path,parent:v});return handleResult(v,w)}"~validate"(u){var h,b;const v={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:u,parsedType:getParsedType(u)};if(!this["~standard"].async)try{const w=this._parseSync({data:u,path:[],parent:v});return isValid(w)?{value:w.value}:{issues:v.common.issues}}catch(w){!((b=(h=w==null?void 0:w.message)===null||h===void 0?void 0:h.toLowerCase())===null||b===void 0)&&b.includes("encountered")&&(this["~standard"].async=!0),v.common={issues:[],async:!0}}return this._parseAsync({data:u,path:[],parent:v}).then(w=>isValid(w)?{value:w.value}:{issues:v.common.issues})}async parseAsync(u,h){const b=await this.safeParseAsync(u,h);if(b.success)return b.data;throw b.error}async safeParseAsync(u,h){const b={common:{issues:[],contextualErrorMap:h==null?void 0:h.errorMap,async:!0},path:(h==null?void 0:h.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:u,parsedType:getParsedType(u)},v=this._parse({data:u,path:b.path,parent:b}),w=await(isAsync(v)?v:Promise.resolve(v));return handleResult(b,w)}refine(u,h){const b=v=>typeof h=="string"||typeof h>"u"?{message:h}:typeof h=="function"?h(v):h;return this._refinement((v,w)=>{const _=u(v),E=()=>w.addIssue({code:ZodIssueCode.custom,...b(v)});return typeof Promise<"u"&&_ instanceof Promise?_.then(S=>S?!0:(E(),!1)):_?!0:(E(),!1)})}refinement(u,h){return this._refinement((b,v)=>u(b)?!0:(v.addIssue(typeof h=="function"?h(b,v):h),!1))}_refinement(u){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:u}})}superRefine(u){return this._refinement(u)}constructor(u){this.spa=this.safeParseAsync,this._def=u,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:h=>this["~validate"](h)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(u){return ZodUnion.create([this,u],this._def)}and(u){return ZodIntersection.create(this,u,this._def)}transform(u){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:u}})}default(u){const h=typeof u=="function"?u:()=>u;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:h,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(u){const h=typeof u=="function"?u:()=>u;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:h,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(u){const h=this.constructor;return new h({...this._def,description:u})}pipe(u){return ZodPipeline.create(this,u)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(y){let u="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return y.precision?u=`${u}\\.\\d{${y.precision}}`:y.precision==null&&(u=`${u}(\\.\\d+)?`),u}function timeRegex(y){return new RegExp(`^${timeRegexSource(y)}$`)}function datetimeRegex(y){let u=`${dateRegexSource}T${timeRegexSource(y)}`;const h=[];return h.push(y.local?"Z?":"Z"),y.offset&&h.push("([+-]\\d{2}:?\\d{2})"),u=`${u}(${h.join("|")})`,new RegExp(`^${u}$`)}function isValidIP(y,u){return!!((u==="v4"||!u)&&ipv4Regex.test(y)||(u==="v6"||!u)&&ipv6Regex.test(y))}function isValidJWT(y,u){if(!jwtRegex.test(y))return!1;try{const[h]=y.split("."),b=h.replace(/-/g,"+").replace(/_/g,"/").padEnd(h.length+(4-h.length%4)%4,"="),v=JSON.parse(atob(b));return!(typeof v!="object"||v===null||!v.typ||!v.alg||u&&v.alg!==u)}catch{return!1}}function isValidCidr(y,u){return!!((u==="v4"||!u)&&ipv4CidrRegex.test(y)||(u==="v6"||!u)&&ipv6CidrRegex.test(y))}class ZodString extends ZodType{_parse(u){if(this._def.coerce&&(u.data=String(u.data)),this._getType(u)!==ZodParsedType.string){const w=this._getOrReturnCtx(u);return addIssueToContext(w,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:w.parsedType}),INVALID}const b=new ParseStatus;let v;for(const w of this._def.checks)if(w.kind==="min")u.data.length<w.value&&(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.too_small,minimum:w.value,type:"string",inclusive:!0,exact:!1,message:w.message}),b.dirty());else if(w.kind==="max")u.data.length>w.value&&(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.too_big,maximum:w.value,type:"string",inclusive:!0,exact:!1,message:w.message}),b.dirty());else if(w.kind==="length"){const _=u.data.length>w.value,E=u.data.length<w.value;(_||E)&&(v=this._getOrReturnCtx(u,v),_?addIssueToContext(v,{code:ZodIssueCode.too_big,maximum:w.value,type:"string",inclusive:!0,exact:!0,message:w.message}):E&&addIssueToContext(v,{code:ZodIssueCode.too_small,minimum:w.value,type:"string",inclusive:!0,exact:!0,message:w.message}),b.dirty())}else if(w.kind==="email")emailRegex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"email",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty());else if(w.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"emoji",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty());else if(w.kind==="uuid")uuidRegex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"uuid",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty());else if(w.kind==="nanoid")nanoidRegex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty());else if(w.kind==="cuid")cuidRegex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"cuid",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty());else if(w.kind==="cuid2")cuid2Regex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty());else if(w.kind==="ulid")ulidRegex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"ulid",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty());else if(w.kind==="url")try{new URL(u.data)}catch{v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"url",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty()}else w.kind==="regex"?(w.regex.lastIndex=0,w.regex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"regex",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty())):w.kind==="trim"?u.data=u.data.trim():w.kind==="includes"?u.data.includes(w.value,w.position)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.invalid_string,validation:{includes:w.value,position:w.position},message:w.message}),b.dirty()):w.kind==="toLowerCase"?u.data=u.data.toLowerCase():w.kind==="toUpperCase"?u.data=u.data.toUpperCase():w.kind==="startsWith"?u.data.startsWith(w.value)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.invalid_string,validation:{startsWith:w.value},message:w.message}),b.dirty()):w.kind==="endsWith"?u.data.endsWith(w.value)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.invalid_string,validation:{endsWith:w.value},message:w.message}),b.dirty()):w.kind==="datetime"?datetimeRegex(w).test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.invalid_string,validation:"datetime",message:w.message}),b.dirty()):w.kind==="date"?dateRegex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.invalid_string,validation:"date",message:w.message}),b.dirty()):w.kind==="time"?timeRegex(w).test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.invalid_string,validation:"time",message:w.message}),b.dirty()):w.kind==="duration"?durationRegex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"duration",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty()):w.kind==="ip"?isValidIP(u.data,w.version)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"ip",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty()):w.kind==="jwt"?isValidJWT(u.data,w.alg)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"jwt",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty()):w.kind==="cidr"?isValidCidr(u.data,w.version)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"cidr",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty()):w.kind==="base64"?base64Regex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"base64",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty()):w.kind==="base64url"?base64urlRegex.test(u.data)||(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{validation:"base64url",code:ZodIssueCode.invalid_string,message:w.message}),b.dirty()):util$c.assertNever(w);return{status:b.value,value:u.data}}_regex(u,h,b){return this.refinement(v=>u.test(v),{validation:h,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(b)})}_addCheck(u){return new ZodString({...this._def,checks:[...this._def.checks,u]})}email(u){return this._addCheck({kind:"email",...errorUtil.errToObj(u)})}url(u){return this._addCheck({kind:"url",...errorUtil.errToObj(u)})}emoji(u){return this._addCheck({kind:"emoji",...errorUtil.errToObj(u)})}uuid(u){return this._addCheck({kind:"uuid",...errorUtil.errToObj(u)})}nanoid(u){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(u)})}cuid(u){return this._addCheck({kind:"cuid",...errorUtil.errToObj(u)})}cuid2(u){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(u)})}ulid(u){return this._addCheck({kind:"ulid",...errorUtil.errToObj(u)})}base64(u){return this._addCheck({kind:"base64",...errorUtil.errToObj(u)})}base64url(u){return this._addCheck({kind:"base64url",...errorUtil.errToObj(u)})}jwt(u){return this._addCheck({kind:"jwt",...errorUtil.errToObj(u)})}ip(u){return this._addCheck({kind:"ip",...errorUtil.errToObj(u)})}cidr(u){return this._addCheck({kind:"cidr",...errorUtil.errToObj(u)})}datetime(u){var h,b;return typeof u=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:u}):this._addCheck({kind:"datetime",precision:typeof(u==null?void 0:u.precision)>"u"?null:u==null?void 0:u.precision,offset:(h=u==null?void 0:u.offset)!==null&&h!==void 0?h:!1,local:(b=u==null?void 0:u.local)!==null&&b!==void 0?b:!1,...errorUtil.errToObj(u==null?void 0:u.message)})}date(u){return this._addCheck({kind:"date",message:u})}time(u){return typeof u=="string"?this._addCheck({kind:"time",precision:null,message:u}):this._addCheck({kind:"time",precision:typeof(u==null?void 0:u.precision)>"u"?null:u==null?void 0:u.precision,...errorUtil.errToObj(u==null?void 0:u.message)})}duration(u){return this._addCheck({kind:"duration",...errorUtil.errToObj(u)})}regex(u,h){return this._addCheck({kind:"regex",regex:u,...errorUtil.errToObj(h)})}includes(u,h){return this._addCheck({kind:"includes",value:u,position:h==null?void 0:h.position,...errorUtil.errToObj(h==null?void 0:h.message)})}startsWith(u,h){return this._addCheck({kind:"startsWith",value:u,...errorUtil.errToObj(h)})}endsWith(u,h){return this._addCheck({kind:"endsWith",value:u,...errorUtil.errToObj(h)})}min(u,h){return this._addCheck({kind:"min",value:u,...errorUtil.errToObj(h)})}max(u,h){return this._addCheck({kind:"max",value:u,...errorUtil.errToObj(h)})}length(u,h){return this._addCheck({kind:"length",value:u,...errorUtil.errToObj(h)})}nonempty(u){return this.min(1,errorUtil.errToObj(u))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(u=>u.kind==="datetime")}get isDate(){return!!this._def.checks.find(u=>u.kind==="date")}get isTime(){return!!this._def.checks.find(u=>u.kind==="time")}get isDuration(){return!!this._def.checks.find(u=>u.kind==="duration")}get isEmail(){return!!this._def.checks.find(u=>u.kind==="email")}get isURL(){return!!this._def.checks.find(u=>u.kind==="url")}get isEmoji(){return!!this._def.checks.find(u=>u.kind==="emoji")}get isUUID(){return!!this._def.checks.find(u=>u.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(u=>u.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(u=>u.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(u=>u.kind==="cuid2")}get isULID(){return!!this._def.checks.find(u=>u.kind==="ulid")}get isIP(){return!!this._def.checks.find(u=>u.kind==="ip")}get isCIDR(){return!!this._def.checks.find(u=>u.kind==="cidr")}get isBase64(){return!!this._def.checks.find(u=>u.kind==="base64")}get isBase64url(){return!!this._def.checks.find(u=>u.kind==="base64url")}get minLength(){let u=null;for(const h of this._def.checks)h.kind==="min"&&(u===null||h.value>u)&&(u=h.value);return u}get maxLength(){let u=null;for(const h of this._def.checks)h.kind==="max"&&(u===null||h.value<u)&&(u=h.value);return u}}ZodString.create=y=>{var u;return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:(u=y==null?void 0:y.coerce)!==null&&u!==void 0?u:!1,...processCreateParams(y)})};function floatSafeRemainder(y,u){const h=(y.toString().split(".")[1]||"").length,b=(u.toString().split(".")[1]||"").length,v=h>b?h:b,w=parseInt(y.toFixed(v).replace(".","")),_=parseInt(u.toFixed(v).replace(".",""));return w%_/Math.pow(10,v)}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(u){if(this._def.coerce&&(u.data=Number(u.data)),this._getType(u)!==ZodParsedType.number){const w=this._getOrReturnCtx(u);return addIssueToContext(w,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:w.parsedType}),INVALID}let b;const v=new ParseStatus;for(const w of this._def.checks)w.kind==="int"?util$c.isInteger(u.data)||(b=this._getOrReturnCtx(u,b),addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:w.message}),v.dirty()):w.kind==="min"?(w.inclusive?u.data<w.value:u.data<=w.value)&&(b=this._getOrReturnCtx(u,b),addIssueToContext(b,{code:ZodIssueCode.too_small,minimum:w.value,type:"number",inclusive:w.inclusive,exact:!1,message:w.message}),v.dirty()):w.kind==="max"?(w.inclusive?u.data>w.value:u.data>=w.value)&&(b=this._getOrReturnCtx(u,b),addIssueToContext(b,{code:ZodIssueCode.too_big,maximum:w.value,type:"number",inclusive:w.inclusive,exact:!1,message:w.message}),v.dirty()):w.kind==="multipleOf"?floatSafeRemainder(u.data,w.value)!==0&&(b=this._getOrReturnCtx(u,b),addIssueToContext(b,{code:ZodIssueCode.not_multiple_of,multipleOf:w.value,message:w.message}),v.dirty()):w.kind==="finite"?Number.isFinite(u.data)||(b=this._getOrReturnCtx(u,b),addIssueToContext(b,{code:ZodIssueCode.not_finite,message:w.message}),v.dirty()):util$c.assertNever(w);return{status:v.value,value:u.data}}gte(u,h){return this.setLimit("min",u,!0,errorUtil.toString(h))}gt(u,h){return this.setLimit("min",u,!1,errorUtil.toString(h))}lte(u,h){return this.setLimit("max",u,!0,errorUtil.toString(h))}lt(u,h){return this.setLimit("max",u,!1,errorUtil.toString(h))}setLimit(u,h,b,v){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:u,value:h,inclusive:b,message:errorUtil.toString(v)}]})}_addCheck(u){return new ZodNumber({...this._def,checks:[...this._def.checks,u]})}int(u){return this._addCheck({kind:"int",message:errorUtil.toString(u)})}positive(u){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(u)})}negative(u){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(u)})}nonpositive(u){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(u)})}nonnegative(u){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(u)})}multipleOf(u,h){return this._addCheck({kind:"multipleOf",value:u,message:errorUtil.toString(h)})}finite(u){return this._addCheck({kind:"finite",message:errorUtil.toString(u)})}safe(u){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(u)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(u)})}get minValue(){let u=null;for(const h of this._def.checks)h.kind==="min"&&(u===null||h.value>u)&&(u=h.value);return u}get maxValue(){let u=null;for(const h of this._def.checks)h.kind==="max"&&(u===null||h.value<u)&&(u=h.value);return u}get isInt(){return!!this._def.checks.find(u=>u.kind==="int"||u.kind==="multipleOf"&&util$c.isInteger(u.value))}get isFinite(){let u=null,h=null;for(const b of this._def.checks){if(b.kind==="finite"||b.kind==="int"||b.kind==="multipleOf")return!0;b.kind==="min"?(h===null||b.value>h)&&(h=b.value):b.kind==="max"&&(u===null||b.value<u)&&(u=b.value)}return Number.isFinite(h)&&Number.isFinite(u)}}ZodNumber.create=y=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:(y==null?void 0:y.coerce)||!1,...processCreateParams(y)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(u){if(this._def.coerce)try{u.data=BigInt(u.data)}catch{return this._getInvalidInput(u)}if(this._getType(u)!==ZodParsedType.bigint)return this._getInvalidInput(u);let b;const v=new ParseStatus;for(const w of this._def.checks)w.kind==="min"?(w.inclusive?u.data<w.value:u.data<=w.value)&&(b=this._getOrReturnCtx(u,b),addIssueToContext(b,{code:ZodIssueCode.too_small,type:"bigint",minimum:w.value,inclusive:w.inclusive,message:w.message}),v.dirty()):w.kind==="max"?(w.inclusive?u.data>w.value:u.data>=w.value)&&(b=this._getOrReturnCtx(u,b),addIssueToContext(b,{code:ZodIssueCode.too_big,type:"bigint",maximum:w.value,inclusive:w.inclusive,message:w.message}),v.dirty()):w.kind==="multipleOf"?u.data%w.value!==BigInt(0)&&(b=this._getOrReturnCtx(u,b),addIssueToContext(b,{code:ZodIssueCode.not_multiple_of,multipleOf:w.value,message:w.message}),v.dirty()):util$c.assertNever(w);return{status:v.value,value:u.data}}_getInvalidInput(u){const h=this._getOrReturnCtx(u);return addIssueToContext(h,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:h.parsedType}),INVALID}gte(u,h){return this.setLimit("min",u,!0,errorUtil.toString(h))}gt(u,h){return this.setLimit("min",u,!1,errorUtil.toString(h))}lte(u,h){return this.setLimit("max",u,!0,errorUtil.toString(h))}lt(u,h){return this.setLimit("max",u,!1,errorUtil.toString(h))}setLimit(u,h,b,v){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:u,value:h,inclusive:b,message:errorUtil.toString(v)}]})}_addCheck(u){return new ZodBigInt({...this._def,checks:[...this._def.checks,u]})}positive(u){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(u)})}negative(u){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(u)})}nonpositive(u){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(u)})}nonnegative(u){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(u)})}multipleOf(u,h){return this._addCheck({kind:"multipleOf",value:u,message:errorUtil.toString(h)})}get minValue(){let u=null;for(const h of this._def.checks)h.kind==="min"&&(u===null||h.value>u)&&(u=h.value);return u}get maxValue(){let u=null;for(const h of this._def.checks)h.kind==="max"&&(u===null||h.value<u)&&(u=h.value);return u}}ZodBigInt.create=y=>{var u;return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:(u=y==null?void 0:y.coerce)!==null&&u!==void 0?u:!1,...processCreateParams(y)})};class ZodBoolean extends ZodType{_parse(u){if(this._def.coerce&&(u.data=!!u.data),this._getType(u)!==ZodParsedType.boolean){const b=this._getOrReturnCtx(u);return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:b.parsedType}),INVALID}return OK(u.data)}}ZodBoolean.create=y=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:(y==null?void 0:y.coerce)||!1,...processCreateParams(y)});class ZodDate extends ZodType{_parse(u){if(this._def.coerce&&(u.data=new Date(u.data)),this._getType(u)!==ZodParsedType.date){const w=this._getOrReturnCtx(u);return addIssueToContext(w,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:w.parsedType}),INVALID}if(isNaN(u.data.getTime())){const w=this._getOrReturnCtx(u);return addIssueToContext(w,{code:ZodIssueCode.invalid_date}),INVALID}const b=new ParseStatus;let v;for(const w of this._def.checks)w.kind==="min"?u.data.getTime()<w.value&&(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.too_small,message:w.message,inclusive:!0,exact:!1,minimum:w.value,type:"date"}),b.dirty()):w.kind==="max"?u.data.getTime()>w.value&&(v=this._getOrReturnCtx(u,v),addIssueToContext(v,{code:ZodIssueCode.too_big,message:w.message,inclusive:!0,exact:!1,maximum:w.value,type:"date"}),b.dirty()):util$c.assertNever(w);return{status:b.value,value:new Date(u.data.getTime())}}_addCheck(u){return new ZodDate({...this._def,checks:[...this._def.checks,u]})}min(u,h){return this._addCheck({kind:"min",value:u.getTime(),message:errorUtil.toString(h)})}max(u,h){return this._addCheck({kind:"max",value:u.getTime(),message:errorUtil.toString(h)})}get minDate(){let u=null;for(const h of this._def.checks)h.kind==="min"&&(u===null||h.value>u)&&(u=h.value);return u!=null?new Date(u):null}get maxDate(){let u=null;for(const h of this._def.checks)h.kind==="max"&&(u===null||h.value<u)&&(u=h.value);return u!=null?new Date(u):null}}ZodDate.create=y=>new ZodDate({checks:[],coerce:(y==null?void 0:y.coerce)||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(y)});class ZodSymbol extends ZodType{_parse(u){if(this._getType(u)!==ZodParsedType.symbol){const b=this._getOrReturnCtx(u);return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:b.parsedType}),INVALID}return OK(u.data)}}ZodSymbol.create=y=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(y)});class ZodUndefined extends ZodType{_parse(u){if(this._getType(u)!==ZodParsedType.undefined){const b=this._getOrReturnCtx(u);return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:b.parsedType}),INVALID}return OK(u.data)}}ZodUndefined.create=y=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(y)});class ZodNull extends ZodType{_parse(u){if(this._getType(u)!==ZodParsedType.null){const b=this._getOrReturnCtx(u);return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:b.parsedType}),INVALID}return OK(u.data)}}ZodNull.create=y=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(y)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(u){return OK(u.data)}}ZodAny.create=y=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(y)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(u){return OK(u.data)}}ZodUnknown.create=y=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(y)});class ZodNever extends ZodType{_parse(u){const h=this._getOrReturnCtx(u);return addIssueToContext(h,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:h.parsedType}),INVALID}}ZodNever.create=y=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(y)});class ZodVoid extends ZodType{_parse(u){if(this._getType(u)!==ZodParsedType.undefined){const b=this._getOrReturnCtx(u);return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:b.parsedType}),INVALID}return OK(u.data)}}ZodVoid.create=y=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(y)});class ZodArray extends ZodType{_parse(u){const{ctx:h,status:b}=this._processInputParams(u),v=this._def;if(h.parsedType!==ZodParsedType.array)return addIssueToContext(h,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:h.parsedType}),INVALID;if(v.exactLength!==null){const _=h.data.length>v.exactLength.value,E=h.data.length<v.exactLength.value;(_||E)&&(addIssueToContext(h,{code:_?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:E?v.exactLength.value:void 0,maximum:_?v.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:v.exactLength.message}),b.dirty())}if(v.minLength!==null&&h.data.length<v.minLength.value&&(addIssueToContext(h,{code:ZodIssueCode.too_small,minimum:v.minLength.value,type:"array",inclusive:!0,exact:!1,message:v.minLength.message}),b.dirty()),v.maxLength!==null&&h.data.length>v.maxLength.value&&(addIssueToContext(h,{code:ZodIssueCode.too_big,maximum:v.maxLength.value,type:"array",inclusive:!0,exact:!1,message:v.maxLength.message}),b.dirty()),h.common.async)return Promise.all([...h.data].map((_,E)=>v.type._parseAsync(new ParseInputLazyPath(h,_,h.path,E)))).then(_=>ParseStatus.mergeArray(b,_));const w=[...h.data].map((_,E)=>v.type._parseSync(new ParseInputLazyPath(h,_,h.path,E)));return ParseStatus.mergeArray(b,w)}get element(){return this._def.type}min(u,h){return new ZodArray({...this._def,minLength:{value:u,message:errorUtil.toString(h)}})}max(u,h){return new ZodArray({...this._def,maxLength:{value:u,message:errorUtil.toString(h)}})}length(u,h){return new ZodArray({...this._def,exactLength:{value:u,message:errorUtil.toString(h)}})}nonempty(u){return this.min(1,u)}}ZodArray.create=(y,u)=>new ZodArray({type:y,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(u)});function deepPartialify(y){if(y instanceof ZodObject){const u={};for(const h in y.shape){const b=y.shape[h];u[h]=ZodOptional.create(deepPartialify(b))}return new ZodObject({...y._def,shape:()=>u})}else return y instanceof ZodArray?new ZodArray({...y._def,type:deepPartialify(y.element)}):y instanceof ZodOptional?ZodOptional.create(deepPartialify(y.unwrap())):y instanceof ZodNullable?ZodNullable.create(deepPartialify(y.unwrap())):y instanceof ZodTuple?ZodTuple.create(y.items.map(u=>deepPartialify(u))):y}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const u=this._def.shape(),h=util$c.objectKeys(u);return this._cached={shape:u,keys:h}}_parse(u){if(this._getType(u)!==ZodParsedType.object){const x=this._getOrReturnCtx(u);return addIssueToContext(x,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:x.parsedType}),INVALID}const{status:b,ctx:v}=this._processInputParams(u),{shape:w,keys:_}=this._getCached(),E=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const x in v.data)_.includes(x)||E.push(x);const S=[];for(const x of _){const T=w[x],C=v.data[x];S.push({key:{status:"valid",value:x},value:T._parse(new ParseInputLazyPath(v,C,v.path,x)),alwaysSet:x in v.data})}if(this._def.catchall instanceof ZodNever){const x=this._def.unknownKeys;if(x==="passthrough")for(const T of E)S.push({key:{status:"valid",value:T},value:{status:"valid",value:v.data[T]}});else if(x==="strict")E.length>0&&(addIssueToContext(v,{code:ZodIssueCode.unrecognized_keys,keys:E}),b.dirty());else if(x!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const x=this._def.catchall;for(const T of E){const C=v.data[T];S.push({key:{status:"valid",value:T},value:x._parse(new ParseInputLazyPath(v,C,v.path,T)),alwaysSet:T in v.data})}}return v.common.async?Promise.resolve().then(async()=>{const x=[];for(const T of S){const C=await T.key,O=await T.value;x.push({key:C,value:O,alwaysSet:T.alwaysSet})}return x}).then(x=>ParseStatus.mergeObjectSync(b,x)):ParseStatus.mergeObjectSync(b,S)}get shape(){return this._def.shape()}strict(u){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...u!==void 0?{errorMap:(h,b)=>{var v,w,_,E;const S=(_=(w=(v=this._def).errorMap)===null||w===void 0?void 0:w.call(v,h,b).message)!==null&&_!==void 0?_:b.defaultError;return h.code==="unrecognized_keys"?{message:(E=errorUtil.errToObj(u).message)!==null&&E!==void 0?E:S}:{message:S}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(u){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...u})})}merge(u){return new ZodObject({unknownKeys:u._def.unknownKeys,catchall:u._def.catchall,shape:()=>({...this._def.shape(),...u._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(u,h){return this.augment({[u]:h})}catchall(u){return new ZodObject({...this._def,catchall:u})}pick(u){const h={};return util$c.objectKeys(u).forEach(b=>{u[b]&&this.shape[b]&&(h[b]=this.shape[b])}),new ZodObject({...this._def,shape:()=>h})}omit(u){const h={};return util$c.objectKeys(this.shape).forEach(b=>{u[b]||(h[b]=this.shape[b])}),new ZodObject({...this._def,shape:()=>h})}deepPartial(){return deepPartialify(this)}partial(u){const h={};return util$c.objectKeys(this.shape).forEach(b=>{const v=this.shape[b];u&&!u[b]?h[b]=v:h[b]=v.optional()}),new ZodObject({...this._def,shape:()=>h})}required(u){const h={};return util$c.objectKeys(this.shape).forEach(b=>{if(u&&!u[b])h[b]=this.shape[b];else{let w=this.shape[b];for(;w instanceof ZodOptional;)w=w._def.innerType;h[b]=w}}),new ZodObject({...this._def,shape:()=>h})}keyof(){return createZodEnum(util$c.objectKeys(this.shape))}}ZodObject.create=(y,u)=>new ZodObject({shape:()=>y,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(u)});ZodObject.strictCreate=(y,u)=>new ZodObject({shape:()=>y,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(u)});ZodObject.lazycreate=(y,u)=>new ZodObject({shape:y,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(u)});class ZodUnion extends ZodType{_parse(u){const{ctx:h}=this._processInputParams(u),b=this._def.options;function v(w){for(const E of w)if(E.result.status==="valid")return E.result;for(const E of w)if(E.result.status==="dirty")return h.common.issues.push(...E.ctx.common.issues),E.result;const _=w.map(E=>new ZodError(E.ctx.common.issues));return addIssueToContext(h,{code:ZodIssueCode.invalid_union,unionErrors:_}),INVALID}if(h.common.async)return Promise.all(b.map(async w=>{const _={...h,common:{...h.common,issues:[]},parent:null};return{result:await w._parseAsync({data:h.data,path:h.path,parent:_}),ctx:_}})).then(v);{let w;const _=[];for(const S of b){const x={...h,common:{...h.common,issues:[]},parent:null},T=S._parseSync({data:h.data,path:h.path,parent:x});if(T.status==="valid")return T;T.status==="dirty"&&!w&&(w={result:T,ctx:x}),x.common.issues.length&&_.push(x.common.issues)}if(w)return h.common.issues.push(...w.ctx.common.issues),w.result;const E=_.map(S=>new ZodError(S));return addIssueToContext(h,{code:ZodIssueCode.invalid_union,unionErrors:E}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(y,u)=>new ZodUnion({options:y,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(u)});const getDiscriminator=y=>y instanceof ZodLazy?getDiscriminator(y.schema):y instanceof ZodEffects?getDiscriminator(y.innerType()):y instanceof ZodLiteral?[y.value]:y instanceof ZodEnum?y.options:y instanceof ZodNativeEnum?util$c.objectValues(y.enum):y instanceof ZodDefault?getDiscriminator(y._def.innerType):y instanceof ZodUndefined?[void 0]:y instanceof ZodNull?[null]:y instanceof ZodOptional?[void 0,...getDiscriminator(y.unwrap())]:y instanceof ZodNullable?[null,...getDiscriminator(y.unwrap())]:y instanceof ZodBranded||y instanceof ZodReadonly?getDiscriminator(y.unwrap()):y instanceof ZodCatch?getDiscriminator(y._def.innerType):[];class ZodDiscriminatedUnion extends ZodType{_parse(u){const{ctx:h}=this._processInputParams(u);if(h.parsedType!==ZodParsedType.object)return addIssueToContext(h,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:h.parsedType}),INVALID;const b=this.discriminator,v=h.data[b],w=this.optionsMap.get(v);return w?h.common.async?w._parseAsync({data:h.data,path:h.path,parent:h}):w._parseSync({data:h.data,path:h.path,parent:h}):(addIssueToContext(h,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[b]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(u,h,b){const v=new Map;for(const w of h){const _=getDiscriminator(w.shape[u]);if(!_.length)throw new Error(`A discriminator value for key \`${u}\` could not be extracted from all schema options`);for(const E of _){if(v.has(E))throw new Error(`Discriminator property ${String(u)} has duplicate value ${String(E)}`);v.set(E,w)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:u,options:h,optionsMap:v,...processCreateParams(b)})}}function mergeValues(y,u){const h=getParsedType(y),b=getParsedType(u);if(y===u)return{valid:!0,data:y};if(h===ZodParsedType.object&&b===ZodParsedType.object){const v=util$c.objectKeys(u),w=util$c.objectKeys(y).filter(E=>v.indexOf(E)!==-1),_={...y,...u};for(const E of w){const S=mergeValues(y[E],u[E]);if(!S.valid)return{valid:!1};_[E]=S.data}return{valid:!0,data:_}}else if(h===ZodParsedType.array&&b===ZodParsedType.array){if(y.length!==u.length)return{valid:!1};const v=[];for(let w=0;w<y.length;w++){const _=y[w],E=u[w],S=mergeValues(_,E);if(!S.valid)return{valid:!1};v.push(S.data)}return{valid:!0,data:v}}else return h===ZodParsedType.date&&b===ZodParsedType.date&&+y==+u?{valid:!0,data:y}:{valid:!1}}class ZodIntersection extends ZodType{_parse(u){const{status:h,ctx:b}=this._processInputParams(u),v=(w,_)=>{if(isAborted(w)||isAborted(_))return INVALID;const E=mergeValues(w.value,_.value);return E.valid?((isDirty(w)||isDirty(_))&&h.dirty(),{status:h.value,value:E.data}):(addIssueToContext(b,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return b.common.async?Promise.all([this._def.left._parseAsync({data:b.data,path:b.path,parent:b}),this._def.right._parseAsync({data:b.data,path:b.path,parent:b})]).then(([w,_])=>v(w,_)):v(this._def.left._parseSync({data:b.data,path:b.path,parent:b}),this._def.right._parseSync({data:b.data,path:b.path,parent:b}))}}ZodIntersection.create=(y,u,h)=>new ZodIntersection({left:y,right:u,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(h)});class ZodTuple extends ZodType{_parse(u){const{status:h,ctx:b}=this._processInputParams(u);if(b.parsedType!==ZodParsedType.array)return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:b.parsedType}),INVALID;if(b.data.length<this._def.items.length)return addIssueToContext(b,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&b.data.length>this._def.items.length&&(addIssueToContext(b,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),h.dirty());const w=[...b.data].map((_,E)=>{const S=this._def.items[E]||this._def.rest;return S?S._parse(new ParseInputLazyPath(b,_,b.path,E)):null}).filter(_=>!!_);return b.common.async?Promise.all(w).then(_=>ParseStatus.mergeArray(h,_)):ParseStatus.mergeArray(h,w)}get items(){return this._def.items}rest(u){return new ZodTuple({...this._def,rest:u})}}ZodTuple.create=(y,u)=>{if(!Array.isArray(y))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:y,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(u)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(u){const{status:h,ctx:b}=this._processInputParams(u);if(b.parsedType!==ZodParsedType.object)return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:b.parsedType}),INVALID;const v=[],w=this._def.keyType,_=this._def.valueType;for(const E in b.data)v.push({key:w._parse(new ParseInputLazyPath(b,E,b.path,E)),value:_._parse(new ParseInputLazyPath(b,b.data[E],b.path,E)),alwaysSet:E in b.data});return b.common.async?ParseStatus.mergeObjectAsync(h,v):ParseStatus.mergeObjectSync(h,v)}get element(){return this._def.valueType}static create(u,h,b){return h instanceof ZodType?new ZodRecord({keyType:u,valueType:h,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(b)}):new ZodRecord({keyType:ZodString.create(),valueType:u,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(h)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(u){const{status:h,ctx:b}=this._processInputParams(u);if(b.parsedType!==ZodParsedType.map)return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:b.parsedType}),INVALID;const v=this._def.keyType,w=this._def.valueType,_=[...b.data.entries()].map(([E,S],x)=>({key:v._parse(new ParseInputLazyPath(b,E,b.path,[x,"key"])),value:w._parse(new ParseInputLazyPath(b,S,b.path,[x,"value"]))}));if(b.common.async){const E=new Map;return Promise.resolve().then(async()=>{for(const S of _){const x=await S.key,T=await S.value;if(x.status==="aborted"||T.status==="aborted")return INVALID;(x.status==="dirty"||T.status==="dirty")&&h.dirty(),E.set(x.value,T.value)}return{status:h.value,value:E}})}else{const E=new Map;for(const S of _){const x=S.key,T=S.value;if(x.status==="aborted"||T.status==="aborted")return INVALID;(x.status==="dirty"||T.status==="dirty")&&h.dirty(),E.set(x.value,T.value)}return{status:h.value,value:E}}}}ZodMap.create=(y,u,h)=>new ZodMap({valueType:u,keyType:y,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(h)});class ZodSet extends ZodType{_parse(u){const{status:h,ctx:b}=this._processInputParams(u);if(b.parsedType!==ZodParsedType.set)return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:b.parsedType}),INVALID;const v=this._def;v.minSize!==null&&b.data.size<v.minSize.value&&(addIssueToContext(b,{code:ZodIssueCode.too_small,minimum:v.minSize.value,type:"set",inclusive:!0,exact:!1,message:v.minSize.message}),h.dirty()),v.maxSize!==null&&b.data.size>v.maxSize.value&&(addIssueToContext(b,{code:ZodIssueCode.too_big,maximum:v.maxSize.value,type:"set",inclusive:!0,exact:!1,message:v.maxSize.message}),h.dirty());const w=this._def.valueType;function _(S){const x=new Set;for(const T of S){if(T.status==="aborted")return INVALID;T.status==="dirty"&&h.dirty(),x.add(T.value)}return{status:h.value,value:x}}const E=[...b.data.values()].map((S,x)=>w._parse(new ParseInputLazyPath(b,S,b.path,x)));return b.common.async?Promise.all(E).then(S=>_(S)):_(E)}min(u,h){return new ZodSet({...this._def,minSize:{value:u,message:errorUtil.toString(h)}})}max(u,h){return new ZodSet({...this._def,maxSize:{value:u,message:errorUtil.toString(h)}})}size(u,h){return this.min(u,h).max(u,h)}nonempty(u){return this.min(1,u)}}ZodSet.create=(y,u)=>new ZodSet({valueType:y,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(u)});class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(u){const{ctx:h}=this._processInputParams(u);if(h.parsedType!==ZodParsedType.function)return addIssueToContext(h,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:h.parsedType}),INVALID;function b(E,S){return makeIssue({data:E,path:h.path,errorMaps:[h.common.contextualErrorMap,h.schemaErrorMap,getErrorMap(),errorMap].filter(x=>!!x),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:S}})}function v(E,S){return makeIssue({data:E,path:h.path,errorMaps:[h.common.contextualErrorMap,h.schemaErrorMap,getErrorMap(),errorMap].filter(x=>!!x),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:S}})}const w={errorMap:h.common.contextualErrorMap},_=h.data;if(this._def.returns instanceof ZodPromise){const E=this;return OK(async function(...S){const x=new ZodError([]),T=await E._def.args.parseAsync(S,w).catch(D=>{throw x.addIssue(b(S,D)),x}),C=await Reflect.apply(_,this,T);return await E._def.returns._def.type.parseAsync(C,w).catch(D=>{throw x.addIssue(v(C,D)),x})})}else{const E=this;return OK(function(...S){const x=E._def.args.safeParse(S,w);if(!x.success)throw new ZodError([b(S,x.error)]);const T=Reflect.apply(_,this,x.data),C=E._def.returns.safeParse(T,w);if(!C.success)throw new ZodError([v(T,C.error)]);return C.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...u){return new ZodFunction({...this._def,args:ZodTuple.create(u).rest(ZodUnknown.create())})}returns(u){return new ZodFunction({...this._def,returns:u})}implement(u){return this.parse(u)}strictImplement(u){return this.parse(u)}static create(u,h,b){return new ZodFunction({args:u||ZodTuple.create([]).rest(ZodUnknown.create()),returns:h||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(b)})}}class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(u){const{ctx:h}=this._processInputParams(u);return this._def.getter()._parse({data:h.data,path:h.path,parent:h})}}ZodLazy.create=(y,u)=>new ZodLazy({getter:y,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(u)});class ZodLiteral extends ZodType{_parse(u){if(u.data!==this._def.value){const h=this._getOrReturnCtx(u);return addIssueToContext(h,{received:h.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:u.data}}get value(){return this._def.value}}ZodLiteral.create=(y,u)=>new ZodLiteral({value:y,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(u)});function createZodEnum(y,u){return new ZodEnum({values:y,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(u)})}class ZodEnum extends ZodType{constructor(){super(...arguments),_ZodEnum_cache.set(this,void 0)}_parse(u){if(typeof u.data!="string"){const h=this._getOrReturnCtx(u),b=this._def.values;return addIssueToContext(h,{expected:util$c.joinValues(b),received:h.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodEnum_cache)||__classPrivateFieldSet(this,_ZodEnum_cache,new Set(this._def.values)),!__classPrivateFieldGet(this,_ZodEnum_cache).has(u.data)){const h=this._getOrReturnCtx(u),b=this._def.values;return addIssueToContext(h,{received:h.data,code:ZodIssueCode.invalid_enum_value,options:b}),INVALID}return OK(u.data)}get options(){return this._def.values}get enum(){const u={};for(const h of this._def.values)u[h]=h;return u}get Values(){const u={};for(const h of this._def.values)u[h]=h;return u}get Enum(){const u={};for(const h of this._def.values)u[h]=h;return u}extract(u,h=this._def){return ZodEnum.create(u,{...this._def,...h})}exclude(u,h=this._def){return ZodEnum.create(this.options.filter(b=>!u.includes(b)),{...this._def,...h})}}_ZodEnum_cache=new WeakMap;ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{constructor(){super(...arguments),_ZodNativeEnum_cache.set(this,void 0)}_parse(u){const h=util$c.getValidEnumValues(this._def.values),b=this._getOrReturnCtx(u);if(b.parsedType!==ZodParsedType.string&&b.parsedType!==ZodParsedType.number){const v=util$c.objectValues(h);return addIssueToContext(b,{expected:util$c.joinValues(v),received:b.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodNativeEnum_cache)||__classPrivateFieldSet(this,_ZodNativeEnum_cache,new Set(util$c.getValidEnumValues(this._def.values))),!__classPrivateFieldGet(this,_ZodNativeEnum_cache).has(u.data)){const v=util$c.objectValues(h);return addIssueToContext(b,{received:b.data,code:ZodIssueCode.invalid_enum_value,options:v}),INVALID}return OK(u.data)}get enum(){return this._def.values}}_ZodNativeEnum_cache=new WeakMap;ZodNativeEnum.create=(y,u)=>new ZodNativeEnum({values:y,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(u)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(u){const{ctx:h}=this._processInputParams(u);if(h.parsedType!==ZodParsedType.promise&&h.common.async===!1)return addIssueToContext(h,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:h.parsedType}),INVALID;const b=h.parsedType===ZodParsedType.promise?h.data:Promise.resolve(h.data);return OK(b.then(v=>this._def.type.parseAsync(v,{path:h.path,errorMap:h.common.contextualErrorMap})))}}ZodPromise.create=(y,u)=>new ZodPromise({type:y,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(u)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(u){const{status:h,ctx:b}=this._processInputParams(u),v=this._def.effect||null,w={addIssue:_=>{addIssueToContext(b,_),_.fatal?h.abort():h.dirty()},get path(){return b.path}};if(w.addIssue=w.addIssue.bind(w),v.type==="preprocess"){const _=v.transform(b.data,w);if(b.common.async)return Promise.resolve(_).then(async E=>{if(h.value==="aborted")return INVALID;const S=await this._def.schema._parseAsync({data:E,path:b.path,parent:b});return S.status==="aborted"?INVALID:S.status==="dirty"||h.value==="dirty"?DIRTY(S.value):S});{if(h.value==="aborted")return INVALID;const E=this._def.schema._parseSync({data:_,path:b.path,parent:b});return E.status==="aborted"?INVALID:E.status==="dirty"||h.value==="dirty"?DIRTY(E.value):E}}if(v.type==="refinement"){const _=E=>{const S=v.refinement(E,w);if(b.common.async)return Promise.resolve(S);if(S instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return E};if(b.common.async===!1){const E=this._def.schema._parseSync({data:b.data,path:b.path,parent:b});return E.status==="aborted"?INVALID:(E.status==="dirty"&&h.dirty(),_(E.value),{status:h.value,value:E.value})}else return this._def.schema._parseAsync({data:b.data,path:b.path,parent:b}).then(E=>E.status==="aborted"?INVALID:(E.status==="dirty"&&h.dirty(),_(E.value).then(()=>({status:h.value,value:E.value}))))}if(v.type==="transform")if(b.common.async===!1){const _=this._def.schema._parseSync({data:b.data,path:b.path,parent:b});if(!isValid(_))return _;const E=v.transform(_.value,w);if(E instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:h.value,value:E}}else return this._def.schema._parseAsync({data:b.data,path:b.path,parent:b}).then(_=>isValid(_)?Promise.resolve(v.transform(_.value,w)).then(E=>({status:h.value,value:E})):_);util$c.assertNever(v)}}ZodEffects.create=(y,u,h)=>new ZodEffects({schema:y,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:u,...processCreateParams(h)});ZodEffects.createWithPreprocess=(y,u,h)=>new ZodEffects({schema:u,effect:{type:"preprocess",transform:y},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(h)});class ZodOptional extends ZodType{_parse(u){return this._getType(u)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(u)}unwrap(){return this._def.innerType}}ZodOptional.create=(y,u)=>new ZodOptional({innerType:y,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(u)});class ZodNullable extends ZodType{_parse(u){return this._getType(u)===ZodParsedType.null?OK(null):this._def.innerType._parse(u)}unwrap(){return this._def.innerType}}ZodNullable.create=(y,u)=>new ZodNullable({innerType:y,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(u)});class ZodDefault extends ZodType{_parse(u){const{ctx:h}=this._processInputParams(u);let b=h.data;return h.parsedType===ZodParsedType.undefined&&(b=this._def.defaultValue()),this._def.innerType._parse({data:b,path:h.path,parent:h})}removeDefault(){return this._def.innerType}}ZodDefault.create=(y,u)=>new ZodDefault({innerType:y,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof u.default=="function"?u.default:()=>u.default,...processCreateParams(u)});class ZodCatch extends ZodType{_parse(u){const{ctx:h}=this._processInputParams(u),b={...h,common:{...h.common,issues:[]}},v=this._def.innerType._parse({data:b.data,path:b.path,parent:{...b}});return isAsync(v)?v.then(w=>({status:"valid",value:w.status==="valid"?w.value:this._def.catchValue({get error(){return new ZodError(b.common.issues)},input:b.data})})):{status:"valid",value:v.status==="valid"?v.value:this._def.catchValue({get error(){return new ZodError(b.common.issues)},input:b.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(y,u)=>new ZodCatch({innerType:y,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof u.catch=="function"?u.catch:()=>u.catch,...processCreateParams(u)});class ZodNaN extends ZodType{_parse(u){if(this._getType(u)!==ZodParsedType.nan){const b=this._getOrReturnCtx(u);return addIssueToContext(b,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:b.parsedType}),INVALID}return{status:"valid",value:u.data}}}ZodNaN.create=y=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(y)});const BRAND=Symbol("zod_brand");class ZodBranded extends ZodType{_parse(u){const{ctx:h}=this._processInputParams(u),b=h.data;return this._def.type._parse({data:b,path:h.path,parent:h})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(u){const{status:h,ctx:b}=this._processInputParams(u);if(b.common.async)return(async()=>{const w=await this._def.in._parseAsync({data:b.data,path:b.path,parent:b});return w.status==="aborted"?INVALID:w.status==="dirty"?(h.dirty(),DIRTY(w.value)):this._def.out._parseAsync({data:w.value,path:b.path,parent:b})})();{const v=this._def.in._parseSync({data:b.data,path:b.path,parent:b});return v.status==="aborted"?INVALID:v.status==="dirty"?(h.dirty(),{status:"dirty",value:v.value}):this._def.out._parseSync({data:v.value,path:b.path,parent:b})}}static create(u,h){return new ZodPipeline({in:u,out:h,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(u){const h=this._def.innerType._parse(u),b=v=>(isValid(v)&&(v.value=Object.freeze(v.value)),v);return isAsync(h)?h.then(v=>b(v)):b(h)}unwrap(){return this._def.innerType}}ZodReadonly.create=(y,u)=>new ZodReadonly({innerType:y,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(u)});function custom(y,u={},h){return y?ZodAny.create().superRefine((b,v)=>{var w,_;if(!y(b)){const E=typeof u=="function"?u(b):typeof u=="string"?{message:u}:u,S=(_=(w=E.fatal)!==null&&w!==void 0?w:h)!==null&&_!==void 0?_:!0,x=typeof E=="string"?{message:E}:E;v.addIssue({code:"custom",...x,fatal:S})}}):ZodAny.create()}const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(y){y.ZodString="ZodString",y.ZodNumber="ZodNumber",y.ZodNaN="ZodNaN",y.ZodBigInt="ZodBigInt",y.ZodBoolean="ZodBoolean",y.ZodDate="ZodDate",y.ZodSymbol="ZodSymbol",y.ZodUndefined="ZodUndefined",y.ZodNull="ZodNull",y.ZodAny="ZodAny",y.ZodUnknown="ZodUnknown",y.ZodNever="ZodNever",y.ZodVoid="ZodVoid",y.ZodArray="ZodArray",y.ZodObject="ZodObject",y.ZodUnion="ZodUnion",y.ZodDiscriminatedUnion="ZodDiscriminatedUnion",y.ZodIntersection="ZodIntersection",y.ZodTuple="ZodTuple",y.ZodRecord="ZodRecord",y.ZodMap="ZodMap",y.ZodSet="ZodSet",y.ZodFunction="ZodFunction",y.ZodLazy="ZodLazy",y.ZodLiteral="ZodLiteral",y.ZodEnum="ZodEnum",y.ZodEffects="ZodEffects",y.ZodNativeEnum="ZodNativeEnum",y.ZodOptional="ZodOptional",y.ZodNullable="ZodNullable",y.ZodDefault="ZodDefault",y.ZodCatch="ZodCatch",y.ZodPromise="ZodPromise",y.ZodBranded="ZodBranded",y.ZodPipeline="ZodPipeline",y.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const instanceOfType=(y,u={message:`Input not instance of ${y.name}`})=>custom(h=>h instanceof y,u),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce$1={string:y=>ZodString.create({...y,coerce:!0}),number:y=>ZodNumber.create({...y,coerce:!0}),boolean:y=>ZodBoolean.create({...y,coerce:!0}),bigint:y=>ZodBigInt.create({...y,coerce:!0}),date:y=>ZodDate.create({...y,coerce:!0})},NEVER=INVALID;var z=Object.freeze({__proto__:null,defaultErrorMap:errorMap,setErrorMap,getErrorMap,makeIssue,EMPTY_PATH,addIssueToContext,ParseStatus,INVALID,DIRTY,OK,isAborted,isDirty,isValid,isAsync,get util(){return util$c},get objectUtil(){return objectUtil},ZodParsedType,getParsedType,ZodType,datetimeRegex,ZodString,ZodNumber,ZodBigInt,ZodBoolean,ZodDate,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodArray,ZodObject,ZodUnion,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodFunction,ZodLazy,ZodLiteral,ZodEnum,ZodNativeEnum,ZodPromise,ZodEffects,ZodTransformer:ZodEffects,ZodOptional,ZodNullable,ZodDefault,ZodCatch,ZodNaN,BRAND,ZodBranded,ZodPipeline,ZodReadonly,custom,Schema:ZodType,ZodSchema:ZodType,late,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind},coerce:coerce$1,any:anyType,array:arrayType,bigint:bigIntType,boolean:booleanType,date:dateType,discriminatedUnion:discriminatedUnionType,effect:effectsType,enum:enumType,function:functionType,instanceof:instanceOfType,intersection:intersectionType,lazy:lazyType,literal:literalType,map:mapType,nan:nanType,nativeEnum:nativeEnumType,never:neverType,null:nullType,nullable:nullableType,number:numberType,object:objectType,oboolean,onumber,optional:optionalType,ostring,pipeline:pipelineType,preprocess:preprocessType,promise:promiseType,record:recordType,set:setType,strictObject:strictObjectType,string:stringType,symbol:symbolType,transformer:effectsType,tuple:tupleType,undefined:undefinedType,union:unionType,unknown:unknownType,void:voidType,NEVER,ZodIssueCode,quotelessJson,ZodError}),MessageType=(y=>(y.TEXT="text",y.THREAD="thread",y.REACTION="reaction",y))(MessageType||{});const logger$3=Logger$2.getInstance(),CORE_MESSAGE_PROPERTIES=["id","targetMessageId","type","message","username","address","timestamp","signature","index","chatTopic","userTopic","additionalProps"],MessageSchema=z.object({id:z.string(),targetMessageId:z.string().optional(),type:z.nativeEnum(MessageType),message:z.string(),username:z.string(),address:z.string(),timestamp:z.number(),signature:z.string(),index:z.number(),chatTopic:z.string(),userTopic:z.string(),additionalProps:z.record(z.any()).optional()}).refine(y=>!y.additionalProps||Object.keys(y.additionalProps).length===0?!0:validateAdditionalPropertiesInternal(y.additionalProps).isValid,{message:"Invalid additional properties in message"}),StateRefSchema=z.object({reference:z.string(),timestamp:z.number()}),StatefulMessageSchema=z.object({message:MessageSchema,messageStateRefs:z.array(StateRefSchema).nullable()});function validateGsocMessage(y){const u=StatefulMessageSchema.safeParse(y);return u.success?validateUserSignature(y.message)?!0:(logger$3.warn("Invalid main message signature"),!1):(logger$3.warn("GSOC message validation failed:",u.error.format()),!1)}function validateMessageState(y){if(!Array.isArray(y))return logger$3.warn("Message state must be an array"),!1;for(const u of y)if(!validateMessageData(u))return logger$3.warn("Invalid message in message state:",u.id),!1;return!0}function validateMessageData(y){const u=MessageSchema.safeParse(y);return u.success?validateUserSignature(y)?!0:(logger$3.warn("Invalid message signature"),!1):(logger$3.warn("Message data validation failed:",u.error.format()),!1)}function validateUserSignature(y){try{const u={username:y.username,address:y.address,timestamp:y.timestamp,message:y.message},h=new TextEncoder,b=Binary.concatBytes(h.encode(`Ethereum Signed Message:
11
+ 32`),Binary.keccak256(h.encode(JSON.stringify(u))));if(new beeJs.Signature(y.signature).isValid(b,y.address))throw new Error("Signature verification failed!");return!0}catch(u){return logger$3.warn("Error in validateUserSignature",u),!1}}function validateAdditionalPropertiesInternal(y){const u=[];if(y==null)return{isValid:!0,errors:[]};if(typeof y!="object"||Array.isArray(y))return u.push("Additional properties must be a plain object"),{isValid:!1,errors:u};for(const S of Object.keys(y))CORE_MESSAGE_PROPERTIES.includes(S)&&u.push(`Property '${S}' is reserved and cannot be overridden`);const h=JSON.stringify(y),b=new TextEncoder().encode(h).length,v=1*1024;b>v&&u.push(`Additional properties too large: ${b} bytes (max: ${v} bytes)`);const w=5;function _(S,x=0){if(x>w)return!1;if(typeof S=="object"&&S!==null&&!Array.isArray(S)){for(const T of Object.values(S))if(!_(T,x+1))return!1}return!0}_(y)||u.push(`Additional properties nested too deeply (max depth: ${w})`);for(const[S,x]of Object.entries(y))if(S.length>100&&u.push(`Property key '${S}' too long (max: 100 characters)`),typeof x=="string"&&x.length>1e3&&u.push(`Property '${S}' value too long (max: 1000 characters)`),typeof x=="string"){const T=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/data:text\/html/gi,/vbscript:/gi,/on\w+\s*=/gi];for(const C of T)if(C.test(x)){u.push(`Property '${S}' contains potentially dangerous content`);break}}const E=20;return Object.keys(y).length>E&&u.push(`Too many additional properties: ${Object.keys(y).length} (max: ${E})`),{isValid:u.length===0,errors:u}}function validateMessageWithAdditionalProperties(y){const u=MessageSchema.safeParse(y);if(!u.success){const h=u.error.issues.map(b=>b.path.length>0?`${b.path.join(".")}: ${b.message}`:b.message);return logger$3.warn("Message validation failed:",u.error.format()),{isValid:!1,errors:h}}return{isValid:!0,errors:[]}}function alloc$1(y=0){return new Uint8Array(y)}function allocUnsafe(y=0){return new Uint8Array(y)}const N1$1=Math.pow(2,7),N2$1=Math.pow(2,14),N3$1=Math.pow(2,21),N4$1=Math.pow(2,28),N5$1=Math.pow(2,35),N6$1=Math.pow(2,42),N7$1=Math.pow(2,49),MSB$2=128,REST$2=127;function encodingLength$1(y){if(y<N1$1)return 1;if(y<N2$1)return 2;if(y<N3$1)return 3;if(y<N4$1)return 4;if(y<N5$1)return 5;if(y<N6$1)return 6;if(y<N7$1)return 7;if(Number.MAX_SAFE_INTEGER!=null&&y>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function encodeUint8Array(y,u,h=0){switch(encodingLength$1(y)){case 8:u[h++]=y&255|MSB$2,y/=128;case 7:u[h++]=y&255|MSB$2,y/=128;case 6:u[h++]=y&255|MSB$2,y/=128;case 5:u[h++]=y&255|MSB$2,y/=128;case 4:u[h++]=y&255|MSB$2,y>>>=7;case 3:u[h++]=y&255|MSB$2,y>>>=7;case 2:u[h++]=y&255|MSB$2,y>>>=7;case 1:{u[h++]=y&255,y>>>=7;break}default:throw new Error("unreachable")}return u}function encodeUint8ArrayList(y,u,h=0){switch(encodingLength$1(y)){case 8:u.set(h++,y&255|MSB$2),y/=128;case 7:u.set(h++,y&255|MSB$2),y/=128;case 6:u.set(h++,y&255|MSB$2),y/=128;case 5:u.set(h++,y&255|MSB$2),y/=128;case 4:u.set(h++,y&255|MSB$2),y>>>=7;case 3:u.set(h++,y&255|MSB$2),y>>>=7;case 2:u.set(h++,y&255|MSB$2),y>>>=7;case 1:{u.set(h++,y&255),y>>>=7;break}default:throw new Error("unreachable")}return u}function decodeUint8Array(y,u){let h=y[u],b=0;if(b+=h&REST$2,h<MSB$2||(h=y[u+1],b+=(h&REST$2)<<7,h<MSB$2)||(h=y[u+2],b+=(h&REST$2)<<14,h<MSB$2)||(h=y[u+3],b+=(h&REST$2)<<21,h<MSB$2)||(h=y[u+4],b+=(h&REST$2)*N4$1,h<MSB$2)||(h=y[u+5],b+=(h&REST$2)*N5$1,h<MSB$2)||(h=y[u+6],b+=(h&REST$2)*N6$1,h<MSB$2)||(h=y[u+7],b+=(h&REST$2)*N7$1,h<MSB$2))return b;throw new RangeError("Could not decode varint")}function decodeUint8ArrayList(y,u){let h=y.get(u),b=0;if(b+=h&REST$2,h<MSB$2||(h=y.get(u+1),b+=(h&REST$2)<<7,h<MSB$2)||(h=y.get(u+2),b+=(h&REST$2)<<14,h<MSB$2)||(h=y.get(u+3),b+=(h&REST$2)<<21,h<MSB$2)||(h=y.get(u+4),b+=(h&REST$2)*N4$1,h<MSB$2)||(h=y.get(u+5),b+=(h&REST$2)*N5$1,h<MSB$2)||(h=y.get(u+6),b+=(h&REST$2)*N6$1,h<MSB$2)||(h=y.get(u+7),b+=(h&REST$2)*N7$1,h<MSB$2))return b;throw new RangeError("Could not decode varint")}function encode$8(y,u,h=0){return u==null&&(u=allocUnsafe(encodingLength$1(y))),u instanceof Uint8Array?encodeUint8Array(y,u,h):encodeUint8ArrayList(y,u,h)}function decode$8(y,u=0){return y instanceof Uint8Array?decodeUint8Array(y,u):decodeUint8ArrayList(y,u)}const f32=new Float32Array([-0]),f8b=new Uint8Array(f32.buffer);function writeFloatLE(y,u,h){f32[0]=y,u[h]=f8b[0],u[h+1]=f8b[1],u[h+2]=f8b[2],u[h+3]=f8b[3]}function readFloatLE(y,u){return f8b[0]=y[u],f8b[1]=y[u+1],f8b[2]=y[u+2],f8b[3]=y[u+3],f32[0]}const f64=new Float64Array([-0]),d8b=new Uint8Array(f64.buffer);function writeDoubleLE(y,u,h){f64[0]=y,u[h]=d8b[0],u[h+1]=d8b[1],u[h+2]=d8b[2],u[h+3]=d8b[3],u[h+4]=d8b[4],u[h+5]=d8b[5],u[h+6]=d8b[6],u[h+7]=d8b[7]}function readDoubleLE(y,u){return d8b[0]=y[u],d8b[1]=y[u+1],d8b[2]=y[u+2],d8b[3]=y[u+3],d8b[4]=y[u+4],d8b[5]=y[u+5],d8b[6]=y[u+6],d8b[7]=y[u+7],f64[0]}const MAX_SAFE_NUMBER_INTEGER=BigInt(Number.MAX_SAFE_INTEGER),MIN_SAFE_NUMBER_INTEGER=BigInt(Number.MIN_SAFE_INTEGER);let LongBits$2=class Fs{constructor(u,h){Z(this,"lo");Z(this,"hi");this.lo=u|0,this.hi=h|0}toNumber(u=!1){if(!u&&this.hi>>>31>0){const h=~this.lo+1>>>0;let b=~this.hi>>>0;return h===0&&(b=b+1>>>0),-(h+b*4294967296)}return this.lo+this.hi*4294967296}toBigInt(u=!1){if(u)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const h=~this.lo+1>>>0;let b=~this.hi>>>0;return h===0&&(b=b+1>>>0),-(BigInt(h)+(BigInt(b)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(u=!1){return this.toBigInt(u).toString()}zzEncode(){const u=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^u)>>>0,this.lo=(this.lo<<1^u)>>>0,this}zzDecode(){const u=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^u)>>>0,this.hi=(this.hi>>>1^u)>>>0,this}length(){const u=this.lo,h=(this.lo>>>28|this.hi<<4)>>>0,b=this.hi>>>24;return b===0?h===0?u<16384?u<128?1:2:u<2097152?3:4:h<16384?h<128?5:6:h<2097152?7:8:b<128?9:10}static fromBigInt(u){if(u===0n)return zero;if(u<MAX_SAFE_NUMBER_INTEGER&&u>MIN_SAFE_NUMBER_INTEGER)return this.fromNumber(Number(u));const h=u<0n;h&&(u=-u);let b=u>>32n,v=u-(b<<32n);return h&&(b=~b|0n,v=~v|0n,++v>TWO_32&&(v=0n,++b>TWO_32&&(b=0n))),new Fs(Number(v),Number(b))}static fromNumber(u){if(u===0)return zero;const h=u<0;h&&(u=-u);let b=u>>>0,v=(u-b)/4294967296>>>0;return h&&(v=~v>>>0,b=~b>>>0,++b>4294967295&&(b=0,++v>4294967295&&(v=0))),new Fs(b,v)}static from(u){return typeof u=="number"?Fs.fromNumber(u):typeof u=="bigint"?Fs.fromBigInt(u):typeof u=="string"?Fs.fromBigInt(BigInt(u)):u.low!=null||u.high!=null?new Fs(u.low>>>0,u.high>>>0):zero}};const zero=new LongBits$2(0,0);zero.toBigInt=function(){return 0n};zero.zzEncode=zero.zzDecode=function(){return this};zero.length=function(){return 1};const TWO_32=4294967296n;function length$1(y){let u=0,h=0;for(let b=0;b<y.length;++b)h=y.charCodeAt(b),h<128?u+=1:h<2048?u+=2:(h&64512)===55296&&(y.charCodeAt(b+1)&64512)===56320?(++b,u+=4):u+=3;return u}function read$2(y,u,h){if(h-u<1)return"";let v;const w=[];let _=0,E;for(;u<h;)E=y[u++],E<128?w[_++]=E:E>191&&E<224?w[_++]=(E&31)<<6|y[u++]&63:E>239&&E<365?(E=((E&7)<<18|(y[u++]&63)<<12|(y[u++]&63)<<6|y[u++]&63)-65536,w[_++]=55296+(E>>10),w[_++]=56320+(E&1023)):w[_++]=(E&15)<<12|(y[u++]&63)<<6|y[u++]&63,_>8191&&((v??(v=[])).push(String.fromCharCode.apply(String,w)),_=0);return v!=null?(_>0&&v.push(String.fromCharCode.apply(String,w.slice(0,_))),v.join("")):String.fromCharCode.apply(String,w.slice(0,_))}function write$1(y,u,h){const b=h;let v,w;for(let _=0;_<y.length;++_)v=y.charCodeAt(_),v<128?u[h++]=v:v<2048?(u[h++]=v>>6|192,u[h++]=v&63|128):(v&64512)===55296&&((w=y.charCodeAt(_+1))&64512)===56320?(v=65536+((v&1023)<<10)+(w&1023),++_,u[h++]=v>>18|240,u[h++]=v>>12&63|128,u[h++]=v>>6&63|128,u[h++]=v&63|128):(u[h++]=v>>12|224,u[h++]=v>>6&63|128,u[h++]=v&63|128);return h-b}function indexOutOfRange$1(y,u){return RangeError(`index out of range: ${y.pos} + ${u??1} > ${y.len}`)}function readFixed32End(y,u){return(y[u-4]|y[u-3]<<8|y[u-2]<<16|y[u-1]<<24)>>>0}class Uint8ArrayReader{constructor(u){Z(this,"buf");Z(this,"pos");Z(this,"len");Z(this,"_slice",Uint8Array.prototype.subarray);this.buf=u,this.pos=0,this.len=u.length}uint32(){let u=4294967295;if(u=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(u=(u|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(u=(u|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(u=(u|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(u=(u|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return u;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange$1(this,10);return u}int32(){return this.uint32()|0}sint32(){const u=this.uint32();return u>>>1^-(u&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw indexOutOfRange$1(this,4);return readFixed32End(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw indexOutOfRange$1(this,4);return readFixed32End(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw indexOutOfRange$1(this,4);const u=readFloatLE(this.buf,this.pos);return this.pos+=4,u}double(){if(this.pos+8>this.len)throw indexOutOfRange$1(this,4);const u=readDoubleLE(this.buf,this.pos);return this.pos+=8,u}bytes(){const u=this.uint32(),h=this.pos,b=this.pos+u;if(b>this.len)throw indexOutOfRange$1(this,u);return this.pos+=u,h===b?new Uint8Array(0):this.buf.subarray(h,b)}string(){const u=this.bytes();return read$2(u,0,u.length)}skip(u){if(typeof u=="number"){if(this.pos+u>this.len)throw indexOutOfRange$1(this,u);this.pos+=u}else do if(this.pos>=this.len)throw indexOutOfRange$1(this);while(this.buf[this.pos++]&128);return this}skipType(u){switch(u){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(u=this.uint32()&7)!==4;)this.skipType(u);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${u} at offset ${this.pos}`)}return this}readLongVarint(){const u=new LongBits$2(0,0);let h=0;if(this.len-this.pos>4){for(;h<4;++h)if(u.lo=(u.lo|(this.buf[this.pos]&127)<<h*7)>>>0,this.buf[this.pos++]<128)return u;if(u.lo=(u.lo|(this.buf[this.pos]&127)<<28)>>>0,u.hi=(u.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return u;h=0}else{for(;h<3;++h){if(this.pos>=this.len)throw indexOutOfRange$1(this);if(u.lo=(u.lo|(this.buf[this.pos]&127)<<h*7)>>>0,this.buf[this.pos++]<128)return u}return u.lo=(u.lo|(this.buf[this.pos++]&127)<<h*7)>>>0,u}if(this.len-this.pos>4){for(;h<5;++h)if(u.hi=(u.hi|(this.buf[this.pos]&127)<<h*7+3)>>>0,this.buf[this.pos++]<128)return u}else for(;h<5;++h){if(this.pos>=this.len)throw indexOutOfRange$1(this);if(u.hi=(u.hi|(this.buf[this.pos]&127)<<h*7+3)>>>0,this.buf[this.pos++]<128)return u}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange$1(this,8);const u=readFixed32End(this.buf,this.pos+=4),h=readFixed32End(this.buf,this.pos+=4);return new LongBits$2(u,h)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const u=decodeUint8Array(this.buf,this.pos);return this.pos+=encodingLength$1(u),u}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function createReader(y){return new Uint8ArrayReader(y instanceof Uint8Array?y:y.subarray())}function decodeMessage(y,u,h){const b=createReader(y);return u.decode(b,void 0,h)}function equals$2(y,u){if(y===u)return!0;if(y.byteLength!==u.byteLength)return!1;for(let h=0;h<y.byteLength;h++)if(y[h]!==u[h])return!1;return!0}function coerce(y){if(y instanceof Uint8Array&&y.constructor.name==="Uint8Array")return y;if(y instanceof ArrayBuffer)return new Uint8Array(y);if(ArrayBuffer.isView(y))return new Uint8Array(y.buffer,y.byteOffset,y.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$1(y){return new TextEncoder().encode(y)}function toString$2(y){return new TextDecoder().decode(y)}function base$3(y,u){if(y.length>=255)throw new TypeError("Alphabet too long");for(var h=new Uint8Array(256),b=0;b<h.length;b++)h[b]=255;for(var v=0;v<y.length;v++){var w=y.charAt(v),_=w.charCodeAt(0);if(h[_]!==255)throw new TypeError(w+" is ambiguous");h[_]=v}var E=y.length,S=y.charAt(0),x=Math.log(E)/Math.log(256),T=Math.log(256)/Math.log(E);function C(U){if(U instanceof Uint8Array||(ArrayBuffer.isView(U)?U=new Uint8Array(U.buffer,U.byteOffset,U.byteLength):Array.isArray(U)&&(U=Uint8Array.from(U))),!(U instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(U.length===0)return"";for(var te=0,X=0,ie=0,ee=U.length;ie!==ee&&U[ie]===0;)ie++,te++;for(var ae=(ee-ie)*T+1>>>0,de=new Uint8Array(ae);ie!==ee;){for(var Se=U[ie],ve=0,Pe=ae-1;(Se!==0||ve<X)&&Pe!==-1;Pe--,ve++)Se+=256*de[Pe]>>>0,de[Pe]=Se%E>>>0,Se=Se/E>>>0;if(Se!==0)throw new Error("Non-zero carry");X=ve,ie++}for(var Ie=ae-X;Ie!==ae&&de[Ie]===0;)Ie++;for(var Ee=S.repeat(te);Ie<ae;++Ie)Ee+=y.charAt(de[Ie]);return Ee}function O(U){if(typeof U!="string")throw new TypeError("Expected String");if(U.length===0)return new Uint8Array;var te=0;if(U[te]!==" "){for(var X=0,ie=0;U[te]===S;)X++,te++;for(var ee=(U.length-te)*x+1>>>0,ae=new Uint8Array(ee);U[te];){var de=h[U.charCodeAt(te)];if(de===255)return;for(var Se=0,ve=ee-1;(de!==0||Se<ie)&&ve!==-1;ve--,Se++)de+=E*ae[ve]>>>0,ae[ve]=de%256>>>0,de=de/256>>>0;if(de!==0)throw new Error("Non-zero carry");ie=Se,te++}if(U[te]!==" "){for(var Pe=ee-ie;Pe!==ee&&ae[Pe]===0;)Pe++;for(var Ie=new Uint8Array(X+(ee-Pe)),Ee=X;Pe!==ee;)Ie[Ee++]=ae[Pe++];return Ie}}}function D(U){var te=O(U);if(te)return te;throw new Error(`Non-${u} character`)}return{encode:C,decodeUnsafe:O,decode:D}}var src$1=base$3,_brrp__multiformats_scope_baseX=src$1;let Encoder$2=class{constructor(u,h,b){Z(this,"name");Z(this,"prefix");Z(this,"baseEncode");this.name=u,this.prefix=h,this.baseEncode=b}encode(u){if(u instanceof Uint8Array)return`${this.prefix}${this.baseEncode(u)}`;throw Error("Unknown type, must be binary type")}},Decoder$2=class{constructor(u,h,b){Z(this,"name");Z(this,"prefix");Z(this,"baseDecode");Z(this,"prefixCodePoint");this.name=u,this.prefix=h;const v=h.codePointAt(0);if(v===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=v,this.baseDecode=b}decode(u){if(typeof u=="string"){if(u.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(u)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(u.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(u){return or$2(this,u)}};class ComposedDecoder{constructor(u){Z(this,"decoders");this.decoders=u}or(u){return or$2(this,u)}decode(u){const h=u[0],b=this.decoders[h];if(b!=null)return b.decode(u);throw RangeError(`Unable to decode multibase string ${JSON.stringify(u)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function or$2(y,u){return new ComposedDecoder({...y.decoders??{[y.prefix]:y},...u.decoders??{[u.prefix]:u}})}class Codec{constructor(u,h,b,v){Z(this,"name");Z(this,"prefix");Z(this,"baseEncode");Z(this,"baseDecode");Z(this,"encoder");Z(this,"decoder");this.name=u,this.prefix=h,this.baseEncode=b,this.baseDecode=v,this.encoder=new Encoder$2(u,h,b),this.decoder=new Decoder$2(u,h,v)}encode(u){return this.encoder.encode(u)}decode(u){return this.decoder.decode(u)}}function from$1({name:y,prefix:u,encode:h,decode:b}){return new Codec(y,u,h,b)}function baseX({name:y,prefix:u,alphabet:h}){const{encode:b,decode:v}=_brrp__multiformats_scope_baseX(h,y);return from$1({prefix:u,name:y,encode:b,decode:w=>coerce(v(w))})}function decode$7(y,u,h,b){let v=y.length;for(;y[v-1]==="=";)--v;const w=new Uint8Array(v*h/8|0);let _=0,E=0,S=0;for(let x=0;x<v;++x){const T=u[y[x]];if(T===void 0)throw new SyntaxError(`Non-${b} character`);E=E<<h|T,_+=h,_>=8&&(_-=8,w[S++]=255&E>>_)}if(_>=h||255&E<<8-_)throw new SyntaxError("Unexpected end of data");return w}function encode$7(y,u,h){const b=u[u.length-1]==="=",v=(1<<h)-1;let w="",_=0,E=0;for(let S=0;S<y.length;++S)for(E=E<<8|y[S],_+=8;_>h;)_-=h,w+=u[v&E>>_];if(_!==0&&(w+=u[v&E<<h-_]),b)for(;w.length*h&7;)w+="=";return w}function createAlphabetIdx(y){const u={};for(let h=0;h<y.length;++h)u[y[h]]=h;return u}function rfc4648({name:y,prefix:u,bitsPerChar:h,alphabet:b}){const v=createAlphabetIdx(b);return from$1({prefix:u,name:y,encode(w){return encode$7(w,b,h)},decode(w){return decode$7(w,v,h,y)}})}const base10=baseX({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$1=Object.freeze(Object.defineProperty({__proto__:null,base10},Symbol.toStringTag,{value:"Module"})),base16=rfc4648({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper=rfc4648({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$1=Object.freeze(Object.defineProperty({__proto__:null,base16,base16upper},Symbol.toStringTag,{value:"Module"})),base2=rfc4648({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$1=Object.freeze(Object.defineProperty({__proto__:null,base2},Symbol.toStringTag,{value:"Module"})),alphabet=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),alphabetBytesToChars=alphabet.reduce((y,u,h)=>(y[h]=u,y),[]),alphabetCharsToBytes=alphabet.reduce((y,u,h)=>{const b=u.codePointAt(0);if(b==null)throw new Error(`Invalid character: ${u}`);return y[b]=h,y},[]);function encode$6(y){return y.reduce((u,h)=>(u+=alphabetBytesToChars[h],u),"")}function decode$6(y){const u=[];for(const h of y){const b=h.codePointAt(0);if(b==null)throw new Error(`Invalid character: ${h}`);const v=alphabetCharsToBytes[b];if(v==null)throw new Error(`Non-base256emoji character: ${h}`);u.push(v)}return new Uint8Array(u)}const base256emoji=from$1({prefix:"🚀",name:"base256emoji",encode:encode$6,decode:decode$6}),base256emoji$1=Object.freeze(Object.defineProperty({__proto__:null,base256emoji},Symbol.toStringTag,{value:"Module"})),base32$2=rfc4648({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper=rfc4648({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad=rfc4648({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper=rfc4648({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex=rfc4648({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper=rfc4648({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad=rfc4648({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper=rfc4648({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z=rfc4648({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$3=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$2,base32hex,base32hexpad,base32hexpadupper,base32hexupper,base32pad,base32padupper,base32upper,base32z},Symbol.toStringTag,{value:"Module"})),base36=baseX({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper=baseX({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$1=Object.freeze(Object.defineProperty({__proto__:null,base36,base36upper},Symbol.toStringTag,{value:"Module"})),base58btc=baseX({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr=baseX({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58=Object.freeze(Object.defineProperty({__proto__:null,base58btc,base58flickr},Symbol.toStringTag,{value:"Module"})),base64$2=rfc4648({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad=rfc4648({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url=rfc4648({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad=rfc4648({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$3=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$2,base64pad,base64url,base64urlpad},Symbol.toStringTag,{value:"Module"})),base8=rfc4648({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$1=Object.freeze(Object.defineProperty({__proto__:null,base8},Symbol.toStringTag,{value:"Module"})),identity$1=from$1({prefix:"\0",name:"identity",encode:y=>toString$2(y),decode:y=>fromString$1(y)}),identityBase=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$1},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;var encode_1=encode$5,MSB$1=128,REST$1=127,MSBALL=~REST$1,INT=Math.pow(2,31);function encode$5(y,u,h){u=u||[],h=h||0;for(var b=h;y>=INT;)u[h++]=y&255|MSB$1,y/=128;for(;y&MSBALL;)u[h++]=y&255|MSB$1,y>>>=7;return u[h]=y|0,encode$5.bytes=h-b+1,u}var decode$5=read$1,MSB$1$1=128,REST$1$1=127;function read$1(y,b){var h=0,b=b||0,v=0,w=b,_,E=y.length;do{if(w>=E)throw read$1.bytes=0,new RangeError("Could not decode varint");_=y[w++],h+=v<28?(_&REST$1$1)<<v:(_&REST$1$1)*Math.pow(2,v),v+=7}while(_>=MSB$1$1);return read$1.bytes=w-b,h}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function(y){return y<N1?1:y<N2?2:y<N3?3:y<N4?4:y<N5?5:y<N6?6:y<N7?7:y<N8?8:y<N9?9:10},varint={encode:encode_1,decode:decode$5,encodingLength:length},_brrp_varint=varint;function decode$4(y,u=0){return[_brrp_varint.decode(y,u),_brrp_varint.decode.bytes]}function encodeTo(y,u,h=0){return _brrp_varint.encode(y,u,h),u}function encodingLength(y){return _brrp_varint.encodingLength(y)}function create$2(y,u){const h=u.byteLength,b=encodingLength(y),v=b+encodingLength(h),w=new Uint8Array(v+h);return encodeTo(y,w,0),encodeTo(h,w,b),w.set(u,v),new Digest(y,h,u,w)}function decode$3(y){const u=coerce(y),[h,b]=decode$4(u),[v,w]=decode$4(u.subarray(b)),_=u.subarray(b+w);if(_.byteLength!==v)throw new Error("Incorrect length");return new Digest(h,v,_,u)}function equals$1(y,u){if(y===u)return!0;{const h=u;return y.code===h.code&&y.size===h.size&&h.bytes instanceof Uint8Array&&equals$2(y.bytes,h.bytes)}}class Digest{constructor(u,h,b,v){Z(this,"code");Z(this,"size");Z(this,"digest");Z(this,"bytes");this.code=u,this.size=h,this.digest=b,this.bytes=v}}const code=0,name$2="identity",encode$4=coerce;function digest(y,u){if((u==null?void 0:u.truncate)!=null&&u.truncate!==y.byteLength){if(u.truncate<0||u.truncate>y.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${y.byteLength}`);y=y.subarray(0,u.truncate)}return create$2(code,encode$4(y))}const identity={code,name:name$2,encode:encode$4,digest},DEFAULT_MIN_DIGEST_LENGTH=20;function from({name:y,code:u,encode:h,minDigestLength:b,maxDigestLength:v}){return new Hasher(y,u,h,b,v)}class Hasher{constructor(u,h,b,v,w){Z(this,"name");Z(this,"code");Z(this,"encode");Z(this,"minDigestLength");Z(this,"maxDigestLength");this.name=u,this.code=h,this.encode=b,this.minDigestLength=v??DEFAULT_MIN_DIGEST_LENGTH,this.maxDigestLength=w}digest(u,h){if((h==null?void 0:h.truncate)!=null){if(h.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&h.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(u instanceof Uint8Array){const b=this.encode(u);return b instanceof Uint8Array?createDigest(b,this.code,h==null?void 0:h.truncate):b.then(v=>createDigest(v,this.code,h==null?void 0:h.truncate))}else throw Error("Unknown type, must be binary type")}}function createDigest(y,u,h){if(h!=null&&h!==y.byteLength){if(h>y.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${y.byteLength}`);y=y.subarray(0,h)}return create$2(u,y)}function sha$5(y){return async u=>new Uint8Array(await crypto.subtle.digest(y,u))}const sha256$4=from({name:"sha2-256",code:18,encode:sha$5("SHA-256")});function format(y,u){const{bytes:h,version:b}=y;switch(b){case 0:return toStringV0(h,baseCache(y),u??base58btc.encoder);default:return toStringV1(h,baseCache(y),u??base32$2.encoder)}}const cache$2=new WeakMap;function baseCache(y){const u=cache$2.get(y);if(u==null){const h=new Map;return cache$2.set(y,h),h}return u}var Zd;class CID{constructor(u,h,b,v){Z(this,"code");Z(this,"version");Z(this,"multihash");Z(this,"bytes");Z(this,"/");Z(this,Zd,"CID");this.code=h,this.version=u,this.multihash=b,this.bytes=v,this["/"]=v}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:u,multihash:h}=this;if(u!==DAG_PB_CODE)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(h.code!==SHA_256_CODE)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return CID.createV0(h)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:u,digest:h}=this.multihash,b=create$2(u,h);return CID.createV1(this.code,b)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(u){return CID.equals(this,u)}static equals(u,h){const b=h;return b!=null&&u.code===b.code&&u.version===b.version&&equals$1(u.multihash,b.multihash)}toString(u){return format(this,u)}toJSON(){return{"/":format(this)}}link(){return this}[(Zd=Symbol.toStringTag,Symbol.for("nodejs.util.inspect.custom"))](){return`CID(${this.toString()})`}static asCID(u){if(u==null)return null;const h=u;if(h instanceof CID)return h;if(h["/"]!=null&&h["/"]===h.bytes||h.asCID===h){const{version:b,code:v,multihash:w,bytes:_}=h;return new CID(b,v,w,_??encodeCID(b,v,w.bytes))}else if(h[cidSymbol]===!0){const{version:b,multihash:v,code:w}=h,_=decode$3(v);return CID.create(b,w,_)}else return null}static create(u,h,b){if(typeof h!="number")throw new Error("String codecs are no longer supported");if(!(b.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(u){case 0:{if(h!==DAG_PB_CODE)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);return new CID(u,h,b,b.bytes)}case 1:{const v=encodeCID(u,h,b.bytes);return new CID(u,h,b,v)}default:throw new Error("Invalid version")}}static createV0(u){return CID.create(0,DAG_PB_CODE,u)}static createV1(u,h){return CID.create(1,u,h)}static decode(u){const[h,b]=CID.decodeFirst(u);if(b.length!==0)throw new Error("Incorrect length");return h}static decodeFirst(u){const h=CID.inspectBytes(u),b=h.size-h.multihashSize,v=coerce(u.subarray(b,b+h.multihashSize));if(v.byteLength!==h.multihashSize)throw new Error("Incorrect length");const w=v.subarray(h.multihashSize-h.digestSize),_=new Digest(h.multihashCode,h.digestSize,w,v);return[h.version===0?CID.createV0(_):CID.createV1(h.codec,_),u.subarray(h.size)]}static inspectBytes(u){let h=0;const b=()=>{const[C,O]=decode$4(u.subarray(h));return h+=O,C};let v=b(),w=DAG_PB_CODE;if(v===18?(v=0,h=0):w=b(),v!==0&&v!==1)throw new RangeError(`Invalid CID version ${v}`);const _=h,E=b(),S=b(),x=h+S,T=x-_;return{version:v,codec:w,multihashCode:E,digestSize:S,multihashSize:T,size:x}}static parse(u,h){const[b,v]=parseCIDtoBytes(u,h),w=CID.decode(v);if(w.version===0&&u[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache(w).set(b,u),w}}function parseCIDtoBytes(y,u){switch(y[0]){case"Q":{const h=u??base58btc;return[base58btc.prefix,h.decode(`${base58btc.prefix}${y}`)]}case base58btc.prefix:{const h=u??base58btc;return[base58btc.prefix,h.decode(y)]}case base32$2.prefix:{const h=u??base32$2;return[base32$2.prefix,h.decode(y)]}case base36.prefix:{const h=u??base36;return[base36.prefix,h.decode(y)]}default:{if(u==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[y[0],u.decode(y)]}}}function toStringV0(y,u,h){const{prefix:b}=h;if(b!==base58btc.prefix)throw Error(`Cannot string encode V0 in ${h.name} encoding`);const v=u.get(b);if(v==null){const w=h.encode(y).slice(1);return u.set(b,w),w}else return v}function toStringV1(y,u,h){const{prefix:b}=h,v=u.get(b);if(v==null){const w=h.encode(y);return u.set(b,w),w}else return v}const DAG_PB_CODE=112,SHA_256_CODE=18;function encodeCID(y,u,h){const b=encodingLength(y),v=b+encodingLength(u),w=new Uint8Array(v+h.byteLength);return encodeTo(y,w,0),encodeTo(u,w,b),w.set(h,v),w}const cidSymbol=Symbol.for("@ipld/js-cid/CID"),bases={...identityBase,...base2$1,...base8$1,...base10$1,...base16$1,...base32$3,...base36$1,...base58,...base64$3,...base256emoji$1};function createCodec$1(y,u,h,b){return{name:y,prefix:u,encoder:{name:y,prefix:u,encode:h},decoder:{decode:b}}}const string$1=createCodec$1("utf8","u",y=>"u"+new TextDecoder("utf8").decode(y),y=>new TextEncoder().encode(y.substring(1))),ascii=createCodec$1("ascii","a",y=>{let u="a";for(let h=0;h<y.length;h++)u+=String.fromCharCode(y[h]);return u},y=>{y=y.substring(1);const u=allocUnsafe(y.length);for(let h=0;h<y.length;h++)u[h]=y.charCodeAt(h);return u}),BASES={utf8:string$1,"utf-8":string$1,hex:bases.base16,latin1:ascii,ascii,binary:ascii,...bases};function fromString(y,u="utf8"){const h=BASES[u];if(h==null)throw new Error(`Unsupported encoding "${u}"`);return h.decoder.decode(`${h.prefix}${y}`)}function pool$1(y){let b,v=8192;return function(_){if(_<1||_>4096)return allocUnsafe(_);v+_>8192&&(b=allocUnsafe(8192),v=0);const E=b.subarray(v,v+=_);return v&7&&(v=(v|7)+1),E}}let Op$1=class{constructor(u,h,b){Z(this,"fn");Z(this,"len");Z(this,"next");Z(this,"val");this.fn=u,this.len=h,this.next=void 0,this.val=b}};function noop$4(){}let State$1=class{constructor(u){Z(this,"head");Z(this,"tail");Z(this,"len");Z(this,"next");this.head=u.head,this.tail=u.tail,this.len=u.len,this.next=u.states}};const bufferPool=pool$1();function alloc(y){return globalThis.Buffer!=null?allocUnsafe(y):bufferPool(y)}class Uint8ArrayWriter{constructor(){Z(this,"len");Z(this,"head");Z(this,"tail");Z(this,"states");this.len=0,this.head=new Op$1(noop$4,0,0),this.tail=this.head,this.states=null}_push(u,h,b){return this.tail=this.tail.next=new Op$1(u,h,b),this.len+=h,this}uint32(u){return this.len+=(this.tail=this.tail.next=new VarintOp$1((u=u>>>0)<128?1:u<16384?2:u<2097152?3:u<268435456?4:5,u)).len,this}int32(u){return u<0?this._push(writeVarint64$1,10,LongBits$2.fromNumber(u)):this.uint32(u)}sint32(u){return this.uint32((u<<1^u>>31)>>>0)}uint64(u){const h=LongBits$2.fromBigInt(u);return this._push(writeVarint64$1,h.length(),h)}uint64Number(u){return this._push(encodeUint8Array,encodingLength$1(u),u)}uint64String(u){return this.uint64(BigInt(u))}int64(u){return this.uint64(u)}int64Number(u){return this.uint64Number(u)}int64String(u){return this.uint64String(u)}sint64(u){const h=LongBits$2.fromBigInt(u).zzEncode();return this._push(writeVarint64$1,h.length(),h)}sint64Number(u){const h=LongBits$2.fromNumber(u).zzEncode();return this._push(writeVarint64$1,h.length(),h)}sint64String(u){return this.sint64(BigInt(u))}bool(u){return this._push(writeByte$1,1,u?1:0)}fixed32(u){return this._push(writeFixed32$1,4,u>>>0)}sfixed32(u){return this.fixed32(u)}fixed64(u){const h=LongBits$2.fromBigInt(u);return this._push(writeFixed32$1,4,h.lo)._push(writeFixed32$1,4,h.hi)}fixed64Number(u){const h=LongBits$2.fromNumber(u);return this._push(writeFixed32$1,4,h.lo)._push(writeFixed32$1,4,h.hi)}fixed64String(u){return this.fixed64(BigInt(u))}sfixed64(u){return this.fixed64(u)}sfixed64Number(u){return this.fixed64Number(u)}sfixed64String(u){return this.fixed64String(u)}float(u){return this._push(writeFloatLE,4,u)}double(u){return this._push(writeDoubleLE,8,u)}bytes(u){const h=u.length>>>0;return h===0?this._push(writeByte$1,1,0):this.uint32(h)._push(writeBytes$1,h,u)}string(u){const h=length$1(u);return h!==0?this.uint32(h)._push(write$1,h,u):this._push(writeByte$1,1,0)}fork(){return this.states=new State$1(this),this.head=this.tail=new Op$1(noop$4,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op$1(noop$4,0,0),this.len=0),this}ldelim(){const u=this.head,h=this.tail,b=this.len;return this.reset().uint32(b),b!==0&&(this.tail.next=u.next,this.tail=h,this.len+=b),this}finish(){let u=this.head.next;const h=alloc(this.len);let b=0;for(;u!=null;)u.fn(u.val,h,b),b+=u.len,u=u.next;return h}}function writeByte$1(y,u,h){u[h]=y&255}function writeVarint32$1(y,u,h){for(;y>127;)u[h++]=y&127|128,y>>>=7;u[h]=y}let VarintOp$1=class extends Op$1{constructor(h,b){super(writeVarint32$1,h,b);Z(this,"next");this.next=void 0}};function writeVarint64$1(y,u,h){for(;y.hi!==0;)u[h++]=y.lo&127|128,y.lo=(y.lo>>>7|y.hi<<25)>>>0,y.hi>>>=7;for(;y.lo>127;)u[h++]=y.lo&127|128,y.lo=y.lo>>>7;u[h++]=y.lo}function writeFixed32$1(y,u,h){u[h]=y&255,u[h+1]=y>>>8&255,u[h+2]=y>>>16&255,u[h+3]=y>>>24}function writeBytes$1(y,u,h){u.set(y,h)}globalThis.Buffer!=null&&(Uint8ArrayWriter.prototype.bytes=function(y){const u=y.length>>>0;return this.uint32(u),u>0&&this._push(writeBytesBuffer,u,y),this},Uint8ArrayWriter.prototype.string=function(y){const u=globalThis.Buffer.byteLength(y);return this.uint32(u),u>0&&this._push(writeStringBuffer$1,u,y),this});function writeBytesBuffer(y,u,h){u.set(y,h)}function writeStringBuffer$1(y,u,h){y.length<40?write$1(y,u,h):u.utf8Write!=null?u.utf8Write(y,h):u.set(fromString(y),h)}function createWriter(){return new Uint8ArrayWriter}function encodeMessage(y,u){const h=createWriter();return u.encode(y,h,{lengthDelimited:!1}),h.finish()}var CODEC_TYPES;(function(y){y[y.VARINT=0]="VARINT",y[y.BIT64=1]="BIT64",y[y.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",y[y.START_GROUP=3]="START_GROUP",y[y.END_GROUP=4]="END_GROUP",y[y.BIT32=5]="BIT32"})(CODEC_TYPES||(CODEC_TYPES={}));function createCodec(y,u,h,b){return{name:y,type:u,encode:h,decode:b}}function enumeration(y){function u(v){if(y[v.toString()]==null)throw new Error("Invalid enum value");return y[v]}const h=function(w,_){const E=u(w);_.int32(E)},b=function(w){const _=w.int32();return u(_)};return createCodec("enum",CODEC_TYPES.VARINT,h,b)}function message$1(y,u){return createCodec("message",CODEC_TYPES.LENGTH_DELIMITED,y,u)}class MaxLengthError extends Error{constructor(){super(...arguments);Z(this,"code","ERR_MAX_LENGTH");Z(this,"name","MaxLengthError")}}class MaxSizeError extends Error{constructor(){super(...arguments);Z(this,"code","ERR_MAX_SIZE");Z(this,"name","MaxSizeError")}}var RateLimitProof$4;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.proof!=null&&h.proof.byteLength>0&&(b.uint32(10),b.bytes(h.proof)),h.merkleRoot!=null&&h.merkleRoot.byteLength>0&&(b.uint32(18),b.bytes(h.merkleRoot)),h.epoch!=null&&h.epoch.byteLength>0&&(b.uint32(26),b.bytes(h.epoch)),h.shareX!=null&&h.shareX.byteLength>0&&(b.uint32(34),b.bytes(h.shareX)),h.shareY!=null&&h.shareY.byteLength>0&&(b.uint32(42),b.bytes(h.shareY)),h.nullifier!=null&&h.nullifier.byteLength>0&&(b.uint32(50),b.bytes(h.nullifier)),h.rlnIdentifier!=null&&h.rlnIdentifier.byteLength>0&&(b.uint32(58),b.bytes(h.rlnIdentifier)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={proof:alloc$1(0),merkleRoot:alloc$1(0),epoch:alloc$1(0),shareX:alloc$1(0),shareY:alloc$1(0),nullifier:alloc$1(0),rlnIdentifier:alloc$1(0)},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.proof=h.bytes();break}case 2:{w.merkleRoot=h.bytes();break}case 3:{w.epoch=h.bytes();break}case 4:{w.shareX=h.bytes();break}case 5:{w.shareY=h.bytes();break}case 6:{w.nullifier=h.bytes();break}case 7:{w.rlnIdentifier=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(RateLimitProof$4||(RateLimitProof$4={}));var WakuMessage$4;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.payload!=null&&h.payload.byteLength>0&&(b.uint32(10),b.bytes(h.payload)),h.contentTopic!=null&&h.contentTopic!==""&&(b.uint32(18),b.string(h.contentTopic)),h.version!=null&&(b.uint32(24),b.uint32(h.version)),h.timestamp!=null&&(b.uint32(80),b.sint64(h.timestamp)),h.meta!=null&&(b.uint32(90),b.bytes(h.meta)),h.rateLimitProof!=null&&(b.uint32(170),RateLimitProof$4.codec().encode(h.rateLimitProof,b)),h.ephemeral!=null&&(b.uint32(248),b.bool(h.ephemeral)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={payload:alloc$1(0),contentTopic:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.payload=h.bytes();break}case 2:{w.contentTopic=h.string();break}case 3:{w.version=h.uint32();break}case 10:{w.timestamp=h.sint64();break}case 11:{w.meta=h.bytes();break}case 21:{w.rateLimitProof=RateLimitProof$4.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.rateLimitProof});break}case 31:{w.ephemeral=h.bool();break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(WakuMessage$4||(WakuMessage$4={}));var FilterRequest;(function(y){(function(h){let b;h.codec=()=>(b==null&&(b=message$1((v,w,_={})=>{_.lengthDelimited!==!1&&w.fork(),v.contentTopic!=null&&v.contentTopic!==""&&(w.uint32(10),w.string(v.contentTopic)),_.lengthDelimited!==!1&&w.ldelim()},(v,w,_={})=>{const E={contentTopic:""},S=w==null?v.len:v.pos+w;for(;v.pos<S;){const x=v.uint32();switch(x>>>3){case 1:{E.contentTopic=v.string();break}default:{v.skipType(x&7);break}}}return E})),b),h.encode=v=>encodeMessage(v,h.codec()),h.decode=(v,w)=>decodeMessage(v,h.codec(),w)})(y.ContentFilter||(y.ContentFilter={}));let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.subscribe!=null&&h.subscribe!==!1&&(b.uint32(8),b.bool(h.subscribe)),h.topic!=null&&h.topic!==""&&(b.uint32(18),b.string(h.topic)),h.contentFilters!=null)for(const w of h.contentFilters)b.uint32(26),y.ContentFilter.codec().encode(w,b);v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={subscribe:!1,topic:"",contentFilters:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{w.subscribe=h.bool();break}case 2:{w.topic=h.string();break}case 3:{if(((E=v.limits)==null?void 0:E.contentFilters)!=null&&w.contentFilters.length===v.limits.contentFilters)throw new MaxLengthError('Decode error - map field "contentFilters" had too many elements');w.contentFilters.push(y.ContentFilter.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.contentFilters$}));break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(FilterRequest||(FilterRequest={}));var MessagePush$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.messages!=null)for(const w of h.messages)b.uint32(10),WakuMessage$3.codec().encode(w,b);v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={messages:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{if(((E=v.limits)==null?void 0:E.messages)!=null&&w.messages.length===v.limits.messages)throw new MaxLengthError('Decode error - map field "messages" had too many elements');w.messages.push(WakuMessage$3.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.messages$}));break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(MessagePush$1||(MessagePush$1={}));var FilterRpc;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.requestId!=null&&h.requestId!==""&&(b.uint32(10),b.string(h.requestId)),h.request!=null&&(b.uint32(18),FilterRequest.codec().encode(h.request,b)),h.push!=null&&(b.uint32(26),MessagePush$1.codec().encode(h.push,b)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={requestId:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{w.requestId=h.string();break}case 2:{w.request=FilterRequest.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.request});break}case 3:{w.push=MessagePush$1.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.push});break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(FilterRpc||(FilterRpc={}));var RateLimitProof$3;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.proof!=null&&h.proof.byteLength>0&&(b.uint32(10),b.bytes(h.proof)),h.merkleRoot!=null&&h.merkleRoot.byteLength>0&&(b.uint32(18),b.bytes(h.merkleRoot)),h.epoch!=null&&h.epoch.byteLength>0&&(b.uint32(26),b.bytes(h.epoch)),h.shareX!=null&&h.shareX.byteLength>0&&(b.uint32(34),b.bytes(h.shareX)),h.shareY!=null&&h.shareY.byteLength>0&&(b.uint32(42),b.bytes(h.shareY)),h.nullifier!=null&&h.nullifier.byteLength>0&&(b.uint32(50),b.bytes(h.nullifier)),h.rlnIdentifier!=null&&h.rlnIdentifier.byteLength>0&&(b.uint32(58),b.bytes(h.rlnIdentifier)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={proof:alloc$1(0),merkleRoot:alloc$1(0),epoch:alloc$1(0),shareX:alloc$1(0),shareY:alloc$1(0),nullifier:alloc$1(0),rlnIdentifier:alloc$1(0)},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.proof=h.bytes();break}case 2:{w.merkleRoot=h.bytes();break}case 3:{w.epoch=h.bytes();break}case 4:{w.shareX=h.bytes();break}case 5:{w.shareY=h.bytes();break}case 6:{w.nullifier=h.bytes();break}case 7:{w.rlnIdentifier=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(RateLimitProof$3||(RateLimitProof$3={}));var WakuMessage$3;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.payload!=null&&h.payload.byteLength>0&&(b.uint32(10),b.bytes(h.payload)),h.contentTopic!=null&&h.contentTopic!==""&&(b.uint32(18),b.string(h.contentTopic)),h.version!=null&&(b.uint32(24),b.uint32(h.version)),h.timestamp!=null&&(b.uint32(80),b.sint64(h.timestamp)),h.meta!=null&&(b.uint32(90),b.bytes(h.meta)),h.rateLimitProof!=null&&(b.uint32(170),RateLimitProof$3.codec().encode(h.rateLimitProof,b)),h.ephemeral!=null&&(b.uint32(248),b.bool(h.ephemeral)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={payload:alloc$1(0),contentTopic:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.payload=h.bytes();break}case 2:{w.contentTopic=h.string();break}case 3:{w.version=h.uint32();break}case 10:{w.timestamp=h.sint64();break}case 11:{w.meta=h.bytes();break}case 21:{w.rateLimitProof=RateLimitProof$3.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.rateLimitProof});break}case 31:{w.ephemeral=h.bool();break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(WakuMessage$3||(WakuMessage$3={}));var TopicOnlyMessage;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.contentTopic!=null&&h.contentTopic!==""&&(b.uint32(18),b.string(h.contentTopic)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={contentTopic:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 2:{w.contentTopic=h.string();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(TopicOnlyMessage||(TopicOnlyMessage={}));var FilterSubscribeRequest;(function(y){let u;(function(v){v.SUBSCRIBER_PING="SUBSCRIBER_PING",v.SUBSCRIBE="SUBSCRIBE",v.UNSUBSCRIBE="UNSUBSCRIBE",v.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"})(u=y.FilterSubscribeType||(y.FilterSubscribeType={}));let h;(function(v){v[v.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",v[v.SUBSCRIBE=1]="SUBSCRIBE",v[v.UNSUBSCRIBE=2]="UNSUBSCRIBE",v[v.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"})(h||(h={})),function(v){v.codec=()=>enumeration(h)}(u=y.FilterSubscribeType||(y.FilterSubscribeType={}));let b;y.codec=()=>(b==null&&(b=message$1((v,w,_={})=>{if(_.lengthDelimited!==!1&&w.fork(),v.requestId!=null&&v.requestId!==""&&(w.uint32(10),w.string(v.requestId)),v.filterSubscribeType!=null&&h[v.filterSubscribeType]!==0&&(w.uint32(16),y.FilterSubscribeType.codec().encode(v.filterSubscribeType,w)),v.pubsubTopic!=null&&(w.uint32(82),w.string(v.pubsubTopic)),v.contentTopics!=null)for(const E of v.contentTopics)w.uint32(90),w.string(E);_.lengthDelimited!==!1&&w.ldelim()},(v,w,_={})=>{var x;const E={requestId:"",filterSubscribeType:u.SUBSCRIBER_PING,contentTopics:[]},S=w==null?v.len:v.pos+w;for(;v.pos<S;){const T=v.uint32();switch(T>>>3){case 1:{E.requestId=v.string();break}case 2:{E.filterSubscribeType=y.FilterSubscribeType.codec().decode(v);break}case 10:{E.pubsubTopic=v.string();break}case 11:{if(((x=_.limits)==null?void 0:x.contentTopics)!=null&&E.contentTopics.length===_.limits.contentTopics)throw new MaxLengthError('Decode error - map field "contentTopics" had too many elements');E.contentTopics.push(v.string());break}default:{v.skipType(T&7);break}}}return E})),b),y.encode=v=>encodeMessage(v,y.codec()),y.decode=(v,w)=>decodeMessage(v,y.codec(),w)})(FilterSubscribeRequest||(FilterSubscribeRequest={}));var FilterSubscribeResponse$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.requestId!=null&&h.requestId!==""&&(b.uint32(10),b.string(h.requestId)),h.statusCode!=null&&h.statusCode!==0&&(b.uint32(80),b.uint32(h.statusCode)),h.statusDesc!=null&&(b.uint32(90),b.string(h.statusDesc)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={requestId:"",statusCode:0},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.requestId=h.string();break}case 10:{w.statusCode=h.uint32();break}case 11:{w.statusDesc=h.string();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(FilterSubscribeResponse$1||(FilterSubscribeResponse$1={}));var MessagePush;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.wakuMessage!=null&&(b.uint32(10),WakuMessage$2.codec().encode(h.wakuMessage,b)),h.pubsubTopic!=null&&(b.uint32(18),b.string(h.pubsubTopic)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.wakuMessage=WakuMessage$2.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.wakuMessage});break}case 2:{w.pubsubTopic=h.string();break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(MessagePush||(MessagePush={}));var RateLimitProof$2;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.proof!=null&&h.proof.byteLength>0&&(b.uint32(10),b.bytes(h.proof)),h.merkleRoot!=null&&h.merkleRoot.byteLength>0&&(b.uint32(18),b.bytes(h.merkleRoot)),h.epoch!=null&&h.epoch.byteLength>0&&(b.uint32(26),b.bytes(h.epoch)),h.shareX!=null&&h.shareX.byteLength>0&&(b.uint32(34),b.bytes(h.shareX)),h.shareY!=null&&h.shareY.byteLength>0&&(b.uint32(42),b.bytes(h.shareY)),h.nullifier!=null&&h.nullifier.byteLength>0&&(b.uint32(50),b.bytes(h.nullifier)),h.rlnIdentifier!=null&&h.rlnIdentifier.byteLength>0&&(b.uint32(58),b.bytes(h.rlnIdentifier)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={proof:alloc$1(0),merkleRoot:alloc$1(0),epoch:alloc$1(0),shareX:alloc$1(0),shareY:alloc$1(0),nullifier:alloc$1(0),rlnIdentifier:alloc$1(0)},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.proof=h.bytes();break}case 2:{w.merkleRoot=h.bytes();break}case 3:{w.epoch=h.bytes();break}case 4:{w.shareX=h.bytes();break}case 5:{w.shareY=h.bytes();break}case 6:{w.nullifier=h.bytes();break}case 7:{w.rlnIdentifier=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(RateLimitProof$2||(RateLimitProof$2={}));var WakuMessage$2;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.payload!=null&&h.payload.byteLength>0&&(b.uint32(10),b.bytes(h.payload)),h.contentTopic!=null&&h.contentTopic!==""&&(b.uint32(18),b.string(h.contentTopic)),h.version!=null&&(b.uint32(24),b.uint32(h.version)),h.timestamp!=null&&(b.uint32(80),b.sint64(h.timestamp)),h.meta!=null&&(b.uint32(90),b.bytes(h.meta)),h.rateLimitProof!=null&&(b.uint32(170),RateLimitProof$2.codec().encode(h.rateLimitProof,b)),h.ephemeral!=null&&(b.uint32(248),b.bool(h.ephemeral)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={payload:alloc$1(0),contentTopic:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.payload=h.bytes();break}case 2:{w.contentTopic=h.string();break}case 3:{w.version=h.uint32();break}case 10:{w.timestamp=h.sint64();break}case 11:{w.meta=h.bytes();break}case 21:{w.rateLimitProof=RateLimitProof$2.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.rateLimitProof});break}case 31:{w.ephemeral=h.bool();break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(WakuMessage$2||(WakuMessage$2={}));var PushRequest;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.pubsubTopic!=null&&h.pubsubTopic!==""&&(b.uint32(10),b.string(h.pubsubTopic)),h.message!=null&&(b.uint32(18),WakuMessage$1.codec().encode(h.message,b)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={pubsubTopic:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.pubsubTopic=h.string();break}case 2:{w.message=WakuMessage$1.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.message});break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PushRequest||(PushRequest={}));var PushResponse;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.isSuccess!=null&&h.isSuccess!==!1&&(b.uint32(8),b.bool(h.isSuccess)),h.info!=null&&(b.uint32(18),b.string(h.info)),h.statusCode!=null&&(b.uint32(80),b.uint32(h.statusCode)),h.statusDesc!=null&&(b.uint32(90),b.string(h.statusDesc)),h.relayPeerCount!=null&&(b.uint32(96),b.uint32(h.relayPeerCount)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={isSuccess:!1},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.isSuccess=h.bool();break}case 2:{w.info=h.string();break}case 10:{w.statusCode=h.uint32();break}case 11:{w.statusDesc=h.string();break}case 12:{w.relayPeerCount=h.uint32();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PushResponse||(PushResponse={}));var PushRpc$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.requestId!=null&&h.requestId!==""&&(b.uint32(10),b.string(h.requestId)),h.request!=null&&(b.uint32(18),PushRequest.codec().encode(h.request,b)),h.response!=null&&(b.uint32(26),PushResponse.codec().encode(h.response,b)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={requestId:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{w.requestId=h.string();break}case 2:{w.request=PushRequest.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.request});break}case 3:{w.response=PushResponse.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.response});break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PushRpc$1||(PushRpc$1={}));var LightPushRequestV3;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.requestId!=null&&h.requestId!==""&&(b.uint32(10),b.string(h.requestId)),h.pubsubTopic!=null&&(b.uint32(162),b.string(h.pubsubTopic)),h.message!=null&&(b.uint32(170),WakuMessage$1.codec().encode(h.message,b)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={requestId:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.requestId=h.string();break}case 20:{w.pubsubTopic=h.string();break}case 21:{w.message=WakuMessage$1.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.message});break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(LightPushRequestV3||(LightPushRequestV3={}));var LightPushResponseV3;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.requestId!=null&&h.requestId!==""&&(b.uint32(10),b.string(h.requestId)),h.statusCode!=null&&h.statusCode!==0&&(b.uint32(80),b.uint32(h.statusCode)),h.statusDesc!=null&&(b.uint32(90),b.string(h.statusDesc)),h.relayPeerCount!=null&&(b.uint32(96),b.uint32(h.relayPeerCount)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={requestId:"",statusCode:0},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.requestId=h.string();break}case 10:{w.statusCode=h.uint32();break}case 11:{w.statusDesc=h.string();break}case 12:{w.relayPeerCount=h.uint32();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(LightPushResponseV3||(LightPushResponseV3={}));var RateLimitProof$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.proof!=null&&h.proof.byteLength>0&&(b.uint32(10),b.bytes(h.proof)),h.merkleRoot!=null&&h.merkleRoot.byteLength>0&&(b.uint32(18),b.bytes(h.merkleRoot)),h.epoch!=null&&h.epoch.byteLength>0&&(b.uint32(26),b.bytes(h.epoch)),h.shareX!=null&&h.shareX.byteLength>0&&(b.uint32(34),b.bytes(h.shareX)),h.shareY!=null&&h.shareY.byteLength>0&&(b.uint32(42),b.bytes(h.shareY)),h.nullifier!=null&&h.nullifier.byteLength>0&&(b.uint32(50),b.bytes(h.nullifier)),h.rlnIdentifier!=null&&h.rlnIdentifier.byteLength>0&&(b.uint32(58),b.bytes(h.rlnIdentifier)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={proof:alloc$1(0),merkleRoot:alloc$1(0),epoch:alloc$1(0),shareX:alloc$1(0),shareY:alloc$1(0),nullifier:alloc$1(0),rlnIdentifier:alloc$1(0)},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.proof=h.bytes();break}case 2:{w.merkleRoot=h.bytes();break}case 3:{w.epoch=h.bytes();break}case 4:{w.shareX=h.bytes();break}case 5:{w.shareY=h.bytes();break}case 6:{w.nullifier=h.bytes();break}case 7:{w.rlnIdentifier=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(RateLimitProof$1||(RateLimitProof$1={}));var WakuMessage$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.payload!=null&&h.payload.byteLength>0&&(b.uint32(10),b.bytes(h.payload)),h.contentTopic!=null&&h.contentTopic!==""&&(b.uint32(18),b.string(h.contentTopic)),h.version!=null&&(b.uint32(24),b.uint32(h.version)),h.timestamp!=null&&(b.uint32(80),b.sint64(h.timestamp)),h.meta!=null&&(b.uint32(90),b.bytes(h.meta)),h.rateLimitProof!=null&&(b.uint32(170),RateLimitProof$1.codec().encode(h.rateLimitProof,b)),h.ephemeral!=null&&(b.uint32(248),b.bool(h.ephemeral)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={payload:alloc$1(0),contentTopic:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.payload=h.bytes();break}case 2:{w.contentTopic=h.string();break}case 3:{w.version=h.uint32();break}case 10:{w.timestamp=h.sint64();break}case 11:{w.meta=h.bytes();break}case 21:{w.rateLimitProof=RateLimitProof$1.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.rateLimitProof});break}case 31:{w.ephemeral=h.bool();break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(WakuMessage$1||(WakuMessage$1={}));var WakuMessageKeyValue;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.messageHash!=null&&(b.uint32(10),b.bytes(h.messageHash)),h.message!=null&&(b.uint32(18),WakuMessage.codec().encode(h.message,b)),h.pubsubTopic!=null&&(b.uint32(26),b.string(h.pubsubTopic)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.messageHash=h.bytes();break}case 2:{w.message=WakuMessage.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.message});break}case 3:{w.pubsubTopic=h.string();break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(WakuMessageKeyValue||(WakuMessageKeyValue={}));var StoreQueryRequest$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.requestId!=null&&h.requestId!==""&&(b.uint32(10),b.string(h.requestId)),h.includeData!=null&&h.includeData!==!1&&(b.uint32(16),b.bool(h.includeData)),h.pubsubTopic!=null&&(b.uint32(82),b.string(h.pubsubTopic)),h.contentTopics!=null)for(const w of h.contentTopics)b.uint32(90),b.string(w);if(h.timeStart!=null&&(b.uint32(96),b.sint64(h.timeStart)),h.timeEnd!=null&&(b.uint32(104),b.sint64(h.timeEnd)),h.messageHashes!=null)for(const w of h.messageHashes)b.uint32(162),b.bytes(w);h.paginationCursor!=null&&(b.uint32(410),b.bytes(h.paginationCursor)),h.paginationForward!=null&&h.paginationForward!==!1&&(b.uint32(416),b.bool(h.paginationForward)),h.paginationLimit!=null&&(b.uint32(424),b.uint64(h.paginationLimit)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{w.requestId=h.string();break}case 2:{w.includeData=h.bool();break}case 10:{w.pubsubTopic=h.string();break}case 11:{if(((E=v.limits)==null?void 0:E.contentTopics)!=null&&w.contentTopics.length===v.limits.contentTopics)throw new MaxLengthError('Decode error - map field "contentTopics" had too many elements');w.contentTopics.push(h.string());break}case 12:{w.timeStart=h.sint64();break}case 13:{w.timeEnd=h.sint64();break}case 20:{if(((S=v.limits)==null?void 0:S.messageHashes)!=null&&w.messageHashes.length===v.limits.messageHashes)throw new MaxLengthError('Decode error - map field "messageHashes" had too many elements');w.messageHashes.push(h.bytes());break}case 51:{w.paginationCursor=h.bytes();break}case 52:{w.paginationForward=h.bool();break}case 53:{w.paginationLimit=h.uint64();break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(StoreQueryRequest$1||(StoreQueryRequest$1={}));var StoreQueryResponse$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.requestId!=null&&h.requestId!==""&&(b.uint32(10),b.string(h.requestId)),h.statusCode!=null&&(b.uint32(80),b.uint32(h.statusCode)),h.statusDesc!=null&&(b.uint32(90),b.string(h.statusDesc)),h.messages!=null)for(const w of h.messages)b.uint32(162),WakuMessageKeyValue.codec().encode(w,b);h.paginationCursor!=null&&(b.uint32(410),b.bytes(h.paginationCursor)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={requestId:"",messages:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{w.requestId=h.string();break}case 10:{w.statusCode=h.uint32();break}case 11:{w.statusDesc=h.string();break}case 20:{if(((E=v.limits)==null?void 0:E.messages)!=null&&w.messages.length===v.limits.messages)throw new MaxLengthError('Decode error - map field "messages" had too many elements');w.messages.push(WakuMessageKeyValue.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.messages$}));break}case 51:{w.paginationCursor=h.bytes();break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(StoreQueryResponse$1||(StoreQueryResponse$1={}));var RateLimitProof;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.proof!=null&&h.proof.byteLength>0&&(b.uint32(10),b.bytes(h.proof)),h.merkleRoot!=null&&h.merkleRoot.byteLength>0&&(b.uint32(18),b.bytes(h.merkleRoot)),h.epoch!=null&&h.epoch.byteLength>0&&(b.uint32(26),b.bytes(h.epoch)),h.shareX!=null&&h.shareX.byteLength>0&&(b.uint32(34),b.bytes(h.shareX)),h.shareY!=null&&h.shareY.byteLength>0&&(b.uint32(42),b.bytes(h.shareY)),h.nullifier!=null&&h.nullifier.byteLength>0&&(b.uint32(50),b.bytes(h.nullifier)),h.rlnIdentifier!=null&&h.rlnIdentifier.byteLength>0&&(b.uint32(58),b.bytes(h.rlnIdentifier)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={proof:alloc$1(0),merkleRoot:alloc$1(0),epoch:alloc$1(0),shareX:alloc$1(0),shareY:alloc$1(0),nullifier:alloc$1(0),rlnIdentifier:alloc$1(0)},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.proof=h.bytes();break}case 2:{w.merkleRoot=h.bytes();break}case 3:{w.epoch=h.bytes();break}case 4:{w.shareX=h.bytes();break}case 5:{w.shareY=h.bytes();break}case 6:{w.nullifier=h.bytes();break}case 7:{w.rlnIdentifier=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(RateLimitProof||(RateLimitProof={}));var WakuMessage;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.payload!=null&&h.payload.byteLength>0&&(b.uint32(10),b.bytes(h.payload)),h.contentTopic!=null&&h.contentTopic!==""&&(b.uint32(18),b.string(h.contentTopic)),h.version!=null&&(b.uint32(24),b.uint32(h.version)),h.timestamp!=null&&(b.uint32(80),b.sint64(h.timestamp)),h.meta!=null&&(b.uint32(90),b.bytes(h.meta)),h.rateLimitProof!=null&&(b.uint32(170),RateLimitProof.codec().encode(h.rateLimitProof,b)),h.ephemeral!=null&&(b.uint32(248),b.bool(h.ephemeral)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={payload:alloc$1(0),contentTopic:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.payload=h.bytes();break}case 2:{w.contentTopic=h.string();break}case 3:{w.version=h.uint32();break}case 10:{w.timestamp=h.sint64();break}case 11:{w.meta=h.bytes();break}case 21:{w.rateLimitProof=RateLimitProof.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.rateLimitProof});break}case 31:{w.ephemeral=h.bool();break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(WakuMessage||(WakuMessage={}));var PeerInfo;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.enr!=null&&(b.uint32(10),b.bytes(h.enr)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.enr=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PeerInfo||(PeerInfo={}));var PeerExchangeQuery;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.numPeers!=null&&(b.uint32(8),b.uint64(h.numPeers)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.numPeers=h.uint64();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PeerExchangeQuery||(PeerExchangeQuery={}));var PeerExchangeResponse;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.peerInfos!=null)for(const w of h.peerInfos)b.uint32(10),PeerInfo.codec().encode(w,b);v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={peerInfos:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{if(((E=v.limits)==null?void 0:E.peerInfos)!=null&&w.peerInfos.length===v.limits.peerInfos)throw new MaxLengthError('Decode error - map field "peerInfos" had too many elements');w.peerInfos.push(PeerInfo.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.peerInfos$}));break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PeerExchangeResponse||(PeerExchangeResponse={}));var PeerExchangeRPC$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.query!=null&&(b.uint32(10),PeerExchangeQuery.codec().encode(h.query,b)),h.response!=null&&(b.uint32(18),PeerExchangeResponse.codec().encode(h.response,b)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{w.query=PeerExchangeQuery.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.query});break}case 2:{w.response=PeerExchangeResponse.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.response});break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PeerExchangeRPC$1||(PeerExchangeRPC$1={}));var WakuMetadataRequest;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.clusterId!=null&&(b.uint32(8),b.uint32(h.clusterId)),h.shards!=null)for(const w of h.shards)b.uint32(16),b.uint32(w);v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={shards:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.clusterId=h.uint32();break}case 2:{if(((E=v.limits)==null?void 0:E.shards)!=null&&w.shards.length===v.limits.shards)throw new MaxLengthError('Decode error - map field "shards" had too many elements');w.shards.push(h.uint32());break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(WakuMetadataRequest||(WakuMetadataRequest={}));var WakuMetadataResponse;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.clusterId!=null&&(b.uint32(8),b.uint32(h.clusterId)),h.shards!=null)for(const w of h.shards)b.uint32(16),b.uint32(w);v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={shards:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.clusterId=h.uint32();break}case 2:{if(((E=v.limits)==null?void 0:E.shards)!=null&&w.shards.length===v.limits.shards)throw new MaxLengthError('Decode error - map field "shards" had too many elements');w.shards.push(h.uint32());break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(WakuMetadataResponse||(WakuMetadataResponse={}));var HistoryEntry;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.messageId!=null&&h.messageId!==""&&(b.uint32(10),b.string(h.messageId)),h.retrievalHint!=null&&(b.uint32(18),b.bytes(h.retrievalHint)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={messageId:""},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.messageId=h.string();break}case 2:{w.retrievalHint=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(HistoryEntry||(HistoryEntry={}));var SdsMessage;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.senderId!=null&&h.senderId!==""&&(b.uint32(10),b.string(h.senderId)),h.messageId!=null&&h.messageId!==""&&(b.uint32(18),b.string(h.messageId)),h.channelId!=null&&h.channelId!==""&&(b.uint32(26),b.string(h.channelId)),h.lamportTimestamp!=null&&(b.uint32(80),b.int32(h.lamportTimestamp)),h.causalHistory!=null)for(const w of h.causalHistory)b.uint32(90),HistoryEntry.codec().encode(w,b);h.bloomFilter!=null&&(b.uint32(98),b.bytes(h.bloomFilter)),h.content!=null&&(b.uint32(162),b.bytes(h.content)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={senderId:"",messageId:"",channelId:"",causalHistory:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{w.senderId=h.string();break}case 2:{w.messageId=h.string();break}case 3:{w.channelId=h.string();break}case 10:{w.lamportTimestamp=h.int32();break}case 11:{if(((E=v.limits)==null?void 0:E.causalHistory)!=null&&w.causalHistory.length===v.limits.causalHistory)throw new MaxLengthError('Decode error - map field "causalHistory" had too many elements');w.causalHistory.push(HistoryEntry.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.causalHistory$}));break}case 12:{w.bloomFilter=h.bytes();break}case 20:{w.content=h.bytes();break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(SdsMessage||(SdsMessage={}));function isDefined(y){return!!y}function shuffle(y){if(y.length<=1)return y;const u=()=>Math.floor(Math.random()*Math.floor(y.length));for(let h=0;h<y.length;h++){const b=u(),v=y[h];y[h]=y[b],y[b]=v}return y}const MB=1024**2,SIZE_CAP_IN_MB=1;async function isMessageSizeUnderCap(y,u){const h=await y.toWire(u);return h?isWireSizeUnderCap(h):!1}const isWireSizeUnderCap=y=>y.length/MB<=SIZE_CAP_IN_MB;function isAutoSharding(y){return"clusterId"in y&&"numShardsInCluster"in y}const crypto$4=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function isBytes$3(y){return y instanceof Uint8Array||ArrayBuffer.isView(y)&&y.constructor.name==="Uint8Array"}function anumber$1(y){if(!Number.isSafeInteger(y)||y<0)throw new Error("positive integer expected, got "+y)}function abytes$2(y,...u){if(!isBytes$3(y))throw new Error("Uint8Array expected");if(u.length>0&&!u.includes(y.length))throw new Error("Uint8Array expected of length "+u+", got length="+y.length)}function ahash(y){if(typeof y!="function"||typeof y.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");anumber$1(y.outputLen),anumber$1(y.blockLen)}function aexists$1(y,u=!0){if(y.destroyed)throw new Error("Hash instance has been destroyed");if(u&&y.finished)throw new Error("Hash#digest() has already been called")}function aoutput$1(y,u){abytes$2(y);const h=u.outputLen;if(y.length<h)throw new Error("digestInto() expects output buffer of length at least "+h)}function clean$1(...y){for(let u=0;u<y.length;u++)y[u].fill(0)}function createView$1(y){return new DataView(y.buffer,y.byteOffset,y.byteLength)}function rotr(y,u){return y<<32-u|y>>>u}const hasHexBuiltin=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hexes$1=Array.from({length:256},(y,u)=>u.toString(16).padStart(2,"0"));function bytesToHex$2(y){if(abytes$2(y),hasHexBuiltin)return y.toHex();let u="";for(let h=0;h<y.length;h++)u+=hexes$1[y[h]];return u}const asciis$1={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16$1(y){if(y>=asciis$1._0&&y<=asciis$1._9)return y-asciis$1._0;if(y>=asciis$1.A&&y<=asciis$1.F)return y-(asciis$1.A-10);if(y>=asciis$1.a&&y<=asciis$1.f)return y-(asciis$1.a-10)}function hexToBytes$2(y){if(typeof y!="string")throw new Error("hex string expected, got "+typeof y);if(hasHexBuiltin)return Uint8Array.fromHex(y);const u=y.length,h=u/2;if(u%2)throw new Error("hex string expected, got unpadded hex of length "+u);const b=new Uint8Array(h);for(let v=0,w=0;v<h;v++,w+=2){const _=asciiToBase16$1(y.charCodeAt(w)),E=asciiToBase16$1(y.charCodeAt(w+1));if(_===void 0||E===void 0){const S=y[w]+y[w+1];throw new Error('hex string expected, got non-hex character "'+S+'" at index '+w)}b[v]=_*16+E}return b}function utf8ToBytes$2(y){if(typeof y!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(y))}function toBytes$1(y){return typeof y=="string"&&(y=utf8ToBytes$2(y)),abytes$2(y),y}function concatBytes$1(...y){let u=0;for(let b=0;b<y.length;b++){const v=y[b];abytes$2(v),u+=v.length}const h=new Uint8Array(u);for(let b=0,v=0;b<y.length;b++){const w=y[b];h.set(w,v),v+=w.length}return h}let Hash$8=class{};function createHasher(y){const u=b=>y().update(toBytes$1(b)).digest(),h=y();return u.outputLen=h.outputLen,u.blockLen=h.blockLen,u.create=()=>y(),u}function randomBytes$4(y=32){if(crypto$4&&typeof crypto$4.getRandomValues=="function")return crypto$4.getRandomValues(new Uint8Array(y));if(crypto$4&&typeof crypto$4.randomBytes=="function")return Uint8Array.from(crypto$4.randomBytes(y));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64$1(y,u,h,b){if(typeof y.setBigUint64=="function")return y.setBigUint64(u,h,b);const v=BigInt(32),w=BigInt(4294967295),_=Number(h>>v&w),E=Number(h&w),S=b?4:0,x=b?0:4;y.setUint32(u+S,_,b),y.setUint32(u+x,E,b)}function Chi(y,u,h){return y&u^~y&h}function Maj(y,u,h){return y&u^y&h^u&h}class HashMD extends Hash$8{constructor(u,h,b,v){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=u,this.outputLen=h,this.padOffset=b,this.isLE=v,this.buffer=new Uint8Array(u),this.view=createView$1(this.buffer)}update(u){aexists$1(this),u=toBytes$1(u),abytes$2(u);const{view:h,buffer:b,blockLen:v}=this,w=u.length;for(let _=0;_<w;){const E=Math.min(v-this.pos,w-_);if(E===v){const S=createView$1(u);for(;v<=w-_;_+=v)this.process(S,_);continue}b.set(u.subarray(_,_+E),this.pos),this.pos+=E,_+=E,this.pos===v&&(this.process(h,0),this.pos=0)}return this.length+=u.length,this.roundClean(),this}digestInto(u){aexists$1(this),aoutput$1(u,this),this.finished=!0;const{buffer:h,view:b,blockLen:v,isLE:w}=this;let{pos:_}=this;h[_++]=128,clean$1(this.buffer.subarray(_)),this.padOffset>v-_&&(this.process(b,0),_=0);for(let C=_;C<v;C++)h[C]=0;setBigUint64$1(b,v-8,BigInt(this.length*8),w),this.process(b,0);const E=createView$1(u),S=this.outputLen;if(S%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const x=S/4,T=this.get();if(x>T.length)throw new Error("_sha2: outputLen bigger than state");for(let C=0;C<x;C++)E.setUint32(4*C,T[C],w)}digest(){const{buffer:u,outputLen:h}=this;this.digestInto(u);const b=u.slice(0,h);return this.destroy(),b}_cloneInto(u){u||(u=new this.constructor),u.set(...this.get());const{blockLen:h,buffer:b,length:v,finished:w,destroyed:_,pos:E}=this;return u.destroyed=_,u.finished=w,u.length=v,u.pos=E,v%h&&u.buffer.set(b),u}clone(){return this._cloneInto()}}const SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(y,u=!1){return u?{h:Number(y&U32_MASK64),l:Number(y>>_32n&U32_MASK64)}:{h:Number(y>>_32n&U32_MASK64)|0,l:Number(y&U32_MASK64)|0}}function split(y,u=!1){const h=y.length;let b=new Uint32Array(h),v=new Uint32Array(h);for(let w=0;w<h;w++){const{h:_,l:E}=fromBig(y[w],u);[b[w],v[w]]=[_,E]}return[b,v]}const shrSH=(y,u,h)=>y>>>h,shrSL=(y,u,h)=>y<<32-h|u>>>h,rotrSH=(y,u,h)=>y>>>h|u<<32-h,rotrSL=(y,u,h)=>y<<32-h|u>>>h,rotrBH=(y,u,h)=>y<<64-h|u>>>h-32,rotrBL=(y,u,h)=>y>>>h-32|u<<64-h;function add(y,u,h,b){const v=(u>>>0)+(b>>>0);return{h:y+h+(v/2**32|0)|0,l:v|0}}const add3L=(y,u,h)=>(y>>>0)+(u>>>0)+(h>>>0),add3H=(y,u,h,b)=>u+h+b+(y/2**32|0)|0,add4L=(y,u,h,b)=>(y>>>0)+(u>>>0)+(h>>>0)+(b>>>0),add4H=(y,u,h,b,v)=>u+h+b+v+(y/2**32|0)|0,add5L=(y,u,h,b,v)=>(y>>>0)+(u>>>0)+(h>>>0)+(b>>>0)+(v>>>0),add5H=(y,u,h,b,v,w)=>u+h+b+v+w+(y/2**32|0)|0,SHA256_K=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]),SHA256_W=new Uint32Array(64);let SHA256$2=class extends HashMD{constructor(u=32){super(64,u,8,!1),this.A=SHA256_IV[0]|0,this.B=SHA256_IV[1]|0,this.C=SHA256_IV[2]|0,this.D=SHA256_IV[3]|0,this.E=SHA256_IV[4]|0,this.F=SHA256_IV[5]|0,this.G=SHA256_IV[6]|0,this.H=SHA256_IV[7]|0}get(){const{A:u,B:h,C:b,D:v,E:w,F:_,G:E,H:S}=this;return[u,h,b,v,w,_,E,S]}set(u,h,b,v,w,_,E,S){this.A=u|0,this.B=h|0,this.C=b|0,this.D=v|0,this.E=w|0,this.F=_|0,this.G=E|0,this.H=S|0}process(u,h){for(let C=0;C<16;C++,h+=4)SHA256_W[C]=u.getUint32(h,!1);for(let C=16;C<64;C++){const O=SHA256_W[C-15],D=SHA256_W[C-2],U=rotr(O,7)^rotr(O,18)^O>>>3,te=rotr(D,17)^rotr(D,19)^D>>>10;SHA256_W[C]=te+SHA256_W[C-7]+U+SHA256_W[C-16]|0}let{A:b,B:v,C:w,D:_,E,F:S,G:x,H:T}=this;for(let C=0;C<64;C++){const O=rotr(E,6)^rotr(E,11)^rotr(E,25),D=T+O+Chi(E,S,x)+SHA256_K[C]+SHA256_W[C]|0,te=(rotr(b,2)^rotr(b,13)^rotr(b,22))+Maj(b,v,w)|0;T=x,x=S,S=E,E=_+D|0,_=w,w=v,v=b,b=D+te|0}b=b+this.A|0,v=v+this.B|0,w=w+this.C|0,_=_+this.D|0,E=E+this.E|0,S=S+this.F|0,x=x+this.G|0,T=T+this.H|0,this.set(b,v,w,_,E,S,x,T)}roundClean(){clean$1(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0),clean$1(this.buffer)}};const K512=split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(y=>BigInt(y))),SHA512_Kh=K512[0],SHA512_Kl=K512[1],SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);let SHA512$3=class extends HashMD{constructor(u=64){super(128,u,16,!1),this.Ah=SHA512_IV[0]|0,this.Al=SHA512_IV[1]|0,this.Bh=SHA512_IV[2]|0,this.Bl=SHA512_IV[3]|0,this.Ch=SHA512_IV[4]|0,this.Cl=SHA512_IV[5]|0,this.Dh=SHA512_IV[6]|0,this.Dl=SHA512_IV[7]|0,this.Eh=SHA512_IV[8]|0,this.El=SHA512_IV[9]|0,this.Fh=SHA512_IV[10]|0,this.Fl=SHA512_IV[11]|0,this.Gh=SHA512_IV[12]|0,this.Gl=SHA512_IV[13]|0,this.Hh=SHA512_IV[14]|0,this.Hl=SHA512_IV[15]|0}get(){const{Ah:u,Al:h,Bh:b,Bl:v,Ch:w,Cl:_,Dh:E,Dl:S,Eh:x,El:T,Fh:C,Fl:O,Gh:D,Gl:U,Hh:te,Hl:X}=this;return[u,h,b,v,w,_,E,S,x,T,C,O,D,U,te,X]}set(u,h,b,v,w,_,E,S,x,T,C,O,D,U,te,X){this.Ah=u|0,this.Al=h|0,this.Bh=b|0,this.Bl=v|0,this.Ch=w|0,this.Cl=_|0,this.Dh=E|0,this.Dl=S|0,this.Eh=x|0,this.El=T|0,this.Fh=C|0,this.Fl=O|0,this.Gh=D|0,this.Gl=U|0,this.Hh=te|0,this.Hl=X|0}process(u,h){for(let ae=0;ae<16;ae++,h+=4)SHA512_W_H[ae]=u.getUint32(h),SHA512_W_L[ae]=u.getUint32(h+=4);for(let ae=16;ae<80;ae++){const de=SHA512_W_H[ae-15]|0,Se=SHA512_W_L[ae-15]|0,ve=rotrSH(de,Se,1)^rotrSH(de,Se,8)^shrSH(de,Se,7),Pe=rotrSL(de,Se,1)^rotrSL(de,Se,8)^shrSL(de,Se,7),Ie=SHA512_W_H[ae-2]|0,Ee=SHA512_W_L[ae-2]|0,De=rotrSH(Ie,Ee,19)^rotrBH(Ie,Ee,61)^shrSH(Ie,Ee,6),be=rotrSL(Ie,Ee,19)^rotrBL(Ie,Ee,61)^shrSL(Ie,Ee,6),B=add4L(Pe,be,SHA512_W_L[ae-7],SHA512_W_L[ae-16]),F=add4H(B,ve,De,SHA512_W_H[ae-7],SHA512_W_H[ae-16]);SHA512_W_H[ae]=F|0,SHA512_W_L[ae]=B|0}let{Ah:b,Al:v,Bh:w,Bl:_,Ch:E,Cl:S,Dh:x,Dl:T,Eh:C,El:O,Fh:D,Fl:U,Gh:te,Gl:X,Hh:ie,Hl:ee}=this;for(let ae=0;ae<80;ae++){const de=rotrSH(C,O,14)^rotrSH(C,O,18)^rotrBH(C,O,41),Se=rotrSL(C,O,14)^rotrSL(C,O,18)^rotrBL(C,O,41),ve=C&D^~C&te,Pe=O&U^~O&X,Ie=add5L(ee,Se,Pe,SHA512_Kl[ae],SHA512_W_L[ae]),Ee=add5H(Ie,ie,de,ve,SHA512_Kh[ae],SHA512_W_H[ae]),De=Ie|0,be=rotrSH(b,v,28)^rotrBH(b,v,34)^rotrBH(b,v,39),B=rotrSL(b,v,28)^rotrBL(b,v,34)^rotrBL(b,v,39),F=b&w^b&E^w&E,M=v&_^v&S^_&S;ie=te|0,ee=X|0,te=D|0,X=U|0,D=C|0,U=O|0,{h:C,l:O}=add(x|0,T|0,Ee|0,De|0),x=E|0,T=S|0,E=w|0,S=_|0,w=b|0,_=v|0;const N=add3L(De,B,M);b=add3H(N,Ee,be,F),v=N|0}({h:b,l:v}=add(this.Ah|0,this.Al|0,b|0,v|0)),{h:w,l:_}=add(this.Bh|0,this.Bl|0,w|0,_|0),{h:E,l:S}=add(this.Ch|0,this.Cl|0,E|0,S|0),{h:x,l:T}=add(this.Dh|0,this.Dl|0,x|0,T|0),{h:C,l:O}=add(this.Eh|0,this.El|0,C|0,O|0),{h:D,l:U}=add(this.Fh|0,this.Fl|0,D|0,U|0),{h:te,l:X}=add(this.Gh|0,this.Gl|0,te|0,X|0),{h:ie,l:ee}=add(this.Hh|0,this.Hl|0,ie|0,ee|0),this.set(b,v,w,_,E,S,x,T,C,O,D,U,te,X,ie,ee)}roundClean(){clean$1(SHA512_W_H,SHA512_W_L)}destroy(){clean$1(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};const sha256$3=createHasher(()=>new SHA256$2),sha512$2=createHasher(()=>new SHA512$3),sha256$2=sha256$3;function toString$1(y,u="utf8"){const h=BASES[u];if(h==null)throw new Error(`Unsupported encoding "${u}"`);return h.encoder.encode(y).substring(1)}function hexToBytes$1(y){if(typeof y=="string"){const u=y.replace(/^0x/i,"");return fromString(u.toLowerCase(),"base16")}return y}function numberToBytes(y){const u=new ArrayBuffer(8),h=new DataView(u);return typeof y=="number"?h.setFloat64(0,y,!1):h.setBigInt64(0,y,!1),new Uint8Array(u)}const bytesToHex$1=y=>toString$1(y,"base16"),bytesToUtf8=y=>toString$1(y,"utf8"),utf8ToBytes$1=y=>fromString(y,"utf8");function concat$1(y,u){const h=y.reduce((w,_)=>w+_.length,0),b=new Uint8Array(h);let v=0;for(const w of y)b.set(w,v),v+=w.length;return b}const formatPubsubTopic=(y,u)=>`/waku/2/rs/${y}/${u}`,pubsubTopicToSingleShardInfo=y=>{const u=y.split("/");if(u.length!=6||u[1]!=="waku"||u[2]!=="2"||u[3]!=="rs")throw new Error("Invalid pubsub topic");const h=parseInt(u[4]),b=parseInt(u[5]);if(isNaN(h)||isNaN(b))throw new Error("Invalid clusterId or shard");return{clusterId:h,shard:b}};function ensureValidContentTopic(y){const u=y.split("/");if(u.length<5||u.length>6)throw Error(`Content topic format is invalid: ${y}`);let h=0;if(u.length==6){if(h=parseInt(u[1]),isNaN(h))throw new Error(`Invalid generation field in content topic: ${y}`);if(h>0)throw new Error(`Generation greater than 0 is not supported: ${y}`)}const b=u.splice(-4);if(b[0].length==0)throw new Error(`Application field cannot be empty: ${y}`);if(b[1].length==0)throw new Error(`Version field cannot be empty: ${y}`);if(b[2].length==0)throw new Error(`Topic name field cannot be empty: ${y}`);if(b[3].length==0)throw new Error(`Encoding field cannot be empty: ${y}`);return{generation:h,application:b[0],version:b[1],topicName:b[2],encoding:b[3]}}function contentTopicToShardIndex(y,u){const{application:h,version:b}=ensureValidContentTopic(y),v=sha256$2(concat$1([utf8ToBytes$1(h),utf8ToBytes$1(b)])),w=new DataView(v.buffer.slice(-8));return Number(w.getBigUint64(0,!1)%BigInt(u))}class BaseRoutingInfo{constructor(u,h,b){Z(this,"networkConfig");Z(this,"pubsubTopic");Z(this,"shardId");this.networkConfig=u,this.pubsubTopic=h,this.shardId=b}}class AutoShardingRoutingInfo extends BaseRoutingInfo{constructor(h,b,v,w){super(h,b,v);Z(this,"networkConfig");Z(this,"pubsubTopic");Z(this,"shardId");Z(this,"contentTopic");this.networkConfig=h,this.pubsubTopic=b,this.shardId=v,this.contentTopic=w}static fromContentTopic(h,b){ensureValidContentTopic(h);const v=contentTopicToShardIndex(h,b.numShardsInCluster),w=formatPubsubTopic(b.clusterId,v);return new AutoShardingRoutingInfo(b,w,v,h)}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!0}get isStaticSharding(){return!1}}class StaticShardingRoutingInfo extends BaseRoutingInfo{constructor(h,b,v){super(h,b,v);Z(this,"networkConfig");Z(this,"pubsubTopic");Z(this,"shardId");this.networkConfig=h,this.pubsubTopic=b,this.shardId=v}static fromShard(h,b){const v=formatPubsubTopic(b.clusterId,h);return new StaticShardingRoutingInfo(b,v,h)}static fromPubsubTopic(h,b){const{clusterId:v,shard:w}=pubsubTopicToSingleShardInfo(h);if(v!=b.clusterId)throw"Pubsub topic does not match network config's cluster id";return new StaticShardingRoutingInfo(b,h,w)}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!1}get isStaticSharding(){return!0}}function createRoutingInfo(y,u){if(isAutoSharding(y)){if(u.contentTopic)return AutoShardingRoutingInfo.fromContentTopic(u.contentTopic,y);throw new Error("AutoSharding requires contentTopic")}else{if(u.shardId!==void 0)return StaticShardingRoutingInfo.fromShard(u.shardId,y);if(u.pubsubTopic)return StaticShardingRoutingInfo.fromPubsubTopic(u.pubsubTopic,y);throw new Error("StaticSharding requires shardId or pubsubTopic")}}const decodeRelayShard=y=>{if(y=new Uint8Array(y),y.length<3)throw new Error("Insufficient data");const u=new DataView(y.buffer),h=u.getUint16(0),b=[];if(y.length===130)for(let v=0;v<1024;v++){const w=Math.floor(v/8)+2,_=7-v%8;u.getUint8(w)&1<<_&&b.push(v)}else{const v=u.getUint8(2);for(let w=0,_=3;w<v;w++,_+=2){if(_+1>=y.length)throw new Error("Unexpected end of data");b.push(u.getUint16(_))}}return{clusterId:h,shards:b}},encodeRelayShard=y=>{const{clusterId:u,shards:h}=y,b=h.length>=64?130:3+2*h.length,v=new ArrayBuffer(b),w=new DataView(v);if(w.setUint16(0,u),h.length>=64)for(const _ of h){const E=Math.floor(_/8)+2,S=7-_%8;w.setUint8(E,w.getUint8(E)|1<<S)}else{w.setUint8(2,h.length);for(let _=0,E=3;_<h.length;_++,E+=2)w.setUint16(E,h[_])}return new Uint8Array(v)},connectionSymbol=Symbol.for("@libp2p/connection"),contentRoutingSymbol=Symbol.for("@libp2p/content-routing"),peerDiscoverySymbol=Symbol.for("@libp2p/peer-discovery"),peerIdSymbol=Symbol.for("@libp2p/peer-id");function isPeerId(y){return!!(y!=null&&y[peerIdSymbol])}const peerRoutingSymbol=Symbol.for("@libp2p/peer-routing"),KEEP_ALIVE="keep-alive",transportSymbol=Symbol.for("@libp2p/transport");var FaultTolerance;(function(y){y[y.FATAL_ALL=0]="FATAL_ALL",y[y.NO_FATAL=1]="NO_FATAL"})(FaultTolerance||(FaultTolerance={}));var ql;let AbortError$5=(ql=class extends Error{constructor(u="The operation was aborted"){super(u),this.name="AbortError"}},Z(ql,"name","AbortError"),ql);class UnexpectedPeerError extends Error{constructor(u="Unexpected Peer"){super(u),this.name="UnexpectedPeerError"}}Z(UnexpectedPeerError,"name","UnexpectedPeerError");var Hl;let InvalidCryptoExchangeError$1=(Hl=class extends Error{constructor(u="Invalid crypto exchange"){super(u),this.name="InvalidCryptoExchangeError"}},Z(Hl,"name","InvalidCryptoExchangeError"),Hl);var Kl;let InvalidParametersError$2=(Kl=class extends Error{constructor(u="Invalid parameters"){super(u),this.name="InvalidParametersError"}},Z(Kl,"name","InvalidParametersError"),Kl);var Vl;let InvalidPublicKeyError$1=(Vl=class extends Error{constructor(u="Invalid public key"){super(u),this.name="InvalidPublicKeyError"}},Z(Vl,"name","InvalidPublicKeyError"),Vl);class ConnectionClosingError extends Error{constructor(u="The connection is closing"){super(u),this.name="ConnectionClosingError"}}Z(ConnectionClosingError,"name","ConnectionClosingError");class ConnectionClosedError extends Error{constructor(u="The connection is closed"){super(u),this.name="ConnectionClosedError"}}Z(ConnectionClosedError,"name","ConnectionClosedError");class ConnectionFailedError extends Error{constructor(u="Connection failed"){super(u),this.name="ConnectionFailedError"}}Z(ConnectionFailedError,"name","ConnectionFailedError");class MuxerClosedError extends Error{constructor(u="The muxer is closed"){super(u),this.name="MuxerClosedError"}}Z(MuxerClosedError,"name","MuxerClosedError");class StreamResetError extends Error{constructor(u="The stream has been reset"){super(u),this.name="StreamResetError"}}Z(StreamResetError,"name","StreamResetError");class StreamStateError extends Error{constructor(u="The stream is in an invalid state"){super(u),this.name="StreamStateError"}}Z(StreamStateError,"name","StreamStateError");var Zl;let NotFoundError$1=(Zl=class extends Error{constructor(u="Not found"){super(u),this.name="NotFoundError"}},Z(Zl,"name","NotFoundError"),Zl);class InvalidPeerIdError extends Error{constructor(u="Invalid PeerID"){super(u),this.name="InvalidPeerIdError"}}Z(InvalidPeerIdError,"name","InvalidPeerIdError");var Wl;let InvalidMultiaddrError$1=(Wl=class extends Error{constructor(u="Invalid multiaddr"){super(u),this.name="InvalidMultiaddrError"}},Z(Wl,"name","InvalidMultiaddrError"),Wl);class InvalidCIDError extends Error{constructor(u="Invalid CID"){super(u),this.name="InvalidCIDError"}}Z(InvalidCIDError,"name","InvalidCIDError");class InvalidMultihashError extends Error{constructor(u="Invalid Multihash"){super(u),this.name="InvalidMultihashError"}}Z(InvalidMultihashError,"name","InvalidMultihashError");class UnsupportedProtocolError extends Error{constructor(u="Unsupported protocol error"){super(u),this.name="UnsupportedProtocolError"}}Z(UnsupportedProtocolError,"name","UnsupportedProtocolError");class InvalidMessageError extends Error{constructor(u="Invalid message"){super(u),this.name="InvalidMessageError"}}Z(InvalidMessageError,"name","InvalidMessageError");var Gl;let ProtocolError$1=(Gl=class extends Error{constructor(u="Protocol error"){super(u),this.name="ProtocolError"}},Z(Gl,"name","ProtocolError"),Gl);var jl;let TimeoutError$1=(jl=class extends Error{constructor(u="Timed out"){super(u),this.name="TimeoutError"}},Z(jl,"name","TimeoutError"),jl);class NotStartedError extends Error{constructor(u="Not started"){super(u),this.name="NotStartedError"}}Z(NotStartedError,"name","NotStartedError");class DialError extends Error{constructor(u="Dial error"){super(u),this.name="DialError"}}Z(DialError,"name","DialError");class LimitedConnectionError extends Error{constructor(u="Limited connection"){super(u),this.name="LimitedConnectionError"}}Z(LimitedConnectionError,"name","LimitedConnectionError");class TooManyInboundProtocolStreamsError extends Error{constructor(u="Too many inbound protocol streams"){super(u),this.name="TooManyInboundProtocolStreamsError"}}Z(TooManyInboundProtocolStreamsError,"name","TooManyInboundProtocolStreamsError");class TooManyOutboundProtocolStreamsError extends Error{constructor(u="Too many outbound protocol streams"){super(u),this.name="TooManyOutboundProtocolStreamsError"}}Z(TooManyOutboundProtocolStreamsError,"name","TooManyOutboundProtocolStreamsError");var Xl;let UnsupportedKeyTypeError$1=(Xl=class extends Error{constructor(u="Unsupported key type"){super(u),this.name="UnsupportedKeyTypeError"}},Z(Xl,"name","UnsupportedKeyTypeError"),Xl);function setMaxListeners(){}var hi;class TypedEventEmitter extends EventTarget{constructor(){super();ur(this,hi,new Map)}listenerCount(h){const b=je(this,hi).get(h);return b==null?0:b.length}addEventListener(h,b,v){super.addEventListener(h,b,v);let w=je(this,hi).get(h);w==null&&(w=[],je(this,hi).set(h,w)),w.push({callback:b,once:(v!==!0&&v!==!1&&(v==null?void 0:v.once))??!1})}removeEventListener(h,b,v){super.removeEventListener(h.toString(),b??null,v);let w=je(this,hi).get(h);w!=null&&(w=w.filter(({callback:_})=>_!==b),je(this,hi).set(h,w))}dispatchEvent(h){const b=super.dispatchEvent(h);let v=je(this,hi).get(h.type);return v==null||(v=v.filter(({once:w})=>!w),je(this,hi).set(h.type,v)),b}safeDispatchEvent(h,b={}){return this.dispatchEvent(new CustomEvent(h,b))}}hi=new WeakMap;function isStartable(y){return y!=null&&typeof y.start=="function"&&typeof y.stop=="function"}async function start(...y){const u=[];for(const h of y)isStartable(h)&&u.push(h);await Promise.all(u.map(async h=>{h.beforeStart!=null&&await h.beforeStart()})),await Promise.all(u.map(async h=>{await h.start()})),await Promise.all(u.map(async h=>{h.afterStart!=null&&await h.afterStart()}))}async function stop(...y){const u=[];for(const h of y)isStartable(h)&&u.push(h);await Promise.all(u.map(async h=>{h.beforeStop!=null&&await h.beforeStop()})),await Promise.all(u.map(async h=>{await h.stop()})),await Promise.all(u.map(async h=>{h.afterStop!=null&&await h.afterStop()}))}const serviceCapabilities=Symbol.for("@libp2p/service-capabilities"),serviceDependencies=Symbol.for("@libp2p/service-dependencies");function getDefaultExportFromCjs(y){return y&&y.__esModule&&Object.prototype.hasOwnProperty.call(y,"default")?y.default:y}var browser$d={exports:{}},process=browser$d.exports={},cachedSetTimeout,cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?cachedSetTimeout=setTimeout:cachedSetTimeout=defaultSetTimout}catch{cachedSetTimeout=defaultSetTimout}try{typeof clearTimeout=="function"?cachedClearTimeout=clearTimeout:cachedClearTimeout=defaultClearTimeout}catch{cachedClearTimeout=defaultClearTimeout}})();function runTimeout(y){if(cachedSetTimeout===setTimeout)return setTimeout(y,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(y,0);try{return cachedSetTimeout(y,0)}catch{try{return cachedSetTimeout.call(null,y,0)}catch{return cachedSetTimeout.call(this,y,0)}}}function runClearTimeout(y){if(cachedClearTimeout===clearTimeout)return clearTimeout(y);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(y);try{return cachedClearTimeout(y)}catch{try{return cachedClearTimeout.call(null,y)}catch{return cachedClearTimeout.call(this,y)}}}var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){!draining||!currentQueue||(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var y=runTimeout(cleanUpNextTick);draining=!0;for(var u=queue.length;u;){for(currentQueue=queue,queue=[];++queueIndex<u;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,u=queue.length}currentQueue=null,draining=!1,runClearTimeout(y)}}process.nextTick=function(y){var u=new Array(arguments.length-1);if(arguments.length>1)for(var h=1;h<arguments.length;h++)u[h-1]=arguments[h];queue.push(new Item(y,u)),queue.length===1&&!draining&&runTimeout(drainQueue)};function Item(y,u){this.fun=y,this.array=u}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=!0;process.env={};process.argv=[];process.version="";process.versions={};function noop$3(){}process.on=noop$3;process.addListener=noop$3;process.once=noop$3;process.off=noop$3;process.removeListener=noop$3;process.removeAllListeners=noop$3;process.emit=noop$3;process.prependListener=noop$3;process.prependOnceListener=noop$3;process.listeners=function(y){return[]};process.binding=function(y){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(y){throw new Error("process.chdir is not supported")};process.umask=function(){return 0};var browserExports$2=browser$d.exports;const process$1=getDefaultExportFromCjs(browserExports$2);var browser$c={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var y=1e3,u=y*60,h=u*60,b=h*24,v=b*7,w=b*365.25;ms=function(T,C){C=C||{};var O=typeof T;if(O==="string"&&T.length>0)return _(T);if(O==="number"&&isFinite(T))return C.long?S(T):E(T);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(T))};function _(T){if(T=String(T),!(T.length>100)){var C=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(T);if(C){var O=parseFloat(C[1]),D=(C[2]||"ms").toLowerCase();switch(D){case"years":case"year":case"yrs":case"yr":case"y":return O*w;case"weeks":case"week":case"w":return O*v;case"days":case"day":case"d":return O*b;case"hours":case"hour":case"hrs":case"hr":case"h":return O*h;case"minutes":case"minute":case"mins":case"min":case"m":return O*u;case"seconds":case"second":case"secs":case"sec":case"s":return O*y;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return O;default:return}}}}function E(T){var C=Math.abs(T);return C>=b?Math.round(T/b)+"d":C>=h?Math.round(T/h)+"h":C>=u?Math.round(T/u)+"m":C>=y?Math.round(T/y)+"s":T+"ms"}function S(T){var C=Math.abs(T);return C>=b?x(T,C,b,"day"):C>=h?x(T,C,h,"hour"):C>=u?x(T,C,u,"minute"):C>=y?x(T,C,y,"second"):T+" ms"}function x(T,C,O,D){var U=C>=O*1.5;return Math.round(T/O)+" "+D+(U?"s":"")}return ms}function setup$1(y){h.debug=h,h.default=h,h.coerce=S,h.disable=_,h.enable=v,h.enabled=E,h.humanize=requireMs(),h.destroy=x,Object.keys(y).forEach(T=>{h[T]=y[T]}),h.names=[],h.skips=[],h.formatters={};function u(T){let C=0;for(let O=0;O<T.length;O++)C=(C<<5)-C+T.charCodeAt(O),C|=0;return h.colors[Math.abs(C)%h.colors.length]}h.selectColor=u;function h(T){let C,O=null,D,U;function te(...X){if(!te.enabled)return;const ie=te,ee=Number(new Date),ae=ee-(C||ee);ie.diff=ae,ie.prev=C,ie.curr=ee,C=ee,X[0]=h.coerce(X[0]),typeof X[0]!="string"&&X.unshift("%O");let de=0;X[0]=X[0].replace(/%([a-zA-Z%])/g,(ve,Pe)=>{if(ve==="%%")return"%";de++;const Ie=h.formatters[Pe];if(typeof Ie=="function"){const Ee=X[de];ve=Ie.call(ie,Ee),X.splice(de,1),de--}return ve}),h.formatArgs.call(ie,X),(ie.log||h.log).apply(ie,X)}return te.namespace=T,te.useColors=h.useColors(),te.color=h.selectColor(T),te.extend=b,te.destroy=h.destroy,Object.defineProperty(te,"enabled",{enumerable:!0,configurable:!1,get:()=>O!==null?O:(D!==h.namespaces&&(D=h.namespaces,U=h.enabled(T)),U),set:X=>{O=X}}),typeof h.init=="function"&&h.init(te),te}function b(T,C){const O=h(this.namespace+(typeof C>"u"?":":C)+T);return O.log=this.log,O}function v(T){h.save(T),h.namespaces=T,h.names=[],h.skips=[];const C=(typeof T=="string"?T:"").trim().replace(" ",",").split(",").filter(Boolean);for(const O of C)O[0]==="-"?h.skips.push(O.slice(1)):h.names.push(O)}function w(T,C){let O=0,D=0,U=-1,te=0;for(;O<T.length;)if(D<C.length&&(C[D]===T[O]||C[D]==="*"))C[D]==="*"?(U=D,te=O,D++):(O++,D++);else if(U!==-1)D=U+1,te++,O=te;else return!1;for(;D<C.length&&C[D]==="*";)D++;return D===C.length}function _(){const T=[...h.names,...h.skips.map(C=>"-"+C)].join(",");return h.enable(""),T}function E(T){for(const C of h.skips)if(w(T,C))return!1;for(const C of h.names)if(w(T,C))return!0;return!1}function S(T){return T instanceof Error?T.stack||T.message:T}function x(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return h.enable(h.load()),h}var common$7=setup$1;(function(y,u){u.formatArgs=b,u.save=v,u.load=w,u.useColors=h,u.storage=_(),u.destroy=(()=>{let S=!1;return()=>{S||(S=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),u.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function h(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let S;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(S=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(S[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function b(S){if(S[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+S[0]+(this.useColors?"%c ":" ")+"+"+y.exports.humanize(this.diff),!this.useColors)return;const x="color: "+this.color;S.splice(1,0,x,"color: inherit");let T=0,C=0;S[0].replace(/%[a-zA-Z%]/g,O=>{O!=="%%"&&(T++,O==="%c"&&(C=T))}),S.splice(C,0,x)}u.log=console.debug||console.log||(()=>{});function v(S){try{S?u.storage.setItem("debug",S):u.storage.removeItem("debug")}catch{}}function w(){let S;try{S=u.storage.getItem("debug")}catch{}return!S&&typeof process$1<"u"&&"env"in process$1&&(S=process$1.env.DEBUG),S}function _(){try{return localStorage}catch{}}y.exports=common$7(u);const{formatters:E}=y.exports;E.j=function(S){try{return JSON.stringify(S)}catch(x){return"[UnexpectedJSONParseError]: "+x.message}}})(browser$c,browser$c.exports);var browserExports$1=browser$c.exports;const debug=getDefaultExportFromCjs$1(browserExports$1),APP_NAME="waku";let Logger$1=class Ou{constructor(u){Z(this,"_info");Z(this,"_warn");Z(this,"_error");this._info=debug(Ou.createDebugNamespace("info",u)),this._warn=debug(Ou.createDebugNamespace("warn",u)),this._error=debug(Ou.createDebugNamespace("error",u))}static createDebugNamespace(u,h){return h?`${APP_NAME}:${h}:${u}`:`${APP_NAME}:${u}`}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(u,...h){(this[u]||this.log)(...h)}};function messageHash(y,u){const h=utf8ToBytes$1(y),b=utf8ToBytes$1(u.contentTopic),v=tryConvertTimestampToBytes(u.timestamp),w=concat$1([h,u.payload,b,u.meta,v].filter(isDefined));return sha256$2(w)}function tryConvertTimestampToBytes(y){if(!y)return;let u;return typeof y=="bigint"?u=y:u=BigInt(y.valueOf())*1000000n,numberToBytes(u)}function messageHashStr(y,u){const h=messageHash(y,u);return bytesToHex$1(h)}const log$w=new Logger$1("message:version-0"),OneMillion=BigInt(1e6),Version=0;class DecodedMessage{constructor(u,h){Z(this,"pubsubTopic");Z(this,"proto");Z(this,"_hash");Z(this,"_hashStr");this.pubsubTopic=u,this.proto=h}get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get hash(){return this._hash===void 0&&(this._hash=messageHash(this.pubsubTopic,this.proto)),this._hash}get hashStr(){return this._hashStr===void 0&&(this._hashStr=bytesToHex$1(this.hash)),this._hashStr}get timestamp(){try{if(this.proto.timestamp){const u=this.proto.timestamp/OneMillion;return new Date(Number(u))}return}catch{return}}get meta(){return this.proto.meta}get version(){return this.proto.version??Version}get rateLimitProof(){return this.proto.rateLimitProof}}let Encoder$1=class{constructor(u,h=!1,b,v){Z(this,"contentTopic");Z(this,"ephemeral");Z(this,"routingInfo");Z(this,"metaSetter");if(this.contentTopic=u,this.ephemeral=h,this.routingInfo=b,this.metaSetter=v,!u||u==="")throw new Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}async toWire(u){return WakuMessage$4.encode(await this.toProtoObj(u))}async toProtoObj(u){const h=u.timestamp??new Date,b={payload:u.payload,version:Version,contentTopic:this.contentTopic,timestamp:BigInt(h.valueOf())*OneMillion,meta:void 0,rateLimitProof:u.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const v=this.metaSetter(b);return{...b,meta:v}}return b}};function createEncoder({contentTopic:y,routingInfo:u,ephemeral:h,metaSetter:b}){return new Encoder$1(y,h,u,b)}let Decoder$1=class{constructor(u,h){Z(this,"contentTopic");Z(this,"routingInfo");if(this.contentTopic=u,this.routingInfo=h,!u||u==="")throw new Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}fromWireToProtoObj(u){const h=WakuMessage$4.decode(u);return Promise.resolve({payload:h.payload,contentTopic:h.contentTopic,version:h.version??void 0,timestamp:h.timestamp??void 0,meta:h.meta??void 0,rateLimitProof:h.rateLimitProof??void 0,ephemeral:h.ephemeral??!1})}async fromProtoObj(u,h){return h.version??Version!==0?(log$w.error("Failed to decode due to incorrect version, expected:",Version,", actual:",h.version),Promise.resolve(void 0)):new DecodedMessage(u,h)}};function createDecoder(y,u){return new Decoder$1(y,u)}var LightPushStatusCode;(function(y){y[y.SUCCESS=200]="SUCCESS",y[y.BAD_REQUEST=400]="BAD_REQUEST",y[y.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",y[y.INVALID_MESSAGE=420]="INVALID_MESSAGE",y[y.UNSUPPORTED_TOPIC=421]="UNSUPPORTED_TOPIC",y[y.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",y[y.INTERNAL_ERROR=500]="INTERNAL_ERROR",y[y.UNAVAILABLE=503]="UNAVAILABLE",y[y.NO_RLN_PROOF=504]="NO_RLN_PROOF",y[y.NO_PEERS=505]="NO_PEERS"})(LightPushStatusCode||(LightPushStatusCode={}));LightPushStatusCode.SUCCESS+"",LightPushStatusCode.BAD_REQUEST+"",LightPushStatusCode.PAYLOAD_TOO_LARGE+"",LightPushStatusCode.INVALID_MESSAGE+"",LightPushStatusCode.UNSUPPORTED_TOPIC+"",LightPushStatusCode.TOO_MANY_REQUESTS+"",LightPushStatusCode.INTERNAL_ERROR+"",LightPushStatusCode.UNAVAILABLE+"",LightPushStatusCode.NO_RLN_PROOF+"",LightPushStatusCode.NO_PEERS+"";var Protocols;(function(y){y.Relay="relay",y.Store="store",y.LightPush="lightpush",y.Filter="filter"})(Protocols||(Protocols={}));var LightPushError;(function(y){y.GENERIC_FAIL="Generic error",y.DECODE_FAILED="Failed to decode",y.NO_PEER_AVAILABLE="No peer available",y.NO_STREAM_AVAILABLE="No stream available",y.NO_RESPONSE="No response received",y.STREAM_ABORTED="Stream aborted",y.ENCODE_FAILED="Failed to encode",y.EMPTY_PAYLOAD="Payload is empty",y.SIZE_TOO_BIG="Size is too big",y.TOPIC_NOT_CONFIGURED="Topic not configured",y.RLN_PROOF_GENERATION="Proof generation failed",y.REMOTE_PEER_REJECTED="Remote peer rejected",y.BAD_REQUEST="Bad request format",y.PAYLOAD_TOO_LARGE="Message payload exceeds maximum size",y.INVALID_MESSAGE="Message validation failed",y.UNSUPPORTED_TOPIC="Unsupported pubsub topic",y.TOO_MANY_REQUESTS="Rate limit exceeded",y.INTERNAL_ERROR="Internal server error",y.UNAVAILABLE="Service temporarily unavailable",y.NO_RLN_PROOF="RLN proof generation failed",y.NO_PEERS="No relay peers available"})(LightPushError||(LightPushError={}));var FilterError;(function(y){y.GENERIC_FAIL="Generic error",y.DECODE_FAILED="Failed to decode",y.NO_PEER_AVAILABLE="No peer available",y.NO_STREAM_AVAILABLE="No stream available",y.NO_RESPONSE="No response received",y.STREAM_ABORTED="Stream aborted",y.REMOTE_PEER_REJECTED="Remote peer rejected",y.TOPIC_NOT_CONFIGURED="Topic not configured",y.SUBSCRIPTION_FAILED="Subscription failed",y.UNSUBSCRIBE_FAILED="Unsubscribe failed",y.PING_FAILED="Ping failed",y.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",y.INVALID_DECODER_TOPICS="Invalid decoder topics",y.SUBSCRIPTION_LIMIT_EXCEEDED="Subscription limit exceeded",y.INVALID_CONTENT_TOPIC="Invalid content topic",y.PUSH_MESSAGE_FAILED="Push message failed",y.EMPTY_MESSAGE="Empty message received",y.MISSING_PUBSUB_TOPIC="Pubsub topic missing from push message"})(FilterError||(FilterError={}));var ProtocolError;(function(y){y.GENERIC_FAIL="Generic error",y.REMOTE_PEER_REJECTED="Remote peer rejected",y.DECODE_FAILED="Failed to decode",y.NO_PEER_AVAILABLE="No peer available",y.NO_STREAM_AVAILABLE="No stream available",y.NO_RESPONSE="No response received",y.ENCODE_FAILED="Failed to encode",y.EMPTY_PAYLOAD="Payload is empty",y.SIZE_TOO_BIG="Size is too big",y.TOPIC_NOT_CONFIGURED="Topic not configured",y.STREAM_ABORTED="Stream aborted",y.RLN_PROOF_GENERATION="Proof generation failed",y.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",y.INVALID_DECODER_TOPICS="Invalid decoder topics"})(ProtocolError||(ProtocolError={}));var WakuEvent;(function(y){y.Connection="waku:connection",y.Health="waku:health"})(WakuEvent||(WakuEvent={}));var Tags;(function(y){y.BOOTSTRAP="bootstrap",y.PEER_EXCHANGE="peer-exchange",y.PEER_CACHE="peer-cache"})(Tags||(Tags={}));const CONNECTION_LOCKED_TAG="locked",DNS_DISCOVERY_TAG="@waku/bootstrap",DEFAULT_CLUSTER_ID=1,DEFAULT_NUM_SHARDS=8,DefaultNetworkConfig={clusterId:DEFAULT_CLUSTER_ID,numShardsInCluster:DEFAULT_NUM_SHARDS};var HealthStatus;(function(y){y.Unhealthy="Unhealthy",y.MinimallyHealthy="MinimallyHealthy",y.SufficientlyHealthy="SufficientlyHealthy"})(HealthStatus||(HealthStatus={}));function isAsyncIterable$8(y){return y[Symbol.asyncIterator]!=null}function all$2(y){if(isAsyncIterable$8(y))return(async()=>{const h=[];for await(const b of y)h.push(b);return h})();const u=[];for(const h of y)u.push(h);return u}function asUint8Array(y){return y}function concat(y,u){u==null&&(u=y.reduce((v,w)=>v+w.length,0));const h=allocUnsafe(u);let b=0;for(const v of y)h.set(v,b),b+=v.length;return h}function equals(y,u){if(y===u)return!0;if(y.byteLength!==u.byteLength)return!1;for(let h=0;h<y.byteLength;h++)if(y[h]!==u[h])return!1;return!0}const symbol$1=Symbol.for("@achingbrain/uint8arraylist");function findBufAndOffset(y,u){if(u==null||u<0)throw new RangeError("index is out of bounds");let h=0;for(const b of y){const v=h+b.byteLength;if(u<v)return{buf:b,index:u-h};h=v}throw new RangeError("index is out of bounds")}function isUint8ArrayList(y){return!!(y!=null&&y[symbol$1])}var zd;class Uint8ArrayList{constructor(...u){Z(this,"bufs");Z(this,"length");Z(this,zd,!0);this.bufs=[],this.length=0,u.length>0&&this.appendAll(u)}*[(zd=symbol$1,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...u){this.appendAll(u)}appendAll(u){let h=0;for(const b of u)if(b instanceof Uint8Array)h+=b.byteLength,this.bufs.push(b);else if(isUint8ArrayList(b))h+=b.byteLength,this.bufs.push(...b.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=h}prepend(...u){this.prependAll(u)}prependAll(u){let h=0;for(const b of u.reverse())if(b instanceof Uint8Array)h+=b.byteLength,this.bufs.unshift(b);else if(isUint8ArrayList(b))h+=b.byteLength,this.bufs.unshift(...b.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=h}get(u){const h=findBufAndOffset(this.bufs,u);return h.buf[h.index]}set(u,h){const b=findBufAndOffset(this.bufs,u);b.buf[b.index]=h}write(u,h=0){if(u instanceof Uint8Array)for(let b=0;b<u.length;b++)this.set(h+b,u[b]);else if(isUint8ArrayList(u))for(let b=0;b<u.length;b++)this.set(h+b,u.get(b));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(u){if(u=Math.trunc(u),!(Number.isNaN(u)||u<=0)){if(u===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(u>=this.bufs[0].byteLength)u-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(u),this.length-=u;break}}}slice(u,h){const{bufs:b,length:v}=this._subList(u,h);return concat(b,v)}subarray(u,h){const{bufs:b,length:v}=this._subList(u,h);return b.length===1?b[0]:concat(b,v)}sublist(u,h){const{bufs:b,length:v}=this._subList(u,h),w=new Uint8ArrayList;return w.length=v,w.bufs=[...b],w}_subList(u,h){if(u=u??0,h=h??this.length,u<0&&(u=this.length+u),h<0&&(h=this.length+h),u<0||h>this.length)throw new RangeError("index is out of bounds");if(u===h)return{bufs:[],length:0};if(u===0&&h===this.length)return{bufs:this.bufs,length:this.length};const b=[];let v=0;for(let w=0;w<this.bufs.length;w++){const _=this.bufs[w],E=v,S=E+_.byteLength;if(v=S,u>=S)continue;const x=u>=E&&u<S,T=h>E&&h<=S;if(x&&T){if(u===E&&h===S){b.push(_);break}const C=u-E;b.push(_.subarray(C,C+(h-u)));break}if(x){if(u===0){b.push(_);continue}b.push(_.subarray(u-E));continue}if(T){if(h===S){b.push(_);break}b.push(_.subarray(0,h-E));break}b.push(_)}return{bufs:b,length:h-u}}indexOf(u,h=0){if(!isUint8ArrayList(u)&&!(u instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const b=u instanceof Uint8Array?u:u.subarray();if(h=Number(h??0),isNaN(h)&&(h=0),h<0&&(h=this.length+h),h<0&&(h=0),u.length===0)return h>this.length?this.length:h;const v=b.byteLength;if(v===0)throw new TypeError("search must be at least 1 byte long");const w=256,_=new Int32Array(w);for(let C=0;C<w;C++)_[C]=-1;for(let C=0;C<v;C++)_[b[C]]=C;const E=_,S=this.byteLength-b.byteLength,x=b.byteLength-1;let T;for(let C=h;C<=S;C+=T){T=0;for(let O=x;O>=0;O--){const D=this.get(C+O);if(b[O]!==D){T=Math.max(1,O-E[D]);break}}if(T===0)return C}return-1}getInt8(u){const h=this.subarray(u,u+1);return new DataView(h.buffer,h.byteOffset,h.byteLength).getInt8(0)}setInt8(u,h){const b=allocUnsafe(1);new DataView(b.buffer,b.byteOffset,b.byteLength).setInt8(0,h),this.write(b,u)}getInt16(u,h){const b=this.subarray(u,u+2);return new DataView(b.buffer,b.byteOffset,b.byteLength).getInt16(0,h)}setInt16(u,h,b){const v=alloc$1(2);new DataView(v.buffer,v.byteOffset,v.byteLength).setInt16(0,h,b),this.write(v,u)}getInt32(u,h){const b=this.subarray(u,u+4);return new DataView(b.buffer,b.byteOffset,b.byteLength).getInt32(0,h)}setInt32(u,h,b){const v=alloc$1(4);new DataView(v.buffer,v.byteOffset,v.byteLength).setInt32(0,h,b),this.write(v,u)}getBigInt64(u,h){const b=this.subarray(u,u+8);return new DataView(b.buffer,b.byteOffset,b.byteLength).getBigInt64(0,h)}setBigInt64(u,h,b){const v=alloc$1(8);new DataView(v.buffer,v.byteOffset,v.byteLength).setBigInt64(0,h,b),this.write(v,u)}getUint8(u){const h=this.subarray(u,u+1);return new DataView(h.buffer,h.byteOffset,h.byteLength).getUint8(0)}setUint8(u,h){const b=allocUnsafe(1);new DataView(b.buffer,b.byteOffset,b.byteLength).setUint8(0,h),this.write(b,u)}getUint16(u,h){const b=this.subarray(u,u+2);return new DataView(b.buffer,b.byteOffset,b.byteLength).getUint16(0,h)}setUint16(u,h,b){const v=alloc$1(2);new DataView(v.buffer,v.byteOffset,v.byteLength).setUint16(0,h,b),this.write(v,u)}getUint32(u,h){const b=this.subarray(u,u+4);return new DataView(b.buffer,b.byteOffset,b.byteLength).getUint32(0,h)}setUint32(u,h,b){const v=alloc$1(4);new DataView(v.buffer,v.byteOffset,v.byteLength).setUint32(0,h,b),this.write(v,u)}getBigUint64(u,h){const b=this.subarray(u,u+8);return new DataView(b.buffer,b.byteOffset,b.byteLength).getBigUint64(0,h)}setBigUint64(u,h,b){const v=alloc$1(8);new DataView(v.buffer,v.byteOffset,v.byteLength).setBigUint64(0,h,b),this.write(v,u)}getFloat32(u,h){const b=this.subarray(u,u+4);return new DataView(b.buffer,b.byteOffset,b.byteLength).getFloat32(0,h)}setFloat32(u,h,b){const v=alloc$1(4);new DataView(v.buffer,v.byteOffset,v.byteLength).setFloat32(0,h,b),this.write(v,u)}getFloat64(u,h){const b=this.subarray(u,u+8);return new DataView(b.buffer,b.byteOffset,b.byteLength).getFloat64(0,h)}setFloat64(u,h,b){const v=alloc$1(8);new DataView(v.buffer,v.byteOffset,v.byteLength).setFloat64(0,h,b),this.write(v,u)}equals(u){if(u==null||!(u instanceof Uint8ArrayList)||u.bufs.length!==this.bufs.length)return!1;for(let h=0;h<this.bufs.length;h++)if(!equals(this.bufs[h],u.bufs[h]))return!1;return!0}static fromUint8Arrays(u,h){const b=new Uint8ArrayList;return b.bufs=u,h==null&&(h=u.reduce((v,w)=>v+w.byteLength,0)),b.length=h,b}}function isAsyncIterable$7(y){return y[Symbol.asyncIterator]!=null}const defaultEncoder$1=y=>{const u=encodingLength$1(y),h=allocUnsafe(u);return encode$8(y,h),defaultEncoder$1.bytes=u,h};defaultEncoder$1.bytes=0;function encode$3(y,u){u=u??{};const h=u.lengthEncoder??defaultEncoder$1;function*b(v){const w=h(v.byteLength);w instanceof Uint8Array?yield w:yield*w,v instanceof Uint8Array?yield v:yield*v}return isAsyncIterable$7(y)?async function*(){for await(const v of y)yield*b(v)}():function*(){for(const v of y)yield*b(v)}()}encode$3.single=(y,u)=>{u=u??{};const h=u.lengthEncoder??defaultEncoder$1;return new Uint8ArrayList(h(y.byteLength),y)};let InvalidMessageLengthError$2=class extends Error{constructor(){super(...arguments);Z(this,"name","InvalidMessageLengthError");Z(this,"code","ERR_INVALID_MSG_LENGTH")}},InvalidDataLengthError$2=class extends Error{constructor(){super(...arguments);Z(this,"name","InvalidDataLengthError");Z(this,"code","ERR_MSG_DATA_TOO_LONG")}},InvalidDataLengthLengthError$2=class extends Error{constructor(){super(...arguments);Z(this,"name","InvalidDataLengthLengthError");Z(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},UnexpectedEOFError$2=class extends Error{constructor(){super(...arguments);Z(this,"name","UnexpectedEOFError");Z(this,"code","ERR_UNEXPECTED_EOF")}};const MAX_LENGTH_LENGTH$1=8,MAX_DATA_LENGTH$1=1024*1024*4;var ReadMode$1;(function(y){y[y.LENGTH=0]="LENGTH",y[y.DATA=1]="DATA"})(ReadMode$1||(ReadMode$1={}));const defaultDecoder$1=y=>{const u=decode$8(y);return defaultDecoder$1.bytes=encodingLength$1(u),u};defaultDecoder$1.bytes=0;function decode$2(y,u){const h=new Uint8ArrayList;let b=ReadMode$1.LENGTH,v=-1;const w=(u==null?void 0:u.lengthDecoder)??defaultDecoder$1,_=(u==null?void 0:u.maxLengthLength)??MAX_LENGTH_LENGTH$1,E=(u==null?void 0:u.maxDataLength)??MAX_DATA_LENGTH$1;function*S(){for(;h.byteLength>0;){if(b===ReadMode$1.LENGTH)try{if(v=w(h),v<0)throw new InvalidMessageLengthError$2("Invalid message length");if(v>E)throw new InvalidDataLengthError$2("Message length too long");const x=w.bytes;h.consume(x),(u==null?void 0:u.onLength)!=null&&u.onLength(v),b=ReadMode$1.DATA}catch(x){if(x instanceof RangeError){if(h.byteLength>_)throw new InvalidDataLengthLengthError$2("Message length length too long");break}throw x}if(b===ReadMode$1.DATA){if(h.byteLength<v)break;const x=h.sublist(0,v);h.consume(v),(u==null?void 0:u.onData)!=null&&u.onData(x),yield x,b=ReadMode$1.LENGTH}}}return isAsyncIterable$7(y)?async function*(){for await(const x of y)h.append(x),yield*S();if(h.byteLength>0)throw new UnexpectedEOFError$2("Unexpected end of input")}():function*(){for(const x of y)h.append(x),yield*S();if(h.byteLength>0)throw new UnexpectedEOFError$2("Unexpected end of input")}()}decode$2.fromReader=(y,u)=>{let h=1;const b=async function*(){for(;;)try{const{done:w,value:_}=await y.next(h);if(w===!0)return;_!=null&&(yield _)}catch(w){if(w.code==="ERR_UNDER_READ")return{done:!0,value:null};throw w}finally{h=1}}();return decode$2(b,{...u??{},onLength:w=>{h=w}})};function pDefer(){const y={};return y.promise=new Promise((u,h)=>{y.resolve=u,y.reject=h}),y}class FixedFIFO{constructor(u){Z(this,"buffer");Z(this,"mask");Z(this,"top");Z(this,"btm");Z(this,"next");if(!(u>0)||u-1&u)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(u),this.mask=u-1,this.top=0,this.btm=0,this.next=null}push(u){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=u,this.top=this.top+1&this.mask,!0)}shift(){const u=this.buffer[this.btm];if(u!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,u}isEmpty(){return this.buffer[this.btm]===void 0}}class FIFO{constructor(u={}){Z(this,"size");Z(this,"hwm");Z(this,"head");Z(this,"tail");this.hwm=u.splitLimit??16,this.head=new FixedFIFO(this.hwm),this.tail=this.head,this.size=0}calculateSize(u){return(u==null?void 0:u.byteLength)!=null?u.byteLength:1}push(u){if((u==null?void 0:u.value)!=null&&(this.size+=this.calculateSize(u.value)),!this.head.push(u)){const h=this.head;this.head=h.next=new FixedFIFO(2*this.head.buffer.length),this.head.push(u)}}shift(){let u=this.tail.shift();if(u===void 0&&this.tail.next!=null){const h=this.tail.next;this.tail.next=null,this.tail=h,u=this.tail.shift()}return(u==null?void 0:u.value)!=null&&(this.size-=this.calculateSize(u.value)),u}isEmpty(){return this.head.isEmpty()}}let AbortError$4=class extends Error{constructor(h,b){super(h??"The operation was aborted");Z(this,"type");Z(this,"code");this.type="aborted",this.code=b??"ABORT_ERR"}};function pushable(y={}){return _pushable(h=>{const b=h.shift();if(b==null)return{done:!0};if(b.error!=null)throw b.error;return{done:b.done===!0,value:b.value}},y)}function _pushable(y,u){u=u??{};let h=u.onEnd,b=new FIFO,v,w,_,E=pDefer();const S=async()=>{try{return b.isEmpty()?_?{done:!0}:await new Promise((X,ie)=>{w=ee=>{w=null,b.push(ee);try{X(y(b))}catch(ae){ie(ae)}return v}}):y(b)}finally{b.isEmpty()&&queueMicrotask(()=>{E.resolve(),E=pDefer()})}},x=X=>w!=null?w(X):(b.push(X),v),T=X=>(b=new FIFO,w!=null?w({error:X}):(b.push({error:X}),v)),C=X=>{if(_)return v;if((u==null?void 0:u.objectMode)!==!0&&(X==null?void 0:X.byteLength)==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return x({done:!1,value:X})},O=X=>_?v:(_=!0,X!=null?T(X):x({done:!0})),D=()=>(b=new FIFO,O(),{done:!0}),U=X=>(O(X),{done:!0});if(v={[Symbol.asyncIterator](){return this},next:S,return:D,throw:U,push:C,end:O,get readableLength(){return b.size},onEmpty:async X=>{const ie=X==null?void 0:X.signal;if(ie==null||ie.throwIfAborted(),b.isEmpty())return;let ee,ae;ie!=null&&(ee=new Promise((de,Se)=>{ae=()=>{Se(new AbortError$4)},ie.addEventListener("abort",ae)}));try{await Promise.race([E.promise,ee])}finally{ae!=null&&ie!=null&&(ie==null||ie.removeEventListener("abort",ae))}}},h==null)return v;const te=v;return v={[Symbol.asyncIterator](){return this},next(){return te.next()},throw(X){return te.throw(X),h!=null&&(h(X),h=void 0),{done:!0}},return(){return te.return(),h!=null&&(h(),h=void 0),{done:!0}},push:C,end(X){return te.end(X),h!=null&&(h(X),h=void 0),v},get readableLength(){return te.readableLength},onEmpty:X=>te.onEmpty(X)},v}let AbortError$3=class extends Error{constructor(h,b,v){super(h??"The operation was aborted");Z(this,"type");Z(this,"code");this.type="aborted",this.name=v??"AbortError",this.code=b??"ABORT_ERR"}};async function raceSignal(y,u,h){if(u==null)return y;if(u.aborted)return y.catch(()=>{}),Promise.reject(new AbortError$3(h==null?void 0:h.errorMessage,h==null?void 0:h.errorCode,h==null?void 0:h.errorName));let b;const v=new AbortError$3(h==null?void 0:h.errorMessage,h==null?void 0:h.errorCode,h==null?void 0:h.errorName);try{return await Promise.race([y,new Promise((w,_)=>{b=()=>{_(v)},u.addEventListener("abort",b)})])}finally{b!=null&&u.removeEventListener("abort",b)}}class QueuelessPushable{constructor(){Z(this,"readNext");Z(this,"haveNext");Z(this,"ended");Z(this,"nextResult");Z(this,"error");this.ended=!1,this.readNext=pDefer(),this.haveNext=pDefer()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");const u=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=pDefer(),u}async throw(u){return this.ended=!0,this.error=u,u!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(u)),{done:!0,value:void 0}}async return(){const u={done:!0,value:void 0};return this.ended=!0,this.nextResult=u,this.haveNext.resolve(),u}async push(u,h){await this._push(u,h)}async end(u,h){u!=null?await this.throw(u):await this._push(void 0,h)}async _push(u,h){if(u!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;u!=null?this.nextResult={done:!1,value:u}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=pDefer(),await raceSignal(this.readNext.promise,h==null?void 0:h.signal,h)}}function queuelessPushable(){return new QueuelessPushable}function isAsyncIterable$6(y){return y[Symbol.asyncIterator]!=null}async function addAllToPushable(y,u,h){try{await Promise.all(y.map(async b=>{for await(const v of b)await u.push(v,{signal:h}),h.throwIfAborted()})),await u.end(void 0,{signal:h})}catch(b){await u.end(b,{signal:h}).catch(()=>{})}}async function*mergeSources(y){const u=new AbortController,h=queuelessPushable();addAllToPushable(y,h,u.signal).catch(()=>{});try{yield*h}finally{u.abort()}}function*mergeSyncSources(y){for(const u of y)yield*u}function merge$1(...y){const u=[];for(const h of y)isAsyncIterable$6(h)||u.push(h);return u.length===y.length?mergeSyncSources(u):mergeSources(y)}function pipe$1(y,...u){if(y==null)throw new Error("Empty pipeline");if(isDuplex(y)){const b=y;y=()=>b.source}else if(isIterable(y)||isAsyncIterable$5(y)){const b=y;y=()=>b}const h=[y,...u];if(h.length>1&&isDuplex(h[h.length-1])&&(h[h.length-1]=h[h.length-1].sink),h.length>2)for(let b=1;b<h.length-1;b++)isDuplex(h[b])&&(h[b]=duplexPipelineFn(h[b]));return rawPipe(...h)}const rawPipe=(...y)=>{let u;for(;y.length>0;)u=y.shift()(u);return u},isAsyncIterable$5=y=>(y==null?void 0:y[Symbol.asyncIterator])!=null,isIterable=y=>(y==null?void 0:y[Symbol.iterator])!=null,isDuplex=y=>y==null?!1:y.sink!=null&&y.source!=null,duplexPipelineFn=y=>u=>{const h=y.sink(u);if((h==null?void 0:h.then)!=null){const b=pushable({objectMode:!0});h.then(()=>{b.end()},_=>{b.end(_)});let v;const w=y.source;if(isAsyncIterable$5(w))v=async function*(){yield*w,b.end()};else if(isIterable(w))v=function*(){yield*w,b.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return merge$1(b,v())}return y.source};function selectOpenConnection(y){return y.filter(u=>u.status==="open").sort((u,h)=>h.timeline.open-u.timeline.open).at(0)}const STREAM_LOCK_KEY="consumed";class StreamManager{constructor(u,h){Z(this,"multicodec");Z(this,"libp2p");Z(this,"log");Z(this,"ongoingCreation",new Set);Z(this,"streamPool",new Map);Z(this,"handlePeerUpdateStreamPool",u=>{const{peer:h}=u.detail;!h.protocols.includes(this.multicodec)||this.getOpenStreamForCodec(h.id)||this.scheduleNewStream(h)});this.multicodec=u,this.libp2p=h,this.log=new Logger$1(`stream-manager:${u}`),this.libp2p.events.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(u){try{const h=u.toString(),b=this.streamPool.get(h);b&&(this.streamPool.delete(h),await b);const v=this.getOpenStreamForCodec(u)||await this.createStream(u);return v?(this.log.info(`Using stream for peerId=${h} multicodec=${this.multicodec}`),this.lockStream(h,v),v):void 0}catch(h){this.log.error("Failed to getStream:",h);return}}async createStream(u,h=0){const b=this.libp2p.connectionManager.getConnections(u),v=selectOpenConnection(b);if(!v){this.log.error(`Failed to get a connection to the peer peerId=${u.toString()} multicodec=${this.multicodec}`);return}let w,_;for(let E=0;E<h+1;E++)try{this.log.info(`Attempting to create a stream for peerId=${u.toString()} multicodec=${this.multicodec}`),_=await v.newStream(this.multicodec),this.log.info(`Created stream for peerId=${u.toString()} multicodec=${this.multicodec}`);break}catch(S){w=S}if(!_){this.log.error(`Failed to create a new stream for ${u.toString()} -- `+w);return}return _}async createStreamWithLock(u){const h=u.id.toString();if(this.ongoingCreation.has(h)){this.log.info(`Skipping creation of a stream due to lock for peerId=${h} multicodec=${this.multicodec}`);return}try{this.ongoingCreation.add(h),await this.createStream(u.id)}catch(b){this.log.error("Failed to createStreamWithLock:",b)}finally{this.ongoingCreation.delete(h)}}scheduleNewStream(u){this.log.info(`Scheduling creation of a stream for peerId=${u.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(u.id.toString())&&this.streamPool.delete(u.id.toString()),this.streamPool.set(u.id.toString(),this.createStreamWithLock(u))}getOpenStreamForCodec(u){const h=this.libp2p.connectionManager.getConnections(u),b=selectOpenConnection(h);if(!b){this.log.info(`No open connection found for peerId=${u.toString()} multicodec=${this.multicodec}`);return}const v=b.streams.find(_=>_.protocol===this.multicodec);if(!v){this.log.info(`No open stream found for peerId=${u.toString()} multicodec=${this.multicodec}`);return}if(["done","closed","closing"].includes(v.writeStatus||"")||this.isStreamLocked(v)){this.log.info(`Stream for peerId=${u.toString()} multicodec=${this.multicodec} is unusable`);return}return this.log.info(`Found open stream for peerId=${u.toString()} multicodec=${this.multicodec}`),v}lockStream(u,h){this.log.info(`Locking stream for peerId:${u} streamId:${h.id}`),h.metadata[STREAM_LOCK_KEY]=!0}isStreamLocked(u){return!!u.metadata[STREAM_LOCK_KEY]}}let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues&&(getRandomValues=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!getRandomValues))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}const byteToHex=[];for(let y=0;y<256;++y)byteToHex.push((y+256).toString(16).slice(1));function unsafeStringify(y,u=0){return byteToHex[y[u+0]]+byteToHex[y[u+1]]+byteToHex[y[u+2]]+byteToHex[y[u+3]]+"-"+byteToHex[y[u+4]]+byteToHex[y[u+5]]+"-"+byteToHex[y[u+6]]+byteToHex[y[u+7]]+"-"+byteToHex[y[u+8]]+byteToHex[y[u+9]]+"-"+byteToHex[y[u+10]]+byteToHex[y[u+11]]+byteToHex[y[u+12]]+byteToHex[y[u+13]]+byteToHex[y[u+14]]+byteToHex[y[u+15]]}const randomUUID=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),native={randomUUID};function v4(y,u,h){if(native.randomUUID&&!u&&!y)return native.randomUUID();y=y||{};const b=y.random||(y.rng||rng)();return b[6]=b[6]&15|64,b[8]=b[8]&63|128,unsafeStringify(b)}class FilterPushRpc{constructor(u){Z(this,"proto");this.proto=u}static decode(u){const h=MessagePush.decode(u);return new FilterPushRpc(h)}encode(){return MessagePush.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class FilterSubscribeRpc{constructor(u){Z(this,"proto");this.proto=u}static createSubscribeRequest(u,h){return new FilterSubscribeRpc({requestId:v4(),filterSubscribeType:FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBE,pubsubTopic:u,contentTopics:h})}static createUnsubscribeRequest(u,h){return new FilterSubscribeRpc({requestId:v4(),filterSubscribeType:FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:u,contentTopics:h})}static createUnsubscribeAllRequest(u){return new FilterSubscribeRpc({requestId:v4(),filterSubscribeType:FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:u,contentTopics:[]})}static createSubscriberPingRequest(){return new FilterSubscribeRpc({requestId:v4(),filterSubscribeType:FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(u){const h=FilterSubscribeRequest.decode(u);return new FilterSubscribeRpc(h)}encode(){return FilterSubscribeRequest.encode(this.proto)}get filterSubscribeType(){return this.proto.filterSubscribeType}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.proto.pubsubTopic}get contentTopics(){return this.proto.contentTopics}}class FilterSubscribeResponse{constructor(u){Z(this,"proto");this.proto=u}static decode(u){const h=FilterSubscribeResponse$1.decode(u);return new FilterSubscribeResponse(h)}encode(){return FilterSubscribeResponse$1.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const log$v=new Logger$1("filter-core"),FilterCodecs={SUBSCRIBE:"/vac/waku/filter-subscribe/2.0.0-beta1",PUSH:"/vac/waku/filter-push/2.0.0-beta1"};class FilterCore{constructor(u,h){Z(this,"handleIncomingMessage");Z(this,"libp2p");Z(this,"streamManager");Z(this,"multicodec",FilterCodecs.SUBSCRIBE);this.handleIncomingMessage=u,this.libp2p=h,this.streamManager=new StreamManager(FilterCodecs.SUBSCRIBE,h.components)}async start(){try{await this.libp2p.handle(FilterCodecs.PUSH,this.onRequest.bind(this),{maxInboundStreams:100})}catch(u){log$v.error("Failed to register ",FilterCodecs.PUSH,u)}}async stop(){try{await this.libp2p.unhandle(FilterCodecs.PUSH)}catch(u){log$v.error("Failed to unregister ",FilterCodecs.PUSH,u)}}async subscribe(u,h,b){const v=await this.streamManager.getStream(h);if(!v)return{success:null,failure:{error:FilterError.NO_STREAM_AVAILABLE,peerId:h}};const w=FilterSubscribeRpc.createSubscribeRequest(u,b);let _;try{if(_=await pipe$1([w.encode()],encode$3,v,decode$2,async T=>await all$2(T)),!(_!=null&&_.length))throw Error("Received no response from subscription request.")}catch(T){return log$v.error("Failed to send subscribe request",T),{success:null,failure:{error:FilterError.GENERIC_FAIL,peerId:h}}}const{statusCode:E,requestId:S,statusDesc:x}=FilterSubscribeResponse.decode(_[0].slice());return E<200||E>=300?(log$v.error(`Filter subscribe request ${S} failed with status code ${E}: ${x}`),{failure:{error:FilterError.REMOTE_PEER_REJECTED,peerId:h},success:null}):{failure:null,success:h}}async unsubscribe(u,h,b){const v=await this.streamManager.getStream(h);if(!v)return log$v.error(`Failed to get a stream for remote peer:${h.toString()}`),{success:null,failure:{error:FilterError.NO_STREAM_AVAILABLE,peerId:h}};const w=FilterSubscribeRpc.createUnsubscribeRequest(u,b);try{await pipe$1([w.encode()],encode$3,v.sink)}catch(_){return log$v.error("Failed to send unsubscribe request",_),{success:null,failure:{error:FilterError.GENERIC_FAIL,peerId:h}}}return{success:h,failure:null}}async unsubscribeAll(u,h){const b=await this.streamManager.getStream(h);if(!b)return log$v.error(`Failed to get a stream for remote peer:${h.toString()}`),{success:null,failure:{error:FilterError.NO_STREAM_AVAILABLE,peerId:h}};const v=FilterSubscribeRpc.createUnsubscribeAllRequest(u),w=await pipe$1([v.encode()],encode$3,b,decode$2,async x=>await all$2(x));if(!w||!w.length)return{failure:{error:FilterError.NO_RESPONSE,peerId:h},success:null};const{statusCode:_,requestId:E,statusDesc:S}=FilterSubscribeResponse.decode(w[0].slice());return _<200||_>=300?(log$v.error(`Filter unsubscribe all request ${E} failed with status code ${_}: ${S}`),{failure:{error:FilterError.REMOTE_PEER_REJECTED,peerId:h},success:null}):{failure:null,success:h}}async ping(u){const h=await this.streamManager.getStream(u);if(!h)return log$v.error(`Failed to get a stream for remote peer:${u.toString()}`),{success:null,failure:{error:FilterError.NO_STREAM_AVAILABLE,peerId:u}};const b=FilterSubscribeRpc.createSubscriberPingRequest();let v;try{v=await pipe$1([b.encode()],encode$3,h,decode$2,async S=>await all$2(S))}catch(S){return log$v.error("Failed to send ping request",S),{success:null,failure:{error:FilterError.GENERIC_FAIL,peerId:u}}}if(!v||!v.length)return{success:null,failure:{error:FilterError.NO_RESPONSE,peerId:u}};const{statusCode:w,requestId:_,statusDesc:E}=FilterSubscribeResponse.decode(v[0].slice());return w<200||w>=300?(log$v.error(`Filter ping request ${_} failed with status code ${w}: ${E}`),{success:null,failure:{error:FilterError.REMOTE_PEER_REJECTED,peerId:u}}):{success:u,failure:null}}onRequest(u){const{connection:h,stream:b}=u,{remotePeer:v}=h;log$v.info(`Received message from ${v.toString()}`);try{pipe$1(b,decode$2,async w=>{for await(const _ of w){const E=FilterPushRpc.decode(_.slice()),{pubsubTopic:S,wakuMessage:x}=E;if(!x){log$v.error("Received empty message");return}if(!S){log$v.error("Pubsub topic missing from push message");return}await this.handleIncomingMessage(S,x,h.remotePeer.toString())}}).then(()=>{log$v.info("Receiving pipe closed.")},async w=>{log$v.error(`Error with receiving pipe on peer:${h.remotePeer.toString()} -- stream:${b.id} -- protocol:${b.protocol}: `,w)})}catch(w){log$v.error("Error decoding message",w)}}}const CODECS={v2:"/vac/waku/lightpush/2.0.0-beta1",v3:"/vac/waku/lightpush/3.0.0"},LightPushCodecV2=CODECS.v2,LightPushCodec=CODECS.v3;class PushRpcV2{constructor(u){Z(this,"proto");this.proto=u}static createRequest(u,h){return new PushRpcV2({requestId:v4(),request:{message:u,pubsubTopic:h},response:void 0})}static decode(u){const h=PushRpc$1.decode(u);return new PushRpcV2(h)}encode(){return PushRpc$1.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}class PushRpc{constructor(u){Z(this,"proto");this.proto=u}static createRequest(u,h){return new PushRpc({requestId:v4(),pubsubTopic:h,message:u})}static createResponse(u,h,b,v){return new PushRpc({requestId:u,statusCode:h,statusDesc:b,relayPeerCount:v})}static decodeRequest(u){const h=LightPushRequestV3.decode(u);return new PushRpc(h)}static decodeResponse(u){const h=LightPushResponseV3.decode(u);return new PushRpc(h)}encode(){return this.isRequest()?LightPushRequestV3.encode(this.proto):LightPushResponseV3.encode(this.proto)}get request(){return this.isRequest()?this.proto:void 0}get response(){return this.isResponse()?this.proto:void 0}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.isRequest()?this.proto.pubsubTopic:void 0}get message(){return this.isRequest()?this.proto.message:void 0}get statusCode(){return this.isResponse()?this.proto.statusCode:void 0}get statusDesc(){return this.isResponse()?this.proto.statusDesc:void 0}get relayPeerCount(){return this.isResponse()?this.proto.relayPeerCount:void 0}isRequest(){return"pubsubTopic"in this.proto&&"message"in this.proto}isResponse(){return"statusCode"in this.proto}}const RLN_GENERATION_PREFIX_ERROR="could not generate rln proof",RLN_MESSAGE_ID_PREFIX_ERROR="could not get new message id to generate an rln proof",RLN_REMOTE_VALIDATION="RLN validation failed",isRLNResponseError=y=>y?y.includes(RLN_GENERATION_PREFIX_ERROR)||y.includes(RLN_MESSAGE_ID_PREFIX_ERROR)||y.includes(RLN_REMOTE_VALIDATION):!1,log$u=new Logger$1("light-push:protocol-handler");class ProtocolHandler{static async preparePushMessage(u,h,b){try{if(!h.payload||h.payload.length===0)return log$u.error("Failed to send waku light push: payload is empty"),{rpc:null,error:LightPushError.EMPTY_PAYLOAD};if(!await isMessageSizeUnderCap(u,h))return log$u.error("Failed to send waku light push: message is bigger than 1MB"),{rpc:null,error:LightPushError.SIZE_TOO_BIG};const v=await u.toProtoObj(h);return v?b===CODECS.v3?(log$u.info("Creating v3 RPC message"),{rpc:ProtocolHandler.createV3Rpc(v,u.pubsubTopic),error:null}):(log$u.info("Creating v2 RPC message"),{rpc:ProtocolHandler.createV2Rpc(v,u.pubsubTopic),error:null}):(log$u.error("Failed to encode to protoMessage, aborting push"),{rpc:null,error:LightPushError.ENCODE_FAILED})}catch(v){return log$u.error("Failed to prepare push message",v),{rpc:null,error:LightPushError.GENERIC_FAIL}}}static handleResponse(u,h,b){return h===CODECS.v3?ProtocolHandler.handleV3Response(u,b):ProtocolHandler.handleV2Response(u,b)}static handleV3Response(u,h){try{const b=PushRpc.decodeResponse(u),v=b.statusCode,w=b.statusDesc;if(v!==LightPushStatusCode.SUCCESS){const _=LightPushError.REMOTE_PEER_REJECTED;return log$u.error(`Remote peer rejected with v3 status code ${v}: ${w}`),{success:null,failure:{error:_,peerId:h}}}return b.relayPeerCount!==void 0&&log$u.info(`Message relayed to ${b.relayPeerCount} peers`),{success:h,failure:null}}catch{return{success:null,failure:{error:LightPushError.DECODE_FAILED,peerId:h}}}}static handleV2Response(u,h){let b;try{b=PushRpcV2.decode(u).response}catch{return{success:null,failure:{error:LightPushError.DECODE_FAILED,peerId:h}}}return b?isRLNResponseError(b.info)?(log$u.error("Remote peer fault: RLN generation"),{success:null,failure:{error:LightPushError.RLN_PROOF_GENERATION,peerId:h}}):b.isSuccess?{success:h,failure:null}:(log$u.error("Remote peer rejected the message: ",b.info),{success:null,failure:{error:LightPushError.REMOTE_PEER_REJECTED,peerId:h}}):{success:null,failure:{error:LightPushError.NO_RESPONSE,peerId:h}}}static createV2Rpc(u,h){const b=PushRpcV2.createRequest(u,h);return Object.assign(b,{version:"v2"})}static createV3Rpc(u,h){u.timestamp||(u.timestamp=BigInt(Date.now())*BigInt(1e6));const b=PushRpc.createRequest(u,h);return Object.assign(b,{version:"v3"})}}const log$t=new Logger$1("light-push");class LightPushCore{constructor(u){Z(this,"libp2p");Z(this,"streamManager");Z(this,"streamManagerV2");Z(this,"multicodec",[CODECS.v3,CODECS.v2]);this.libp2p=u,this.streamManagerV2=new StreamManager(CODECS.v2,u.components),this.streamManager=new StreamManager(CODECS.v3,u.components)}async send(u,h,b,v=!1){const w=await this.getProtocol(b,v);if(log$t.info(`Sending light push request to peer:${b.toString()}, protocol:${w}`),!w)return{success:null,failure:{error:LightPushError.GENERIC_FAIL,peerId:b}};const{rpc:_,error:E}=await ProtocolHandler.preparePushMessage(u,h,w);if(E)return{success:null,failure:{error:E,peerId:b}};const S=await this.getStream(b,w);if(!S)return log$t.error(`Failed to get a stream for remote peer:${b.toString()}`),{success:null,failure:{error:LightPushError.NO_STREAM_AVAILABLE,peerId:b}};let x;try{x=await pipe$1([_.encode()],encode$3,S,decode$2,async C=>await all$2(C))}catch(C){return log$t.error("Failed to send waku light push request",C),{success:null,failure:{error:LightPushError.STREAM_ABORTED,peerId:b}}}const T=new Uint8ArrayList;return x.forEach(C=>T.append(C)),T.length===0?{success:null,failure:{error:LightPushError.NO_RESPONSE,peerId:b}}:ProtocolHandler.handleResponse(T,w,b)}async getProtocol(u,h){try{const b=await this.libp2p.peerStore.get(u);if(h||!b.protocols.includes(CODECS.v3)&&b.protocols.includes(CODECS.v2))return CODECS.v2;if(b.protocols.includes(CODECS.v3))return CODECS.v3;throw new Error("No supported protocol found")}catch(b){log$t.error("Failed to get protocol",b);return}}async getStream(u,h){switch(h){case CODECS.v2:return this.streamManagerV2.getStream(u);case CODECS.v3:return this.streamManager.getStream(u);default:return}}}const EmptyMessage={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0};function toProtoMessage(y){return{...EmptyMessage,...y}}const DEFAULT_PAGE_SIZE=20,MAX_PAGE_SIZE=100,MAX_TIME_RANGE=24*60*60*1e3,ONE_MILLION=1e6;class StoreQueryRequest{constructor(u){Z(this,"proto");this.proto=u}static create(u){const h=new StoreQueryRequest({...u,contentTopics:u.contentTopics||[],requestId:v4(),timeStart:u.timeStart?BigInt(u.timeStart.getTime()*ONE_MILLION):void 0,timeEnd:u.timeEnd?BigInt(u.timeEnd.getTime()*ONE_MILLION):void 0,messageHashes:u.messageHashes||[],paginationLimit:u.paginationLimit?BigInt(u.paginationLimit):void 0}),b=u.messageHashes&&u.messageHashes.length>0,v=u.contentTopics&&u.contentTopics.length>0,w=u.timeStart||u.timeEnd;if(b){if(v||w)throw new Error("Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)")}else if(u.pubsubTopic&&(!u.contentTopics||u.contentTopics.length===0)||!u.pubsubTopic&&u.contentTopics&&u.contentTopics.length>0)throw new Error("Both pubsubTopic and contentTopics must be set together for content-filtered queries");return h}static decode(u){const h=StoreQueryRequest$1.decode(u);return new StoreQueryRequest(h)}encode(){return StoreQueryRequest$1.encode(this.proto)}}class StoreQueryResponse{constructor(u){Z(this,"proto");this.proto=u}static decode(u){const h=StoreQueryResponse$1.decode(u);return new StoreQueryResponse(h)}encode(){return StoreQueryResponse$1.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const log$s=new Logger$1("store"),StoreCodec="/vac/waku/store-query/3.0.0";class StoreCore{constructor(u){Z(this,"streamManager");Z(this,"multicodec",StoreCodec);this.streamManager=new StreamManager(StoreCodec,u.components)}get maxTimeLimit(){return MAX_TIME_RANGE}async*queryPerPage(u,h,b){var _,E;if(u.timeStart&&u.timeEnd&&u.timeEnd.getTime()-u.timeStart.getTime()>MAX_TIME_RANGE)throw new Error("Time range bigger than 24h");if(!(u.messageHashes&&u.messageHashes.length>0)&&u.contentTopics&&u.contentTopics.toString()!==Array.from(h.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let w=u.paginationCursor;for(;;){const S=StoreQueryRequest.create({...u,paginationCursor:w});log$s.info("Sending store query request:",{hasMessageHashes:!!((_=u.messageHashes)!=null&&_.length),messageHashCount:(E=u.messageHashes)==null?void 0:E.length,pubsubTopic:u.pubsubTopic,contentTopics:u.contentTopics});const x=await this.streamManager.getStream(b);if(!x){log$s.error(`Failed to get a stream for remote peer:${b.toString()}`);break}const T=await pipe$1([S.encode()],encode$3,x,decode$2,async U=>await all$2(U)),C=new Uint8ArrayList;T.forEach(U=>{C.append(U)});const O=StoreQueryResponse.decode(C);if(!O.statusCode||O.statusCode>=300){const U=`Store query failed with status code: ${O.statusCode}, description: ${O.statusDesc}`;throw log$s.error(U),new Error(U)}if(!O.messages||!O.messages.length){log$s.warn("Stopping pagination due to empty messages in response");break}if(log$s.info(`${O.messages.length} messages retrieved from store`),yield O.messages.map(U=>{if(!U.message)return Promise.resolve(void 0);const te=U.message.contentTopic;if(te){const X=h.get(te);if(X)return X.fromProtoObj(U.pubsubTopic||"",toProtoMessage(U.message))}return Promise.resolve(void 0)}),u.paginationForward?w=O.messages[O.messages.length-1].messageHash:w=O.messages[0].messageHash,O.messages.length>MAX_PAGE_SIZE&&O.messages.length<(u.paginationLimit||DEFAULT_PAGE_SIZE))break}}}var Yl;let InvalidParametersError$1=(Yl=class extends Error{constructor(u="Invalid parameters"){super(u),this.name="InvalidParametersError"}},Z(Yl,"name","InvalidParametersError"),Yl);class InvalidPublicKeyError extends Error{constructor(u="Invalid public key"){super(u),this.name="InvalidPublicKeyError"}}Z(InvalidPublicKeyError,"name","InvalidPublicKeyError");class UnsupportedKeyTypeError extends Error{constructor(u="Unsupported key type"){super(u),this.name="UnsupportedKeyTypeError"}}Z(UnsupportedKeyTypeError,"name","UnsupportedKeyTypeError");const TAG_MASK$1=parseInt("11111",2),LONG_LENGTH_MASK$1=parseInt("10000000",2),LONG_LENGTH_BYTES_MASK$1=parseInt("01111111",2),decoders$3={0:readSequence$1,1:readSequence$1,2:readInteger$1,3:readBitString$1,4:readOctetString$1,5:readNull$1,6:readObjectIdentifier$1,16:readSequence$1,22:readSequence$1,48:readSequence$1};function decodeDer$1(y,u={offset:0}){const h=y[u.offset]&TAG_MASK$1;if(u.offset++,decoders$3[h]!=null)return decoders$3[h](y,u);throw new Error("No decoder for tag "+h)}function readLength$1(y,u){let h=0;if((y[u.offset]&LONG_LENGTH_MASK$1)===LONG_LENGTH_MASK$1){const b=y[u.offset]&LONG_LENGTH_BYTES_MASK$1;let v="0x";u.offset++;for(let w=0;w<b;w++,u.offset++)v+=y[u.offset].toString(16).padStart(2,"0");h=parseInt(v,16)}else h=y[u.offset],u.offset++;return h}function readSequence$1(y,u){readLength$1(y,u);const h=[];for(;!(u.offset>=y.byteLength);){const b=decodeDer$1(y,u);if(b===null)break;h.push(b)}return h}function readInteger$1(y,u){const h=readLength$1(y,u),b=u.offset,v=u.offset+h,w=[];for(let _=b;_<v;_++)_===b&&y[_]===0||w.push(y[_]);return u.offset+=h,Uint8Array.from(w)}function readObjectIdentifier$1(y,u){const h=readLength$1(y,u),b=u.offset+h,v=y[u.offset];u.offset++;let w=0,_=0;v<40?(w=0,_=v):v<80?(w=1,_=v-40):(w=2,_=v-80);let E=`${w}.${_}`,S=[];for(;u.offset<b;){const x=y[u.offset];if(u.offset++,S.push(x&127),x<128){S.reverse();let T=0;for(let C=0;C<S.length;C++)T+=S[C]<<C*7;E+=`.${T}`,S=[]}}return E}function readNull$1(y,u){return u.offset++,null}function readBitString$1(y,u){const h=readLength$1(y,u),b=y[u.offset];u.offset++;const v=y.subarray(u.offset,u.offset+h-1);if(u.offset+=h,b!==0)throw new Error("Unused bits in bit string is unimplemented");return v}function readOctetString$1(y,u){const h=readLength$1(y,u),b=y.subarray(u.offset,u.offset+h);return u.offset+=h,b}function encodeNumber$1(y){let u=y.toString(16);u.length%2===1&&(u="0"+u);const h=new Uint8ArrayList;for(let b=0;b<u.length;b+=2)h.append(Uint8Array.from([parseInt(`${u[b]}${u[b+1]}`,16)]));return h}function encodeLength$1(y){if(y.byteLength<128)return Uint8Array.from([y.byteLength]);const u=encodeNumber$1(y.byteLength);return new Uint8ArrayList(Uint8Array.from([u.byteLength|LONG_LENGTH_MASK$1]),u)}function encodeInteger$1(y){const u=new Uint8ArrayList,h=128;return(y.subarray()[0]&h)===h&&u.append(Uint8Array.from([0])),u.append(y),new Uint8ArrayList(Uint8Array.from([2]),encodeLength$1(u),u)}function encodeBitString$1(y){const u=Uint8Array.from([0]),h=new Uint8ArrayList(u,y);return new Uint8ArrayList(Uint8Array.from([3]),encodeLength$1(h),h)}function encodeSequence$1(y,u=48){const h=new Uint8ArrayList;for(const b of y)h.append(b);return new Uint8ArrayList(Uint8Array.from([u]),encodeLength$1(h),h)}async function hashAndVerify$7(y,u,h,b){var _,E;const v=await crypto.subtle.importKey("jwk",y,{name:"ECDSA",namedCurve:y.crv??"P-256"},!1,["verify"]);(_=b==null?void 0:b.signal)==null||_.throwIfAborted();const w=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},v,u,h.subarray());return(E=b==null?void 0:b.signal)==null||E.throwIfAborted(),w}const OID_256$1=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),OID_384$1=Uint8Array.from([6,5,43,129,4,0,34]),OID_521$1=Uint8Array.from([6,5,43,129,4,0,35]),P_256_KEY_JWK$1={ext:!0,kty:"EC",crv:"P-256"},P_384_KEY_JWK$1={ext:!0,kty:"EC",crv:"P-384"},P_521_KEY_JWK$1={ext:!0,kty:"EC",crv:"P-521"},P_256_KEY_LENGTH$1=32,P_384_KEY_LENGTH$1=48,P_521_KEY_LENGTH$1=66;function unmarshalECDSAPublicKey(y){const u=decodeDer$1(y);return pkiMessageToECDSAPublicKey$1(u)}function pkiMessageToECDSAPublicKey$1(y){const u=y[1][1][0],h=1;let b,v;if(u.byteLength===P_256_KEY_LENGTH$1*2+1)return b=toString$1(u.subarray(h,h+P_256_KEY_LENGTH$1),"base64url"),v=toString$1(u.subarray(h+P_256_KEY_LENGTH$1),"base64url"),new ECDSAPublicKey$1({...P_256_KEY_JWK$1,key_ops:["verify"],x:b,y:v});if(u.byteLength===P_384_KEY_LENGTH$1*2+1)return b=toString$1(u.subarray(h,h+P_384_KEY_LENGTH$1),"base64url"),v=toString$1(u.subarray(h+P_384_KEY_LENGTH$1),"base64url"),new ECDSAPublicKey$1({...P_384_KEY_JWK$1,key_ops:["verify"],x:b,y:v});if(u.byteLength===P_521_KEY_LENGTH$1*2+1)return b=toString$1(u.subarray(h,h+P_521_KEY_LENGTH$1),"base64url"),v=toString$1(u.subarray(h+P_521_KEY_LENGTH$1),"base64url"),new ECDSAPublicKey$1({...P_521_KEY_JWK$1,key_ops:["verify"],x:b,y:v});throw new InvalidParametersError$1(`coordinates were wrong length, got ${u.byteLength}, expected 65, 97 or 133`)}function publicKeyToPKIMessage$1(y){return encodeSequence$1([encodeInteger$1(Uint8Array.from([1])),encodeSequence$1([getOID$1(y.crv)],160),encodeSequence$1([encodeBitString$1(new Uint8ArrayList(Uint8Array.from([4]),fromString(y.x??"","base64url"),fromString(y.y??"","base64url")))],161)]).subarray()}function getOID$1(y){if(y==="P-256")return OID_256$1;if(y==="P-384")return OID_384$1;if(y==="P-521")return OID_521$1;throw new InvalidParametersError$1(`Invalid curve ${y}`)}let ECDSAPublicKey$1=class{constructor(u){Z(this,"type","ECDSA");Z(this,"jwk");Z(this,"_raw");this.jwk=u}get raw(){return this._raw==null&&(this._raw=publicKeyToPKIMessage$1(this.jwk)),this._raw}toMultihash(){return identity.digest(publicKeyToProtobuf$1(this))}toCID(){return CID.createV1(114,this.toMultihash())}toString(){return base58btc.encode(this.toMultihash().bytes).substring(1)}equals(u){return u==null||!(u.raw instanceof Uint8Array)?!1:equals(this.raw,u.raw)}async verify(u,h,b){return hashAndVerify$7(this.jwk,h,u,b)}};/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$6=BigInt(0),_1n$7=BigInt(1);function _abool2(y,u=""){if(typeof y!="boolean"){const h=u&&`"${u}"`;throw new Error(h+"expected boolean, got type="+typeof y)}return y}function _abytes2(y,u,h=""){const b=isBytes$3(y),v=y==null?void 0:y.length,w=u!==void 0;if(!b||w&&v!==u){const _=h&&`"${h}" `,E=w?` of length ${u}`:"",S=b?`length=${v}`:`type=${typeof y}`;throw new Error(_+"expected Uint8Array"+E+", got "+S)}return y}function numberToHexUnpadded$1(y){const u=y.toString(16);return u.length&1?"0"+u:u}function hexToNumber$1(y){if(typeof y!="string")throw new Error("hex string expected, got "+typeof y);return y===""?_0n$6:BigInt("0x"+y)}function bytesToNumberBE(y){return hexToNumber$1(bytesToHex$2(y))}function bytesToNumberLE(y){return abytes$2(y),hexToNumber$1(bytesToHex$2(Uint8Array.from(y).reverse()))}function numberToBytesBE(y,u){return hexToBytes$2(y.toString(16).padStart(u*2,"0"))}function numberToBytesLE(y,u){return numberToBytesBE(y,u).reverse()}function ensureBytes$1(y,u,h){let b;if(typeof u=="string")try{b=hexToBytes$2(u)}catch(w){throw new Error(y+" must be hex string or Uint8Array, cause: "+w)}else if(isBytes$3(u))b=Uint8Array.from(u);else throw new Error(y+" must be hex string or Uint8Array");const v=b.length;if(typeof h=="number"&&v!==h)throw new Error(y+" of length "+h+" expected, got "+v);return b}function copyBytes$1(y){return Uint8Array.from(y)}const isPosBig=y=>typeof y=="bigint"&&_0n$6<=y;function inRange(y,u,h){return isPosBig(y)&&isPosBig(u)&&isPosBig(h)&&u<=y&&y<h}function aInRange(y,u,h,b){if(!inRange(u,h,b))throw new Error("expected valid "+y+": "+h+" <= n < "+b+", got "+u)}function bitLen(y){let u;for(u=0;y>_0n$6;y>>=_1n$7,u+=1);return u}const bitMask=y=>(_1n$7<<BigInt(y))-_1n$7;function createHmacDrbg(y,u,h){if(typeof y!="number"||y<2)throw new Error("hashLen must be a number");if(typeof u!="number"||u<2)throw new Error("qByteLen must be a number");if(typeof h!="function")throw new Error("hmacFn must be a function");const b=D=>new Uint8Array(D),v=D=>Uint8Array.of(D);let w=b(y),_=b(y),E=0;const S=()=>{w.fill(1),_.fill(0),E=0},x=(...D)=>h(_,w,...D),T=(D=b(0))=>{_=x(v(0),D),w=x(),D.length!==0&&(_=x(v(1),D),w=x())},C=()=>{if(E++>=1e3)throw new Error("drbg: tried 1000 values");let D=0;const U=[];for(;D<u;){w=x();const te=w.slice();U.push(te),D+=w.length}return concatBytes$1(...U)};return(D,U)=>{S(),T(D);let te;for(;!(te=U(C()));)T();return S(),te}}function _validateObject(y,u,h={}){if(!y||typeof y!="object")throw new Error("expected valid options object");function b(v,w,_){const E=y[v];if(_&&E===void 0)return;const S=typeof E;if(S!==w||E===null)throw new Error(`param "${v}" is invalid: expected ${w}, got ${S}`)}Object.entries(u).forEach(([v,w])=>b(v,w,!1)),Object.entries(h).forEach(([v,w])=>b(v,w,!0))}function memoized(y){const u=new WeakMap;return(h,...b)=>{const v=u.get(h);if(v!==void 0)return v;const w=y(h,...b);return u.set(h,w),w}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$5=BigInt(0),_1n$6=BigInt(1),_2n$6=BigInt(2),_3n$3=BigInt(3),_4n$1=BigInt(4),_5n$1=BigInt(5),_7n=BigInt(7),_8n$3=BigInt(8),_9n=BigInt(9),_16n=BigInt(16);function mod$1(y,u){const h=y%u;return h>=_0n$5?h:u+h}function pow2$1(y,u,h){let b=y;for(;u-- >_0n$5;)b*=b,b%=h;return b}function invert$1(y,u){if(y===_0n$5)throw new Error("invert: expected non-zero number");if(u<=_0n$5)throw new Error("invert: expected positive modulus, got "+u);let h=mod$1(y,u),b=u,v=_0n$5,w=_1n$6;for(;h!==_0n$5;){const E=b/h,S=b%h,x=v-w*E;b=h,h=S,v=w,w=x}if(b!==_1n$6)throw new Error("invert: does not exist");return mod$1(v,u)}function assertIsSquare(y,u,h){if(!y.eql(y.sqr(u),h))throw new Error("Cannot find square root")}function sqrt3mod4(y,u){const h=(y.ORDER+_1n$6)/_4n$1,b=y.pow(u,h);return assertIsSquare(y,b,u),b}function sqrt5mod8(y,u){const h=(y.ORDER-_5n$1)/_8n$3,b=y.mul(u,_2n$6),v=y.pow(b,h),w=y.mul(u,v),_=y.mul(y.mul(w,_2n$6),v),E=y.mul(w,y.sub(_,y.ONE));return assertIsSquare(y,E,u),E}function sqrt9mod16(y){const u=Field$1(y),h=tonelliShanks(y),b=h(u,u.neg(u.ONE)),v=h(u,b),w=h(u,u.neg(b)),_=(y+_7n)/_16n;return(E,S)=>{let x=E.pow(S,_),T=E.mul(x,b);const C=E.mul(x,v),O=E.mul(x,w),D=E.eql(E.sqr(T),S),U=E.eql(E.sqr(C),S);x=E.cmov(x,T,D),T=E.cmov(O,C,U);const te=E.eql(E.sqr(T),S),X=E.cmov(x,T,te);return assertIsSquare(E,X,S),X}}function tonelliShanks(y){if(y<_3n$3)throw new Error("sqrt is not defined for small field");let u=y-_1n$6,h=0;for(;u%_2n$6===_0n$5;)u/=_2n$6,h++;let b=_2n$6;const v=Field$1(y);for(;FpLegendre(v,b)===1;)if(b++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(h===1)return sqrt3mod4;let w=v.pow(b,u);const _=(u+_1n$6)/_2n$6;return function(S,x){if(S.is0(x))return x;if(FpLegendre(S,x)!==1)throw new Error("Cannot find square root");let T=h,C=S.mul(S.ONE,w),O=S.pow(x,u),D=S.pow(x,_);for(;!S.eql(O,S.ONE);){if(S.is0(O))return S.ZERO;let U=1,te=S.sqr(O);for(;!S.eql(te,S.ONE);)if(U++,te=S.sqr(te),U===T)throw new Error("Cannot find square root");const X=_1n$6<<BigInt(T-U-1),ie=S.pow(C,X);T=U,C=S.sqr(ie),O=S.mul(O,C),D=S.mul(D,ie)}return D}}function FpSqrt(y){return y%_4n$1===_3n$3?sqrt3mod4:y%_8n$3===_5n$1?sqrt5mod8:y%_16n===_9n?sqrt9mod16(y):tonelliShanks(y)}const isNegativeLE=(y,u)=>(mod$1(y,u)&_1n$6)===_1n$6,FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(y){const u={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},h=FIELD_FIELDS.reduce((b,v)=>(b[v]="function",b),u);return _validateObject(y,h),y}function FpPow(y,u,h){if(h<_0n$5)throw new Error("invalid exponent, negatives unsupported");if(h===_0n$5)return y.ONE;if(h===_1n$6)return u;let b=y.ONE,v=u;for(;h>_0n$5;)h&_1n$6&&(b=y.mul(b,v)),v=y.sqr(v),h>>=_1n$6;return b}function FpInvertBatch(y,u,h=!1){const b=new Array(u.length).fill(h?y.ZERO:void 0),v=u.reduce((_,E,S)=>y.is0(E)?_:(b[S]=_,y.mul(_,E)),y.ONE),w=y.inv(v);return u.reduceRight((_,E,S)=>y.is0(E)?_:(b[S]=y.mul(_,b[S]),y.mul(_,E)),w),b}function FpLegendre(y,u){const h=(y.ORDER-_1n$6)/_2n$6,b=y.pow(u,h),v=y.eql(b,y.ONE),w=y.eql(b,y.ZERO),_=y.eql(b,y.neg(y.ONE));if(!v&&!w&&!_)throw new Error("invalid Legendre symbol result");return v?1:w?0:-1}function nLength(y,u){u!==void 0&&anumber$1(u);const h=u!==void 0?u:y.toString(2).length,b=Math.ceil(h/8);return{nBitLength:h,nByteLength:b}}function Field$1(y,u,h=!1,b={}){if(y<=_0n$5)throw new Error("invalid field: expected ORDER > 0, got "+y);let v,w,_=!1,E;if(typeof u=="object"&&u!=null){if(b.sqrt||h)throw new Error("cannot specify opts in two arguments");const O=u;O.BITS&&(v=O.BITS),O.sqrt&&(w=O.sqrt),typeof O.isLE=="boolean"&&(h=O.isLE),typeof O.modFromBytes=="boolean"&&(_=O.modFromBytes),E=O.allowedLengths}else typeof u=="number"&&(v=u),b.sqrt&&(w=b.sqrt);const{nBitLength:S,nByteLength:x}=nLength(y,v);if(x>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let T;const C=Object.freeze({ORDER:y,isLE:h,BITS:S,BYTES:x,MASK:bitMask(S),ZERO:_0n$5,ONE:_1n$6,allowedLengths:E,create:O=>mod$1(O,y),isValid:O=>{if(typeof O!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof O);return _0n$5<=O&&O<y},is0:O=>O===_0n$5,isValidNot0:O=>!C.is0(O)&&C.isValid(O),isOdd:O=>(O&_1n$6)===_1n$6,neg:O=>mod$1(-O,y),eql:(O,D)=>O===D,sqr:O=>mod$1(O*O,y),add:(O,D)=>mod$1(O+D,y),sub:(O,D)=>mod$1(O-D,y),mul:(O,D)=>mod$1(O*D,y),pow:(O,D)=>FpPow(C,O,D),div:(O,D)=>mod$1(O*invert$1(D,y),y),sqrN:O=>O*O,addN:(O,D)=>O+D,subN:(O,D)=>O-D,mulN:(O,D)=>O*D,inv:O=>invert$1(O,y),sqrt:w||(O=>(T||(T=FpSqrt(y)),T(C,O))),toBytes:O=>h?numberToBytesLE(O,x):numberToBytesBE(O,x),fromBytes:(O,D=!0)=>{if(E){if(!E.includes(O.length)||O.length>x)throw new Error("Field.fromBytes: expected "+E+" bytes, got "+O.length);const te=new Uint8Array(x);te.set(O,h?0:te.length-O.length),O=te}if(O.length!==x)throw new Error("Field.fromBytes: expected "+x+" bytes, got "+O.length);let U=h?bytesToNumberLE(O):bytesToNumberBE(O);if(_&&(U=mod$1(U,y)),!D&&!C.isValid(U))throw new Error("invalid field element: outside of range 0..ORDER");return U},invertBatch:O=>FpInvertBatch(C,O),cmov:(O,D,U)=>U?D:O});return Object.freeze(C)}function getFieldBytesLength(y){if(typeof y!="bigint")throw new Error("field order must be bigint");const u=y.toString(2).length;return Math.ceil(u/8)}function getMinHashLength(y){const u=getFieldBytesLength(y);return u+Math.ceil(u/2)}function mapHashToField(y,u,h=!1){const b=y.length,v=getFieldBytesLength(u),w=getMinHashLength(u);if(b<16||b<w||b>1024)throw new Error("expected "+w+"-1024 bytes of input, got "+b);const _=h?bytesToNumberLE(y):bytesToNumberBE(y),E=mod$1(_,u-_1n$6)+_1n$6;return h?numberToBytesLE(E,v):numberToBytesBE(E,v)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$5=BigInt(1);function negateCt(y,u){const h=u.negate();return y?h:u}function normalizeZ(y,u){const h=FpInvertBatch(y.Fp,u.map(b=>b.Z));return u.map((b,v)=>y.fromAffine(b.toAffine(h[v])))}function validateW(y,u){if(!Number.isSafeInteger(y)||y<=0||y>u)throw new Error("invalid window size, expected [1.."+u+"], got W="+y)}function calcWOpts(y,u){validateW(y,u);const h=Math.ceil(u/y)+1,b=2**(y-1),v=2**y,w=bitMask(y),_=BigInt(y);return{windows:h,windowSize:b,mask:w,maxNumber:v,shiftBy:_}}function calcOffsets(y,u,h){const{windowSize:b,mask:v,maxNumber:w,shiftBy:_}=h;let E=Number(y&v),S=y>>_;E>b&&(E-=w,S+=_1n$5);const x=u*b,T=x+Math.abs(E)-1,C=E===0,O=E<0,D=u%2!==0;return{nextN:S,offset:T,isZero:C,isNeg:O,isNegF:D,offsetF:x}}function validateMSMPoints(y,u){if(!Array.isArray(y))throw new Error("array expected");y.forEach((h,b)=>{if(!(h instanceof u))throw new Error("invalid point at index "+b)})}function validateMSMScalars(y,u){if(!Array.isArray(y))throw new Error("array of scalars expected");y.forEach((h,b)=>{if(!u.isValid(h))throw new Error("invalid scalar at index "+b)})}const pointPrecomputes$1=new WeakMap,pointWindowSizes=new WeakMap;function getW(y){return pointWindowSizes.get(y)||1}function assert0(y){if(y!==_0n$4)throw new Error("invalid wNAF")}class wNAF{constructor(u,h){this.BASE=u.BASE,this.ZERO=u.ZERO,this.Fn=u.Fn,this.bits=h}_unsafeLadder(u,h,b=this.ZERO){let v=u;for(;h>_0n$4;)h&_1n$5&&(b=b.add(v)),v=v.double(),h>>=_1n$5;return b}precomputeWindow(u,h){const{windows:b,windowSize:v}=calcWOpts(h,this.bits),w=[];let _=u,E=_;for(let S=0;S<b;S++){E=_,w.push(E);for(let x=1;x<v;x++)E=E.add(_),w.push(E);_=E.double()}return w}wNAF(u,h,b){if(!this.Fn.isValid(b))throw new Error("invalid scalar");let v=this.ZERO,w=this.BASE;const _=calcWOpts(u,this.bits);for(let E=0;E<_.windows;E++){const{nextN:S,offset:x,isZero:T,isNeg:C,isNegF:O,offsetF:D}=calcOffsets(b,E,_);b=S,T?w=w.add(negateCt(O,h[D])):v=v.add(negateCt(C,h[x]))}return assert0(b),{p:v,f:w}}wNAFUnsafe(u,h,b,v=this.ZERO){const w=calcWOpts(u,this.bits);for(let _=0;_<w.windows&&b!==_0n$4;_++){const{nextN:E,offset:S,isZero:x,isNeg:T}=calcOffsets(b,_,w);if(b=E,!x){const C=h[S];v=v.add(T?C.negate():C)}}return assert0(b),v}getPrecomputes(u,h,b){let v=pointPrecomputes$1.get(h);return v||(v=this.precomputeWindow(h,u),u!==1&&(typeof b=="function"&&(v=b(v)),pointPrecomputes$1.set(h,v))),v}cached(u,h,b){const v=getW(u);return this.wNAF(v,this.getPrecomputes(v,u,b),h)}unsafe(u,h,b,v){const w=getW(u);return w===1?this._unsafeLadder(u,h,v):this.wNAFUnsafe(w,this.getPrecomputes(w,u,b),h,v)}createCache(u,h){validateW(h,this.bits),pointWindowSizes.set(u,h),pointPrecomputes$1.delete(u)}hasCache(u){return getW(u)!==1}}function mulEndoUnsafe(y,u,h,b){let v=u,w=y.ZERO,_=y.ZERO;for(;h>_0n$4||b>_0n$4;)h&_1n$5&&(w=w.add(v)),b&_1n$5&&(_=_.add(v)),v=v.double(),h>>=_1n$5,b>>=_1n$5;return{p1:w,p2:_}}function pippenger(y,u,h,b){validateMSMPoints(h,y),validateMSMScalars(b,u);const v=h.length,w=b.length;if(v!==w)throw new Error("arrays of points and scalars must have equal length");const _=y.ZERO,E=bitLen(BigInt(v));let S=1;E>12?S=E-3:E>4?S=E-2:E>0&&(S=2);const x=bitMask(S),T=new Array(Number(x)+1).fill(_),C=Math.floor((u.BITS-1)/S)*S;let O=_;for(let D=C;D>=0;D-=S){T.fill(_);for(let te=0;te<w;te++){const X=b[te],ie=Number(X>>BigInt(D)&x);T[ie]=T[ie].add(h[te])}let U=_;for(let te=T.length-1,X=_;te>0;te--)X=X.add(T[te]),U=U.add(X);if(O=O.add(U),D!==0)for(let te=0;te<S;te++)O=O.double()}return O}function createField(y,u,h){if(u){if(u.ORDER!==y)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField(u),u}else return Field$1(y,{isLE:h})}function _createCurveFields(y,u,h={},b){if(b===void 0&&(b=y==="edwards"),!u||typeof u!="object")throw new Error(`expected valid ${y} CURVE object`);for(const S of["p","n","h"]){const x=u[S];if(!(typeof x=="bigint"&&x>_0n$4))throw new Error(`CURVE.${S} must be positive bigint`)}const v=createField(u.p,h.Fp,b),w=createField(u.n,h.Fn,b),E=["Gx","Gy","a",y==="weierstrass"?"b":"d"];for(const S of E)if(!v.isValid(u[S]))throw new Error(`CURVE.${S} must be valid field element of CURVE.Fp`);return u=Object.freeze(Object.assign({},u)),{CURVE:u,Fp:v,Fn:w}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$4=BigInt(1),_2n$5=BigInt(2),_8n$2=BigInt(8);function isEdValidXY(y,u,h,b){const v=y.sqr(h),w=y.sqr(b),_=y.add(y.mul(u.a,v),w),E=y.add(y.ONE,y.mul(u.d,y.mul(v,w)));return y.eql(_,E)}function edwards$1(y,u={}){const h=_createCurveFields("edwards",y,u,u.FpFnLE),{Fp:b,Fn:v}=h;let w=h.CURVE;const{h:_}=w;_validateObject(u,{},{uvRatio:"function"});const E=_2n$5<<BigInt(v.BYTES*8)-_1n$4,S=X=>b.create(X),x=u.uvRatio||((X,ie)=>{try{return{isValid:!0,value:b.sqrt(b.div(X,ie))}}catch{return{isValid:!1,value:_0n$3}}});if(!isEdValidXY(b,w,w.Gx,w.Gy))throw new Error("bad curve params: generator point");function T(X,ie,ee=!1){const ae=ee?_1n$4:_0n$3;return aInRange("coordinate "+X,ie,ae,E),ie}function C(X){if(!(X instanceof U))throw new Error("ExtendedPoint expected")}const O=memoized((X,ie)=>{const{X:ee,Y:ae,Z:de}=X,Se=X.is0();ie==null&&(ie=Se?_8n$2:b.inv(de));const ve=S(ee*ie),Pe=S(ae*ie),Ie=b.mul(de,ie);if(Se)return{x:_0n$3,y:_1n$4};if(Ie!==_1n$4)throw new Error("invZ was invalid");return{x:ve,y:Pe}}),D=memoized(X=>{const{a:ie,d:ee}=w;if(X.is0())throw new Error("bad point: ZERO");const{X:ae,Y:de,Z:Se,T:ve}=X,Pe=S(ae*ae),Ie=S(de*de),Ee=S(Se*Se),De=S(Ee*Ee),be=S(Pe*ie),B=S(Ee*S(be+Ie)),F=S(De+S(ee*S(Pe*Ie)));if(B!==F)throw new Error("bad point: equation left != right (1)");const M=S(ae*de),N=S(Se*ve);if(M!==N)throw new Error("bad point: equation left != right (2)");return!0});class U{constructor(ie,ee,ae,de){this.X=T("x",ie),this.Y=T("y",ee),this.Z=T("z",ae,!0),this.T=T("t",de),Object.freeze(this)}static CURVE(){return w}static fromAffine(ie){if(ie instanceof U)throw new Error("extended point not allowed");const{x:ee,y:ae}=ie||{};return T("x",ee),T("y",ae),new U(ee,ae,_1n$4,S(ee*ae))}static fromBytes(ie,ee=!1){const ae=b.BYTES,{a:de,d:Se}=w;ie=copyBytes$1(_abytes2(ie,ae,"point")),_abool2(ee,"zip215");const ve=copyBytes$1(ie),Pe=ie[ae-1];ve[ae-1]=Pe&-129;const Ie=bytesToNumberLE(ve),Ee=ee?E:b.ORDER;aInRange("point.y",Ie,_0n$3,Ee);const De=S(Ie*Ie),be=S(De-_1n$4),B=S(Se*De-de);let{isValid:F,value:M}=x(be,B);if(!F)throw new Error("bad point: invalid y coordinate");const N=(M&_1n$4)===_1n$4,Q=(Pe&128)!==0;if(!ee&&M===_0n$3&&Q)throw new Error("bad point: x=0 and x_0=1");return Q!==N&&(M=S(-M)),U.fromAffine({x:M,y:Ie})}static fromHex(ie,ee=!1){return U.fromBytes(ensureBytes$1("point",ie),ee)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(ie=8,ee=!0){return te.createCache(this,ie),ee||this.multiply(_2n$5),this}assertValidity(){D(this)}equals(ie){C(ie);const{X:ee,Y:ae,Z:de}=this,{X:Se,Y:ve,Z:Pe}=ie,Ie=S(ee*Pe),Ee=S(Se*de),De=S(ae*Pe),be=S(ve*de);return Ie===Ee&&De===be}is0(){return this.equals(U.ZERO)}negate(){return new U(S(-this.X),this.Y,this.Z,S(-this.T))}double(){const{a:ie}=w,{X:ee,Y:ae,Z:de}=this,Se=S(ee*ee),ve=S(ae*ae),Pe=S(_2n$5*S(de*de)),Ie=S(ie*Se),Ee=ee+ae,De=S(S(Ee*Ee)-Se-ve),be=Ie+ve,B=be-Pe,F=Ie-ve,M=S(De*B),N=S(be*F),Q=S(De*F),j=S(B*be);return new U(M,N,j,Q)}add(ie){C(ie);const{a:ee,d:ae}=w,{X:de,Y:Se,Z:ve,T:Pe}=this,{X:Ie,Y:Ee,Z:De,T:be}=ie,B=S(de*Ie),F=S(Se*Ee),M=S(Pe*ae*be),N=S(ve*De),Q=S((de+Se)*(Ie+Ee)-B-F),j=N-M,ne=N+M,J=S(F-ee*B),q=S(Q*j),re=S(ne*J),H=S(Q*J),he=S(j*ne);return new U(q,re,he,H)}subtract(ie){return this.add(ie.negate())}multiply(ie){if(!v.isValidNot0(ie))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:ee,f:ae}=te.cached(this,ie,de=>normalizeZ(U,de));return normalizeZ(U,[ee,ae])[0]}multiplyUnsafe(ie,ee=U.ZERO){if(!v.isValid(ie))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return ie===_0n$3?U.ZERO:this.is0()||ie===_1n$4?this:te.unsafe(this,ie,ae=>normalizeZ(U,ae),ee)}isSmallOrder(){return this.multiplyUnsafe(_).is0()}isTorsionFree(){return te.unsafe(this,w.n).is0()}toAffine(ie){return O(this,ie)}clearCofactor(){return _===_1n$4?this:this.multiplyUnsafe(_)}toBytes(){const{x:ie,y:ee}=this.toAffine(),ae=b.toBytes(ee);return ae[ae.length-1]|=ie&_1n$4?128:0,ae}toHex(){return bytesToHex$2(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(ie){return normalizeZ(U,ie)}static msm(ie,ee){return pippenger(U,v,ie,ee)}_setWindowSize(ie){this.precompute(ie)}toRawBytes(){return this.toBytes()}}U.BASE=new U(w.Gx,w.Gy,_1n$4,S(w.Gx*w.Gy)),U.ZERO=new U(_0n$3,_1n$4,_1n$4,_0n$3),U.Fp=b,U.Fn=v;const te=new wNAF(U,v.BITS);return U.BASE.precompute(8),U}function eddsa$1(y,u,h={}){if(typeof u!="function")throw new Error('"hash" function param is required');_validateObject(h,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:b}=h,{BASE:v,Fp:w,Fn:_}=y,E=h.randomBytes||randomBytes$4,S=h.adjustScalarBytes||(Ee=>Ee),x=h.domain||((Ee,De,be)=>{if(_abool2(be,"phflag"),De.length||be)throw new Error("Contexts/pre-hash are not supported");return Ee});function T(Ee){return _.create(bytesToNumberLE(Ee))}function C(Ee){const De=ae.secretKey;Ee=ensureBytes$1("private key",Ee,De);const be=ensureBytes$1("hashed private key",u(Ee),2*De),B=S(be.slice(0,De)),F=be.slice(De,2*De),M=T(B);return{head:B,prefix:F,scalar:M}}function O(Ee){const{head:De,prefix:be,scalar:B}=C(Ee),F=v.multiply(B),M=F.toBytes();return{head:De,prefix:be,scalar:B,point:F,pointBytes:M}}function D(Ee){return O(Ee).pointBytes}function U(Ee=Uint8Array.of(),...De){const be=concatBytes$1(...De);return T(u(x(be,ensureBytes$1("context",Ee),!!b)))}function te(Ee,De,be={}){Ee=ensureBytes$1("message",Ee),b&&(Ee=b(Ee));const{prefix:B,scalar:F,pointBytes:M}=O(De),N=U(be.context,B,Ee),Q=v.multiply(N).toBytes(),j=U(be.context,Q,M,Ee),ne=_.create(N+j*F);if(!_.isValid(ne))throw new Error("sign failed: invalid s");const J=concatBytes$1(Q,_.toBytes(ne));return _abytes2(J,ae.signature,"result")}const X={zip215:!0};function ie(Ee,De,be,B=X){const{context:F,zip215:M}=B,N=ae.signature;Ee=ensureBytes$1("signature",Ee,N),De=ensureBytes$1("message",De),be=ensureBytes$1("publicKey",be,ae.publicKey),M!==void 0&&_abool2(M,"zip215"),b&&(De=b(De));const Q=N/2,j=Ee.subarray(0,Q),ne=bytesToNumberLE(Ee.subarray(Q,N));let J,q,re;try{J=y.fromBytes(be,M),q=y.fromBytes(j,M),re=v.multiplyUnsafe(ne)}catch{return!1}if(!M&&J.isSmallOrder())return!1;const H=U(F,q.toBytes(),J.toBytes(),De);return q.add(J.multiplyUnsafe(H)).subtract(re).clearCofactor().is0()}const ee=w.BYTES,ae={secretKey:ee,publicKey:ee,signature:2*ee,seed:ee};function de(Ee=E(ae.seed)){return _abytes2(Ee,ae.seed,"seed")}function Se(Ee){const De=Ie.randomSecretKey(Ee);return{secretKey:De,publicKey:D(De)}}function ve(Ee){return isBytes$3(Ee)&&Ee.length===_.BYTES}function Pe(Ee,De){try{return!!y.fromBytes(Ee,De)}catch{return!1}}const Ie={getExtendedPublicKey:O,randomSecretKey:de,isValidSecretKey:ve,isValidPublicKey:Pe,toMontgomery(Ee){const{y:De}=y.fromBytes(Ee),be=ae.publicKey,B=be===32;if(!B&&be!==57)throw new Error("only defined for 25519 and 448");const F=B?w.div(_1n$4+De,_1n$4-De):w.div(De-_1n$4,De+_1n$4);return w.toBytes(F)},toMontgomerySecret(Ee){const De=ae.secretKey;_abytes2(Ee,De);const be=u(Ee.subarray(0,De));return S(be).subarray(0,De)},randomPrivateKey:de,precompute(Ee=8,De=y.BASE){return De.precompute(Ee,!1)}};return Object.freeze({keygen:Se,getPublicKey:D,sign:te,verify:ie,utils:Ie,Point:y,lengths:ae})}function _eddsa_legacy_opts_to_new(y){const u={a:y.a,d:y.d,p:y.Fp.ORDER,n:y.n,h:y.h,Gx:y.Gx,Gy:y.Gy},h=y.Fp,b=Field$1(u.n,y.nBitLength,!0),v={Fp:h,Fn:b,uvRatio:y.uvRatio},w={randomBytes:y.randomBytes,adjustScalarBytes:y.adjustScalarBytes,domain:y.domain,prehash:y.prehash,mapToCurve:y.mapToCurve};return{CURVE:u,curveOpts:v,hash:y.hash,eddsaOpts:w}}function _eddsa_new_output_to_legacy(y,u){const h=u.Point;return Object.assign({},u,{ExtendedPoint:h,CURVE:y,nBitLength:h.Fn.BITS,nByteLength:h.Fn.BYTES})}function twistedEdwards(y){const{CURVE:u,curveOpts:h,hash:b,eddsaOpts:v}=_eddsa_legacy_opts_to_new(y),w=edwards$1(u,h),_=eddsa$1(w,b,v);return _eddsa_new_output_to_legacy(y,_)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$3=BigInt(1),_2n$4=BigInt(2);function validateOpts(y){return _validateObject(y,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...y})}function montgomery(y){const u=validateOpts(y),{P:h,type:b,adjustScalarBytes:v,powPminus2:w,randomBytes:_}=u,E=b==="x25519";if(!E&&b!=="x448")throw new Error("invalid type");const S=_||randomBytes$4,x=E?255:448,T=E?32:56,C=BigInt(E?9:5),O=BigInt(E?121665:39081),D=E?_2n$4**BigInt(254):_2n$4**BigInt(447),U=E?BigInt(8)*_2n$4**BigInt(251)-_1n$3:BigInt(4)*_2n$4**BigInt(445)-_1n$3,te=D+U+_1n$3,X=F=>mod$1(F,h),ie=ee(C);function ee(F){return numberToBytesLE(X(F),T)}function ae(F){const M=ensureBytes$1("u coordinate",F,T);return E&&(M[31]&=127),X(bytesToNumberLE(M))}function de(F){return bytesToNumberLE(v(ensureBytes$1("scalar",F,T)))}function Se(F,M){const N=Ie(ae(M),de(F));if(N===_0n$2)throw new Error("invalid private or public key received");return ee(N)}function ve(F){return Se(F,ie)}function Pe(F,M,N){const Q=X(F*(M-N));return M=X(M-Q),N=X(N+Q),{x_2:M,x_3:N}}function Ie(F,M){aInRange("u",F,_0n$2,h),aInRange("scalar",M,D,te);const N=M,Q=F;let j=_1n$3,ne=_0n$2,J=F,q=_1n$3,re=_0n$2;for(let he=BigInt(x-1);he>=_0n$2;he--){const Oe=N>>he&_1n$3;re^=Oe,{x_2:j,x_3:J}=Pe(re,j,J),{x_2:ne,x_3:q}=Pe(re,ne,q),re=Oe;const Ne=j+ne,Ae=X(Ne*Ne),le=j-ne,me=X(le*le),Me=Ae-me,fe=J+q,ge=J-q,ce=X(ge*Ne),_e=X(fe*le),Re=ce+_e,Ue=ce-_e;J=X(Re*Re),q=X(Q*X(Ue*Ue)),j=X(Ae*me),ne=X(Me*(Ae+X(O*Me)))}({x_2:j,x_3:J}=Pe(re,j,J)),{x_2:ne,x_3:q}=Pe(re,ne,q);const H=w(ne);return X(j*H)}const Ee={secretKey:T,publicKey:T,seed:T},De=(F=S(T))=>(abytes$2(F,Ee.seed),F);function be(F){const M=De(F);return{secretKey:M,publicKey:ve(M)}}return{keygen:be,getSharedSecret:(F,M)=>Se(F,M),getPublicKey:F=>ve(F),scalarMult:Se,scalarMultBase:ve,utils:{randomSecretKey:De,randomPrivateKey:De},GuBytes:ie.slice(),lengths:Ee}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _1n$2=BigInt(1),_2n$3=BigInt(2),_3n$2=BigInt(3),_5n=BigInt(5),_8n$1=BigInt(8),ed25519_CURVE_p=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ed25519_CURVE={p:ed25519_CURVE_p,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:_8n$1,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ed25519_pow_2_252_3(y){const u=BigInt(10),h=BigInt(20),b=BigInt(40),v=BigInt(80),w=ed25519_CURVE_p,E=y*y%w*y%w,S=pow2$1(E,_2n$3,w)*E%w,x=pow2$1(S,_1n$2,w)*y%w,T=pow2$1(x,_5n,w)*x%w,C=pow2$1(T,u,w)*T%w,O=pow2$1(C,h,w)*C%w,D=pow2$1(O,b,w)*O%w,U=pow2$1(D,v,w)*D%w,te=pow2$1(U,v,w)*D%w,X=pow2$1(te,u,w)*T%w;return{pow_p_5_8:pow2$1(X,_2n$3,w)*y%w,b2:E}}function adjustScalarBytes(y){return y[0]&=248,y[31]&=127,y[31]|=64,y}const ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function uvRatio(y,u){const h=ed25519_CURVE_p,b=mod$1(u*u*u,h),v=mod$1(b*b*u,h),w=ed25519_pow_2_252_3(y*v).pow_p_5_8;let _=mod$1(y*b*w,h);const E=mod$1(u*_*_,h),S=_,x=mod$1(_*ED25519_SQRT_M1,h),T=E===y,C=E===mod$1(-y,h),O=E===mod$1(-y*ED25519_SQRT_M1,h);return T&&(_=S),(C||O)&&(_=x),isNegativeLE(_,h)&&(_=mod$1(-_,h)),{isValid:T||C,value:_}}const Fp=Field$1(ed25519_CURVE.p,{isLE:!0}),ed25519Defaults={...ed25519_CURVE,Fp,hash:sha512$2,adjustScalarBytes,uvRatio},ed25519=twistedEdwards(ed25519Defaults),x25519=(()=>{const y=Fp.ORDER;return montgomery({P:y,type:"x25519",powPminus2:u=>{const{pow_p_5_8:h,b2:b}=ed25519_pow_2_252_3(u);return mod$1(pow2$1(h,_3n$2,y)*b,y)},adjustScalarBytes})})();let VerificationError$1=class extends Error{constructor(u="An error occurred while verifying a message"){super(u),this.name="VerificationError"}},WebCryptoMissingError$1=class extends Error{constructor(u="Missing Web Crypto API"){super(u),this.name="WebCryptoMissingError"}};const webcrypto$1={get(y=globalThis){const u=y.crypto;if((u==null?void 0:u.subtle)==null)throw new WebCryptoMissingError$1("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return u}},PUBLIC_KEY_BYTE_LENGTH$2=32,PRIVATE_KEY_BYTE_LENGTH=64,KEYS_BYTE_LENGTH=32;let ed25519Supported$1;const webCryptoEd25519SupportedPromise$1=(async()=>{try{return await webcrypto$1.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function generateKey(){const y=ed25519.utils.randomPrivateKey(),u=ed25519.getPublicKey(y);return{privateKey:concatKeys(y,u),publicKey:u}}async function hashAndSignWebCrypto(y,u){let h;y.length===PRIVATE_KEY_BYTE_LENGTH?h=y.subarray(0,32):h=y;const b={crv:"Ed25519",kty:"OKP",x:toString$1(y.subarray(32),"base64url"),d:toString$1(h,"base64url"),ext:!0,key_ops:["sign"]},v=await webcrypto$1.get().subtle.importKey("jwk",b,{name:"Ed25519"},!0,["sign"]),w=await webcrypto$1.get().subtle.sign({name:"Ed25519"},v,u instanceof Uint8Array?u:u.subarray());return new Uint8Array(w,0,w.byteLength)}function hashAndSignNoble(y,u){const h=y.subarray(0,KEYS_BYTE_LENGTH);return ed25519.sign(u instanceof Uint8Array?u:u.subarray(),h)}async function hashAndSign(y,u){return ed25519Supported$1==null&&(ed25519Supported$1=await webCryptoEd25519SupportedPromise$1),ed25519Supported$1?hashAndSignWebCrypto(y,u):hashAndSignNoble(y,u)}async function hashAndVerifyWebCrypto$1(y,u,h){if(y.buffer instanceof ArrayBuffer){const b=await webcrypto$1.get().subtle.importKey("raw",y.buffer,{name:"Ed25519"},!1,["verify"]);return await webcrypto$1.get().subtle.verify({name:"Ed25519"},b,u,h instanceof Uint8Array?h:h.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function hashAndVerifyNoble$1(y,u,h){return ed25519.verify(u,h instanceof Uint8Array?h:h.subarray(),y)}async function hashAndVerify$6(y,u,h){return ed25519Supported$1==null&&(ed25519Supported$1=await webCryptoEd25519SupportedPromise$1),ed25519Supported$1?hashAndVerifyWebCrypto$1(y,u,h):hashAndVerifyNoble$1(y,u,h)}function concatKeys(y,u){const h=new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);for(let b=0;b<KEYS_BYTE_LENGTH;b++)h[b]=y[b],h[KEYS_BYTE_LENGTH+b]=u[b];return h}function isPromise$3(y){return y==null?!1:typeof y.then=="function"&&typeof y.catch=="function"&&typeof y.finally=="function"}let Ed25519PublicKey$1=class{constructor(u){Z(this,"type","Ed25519");Z(this,"raw");this.raw=ensureEd25519Key$1(u,PUBLIC_KEY_BYTE_LENGTH$2)}toMultihash(){return identity.digest(publicKeyToProtobuf$1(this))}toCID(){return CID.createV1(114,this.toMultihash())}toString(){return base58btc.encode(this.toMultihash().bytes).substring(1)}equals(u){return u==null||!(u.raw instanceof Uint8Array)?!1:equals(this.raw,u.raw)}verify(u,h,b){var w;(w=b==null?void 0:b.signal)==null||w.throwIfAborted();const v=hashAndVerify$6(this.raw,h,u);return isPromise$3(v)?v.then(_=>{var E;return(E=b==null?void 0:b.signal)==null||E.throwIfAborted(),_}):v}};class Ed25519PrivateKey{constructor(u,h){Z(this,"type","Ed25519");Z(this,"raw");Z(this,"publicKey");this.raw=ensureEd25519Key$1(u,PRIVATE_KEY_BYTE_LENGTH),this.publicKey=new Ed25519PublicKey$1(h)}equals(u){return u==null||!(u.raw instanceof Uint8Array)?!1:equals(this.raw,u.raw)}sign(u,h){var v,w;(v=h==null?void 0:h.signal)==null||v.throwIfAborted();const b=hashAndSign(this.raw,u);return isPromise$3(b)?b.then(_=>{var E;return(E=h==null?void 0:h.signal)==null||E.throwIfAborted(),_}):((w=h==null?void 0:h.signal)==null||w.throwIfAborted(),b)}}function unmarshalEd25519PublicKey$1(y){return y=ensureEd25519Key$1(y,PUBLIC_KEY_BYTE_LENGTH$2),new Ed25519PublicKey$1(y)}async function generateEd25519KeyPair(){const{privateKey:y,publicKey:u}=generateKey();return new Ed25519PrivateKey(y,u)}function ensureEd25519Key$1(y,u){if(y=Uint8Array.from(y??[]),y.length!==u)throw new InvalidParametersError$1(`Key must be a Uint8Array of length ${u}, got ${y.length}`);return y}var KeyType$1;(function(y){y.RSA="RSA",y.Ed25519="Ed25519",y.secp256k1="secp256k1",y.ECDSA="ECDSA"})(KeyType$1||(KeyType$1={}));var __KeyTypeValues$1;(function(y){y[y.RSA=0]="RSA",y[y.Ed25519=1]="Ed25519",y[y.secp256k1=2]="secp256k1",y[y.ECDSA=3]="ECDSA"})(__KeyTypeValues$1||(__KeyTypeValues$1={}));(function(y){y.codec=()=>enumeration(__KeyTypeValues$1)})(KeyType$1||(KeyType$1={}));var PublicKey$2;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.Type!=null&&(b.uint32(8),KeyType$1.codec().encode(h.Type,b)),h.Data!=null&&(b.uint32(18),b.bytes(h.Data)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.Type=KeyType$1.codec().decode(h);break}case 2:{w.Data=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PublicKey$2||(PublicKey$2={}));var PrivateKey$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.Type!=null&&(b.uint32(8),KeyType$1.codec().encode(h.Type,b)),h.Data!=null&&(b.uint32(18),b.bytes(h.Data)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.Type=KeyType$1.codec().decode(h);break}case 2:{w.Data=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PrivateKey$1||(PrivateKey$1={}));function randomBytes$3(y){if(isNaN(y)||y<=0)throw new InvalidParametersError$1("random bytes length must be a Number bigger than 0");return randomBytes$4(y)}let RSAPublicKey$2=class{constructor(u,h){Z(this,"type","RSA");Z(this,"jwk");Z(this,"_raw");Z(this,"_multihash");this.jwk=u,this._multihash=h}get raw(){return this._raw==null&&(this._raw=jwkToPkix$1(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return CID.createV1(114,this._multihash)}toString(){return base58btc.encode(this.toMultihash().bytes).substring(1)}equals(u){return u==null||!(u.raw instanceof Uint8Array)?!1:equals(this.raw,u.raw)}verify(u,h,b){return hashAndVerify$5(this.jwk,h,u,b)}};const SHA2_256_CODE$1=18,MAX_RSA_JWK_SIZE=1062,RSA_ALGORITHM_IDENTIFIER$1=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function pkixMessageToJwk$1(y){const u=decodeDer$1(y[1],{offset:0});return{kty:"RSA",n:toString$1(u[0],"base64url"),e:toString$1(u[1],"base64url")}}function jwkToPkix$1(y){if(y.n==null||y.e==null)throw new InvalidParametersError$1("JWK was missing components");return encodeSequence$1([RSA_ALGORITHM_IDENTIFIER$1,encodeBitString$1(encodeSequence$1([encodeInteger$1(fromString(y.n,"base64url")),encodeInteger$1(fromString(y.e,"base64url"))]))]).subarray()}function pkixToRSAPublicKey(y,u){if(y.byteLength>=MAX_RSA_JWK_SIZE)throw new InvalidPublicKeyError("Key size is too large");const h=decodeDer$1(y,{offset:0});return pkixMessageToRSAPublicKey$1(h,y,u)}function pkixMessageToRSAPublicKey$1(y,u,h){const b=pkixMessageToJwk$1(y);if(h==null){const v=sha256$2(PublicKey$2.encode({Type:KeyType$1.RSA,Data:u}));h=create$2(SHA2_256_CODE$1,v)}return new RSAPublicKey$2(b,h)}async function hashAndVerify$5(y,u,h,b){var _,E;const v=await webcrypto$1.get().subtle.importKey("jwk",y,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);(_=b==null?void 0:b.signal)==null||_.throwIfAborted();const w=await webcrypto$1.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},v,u,h instanceof Uint8Array?h:h.subarray());return(E=b==null?void 0:b.signal)==null||E.throwIfAborted(),w}class HMAC extends Hash$8{constructor(u,h){super(),this.finished=!1,this.destroyed=!1,ahash(u);const b=toBytes$1(h);if(this.iHash=u.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;const v=this.blockLen,w=new Uint8Array(v);w.set(b.length>v?u.create().update(b).digest():b);for(let _=0;_<w.length;_++)w[_]^=54;this.iHash.update(w),this.oHash=u.create();for(let _=0;_<w.length;_++)w[_]^=106;this.oHash.update(w),clean$1(w)}update(u){return aexists$1(this),this.iHash.update(u),this}digestInto(u){aexists$1(this),abytes$2(u,this.outputLen),this.finished=!0,this.iHash.digestInto(u),this.oHash.update(u),this.oHash.digestInto(u),this.destroy()}digest(){const u=new Uint8Array(this.oHash.outputLen);return this.digestInto(u),u}_cloneInto(u){u||(u=Object.create(Object.getPrototypeOf(this),{}));const{oHash:h,iHash:b,finished:v,destroyed:w,blockLen:_,outputLen:E}=this;return u=u,u.finished=v,u.destroyed=w,u.blockLen=_,u.outputLen=E,u.oHash=h._cloneInto(u.oHash),u.iHash=b._cloneInto(u.iHash),u}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac$1=(y,u,h)=>new HMAC(y,u).update(h).digest();hmac$1.create=(y,u)=>new HMAC(y,u);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const divNearest$1=(y,u)=>(y+(y>=0?u:-u)/_2n$2)/u;function _splitEndoScalar(y,u,h){const[[b,v],[w,_]]=u,E=divNearest$1(_*y,h),S=divNearest$1(-v*y,h);let x=y-E*b-S*w,T=-E*v-S*_;const C=x<_0n$1,O=T<_0n$1;C&&(x=-x),O&&(T=-T);const D=bitMask(Math.ceil(bitLen(h)/2))+_1n$1;if(x<_0n$1||x>=D||T<_0n$1||T>=D)throw new Error("splitScalar (endomorphism): failed, k="+y);return{k1neg:C,k1:x,k2neg:O,k2:T}}function validateSigFormat(y){if(!["compact","recovered","der"].includes(y))throw new Error('Signature format must be "compact", "recovered", or "der"');return y}function validateSigOpts(y,u){const h={};for(let b of Object.keys(u))h[b]=y[b]===void 0?u[b]:y[b];return _abool2(h.lowS,"lowS"),_abool2(h.prehash,"prehash"),h.format!==void 0&&validateSigFormat(h.format),h}class DERErr extends Error{constructor(u=""){super(u)}}const DER={Err:DERErr,_tlv:{encode:(y,u)=>{const{Err:h}=DER;if(y<0||y>256)throw new h("tlv.encode: wrong tag");if(u.length&1)throw new h("tlv.encode: unpadded data");const b=u.length/2,v=numberToHexUnpadded$1(b);if(v.length/2&128)throw new h("tlv.encode: long form length too big");const w=b>127?numberToHexUnpadded$1(v.length/2|128):"";return numberToHexUnpadded$1(y)+w+v+u},decode(y,u){const{Err:h}=DER;let b=0;if(y<0||y>256)throw new h("tlv.encode: wrong tag");if(u.length<2||u[b++]!==y)throw new h("tlv.decode: wrong tlv");const v=u[b++],w=!!(v&128);let _=0;if(!w)_=v;else{const S=v&127;if(!S)throw new h("tlv.decode(long): indefinite length not supported");if(S>4)throw new h("tlv.decode(long): byte length is too big");const x=u.subarray(b,b+S);if(x.length!==S)throw new h("tlv.decode: length bytes not complete");if(x[0]===0)throw new h("tlv.decode(long): zero leftmost byte");for(const T of x)_=_<<8|T;if(b+=S,_<128)throw new h("tlv.decode(long): not minimal encoding")}const E=u.subarray(b,b+_);if(E.length!==_)throw new h("tlv.decode: wrong value length");return{v:E,l:u.subarray(b+_)}}},_int:{encode(y){const{Err:u}=DER;if(y<_0n$1)throw new u("integer: negative integers are not allowed");let h=numberToHexUnpadded$1(y);if(Number.parseInt(h[0],16)&8&&(h="00"+h),h.length&1)throw new u("unexpected DER parsing assertion: unpadded hex");return h},decode(y){const{Err:u}=DER;if(y[0]&128)throw new u("invalid signature integer: negative");if(y[0]===0&&!(y[1]&128))throw new u("invalid signature integer: unnecessary leading zero");return bytesToNumberBE(y)}},toSig(y){const{Err:u,_int:h,_tlv:b}=DER,v=ensureBytes$1("signature",y),{v:w,l:_}=b.decode(48,v);if(_.length)throw new u("invalid signature: left bytes after parsing");const{v:E,l:S}=b.decode(2,w),{v:x,l:T}=b.decode(2,S);if(T.length)throw new u("invalid signature: left bytes after parsing");return{r:h.decode(E),s:h.decode(x)}},hexFromSig(y){const{_tlv:u,_int:h}=DER,b=u.encode(2,h.encode(y.r)),v=u.encode(2,h.encode(y.s)),w=b+v;return u.encode(48,w)}},_0n$1=BigInt(0),_1n$1=BigInt(1),_2n$2=BigInt(2),_3n$1=BigInt(3),_4n=BigInt(4);function _normFnElement(y,u){const{BYTES:h}=y;let b;if(typeof u=="bigint")b=u;else{let v=ensureBytes$1("private key",u);try{b=y.fromBytes(v)}catch{throw new Error(`invalid private key: expected ui8a of size ${h}, got ${typeof u}`)}}if(!y.isValidNot0(b))throw new Error("invalid private key: out of range [1..N-1]");return b}function weierstrassN(y,u={}){const h=_createCurveFields("weierstrass",y,u),{Fp:b,Fn:v}=h;let w=h.CURVE;const{h:_,n:E}=w;_validateObject(u,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:S}=u;if(S&&(!b.is0(w.a)||typeof S.beta!="bigint"||!Array.isArray(S.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const x=getWLengths(b,v);function T(){if(!b.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function C(B,F,M){const{x:N,y:Q}=F.toAffine(),j=b.toBytes(N);if(_abool2(M,"isCompressed"),M){T();const ne=!b.isOdd(Q);return concatBytes$1(pprefix(ne),j)}else return concatBytes$1(Uint8Array.of(4),j,b.toBytes(Q))}function O(B){_abytes2(B,void 0,"Point");const{publicKey:F,publicKeyUncompressed:M}=x,N=B.length,Q=B[0],j=B.subarray(1);if(N===F&&(Q===2||Q===3)){const ne=b.fromBytes(j);if(!b.isValid(ne))throw new Error("bad point: is not on curve, wrong x");const J=te(ne);let q;try{q=b.sqrt(J)}catch(he){const Oe=he instanceof Error?": "+he.message:"";throw new Error("bad point: is not on curve, sqrt error"+Oe)}T();const re=b.isOdd(q);return(Q&1)===1!==re&&(q=b.neg(q)),{x:ne,y:q}}else if(N===M&&Q===4){const ne=b.BYTES,J=b.fromBytes(j.subarray(0,ne)),q=b.fromBytes(j.subarray(ne,ne*2));if(!X(J,q))throw new Error("bad point: is not on curve");return{x:J,y:q}}else throw new Error(`bad point: got length ${N}, expected compressed=${F} or uncompressed=${M}`)}const D=u.toBytes||C,U=u.fromBytes||O;function te(B){const F=b.sqr(B),M=b.mul(F,B);return b.add(b.add(M,b.mul(B,w.a)),w.b)}function X(B,F){const M=b.sqr(F),N=te(B);return b.eql(M,N)}if(!X(w.Gx,w.Gy))throw new Error("bad curve params: generator point");const ie=b.mul(b.pow(w.a,_3n$1),_4n),ee=b.mul(b.sqr(w.b),BigInt(27));if(b.is0(b.add(ie,ee)))throw new Error("bad curve params: a or b");function ae(B,F,M=!1){if(!b.isValid(F)||M&&b.is0(F))throw new Error(`bad point coordinate ${B}`);return F}function de(B){if(!(B instanceof Ee))throw new Error("ProjectivePoint expected")}function Se(B){if(!S||!S.basises)throw new Error("no endo");return _splitEndoScalar(B,S.basises,v.ORDER)}const ve=memoized((B,F)=>{const{X:M,Y:N,Z:Q}=B;if(b.eql(Q,b.ONE))return{x:M,y:N};const j=B.is0();F==null&&(F=j?b.ONE:b.inv(Q));const ne=b.mul(M,F),J=b.mul(N,F),q=b.mul(Q,F);if(j)return{x:b.ZERO,y:b.ZERO};if(!b.eql(q,b.ONE))throw new Error("invZ was invalid");return{x:ne,y:J}}),Pe=memoized(B=>{if(B.is0()){if(u.allowInfinityPoint&&!b.is0(B.Y))return;throw new Error("bad point: ZERO")}const{x:F,y:M}=B.toAffine();if(!b.isValid(F)||!b.isValid(M))throw new Error("bad point: x or y not field elements");if(!X(F,M))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Ie(B,F,M,N,Q){return M=new Ee(b.mul(M.X,B),M.Y,M.Z),F=negateCt(N,F),M=negateCt(Q,M),F.add(M)}class Ee{constructor(F,M,N){this.X=ae("x",F),this.Y=ae("y",M,!0),this.Z=ae("z",N),Object.freeze(this)}static CURVE(){return w}static fromAffine(F){const{x:M,y:N}=F||{};if(!F||!b.isValid(M)||!b.isValid(N))throw new Error("invalid affine point");if(F instanceof Ee)throw new Error("projective point not allowed");return b.is0(M)&&b.is0(N)?Ee.ZERO:new Ee(M,N,b.ONE)}static fromBytes(F){const M=Ee.fromAffine(U(_abytes2(F,void 0,"point")));return M.assertValidity(),M}static fromHex(F){return Ee.fromBytes(ensureBytes$1("pointHex",F))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(F=8,M=!0){return be.createCache(this,F),M||this.multiply(_3n$1),this}assertValidity(){Pe(this)}hasEvenY(){const{y:F}=this.toAffine();if(!b.isOdd)throw new Error("Field doesn't support isOdd");return!b.isOdd(F)}equals(F){de(F);const{X:M,Y:N,Z:Q}=this,{X:j,Y:ne,Z:J}=F,q=b.eql(b.mul(M,J),b.mul(j,Q)),re=b.eql(b.mul(N,J),b.mul(ne,Q));return q&&re}negate(){return new Ee(this.X,b.neg(this.Y),this.Z)}double(){const{a:F,b:M}=w,N=b.mul(M,_3n$1),{X:Q,Y:j,Z:ne}=this;let J=b.ZERO,q=b.ZERO,re=b.ZERO,H=b.mul(Q,Q),he=b.mul(j,j),Oe=b.mul(ne,ne),Ne=b.mul(Q,j);return Ne=b.add(Ne,Ne),re=b.mul(Q,ne),re=b.add(re,re),J=b.mul(F,re),q=b.mul(N,Oe),q=b.add(J,q),J=b.sub(he,q),q=b.add(he,q),q=b.mul(J,q),J=b.mul(Ne,J),re=b.mul(N,re),Oe=b.mul(F,Oe),Ne=b.sub(H,Oe),Ne=b.mul(F,Ne),Ne=b.add(Ne,re),re=b.add(H,H),H=b.add(re,H),H=b.add(H,Oe),H=b.mul(H,Ne),q=b.add(q,H),Oe=b.mul(j,ne),Oe=b.add(Oe,Oe),H=b.mul(Oe,Ne),J=b.sub(J,H),re=b.mul(Oe,he),re=b.add(re,re),re=b.add(re,re),new Ee(J,q,re)}add(F){de(F);const{X:M,Y:N,Z:Q}=this,{X:j,Y:ne,Z:J}=F;let q=b.ZERO,re=b.ZERO,H=b.ZERO;const he=w.a,Oe=b.mul(w.b,_3n$1);let Ne=b.mul(M,j),Ae=b.mul(N,ne),le=b.mul(Q,J),me=b.add(M,N),Me=b.add(j,ne);me=b.mul(me,Me),Me=b.add(Ne,Ae),me=b.sub(me,Me),Me=b.add(M,Q);let fe=b.add(j,J);return Me=b.mul(Me,fe),fe=b.add(Ne,le),Me=b.sub(Me,fe),fe=b.add(N,Q),q=b.add(ne,J),fe=b.mul(fe,q),q=b.add(Ae,le),fe=b.sub(fe,q),H=b.mul(he,Me),q=b.mul(Oe,le),H=b.add(q,H),q=b.sub(Ae,H),H=b.add(Ae,H),re=b.mul(q,H),Ae=b.add(Ne,Ne),Ae=b.add(Ae,Ne),le=b.mul(he,le),Me=b.mul(Oe,Me),Ae=b.add(Ae,le),le=b.sub(Ne,le),le=b.mul(he,le),Me=b.add(Me,le),Ne=b.mul(Ae,Me),re=b.add(re,Ne),Ne=b.mul(fe,Me),q=b.mul(me,q),q=b.sub(q,Ne),Ne=b.mul(me,Ae),H=b.mul(fe,H),H=b.add(H,Ne),new Ee(q,re,H)}subtract(F){return this.add(F.negate())}is0(){return this.equals(Ee.ZERO)}multiply(F){const{endo:M}=u;if(!v.isValidNot0(F))throw new Error("invalid scalar: out of range");let N,Q;const j=ne=>be.cached(this,ne,J=>normalizeZ(Ee,J));if(M){const{k1neg:ne,k1:J,k2neg:q,k2:re}=Se(F),{p:H,f:he}=j(J),{p:Oe,f:Ne}=j(re);Q=he.add(Ne),N=Ie(M.beta,H,Oe,ne,q)}else{const{p:ne,f:J}=j(F);N=ne,Q=J}return normalizeZ(Ee,[N,Q])[0]}multiplyUnsafe(F){const{endo:M}=u,N=this;if(!v.isValid(F))throw new Error("invalid scalar: out of range");if(F===_0n$1||N.is0())return Ee.ZERO;if(F===_1n$1)return N;if(be.hasCache(this))return this.multiply(F);if(M){const{k1neg:Q,k1:j,k2neg:ne,k2:J}=Se(F),{p1:q,p2:re}=mulEndoUnsafe(Ee,N,j,J);return Ie(M.beta,q,re,Q,ne)}else return be.unsafe(N,F)}multiplyAndAddUnsafe(F,M,N){const Q=this.multiplyUnsafe(M).add(F.multiplyUnsafe(N));return Q.is0()?void 0:Q}toAffine(F){return ve(this,F)}isTorsionFree(){const{isTorsionFree:F}=u;return _===_1n$1?!0:F?F(Ee,this):be.unsafe(this,E).is0()}clearCofactor(){const{clearCofactor:F}=u;return _===_1n$1?this:F?F(Ee,this):this.multiplyUnsafe(_)}isSmallOrder(){return this.multiplyUnsafe(_).is0()}toBytes(F=!0){return _abool2(F,"isCompressed"),this.assertValidity(),D(Ee,this,F)}toHex(F=!0){return bytesToHex$2(this.toBytes(F))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(F=!0){return this.toBytes(F)}_setWindowSize(F){this.precompute(F)}static normalizeZ(F){return normalizeZ(Ee,F)}static msm(F,M){return pippenger(Ee,v,F,M)}static fromPrivateKey(F){return Ee.BASE.multiply(_normFnElement(v,F))}}Ee.BASE=new Ee(w.Gx,w.Gy,b.ONE),Ee.ZERO=new Ee(b.ZERO,b.ONE,b.ZERO),Ee.Fp=b,Ee.Fn=v;const De=v.BITS,be=new wNAF(Ee,u.endo?Math.ceil(De/2):De);return Ee.BASE.precompute(8),Ee}function pprefix(y){return Uint8Array.of(y?2:3)}function getWLengths(y,u){return{secretKey:u.BYTES,publicKey:1+y.BYTES,publicKeyUncompressed:1+2*y.BYTES,publicKeyHasPrefix:!0,signature:2*u.BYTES}}function ecdh(y,u={}){const{Fn:h}=y,b=u.randomBytes||randomBytes$4,v=Object.assign(getWLengths(y.Fp,h),{seed:getMinHashLength(h.ORDER)});function w(D){try{return!!_normFnElement(h,D)}catch{return!1}}function _(D,U){const{publicKey:te,publicKeyUncompressed:X}=v;try{const ie=D.length;return U===!0&&ie!==te||U===!1&&ie!==X?!1:!!y.fromBytes(D)}catch{return!1}}function E(D=b(v.seed)){return mapHashToField(_abytes2(D,v.seed,"seed"),h.ORDER)}function S(D,U=!0){return y.BASE.multiply(_normFnElement(h,D)).toBytes(U)}function x(D){const U=E(D);return{secretKey:U,publicKey:S(U)}}function T(D){if(typeof D=="bigint")return!1;if(D instanceof y)return!0;const{secretKey:U,publicKey:te,publicKeyUncompressed:X}=v;if(h.allowedLengths||U===te)return;const ie=ensureBytes$1("key",D).length;return ie===te||ie===X}function C(D,U,te=!0){if(T(D)===!0)throw new Error("first arg must be private key");if(T(U)===!1)throw new Error("second arg must be public key");const X=_normFnElement(h,D);return y.fromHex(U).multiply(X).toBytes(te)}return Object.freeze({getPublicKey:S,getSharedSecret:C,keygen:x,Point:y,utils:{isValidSecretKey:w,isValidPublicKey:_,randomSecretKey:E,isValidPrivateKey:w,randomPrivateKey:E,normPrivateKeyToScalar:D=>_normFnElement(h,D),precompute(D=8,U=y.BASE){return U.precompute(D,!1)}},lengths:v})}function ecdsa(y,u,h={}){ahash(u),_validateObject(h,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const b=h.randomBytes||randomBytes$4,v=h.hmac||((M,...N)=>hmac$1(u,M,concatBytes$1(...N))),{Fp:w,Fn:_}=y,{ORDER:E,BITS:S}=_,{keygen:x,getPublicKey:T,getSharedSecret:C,utils:O,lengths:D}=ecdh(y,h),U={prehash:!1,lowS:typeof h.lowS=="boolean"?h.lowS:!1,format:void 0,extraEntropy:!1},te="compact";function X(M){const N=E>>_1n$1;return M>N}function ie(M,N){if(!_.isValidNot0(N))throw new Error(`invalid signature ${M}: out of range 1..Point.Fn.ORDER`);return N}function ee(M,N){validateSigFormat(N);const Q=D.signature,j=N==="compact"?Q:N==="recovered"?Q+1:void 0;return _abytes2(M,j,`${N} signature`)}class ae{constructor(N,Q,j){this.r=ie("r",N),this.s=ie("s",Q),j!=null&&(this.recovery=j),Object.freeze(this)}static fromBytes(N,Q=te){ee(N,Q);let j;if(Q==="der"){const{r:re,s:H}=DER.toSig(_abytes2(N));return new ae(re,H)}Q==="recovered"&&(j=N[0],Q="compact",N=N.subarray(1));const ne=_.BYTES,J=N.subarray(0,ne),q=N.subarray(ne,ne*2);return new ae(_.fromBytes(J),_.fromBytes(q),j)}static fromHex(N,Q){return this.fromBytes(hexToBytes$2(N),Q)}addRecoveryBit(N){return new ae(this.r,this.s,N)}recoverPublicKey(N){const Q=w.ORDER,{r:j,s:ne,recovery:J}=this;if(J==null||![0,1,2,3].includes(J))throw new Error("recovery id invalid");if(E*_2n$2<Q&&J>1)throw new Error("recovery id is ambiguous for h>1 curve");const re=J===2||J===3?j+E:j;if(!w.isValid(re))throw new Error("recovery id 2 or 3 invalid");const H=w.toBytes(re),he=y.fromBytes(concatBytes$1(pprefix((J&1)===0),H)),Oe=_.inv(re),Ne=Se(ensureBytes$1("msgHash",N)),Ae=_.create(-Ne*Oe),le=_.create(ne*Oe),me=y.BASE.multiplyUnsafe(Ae).add(he.multiplyUnsafe(le));if(me.is0())throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return X(this.s)}toBytes(N=te){if(validateSigFormat(N),N==="der")return hexToBytes$2(DER.hexFromSig(this));const Q=_.toBytes(this.r),j=_.toBytes(this.s);if(N==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return concatBytes$1(Uint8Array.of(this.recovery),Q,j)}return concatBytes$1(Q,j)}toHex(N){return bytesToHex$2(this.toBytes(N))}assertValidity(){}static fromCompact(N){return ae.fromBytes(ensureBytes$1("sig",N),"compact")}static fromDER(N){return ae.fromBytes(ensureBytes$1("sig",N),"der")}normalizeS(){return this.hasHighS()?new ae(this.r,_.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return bytesToHex$2(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return bytesToHex$2(this.toBytes("compact"))}}const de=h.bits2int||function(N){if(N.length>8192)throw new Error("input is too large");const Q=bytesToNumberBE(N),j=N.length*8-S;return j>0?Q>>BigInt(j):Q},Se=h.bits2int_modN||function(N){return _.create(de(N))},ve=bitMask(S);function Pe(M){return aInRange("num < 2^"+S,M,_0n$1,ve),_.toBytes(M)}function Ie(M,N){return _abytes2(M,void 0,"message"),N?_abytes2(u(M),void 0,"prehashed message"):M}function Ee(M,N,Q){if(["recovered","canonical"].some(Ae=>Ae in Q))throw new Error("sign() legacy options not supported");const{lowS:j,prehash:ne,extraEntropy:J}=validateSigOpts(Q,U);M=Ie(M,ne);const q=Se(M),re=_normFnElement(_,N),H=[Pe(re),Pe(q)];if(J!=null&&J!==!1){const Ae=J===!0?b(D.secretKey):J;H.push(ensureBytes$1("extraEntropy",Ae))}const he=concatBytes$1(...H),Oe=q;function Ne(Ae){const le=de(Ae);if(!_.isValidNot0(le))return;const me=_.inv(le),Me=y.BASE.multiply(le).toAffine(),fe=_.create(Me.x);if(fe===_0n$1)return;const ge=_.create(me*_.create(Oe+fe*re));if(ge===_0n$1)return;let ce=(Me.x===fe?0:2)|Number(Me.y&_1n$1),_e=ge;return j&&X(ge)&&(_e=_.neg(ge),ce^=1),new ae(fe,_e,ce)}return{seed:he,k2sig:Ne}}function De(M,N,Q={}){M=ensureBytes$1("message",M);const{seed:j,k2sig:ne}=Ee(M,N,Q);return createHmacDrbg(u.outputLen,_.BYTES,v)(j,ne)}function be(M){let N;const Q=typeof M=="string"||isBytes$3(M),j=!Q&&M!==null&&typeof M=="object"&&typeof M.r=="bigint"&&typeof M.s=="bigint";if(!Q&&!j)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(j)N=new ae(M.r,M.s);else if(Q){try{N=ae.fromBytes(ensureBytes$1("sig",M),"der")}catch(ne){if(!(ne instanceof DER.Err))throw ne}if(!N)try{N=ae.fromBytes(ensureBytes$1("sig",M),"compact")}catch{return!1}}return N||!1}function B(M,N,Q,j={}){const{lowS:ne,prehash:J,format:q}=validateSigOpts(j,U);if(Q=ensureBytes$1("publicKey",Q),N=Ie(ensureBytes$1("message",N),J),"strict"in j)throw new Error("options.strict was renamed to lowS");const re=q===void 0?be(M):ae.fromBytes(ensureBytes$1("sig",M),q);if(re===!1)return!1;try{const H=y.fromBytes(Q);if(ne&&re.hasHighS())return!1;const{r:he,s:Oe}=re,Ne=Se(N),Ae=_.inv(Oe),le=_.create(Ne*Ae),me=_.create(he*Ae),Me=y.BASE.multiplyUnsafe(le).add(H.multiplyUnsafe(me));return Me.is0()?!1:_.create(Me.x)===he}catch{return!1}}function F(M,N,Q={}){const{prehash:j}=validateSigOpts(Q,U);return N=Ie(N,j),ae.fromBytes(M,"recovered").recoverPublicKey(N).toBytes()}return Object.freeze({keygen:x,getPublicKey:T,getSharedSecret:C,utils:O,lengths:D,Point:y,sign:De,verify:B,recoverPublicKey:F,Signature:ae,hash:u})}function _weierstrass_legacy_opts_to_new(y){const u={a:y.a,b:y.b,p:y.Fp.ORDER,n:y.n,h:y.h,Gx:y.Gx,Gy:y.Gy},h=y.Fp;let b=y.allowedPrivateKeyLengths?Array.from(new Set(y.allowedPrivateKeyLengths.map(_=>Math.ceil(_/2)))):void 0;const v=Field$1(u.n,{BITS:y.nBitLength,allowedLengths:b,modFromBytes:y.wrapPrivateKey}),w={Fp:h,Fn:v,allowInfinityPoint:y.allowInfinityPoint,endo:y.endo,isTorsionFree:y.isTorsionFree,clearCofactor:y.clearCofactor,fromBytes:y.fromBytes,toBytes:y.toBytes};return{CURVE:u,curveOpts:w}}function _ecdsa_legacy_opts_to_new(y){const{CURVE:u,curveOpts:h}=_weierstrass_legacy_opts_to_new(y),b={hmac:y.hmac,randomBytes:y.randomBytes,lowS:y.lowS,bits2int:y.bits2int,bits2int_modN:y.bits2int_modN};return{CURVE:u,curveOpts:h,hash:y.hash,ecdsaOpts:b}}function _ecdsa_new_output_to_legacy(y,u){const h=u.Point;return Object.assign({},u,{ProjectivePoint:h,CURVE:Object.assign({},y,nLength(h.Fn.ORDER,h.Fn.BITS))})}function weierstrass$1(y){const{CURVE:u,curveOpts:h,hash:b,ecdsaOpts:v}=_ecdsa_legacy_opts_to_new(y),w=weierstrassN(u,h),_=ecdsa(w,b,v);return _ecdsa_new_output_to_legacy(y,_)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function createCurve(y,u){const h=b=>weierstrass$1({...y,hash:b});return{...h(u),create:h}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},secp256k1_ENDO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},_2n$1=BigInt(2);function sqrtMod$1(y){const u=secp256k1_CURVE.p,h=BigInt(3),b=BigInt(6),v=BigInt(11),w=BigInt(22),_=BigInt(23),E=BigInt(44),S=BigInt(88),x=y*y*y%u,T=x*x*y%u,C=pow2$1(T,h,u)*T%u,O=pow2$1(C,h,u)*T%u,D=pow2$1(O,_2n$1,u)*x%u,U=pow2$1(D,v,u)*D%u,te=pow2$1(U,w,u)*U%u,X=pow2$1(te,E,u)*te%u,ie=pow2$1(X,S,u)*X%u,ee=pow2$1(ie,E,u)*te%u,ae=pow2$1(ee,h,u)*T%u,de=pow2$1(ae,_,u)*U%u,Se=pow2$1(de,b,u)*x%u,ve=pow2$1(Se,_2n$1,u);if(!Fpk1.eql(Fpk1.sqr(ve),y))throw new Error("Cannot find square root");return ve}const Fpk1=Field$1(secp256k1_CURVE.p,{sqrt:sqrtMod$1}),secp256k1$1=createCurve({...secp256k1_CURVE,Fp:Fpk1,lowS:!0,endo:secp256k1_ENDO},sha256$3);function hashAndVerify$4(y,u,h,b){var w;const v=sha256$4.digest(h instanceof Uint8Array?h:h.subarray());if(isPromise$3(v))return v.then(({digest:_})=>{var E;return(E=b==null?void 0:b.signal)==null||E.throwIfAborted(),secp256k1$1.verify(u,_,y)}).catch(_=>{throw _.name==="AbortError"?_:new VerificationError$1(String(_))});try{return(w=b==null?void 0:b.signal)==null||w.throwIfAborted(),secp256k1$1.verify(u,v.digest,y)}catch(_){throw new VerificationError$1(String(_))}}let Secp256k1PublicKey$1=class{constructor(u){Z(this,"type","secp256k1");Z(this,"raw");Z(this,"_key");this._key=validateSecp256k1PublicKey$1(u),this.raw=compressSecp256k1PublicKey$1(this._key)}toMultihash(){return identity.digest(publicKeyToProtobuf$1(this))}toCID(){return CID.createV1(114,this.toMultihash())}toString(){return base58btc.encode(this.toMultihash().bytes).substring(1)}equals(u){return u==null||!(u.raw instanceof Uint8Array)?!1:equals(this.raw,u.raw)}verify(u,h,b){return hashAndVerify$4(this._key,h,u,b)}};function unmarshalSecp256k1PublicKey$1(y){return new Secp256k1PublicKey$1(y)}function compressSecp256k1PublicKey$1(y){return secp256k1$1.ProjectivePoint.fromHex(y).toRawBytes(!0)}function validateSecp256k1PublicKey$1(y){try{return secp256k1$1.ProjectivePoint.fromHex(y),y}catch(u){throw new InvalidPublicKeyError(String(u))}}async function generateKeyPair(y,u){return generateEd25519KeyPair()}function publicKeyFromProtobuf(y,u){const{Type:h,Data:b}=PublicKey$2.decode(y),v=b??new Uint8Array;switch(h){case KeyType$1.RSA:return pkixToRSAPublicKey(v,u);case KeyType$1.Ed25519:return unmarshalEd25519PublicKey$1(v);case KeyType$1.secp256k1:return unmarshalSecp256k1PublicKey$1(v);case KeyType$1.ECDSA:return unmarshalECDSAPublicKey(v);default:throw new UnsupportedKeyTypeError}}function publicKeyFromMultihash(y){const{Type:u,Data:h}=PublicKey$2.decode(y.digest),b=h??new Uint8Array;switch(u){case KeyType$1.Ed25519:return unmarshalEd25519PublicKey$1(b);case KeyType$1.secp256k1:return unmarshalSecp256k1PublicKey$1(b);case KeyType$1.ECDSA:return unmarshalECDSAPublicKey(b);default:throw new UnsupportedKeyTypeError}}function publicKeyToProtobuf$1(y){return PublicKey$2.encode({Type:KeyType$1[y.type],Data:y.raw})}const inspect$2=Symbol.for("nodejs.util.inspect.custom"),LIBP2P_KEY_CODE$2=114;var Wd;let PeerIdImpl$1=class{constructor(u){Z(this,"type");Z(this,"multihash");Z(this,"publicKey");Z(this,"string");Z(this,Wd,!0);this.type=u.type,this.multihash=u.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}toString(){return this.string==null&&(this.string=base58btc.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return CID.createV1(LIBP2P_KEY_CODE$2,this.multihash)}toJSON(){return this.toString()}equals(u){var h;if(u==null)return!1;if(u instanceof Uint8Array)return equals(this.multihash.bytes,u);if(typeof u=="string")return this.toString()===u;if(((h=u==null?void 0:u.toMultihash())==null?void 0:h.bytes)!=null)return equals(this.multihash.bytes,u.toMultihash().bytes);throw new Error("not valid Id")}[(Wd=peerIdSymbol,inspect$2)](){return`PeerId(${this.toString()})`}},RSAPeerId$1=class extends PeerIdImpl$1{constructor(h){super({...h,type:"RSA"});Z(this,"type","RSA");Z(this,"publicKey");this.publicKey=h.publicKey}},Ed25519PeerId$1=class extends PeerIdImpl$1{constructor(h){super({...h,type:"Ed25519"});Z(this,"type","Ed25519");Z(this,"publicKey");this.publicKey=h.publicKey}},Secp256k1PeerId$1=class extends PeerIdImpl$1{constructor(h){super({...h,type:"secp256k1"});Z(this,"type","secp256k1");Z(this,"publicKey");this.publicKey=h.publicKey}};const TRANSPORT_IPFS_GATEWAY_HTTP_CODE$1=2336;var Gd,jd;class URLPeerId{constructor(u){Z(this,"type","url");Z(this,"multihash");Z(this,"publicKey");Z(this,"url");Z(this,Gd,!0);this.url=u.toString(),this.multihash=identity.digest(fromString(this.url))}[(jd=inspect$2,Gd=peerIdSymbol,jd)](){return`PeerId(${this.url})`}toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE$1,this.toMultihash())}toJSON(){return this.toString()}equals(u){return u==null?!1:(u instanceof Uint8Array&&(u=toString$1(u)),u.toString()===this.toString())}}const LIBP2P_KEY_CODE$1=114,TRANSPORT_IPFS_GATEWAY_HTTP_CODE=2336;function peerIdFromString$1(y,u){let h;if(y.charAt(0)==="1"||y.charAt(0)==="Q")h=decode$3(base58btc.decode(`z${y}`));else{if(y.startsWith("k51qzi5uqu5")||y.startsWith("kzwfwjn5ji4")||y.startsWith("k2k4r8")||y.startsWith("bafz"))return peerIdFromCID(CID.parse(y));throw new InvalidParametersError$2('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return peerIdFromMultihash(h)}function peerIdFromPublicKey$1(y){if(y.type==="Ed25519")return new Ed25519PeerId$1({multihash:y.toCID().multihash,publicKey:y});if(y.type==="secp256k1")return new Secp256k1PeerId$1({multihash:y.toCID().multihash,publicKey:y});if(y.type==="RSA")return new RSAPeerId$1({multihash:y.toCID().multihash,publicKey:y});throw new UnsupportedKeyTypeError$1}function peerIdFromPrivateKey(y){return peerIdFromPublicKey$1(y.publicKey)}function peerIdFromMultihash(y){if(isSha256Multihash(y))return new RSAPeerId$1({multihash:y});if(isIdentityMultihash(y))try{const u=publicKeyFromMultihash(y);if(u.type==="Ed25519")return new Ed25519PeerId$1({multihash:y,publicKey:u});if(u.type==="secp256k1")return new Secp256k1PeerId$1({multihash:y,publicKey:u})}catch{const h=toString$1(y.digest);return new URLPeerId(new URL(h))}throw new InvalidMultihashError("Supplied PeerID Multihash is invalid")}function peerIdFromCID(y){if((y==null?void 0:y.multihash)==null||y.version==null||y.version===1&&y.code!==LIBP2P_KEY_CODE$1&&y.code!==TRANSPORT_IPFS_GATEWAY_HTTP_CODE)throw new InvalidCIDError("Supplied PeerID CID is invalid");if(y.code===TRANSPORT_IPFS_GATEWAY_HTTP_CODE){const u=toString$1(y.multihash.digest);return new URLPeerId(new URL(u))}return peerIdFromMultihash(y.multihash)}function isIdentityMultihash(y){return y.code===identity.code}function isSha256Multihash(y){return y.code===sha256$4.code}class InvalidMultiaddrError extends Error{constructor(){super(...arguments);Z(this,"name","InvalidMultiaddrError")}}Z(InvalidMultiaddrError,"name","InvalidMultiaddrError");class ValidationError extends Error{constructor(){super(...arguments);Z(this,"name","ValidationError")}}Z(ValidationError,"name","ValidationError");class InvalidParametersError extends Error{constructor(){super(...arguments);Z(this,"name","InvalidParametersError")}}Z(InvalidParametersError,"name","InvalidParametersError");class UnknownProtocolError extends Error{constructor(){super(...arguments);Z(this,"name","UnknownProtocolError")}}Z(UnknownProtocolError,"name","UnknownProtocolError");class Parser{constructor(){Z(this,"index",0);Z(this,"input","")}new(u){return this.index=0,this.input=u,this}readAtomically(u){const h=this.index,b=u();return b===void 0&&(this.index=h),b}parseWith(u){const h=u();if(this.index===this.input.length)return h}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(u){return this.readAtomically(()=>{const h=this.readChar();if(h===u)return h})}readSeparator(u,h,b){return this.readAtomically(()=>{if(!(h>0&&this.readGivenChar(u)===void 0))return b()})}readNumber(u,h,b,v){return this.readAtomically(()=>{let w=0,_=0;const E=this.peekChar();if(E===void 0)return;const S=E==="0",x=2**(8*v)-1;for(;;){const T=this.readAtomically(()=>{const C=this.readChar();if(C===void 0)return;const O=Number.parseInt(C,u);if(!Number.isNaN(O))return O});if(T===void 0)break;if(w*=u,w+=T,w>x||(_+=1,h!==void 0&&_>h))return}if(_!==0)return!b&&S&&_>1?void 0:w})}readIPv4Addr(){return this.readAtomically(()=>{const u=new Uint8Array(4);for(let h=0;h<u.length;h++){const b=this.readSeparator(".",h,()=>this.readNumber(10,3,!1,1));if(b===void 0)return;u[h]=b}return u})}readIPv6Addr(){const u=h=>{for(let b=0;b<h.length/2;b++){const v=b*2;if(b<h.length-3){const _=this.readSeparator(":",b,()=>this.readIPv4Addr());if(_!==void 0)return h[v]=_[0],h[v+1]=_[1],h[v+2]=_[2],h[v+3]=_[3],[v+4,!0]}const w=this.readSeparator(":",b,()=>this.readNumber(16,4,!0,2));if(w===void 0)return[v,!1];h[v]=w>>8,h[v+1]=w&255}return[h.length,!1]};return this.readAtomically(()=>{const h=new Uint8Array(16),[b,v]=u(h);if(b===16)return h;if(v||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;const w=new Uint8Array(14),_=16-(b+2),[E]=u(w.subarray(0,_));return h.set(w.subarray(0,E),16-E),h})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}}const MAX_IPV6_LENGTH=45,MAX_IPV4_LENGTH=15,parser=new Parser;function parseIPv4(y){if(!(y.length>MAX_IPV4_LENGTH))return parser.new(y).parseWith(()=>parser.readIPv4Addr())}function parseIPv6(y){if(y.includes("%")&&(y=y.split("%")[0]),!(y.length>MAX_IPV6_LENGTH))return parser.new(y).parseWith(()=>parser.readIPv6Addr())}function parseIP(y,u=!1){if(y.includes("%")&&(y=y.split("%")[0]),y.length>MAX_IPV6_LENGTH)return;const h=parser.new(y).parseWith(()=>parser.readIPAddr());if(h)return u&&h.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,h[0],h[1],h[2],h[3]]):h}function isIPv4(y){return!!parseIPv4(y)}function isIPv6(y){return!!parseIPv6(y)}const CODE_IP4=4,CODE_TCP=6,CODE_UDP=273,CODE_DCCP=33,CODE_IP6=41,CODE_IP6ZONE=42,CODE_IPCIDR=43,CODE_DNS=53,CODE_DNS4=54,CODE_DNS6=55,CODE_DNSADDR=56,CODE_SCTP=132,CODE_UDT=301,CODE_UTP=302,CODE_UNIX=400,CODE_P2P=421,CODE_ONION=444,CODE_ONION3=445,CODE_GARLIC64=446,CODE_GARLIC32=447,CODE_TLS=448,CODE_SNI=449,CODE_NOISE=454,CODE_QUIC=460,CODE_QUIC_V1=461,CODE_WEBTRANSPORT=465,CODE_CERTHASH=466,CODE_HTTP=480,CODE_HTTP_PATH=481,CODE_HTTPS=443,CODE_WS=477,CODE_WSS=478,CODE_P2P_WEBSOCKET_STAR=479,CODE_P2P_STARDUST=277,CODE_P2P_WEBRTC_STAR=275,CODE_P2P_WEBRTC_DIRECT=276,CODE_WEBRTC_DIRECT=280,CODE_WEBRTC=281,CODE_P2P_CIRCUIT=290,CODE_MEMORY=777;function bytesToString(y){return u=>toString$1(u,y)}function stringToBytes(y){return u=>fromString(u,y)}function bytes2port(y){return new DataView(y.buffer).getUint16(y.byteOffset).toString()}function port2bytes(y){const u=new ArrayBuffer(2);return new DataView(u).setUint16(0,typeof y=="string"?parseInt(y):y),new Uint8Array(u)}function onion2bytes(y){const u=y.split(":");if(u.length!==2)throw new Error(`failed to parse onion addr: ["'${u.join('", "')}'"]' does not contain a port number`);if(u[0].length!==16)throw new Error(`failed to parse onion addr: ${u[0]} not a Tor onion address.`);const h=fromString(u[0],"base32"),b=parseInt(u[1],10);if(b<1||b>65536)throw new Error("Port number is not in range(1, 65536)");const v=port2bytes(b);return concat([h,v],h.length+v.length)}function onion32bytes(y){const u=y.split(":");if(u.length!==2)throw new Error(`failed to parse onion addr: ["'${u.join('", "')}'"]' does not contain a port number`);if(u[0].length!==56)throw new Error(`failed to parse onion addr: ${u[0]} not a Tor onion3 address.`);const h=base32$2.decode(`b${u[0]}`),b=parseInt(u[1],10);if(b<1||b>65536)throw new Error("Port number is not in range(1, 65536)");const v=port2bytes(b);return concat([h,v],h.length+v.length)}function bytes2onion(y){const u=y.subarray(0,y.length-2),h=y.subarray(y.length-2),b=toString$1(u,"base32"),v=bytes2port(h);return`${b}:${v}`}const ip4ToBytes=function(y){y=y.toString().trim();const u=new Uint8Array(4);return y.split(/\./g).forEach((h,b)=>{const v=parseInt(h,10);if(isNaN(v)||v<0||v>255)throw new InvalidMultiaddrError("Invalid byte value in IP address");u[b]=v}),u},ip6ToBytes=function(y){let u=0;y=y.toString().trim();const h=y.split(":",8);let b;for(b=0;b<h.length;b++){const w=isIPv4(h[b]);let _;w&&(_=ip4ToBytes(h[b]),h[b]=toString$1(_.subarray(0,2),"base16")),_!=null&&++b<8&&h.splice(b,0,toString$1(_.subarray(2,4),"base16"))}if(h[0]==="")for(;h.length<8;)h.unshift("0");else if(h[h.length-1]==="")for(;h.length<8;)h.push("0");else if(h.length<8){for(b=0;b<h.length&&h[b]!=="";b++);const w=[b,1];for(b=9-h.length;b>0;b--)w.push("0");h.splice.apply(h,w)}const v=new Uint8Array(u+16);for(b=0;b<h.length;b++){h[b]===""&&(h[b]="0");const w=parseInt(h[b],16);if(isNaN(w)||w<0||w>65535)throw new InvalidMultiaddrError("Invalid byte value in IP address");v[u++]=w>>8&255,v[u++]=w&255}return v},ip4ToString=function(y){if(y.byteLength!==4)throw new InvalidMultiaddrError("IPv4 address was incorrect length");const u=[];for(let h=0;h<y.byteLength;h++)u.push(y[h]);return u.join(".")},ip6ToString=function(y){if(y.byteLength!==16)throw new InvalidMultiaddrError("IPv6 address was incorrect length");const u=[];for(let b=0;b<y.byteLength;b+=2){const v=y[b],w=y[b+1],_=`${v.toString(16).padStart(2,"0")}${w.toString(16).padStart(2,"0")}`;u.push(_)}const h=u.join(":");try{const b=new URL(`http://[${h}]`);return b.hostname.substring(1,b.hostname.length-1)}catch{throw new InvalidMultiaddrError(`Invalid IPv6 address "${h}"`)}};function ip6StringToValue(y){try{const u=new URL(`http://[${y}]`);return u.hostname.substring(1,u.hostname.length-1)}catch{throw new InvalidMultiaddrError(`Invalid IPv6 address "${y}"`)}}const decoders$2=Object.values(bases).map(y=>y.decoder),anybaseDecoder=function(){let y=decoders$2[0].or(decoders$2[1]);return decoders$2.slice(2).forEach(u=>y=y.or(u)),y}();function mb2bytes(y){return anybaseDecoder.decode(y)}function bytes2mb(y){return u=>y.encoder.encode(u)}function integer(y){if(parseInt(y).toString()!==y)throw new ValidationError("Value must be an integer")}function positive(y){if(y<0)throw new ValidationError("Value must be a positive integer, or zero")}function maxValue(y){return u=>{if(u>y)throw new ValidationError(`Value must be smaller than or equal to ${y}`)}}function validate$1(...y){return u=>{for(const h of y)h(u)}}const validatePort=validate$1(integer,positive,maxValue(65535)),V$1=-1;class Registry{constructor(){Z(this,"protocolsByCode",new Map);Z(this,"protocolsByName",new Map)}getProtocol(u){let h;if(typeof u=="string"?h=this.protocolsByName.get(u):h=this.protocolsByCode.get(u),h==null)throw new UnknownProtocolError(`Protocol ${u} was unknown`);return h}addProtocol(u){var h;this.protocolsByCode.set(u.code,u),this.protocolsByName.set(u.name,u),(h=u.aliases)==null||h.forEach(b=>{this.protocolsByName.set(b,u)})}removeProtocol(u){var b;const h=this.protocolsByCode.get(u);h!=null&&(this.protocolsByCode.delete(h.code),this.protocolsByName.delete(h.name),(b=h.aliases)==null||b.forEach(v=>{this.protocolsByName.delete(v)}))}}const registry=new Registry,codecs=[{code:CODE_IP4,name:"ip4",size:32,valueToBytes:ip4ToBytes,bytesToValue:ip4ToString,validate:y=>{if(!isIPv4(y))throw new ValidationError(`Invalid IPv4 address "${y}"`)}},{code:CODE_TCP,name:"tcp",size:16,valueToBytes:port2bytes,bytesToValue:bytes2port,validate:validatePort},{code:CODE_UDP,name:"udp",size:16,valueToBytes:port2bytes,bytesToValue:bytes2port,validate:validatePort},{code:CODE_DCCP,name:"dccp",size:16,valueToBytes:port2bytes,bytesToValue:bytes2port,validate:validatePort},{code:CODE_IP6,name:"ip6",size:128,valueToBytes:ip6ToBytes,bytesToValue:ip6ToString,stringToValue:ip6StringToValue,validate:y=>{if(!isIPv6(y))throw new ValidationError(`Invalid IPv6 address "${y}"`)}},{code:CODE_IP6ZONE,name:"ip6zone",size:V$1},{code:CODE_IPCIDR,name:"ipcidr",size:8,bytesToValue:bytesToString("base10"),valueToBytes:stringToBytes("base10")},{code:CODE_DNS,name:"dns",size:V$1,resolvable:!0},{code:CODE_DNS4,name:"dns4",size:V$1,resolvable:!0},{code:CODE_DNS6,name:"dns6",size:V$1,resolvable:!0},{code:CODE_DNSADDR,name:"dnsaddr",size:V$1,resolvable:!0},{code:CODE_SCTP,name:"sctp",size:16,valueToBytes:port2bytes,bytesToValue:bytes2port,validate:validatePort},{code:CODE_UDT,name:"udt"},{code:CODE_UTP,name:"utp"},{code:CODE_UNIX,name:"unix",size:V$1,path:!0,stringToValue:y=>decodeURIComponent(y),valueToString:y=>encodeURIComponent(y)},{code:CODE_P2P,name:"p2p",aliases:["ipfs"],size:V$1,bytesToValue:bytesToString("base58btc"),valueToBytes:y=>y.startsWith("Q")||y.startsWith("1")?stringToBytes("base58btc")(y):CID.parse(y).multihash.bytes},{code:CODE_ONION,name:"onion",size:96,bytesToValue:bytes2onion,valueToBytes:onion2bytes},{code:CODE_ONION3,name:"onion3",size:296,bytesToValue:bytes2onion,valueToBytes:onion32bytes},{code:CODE_GARLIC64,name:"garlic64",size:V$1},{code:CODE_GARLIC32,name:"garlic32",size:V$1},{code:CODE_TLS,name:"tls"},{code:CODE_SNI,name:"sni",size:V$1},{code:CODE_NOISE,name:"noise"},{code:CODE_QUIC,name:"quic"},{code:CODE_QUIC_V1,name:"quic-v1"},{code:CODE_WEBTRANSPORT,name:"webtransport"},{code:CODE_CERTHASH,name:"certhash",size:V$1,bytesToValue:bytes2mb(base64url),valueToBytes:mb2bytes},{code:CODE_HTTP,name:"http"},{code:CODE_HTTP_PATH,name:"http-path",size:V$1,stringToValue:y=>`/${decodeURIComponent(y)}`,valueToString:y=>encodeURIComponent(y.substring(1))},{code:CODE_HTTPS,name:"https"},{code:CODE_WS,name:"ws"},{code:CODE_WSS,name:"wss"},{code:CODE_P2P_WEBSOCKET_STAR,name:"p2p-websocket-star"},{code:CODE_P2P_STARDUST,name:"p2p-stardust"},{code:CODE_P2P_WEBRTC_STAR,name:"p2p-webrtc-star"},{code:CODE_P2P_WEBRTC_DIRECT,name:"p2p-webrtc-direct"},{code:CODE_WEBRTC_DIRECT,name:"webrtc-direct"},{code:CODE_WEBRTC,name:"webrtc"},{code:CODE_P2P_CIRCUIT,name:"p2p-circuit"},{code:CODE_MEMORY,name:"memory",size:V$1}];codecs.forEach(y=>{registry.addProtocol(y)});function bytesToComponents(y){var b;const u=[];let h=0;for(;h<y.length;){const v=decode$8(y,h),w=registry.getProtocol(v),_=encodingLength$1(v),E=sizeForAddr(w,y,h+_);let S=0;E>0&&w.size===V$1&&(S=encodingLength$1(E));const x=_+S+E,T={code:v,name:w.name,bytes:y.subarray(h,h+x)};if(E>0){const C=h+_+S,O=y.subarray(C,C+E);T.value=((b=w.bytesToValue)==null?void 0:b.call(w,O))??toString$1(O)}u.push(T),h+=x}return u}function componentsToBytes(y){var b;let u=0;const h=[];for(const v of y){if(v.bytes==null){const w=registry.getProtocol(v.code),_=encodingLength$1(v.code);let E,S=0,x=0;v.value!=null&&(E=((b=w.valueToBytes)==null?void 0:b.call(w,v.value))??fromString(v.value),S=E.byteLength,w.size===V$1&&(x=encodingLength$1(S)));const T=new Uint8Array(_+x+S);let C=0;encodeUint8Array(v.code,T,C),C+=_,E!=null&&(w.size===V$1&&(encodeUint8Array(S,T,C),C+=x),T.set(E,C)),v.bytes=T}h.push(v.bytes),u+=v.bytes.byteLength}return concat(h,u)}function stringToComponents(y){var w;if(y.charAt(0)!=="/")throw new InvalidMultiaddrError('String multiaddr must start with "/"');const u=[];let h="protocol",b="",v="";for(let _=1;_<y.length;_++){const E=y.charAt(_);E!=="/"&&(h==="protocol"?v+=y.charAt(_):b+=y.charAt(_));const S=_===y.length-1;if(E==="/"||S){const x=registry.getProtocol(v);if(h==="protocol"){if(x.size==null||x.size===0){u.push({code:x.code,name:x.name}),b="",v="",h="protocol";continue}else if(S)throw new InvalidMultiaddrError(`Component ${v} was missing value`);h="value"}else if(h==="value"){const T={code:x.code,name:x.name};if(x.size!=null&&x.size!==0){if(b==="")throw new InvalidMultiaddrError(`Component ${v} was missing value`);T.value=((w=x.stringToValue)==null?void 0:w.call(x,b))??b}u.push(T),b="",v="",h="protocol"}}}if(v!==""&&b!=="")throw new InvalidMultiaddrError("Incomplete multiaddr");return u}function componentsToString(y){return`/${y.flatMap(u=>{var b;if(u.value==null)return u.name;const h=registry.getProtocol(u.code);if(h==null)throw new InvalidMultiaddrError(`Unknown protocol code ${u.code}`);return[u.name,((b=h.valueToString)==null?void 0:b.call(h,u.value))??u.value]}).join("/")}`}function sizeForAddr(y,u,h){return y.size==null||y.size===0?0:y.size>0?y.size/8:decode$8(u,h)}const inspect$1=Symbol.for("nodejs.util.inspect.custom"),symbol=Symbol.for("@multiformats/multiaddr"),DNS_CODES=[CODE_DNS,CODE_DNS4,CODE_DNS6,CODE_DNSADDR];class NoAvailableResolverError extends Error{constructor(u="No available resolver"){super(u),this.name="NoAvailableResolverError"}}function toComponents(y){if(y==null&&(y="/"),isMultiaddr(y))return y.getComponents();if(y instanceof Uint8Array)return bytesToComponents(y);if(typeof y=="string")return y=y.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),y===""&&(y="/"),stringToComponents(y);if(Array.isArray(y))return y;throw new InvalidMultiaddrError("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Xd,_r,Bo,ko;const Oo=class Oo{constructor(u="/",h={}){Z(this,Xd,!0);ur(this,_r);ur(this,Bo);ur(this,ko);Ft(this,_r,toComponents(u)),h.validate!==!1&&validate(this)}get bytes(){return je(this,ko)==null&&Ft(this,ko,componentsToBytes(je(this,_r))),je(this,ko)}toString(){return je(this,Bo)==null&&Ft(this,Bo,componentsToString(je(this,_r))),je(this,Bo)}toJSON(){return this.toString()}toOptions(){let u,h,b,v,w="";for(const{code:E,name:S,value:x}of je(this,_r))E===CODE_IP6ZONE&&(w=`%${x??""}`),DNS_CODES.includes(E)&&(h="tcp",v=443,b=`${x??""}${w}`,u=E===CODE_DNS6?6:4),(E===CODE_TCP||E===CODE_UDP)&&(h=S==="tcp"?"tcp":"udp",v=parseInt(x??"")),(E===CODE_IP4||E===CODE_IP6)&&(h="tcp",b=`${x??""}${w}`,u=E===CODE_IP6?6:4);if(u==null||h==null||b==null||v==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:u,host:b,transport:h,port:v}}getComponents(){return[...je(this,_r)]}protos(){return je(this,_r).map(({code:u,value:h})=>{const b=registry.getProtocol(u);return{code:u,size:b.size??0,name:b.name,resolvable:!!b.resolvable,path:!!b.path}})}protoCodes(){return je(this,_r).map(({code:u})=>u)}protoNames(){return je(this,_r).map(({name:u})=>u)}tuples(){return je(this,_r).map(({code:u,value:h})=>{var w;if(h==null)return[u];const b=registry.getProtocol(u),v=[u];return h!=null&&v.push(((w=b.valueToBytes)==null?void 0:w.call(b,h))??fromString(h)),v})}stringTuples(){return je(this,_r).map(({code:u,value:h})=>h==null?[u]:[u,h])}encapsulate(u){const h=new Oo(u);return new Oo([...je(this,_r),...h.getComponents()],{validate:!1})}decapsulate(u){const h=u.toString(),b=this.toString(),v=b.lastIndexOf(h);if(v<0)throw new InvalidParametersError(`Address ${this.toString()} does not contain subaddress: ${u.toString()}`);return new Oo(b.slice(0,v),{validate:!1})}decapsulateCode(u){let h;for(let b=je(this,_r).length-1;b>-1;b--)if(je(this,_r)[b].code===u){h=b;break}return new Oo(je(this,_r).slice(0,h),{validate:!1})}getPeerId(){try{let u=[];je(this,_r).forEach(({code:b,value:v})=>{b===CODE_P2P&&u.push([b,v]),b===CODE_P2P_CIRCUIT&&(u=[])});const h=u.pop();if((h==null?void 0:h[1])!=null){const b=h[1];return b[0]==="Q"||b[0]==="1"?toString$1(base58btc.decode(`z${b}`),"base58btc"):toString$1(CID.parse(b).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(const u of je(this,_r))if(registry.getProtocol(u.code).path)return u.value??null;return null}equals(u){return equals(this.bytes,u.bytes)}async resolve(u){const h=this.protos().find(w=>w.resolvable);if(h==null)return[this];const b=resolvers.get(h.name);if(b==null)throw new NoAvailableResolverError(`no available resolver for ${h.name}`);return(await b(this,u)).map(w=>multiaddr(w))}nodeAddress(){const u=this.toOptions();if(u.transport!=="tcp"&&u.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${u.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:u.family,address:u.host,port:u.port}}isThinWaistAddress(){return!(je(this,_r).length!==2||je(this,_r)[0].code!==CODE_IP4&&je(this,_r)[0].code!==CODE_IP6||je(this,_r)[1].code!==CODE_TCP&&je(this,_r)[1].code!==CODE_UDP)}[(Xd=symbol,inspect$1)](){return`Multiaddr(${this.toString()})`}};_r=new WeakMap,Bo=new WeakMap,ko=new WeakMap;let Multiaddr=Oo;function validate(y){y.getComponents().forEach(u=>{var b;const h=registry.getProtocol(u.code);u.value!=null&&((b=h.validate)==null||b.call(h,u.value))})}function allFF(y,u,h){let b=0;for(const v of y)if(!(b<u)){if(b>h)break;if(v!==255)return!1;b++}return!0}function deepEqual(y,u,h,b){let v=0;for(const w of y)if(!(v<h)){if(v>b)break;if(w!==u[v])return!1;v++}return!0}function ipToString(y){switch(y.length){case IPv4Len:return y.join(".");case IPv6Len:{const u=[];for(let h=0;h<y.length;h++)h%2===0&&u.push(y[h].toString(16).padStart(2,"0")+y[h+1].toString(16).padStart(2,"0"));return u.join(":")}default:throw new Error("Invalid ip length")}}function simpleMaskLength(y){let u=0;for(let[h,b]of y.entries()){if(b===255){u+=8;continue}for(;b&128;)u++,b=b<<1;if(b&128)return-1;for(let v=h+1;v<y.length;v++)if(y[v]!=0)return-1;break}return u}function maskToHex(y){let u="0x";for(const h of y)u+=(h>>4).toString(16)+(h&15).toString(16);return u}const IPv4Len=4,IPv6Len=16,ipv4Prefix=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function maskIp(y,u){u.length===IPv6Len&&y.length===IPv4Len&&allFF(u,0,11)&&(u=u.slice(12)),u.length===IPv4Len&&y.length===IPv6Len&&deepEqual(y,ipv4Prefix,0,11)&&(y=y.slice(12));const h=y.length;if(h!=u.length)throw new Error("Failed to mask ip");const b=new Uint8Array(h);for(let v=0;v<h;v++)b[v]=y[v]&u[v];return b}function containsIp(y,u){if(typeof u=="string"&&(u=parseIP(u)),u==null)throw new Error("Invalid ip");if(u.length!==y.network.length)return!1;for(let h=0;h<u.length;h++)if((y.network[h]&y.mask[h])!==(u[h]&y.mask[h]))return!1;return!0}function parseCidr(y){const[u,h]=y.split("/");if(!u||!h)throw new Error("Failed to parse given CIDR: "+y);let b=IPv4Len,v=parseIPv4(u);if(v==null&&(b=IPv6Len,v=parseIPv6(u),v==null))throw new Error("Failed to parse given CIDR: "+y);const w=parseInt(h,10);if(Number.isNaN(w)||String(w).length!==h.length||w<0||w>b*8)throw new Error("Failed to parse given CIDR: "+y);const _=cidrMask(w,8*b);return{network:maskIp(v,_),mask:_}}function cidrMask(y,u){if(u!==8*IPv4Len&&u!==8*IPv6Len)throw new Error("Invalid CIDR mask");if(y<0||y>u)throw new Error("Invalid CIDR mask");const h=u/8,b=new Uint8Array(h);for(let v=0;v<h;v++){if(y>=8){b[v]=255,y-=8;continue}b[v]=255-(255>>y),y=0}return b}class IpNet{constructor(u,h){if(h==null)({network:this.network,mask:this.mask}=parseCidr(u));else{const b=parseIP(u);if(b==null)throw new Error("Failed to parse network");h=String(h);const v=parseInt(h,10);if(Number.isNaN(v)||String(v).length!==h.length||v<0||v>b.length*8){const w=parseIP(h);if(w==null)throw new Error("Failed to parse mask");this.mask=w}else this.mask=cidrMask(v,8*b.length);this.network=maskIp(b,this.mask)}}contains(u){return containsIp({network:this.network,mask:this.mask},u)}toString(){const u=simpleMaskLength(this.mask),h=u!==-1?String(u):maskToHex(this.mask);return ipToString(this.network)+"/"+h}}function cidrContains(y,u){return new IpNet(y).contains(u)}function convertToIpNet(y){let u,h;if(y.getComponents().forEach(b=>{(b.name==="ip4"||b.name==="ip6")&&(h=b.value),b.name==="ipcidr"&&(u=b.value)}),u==null||h==null)throw new Error("Invalid multiaddr");return new IpNet(h,u)}function convertToString(y,u){var b;const h=registry.getProtocol(y);return((b=h.bytesToValue)==null?void 0:b.call(h,u))??toString$1(u,"base16")}function convertToBytes(y,u){var b;const h=registry.getProtocol(y);return((b=h.valueToBytes)==null?void 0:b.call(h,u))??fromString(u,"base16")}const resolvers=new Map;function isMultiaddr(y){return!!(y!=null&&y[symbol])}function multiaddr(y){return new Multiaddr(y)}function protocols(y){const u=registry.getProtocol(y);return{code:u.code,size:u.size??0,name:u.name,resolvable:!!u.resolvable,path:!!u.path}}const getPeerPing=y=>{if(!y)return-1;try{const u=y.metadata.get("ping");return u?Number(bytesToUtf8(u)):-1}catch{return-1}},mapToPeerIdOrMultiaddr=y=>isPeerId(y)?y:multiaddr(y),mapToPeerId=y=>isPeerId(y)?y:peerIdFromString$1(multiaddr(y).getPeerId()),isAddressesSupported=(y,u)=>{var b,v;const h=((v=(b=y==null?void 0:y.components)==null?void 0:b.transportManager)==null?void 0:v.getTransports())||[];return h.length===0?!1:h.map(w=>w.dialFilter(u)).some(w=>w.length>0)},log$r=new Logger$1("connection-limiter"),DEFAULT_CONNECTION_MONITOR_INTERVAL=5*1e3;class ConnectionLimiter{constructor(u){Z(this,"libp2p");Z(this,"events");Z(this,"networkMonitor");Z(this,"dialer");Z(this,"connectionMonitorInterval",null);Z(this,"options");this.libp2p=u.libp2p,this.events=u.events,this.networkMonitor=u.networkMonitor,this.dialer=u.dialer,this.options=u.options,this.onWakuConnectionEvent=this.onWakuConnectionEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this)}start(){this.dialPeersFromStore(),this.options.enableAutoRecovery&&this.connectionMonitorInterval===null&&(this.connectionMonitorInterval=setInterval(()=>void this.maintainConnections(),DEFAULT_CONNECTION_MONITOR_INTERVAL)),this.events.addEventListener(WakuEvent.Connection,this.onWakuConnectionEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent)}stop(){this.events.removeEventListener(WakuEvent.Connection,this.onWakuConnectionEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent),this.connectionMonitorInterval&&(clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=null)}onWakuConnectionEvent(){if(!this.options.enableAutoRecovery){log$r.info("Auto recovery is disabled, skipping");return}this.networkMonitor.isBrowserConnected()&&this.dialPeersFromStore()}async maintainConnections(){await this.maintainConnectionsCount(),await this.maintainBootstrapConnections(),await this.maintainTTLConnectedPeers()}async onDisconnectedEvent(){this.libp2p.getConnections().length===0&&(log$r.info("No connections, dialing peers from store"),await this.dialPeersFromStore())}async maintainConnectionsCount(){log$r.info("Maintaining connections count");const u=this.libp2p.getConnections();if(u.length<=this.options.maxConnections){log$r.info(`Node has less than max connections ${this.options.maxConnections}, trying to dial more peers`);const h=await this.getPrioritizedPeers();if(h.length===0){log$r.info("No peers to dial, skipping"),await this.triggerBootstrap();return}const b=h.slice(0,this.options.maxConnections-u.length).map(v=>this.dialer.dial(v.id));await Promise.all(b);return}log$r.info(`Node has more than max connections ${this.options.maxConnections}, dropping connections`);try{const h=u.filter(v=>!v.tags.includes(CONNECTION_LOCKED_TAG)).slice(this.options.maxConnections);if(h.length===0){log$r.info("No connections to drop, skipping");return}const b=h.map(v=>this.libp2p.hangUp(v.remotePeer));await Promise.all(b),log$r.info(`Dropped ${h.length} connections`)}catch(h){log$r.error("Unexpected error while maintaining connections",h)}}async maintainBootstrapConnections(){log$r.info("Maintaining bootstrap connections");const u=await this.getBootstrapPeers();if(!(u.length<=this.options.maxBootstrapPeers))try{const h=u.slice(this.options.maxBootstrapPeers);log$r.info(`Dropping ${h.length} bootstrap connections because node has more than max bootstrap connections ${this.options.maxBootstrapPeers}`);const b=h.map(v=>this.libp2p.hangUp(v.id));await Promise.all(b),log$r.info(`Dropped ${h.length} bootstrap connections`)}catch(h){log$r.error("Unexpected error while maintaining bootstrap connections",h)}}async maintainTTLConnectedPeers(){log$r.info("Maintaining TTL connected peers");const u=this.libp2p.getConnections().map(async h=>{try{await this.libp2p.peerStore.merge(h.remotePeer,{metadata:{ttl:numberToBytes(Date.now())}}),log$r.info(`TTL updated for connected peer ${h.remotePeer.toString()}`)}catch(b){log$r.error("Unexpected error while maintaining TTL connected peer",b)}});await Promise.all(u)}async dialPeersFromStore(){log$r.info("Dialing peers from store");try{const u=await this.getPrioritizedPeers();if(u.length===0){log$r.info("No peers to dial, skipping"),await this.triggerBootstrap();return}const h=u.map(b=>this.dialer.dial(b.id));log$r.info(`Dialing ${u.length} peers from store`),await Promise.all(h),log$r.info(`Dialed ${h.length} peers from store`)}catch(u){log$r.error("Unexpected error while dialing peer store peers",u)}}async getPrioritizedPeers(){const u=await this.libp2p.peerStore.all(),h=this.libp2p.getConnections();log$r.info(`Found ${u.length} peers in store, and found ${h.length} connections`);const b=u.filter(S=>!h.some(x=>x.remotePeer.equals(S.id))&&isAddressesSupported(this.libp2p,S.addresses.map(x=>x.multiaddr))),v=b.filter(S=>S.tags.has(Tags.BOOTSTRAP)),w=b.filter(S=>S.tags.has(Tags.PEER_EXCHANGE)),_=b.filter(S=>S.tags.has(Tags.PEER_CACHE)),E=b.filter(S=>!S.tags.has(Tags.BOOTSTRAP)&&!S.tags.has(Tags.PEER_EXCHANGE)&&!S.tags.has(Tags.PEER_CACHE));return[...v,...w,..._,...E]}async getBootstrapPeers(){return(await Promise.all(this.libp2p.getConnections().map(h=>h.remotePeer).map(h=>this.getPeer(h)))).filter(h=>h&&h.tags.has(Tags.BOOTSTRAP))}async getPeer(u){try{return await this.libp2p.peerStore.get(u)}catch(h){return log$r.error(`Failed to get peer ${u}, error: ${h}`),null}}async triggerBootstrap(){log$r.info("Triggering bootstrap discovery");const u=Object.values(this.libp2p.components.components).filter(b=>!!b).filter(b=>[`@waku/${Tags.BOOTSTRAP}`,`@waku/${Tags.PEER_CACHE}`].includes(b==null?void 0:b[Symbol.toStringTag]));if(u.length===0){log$r.warn("No bootstrap components found to trigger");return}log$r.info(`Found ${u.length} bootstrap components, starting them`);const h=u.map(async b=>{var v,w;try{await((v=b==null?void 0:b.stop)==null?void 0:v.call(b)),await((w=b==null?void 0:b.start)==null?void 0:w.call(b)),log$r.info("Successfully started bootstrap component")}catch(_){log$r.error("Failed to start bootstrap component",_)}});await Promise.all(h)}}const log$q=new Logger$1("dialer");class Dialer{constructor(u){Z(this,"libp2p");Z(this,"shardReader");Z(this,"options");Z(this,"dialingQueue",[]);Z(this,"dialHistory",new Map);Z(this,"failedDials",new Map);Z(this,"dialingInterval",null);Z(this,"isProcessing",!1);Z(this,"isImmediateDialing",!1);this.libp2p=u.libp2p,this.shardReader=u.shardReader,this.options=u.options}start(){log$q.info("Starting dialer"),this.dialingInterval||(this.dialingInterval=setInterval(()=>{this.processQueue()},500)),this.dialHistory.clear(),this.failedDials.clear()}stop(){log$q.info("Stopping dialer"),this.dialingInterval&&(clearInterval(this.dialingInterval),this.dialingInterval=null),this.dialHistory.clear(),this.failedDials.clear()}async dial(u){if(await this.shouldSkipPeer(u)){log$q.info(`Skipping peer: ${u}`);return}const b=this.dialingQueue.length===0,v=!this.isProcessing&&!this.isImmediateDialing;b&&v?(this.isImmediateDialing=!0,log$q.info("Dialed peer immediately"),await this.dialPeer(u),this.isImmediateDialing=!1,log$q.info("Released immediate dial lock")):(this.dialingQueue.push(u),log$q.info(`Added peer to dialing queue, queue size: ${this.dialingQueue.length}`))}async processQueue(){if(!(this.dialingQueue.length===0||this.isProcessing)){this.isProcessing=!0;try{const u=this.dialingQueue.slice(0,this.options.maxDialingPeers);this.dialingQueue=this.dialingQueue.slice(u.length),log$q.info(`Processing dial queue: dialing ${u.length} peers, ${this.dialingQueue.length} remaining in queue`),await Promise.all(u.map(h=>this.dialPeer(h)))}finally{this.isProcessing=!1}}}async dialPeer(u){try{log$q.info(`Dialing peer from queue: ${u}`),await this.libp2p.dial(u),this.dialHistory.set(u.toString(),Date.now()),this.failedDials.delete(u.toString()),log$q.info(`Successfully dialed peer from queue: ${u}`)}catch(h){log$q.error(`Error dialing peer ${u}`,h),this.failedDials.set(u.toString(),Date.now())}}async shouldSkipPeer(u){if(this.libp2p.getPeers().some(b=>b.equals(u)))return log$q.info(`Skipping peer ${u} - already connected`),!0;if(this.isRecentlyDialed(u))return log$q.info(`Skipping peer ${u} - already dialed in the last 10 seconds`),!0;if(this.isRecentlyFailed(u))return log$q.info(`Skipping peer ${u} - recently failed to dial`),!0;try{return await this.shardReader.hasShardInfo(u)?await this.shardReader.isPeerOnCluster(u)?!1:(log$q.info(`Skipping peer ${u} - not on same cluster`),!0):(log$q.info(`Skipping peer ${u} - no shard info`),!1)}catch(b){return log$q.error(`Error checking shard info for peer ${u}`,b),!0}}isRecentlyDialed(u){const h=this.dialHistory.get(u.toString());return!!(h&&Date.now()-h<this.options.dialCooldown*1e3)}isRecentlyFailed(u){const h=this.failedDials.get(u.toString());return!!(h&&Date.now()-h<this.options.failedDialCooldown*1e3)}}const log$p=new Logger$1("discovery-dialer");class DiscoveryDialer{constructor(u){Z(this,"libp2p");Z(this,"dialer");this.libp2p=u.libp2p,this.dialer=u.dialer,this.onPeerDiscovery=this.onPeerDiscovery.bind(this)}start(){this.libp2p.addEventListener("peer:discovery",this.onPeerDiscovery)}stop(){this.libp2p.removeEventListener("peer:discovery",this.onPeerDiscovery)}async onPeerDiscovery(u){const h=u.detail.id;log$p.info(`Discovered new peer: ${h}`);try{await this.updatePeerStore(h,u.detail.multiaddrs),await this.dialer.dial(h)}catch(b){log$p.error(`Error dialing peer ${h}`,b)}}async updatePeerStore(u,h){try{log$p.info(`Updating peer store for ${u}`);const b=await this.getPeer(u);if(!b){log$p.info(`Peer ${u} not found in store, saving`),await this.libp2p.peerStore.save(u,{multiaddrs:h});return}if(h.every(w=>b.addresses.some(_=>_.multiaddr.equals(w)))){log$p.info(`Peer ${u} has same addresses in peer store, skipping`);return}log$p.info(`Merging peer ${u} addresses in peer store`),await this.libp2p.peerStore.merge(u,{multiaddrs:h})}catch(b){log$p.error(`Error updating peer store for ${u}`,b)}}async getPeer(u){try{return await this.libp2p.peerStore.get(u)}catch(h){log$p.error(`Error getting peer info for ${u}`,h);return}}}const RelayPingContentTopic="/relay-ping/1/ping/null",log$o=new Logger$1("keep-alive");class KeepAliveManager{constructor({options:u,relay:h,networkConfig:b,libp2p:v}){Z(this,"relay");Z(this,"networkConfig");Z(this,"libp2p");Z(this,"options");Z(this,"pingKeepAliveTimers",new Map);Z(this,"relayKeepAliveTimers",new Map);this.options=u,this.relay=h,this.networkConfig=b,this.libp2p=v,this.onPeerConnect=this.onPeerConnect.bind(this),this.onPeerDisconnect=this.onPeerDisconnect.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onPeerConnect),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnect)}stop(){this.libp2p.removeEventListener("peer:connect",this.onPeerConnect),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnect);for(const u of this.pingKeepAliveTimers.values())clearInterval(u);for(const u of this.relayKeepAliveTimers.values())for(const h of u)clearInterval(h);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}onPeerConnect(u){const h=u.detail;this.startPingForPeer(h)}onPeerDisconnect(u){const h=u.detail;this.stopPingForPeer(h)}startPingForPeer(u){this.stopPingForPeer(u),this.startLibp2pPing(u),this.startRelayPing(u)}stopPingForPeer(u){this.stopLibp2pPing(u),this.stopRelayPing(u)}startLibp2pPing(u){if(this.options.pingKeepAlive===0){log$o.warn(`Ping keep alive is disabled pingKeepAlive:${this.options.pingKeepAlive}, skipping start for libp2p ping`);return}const h=u.toString();if(this.pingKeepAliveTimers.has(h)){log$o.warn(`Ping already started for peer: ${h}, skipping start for libp2p ping`);return}const b=setInterval(()=>{this.pingLibp2p(u)},this.options.pingKeepAlive*1e3);this.pingKeepAliveTimers.set(h,b)}stopLibp2pPing(u){const h=u.toString();if(!this.pingKeepAliveTimers.has(h)){log$o.warn(`Ping not started for peer: ${h}, skipping stop for ping`);return}clearInterval(this.pingKeepAliveTimers.get(h)),this.pingKeepAliveTimers.delete(h)}startRelayPing(u){if(!this.relay)return;if(this.options.relayKeepAlive===0){log$o.warn(`Relay keep alive is disabled relayKeepAlive:${this.options.relayKeepAlive}, skipping start for relay ping`);return}if(this.relayKeepAliveTimers.has(u.toString())){log$o.warn(`Relay ping already started for peer: ${u.toString()}, skipping start for relay ping`);return}const h=[];for(const b of this.relay.pubsubTopics){if(!this.relay.getMeshPeers(b).includes(u.toString())){log$o.warn(`Peer: ${u.toString()} is not in the mesh for topic: ${b}, skipping start for relay ping`);continue}const w=createRoutingInfo(this.networkConfig,{contentTopic:RelayPingContentTopic,pubsubTopic:b}),_=createEncoder({routingInfo:w,contentTopic:RelayPingContentTopic,ephemeral:!0}),E=setInterval(()=>{this.pingRelay(_)},this.options.relayKeepAlive*1e3);h.push(E)}this.relayKeepAliveTimers.set(u.toString(),h)}stopRelayPing(u){var b;if(!this.relay)return;const h=u.toString();if(!this.relayKeepAliveTimers.has(h)){log$o.warn(`Relay ping not started for peer: ${h}, skipping stop for relay ping`);return}(b=this.relayKeepAliveTimers.get(h))==null||b.map(clearInterval),this.relayKeepAliveTimers.delete(h)}async pingRelay(u){try{log$o.info("Sending Waku Relay ping message"),await this.relay.send(u,{payload:new Uint8Array([1])})}catch(h){log$o.error("Failed to send relay ping",h)}}async pingLibp2p(u){try{log$o.info(`Pinging libp2p peer (${u.toString()})`);const h=await this.libp2p.services.ping.ping(u);log$o.info(`Ping succeeded (${u.toString()})`,h),await this.libp2p.peerStore.merge(u,{metadata:{ping:utf8ToBytes$1(h.toString())}}),log$o.info(`Ping updated for peer (${u.toString()})`)}catch(h){log$o.error(`Ping failed for peer (${u.toString()})`,h)}}}class NetworkMonitor{constructor(u){Z(this,"libp2p");Z(this,"events");Z(this,"isNetworkConnected",!1);this.libp2p=u.libp2p,this.events=u.events,this.onConnectedEvent=this.onConnectedEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this),this.dispatchNetworkEvent=this.dispatchNetworkEvent.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onConnectedEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.addEventListener("online",this.dispatchNetworkEvent),globalThis.addEventListener("offline",this.dispatchNetworkEvent)}catch{}}stop(){this.libp2p.removeEventListener("peer:connect",this.onConnectedEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.removeEventListener("online",this.dispatchNetworkEvent),globalThis.removeEventListener("offline",this.dispatchNetworkEvent)}catch{}}isConnected(){return this.isBrowserConnected()?this.isP2PConnected():!1}isP2PConnected(){return this.isNetworkConnected}isBrowserConnected(){var u;try{if(globalThis!=null&&globalThis.navigator&&!((u=globalThis==null?void 0:globalThis.navigator)!=null&&u.onLine))return!1}catch{}return!0}onConnectedEvent(){this.isNetworkConnected||(this.isNetworkConnected=!0,this.dispatchNetworkEvent())}onDisconnectedEvent(){this.isNetworkConnected&&this.libp2p.getConnections().length===0&&(this.isNetworkConnected=!1,this.dispatchNetworkEvent())}dispatchNetworkEvent(){this.events.dispatchEvent(new CustomEvent(WakuEvent.Connection,{detail:this.isConnected()}))}}const log$n=new Logger$1("shard-reader");class ShardReader{constructor(u){Z(this,"libp2p");Z(this,"clusterId");this.libp2p=u.libp2p,this.clusterId=u.networkConfig.clusterId}async isPeerOnCluster(u){const h=await this.getRelayShards(u);return h?h.clusterId===this.clusterId:!1}async hasShardInfo(u){return!!await this.getRelayShards(u)}async isPeerOnTopic(u,h){try{const{clusterId:b,shard:v}=pubsubTopicToSingleShardInfo(h);return b!==this.clusterId?!1:await this.isPeerOnShard(u,v)}catch(b){return log$n.error(`Error comparing pubsub topic ${h} with shard info for ${u}`,b),!1}}async isPeerOnShard(u,h){const b=await this.getRelayShards(u);return log$n.info(`Checking if peer on same shard: this { clusterId: ${this.clusterId}, shardId: ${h} },${u} { clusterId: ${b==null?void 0:b.clusterId}, shards: ${b==null?void 0:b.shards} }`),b?b.clusterId===this.clusterId&&b.shards.includes(h):!1}async getRelayShards(u){try{const b=(await this.libp2p.peerStore.get(u)).metadata.get("shardInfo");return b?decodeRelayShard(b):void 0}catch(h){log$n.error(`Error getting shard info for ${u}`,h);return}}}const log$m=new Logger$1("connection-manager"),DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED=3,DEFAULT_PING_KEEP_ALIVE_SEC=5*60,DEFAULT_RELAY_KEEP_ALIVE_SEC=5*60,DEFAULT_ENABLE_AUTO_RECOVERY=!0,DEFAULT_MAX_CONNECTIONS=10,DEFAULT_MAX_DIALING_PEERS=3,DEFAULT_FAILED_DIAL_COOLDOWN_SEC=60,DEFAULT_DIAL_COOLDOWN_SEC=10;class ConnectionManager{constructor(u){Z(this,"keepAliveManager");Z(this,"discoveryDialer");Z(this,"dialer");Z(this,"shardReader");Z(this,"networkMonitor");Z(this,"connectionLimiter");Z(this,"options");Z(this,"libp2p");this.libp2p=u.libp2p,this.options={maxBootstrapPeers:DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,maxConnections:DEFAULT_MAX_CONNECTIONS,pingKeepAlive:DEFAULT_PING_KEEP_ALIVE_SEC,relayKeepAlive:DEFAULT_RELAY_KEEP_ALIVE_SEC,enableAutoRecovery:DEFAULT_ENABLE_AUTO_RECOVERY,maxDialingPeers:DEFAULT_MAX_DIALING_PEERS,failedDialCooldown:DEFAULT_FAILED_DIAL_COOLDOWN_SEC,dialCooldown:DEFAULT_DIAL_COOLDOWN_SEC,...u.config},this.keepAliveManager=new KeepAliveManager({relay:u.relay,libp2p:u.libp2p,networkConfig:u.networkConfig,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.shardReader=new ShardReader({libp2p:u.libp2p,networkConfig:u.networkConfig}),this.dialer=new Dialer({libp2p:u.libp2p,shardReader:this.shardReader,options:this.options}),this.discoveryDialer=new DiscoveryDialer({libp2p:u.libp2p,dialer:this.dialer}),this.networkMonitor=new NetworkMonitor({libp2p:u.libp2p,events:u.events}),this.connectionLimiter=new ConnectionLimiter({libp2p:u.libp2p,events:u.events,networkMonitor:this.networkMonitor,dialer:this.dialer,options:this.options})}start(){this.dialer.start(),this.networkMonitor.start(),this.discoveryDialer.start(),this.keepAliveManager.start(),this.connectionLimiter.start()}stop(){this.dialer.stop(),this.networkMonitor.stop(),this.discoveryDialer.stop(),this.keepAliveManager.stop(),this.connectionLimiter.stop()}isConnected(){return this.networkMonitor.isConnected()}async dial(u,h){const b=mapToPeerIdOrMultiaddr(u);log$m.info(`Dialing peer ${b.toString()} with protocols ${h}`);const v=await this.libp2p.dialProtocol(b,h);return log$m.info(`Dialed peer ${b.toString()} with protocols ${h}`),v}async hangUp(u){const h=mapToPeerId(u);try{return log$m.info(`Dropping connection with peer ${h.toString()}`),await this.libp2p.hangUp(h),log$m.info(`Dropped connection with peer ${h.toString()}`),!0}catch(b){return log$m.error(`Error dropping connection with peer ${h.toString()} - ${b}`),!1}}async getConnectedPeers(u){const h=this.libp2p.getPeers();if(log$m.info(`Getting connected peers for codec ${u}`),h.length===0)return log$m.info("No connected peers"),[];const v=(await Promise.all(h.map(async w=>{try{return await this.libp2p.peerStore.get(w)}catch{return null}}))).filter(w=>!!w).filter(w=>u?w.protocols.includes(u):!0).sort((w,_)=>getPeerPing(w)-getPeerPing(_));return log$m.info(`Found ${v.length} connected peers for codec ${u}`),v}async hasShardInfo(u){return this.shardReader.hasShardInfo(u)}async isPeerOnTopic(u,h){return this.shardReader.isPeerOnTopic(u,h)}async isPeerOnShard(u,h){return this.shardReader.isPeerOnShard(u,h)}}const log$l=new Logger$1("metadata"),MetadataCodec="/vac/waku/metadata/1.0.0";class Metadata{constructor(u,h){Z(this,"clusterId");Z(this,"streamManager");Z(this,"libp2pComponents");Z(this,"handshakesConfirmed",new Map);Z(this,"multicodec",MetadataCodec);this.clusterId=u,this.streamManager=new StreamManager(MetadataCodec,h),this.libp2pComponents=h,h.registrar.handle(MetadataCodec,b=>{this.onRequest(b)})}async query(u){const h=WakuMetadataRequest.encode({clusterId:this.clusterId,shards:[]});if(!await this.libp2pComponents.peerStore.get(u))return{shardInfo:null,error:ProtocolError.NO_PEER_AVAILABLE};const v=await this.streamManager.getStream(u);if(!v)return log$l.error(`Failed to get a stream for remote peer:${u.toString()}`),{shardInfo:null,error:ProtocolError.NO_STREAM_AVAILABLE};const w=await pipe$1([h],encode$3,v,decode$2,async S=>await all$2(S)),{error:_,shardInfo:E}=this.decodeMetadataResponse(w);return _?{shardInfo:null,error:_}:(await this.savePeerShardInfo(u,E),{shardInfo:E,error:null})}async confirmOrAttemptHandshake(u){const h=this.handshakesConfirmed.get(u.toString());return h?{shardInfo:h,error:null}:await this.query(u)}async onRequest(u){try{const{stream:h,connection:b}=u,v=WakuMetadataResponse.encode({clusterId:this.clusterId,shards:[]}),w=await pipe$1([v],encode$3,h,decode$2,async S=>await all$2(S)),{error:_,shardInfo:E}=this.decodeMetadataResponse(w);if(_)return;await this.savePeerShardInfo(b.remotePeer,E)}catch(h){log$l.error("Error handling metadata request",h)}}decodeMetadataResponse(u){const h=new Uint8ArrayList;u.forEach(v=>{h.append(v)});const b=WakuMetadataResponse.decode(h);return b?{shardInfo:b,error:null}:(log$l.error("Error decoding metadata response"),{shardInfo:null,error:ProtocolError.DECODE_FAILED})}async savePeerShardInfo(u,h){await this.libp2pComponents.peerStore.merge(u,{metadata:{shardInfo:encodeRelayShard(h)}}),this.handshakesConfirmed.set(u.toString(),h)}}function wakuMetadata(y){return u=>new Metadata(y,u)}const log$k=new Logger$1("peer-manager"),DEFAULT_NUM_PEERS_TO_USE=2;var PeerManagerEventNames;(function(y){y.FilterConnect="filter:connect",y.FilterDisconnect="filter:disconnect",y.StoreConnect="store:connect"})(PeerManagerEventNames||(PeerManagerEventNames={}));class PeerManager{constructor(u){Z(this,"events",new TypedEventEmitter);Z(this,"numPeersToUse");Z(this,"libp2p");Z(this,"connectionManager");Z(this,"lockedPeers",new Set);Z(this,"unlockedPeers",new Map);var h;this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=((h=u==null?void 0:u.config)==null?void 0:h.numPeersToUse)||DEFAULT_NUM_PEERS_TO_USE,this.libp2p=u.libp2p,this.connectionManager=u.connectionManager}start(){this.libp2p.addEventListener("peer:identify",this.onConnected),this.libp2p.addEventListener("peer:disconnect",this.onDisconnected)}stop(){this.libp2p.removeEventListener("peer:identify",this.onConnected),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnected)}async getPeers(u){log$k.info(`Getting peers for protocol: ${u.protocol}, pubsubTopic: ${u.pubsubTopic}`);const h=await this.connectionManager.getConnectedPeers();log$k.info(`Found ${h.length} connected peers`);let b=[];for(const E of h){const S=this.hasPeerProtocol(E,u.protocol),x=await this.isPeerOnPubsub(E.id,u.pubsubTopic),T=this.isPeerAvailableForUse(E.id);S&&x&&T&&(b.push(E),log$k.info(`Peer ${E.id} qualifies for protocol ${u.protocol}`))}const v=b.filter(E=>this.isPeerLocked(E.id));if(log$k.info(`Found ${v.length} locked peers out of ${b.length} qualifying peers`),v.length>=this.numPeersToUse){const E=v.slice(0,this.numPeersToUse).map(S=>S.id);return log$k.info(`Using ${E.length} locked peers: ${E.map(S=>S.toString())}`),E}const w=b.filter(E=>!this.isPeerLocked(E.id));log$k.info(`Found ${w.length} unlocked peers, need ${this.numPeersToUse-v.length} more`),b=[...v,...w].slice(0,this.numPeersToUse).map(E=>(this.lockPeer(E.id),E));const _=b.map(E=>E.id);return log$k.info(`Selected ${_.length} peers: ${_.map(E=>E.toString())}`),_}async renewPeer(u,h){log$k.info(`Renewing peer ${u} for protocol: ${h.protocol}, pubsubTopic: ${h.pubsubTopic}`);const v=(await this.connectionManager.getConnectedPeers()).find(w=>w.id.equals(u));if(!v){log$k.warn(`Cannot renew peer:${u}, no connection to the peer.`);return}log$k.info(`Found peer ${u} in connected peers, unlocking and getting new peers`),this.unlockPeer(v.id),await this.getPeers(h)}async isPeerOnPubsub(u,h){return await this.connectionManager.hasShardInfo(u)?this.connectionManager.isPeerOnTopic(u,h):!0}async onConnected(u){const h=u.detail,b=h.protocols.includes(this.getProtocolCodecs(Protocols.Filter)),v=h.protocols.includes(this.getProtocolCodecs(Protocols.Store));b&&this.dispatchFilterPeerConnect(h.peerId),v&&this.dispatchStorePeerConnect(h.peerId)}async onDisconnected(u){const h=u.detail;try{const b=await this.libp2p.peerStore.get(h);this.hasPeerProtocol(b,Protocols.Filter)&&this.dispatchFilterPeerDisconnect(b.id)}catch(b){log$k.error(`Failed to dispatch Filter disconnect event:${b}`)}}hasPeerProtocol(u,h){return u.protocols.includes(this.getProtocolCodecs(h))}lockPeer(u){log$k.info(`Locking peer ${u}`),this.lockedPeers.add(u.toString()),this.libp2p.getConnections().filter(h=>h.remotePeer.equals(u)).forEach(h=>h.tags.push(CONNECTION_LOCKED_TAG)),this.unlockedPeers.delete(u.toString())}isPeerLocked(u){return this.lockedPeers.has(u.toString())}unlockPeer(u){log$k.info(`Unlocking peer ${u}`),this.lockedPeers.delete(u.toString()),this.libp2p.getConnections().filter(h=>h.remotePeer.equals(u)).forEach(h=>{h.tags=h.tags.filter(b=>b!==CONNECTION_LOCKED_TAG)}),this.unlockedPeers.set(u.toString(),Date.now())}isPeerAvailableForUse(u){const h=this.unlockedPeers.get(u.toString());if(!h)return!0;const b=new Date(h).getTime();return Date.now()-b>=1e4}dispatchFilterPeerConnect(u){this.events.dispatchEvent(new CustomEvent(PeerManagerEventNames.FilterConnect,{detail:u}))}dispatchStorePeerConnect(u){this.events.dispatchEvent(new CustomEvent(PeerManagerEventNames.StoreConnect,{detail:u}))}dispatchFilterPeerDisconnect(u){this.events.dispatchEvent(new CustomEvent(PeerManagerEventNames.FilterDisconnect,{detail:u}))}getProtocolCodecs(u){if(u===Protocols.Relay)throw new Error("Relay protocol is not supported");return{[Protocols.Filter]:FilterCodecs.SUBSCRIBE,[Protocols.LightPush]:LightPushCodec,[Protocols.Store]:StoreCodec,"light-push-v2":LightPushCodecV2}[u]}}class TTLSet{constructor(u,h=5e3){Z(this,"ttlMs");Z(this,"cleanupIntervalId",null);Z(this,"entryTimestamps",new Map);this.ttlMs=u,this.startCleanupInterval(h)}dispose(){this.cleanupIntervalId!==null&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.entryTimestamps.clear()}add(u){return this.entryTimestamps.set(u,Date.now()),this}has(u){return this.entryTimestamps.has(u)}startCleanupInterval(u){this.cleanupIntervalId=setInterval(()=>{this.removeExpiredEntries()},u)}removeExpiredEntries(){const u=Date.now();for(const[h,b]of this.entryTimestamps.entries())u-b>this.ttlMs&&this.entryTimestamps.delete(h)}}const log$j=new Logger$1("sdk:filter-subscription");class Subscription{constructor(u){Z(this,"pubsubTopic");Z(this,"protocol");Z(this,"peerManager");Z(this,"config");Z(this,"isStarted",!1);Z(this,"inProgress",!1);Z(this,"peers",new Map);Z(this,"peerFailures",new Map);Z(this,"receivedMessages",new TTLSet(6e4));Z(this,"callbacks",new Map);Z(this,"messageEmitter",new TypedEventEmitter);Z(this,"toSubscribeContentTopics",new Set);Z(this,"toUnsubscribeContentTopics",new Set);Z(this,"subscribeIntervalId",null);Z(this,"keepAliveIntervalId",null);this.config=u.config,this.pubsubTopic=u.pubsubTopic,this.protocol=u.protocol,this.peerManager=u.peerManager,this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}get contentTopics(){const u=Array.from(this.callbacks.keys()).map(b=>b.contentTopic),h=new Set(u).values();return Array.from(h)}start(){if(log$j.info(`Starting subscription for pubsubTopic: ${this.pubsubTopic}`),this.isStarted||this.inProgress){log$j.info("Subscription already started or in progress, skipping start");return}this.inProgress=!0,this.attemptSubscribe({useNewContentTopics:!1}),this.setupSubscriptionInterval(),this.setupKeepAliveInterval(),this.setupEventListeners(),this.isStarted=!0,this.inProgress=!1,log$j.info(`Subscription started for pubsubTopic: ${this.pubsubTopic}`)}stop(){if(log$j.info(`Stopping subscription for pubsubTopic: ${this.pubsubTopic}`),!this.isStarted||this.inProgress){log$j.info("Subscription not started or stop in progress, skipping stop");return}this.inProgress=!0,this.disposeEventListeners(),this.disposeIntervals(),this.disposePeers(),this.disposeHandlers(),this.receivedMessages.dispose(),this.inProgress=!1,this.isStarted=!1,log$j.info(`Subscription stopped for pubsubTopic: ${this.pubsubTopic}`)}isEmpty(){return this.callbacks.size===0}async add(u,h){const b=Array.isArray(u)?u:[u];for(const v of b)this.addSingle(v,h);return this.toSubscribeContentTopics.size>0?await this.attemptSubscribe({useNewContentTopics:!0}):!0}async remove(u){const h=Array.isArray(u)?u:[u];for(const b of h)this.removeSingle(b);return this.toUnsubscribeContentTopics.size>0?await this.attemptUnsubscribe({useNewContentTopics:!0}):!0}invoke(u,h){if(this.isMessageReceived(u)){log$j.info(`Skipping invoking callbacks for already received message: pubsubTopic:${this.pubsubTopic}, peerId:${h.toString()}, contentTopic:${u.contentTopic}`);return}log$j.info(`Invoking message for contentTopic: ${u.contentTopic}`),this.messageEmitter.dispatchEvent(new CustomEvent(u.contentTopic,{detail:u}))}addSingle(u,h){log$j.info(`Adding subscription for contentTopic: ${u.contentTopic}`);const b=!this.contentTopics.includes(u.contentTopic);if(b&&this.toSubscribeContentTopics.add(u.contentTopic),this.callbacks.has(u)){log$j.warn(`Replacing callback associated associated with decoder with pubsubTopic:${u.pubsubTopic} and contentTopic:${u.contentTopic}`);const w=this.callbacks.get(u);this.callbacks.delete(u),this.messageEmitter.removeEventListener(u.contentTopic,w)}const v=w=>{(async()=>{try{const _=await u.fromProtoObj(u.pubsubTopic,w.detail);h(_)}catch(_){log$j.error("Error decoding message",_)}})()};this.callbacks.set(u,v),this.messageEmitter.addEventListener(u.contentTopic,v),log$j.info(`Subscription added for contentTopic: ${u.contentTopic}, isNewContentTopic: ${b}`)}removeSingle(u){log$j.info(`Removing subscription for contentTopic: ${u.contentTopic}`);const h=this.callbacks.get(u);h||log$j.warn(`No callback associated with decoder with pubsubTopic:${u.pubsubTopic} and contentTopic:${u.contentTopic}`),this.callbacks.delete(u),this.messageEmitter.removeEventListener(u.contentTopic,h);const b=!this.contentTopics.includes(u.contentTopic);b&&this.toUnsubscribeContentTopics.add(u.contentTopic),log$j.info(`Subscription removed for contentTopic: ${u.contentTopic}, isCompletelyRemoved: ${b}`)}isMessageReceived(u){try{const h=messageHashStr(this.pubsubTopic,u);if(this.receivedMessages.has(h))return!0;this.receivedMessages.add(h)}catch{}return!1}setupSubscriptionInterval(){log$j.info("Setting up subscription interval with period 1000ms"),this.subscribeIntervalId=setInterval(()=>{(async()=>{this.toSubscribeContentTopics.size>0&&(log$j.info(`Subscription interval: ${this.toSubscribeContentTopics.size} topics to subscribe`),await this.attemptSubscribe({useNewContentTopics:!0})),this.toUnsubscribeContentTopics.size>0&&(log$j.info(`Subscription interval: ${this.toUnsubscribeContentTopics.size} topics to unsubscribe`),await this.attemptUnsubscribe({useNewContentTopics:!0}))})()},1e3)}setupKeepAliveInterval(){log$j.info(`Setting up keep-alive interval with period ${this.config.keepAliveIntervalMs}ms`),this.keepAliveIntervalId=setInterval(()=>{(async()=>{log$j.info(`Keep-alive interval running for ${this.peers.size} peers`);let h=await Promise.all(Array.from(this.peers.values()).map(async b=>{if((await this.protocol.ping(b)).success){log$j.info(`Ping successful for peer: ${b.toString()}`),this.peerFailures.set(b.toString(),0);return}let w=this.peerFailures.get(b.toString())||0;if(w+=1,this.peerFailures.set(b.toString(),w),log$j.warn(`Ping failed for peer: ${b.toString()}, failures: ${w}/${this.config.pingsBeforePeerRenewed}`),!(w<this.config.pingsBeforePeerRenewed))return log$j.info(`Peer ${b.toString()} exceeded max failures (${this.config.pingsBeforePeerRenewed}), will be replaced`),b}));h=h.filter(b=>!!b),await Promise.all(h.map(b=>(this.peers.delete(b==null?void 0:b.toString()),this.peerFailures.delete(b==null?void 0:b.toString()),this.requestUnsubscribe(b,this.contentTopics)))),h.length>0&&(log$j.info(`Replacing ${h.length} failed peers`),await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}))})()},this.config.keepAliveIntervalMs)}setupEventListeners(){this.peerManager.events.addEventListener(PeerManagerEventNames.FilterConnect,this.onPeerConnected),this.peerManager.events.addEventListener(PeerManagerEventNames.FilterDisconnect,this.onPeerDisconnected)}disposeIntervals(){this.subscribeIntervalId&&clearInterval(this.subscribeIntervalId),this.keepAliveIntervalId&&clearInterval(this.keepAliveIntervalId)}disposeHandlers(){for(const[u,h]of this.callbacks.entries())this.messageEmitter.removeEventListener(u.contentTopic,h);this.callbacks.clear()}async disposePeers(){await this.attemptUnsubscribe({useNewContentTopics:!1}),this.peers.clear(),this.peerFailures=new Map}disposeEventListeners(){this.peerManager.events.removeEventListener(PeerManagerEventNames.FilterConnect,this.onPeerConnected),this.peerManager.events.removeEventListener(PeerManagerEventNames.FilterDisconnect,this.onPeerDisconnected)}async onPeerConnected(u){var v;const h=(v=u.detail)==null?void 0:v.toString();if(log$j.info(`Peer connected: ${h}`),!await this.peerManager.isPeerOnPubsub(u.detail,this.pubsubTopic)){log$j.info(`Peer ${h} doesn't support pubsubTopic:${this.pubsubTopic}`);return}if(this.peers.has(h)){log$j.info(`Peer ${h} already subscribed, skipping`);return}await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})}async onPeerDisconnected(u){var v;const h=(v=u.detail)==null?void 0:v.toString();if(log$j.info(`Peer disconnected: ${h}`),!await this.peerManager.isPeerOnPubsub(u.detail,this.pubsubTopic)){log$j.info(`Peer ${h} doesn't support pubsubTopic:${this.pubsubTopic}`);return}if(!this.peers.has(h)){log$j.info(`Disconnected peer ${h} not in use, ignoring`);return}log$j.info(`Active peer ${h} disconnected, removing from peers list`),this.peers.delete(h),this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})}async attemptSubscribe(u){const{useNewContentTopics:h,useOnlyNewPeers:b=!1}=u,v=h?Array.from(this.toSubscribeContentTopics):this.contentTopics;if(log$j.info(`Attempting to subscribe: useNewContentTopics=${h}, useOnlyNewPeers=${b}, contentTopics=${v.length}`),!v.length)return log$j.warn("Requested content topics is an empty array, skipping"),!1;const w=new Set(this.peers.keys()),_=await this.peerManager.getPeers({protocol:Protocols.Filter,pubsubTopic:this.pubsubTopic});for(const T of _){if(this.peers.size>=this.config.numPeersToUse)break;this.peers.set(T.toString(),T)}const E=b?Array.from(this.peers.values()).filter(T=>!w.has(T.toString())):Array.from(this.peers.values());if(log$j.info(`Subscribing with ${E.length} peers for ${v.length} content topics`),b&&E.length===0)return log$j.warn("Requested to use only new peers, but no peers found, skipping"),!1;const S=await Promise.all(E.map(T=>this.requestSubscribe(T,v))),x=S.filter(T=>T).length;return log$j.info(`Subscribe attempts completed: ${x}/${S.length} successful`),h&&(this.toSubscribeContentTopics=new Set),S.some(T=>T)}async requestSubscribe(u,h){if(log$j.info(`requestSubscribe: pubsubTopic:${this.pubsubTopic} contentTopics:${h.join(",")}`),!h.length||!this.pubsubTopic)return log$j.warn("requestSubscribe: no contentTopics or pubsubTopic provided, not sending subscribe request"),!1;const b=await this.protocol.subscribe(this.pubsubTopic,u,h);return b.failure?(log$j.warn(`requestSubscribe: Failed to subscribe ${this.pubsubTopic} to ${u.toString()} with error:${b.failure.error} for contentTopics:${h}`),!1):(log$j.info(`requestSubscribe: Subscribed ${this.pubsubTopic} to ${u.toString()} for contentTopics:${h}`),!0)}async attemptUnsubscribe(u){const{useNewContentTopics:h}=u,b=h?Array.from(this.toUnsubscribeContentTopics):this.contentTopics;if(log$j.info(`Attempting to unsubscribe: useNewContentTopics=${h}, contentTopics=${b.length}`),!b.length)return log$j.warn("Requested content topics is an empty array, skipping"),!1;const v=Array.from(this.peers.values()),w=await Promise.all(v.map(E=>this.requestUnsubscribe(E,h?b:void 0))),_=w.filter(E=>E).length;return log$j.info(`Unsubscribe attempts completed: ${_}/${w.length} successful`),h&&(this.toUnsubscribeContentTopics=new Set),w.some(E=>E)}async requestUnsubscribe(u,h){var v;const b=h?await this.protocol.unsubscribe(this.pubsubTopic,u,h):await this.protocol.unsubscribeAll(this.pubsubTopic,u);return b.failure?(log$j.warn(`requestUnsubscribe: Failed to unsubscribe for pubsubTopic:${this.pubsubTopic} from peerId:${u.toString()} with error:${(v=b.failure)==null?void 0:v.error} for contentTopics:${h}`),!1):(log$j.info(`requestUnsubscribe: Unsubscribed pubsubTopic:${this.pubsubTopic} from peerId:${u.toString()} for contentTopics:${h}`),!0)}}const log$i=new Logger$1("sdk:filter");class Filter{constructor(u){Z(this,"protocol");Z(this,"peerManager");Z(this,"config");Z(this,"subscriptions",new Map);this.config={numPeersToUse:2,pingsBeforePeerRenewed:3,keepAliveIntervalMs:6e4,...u.options},this.peerManager=u.peerManager,this.protocol=new FilterCore(this.onIncomingMessage.bind(this),u.libp2p)}get multicodec(){return this.protocol.multicodec}async start(){await this.protocol.start()}async stop(){await this.protocol.stop()}unsubscribeAll(){for(const u of this.subscriptions.values())u.stop();this.subscriptions.clear()}async subscribe(u,h){const b=Array.isArray(u)?u:[u];if(b.length===0)throw Error("Cannot subscribe with 0 decoders.");const v=b.map(x=>x.pubsubTopic),w=v[0],_=b.map(x=>x.contentTopic);log$i.info(`Subscribing to contentTopics: ${_}, pubsubTopic: ${w}`),this.throwIfTopicNotSame(v);let E=this.subscriptions.get(w);E||(E=new Subscription({pubsubTopic:w,protocol:this.protocol,config:this.config,peerManager:this.peerManager}),E.start());const S=await E.add(b,h);return this.subscriptions.set(w,E),log$i.info(`Subscription ${S?"successful":"failed"} for content topic: ${_}`),S}async unsubscribe(u){const h=Array.isArray(u)?u:[u];if(h.length===0)throw Error("Cannot unsubscribe with 0 decoders.");const b=h.map(S=>S.pubsubTopic),v=b[0],w=h.map(S=>S.contentTopic);log$i.info(`Unsubscribing from contentTopics: ${w}, pubsubTopic: ${v}`),this.throwIfTopicNotSame(b);const _=this.subscriptions.get(v);if(!_)return log$i.warn("No subscriptions associated with the decoder."),!1;const E=await _.remove(h);return _.isEmpty()&&(log$i.warn("Subscription has no decoders anymore, terminating it."),_.stop(),this.subscriptions.delete(v)),log$i.info(`Unsubscribing ${E?"successful":"failed"} for content topic: ${w}`),E}async onIncomingMessage(u,h,b){log$i.info(`Received message for pubsubTopic:${u}, contentTopic:${h.contentTopic}, peerId:${b.toString()}`);const v=this.subscriptions.get(u);if(!v){log$i.error(`No subscription locally registered for topic ${u}`);return}v.invoke(h,b)}throwIfTopicNotSame(u){const h=u[0];if(!u.every(v=>v===h))throw Error(`Cannot subscribe to more than one pubsub topic at the same time, got pubsubTopics:${u}`)}}var FUNC_ERROR_TEXT="Expected a function",NAN=NaN,symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt,freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,freeSelf=typeof self=="object"&&self&&self.Object===Object&&self,root$1=freeGlobal||freeSelf||Function("return this")(),objectProto=Object.prototype,objectToString$2=objectProto.toString,nativeMax=Math.max,nativeMin=Math.min,now=function(){return root$1.Date.now()};function debounce$2(y,u,h){var b,v,w,_,E,S,x=0,T=!1,C=!1,O=!0;if(typeof y!="function")throw new TypeError(FUNC_ERROR_TEXT);u=toNumber(u)||0,isObject$1(h)&&(T=!!h.leading,C="maxWait"in h,w=C?nativeMax(toNumber(h.maxWait)||0,u):w,O="trailing"in h?!!h.trailing:O);function D(ve){var Pe=b,Ie=v;return b=v=void 0,x=ve,_=y.apply(Ie,Pe),_}function U(ve){return x=ve,E=setTimeout(ie,u),T?D(ve):_}function te(ve){var Pe=ve-S,Ie=ve-x,Ee=u-Pe;return C?nativeMin(Ee,w-Ie):Ee}function X(ve){var Pe=ve-S,Ie=ve-x;return S===void 0||Pe>=u||Pe<0||C&&Ie>=w}function ie(){var ve=now();if(X(ve))return ee(ve);E=setTimeout(ie,te(ve))}function ee(ve){return E=void 0,O&&b?D(ve):(b=v=void 0,_)}function ae(){E!==void 0&&clearTimeout(E),x=0,b=S=v=E=void 0}function de(){return E===void 0?_:ee(now())}function Se(){var ve=now(),Pe=X(ve);if(b=arguments,v=this,S=ve,Pe){if(E===void 0)return U(S);if(C)return E=setTimeout(ie,u),D(S)}return E===void 0&&(E=setTimeout(ie,u)),_}return Se.cancel=ae,Se.flush=de,Se}function isObject$1(y){var u=typeof y;return!!y&&(u=="object"||u=="function")}function isObjectLike(y){return!!y&&typeof y=="object"}function isSymbol$1(y){return typeof y=="symbol"||isObjectLike(y)&&objectToString$2.call(y)==symbolTag}function toNumber(y){if(typeof y=="number")return y;if(isSymbol$1(y))return NAN;if(isObject$1(y)){var u=typeof y.valueOf=="function"?y.valueOf():y;y=isObject$1(u)?u+"":u}if(typeof y!="string")return y===0?y:+y;y=y.replace(reTrim,"");var h=reIsBinary.test(y);return h||reIsOctal.test(y)?freeParseInt(y.slice(2),h?2:8):reIsBadHex.test(y)?NAN:+y}var lodash_debounce=debounce$2;const debounce$3=getDefaultExportFromCjs$1(lodash_debounce),log$h=new Logger$1("health-indicator");class HealthIndicator{constructor(u){Z(this,"isStarted",!1);Z(this,"libp2p");Z(this,"events");Z(this,"value",HealthStatus.Unhealthy);Z(this,"debouncedAssessHealth");this.libp2p=u.libp2p,this.events=u.events,this.onPeerIdentify=this.onPeerIdentify.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this),this.debouncedAssessHealth=debounce$3(()=>{this.assessHealth()},100)}start(){this.isStarted||(this.isStarted=!0,log$h.info("start: adding listeners to libp2p"),this.libp2p.addEventListener("peer:identify",this.onPeerIdentify),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth())}stop(){this.isStarted&&(this.isStarted=!1,log$h.info("stop: removing listeners to libp2p"),this.libp2p.removeEventListener("peer:identify",this.onPeerIdentify),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth.cancel())}toValue(){return this.value}onPeerDisconnected(u){log$h.info("onPeerDisconnected: received libp2p event"),this.debouncedAssessHealth()}onPeerIdentify(u){log$h.info("onPeerIdentify: received libp2p event"),this.debouncedAssessHealth()}async assessHealth(){const u=this.libp2p.getConnections();if(u.length===0){log$h.info("assessHealth: no connections, setting to Unhealthy"),this.updateAndDispatchHealthEvent(HealthStatus.Unhealthy);return}const h=await Promise.all(u.map(async _=>{try{return await this.libp2p.peerStore.get(_.remotePeer)}catch{return log$h.warn(`assessHealth: failed to get peer ${_.remotePeer}, skipping`),null}})),b=h.filter(_=>_==null?void 0:_.protocols.includes(FilterCodecs.SUBSCRIBE)).length,v=h.filter(_=>_==null?void 0:_.protocols.includes(LightPushCodec)).length;let w;b===0||v===0?w=HealthStatus.Unhealthy:b>=2&&v>=2?w=HealthStatus.SufficientlyHealthy:b===1&&v===1?w=HealthStatus.MinimallyHealthy:(log$h.error(`assessHealth: unexpected state, cannot identify health status of the node: Filter:${b}; LightPush:${v}`),w=this.value),log$h.info(`assessHealth: node identified as ${w} Filter:${b}; LightPush:${v}`),this.updateAndDispatchHealthEvent(w)}updateAndDispatchHealthEvent(u){this.value!==u&&(this.value=u,this.events.dispatchEvent(new CustomEvent(WakuEvent.Health,{detail:this.value})))}}const shouldPeerBeChanged=y=>y===LightPushError.REMOTE_PEER_REJECTED||y===LightPushError.NO_RESPONSE||y===LightPushError.RLN_PROOF_GENERATION||y===LightPushError.NO_PEER_AVAILABLE,timeout=y=>new Promise((u,h)=>setTimeout(()=>h(new Error("Task timeout")),y)),MAX_CONCURRENT_TASKS=5,TASK_TIMEOUT_MS=1e4,log$g=new Logger$1("sdk:retry-manager");class RetryManager{constructor(u){Z(this,"intervalID",null);Z(this,"retryIntervalMs");Z(this,"inProgress",0);Z(this,"queue",[]);Z(this,"peerManager");this.peerManager=u.peerManager,this.retryIntervalMs=u.retryIntervalMs||1e3}start(){this.intervalID=setInterval(()=>{this.processQueue()},this.retryIntervalMs)}stop(){this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}push(u,h,b){this.queue.push({maxAttempts:h,callback:u,routingInfo:b})}processQueue(){if(this.queue.length!==0)for(;this.queue.length&&this.inProgress<MAX_CONCURRENT_TASKS;){const u=this.queue.shift();u&&this.scheduleTask(u)}}scheduleTask(u){setTimeout(async()=>this.taskExecutor(u),100)}async taskExecutor(u){if(u.maxAttempts<=0){log$g.warn("scheduleTask: max attempts has reached, removing from queue");return}const h=(await this.peerManager.getPeers({protocol:Protocols.LightPush,pubsubTopic:u.routingInfo.pubsubTopic}))[0];if(!h){log$g.warn("scheduleTask: no peers, putting back to queue"),this.queue.push({...u,maxAttempts:u.maxAttempts-1});return}try{this.inProgress+=1;const b=await Promise.race([timeout(TASK_TIMEOUT_MS),u.callback(h)]);if(b===void 0)throw new Error("Task timeout");if(b.failure)throw Error(b.failure.error);if(log$g.info("scheduleTask: executed successfully"),u.maxAttempts===0){log$g.warn("scheduleTask: discarded a task due to limit of max attempts");return}this.queue.push({...u,maxAttempts:u.maxAttempts-1})}catch(b){const v=b;if(log$g.error("scheduleTask: task execution failed with error:",v),shouldPeerBeChanged(v.message)&&await this.peerManager.renewPeer(h,{protocol:Protocols.LightPush,pubsubTopic:u.routingInfo.pubsubTopic}),u.maxAttempts===0){log$g.warn("scheduleTask: discarded a task due to limit of max attempts");return}this.queue.push({...u,maxAttempts:u.maxAttempts-1})}finally{this.inProgress-=1}}}const log$f=new Logger$1("sdk:light-push"),DEFAULT_MAX_ATTEMPTS=3,DEFAULT_SEND_OPTIONS={autoRetry:!0,retryIntervalMs:1e3,maxAttempts:DEFAULT_MAX_ATTEMPTS,numPeersToUse:1};class LightPush{constructor(u){Z(this,"config");Z(this,"retryManager");Z(this,"peerManager");Z(this,"protocol");this.config={...DEFAULT_SEND_OPTIONS,...u.options||{}},this.peerManager=u.peerManager,this.protocol=new LightPushCore(u.libp2p),this.retryManager=new RetryManager({peerManager:u.peerManager,retryIntervalMs:this.config.retryIntervalMs})}get multicodec(){return this.protocol.multicodec}start(){this.retryManager.start()}stop(){this.retryManager.stop()}async send(u,h,b={}){b={useLegacy:!1,...this.config,...b};const{pubsubTopic:v}=u;log$f.info("send: attempting to send a message to pubsubTopic:",v);const w=await this.peerManager.getPeers({protocol:b.useLegacy?"light-push-v2":Protocols.LightPush,pubsubTopic:u.pubsubTopic}),_=(w==null?void 0:w.length)>0?await Promise.all(w.map(S=>this.protocol.send(u,h,S,b.useLegacy).catch(x=>({success:null,failure:{error:LightPushError.GENERIC_FAIL}})))):[],E=_.length?{successes:_.filter(S=>S.success).map(S=>S.success),failures:_.filter(S=>S.failure).map(S=>S.failure)}:{successes:[],failures:[{error:LightPushError.NO_PEER_AVAILABLE}]};if(b.autoRetry&&E.successes.length===0){const S=x=>this.protocol.send(u,h,x,b.useLegacy);this.retryManager.push(S.bind(this),b.maxAttempts||DEFAULT_MAX_ATTEMPTS,u.routingInfo)}return E}}const log$e=new Logger$1("store-sdk");class Store{constructor(u){Z(this,"options");Z(this,"libp2p");Z(this,"peerManager");Z(this,"protocol");this.options=u.options||{},this.peerManager=u.peerManager,this.libp2p=u.libp2p,this.protocol=new StoreCore(u.libp2p)}get multicodec(){return this.protocol.multicodec}async*queryGenerator(u,h){const{decodersAsMap:b,queryOptions:v}=this.buildQueryParams(u,h);for(const w of v){const _=(h==null?void 0:h.peerId)??await this.getPeerToUse(w.pubsubTopic);if(!_)throw log$e.error("No peers available to query"),new Error("No peers available to query");log$e.info(`Querying store with options: ${JSON.stringify(w)}`);const E=this.protocol.queryPerPage(w,b,_);for await(const S of E)yield S}}async queryWithOrderedCallback(u,h,b){log$e.info("Querying store with ordered callback");for await(const v of this.queryGenerator(u,b))if(await this.processMessages(v,h))break}async queryWithPromiseCallback(u,h,b){log$e.info("Querying store with promise callback");let v=!1;for await(const w of this.queryGenerator(u,b)){const _=w.map(async E=>{v||(v=!!await h(E))});if(await Promise.all(_),v)break}}async processMessages(u,h){let b=!1;const w=(await Promise.all(u)).filter(isDefined);return await Promise.all(w.map(async _=>{_&&!b&&(b=!!await h(_))})),b}createCursor(u){return messageHash(u.pubsubTopic,u)}validateDecodersAndPubsubTopic(u){if(u.length===0)throw log$e.error("No decoders provided"),new Error("No decoders provided");const h=Array.from(new Set(u.map(_=>_.pubsubTopic)));if(h.length>1)throw log$e.error("API does not support querying multiple pubsub topics at once"),new Error("API does not support querying multiple pubsub topics at once");const b=h[0],v=new Map;u.forEach(_=>{if(v.has(_.contentTopic))throw log$e.error("API does not support different decoder per content topic"),new Error("API does not support different decoder per content topic");v.set(_.contentTopic,_)});const w=u.filter(_=>_.pubsubTopic===b).map(_=>_.contentTopic);if(w.length===0)throw log$e.error(`No decoders found for topic ${b}`),new Error("No decoders found for topic "+b);return{pubsubTopic:b,contentTopics:w,decodersAsMap:v}}async getPeerToUse(u){const h=await this.peerManager.getPeers({protocol:Protocols.Store,pubsubTopic:u});return this.options.peers?await this.getPeerFromConfigurationOrFirst(h,this.options.peers):h[0]}async getPeerFromConfigurationOrFirst(u,h){const b=h.map(multiaddr),v=[];for(const w of b){const _=u.find(E=>{var S;return E.toString()===((S=w.getPeerId())==null?void 0:S.toString())});if(_)return _;v.push(w)}for(;v.length;){const w=v.pop();if(!w)return;try{if(await this.libp2p.dial(w))return peerIdFromString$1(w.getPeerId())}catch(_){log$e.warn(`Failed to dial peer from options.peers list for Store protocol. Peer:${w.getPeerId()}, error:${_}`)}}return log$e.warn(`Passed node to use for Store not found: ${h.toString()}. Attempting to use first available peers.`),u[0]}buildQueryParams(u,h){var S;const b=(h==null?void 0:h.messageHashes)&&h.messageHashes.length>0;let v,w,_;if(b)v=h.pubsubTopic||((S=u[0])==null?void 0:S.pubsubTopic)||"",w=[],_=new Map,u.forEach(x=>{_.set(x.contentTopic,x)});else{const x=this.validateDecodersAndPubsubTopic(u);v=x.pubsubTopic,w=x.contentTopics,_=x.decodersAsMap}const E=[];if(h!=null&&h.timeStart&&(h!=null&&h.timeEnd)){let x=h.timeStart;const T=h.timeEnd;for(;T.getTime()-x.getTime()>this.protocol.maxTimeLimit;){const C=new Date(x.getTime()+this.protocol.maxTimeLimit);E.push([x,C]),x=C}E.length===0&&(log$e.info("Using single time range"),E.push([x,T]))}return E.length===0?(log$e.info("No sub time ranges"),{decodersAsMap:_,queryOptions:[{pubsubTopic:v,contentTopics:w,includeData:!0,paginationForward:!0,...h}]}):(log$e.info(`Building ${E.length} sub time ranges`),{decodersAsMap:_,queryOptions:E.map(([x,T])=>({pubsubTopic:v,contentTopics:w,includeData:!0,paginationForward:!0,...h,timeStart:x,timeEnd:T}))})}}const log$d=new Logger$1("wait-for-remote-peer");async function waitForRemotePeer(y,u,h){u=u!=null&&u.length?u:getEnabledProtocols(y);const b=y.libp2p.getConnections();if(!y.isStarted())throw Error("Waku node is not started");for(const w of u)switch(w){case Protocols.Relay:if(!y.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");break;case Protocols.LightPush:if(!y.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");break;case Protocols.Store:if(!y.store)throw Error("Cannot wait for Store peer: protocol not mounted");break;case Protocols.Filter:if(!y.filter)throw Error("Cannot wait for Filter peer: protocol not mounted");break}const v=[waitForProtocols(y,u)];b.length>0&&!u.includes(Protocols.Relay)&&v.push(waitForMetadata(y,u)),h?await rejectOnTimeout(Promise.any(v),h,"Timed out waiting for a remote peer."):await Promise.any(v)}function protocolToPeerPromise(y,u){return y.map(h=>waitForConnectedPeer(h,u))}async function waitForProtocols(y,u){const h=[];if(y.relay&&u.includes(Protocols.Relay)&&h.push(y.relay.waitForPeers()),y.store&&u.includes(Protocols.Store)&&h.push(...protocolToPeerPromise([StoreCodec],y.libp2p)),y.lightPush&&u.includes(Protocols.LightPush)){const b=protocolToPeerPromise([LightPushCodec,LightPushCodecV2],y.libp2p);h.push(Promise.any(b))}return y.filter&&u.includes(Protocols.Filter)&&h.push(...protocolToPeerPromise([FilterCodecs.SUBSCRIBE],y.libp2p)),Promise.all(h)}async function waitForConnectedPeer(y,u){log$d.info(`Waiting for ${y} peer.`),await new Promise(h=>{const b=async v=>{var w,_;if((_=(w=v.detail)==null?void 0:w.protocols)!=null&&_.includes(y)){const E=u.services.metadata;if(!E){u.removeEventListener("peer:identify",b),h();return}try{await E.confirmOrAttemptHandshake(v.detail.peerId),u.removeEventListener("peer:identify",b),h()}catch(S){S.code==="ERR_CONNECTION_BEING_CLOSED"&&log$d.error("Connection closed. Some peers can be on different shard."),log$d.error(`Error waiting for metadata: ${S}`)}}};u.addEventListener("peer:identify",b)})}async function waitForMetadata(y,u){const h=y.libp2p.getPeers(),b=y.libp2p.services.metadata,v=mapProtocolsToCodecs(u);if(!h.length||!b){log$d.info(`Skipping waitForMetadata due to missing connections:${h.length} or metadataService:${!!b}`);return}for(const w of h)try{const _=await y.libp2p.peerStore.get(w);if(_.protocols.some(S=>v.has(S))&&!(await b.confirmOrAttemptHandshake(w)).error&&(_.protocols.forEach(T=>{v.has(T)&&v.set(T,!0)}),Array.from(v.values()).every(T=>T)))return}catch(_){_.code==="ERR_CONNECTION_BEING_CLOSED"&&log$d.error("Connection closed. Some peers can be on different shard."),log$d.error(`Error while iterating through peers: ${_}`);continue}}const awaitTimeout=(y,u)=>new Promise((h,b)=>setTimeout(()=>b(Error(u)),y));async function rejectOnTimeout(y,u,h){await Promise.race([y,awaitTimeout(u,h)])}function getEnabledProtocols(y){const u=[];return y.relay&&u.push(Protocols.Relay),y.filter&&u.push(Protocols.Filter),y.store&&u.push(Protocols.Store),y.lightPush&&u.push(Protocols.LightPush),u}function mapProtocolsToCodecs(y){const u=new Map,h={[Protocols.Filter]:[FilterCodecs.SUBSCRIBE],[Protocols.LightPush]:[LightPushCodec,LightPushCodecV2],[Protocols.Store]:[StoreCodec]};for(const b of y)h[b]&&h[b].forEach(v=>{u.set(v,!1)});return u}const log$c=new Logger$1("sdk:waku");class WakuNode{constructor(u,h,b,v){Z(this,"libp2p");Z(this,"relay");Z(this,"store");Z(this,"filter");Z(this,"lightPush");Z(this,"events",new TypedEventEmitter);Z(this,"networkConfig");Z(this,"_nodeStateLock",!1);Z(this,"_nodeStarted",!1);Z(this,"connectionManager");Z(this,"peerManager");Z(this,"healthIndicator");this.relay=v,this.libp2p=h,this.networkConfig=u.networkConfig||DefaultNetworkConfig,b={filter:!1,lightpush:!1,store:!1,...b};const w=this.libp2p.peerId.toString();this.connectionManager=new ConnectionManager({libp2p:h,relay:this.relay,events:this.events,networkConfig:this.networkConfig,config:u==null?void 0:u.connectionManager}),this.peerManager=new PeerManager({libp2p:h,config:{numPeersToUse:u.numPeersToUse},connectionManager:this.connectionManager}),this.healthIndicator=new HealthIndicator({libp2p:h,events:this.events}),b.store&&(this.store=new Store({libp2p:h,peerManager:this.peerManager,options:u==null?void 0:u.store})),b.lightpush&&(this.lightPush=new LightPush({libp2p:h,peerManager:this.peerManager,options:u==null?void 0:u.lightPush})),b.filter&&(this.filter=new Filter({libp2p:h,peerManager:this.peerManager,options:u.filter})),log$c.info("Waku node created",w,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}get health(){return this.healthIndicator.toValue()}async dial(u,h){const b=h??[];typeof h>"u"&&(this.relay&&b.push(Protocols.Relay),this.store&&b.push(Protocols.Store),this.filter&&b.push(Protocols.Filter),this.lightPush&&b.push(Protocols.LightPush));const v=[];return b.includes(Protocols.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach(w=>v.push(w)):log$c.error("Relay codec not included in dial codec: protocol not mounted locally")),b.includes(Protocols.Store)&&(this.store?v.push(this.store.multicodec):log$c.error("Store codec not included in dial codec: protocol not mounted locally")),b.includes(Protocols.LightPush)&&(this.lightPush?v.push(...this.lightPush.multicodec):log$c.error("Light Push codec not included in dial codec: protocol not mounted locally")),b.includes(Protocols.Filter)&&(this.filter?v.push(this.filter.multicodec):log$c.error("Filter codec not included in dial codec: protocol not mounted locally")),log$c.info(`Dialing to ${u==null?void 0:u.toString()} with protocols ${b}`),await this.connectionManager.dial(u,v)}async hangUp(u){return log$c.info(`Hanging up peer:${u==null?void 0:u.toString()}.`),this.connectionManager.hangUp(u)}async start(){var u,h;this._nodeStateLock||this.isStarted()||(this._nodeStateLock=!0,await this.libp2p.start(),await((u=this.filter)==null?void 0:u.start()),this.connectionManager.start(),this.peerManager.start(),this.healthIndicator.start(),(h=this.lightPush)==null||h.start(),this._nodeStateLock=!1,this._nodeStarted=!0)}async stop(){var u,h;this._nodeStateLock||!this.isStarted()||(this._nodeStateLock=!0,(u=this.lightPush)==null||u.stop(),await((h=this.filter)==null?void 0:h.stop()),this.healthIndicator.stop(),this.peerManager.stop(),this.connectionManager.stop(),await this.libp2p.stop(),this._nodeStateLock=!1,this._nodeStarted=!1)}async getConnectedPeers(){return this.connectionManager.getConnectedPeers()}async waitForPeers(u,h){return waitForRemotePeer(this,u,h)}isStarted(){return this._nodeStarted&&this.libp2p.status==="started"}isConnected(){return this.connectionManager.isConnected()}createDecoder(u){const h=this.createRoutingInfo(u.contentTopic,u.shardId);return createDecoder(u.contentTopic,h)}createEncoder(u){const h=this.createRoutingInfo(u.contentTopic,u.shardId);return createEncoder({contentTopic:u.contentTopic,ephemeral:u.ephemeral,routingInfo:h})}createRoutingInfo(u,h){return createRoutingInfo(this.networkConfig,{contentTopic:u,shardId:h})}}const MAX_LENGTH_LENGTH=8,MAX_DATA_LENGTH=1024*1024*4;let InvalidMessageLengthError$1=class extends Error{constructor(){super(...arguments);Z(this,"name","InvalidMessageLengthError");Z(this,"code","ERR_INVALID_MSG_LENGTH")}},InvalidDataLengthError$1=class extends Error{constructor(){super(...arguments);Z(this,"name","InvalidDataLengthError");Z(this,"code","ERR_MSG_DATA_TOO_LONG")}},InvalidDataLengthLengthError$1=class extends Error{constructor(){super(...arguments);Z(this,"name","InvalidDataLengthLengthError");Z(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},UnexpectedEOFError$1=class extends Error{constructor(){super(...arguments);Z(this,"name","UnexpectedEOFError");Z(this,"code","ERR_UNEXPECTED_EOF")}};function isAsyncIterable$4(y){return y[Symbol.asyncIterator]!=null}function validateMaxDataLength(y,u){if(y.byteLength>u)throw new InvalidDataLengthError$1("Message length too long")}const defaultEncoder=y=>{const u=encodingLength$1(y),h=allocUnsafe(u);return encode$8(y,h),defaultEncoder.bytes=u,h};defaultEncoder.bytes=0;function encode$2(y,u){u=u??{};const h=u.lengthEncoder??defaultEncoder,b=(u==null?void 0:u.maxDataLength)??MAX_DATA_LENGTH;function*v(w){validateMaxDataLength(w,b);const _=h(w.byteLength);_ instanceof Uint8Array?yield _:yield*_,w instanceof Uint8Array?yield w:yield*w}return isAsyncIterable$4(y)?async function*(){for await(const w of y)yield*v(w)}():function*(){for(const w of y)yield*v(w)}()}encode$2.single=(y,u)=>{u=u??{};const h=u.lengthEncoder??defaultEncoder,b=(u==null?void 0:u.maxDataLength)??MAX_DATA_LENGTH;return validateMaxDataLength(y,b),new Uint8ArrayList(h(y.byteLength),y)};var ReadMode;(function(y){y[y.LENGTH=0]="LENGTH",y[y.DATA=1]="DATA"})(ReadMode||(ReadMode={}));const defaultDecoder=y=>{const u=decode$8(y);return defaultDecoder.bytes=encodingLength$1(u),u};defaultDecoder.bytes=0;function decode$1(y,u){const h=new Uint8ArrayList;let b=ReadMode.LENGTH,v=-1;const w=(u==null?void 0:u.lengthDecoder)??defaultDecoder,_=(u==null?void 0:u.maxLengthLength)??MAX_LENGTH_LENGTH,E=(u==null?void 0:u.maxDataLength)??MAX_DATA_LENGTH;function*S(){for(;h.byteLength>0;){if(b===ReadMode.LENGTH)try{if(v=w(h),v<0)throw new InvalidMessageLengthError$1("Invalid message length");if(v>E)throw new InvalidDataLengthError$1("Message length too long");const x=w.bytes;h.consume(x),(u==null?void 0:u.onLength)!=null&&u.onLength(v),b=ReadMode.DATA}catch(x){if(x instanceof RangeError){if(h.byteLength>_)throw new InvalidDataLengthLengthError$1("Message length length too long");break}throw x}if(b===ReadMode.DATA){if(h.byteLength<v)break;const x=h.sublist(0,v);h.consume(v),(u==null?void 0:u.onData)!=null&&u.onData(x),yield x,b=ReadMode.LENGTH}}}return isAsyncIterable$4(y)?async function*(){for await(const x of y)h.append(x),yield*S();if(h.byteLength>0)throw new UnexpectedEOFError$1("Unexpected end of input")}():function*(){for(const x of y)h.append(x),yield*S();if(h.byteLength>0)throw new UnexpectedEOFError$1("Unexpected end of input")}()}decode$1.fromReader=(y,u)=>{let h=1;const b=async function*(){for(;;)try{const{done:w,value:_}=await y.next(h);if(w===!0)return;_!=null&&(yield _)}catch(w){if(w.code==="ERR_UNDER_READ")return{done:!0,value:null};throw w}finally{h=1}}();return decode$1(b,{...u??{},onLength:w=>{h=w}})};class UnexpectedEOFError extends Error{constructor(){super(...arguments);Z(this,"name","UnexpectedEOFError");Z(this,"code","ERR_UNEXPECTED_EOF")}}function byteStream(y,u){const h=queuelessPushable();y.sink(h).catch(async _=>{await h.end(_)}),y.sink=async _=>{for await(const E of _)await h.push(E);await h.end()};let b=y.source;y.source[Symbol.iterator]!=null?b=y.source[Symbol.iterator]():y.source[Symbol.asyncIterator]!=null&&(b=y.source[Symbol.asyncIterator]());const v=new Uint8ArrayList;return{read:async _=>{var S;if((S=_==null?void 0:_.signal)==null||S.throwIfAborted(),(_==null?void 0:_.bytes)==null){const{done:x,value:T}=await raceSignal(b.next(),_==null?void 0:_.signal);return x===!0?null:T}for(;v.byteLength<_.bytes;){const{value:x,done:T}=await raceSignal(b.next(),_==null?void 0:_.signal);if(T===!0)throw new UnexpectedEOFError("unexpected end of input");v.append(x)}const E=v.sublist(0,_.bytes);return v.consume(_.bytes),E},write:async(_,E)=>{var S;(S=E==null?void 0:E.signal)==null||S.throwIfAborted(),_ instanceof Uint8Array?await h.push(_,E):await h.push(_.subarray(),E)},unwrap:()=>{if(v.byteLength>0){const _=y.source;y.source=async function*(){(u==null?void 0:u.yieldBytes)===!1?yield v:yield*v,yield*_}()}return y}}}class InvalidMessageLengthError extends Error{constructor(){super(...arguments);Z(this,"name","InvalidMessageLengthError");Z(this,"code","ERR_INVALID_MSG_LENGTH")}}class InvalidDataLengthError extends Error{constructor(){super(...arguments);Z(this,"name","InvalidDataLengthError");Z(this,"code","ERR_MSG_DATA_TOO_LONG")}}class InvalidDataLengthLengthError extends Error{constructor(){super(...arguments);Z(this,"name","InvalidDataLengthLengthError");Z(this,"code","ERR_MSG_LENGTH_TOO_LONG")}}function lpStream(y,u={}){const h=byteStream(y,u);u.maxDataLength!=null&&u.maxLengthLength==null&&(u.maxLengthLength=encodingLength$1(u.maxDataLength));const b=(u==null?void 0:u.lengthDecoder)??decode$8,v=(u==null?void 0:u.lengthEncoder)??encode$8;return{read:async _=>{let E=-1;const S=new Uint8ArrayList;for(;;){S.append(await h.read({..._,bytes:1}));try{E=b(S)}catch(x){if(x instanceof RangeError)continue;throw x}if(E<0)throw new InvalidMessageLengthError("Invalid message length");if((u==null?void 0:u.maxLengthLength)!=null&&S.byteLength>u.maxLengthLength)throw new InvalidDataLengthLengthError("message length length too long");if(E>-1)break}if((u==null?void 0:u.maxDataLength)!=null&&E>u.maxDataLength)throw new InvalidDataLengthError("message length too long");return h.read({..._,bytes:E})},write:async(_,E)=>{await h.write(new Uint8ArrayList(v(_.byteLength),_),E)},writeV:async(_,E)=>{const S=new Uint8ArrayList(..._.flatMap(x=>[v(x.byteLength),x]));await h.write(S,E)},unwrap:()=>h.unwrap()}}function pair(){const y=pDefer();let u=!1;return{sink:async h=>{if(u)throw new Error("already piped");u=!0,y.resolve(h)},source:async function*(){yield*await y.promise}()}}function duplexPair(){const y=pair(),u=pair();return[{source:y.source,sink:u.sink},{source:u.source,sink:y.sink}]}const NOISE_MSG_MAX_LENGTH_BYTES=65535,NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG=NOISE_MSG_MAX_LENGTH_BYTES-16;var Yd,Jd;const DUMP_SESSION_KEYS=!!((Jd=(Yd=globalThis.process)==null?void 0:Yd.env)!=null&&Jd.DUMP_SESSION_KEYS);/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function isBytes$2(y){return y instanceof Uint8Array||ArrayBuffer.isView(y)&&y.constructor.name==="Uint8Array"}function abool(y){if(typeof y!="boolean")throw new Error(`boolean expected, not ${y}`)}function anumber(y){if(!Number.isSafeInteger(y)||y<0)throw new Error("positive integer expected, got "+y)}function abytes$1(y,...u){if(!isBytes$2(y))throw new Error("Uint8Array expected");if(u.length>0&&!u.includes(y.length))throw new Error("Uint8Array expected of length "+u+", got length="+y.length)}function aexists(y,u=!0){if(y.destroyed)throw new Error("Hash instance has been destroyed");if(u&&y.finished)throw new Error("Hash#digest() has already been called")}function aoutput(y,u){abytes$1(y);const h=u.outputLen;if(y.length<h)throw new Error("digestInto() expects output buffer of length at least "+h)}function u32(y){return new Uint32Array(y.buffer,y.byteOffset,Math.floor(y.byteLength/4))}function clean(...y){for(let u=0;u<y.length;u++)y[u].fill(0)}function createView(y){return new DataView(y.buffer,y.byteOffset,y.byteLength)}const isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function utf8ToBytes(y){if(typeof y!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(y))}function toBytes(y){if(typeof y=="string")y=utf8ToBytes(y);else if(isBytes$2(y))y=copyBytes(y);else throw new Error("Uint8Array expected, got "+typeof y);return y}function checkOpts(y,u){if(u==null||typeof u!="object")throw new Error("options must be defined");return Object.assign(y,u)}function equalBytes(y,u){if(y.length!==u.length)return!1;let h=0;for(let b=0;b<y.length;b++)h|=y[b]^u[b];return h===0}const wrapCipher=(y,u)=>{function h(b,...v){if(abytes$1(b),!isLE)throw new Error("Non little-endian hardware is not yet supported");if(y.nonceLength!==void 0){const T=v[0];if(!T)throw new Error("nonce / iv required");y.varSizeNonce?abytes$1(T):abytes$1(T,y.nonceLength)}const w=y.tagLength;w&&v[1]!==void 0&&abytes$1(v[1]);const _=u(b,...v),E=(T,C)=>{if(C!==void 0){if(T!==2)throw new Error("cipher output not supported");abytes$1(C)}};let S=!1;return{encrypt(T,C){if(S)throw new Error("cannot encrypt() twice with same key + nonce");return S=!0,abytes$1(T),E(_.encrypt.length,C),_.encrypt(T,C)},decrypt(T,C){if(abytes$1(T),w&&T.length<w)throw new Error("invalid ciphertext length: smaller than tagLength="+w);return E(_.decrypt.length,C),_.decrypt(T,C)}}}return Object.assign(h,y),h};function getOutput(y,u,h=!0){if(u===void 0)return new Uint8Array(y);if(u.length!==y)throw new Error("invalid output length, expected "+y+", got: "+u.length);if(h&&!isAligned32$1(u))throw new Error("invalid output, must be aligned");return u}function setBigUint64(y,u,h,b){if(typeof y.setBigUint64=="function")return y.setBigUint64(u,h,b);const v=BigInt(32),w=BigInt(4294967295),_=Number(h>>v&w),E=Number(h&w),S=4,x=0;y.setUint32(u+S,_,b),y.setUint32(u+x,E,b)}function u64Lengths(y,u,h){abool(h);const b=new Uint8Array(16),v=createView(b);return setBigUint64(v,0,BigInt(u),h),setBigUint64(v,8,BigInt(y),h),b}function isAligned32$1(y){return y.byteOffset%4===0}function copyBytes(y){return Uint8Array.from(y)}const _utf8ToBytes=y=>Uint8Array.from(y.split("").map(u=>u.charCodeAt(0))),sigma16=_utf8ToBytes("expand 16-byte k"),sigma32=_utf8ToBytes("expand 32-byte k"),sigma16_32=u32(sigma16),sigma32_32=u32(sigma32);function rotl$2(y,u){return y<<u|y>>>32-u}function isAligned32(y){return y.byteOffset%4===0}const BLOCK_LEN=64,BLOCK_LEN32=16,MAX_COUNTER=2**32-1,U32_EMPTY=new Uint32Array;function runCipher(y,u,h,b,v,w,_,E){const S=v.length,x=new Uint8Array(BLOCK_LEN),T=u32(x),C=isAligned32(v)&&isAligned32(w),O=C?u32(v):U32_EMPTY,D=C?u32(w):U32_EMPTY;for(let U=0;U<S;_++){if(y(u,h,b,T,_,E),_>=MAX_COUNTER)throw new Error("arx: counter overflow");const te=Math.min(BLOCK_LEN,S-U);if(C&&te===BLOCK_LEN){const X=U/4;if(U%4!==0)throw new Error("arx: invalid block position");for(let ie=0,ee;ie<BLOCK_LEN32;ie++)ee=X+ie,D[ee]=O[ee]^T[ie];U+=BLOCK_LEN;continue}for(let X=0,ie;X<te;X++)ie=U+X,w[ie]=v[ie]^x[X];U+=te}}function createCipher$2(y,u){const{allowShortKeys:h,extendNonceFn:b,counterLength:v,counterRight:w,rounds:_}=checkOpts({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},u);if(typeof y!="function")throw new Error("core must be a function");return anumber(v),anumber(_),abool(w),abool(h),(E,S,x,T,C=0)=>{abytes$1(E),abytes$1(S),abytes$1(x);const O=x.length;if(T===void 0&&(T=new Uint8Array(O)),abytes$1(T),anumber(C),C<0||C>=MAX_COUNTER)throw new Error("arx: counter overflow");if(T.length<O)throw new Error(`arx: output (${T.length}) is shorter than data (${O})`);const D=[];let U=E.length,te,X;if(U===32)D.push(te=copyBytes(E)),X=sigma32_32;else if(U===16&&h)te=new Uint8Array(32),te.set(E),te.set(E,16),X=sigma16_32,D.push(te);else throw new Error(`arx: invalid 32-byte key, got length=${U}`);isAligned32(S)||D.push(S=copyBytes(S));const ie=u32(te);if(b){if(S.length!==24)throw new Error("arx: extended nonce must be 24 bytes");b(X,ie,u32(S.subarray(0,16)),ie),S=S.subarray(16)}const ee=16-v;if(ee!==S.length)throw new Error(`arx: nonce must be ${ee} or 16 bytes`);if(ee!==12){const de=new Uint8Array(12);de.set(S,w?0:12-S.length),S=de,D.push(S)}const ae=u32(S);return runCipher(y,X,ie,ae,x,T,C,_),clean(...D),T}}const u8to16=(y,u)=>y[u++]&255|(y[u++]&255)<<8;class Poly1305{constructor(u){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,u=toBytes(u),abytes$1(u,32);const h=u8to16(u,0),b=u8to16(u,2),v=u8to16(u,4),w=u8to16(u,6),_=u8to16(u,8),E=u8to16(u,10),S=u8to16(u,12),x=u8to16(u,14);this.r[0]=h&8191,this.r[1]=(h>>>13|b<<3)&8191,this.r[2]=(b>>>10|v<<6)&7939,this.r[3]=(v>>>7|w<<9)&8191,this.r[4]=(w>>>4|_<<12)&255,this.r[5]=_>>>1&8190,this.r[6]=(_>>>14|E<<2)&8191,this.r[7]=(E>>>11|S<<5)&8065,this.r[8]=(S>>>8|x<<8)&8191,this.r[9]=x>>>5&127;for(let T=0;T<8;T++)this.pad[T]=u8to16(u,16+2*T)}process(u,h,b=!1){const v=b?0:2048,{h:w,r:_}=this,E=_[0],S=_[1],x=_[2],T=_[3],C=_[4],O=_[5],D=_[6],U=_[7],te=_[8],X=_[9],ie=u8to16(u,h+0),ee=u8to16(u,h+2),ae=u8to16(u,h+4),de=u8to16(u,h+6),Se=u8to16(u,h+8),ve=u8to16(u,h+10),Pe=u8to16(u,h+12),Ie=u8to16(u,h+14);let Ee=w[0]+(ie&8191),De=w[1]+((ie>>>13|ee<<3)&8191),be=w[2]+((ee>>>10|ae<<6)&8191),B=w[3]+((ae>>>7|de<<9)&8191),F=w[4]+((de>>>4|Se<<12)&8191),M=w[5]+(Se>>>1&8191),N=w[6]+((Se>>>14|ve<<2)&8191),Q=w[7]+((ve>>>11|Pe<<5)&8191),j=w[8]+((Pe>>>8|Ie<<8)&8191),ne=w[9]+(Ie>>>5|v),J=0,q=J+Ee*E+De*(5*X)+be*(5*te)+B*(5*U)+F*(5*D);J=q>>>13,q&=8191,q+=M*(5*O)+N*(5*C)+Q*(5*T)+j*(5*x)+ne*(5*S),J+=q>>>13,q&=8191;let re=J+Ee*S+De*E+be*(5*X)+B*(5*te)+F*(5*U);J=re>>>13,re&=8191,re+=M*(5*D)+N*(5*O)+Q*(5*C)+j*(5*T)+ne*(5*x),J+=re>>>13,re&=8191;let H=J+Ee*x+De*S+be*E+B*(5*X)+F*(5*te);J=H>>>13,H&=8191,H+=M*(5*U)+N*(5*D)+Q*(5*O)+j*(5*C)+ne*(5*T),J+=H>>>13,H&=8191;let he=J+Ee*T+De*x+be*S+B*E+F*(5*X);J=he>>>13,he&=8191,he+=M*(5*te)+N*(5*U)+Q*(5*D)+j*(5*O)+ne*(5*C),J+=he>>>13,he&=8191;let Oe=J+Ee*C+De*T+be*x+B*S+F*E;J=Oe>>>13,Oe&=8191,Oe+=M*(5*X)+N*(5*te)+Q*(5*U)+j*(5*D)+ne*(5*O),J+=Oe>>>13,Oe&=8191;let Ne=J+Ee*O+De*C+be*T+B*x+F*S;J=Ne>>>13,Ne&=8191,Ne+=M*E+N*(5*X)+Q*(5*te)+j*(5*U)+ne*(5*D),J+=Ne>>>13,Ne&=8191;let Ae=J+Ee*D+De*O+be*C+B*T+F*x;J=Ae>>>13,Ae&=8191,Ae+=M*S+N*E+Q*(5*X)+j*(5*te)+ne*(5*U),J+=Ae>>>13,Ae&=8191;let le=J+Ee*U+De*D+be*O+B*C+F*T;J=le>>>13,le&=8191,le+=M*x+N*S+Q*E+j*(5*X)+ne*(5*te),J+=le>>>13,le&=8191;let me=J+Ee*te+De*U+be*D+B*O+F*C;J=me>>>13,me&=8191,me+=M*T+N*x+Q*S+j*E+ne*(5*X),J+=me>>>13,me&=8191;let Me=J+Ee*X+De*te+be*U+B*D+F*O;J=Me>>>13,Me&=8191,Me+=M*C+N*T+Q*x+j*S+ne*E,J+=Me>>>13,Me&=8191,J=(J<<2)+J|0,J=J+q|0,q=J&8191,J=J>>>13,re+=J,w[0]=q,w[1]=re,w[2]=H,w[3]=he,w[4]=Oe,w[5]=Ne,w[6]=Ae,w[7]=le,w[8]=me,w[9]=Me}finalize(){const{h:u,pad:h}=this,b=new Uint16Array(10);let v=u[1]>>>13;u[1]&=8191;for(let E=2;E<10;E++)u[E]+=v,v=u[E]>>>13,u[E]&=8191;u[0]+=v*5,v=u[0]>>>13,u[0]&=8191,u[1]+=v,v=u[1]>>>13,u[1]&=8191,u[2]+=v,b[0]=u[0]+5,v=b[0]>>>13,b[0]&=8191;for(let E=1;E<10;E++)b[E]=u[E]+v,v=b[E]>>>13,b[E]&=8191;b[9]-=8192;let w=(v^1)-1;for(let E=0;E<10;E++)b[E]&=w;w=~w;for(let E=0;E<10;E++)u[E]=u[E]&w|b[E];u[0]=(u[0]|u[1]<<13)&65535,u[1]=(u[1]>>>3|u[2]<<10)&65535,u[2]=(u[2]>>>6|u[3]<<7)&65535,u[3]=(u[3]>>>9|u[4]<<4)&65535,u[4]=(u[4]>>>12|u[5]<<1|u[6]<<14)&65535,u[5]=(u[6]>>>2|u[7]<<11)&65535,u[6]=(u[7]>>>5|u[8]<<8)&65535,u[7]=(u[8]>>>8|u[9]<<5)&65535;let _=u[0]+h[0];u[0]=_&65535;for(let E=1;E<8;E++)_=(u[E]+h[E]|0)+(_>>>16)|0,u[E]=_&65535;clean(b)}update(u){aexists(this),u=toBytes(u),abytes$1(u);const{buffer:h,blockLen:b}=this,v=u.length;for(let w=0;w<v;){const _=Math.min(b-this.pos,v-w);if(_===b){for(;b<=v-w;w+=b)this.process(u,w);continue}h.set(u.subarray(w,w+_),this.pos),this.pos+=_,w+=_,this.pos===b&&(this.process(h,0,!1),this.pos=0)}return this}destroy(){clean(this.h,this.r,this.buffer,this.pad)}digestInto(u){aexists(this),aoutput(u,this),this.finished=!0;const{buffer:h,h:b}=this;let{pos:v}=this;if(v){for(h[v++]=1;v<16;v++)h[v]=0;this.process(h,0,!0)}this.finalize();let w=0;for(let _=0;_<8;_++)u[w++]=b[_]>>>0,u[w++]=b[_]>>>8;return u}digest(){const{buffer:u,outputLen:h}=this;this.digestInto(u);const b=u.slice(0,h);return this.destroy(),b}}function wrapConstructorWithKey(y){const u=(b,v)=>y(v).update(toBytes(b)).digest(),h=y(new Uint8Array(32));return u.outputLen=h.outputLen,u.blockLen=h.blockLen,u.create=b=>y(b),u}const poly1305=wrapConstructorWithKey(y=>new Poly1305(y));function chachaCore(y,u,h,b,v,w=20){let _=y[0],E=y[1],S=y[2],x=y[3],T=u[0],C=u[1],O=u[2],D=u[3],U=u[4],te=u[5],X=u[6],ie=u[7],ee=v,ae=h[0],de=h[1],Se=h[2],ve=_,Pe=E,Ie=S,Ee=x,De=T,be=C,B=O,F=D,M=U,N=te,Q=X,j=ie,ne=ee,J=ae,q=de,re=Se;for(let he=0;he<w;he+=2)ve=ve+De|0,ne=rotl$2(ne^ve,16),M=M+ne|0,De=rotl$2(De^M,12),ve=ve+De|0,ne=rotl$2(ne^ve,8),M=M+ne|0,De=rotl$2(De^M,7),Pe=Pe+be|0,J=rotl$2(J^Pe,16),N=N+J|0,be=rotl$2(be^N,12),Pe=Pe+be|0,J=rotl$2(J^Pe,8),N=N+J|0,be=rotl$2(be^N,7),Ie=Ie+B|0,q=rotl$2(q^Ie,16),Q=Q+q|0,B=rotl$2(B^Q,12),Ie=Ie+B|0,q=rotl$2(q^Ie,8),Q=Q+q|0,B=rotl$2(B^Q,7),Ee=Ee+F|0,re=rotl$2(re^Ee,16),j=j+re|0,F=rotl$2(F^j,12),Ee=Ee+F|0,re=rotl$2(re^Ee,8),j=j+re|0,F=rotl$2(F^j,7),ve=ve+be|0,re=rotl$2(re^ve,16),Q=Q+re|0,be=rotl$2(be^Q,12),ve=ve+be|0,re=rotl$2(re^ve,8),Q=Q+re|0,be=rotl$2(be^Q,7),Pe=Pe+B|0,ne=rotl$2(ne^Pe,16),j=j+ne|0,B=rotl$2(B^j,12),Pe=Pe+B|0,ne=rotl$2(ne^Pe,8),j=j+ne|0,B=rotl$2(B^j,7),Ie=Ie+F|0,J=rotl$2(J^Ie,16),M=M+J|0,F=rotl$2(F^M,12),Ie=Ie+F|0,J=rotl$2(J^Ie,8),M=M+J|0,F=rotl$2(F^M,7),Ee=Ee+De|0,q=rotl$2(q^Ee,16),N=N+q|0,De=rotl$2(De^N,12),Ee=Ee+De|0,q=rotl$2(q^Ee,8),N=N+q|0,De=rotl$2(De^N,7);let H=0;b[H++]=_+ve|0,b[H++]=E+Pe|0,b[H++]=S+Ie|0,b[H++]=x+Ee|0,b[H++]=T+De|0,b[H++]=C+be|0,b[H++]=O+B|0,b[H++]=D+F|0,b[H++]=U+M|0,b[H++]=te+N|0,b[H++]=X+Q|0,b[H++]=ie+j|0,b[H++]=ee+ne|0,b[H++]=ae+J|0,b[H++]=de+q|0,b[H++]=Se+re|0}const chacha20=createCipher$2(chachaCore,{counterRight:!1,counterLength:4,allowShortKeys:!1}),ZEROS16=new Uint8Array(16),updatePadded=(y,u)=>{y.update(u);const h=u.length%16;h&&y.update(ZEROS16.subarray(h))},ZEROS32=new Uint8Array(32);function computeTag(y,u,h,b,v){const w=y(u,h,ZEROS32),_=poly1305.create(w);v&&updatePadded(_,v),updatePadded(_,b);const E=u64Lengths(b.length,v?v.length:0,!0);_.update(E);const S=_.digest();return clean(w,E),S}const _poly1305_aead=y=>(u,h,b)=>({encrypt(w,_){const E=w.length;_=getOutput(E+16,_,!1),_.set(w);const S=_.subarray(0,-16);y(u,h,S,S,1);const x=computeTag(y,u,h,S,b);return _.set(x,E),clean(x),_},decrypt(w,_){_=getOutput(w.length-16,_,!1);const E=w.subarray(0,-16),S=w.subarray(-16),x=computeTag(y,u,h,E,b);if(!equalBytes(S,x))throw new Error("invalid tag");return _.set(w.subarray(0,-16)),y(u,h,_,_,1),clean(x),_}}),chacha20poly1305=wrapCipher({blockSize:64,nonceLength:12,tagLength:16},_poly1305_aead(chacha20));function extract(y,u,h){return ahash(y),h===void 0&&(h=new Uint8Array(y.outputLen)),hmac$1(y,toBytes$1(h),toBytes$1(u))}const HKDF_COUNTER=Uint8Array.from([0]),EMPTY_BUFFER=Uint8Array.of();function expand(y,u,h,b=32){ahash(y),anumber$1(b);const v=y.outputLen;if(b>255*v)throw new Error("Length should be <= 255*HashLen");const w=Math.ceil(b/v);h===void 0&&(h=EMPTY_BUFFER);const _=new Uint8Array(w*v),E=hmac$1.create(y,u),S=E._cloneInto(),x=new Uint8Array(E.outputLen);for(let T=0;T<w;T++)HKDF_COUNTER[0]=T+1,S.update(T===0?EMPTY_BUFFER:x).update(h).update(HKDF_COUNTER).digestInto(x),_.set(x,v*T),E._cloneInto(S);return E.destroy(),S.destroy(),clean$1(x,HKDF_COUNTER),_.slice(0,b)}const pureJsCrypto={hashSHA256(y){return sha256$2(y.subarray())},getHKDF(y,u){const h=extract(sha256$2,u,y),v=expand(sha256$2,h,void 0,96),w=v.subarray(0,32),_=v.subarray(32,64),E=v.subarray(64,96);return[w,_,E]},generateX25519KeyPair(){const y=x25519.utils.randomPrivateKey();return{publicKey:x25519.getPublicKey(y),privateKey:y}},generateX25519KeyPairFromSeed(y){return{publicKey:x25519.getPublicKey(y),privateKey:y}},generateX25519SharedKey(y,u){return x25519.getSharedSecret(y.subarray(),u.subarray())},chaCha20Poly1305Encrypt(y,u,h,b){return chacha20poly1305(b,u,h).encrypt(y.subarray())},chaCha20Poly1305Decrypt(y,u,h,b,v){return chacha20poly1305(b,u,h).decrypt(y.subarray(),v)}},defaultCrypto=pureJsCrypto;function wrapCrypto(y){return{generateKeypair:y.generateX25519KeyPair,dh:(u,h)=>y.generateX25519SharedKey(u.privateKey,h).subarray(0,32),encrypt:y.chaCha20Poly1305Encrypt,decrypt:y.chaCha20Poly1305Decrypt,hash:y.hashSHA256,hkdf:y.getHKDF}}const uint16BEEncode=y=>{const u=allocUnsafe(2);return u[0]=y>>8,u[1]=y,u};uint16BEEncode.bytes=2;const uint16BEDecode=y=>{if(y.length<2)throw RangeError("Could not decode int16BE");if(y instanceof Uint8Array){let u=0;return u+=y[0]<<8,u+=y[1],u}return y.getUint16(0)};uint16BEDecode.bytes=2;function registerMetrics(y){return{xxHandshakeSuccesses:y.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:y.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:y.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:y.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:y.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function logLocalStaticKeys(y,u){!u.enabled||!DUMP_SESSION_KEYS||(y?(u(`LOCAL_STATIC_PUBLIC_KEY ${toString$1(y.publicKey,"hex")}`),u(`LOCAL_STATIC_PRIVATE_KEY ${toString$1(y.privateKey,"hex")}`)):u("Missing local static keys."))}function logLocalEphemeralKeys(y,u){!u.enabled||!DUMP_SESSION_KEYS||(y?(u(`LOCAL_PUBLIC_EPHEMERAL_KEY ${toString$1(y.publicKey,"hex")}`),u(`LOCAL_PRIVATE_EPHEMERAL_KEY ${toString$1(y.privateKey,"hex")}`)):u("Missing local ephemeral keys."))}function logRemoteStaticKey(y,u){!u.enabled||!DUMP_SESSION_KEYS||u(y?`REMOTE_STATIC_PUBLIC_KEY ${toString$1(y.subarray(),"hex")}`:"Missing remote static public key.")}function logRemoteEphemeralKey(y,u){!u.enabled||!DUMP_SESSION_KEYS||u(y?`REMOTE_EPHEMERAL_PUBLIC_KEY ${toString$1(y.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function logCipherState(y,u,h){!h.enabled||!DUMP_SESSION_KEYS||(h(`CIPHER_STATE_1 ${y.n.getUint64()} ${y.k&&toString$1(y.k,"hex")}`),h(`CIPHER_STATE_2 ${u.n.getUint64()} ${u.k&&toString$1(u.k,"hex")}`))}const Ku=class Ku extends Error{constructor(h="Invalid crypto exchange"){super(h);Z(this,"code");this.code=Ku.code}};Z(Ku,"code","ERR_INVALID_CRYPTO_EXCHANGE");let InvalidCryptoExchangeError=Ku;const MIN_NONCE=0,MAX_NONCE=4294967295,ERR_MAX_NONCE="Cipherstate has reached maximum n, a new handshake must be performed";class Nonce{constructor(u=MIN_NONCE){Z(this,"n");Z(this,"bytes");Z(this,"view");this.n=u,this.bytes=alloc$1(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,u,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>MAX_NONCE)throw new Error(ERR_MAX_NONCE)}}const ZEROLEN=alloc$1(0);class CipherState{constructor(u,h=void 0,b=0){Z(this,"k");Z(this,"n");Z(this,"crypto");this.crypto=u,this.k=h,this.n=new Nonce(b)}hasKey(){return!!this.k}encryptWithAd(u,h){if(!this.hasKey())return h;this.n.assertValue();const b=this.crypto.encrypt(h,this.n.getBytes(),u,this.k);return this.n.increment(),b}decryptWithAd(u,h,b){if(!this.hasKey())return h;this.n.assertValue();const v=this.crypto.decrypt(h,this.n.getBytes(),u,this.k,b);return this.n.increment(),v}}class SymmetricState{constructor(u,h){Z(this,"cs");Z(this,"ck");Z(this,"h");Z(this,"crypto");this.crypto=u;const b=fromString(h,"utf-8");this.h=hashProtocolName(u,b),this.ck=this.h,this.cs=new CipherState(u)}mixKey(u){const[h,b]=this.crypto.hkdf(this.ck,u);this.ck=h,this.cs=new CipherState(this.crypto,b)}mixHash(u){this.h=this.crypto.hash(new Uint8ArrayList(this.h,u))}encryptAndHash(u){const h=this.cs.encryptWithAd(this.h,u);return this.mixHash(h),h}decryptAndHash(u){const h=this.cs.decryptWithAd(this.h,u);return this.mixHash(u),h}split(){const[u,h]=this.crypto.hkdf(this.ck,ZEROLEN);return[new CipherState(this.crypto,u),new CipherState(this.crypto,h)]}}class AbstractHandshakeState{constructor(u){Z(this,"ss");Z(this,"s");Z(this,"e");Z(this,"rs");Z(this,"re");Z(this,"initiator");Z(this,"crypto");const{crypto:h,protocolName:b,prologue:v,initiator:w,s:_,e:E,rs:S,re:x}=u;this.crypto=h,this.ss=new SymmetricState(h,b),this.ss.mixHash(v),this.initiator=w,this.s=_,this.e=E,this.rs=S,this.re=x}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const u=this.crypto.generateKeypair();return this.ss.mixHash(u.publicKey),this.e=u,u.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(u,h=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(u.byteLength<h+32)throw new Error("message is not long enough");this.re=u.sublist(h,h+32),this.ss.mixHash(this.re)}readS(u,h=0){if(this.rs)throw new Error("remote static public key is already set");const b=32+(this.ss.cs.hasKey()?16:0);if(u.byteLength<h+b)throw new Error("message is not long enough");const v=u.sublist(h,h+b);return this.rs=this.ss.decryptAndHash(v),b}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class XXHandshakeState extends AbstractHandshakeState{writeMessageA(u){return new Uint8ArrayList(this.writeE(),this.ss.encryptAndHash(u))}writeMessageB(u){const h=this.writeE();this.writeEE();const b=this.writeS();return this.writeES(),new Uint8ArrayList(h,b,this.ss.encryptAndHash(u))}writeMessageC(u){const h=this.writeS();return this.writeSE(),new Uint8ArrayList(h,this.ss.encryptAndHash(u))}readMessageA(u){try{return this.readE(u),this.ss.decryptAndHash(u.sublist(32))}catch(h){throw new InvalidCryptoExchangeError(`handshake stage 0 validation fail: ${h.message}`)}}readMessageB(u){try{this.readE(u),this.readEE();const h=this.readS(u,32);return this.readES(),this.ss.decryptAndHash(u.sublist(32+h))}catch(h){throw new InvalidCryptoExchangeError(`handshake stage 1 validation fail: ${h.message}`)}}readMessageC(u){try{const h=this.readS(u);return this.readSE(),this.ss.decryptAndHash(u.sublist(h))}catch(h){throw new InvalidCryptoExchangeError(`handshake stage 2 validation fail: ${h.message}`)}}}function hashProtocolName(y,u){if(u.length<=32){const h=alloc$1(32);return h.set(u),h}else return y.hash(u)}var NoiseExtensions;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.webtransportCerthashes!=null)for(const w of h.webtransportCerthashes)b.uint32(10),b.bytes(w);if(h.streamMuxers!=null)for(const w of h.streamMuxers)b.uint32(18),b.string(w);v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={webtransportCerthashes:[],streamMuxers:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{if(((E=v.limits)==null?void 0:E.webtransportCerthashes)!=null&&w.webtransportCerthashes.length===v.limits.webtransportCerthashes)throw new MaxLengthError('Decode error - map field "webtransportCerthashes" had too many elements');w.webtransportCerthashes.push(h.bytes());break}case 2:{if(((S=v.limits)==null?void 0:S.streamMuxers)!=null&&w.streamMuxers.length===v.limits.streamMuxers)throw new MaxLengthError('Decode error - map field "streamMuxers" had too many elements');w.streamMuxers.push(h.string());break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(NoiseExtensions||(NoiseExtensions={}));var NoiseHandshakePayload;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.identityKey!=null&&h.identityKey.byteLength>0&&(b.uint32(10),b.bytes(h.identityKey)),h.identitySig!=null&&h.identitySig.byteLength>0&&(b.uint32(18),b.bytes(h.identitySig)),h.extensions!=null&&(b.uint32(34),NoiseExtensions.codec().encode(h.extensions,b)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E;const w={identityKey:alloc$1(0),identitySig:alloc$1(0)},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const S=h.uint32();switch(S>>>3){case 1:{w.identityKey=h.bytes();break}case 2:{w.identitySig=h.bytes();break}case 4:{w.extensions=NoiseExtensions.codec().decode(h,h.uint32(),{limits:(E=v.limits)==null?void 0:E.extensions});break}default:{h.skipType(S&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(NoiseHandshakePayload||(NoiseHandshakePayload={}));async function createHandshakePayload(y,u,h){const b=await y.sign(getSignaturePayload(u));return NoiseHandshakePayload.encode({identityKey:publicKeyToProtobuf$1(y.publicKey),identitySig:b,extensions:h})}async function decodeHandshakePayload(y,u,h){try{const b=NoiseHandshakePayload.decode(y),v=publicKeyFromProtobuf(b.identityKey);if((h==null?void 0:h.equals(v))===!1)throw new Error(`Payload identity key ${v} does not match expected remote identity key ${h}`);if(!u)throw new Error("Remote static does not exist");const w=getSignaturePayload(u);if(!await v.verify(w,b.identitySig))throw new Error("Invalid payload signature");return b}catch(b){throw new UnexpectedPeerError(b.message)}}function getSignaturePayload(y){const u=fromString("noise-libp2p-static-key:");return y instanceof Uint8Array?concat([u,y],u.length+y.length):(y.prepend(u),y)}async function performHandshakeInitiator(y,u){const{log:h,connection:b,crypto:v,privateKey:w,prologue:_,s:E,remoteIdentityKey:S,extensions:x}=y,T=await createHandshakePayload(w,E.publicKey,x),C=new XXHandshakeState({crypto:v,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:_,s:E});logLocalStaticKeys(C.s,h),h.trace("Stage 0 - Initiator starting to send first message."),await b.write(C.writeMessageA(ZEROLEN),u),h.trace("Stage 0 - Initiator finished sending first message."),logLocalEphemeralKeys(C.e,h),h.trace("Stage 1 - Initiator waiting to receive first message from responder...");const O=C.readMessageB(await b.read(u));h.trace("Stage 1 - Initiator received the message."),logRemoteEphemeralKey(C.re,h),logRemoteStaticKey(C.rs,h),h.trace("Initiator going to check remote's signature...");const D=await decodeHandshakePayload(O,C.rs,S);h.trace("All good with the signature!"),h.trace("Stage 2 - Initiator sending third handshake message."),await b.write(C.writeMessageC(T),u),h.trace("Stage 2 - Initiator sent message with signed payload.");const[U,te]=C.ss.split();return logCipherState(U,te,h),{payload:D,encrypt:X=>U.encryptWithAd(ZEROLEN,X),decrypt:(X,ie)=>te.decryptWithAd(ZEROLEN,X,ie)}}async function performHandshakeResponder(y,u){const{log:h,connection:b,crypto:v,privateKey:w,prologue:_,s:E,remoteIdentityKey:S,extensions:x}=y,T=await createHandshakePayload(w,E.publicKey,x),C=new XXHandshakeState({crypto:v,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:_,s:E});logLocalStaticKeys(C.s,h),h.trace("Stage 0 - Responder waiting to receive first message."),C.readMessageA(await b.read(u)),h.trace("Stage 0 - Responder received first message."),logRemoteEphemeralKey(C.re,h),h.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await b.write(C.writeMessageB(T),u),h.trace("Stage 1 - Responder sent the second handshake message with signed payload."),logLocalEphemeralKeys(C.e,h),h.trace("Stage 2 - Responder waiting for third handshake message...");const O=C.readMessageC(await b.read(u));h.trace("Stage 2 - Responder received the message, finished handshake.");const D=await decodeHandshakePayload(O,C.rs,S),[U,te]=C.ss.split();return logCipherState(U,te,h),{payload:D,encrypt:X=>te.encryptWithAd(ZEROLEN,X),decrypt:(X,ie)=>U.decryptWithAd(ZEROLEN,X,ie)}}const CHACHA_TAG_LENGTH=16;function encryptStream(y,u){return async function*(h){for await(const b of h)for(let v=0;v<b.length;v+=NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG){let w=v+NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG;w>b.length&&(w=b.length);let _;b instanceof Uint8Array?_=y.encrypt(b.subarray(v,w)):_=y.encrypt(b.sublist(v,w)),u==null||u.encryptedPackets.increment(),yield new Uint8ArrayList(uint16BEEncode(_.byteLength),_)}}}function decryptStream(y,u){return async function*(h){for await(const b of h)for(let v=0;v<b.length;v+=NOISE_MSG_MAX_LENGTH_BYTES){let w=v+NOISE_MSG_MAX_LENGTH_BYTES;if(w>b.length&&(w=b.length),w-CHACHA_TAG_LENGTH<v)throw new Error("Invalid chunk");const _=b.sublist(v,w),E=b.subarray(v,w-CHACHA_TAG_LENGTH);try{const S=y.decrypt(_,E);u==null||u.decryptedPackets.increment(),yield S}catch(S){throw u==null||u.decryptErrors.increment(),S}}}}var Qd,eh;eh=Symbol.toStringTag,Qd=serviceCapabilities;class Noise{constructor(u,h={}){Z(this,"protocol","/noise");Z(this,"crypto");Z(this,"prologue");Z(this,"staticKey");Z(this,"extensions");Z(this,"metrics");Z(this,"components");Z(this,eh,"@chainsafe/libp2p-noise");Z(this,Qd,["@libp2p/connection-encryption","@chainsafe/libp2p-noise"]);const{staticNoiseKey:b,extensions:v,crypto:w,prologueBytes:_}=h,{metrics:E}=u;this.components=u;const S=w??defaultCrypto;this.crypto=wrapCrypto(S),this.extensions={webtransportCerthashes:[],...v},this.metrics=E?registerMetrics(E):void 0,b?this.staticKey=S.generateX25519KeyPairFromSeed(b):this.staticKey=S.generateX25519KeyPair(),this.prologue=_??alloc$1(0)}async secureOutbound(u,h){var E,S;const b=lpStream(u,{lengthEncoder:uint16BEEncode,lengthDecoder:uint16BEDecode,maxDataLength:NOISE_MSG_MAX_LENGTH_BYTES}),v=await this.performHandshakeInitiator(b,this.components.privateKey,(E=h==null?void 0:h.remotePeer)==null?void 0:E.publicKey,h),w=await this.createSecureConnection(b,v);u.source=w.source,u.sink=w.sink;const _=publicKeyFromProtobuf(v.payload.identityKey);return{conn:u,remoteExtensions:v.payload.extensions,remotePeer:peerIdFromPublicKey$1(_),streamMuxer:(h==null?void 0:h.skipStreamMuxerNegotiation)===!0?void 0:this.getStreamMuxer((S=v.payload.extensions)==null?void 0:S.streamMuxers)}}getStreamMuxer(u){if(u==null||u.length===0)return;const h=this.components.upgrader.getStreamMuxers();if(h!=null)for(const b of u){const v=h.get(b);if(v!=null)return v}if(u.length)throw new InvalidCryptoExchangeError$1("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(u,h){var E,S;const b=lpStream(u,{lengthEncoder:uint16BEEncode,lengthDecoder:uint16BEDecode,maxDataLength:NOISE_MSG_MAX_LENGTH_BYTES}),v=await this.performHandshakeResponder(b,this.components.privateKey,(E=h==null?void 0:h.remotePeer)==null?void 0:E.publicKey,h),w=await this.createSecureConnection(b,v);u.source=w.source,u.sink=w.sink;const _=publicKeyFromProtobuf(v.payload.identityKey);return{conn:u,remoteExtensions:v.payload.extensions,remotePeer:peerIdFromPublicKey$1(_),streamMuxer:(h==null?void 0:h.skipStreamMuxerNegotiation)===!0?void 0:this.getStreamMuxer((S=v.payload.extensions)==null?void 0:S.streamMuxers)}}async performHandshakeInitiator(u,h,b,v){var E,S;let w;const _=(v==null?void 0:v.skipStreamMuxerNegotiation)===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{w=await performHandshakeInitiator({connection:u,privateKey:h,remoteIdentityKey:b,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:_,webtransportCerthashes:[],...this.extensions}},v),(E=this.metrics)==null||E.xxHandshakeSuccesses.increment()}catch(x){throw(S=this.metrics)==null||S.xxHandshakeErrors.increment(),x}return w}async performHandshakeResponder(u,h,b,v){var E,S;let w;const _=(v==null?void 0:v.skipStreamMuxerNegotiation)===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{w=await performHandshakeResponder({connection:u,privateKey:h,remoteIdentityKey:b,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:_,webtransportCerthashes:[],...this.extensions}},v),(E=this.metrics)==null||E.xxHandshakeSuccesses.increment()}catch(x){throw(S=this.metrics)==null||S.xxHandshakeErrors.increment(),x}return w}async createSecureConnection(u,h){const[b,v]=duplexPair(),w=u.unwrap();return await pipe$1(b,encryptStream(h,this.metrics),w,_=>decode$1(_,{lengthDecoder:uint16BEDecode}),decryptStream(h,this.metrics),b),v}}function noise(y={}){return u=>new Noise(u,y)}const DNS4=base$2("dns4"),DNS6=base$2("dns6"),DNSADDR=base$2("dnsaddr"),DNS$1=or$1(base$2("dns"),DNSADDR,DNS4,DNS6),IP=or$1(base$2("ip4"),base$2("ip6")),TCP$1=or$1(and$1(IP,base$2("tcp")),and$1(DNS$1,base$2("tcp"))),UDP=and$1(IP,base$2("udp")),UTP=and$1(UDP,base$2("utp")),QUIC=and$1(UDP,base$2("quic")),QUICV1$1=and$1(UDP,base$2("quic-v1")),_WebSockets$1=or$1(and$1(TCP$1,base$2("ws")),and$1(DNS$1,base$2("ws"))),WebSockets$2=or$1(and$1(_WebSockets$1,base$2("p2p")),_WebSockets$1),_WebSocketsSecure$1=or$1(and$1(TCP$1,base$2("wss")),and$1(DNS$1,base$2("wss")),and$1(TCP$1,base$2("tls"),base$2("ws")),and$1(DNS$1,base$2("tls"),base$2("ws"))),WebSocketsSecure$1=or$1(and$1(_WebSocketsSecure$1,base$2("p2p")),_WebSocketsSecure$1),HTTP=or$1(and$1(TCP$1,base$2("http")),and$1(IP,base$2("http")),and$1(DNS$1,base$2("http"))),HTTPS=or$1(and$1(TCP$1,base$2("https")),and$1(IP,base$2("https")),and$1(DNS$1,base$2("https"))),_WebRTCDirect$1=and$1(UDP,base$2("webrtc-direct"),base$2("certhash")),WebRTCDirect$1=or$1(and$1(_WebRTCDirect$1,base$2("p2p")),_WebRTCDirect$1),_WebTransport$1=and$1(QUICV1$1,base$2("webtransport"),base$2("certhash"),base$2("certhash")),WebTransport$1=or$1(and$1(_WebTransport$1,base$2("p2p")),_WebTransport$1),P2PWebRTCStar=or$1(and$1(WebSockets$2,base$2("p2p-webrtc-star"),base$2("p2p")),and$1(WebSocketsSecure$1,base$2("p2p-webrtc-star"),base$2("p2p")),and$1(WebSockets$2,base$2("p2p-webrtc-star")),and$1(WebSocketsSecure$1,base$2("p2p-webrtc-star"))),P2PWebRTCDirect=or$1(and$1(HTTP,base$2("p2p-webrtc-direct"),base$2("p2p")),and$1(HTTPS,base$2("p2p-webrtc-direct"),base$2("p2p")),and$1(HTTP,base$2("p2p-webrtc-direct")),and$1(HTTPS,base$2("p2p-webrtc-direct"))),Reliable=or$1(_WebSockets$1,_WebSocketsSecure$1,HTTP,HTTPS,P2PWebRTCStar,P2PWebRTCDirect,TCP$1,UTP,QUIC,DNS$1,WebRTCDirect$1,WebTransport$1),_P2P$1=or$1(and$1(Reliable,base$2("p2p")),P2PWebRTCStar,P2PWebRTCDirect,WebRTCDirect$1,WebTransport$1,base$2("p2p")),_Circuit$1=or$1(and$1(_P2P$1,base$2("p2p-circuit"),_P2P$1),and$1(_P2P$1,base$2("p2p-circuit")),and$1(base$2("p2p-circuit"),_P2P$1),and$1(Reliable,base$2("p2p-circuit")),and$1(base$2("p2p-circuit"),Reliable),base$2("p2p-circuit")),CircuitRecursive=()=>or$1(and$1(_Circuit$1,CircuitRecursive),_Circuit$1),Circuit$1=CircuitRecursive(),P2P=or$1(and$1(Circuit$1,_P2P$1,Circuit$1),and$1(_P2P$1,Circuit$1),and$1(Circuit$1,_P2P$1),Circuit$1,_P2P$1);function makeMatchesFunction(y){function u(h){let b;try{b=multiaddr(h)}catch{return!1}const v=y(b.protoNames());return v===null?!1:v===!0||v===!1?v:v.length===0}return u}function and$1(...y){function u(h){if(h.length<y.length)return null;let b=h;return y.some(v=>(b=typeof v=="function"?v().partialMatch(h):v.partialMatch(h),Array.isArray(b)&&(h=b),b===null)),b}return{toString:function(){return"{ "+y.join(" ")+" }"},input:y,matches:makeMatchesFunction(u),partialMatch:u}}function or$1(...y){function u(b){let v=null;return y.some(w=>{const _=typeof w=="function"?w().partialMatch(b):w.partialMatch(b);return _!=null?(v=_,!0):!1}),v}return{toString:function(){return"{ "+y.join(" ")+" }"},input:y,matches:makeMatchesFunction(u),partialMatch:u}}function base$2(y){const u=y;function h(v){let w;try{w=multiaddr(v)}catch{return!1}const _=w.protoNames();return _.length===1&&_[0]===u}function b(v){return v.length===0?null:v[0]===u?v.slice(1):null}return{toString:function(){return u},matches:h,partialMatch:b}}const DEFAULT_BOOTSTRAP_TAG_NAME$1="bootstrap",DEFAULT_BOOTSTRAP_TAG_VALUE$1=50,DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT=1e3;var th,nh,ih,oh;class Bootstrap extends(oh=TypedEventEmitter,ih=peerDiscoverySymbol,nh=Symbol.toStringTag,th=serviceCapabilities,oh){constructor(h,b={list:[]}){if(b.list==null||b.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super();Z(this,"log");Z(this,"timer");Z(this,"list");Z(this,"timeout");Z(this,"components");Z(this,"_init");Z(this,ih,this);Z(this,nh,"@libp2p/bootstrap");Z(this,th,["@libp2p/peer-discovery"]);this.components=h,this.log=h.logger.forComponent("libp2p:bootstrap"),this.timeout=b.timeout??DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT,this.list=[];for(const v of b.list){if(!P2P.matches(v)){this.log.error("Invalid multiaddr");continue}const w=multiaddr(v),_=w.getPeerId();if(_==null){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const E={id:peerIdFromString$1(_),multiaddrs:[w]};this.list.push(E)}this._init=b}isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(h=>{this.log.error(h)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(const h of this.list){if(await this.components.peerStore.merge(h.id,{tags:{[this._init.tagName??DEFAULT_BOOTSTRAP_TAG_NAME$1]:{value:this._init.tagValue??DEFAULT_BOOTSTRAP_TAG_VALUE$1,ttl:this._init.tagTTL}},multiaddrs:h.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:h}),this.components.connectionManager.openConnection(h.id).catch(b=>{this.log.error("could not dial bootstrap peer %p",h.id,b)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}}Z(Bootstrap,"tag","bootstrap");function bootstrap(y){return u=>new Bootstrap(u,y)}var Envelope;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.publicKey!=null&&h.publicKey.byteLength>0&&(b.uint32(10),b.bytes(h.publicKey)),h.payloadType!=null&&h.payloadType.byteLength>0&&(b.uint32(18),b.bytes(h.payloadType)),h.payload!=null&&h.payload.byteLength>0&&(b.uint32(26),b.bytes(h.payload)),h.signature!=null&&h.signature.byteLength>0&&(b.uint32(42),b.bytes(h.signature)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={publicKey:alloc$1(0),payloadType:alloc$1(0),payload:alloc$1(0),signature:alloc$1(0)},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.publicKey=h.bytes();break}case 2:{w.payloadType=h.bytes();break}case 3:{w.payload=h.bytes();break}case 5:{w.signature=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(Envelope||(Envelope={}));class InvalidSignatureError extends Error{constructor(u="Invalid signature"){super(u),this.name="InvalidSignatureError"}}const ji=class ji{constructor(u){Z(this,"publicKey");Z(this,"payloadType");Z(this,"payload");Z(this,"signature");Z(this,"marshaled");const{publicKey:h,payloadType:b,payload:v,signature:w}=u;this.publicKey=h,this.payloadType=b,this.payload=v,this.signature=w}marshal(){return this.marshaled==null&&(this.marshaled=Envelope.encode({publicKey:publicKeyToProtobuf$1(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(u){return u==null?!1:equals(this.marshal(),u.marshal())}async validate(u,h){const b=formatSignaturePayload(u,this.payloadType,this.payload);return this.publicKey.verify(b.subarray(),this.signature,h)}};Z(ji,"createFromProtobuf",u=>{const h=Envelope.decode(u),b=publicKeyFromProtobuf(h.publicKey);return new ji({publicKey:b,payloadType:h.payloadType,payload:h.payload,signature:h.signature})}),Z(ji,"seal",async(u,h,b)=>{if(h==null)throw new Error("Missing private key");const v=u.domain,w=u.codec,_=u.marshal(),E=formatSignaturePayload(v,w,_),S=await h.sign(E.subarray(),b);return new ji({publicKey:h.publicKey,payloadType:w,payload:_,signature:S})}),Z(ji,"openAndCertify",async(u,h,b)=>{const v=ji.createFromProtobuf(u);if(!await v.validate(h,b))throw new InvalidSignatureError("Envelope signature is not valid for the given domain");return v});let RecordEnvelope=ji;const formatSignaturePayload=(y,u,h)=>{const b=fromString(y),v=encode$8(b.byteLength),w=encode$8(u.length),_=encode$8(h.length);return new Uint8ArrayList(v,b,w,u,_,h)};function arrayEquals(y,u){const h=(b,v)=>b.toString().localeCompare(v.toString());return y.length!==u.length?!1:(u.sort(h),y.sort(h).every((b,v)=>u[v].equals(b)))}const ENVELOPE_DOMAIN_PEER_RECORD="libp2p-peer-record",ENVELOPE_PAYLOAD_TYPE_PEER_RECORD=Uint8Array.from([3,1]);var PeerRecord$1;(function(y){(function(h){let b;h.codec=()=>(b==null&&(b=message$1((v,w,_={})=>{_.lengthDelimited!==!1&&w.fork(),v.multiaddr!=null&&v.multiaddr.byteLength>0&&(w.uint32(10),w.bytes(v.multiaddr)),_.lengthDelimited!==!1&&w.ldelim()},(v,w,_={})=>{const E={multiaddr:alloc$1(0)},S=w==null?v.len:v.pos+w;for(;v.pos<S;){const x=v.uint32();switch(x>>>3){case 1:{E.multiaddr=v.bytes();break}default:{v.skipType(x&7);break}}}return E})),b),h.encode=v=>encodeMessage(v,h.codec()),h.decode=(v,w)=>decodeMessage(v,h.codec(),w)})(y.AddressInfo||(y.AddressInfo={}));let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.peerId!=null&&h.peerId.byteLength>0&&(b.uint32(10),b.bytes(h.peerId)),h.seq!=null&&h.seq!==0n&&(b.uint32(16),b.uint64(h.seq)),h.addresses!=null)for(const w of h.addresses)b.uint32(26),y.AddressInfo.codec().encode(w,b);v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={peerId:alloc$1(0),seq:0n,addresses:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 1:{w.peerId=h.bytes();break}case 2:{w.seq=h.uint64();break}case 3:{if(((E=v.limits)==null?void 0:E.addresses)!=null&&w.addresses.length===v.limits.addresses)throw new MaxLengthError('Decode error - map field "addresses" had too many elements');w.addresses.push(y.AddressInfo.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.addresses$}));break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PeerRecord$1||(PeerRecord$1={}));const Ri=class Ri{constructor(u){Z(this,"peerId");Z(this,"multiaddrs");Z(this,"seqNumber");Z(this,"domain",Ri.DOMAIN);Z(this,"codec",Ri.CODEC);Z(this,"marshaled");const{peerId:h,multiaddrs:b,seqNumber:v}=u;this.peerId=h,this.multiaddrs=b??[],this.seqNumber=v??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=PeerRecord$1.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(u=>({multiaddr:u.bytes}))})),this.marshaled}equals(u){return!(!(u instanceof Ri)||!this.peerId.equals(u.peerId)||this.seqNumber!==u.seqNumber||!arrayEquals(this.multiaddrs,u.multiaddrs))}};Z(Ri,"createFromProtobuf",u=>{const h=PeerRecord$1.decode(u),b=peerIdFromMultihash(decode$3(h.peerId)),v=(h.addresses??[]).map(_=>multiaddr(_.multiaddr)),w=h.seq;return new Ri({peerId:b,multiaddrs:v,seqNumber:w})}),Z(Ri,"DOMAIN",ENVELOPE_DOMAIN_PEER_RECORD),Z(Ri,"CODEC",ENVELOPE_PAYLOAD_TYPE_PEER_RECORD);let PeerRecord=Ri;function debounce$1(y,u){let h;const b=function(){const v=function(){h=void 0,y()};clearTimeout(h),h=setTimeout(v,u)};return b.start=()=>{},b.stop=()=>{clearTimeout(h)},b}function isAsyncIterable$3(y){return y[Symbol.asyncIterator]!=null}function drain(y){if(isAsyncIterable$3(y))return(async()=>{for await(const u of y);})();for(const u of y);}const CustomEvent$1=globalThis.CustomEvent??Event;async function*parallel(y,u={}){let h=u.concurrency??1/0;h<1&&(h=1/0);const b=u.ordered??!1,v=new EventTarget,w=[];let _=pDefer(),E=pDefer(),S=!1,x,T=!1;v.addEventListener("task-complete",()=>{E.resolve()}),Promise.resolve().then(async()=>{try{for await(const U of y){if(w.length===h&&(_=pDefer(),await _.promise),T)break;const te={done:!1};w.push(te),U().then(X=>{te.done=!0,te.ok=!0,te.value=X,v.dispatchEvent(new CustomEvent$1("task-complete"))},X=>{te.done=!0,te.err=X,v.dispatchEvent(new CustomEvent$1("task-complete"))})}S=!0,v.dispatchEvent(new CustomEvent$1("task-complete"))}catch(U){x=U,v.dispatchEvent(new CustomEvent$1("task-complete"))}});function C(){var U;return b?(U=w[0])==null?void 0:U.done:!!w.find(te=>te.done)}function*O(){for(;w.length>0&&w[0].done;){const U=w[0];if(w.shift(),U.ok)yield U.value;else throw T=!0,_.resolve(),U.err;_.resolve()}}function*D(){for(;C();)for(let U=0;U<w.length;U++)if(w[U].done){const te=w[U];if(w.splice(U,1),U--,te.ok)yield te.value;else throw T=!0,_.resolve(),te.err;_.resolve()}}for(;;){if(C()||(E=pDefer(),await E.promise),x!=null||(b?yield*O():yield*D(),x!=null))throw x;if(S&&w.length===0)break}}function pbStream(y,u){const h=lpStream(y,u),b={read:async(v,w)=>{const _=await h.read(w);return v.decode(_)},write:async(v,w,_)=>{await h.write(w.encode(v),_)},writeV:async(v,w,_)=>{await h.writeV(v.map(E=>w.encode(E)),_)},pb:v=>({read:async w=>b.read(v,w),write:async(w,_)=>b.write(w,v,_),writeV:async(w,_)=>b.writeV(w,v,_),unwrap:()=>b}),unwrap:()=>h.unwrap()};return b}const IDENTIFY_PROTOCOL_VERSION="0.1.0",MULTICODEC_IDENTIFY_PROTOCOL_NAME="id",MULTICODEC_IDENTIFY_PROTOCOL_VERSION="1.0.0",MAX_IDENTIFY_MESSAGE_SIZE=1024*8,MAX_PUSH_CONCURRENCY=32;var Identify$1;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.protocolVersion!=null&&(b.uint32(42),b.string(h.protocolVersion)),h.agentVersion!=null&&(b.uint32(50),b.string(h.agentVersion)),h.publicKey!=null&&(b.uint32(10),b.bytes(h.publicKey)),h.listenAddrs!=null)for(const w of h.listenAddrs)b.uint32(18),b.bytes(w);if(h.observedAddr!=null&&(b.uint32(34),b.bytes(h.observedAddr)),h.protocols!=null)for(const w of h.protocols)b.uint32(26),b.string(w);h.signedPeerRecord!=null&&(b.uint32(66),b.bytes(h.signedPeerRecord)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S;const w={listenAddrs:[],protocols:[]},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const x=h.uint32();switch(x>>>3){case 5:{w.protocolVersion=h.string();break}case 6:{w.agentVersion=h.string();break}case 1:{w.publicKey=h.bytes();break}case 2:{if(((E=v.limits)==null?void 0:E.listenAddrs)!=null&&w.listenAddrs.length===v.limits.listenAddrs)throw new MaxLengthError('Decode error - map field "listenAddrs" had too many elements');w.listenAddrs.push(h.bytes());break}case 4:{w.observedAddr=h.bytes();break}case 3:{if(((S=v.limits)==null?void 0:S.protocols)!=null&&w.protocols.length===v.limits.protocols)throw new MaxLengthError('Decode error - map field "protocols" had too many elements');w.protocols.push(h.string());break}case 8:{w.signedPeerRecord=h.bytes();break}default:{h.skipType(x&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(Identify$1||(Identify$1={}));const defaultValues$3={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:MAX_IDENTIFY_MESSAGE_SIZE,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:MAX_PUSH_CONCURRENCY};function getCleanMultiaddr(y){if(y!=null&&y.length>0)try{return multiaddr(y)}catch{}}function getAgentVersion(y,u){return u??y.userAgent}async function consumeIdentifyMessage(y,u,h,b,v){if(h("received identify from %p",b.remotePeer),v==null)throw new InvalidMessageError("message was null or undefined");const w={};if(v.listenAddrs.length>0&&(w.addresses=v.listenAddrs.map(S=>({isCertified:!1,multiaddr:multiaddr(S)}))),v.protocols.length>0&&(w.protocols=v.protocols),v.publicKey!=null){const S=publicKeyFromProtobuf(v.publicKey);if(!peerIdFromPublicKey$1(S).equals(b.remotePeer))throw new InvalidMessageError("public key did not match remote PeerId");w.publicKey=S}let _;if(v.signedPeerRecord!=null){h.trace("received signedPeerRecord from %p",b.remotePeer);let S=v.signedPeerRecord;const x=await RecordEnvelope.openAndCertify(S,PeerRecord.DOMAIN);let T=PeerRecord.createFromProtobuf(x.payload);const C=peerIdFromCID(x.publicKey.toCID());if(!T.peerId.equals(C))throw new InvalidMessageError("signing key does not match PeerId in the PeerRecord");if(!b.remotePeer.equals(T.peerId))throw new InvalidMessageError("signing key does not match remote PeerId");let O;try{O=await y.get(T.peerId)}catch(D){if(D.name!=="NotFoundError")throw D}if(O!=null&&(w.metadata=O.metadata,O.peerRecordEnvelope!=null)){const D=RecordEnvelope.createFromProtobuf(O.peerRecordEnvelope),U=PeerRecord.createFromProtobuf(D.payload);U.seqNumber>=T.seqNumber&&(h("sequence number was lower or equal to existing sequence number - stored: %d received: %d",U.seqNumber,T.seqNumber),T=U,S=O.peerRecordEnvelope)}w.peerRecordEnvelope=S,w.addresses=T.multiaddrs.map(D=>({isCertified:!0,multiaddr:D})),_={seq:T.seqNumber,addresses:T.multiaddrs}}else h("%p did not send a signed peer record",b.remotePeer);if(h.trace("patching %p with",b.remotePeer,w),await y.patch(b.remotePeer,w),v.agentVersion!=null||v.protocolVersion!=null){const S={};v.agentVersion!=null&&(S.AgentVersion=fromString(v.agentVersion)),v.protocolVersion!=null&&(S.ProtocolVersion=fromString(v.protocolVersion)),h.trace("merging %p metadata",b.remotePeer,S),await y.merge(b.remotePeer,{metadata:S})}const E={peerId:b.remotePeer,protocolVersion:v.protocolVersion,agentVersion:v.agentVersion,publicKey:v.publicKey,listenAddrs:v.listenAddrs.map(S=>multiaddr(S)),observedAddr:v.observedAddr==null?void 0:multiaddr(v.observedAddr),protocols:v.protocols,signedPeerRecord:_,connection:b};return u.safeDispatchEvent("peer:identify",{detail:E}),E}class AbstractIdentify{constructor(u,h){Z(this,"host");Z(this,"protocol");Z(this,"started");Z(this,"timeout");Z(this,"peerId");Z(this,"privateKey");Z(this,"peerStore");Z(this,"registrar");Z(this,"addressManager");Z(this,"maxInboundStreams");Z(this,"maxOutboundStreams");Z(this,"maxMessageSize");Z(this,"maxObservedAddresses");Z(this,"events");Z(this,"runOnLimitedConnection");Z(this,"log");this.protocol=h.protocol,this.started=!1,this.peerId=u.peerId,this.privateKey=u.privateKey,this.peerStore=u.peerStore,this.registrar=u.registrar,this.addressManager=u.addressManager,this.events=u.events,this.log=h.log,this.timeout=h.timeout??defaultValues$3.timeout,this.maxInboundStreams=h.maxInboundStreams??defaultValues$3.maxInboundStreams,this.maxOutboundStreams=h.maxOutboundStreams??defaultValues$3.maxOutboundStreams,this.maxMessageSize=h.maxMessageSize??defaultValues$3.maxMessageSize,this.maxObservedAddresses=h.maxObservedAddresses??defaultValues$3.maxObservedAddresses,this.runOnLimitedConnection=h.runOnLimitedConnection??defaultValues$3.runOnLimitedConnection,this.host={protocolVersion:`${h.protocolPrefix??defaultValues$3.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,agentVersion:getAgentVersion(u.nodeInfo,h.agentVersion)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:fromString(this.host.agentVersion),ProtocolVersion:fromString(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,u=>{this.handleProtocol(u).catch(h=>{this.log.error(h)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}function isGlobalUnicast(y){try{for(const{code:u,value:h}of y.getComponents())if(h!=null&&u===CODE_IP6)return cidrContains("2000::/3",h)}catch{}return!1}var Netmask_1;(function(){var y,u,h,b,v,w,_,E;E=function(S){var x,T,C,O;return x=(S&255<<24)>>>24,T=(S&255<<16)>>>16,C=(S&65280)>>>8,O=S&255,[x,T,C,O].join(".")},_=function(S){var x,T,C,O,D,U;for(x=[],C=O=0;O<=3&&S.length!==0;C=++O){if(C>0){if(S[0]!==".")throw new Error("Invalid IP");S=S.substring(1)}U=u(S),D=U[0],T=U[1],S=S.substring(T),x.push(D)}if(S.length!==0)throw new Error("Invalid IP");switch(x.length){case 1:if(x[0]>4294967295)throw new Error("Invalid IP");return x[0]>>>0;case 2:if(x[0]>255||x[1]>16777215)throw new Error("Invalid IP");return(x[0]<<24|x[1])>>>0;case 3:if(x[0]>255||x[1]>255||x[2]>65535)throw new Error("Invalid IP");return(x[0]<<24|x[1]<<16|x[2])>>>0;case 4:if(x[0]>255||x[1]>255||x[2]>255||x[3]>255)throw new Error("Invalid IP");return(x[0]<<24|x[1]<<16|x[2]<<8|x[3])>>>0;default:throw new Error("Invalid IP")}},h=function(S){return S.charCodeAt(0)},b=h("0"),w=h("a"),v=h("A"),u=function(S){var x,T,C,O,D;for(O=0,x=10,T="9",C=0,S.length>1&&S[C]==="0"&&(S[C+1]==="x"||S[C+1]==="X"?(C+=2,x=16):"0"<=S[C+1]&&S[C+1]<="9"&&(C++,x=8,T="7")),D=C;C<S.length;){if("0"<=S[C]&&S[C]<=T)O=O*x+(h(S[C])-b)>>>0;else if(x===16)if("a"<=S[C]&&S[C]<="f")O=O*x+(10+h(S[C])-w)>>>0;else if("A"<=S[C]&&S[C]<="F")O=O*x+(10+h(S[C])-v)>>>0;else break;else break;if(O>4294967295)throw new Error("too large");C++}if(C===D)throw new Error("empty octet");return[O,C]},y=function(){function S(x,T){var C,O,D;if(typeof x!="string")throw new Error("Missing `net' parameter");if(T||(D=x.split("/",2),x=D[0],T=D[1]),T||(T=32),typeof T=="string"&&T.indexOf(".")>-1){try{this.maskLong=_(T)}catch{throw new Error("Invalid mask: "+T)}for(C=O=32;O>=0;C=--O)if(this.maskLong===4294967295<<32-C>>>0){this.bitmask=C;break}}else if(T||T===0)this.bitmask=parseInt(T,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(_(x)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+x)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+T);this.size=Math.pow(2,32-this.bitmask),this.base=E(this.netLong),this.mask=E(this.maskLong),this.hostmask=E(~this.maskLong),this.first=this.bitmask<=30?E(this.netLong+1):this.base,this.last=this.bitmask<=30?E(this.netLong+this.size-2):E(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?E(this.netLong+this.size-1):void 0}return S.prototype.contains=function(x){return typeof x=="string"&&(x.indexOf("/")>0||x.split(".").length!==4)&&(x=new S(x)),x instanceof S?this.contains(x.base)&&this.contains(x.broadcast||x.last):(_(x)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},S.prototype.next=function(x){return x==null&&(x=1),new S(E(this.netLong+this.size*x),this.mask)},S.prototype.forEach=function(x){var T,C,O;for(O=_(this.first),C=_(this.last),T=0;O<=C;)x(E(O),O,T),T++,O++},S.prototype.toString=function(){return this.base+"/"+this.bitmask},S}(),Netmask_1=y}).call(commonjsGlobal);const PRIVATE_IP_RANGES=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],NETMASK_RANGES=PRIVATE_IP_RANGES.map(y=>new Netmask_1(y));function ipv4Check(y){for(const u of NETMASK_RANGES)if(u.contains(y))return!0;return!1}function isIpv4MappedIpv6(y){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(y)}function ipv4MappedIpv6Check(y){const u=y.split(":");if(u.length<2)return!1;const h=u[u.length-1].padStart(4,"0"),b=u[u.length-2].padStart(4,"0"),v=`${parseInt(b.substring(0,2),16)}.${parseInt(b.substring(2),16)}.${parseInt(h.substring(0,2),16)}.${parseInt(h.substring(2),16)}`;return ipv4Check(v)}function isIpv4EmbeddedIpv6(y){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(y)}function ipv4EmbeddedIpv6Check(y){const u=y.split(":"),h=u[u.length-1];return ipv4Check(h)}function ipv6Check(y){return/^::$/.test(y)||/^::1$/.test(y)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(y)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(y)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(y)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(y)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(y)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(y)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(y)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(y)||/^ff([0-9a-fA-F]{2,2}):/i.test(y)}function isPrivateIp(y){if(isIPv4(y))return ipv4Check(y);if(isIpv4MappedIpv6(y))return ipv4MappedIpv6Check(y);if(isIpv4EmbeddedIpv6(y))return ipv4EmbeddedIpv6Check(y);if(isIPv6(y))return ipv6Check(y)}function isIpBased(y){try{for(const{code:u}of y.getComponents())if(u!==CODE_IP6ZONE)return u===CODE_IP4||u===CODE_IP6}catch{}return!1}function isPrivate(y){try{if(!isIpBased(y))return!1;const[[,u]]=y.stringTuples();return u==null?!1:isPrivateIp(u)??!1}catch{}return!0}const toParts=y=>y.toString().split("/").slice(1),func=y=>({match:u=>u.length<1?!1:y(u[0])?u.slice(1):!1,pattern:"fn"}),literal=y=>({match:u=>func(h=>h===y).match(u),pattern:y}),string=()=>({match:y=>func(u=>typeof u=="string").match(y),pattern:"{string}"}),number=()=>({match:y=>func(u=>!isNaN(parseInt(u))).match(y),pattern:"{number}"}),peerId=()=>({match:y=>{if(y.length<2||y[0]!=="p2p"&&y[0]!=="ipfs")return!1;if(y[1].startsWith("Q")||y[1].startsWith("1"))try{base58btc.decode(`z${y[1]}`)}catch{return!1}else return!1;return y.slice(2)},pattern:"/p2p/{peerid}"}),certhash=()=>({match:y=>{if(y.length<2||y[0]!=="certhash")return!1;try{base64url.decode(y[1])}catch{return!1}return y.slice(2)},pattern:"/certhash/{certhash}"}),optional=y=>({match:u=>{const h=y.match(u);return h===!1?u:h},pattern:`optional(${y.pattern})`}),or=(...y)=>({match:u=>{let h;for(const b of y){const v=b.match(u);v!==!1&&(h==null||v.length<h.length)&&(h=v)}return h??!1},pattern:`or(${y.map(u=>u.pattern).join(", ")})`}),and=(...y)=>({match:u=>{for(const h of y){const b=h.match(u);if(b===!1)return!1;u=b}return u},pattern:`and(${y.map(u=>u.pattern).join(", ")})`});function fmt(...y){function u(v){let w=toParts(v);for(const _ of y){const E=_.match(w);if(E===!1)return!1;w=E}return w}function h(v){return u(v)!==!1}function b(v){const w=u(v);return w===!1?!1:w.length===0}return{matchers:y,matches:h,exactMatch:b}}const _PEER_ID=peerId(),PEER_ID=fmt(_PEER_ID),_DNS4=and(literal("dns4"),string()),_DNS6=and(literal("dns6"),string()),_DNSADDR=and(literal("dnsaddr"),string()),_DNS=and(literal("dns"),string());fmt(_DNS4,optional(peerId()));fmt(_DNS6,optional(peerId()));fmt(_DNSADDR,optional(peerId()));fmt(or(_DNS,_DNSADDR,_DNS4,_DNS6),optional(peerId()));const _IP4=and(literal("ip4"),func(isIPv4)),_IP6=and(literal("ip6"),func(isIPv6)),_IP=or(_IP4,_IP6),_IP_OR_DOMAIN=or(_IP,_DNS,_DNS4,_DNS6,_DNSADDR),IP_OR_DOMAIN=fmt(or(_IP,and(or(_DNS,_DNSADDR,_DNS4,_DNS6),optional(peerId())))),IP4=fmt(_IP4),IP6=fmt(_IP6),_TCP=and(_IP_OR_DOMAIN,literal("tcp"),number()),_UDP=and(_IP_OR_DOMAIN,literal("udp"),number()),TCP=fmt(and(_TCP,optional(peerId()))),_QUIC=and(_UDP,literal("quic"),optional(peerId())),_QUICV1=and(_UDP,literal("quic-v1"),optional(peerId())),QUIC_V0_OR_V1=or(_QUIC,_QUICV1),QUICV1=fmt(_QUICV1),_WEB=or(_IP_OR_DOMAIN,_TCP,_UDP,_QUIC,_QUICV1),_WebSockets=or(and(_WEB,literal("ws"),optional(peerId()))),WebSockets$1=fmt(_WebSockets),_WebSocketsSecure=or(and(_WEB,literal("wss"),optional(peerId())),and(_WEB,literal("tls"),optional(and(literal("sni"),string())),literal("ws"),optional(peerId()))),WebSocketsSecure=fmt(_WebSocketsSecure),_WebRTCDirect=and(_UDP,literal("webrtc-direct"),optional(certhash()),optional(certhash()),optional(peerId())),WebRTCDirect=fmt(_WebRTCDirect),_WebTransport=and(_QUICV1,literal("webtransport"),optional(certhash()),optional(certhash()),optional(peerId())),WebTransport=fmt(_WebTransport),_P2P=or(_WebSockets,_WebSocketsSecure,and(_TCP,optional(peerId())),and(QUIC_V0_OR_V1,optional(peerId())),and(_IP_OR_DOMAIN,optional(peerId())),_WebRTCDirect,_WebTransport,peerId()),_Circuit=and(_P2P,literal("p2p-circuit"),peerId()),Circuit=fmt(_Circuit),_WebRTC=or(and(_P2P,literal("p2p-circuit"),literal("webrtc"),optional(peerId())),and(_P2P,literal("webrtc"),optional(peerId())),and(literal("webrtc"),optional(peerId()))),WebRTC=fmt(_WebRTC);or(and(_IP_OR_DOMAIN,literal("tcp"),number(),literal("http"),optional(peerId())),and(_IP_OR_DOMAIN,literal("http"),optional(peerId())));or(and(_IP_OR_DOMAIN,literal("tcp"),or(and(literal("443"),literal("http")),and(number(),literal("https")),and(number(),literal("tls"),literal("http"))),optional(peerId())),and(_IP_OR_DOMAIN,literal("tls"),literal("http"),optional(peerId())),and(_IP_OR_DOMAIN,literal("https"),optional(peerId())));or(and(literal("memory"),string(),optional(peerId())));or(and(literal("unix"),string(),optional(peerId())));var ah,uh;class Identify extends(uh=AbstractIdentify,ah=serviceCapabilities,uh){constructor(h,b={}){super(h,{...b,protocol:`/${b.protocolPrefix??defaultValues$3.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`,log:h.logger.forComponent("libp2p:identify")});Z(this,ah,["@libp2p/identify"]);(b.runOnConnectionOpen??defaultValues$3.runOnConnectionOpen)&&h.events.addEventListener("connection:open",v=>{const w=v.detail;this.identify(w).catch(_=>{_.name!==UnsupportedProtocolError.name&&this.log.error("error during identify trigged by connection:open",_)})})}async _identify(h,b={}){let v;if(b.signal==null){const w=AbortSignal.timeout(this.timeout);b={...b,signal:w}}try{v=await h.newStream(this.protocol,{...b,runOnLimitedConnection:this.runOnLimitedConnection});const _=await pbStream(v,{maxDataLength:this.maxMessageSize}).pb(Identify$1).read(b);return await v.close(b),_}catch(w){throw v==null||v.abort(w),w}}async identify(h,b={}){const v=await this._identify(h,b),{publicKey:w,protocols:_,observedAddr:E}=v;if(w==null)throw new InvalidMessageError("public key was missing from identify message");const S=publicKeyFromProtobuf(w),x=peerIdFromCID(S.toCID());if(!h.remotePeer.equals(x))throw new InvalidMessageError("identified peer does not match the expected peer");if(this.peerId.equals(x))throw new InvalidMessageError("identified peer is our own peer id?");return this.maybeAddObservedAddress(E),this.log("identify completed for peer %p and protocols %o",x,_),consumeIdentifyMessage(this.peerStore,this.events,this.log,h,v)}maybeAddObservedAddress(h){const b=getCleanMultiaddr(h);if(b==null)return;if(this.log.trace("our observed address was %a",b),isPrivate(b)){this.log.trace("our observed address was private");return}const v=b.getComponents();if((v[0].code===CODE_IP6||v[0].code===CODE_IP6ZONE&&v[1].code===CODE_IP6)&&!isGlobalUnicast(b)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}TCP.exactMatch(b)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(b))}async handleProtocol(h){const{connection:b,stream:v}=h,w=AbortSignal.timeout(this.timeout);try{const _=await this.peerStore.get(this.peerId),E=this.addressManager.getAddresses().map(C=>C.decapsulateCode(protocols("p2p").code));let S=_.peerRecordEnvelope;if(E.length>0&&S==null){const C=new PeerRecord({peerId:this.peerId,multiaddrs:E});S=(await RecordEnvelope.seal(C,this.privateKey)).marshal().subarray()}let x=b.remoteAddr.bytes;IP_OR_DOMAIN.matches(b.remoteAddr)||(x=void 0),await pbStream(v).pb(Identify$1).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:publicKeyToProtobuf$1(this.privateKey.publicKey),listenAddrs:E.map(C=>C.bytes),signedPeerRecord:S,observedAddr:x,protocols:_.protocols},{signal:w}),await v.close({signal:w})}catch(_){this.log.error("could not respond to identify request",_),v.abort(_)}}}function identify(y={}){return u=>new Identify(u,y)}function getIterator(y){if(y!=null){if(typeof y[Symbol.iterator]=="function")return y[Symbol.iterator]();if(typeof y[Symbol.asyncIterator]=="function")return y[Symbol.asyncIterator]();if(typeof y.next=="function")return y}throw new Error("argument is not an iterator or iterable")}function isPromise$2(y){return y==null?!1:typeof y.then=="function"&&typeof y.catch=="function"&&typeof y.finally=="function"}function closeSource(y,u){var b,v;const h=(v=(b=getIterator(y)).return)==null?void 0:v.call(b);isPromise$2(h)&&h.catch(w=>{u.error("could not cause iterator to return",w)})}const createAbortError=()=>{const y=new Error("Delay aborted");return y.name="AbortError",y},clearMethods=new WeakMap;function createDelay({clearTimeout:y,setTimeout:u}={}){return(h,{value:b,signal:v}={})=>{if(v!=null&&v.aborted)return Promise.reject(createAbortError());let w,_,E;const S=y??clearTimeout,x=()=>{S(w),E(createAbortError())},T=()=>{v&&v.removeEventListener("abort",x)},C=new Promise((O,D)=>{_=()=>{T(),O(b)},E=D,w=(u??setTimeout)(_,h)});return v&&v.addEventListener("abort",x,{once:!0}),clearMethods.set(C,()=>{S(w),w=null,_()}),C}}const delay=createDelay();class RateLimitError extends Error{constructor(h="Rate limit exceeded",b){super(h);Z(this,"remainingPoints");Z(this,"msBeforeNext");Z(this,"consumedPoints");Z(this,"isFirstInDuration");this.name="RateLimitError",this.remainingPoints=b.remainingPoints,this.msBeforeNext=b.msBeforeNext,this.consumedPoints=b.consumedPoints,this.isFirstInDuration=b.isFirstInDuration}}var Jl;let QueueFullError$1=(Jl=class extends Error{constructor(u="The queue was full"){super(u),this.name="QueueFullError"}},Z(Jl,"name","QueueFullError"),Jl);class RateLimiter{constructor(u={}){Z(this,"memoryStorage");Z(this,"points");Z(this,"duration");Z(this,"blockDuration");Z(this,"execEvenly");Z(this,"execEvenlyMinDelayMs");Z(this,"keyPrefix");this.points=u.points??4,this.duration=u.duration??1,this.blockDuration=u.blockDuration??0,this.execEvenly=u.execEvenly??!1,this.execEvenlyMinDelayMs=u.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=u.keyPrefix??"rlflx",this.memoryStorage=new MemoryStorage}async consume(u,h=1,b={}){const v=this.getKey(u),w=this._getKeySecDuration(b);let _=this.memoryStorage.incrby(v,h,w);if(_.remainingPoints=Math.max(this.points-_.consumedPoints,0),_.consumedPoints>this.points)throw this.blockDuration>0&&_.consumedPoints<=this.points+h&&(_=this.memoryStorage.set(v,_.consumedPoints,this.blockDuration)),new RateLimitError("Rate limit exceeded",_);if(this.execEvenly&&_.msBeforeNext>0&&!_.isFirstInDuration){let E=Math.ceil(_.msBeforeNext/(_.remainingPoints+2));E<this.execEvenlyMinDelayMs&&(E=_.consumedPoints*this.execEvenlyMinDelayMs),await delay(E)}return _}penalty(u,h=1,b={}){const v=this.getKey(u),w=this._getKeySecDuration(b),_=this.memoryStorage.incrby(v,h,w);return _.remainingPoints=Math.max(this.points-_.consumedPoints,0),_}reward(u,h=1,b={}){const v=this.getKey(u),w=this._getKeySecDuration(b),_=this.memoryStorage.incrby(v,-h,w);return _.remainingPoints=Math.max(this.points-_.consumedPoints,0),_}block(u,h){const b=h*1e3,v=this.points+1;return this.memoryStorage.set(this.getKey(u),v,h),{remainingPoints:0,msBeforeNext:b===0?-1:b,consumedPoints:v,isFirstInDuration:!1}}set(u,h,b=0){const v=(b>=0?b:this.duration)*1e3;return this.memoryStorage.set(this.getKey(u),h,b),{remainingPoints:0,msBeforeNext:v===0?-1:v,consumedPoints:h,isFirstInDuration:!1}}get(u){const h=this.memoryStorage.get(this.getKey(u));return h!=null&&(h.remainingPoints=Math.max(this.points-h.consumedPoints,0)),h}delete(u){this.memoryStorage.delete(this.getKey(u))}_getKeySecDuration(u){return(u==null?void 0:u.customDuration)!=null&&u.customDuration>=0?u.customDuration:this.duration}getKey(u){return this.keyPrefix.length>0?`${this.keyPrefix}:${u}`:u}parseKey(u){return u.substring(this.keyPrefix.length)}}class MemoryStorage{constructor(){Z(this,"storage");this.storage=new Map}incrby(u,h,b){const v=this.storage.get(u);if(v!=null){const w=v.expiresAt!=null?v.expiresAt.getTime()-new Date().getTime():-1;return v.expiresAt==null||w>0?(v.value+=h,{remainingPoints:0,msBeforeNext:w,consumedPoints:v.value,isFirstInDuration:!1}):this.set(u,h,b)}return this.set(u,h,b)}set(u,h,b){const v=b*1e3,w=this.storage.get(u);w!=null&&clearTimeout(w.timeoutId);const _={value:h,expiresAt:v>0?new Date(Date.now()+v):void 0};return this.storage.set(u,_),v>0&&(_.timeoutId=setTimeout(()=>{this.storage.delete(u)},v),_.timeoutId.unref!=null&&_.timeoutId.unref()),{remainingPoints:0,msBeforeNext:v===0?-1:v,consumedPoints:_.value,isFirstInDuration:!0}}get(u){const h=this.storage.get(u);if(h!=null)return{remainingPoints:0,msBeforeNext:h.expiresAt!=null?h.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:h.value,isFirstInDuration:!1}}delete(u){const h=this.storage.get(u);return h!=null?(h.timeoutId!=null&&clearTimeout(h.timeoutId),this.storage.delete(u),!0):!1}}var MessageTypes;(function(y){y[y.NEW_STREAM=0]="NEW_STREAM",y[y.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",y[y.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",y[y.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",y[y.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",y[y.RESET_RECEIVER=5]="RESET_RECEIVER",y[y.RESET_INITIATOR=6]="RESET_INITIATOR"})(MessageTypes||(MessageTypes={}));const MessageTypeNames=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),InitiatorMessageTypes=Object.freeze({NEW_STREAM:MessageTypes.NEW_STREAM,MESSAGE:MessageTypes.MESSAGE_INITIATOR,CLOSE:MessageTypes.CLOSE_INITIATOR,RESET:MessageTypes.RESET_INITIATOR}),ReceiverMessageTypes=Object.freeze({MESSAGE:MessageTypes.MESSAGE_RECEIVER,CLOSE:MessageTypes.CLOSE_RECEIVER,RESET:MessageTypes.RESET_RECEIVER}),MAX_MSG_SIZE=1<<20,MAX_MSG_QUEUE_SIZE=4<<20;class Decoder{constructor(u=MAX_MSG_SIZE,h=MAX_MSG_QUEUE_SIZE){Z(this,"_buffer");Z(this,"_headerInfo");Z(this,"_maxMessageSize");Z(this,"_maxUnprocessedMessageQueueSize");this._buffer=new Uint8ArrayList,this._headerInfo=null,this._maxMessageSize=u,this._maxUnprocessedMessageQueueSize=h}write(u){if(u==null||u.length===0)return[];if(this._buffer.append(u),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new InvalidMessageError("Unprocessed message queue size too large!");const h=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(x){if(x.name==="InvalidMessageError")throw x;break}const{id:b,type:v,length:w,offset:_}=this._headerInfo;if(this._buffer.length-_<w)break;const S={id:b,type:v};(v===MessageTypes.NEW_STREAM||v===MessageTypes.MESSAGE_INITIATOR||v===MessageTypes.MESSAGE_RECEIVER)&&(S.data=this._buffer.sublist(_,_+w)),h.push(S),this._buffer.consume(_+w),this._headerInfo=null}return h}_decodeHeader(u){const{value:h,offset:b}=readVarInt(u),{value:v,offset:w}=readVarInt(u,b),_=h&7;if(MessageTypeNames[_]==null)throw new Error(`Invalid type received: ${_}`);if(v>this._maxMessageSize)throw new InvalidMessageError("Message size too large");return{id:h>>3,type:_,offset:b+w,length:v}}}const MSB=128,REST=127;function readVarInt(y,u=0){let h=0,b=0,v=u,w;const _=y.length;do{if(v>=_||b>49)throw u=0,new RangeError("Could not decode varint");w=y.get(v++),h+=b<28?(w&REST)<<b:(w&REST)*Math.pow(2,b),b+=7}while(w>=MSB);return u=v-u,{value:h,offset:u}}const POOL_SIZE=10*1024;class Encoder{constructor(){Z(this,"_pool");Z(this,"_poolOffset");this._pool=allocUnsafe(POOL_SIZE),this._poolOffset=0}write(u,h){const b=this._pool;let v=this._poolOffset;encode$8(u.id<<3|u.type,b,v),v+=encodingLength$1(u.id<<3|u.type),(u.type===MessageTypes.NEW_STREAM||u.type===MessageTypes.MESSAGE_INITIATOR||u.type===MessageTypes.MESSAGE_RECEIVER)&&u.data!=null?(encode$8(u.data.length,b,v),v+=encodingLength$1(u.data.length)):(encode$8(0,b,v),v+=encodingLength$1(0));const w=b.subarray(this._poolOffset,v);POOL_SIZE-v<100?(this._pool=allocUnsafe(POOL_SIZE),this._poolOffset=0):this._poolOffset=v,h.append(w),(u.type===MessageTypes.NEW_STREAM||u.type===MessageTypes.MESSAGE_INITIATOR||u.type===MessageTypes.MESSAGE_RECEIVER)&&u.data!=null&&h.append(u.data)}}const encoder=new Encoder;async function*encode$1(y){for await(const u of y){const h=new Uint8ArrayList;encoder.write(u,h),yield h}}class StreamInputBufferError extends Error{constructor(u="Stream input buffer error"){super(u),this.name="StreamInputBufferError"}}const DEFAULT_SEND_CLOSE_WRITE_TIMEOUT=5e3;function isPromise$1(y){return y==null?!1:typeof y.then=="function"&&typeof y.catch=="function"&&typeof y.finally=="function"}class AbstractStream{constructor(u){Z(this,"id");Z(this,"direction");Z(this,"timeline");Z(this,"protocol");Z(this,"metadata");Z(this,"source");Z(this,"status");Z(this,"readStatus");Z(this,"writeStatus");Z(this,"log");Z(this,"sinkController");Z(this,"sinkEnd");Z(this,"closed");Z(this,"endErr");Z(this,"streamSource");Z(this,"onEnd");Z(this,"onCloseRead");Z(this,"onCloseWrite");Z(this,"onReset");Z(this,"onAbort");Z(this,"sendCloseWriteTimeout");Z(this,"sendingData");this.sinkController=new AbortController,this.sinkEnd=pDefer(),this.closed=pDefer(),this.log=u.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=u.id,this.metadata=u.metadata??{},this.direction=u.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=u.sendCloseWriteTimeout??DEFAULT_SEND_CLOSE_WRITE_TIMEOUT,this.onEnd=u.onEnd,this.onCloseRead=u.onCloseRead,this.onCloseWrite=u.onCloseWrite,this.onReset=u.onReset,this.onAbort=u.onAbort,this.source=this.streamSource=pushable({onEnd:h=>{h!=null?this.log.trace("source ended with error",h):this.log.trace("source ended"),this.onSourceEnd(h)}}),this.sink=this.sink.bind(this)}async sink(u){if(this.writeStatus!=="ready")throw new StreamStateError(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const h={signal:this.sinkController.signal};if(this.direction==="outbound"){const v=this.sendNewStream(h);isPromise$1(v)&&await v}const b=()=>{closeSource(u,this.log)};try{this.sinkController.signal.addEventListener("abort",b),this.log.trace("sink reading from source");for await(let v of u){v=v instanceof Uint8Array?new Uint8ArrayList(v):v;const w=this.sendData(v,h);isPromise$1(w)&&(this.sendingData=pDefer(),await w,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",b)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(h){throw this.log.trace("sink ended with error, calling abort with error",h),this.abort(h),h}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(u){var h;this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",u!=null&&this.endErr==null&&(this.endErr=u),(h=this.onCloseRead)==null||h.call(this),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(u){var h;this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",u!=null&&this.endErr==null&&(this.endErr=u),(h=this.onCloseWrite)==null||h.call(this),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(u){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await raceSignal(Promise.all([this.closeWrite(u),this.closeRead(u),this.closed.promise]),u==null?void 0:u.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(u={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const h=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(u)),h==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(u={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await raceSignal(this.sink([]),u.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await raceSignal(this.sendingData.promise,u.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await raceSignal(this.sinkEnd.promise,u.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(u){var b;if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",u),this.log("try to send reset to remote");const h=this.sendReset();isPromise$1(h)&&h.catch(v=>{this.log.error("error sending reset message",v)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(u),(b=this.onAbort)==null||b.call(this,u)}reset(){var h;if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;const u=new StreamResetError("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(u),(h=this.onReset)==null||h.call(this)}_closeSinkAndSource(u){this._closeSink(u),this._closeSource(u)}_closeSink(u){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(u)}_closeSource(u){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(u))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(u){this.streamSource.push(u)}sourceReadableLength(){return this.streamSource.readableLength}}class MplexStream extends AbstractStream{constructor(h){super(h);Z(this,"name");Z(this,"streamId");Z(this,"send");Z(this,"types");Z(this,"maxDataSize");this.types=h.direction==="outbound"?InitiatorMessageTypes:ReceiverMessageTypes,this.send=h.send,this.name=h.name,this.streamId=h.streamId,this.maxDataSize=h.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:InitiatorMessageTypes.NEW_STREAM,data:new Uint8ArrayList(fromString(this.name))})}async sendData(h){for(h=h.sublist();h.byteLength>0;){const b=Math.min(h.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:h.sublist(0,b)}),h.consume(b)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function createStream(y){const{id:u,name:h,send:b,onEnd:v,type:w="initiator",maxMsgSize:_=MAX_MSG_SIZE}=y;return new MplexStream({id:w==="initiator"?`i${u}`:`r${u}`,streamId:u,name:`${h??u}`,direction:w==="initiator"?"outbound":"inbound",maxDataSize:_,onEnd:v,send:b,log:y.logger.forComponent(`libp2p:mplex:stream:${w}:${u}`)})}const MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION=1024,MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION=1024,MAX_STREAM_BUFFER_SIZE=1024*1024*4,DISCONNECT_THRESHOLD=5,CLOSE_TIMEOUT$2=500;function printMessage(y){const u={...y,type:`${MessageTypeNames[y.type]} (${y.type})`};return y.type===MessageTypes.NEW_STREAM&&(u.data=toString$1(y.data instanceof Uint8Array?y.data:y.data.subarray())),(y.type===MessageTypes.MESSAGE_INITIATOR||y.type===MessageTypes.MESSAGE_RECEIVER)&&(u.data=toString$1(y.data instanceof Uint8Array?y.data:y.data.subarray(),"base16")),u}class MplexStreamMuxer{constructor(u,h){Z(this,"protocol","/mplex/6.7.0");Z(this,"sink");Z(this,"source");Z(this,"log");Z(this,"_streamId");Z(this,"_streams");Z(this,"_init");Z(this,"_source");Z(this,"closeController");Z(this,"rateLimiter");Z(this,"closeTimeout");Z(this,"logger");h=h??{},this.log=u.logger.forComponent("libp2p:mplex"),this.logger=u.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=h,this.closeTimeout=h.closeTimeout??CLOSE_TIMEOUT$2,this.sink=this._createSink(),this._source=pushable({objectMode:!0,onEnd:()=>{for(const b of this._streams.initiators.values())b.destroy();for(const b of this._streams.receivers.values())b.destroy()}}),this.source=pipe$1(this._source,b=>encode$1(b)),this.closeController=new AbortController,this.rateLimiter=new RateLimiter({points:h.disconnectThreshold??DISCONNECT_THRESHOLD,duration:1})}get streams(){const u=[];for(const h of this._streams.initiators.values())u.push(h);for(const h of this._streams.receivers.values())u.push(h);return u}newStream(u){if(this.closeController.signal.aborted)throw new MuxerClosedError("Muxer already closed");const h=this._streamId++;u=u==null?h.toString():u.toString();const b=this._streams.initiators;return this._newStream({id:h,name:u,type:"initiator",registry:b})}async close(u){if(this.closeController.signal.aborted)return;const h=(u==null?void 0:u.signal)??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async b=>b.close({signal:h}))),this._source.end(),await this._source.onEmpty({signal:h}),this.closeController.abort()}catch(b){this.abort(b)}}abort(u){this.closeController.signal.aborted||(this.streams.forEach(h=>{h.abort(u)}),this.closeController.abort(u))}_newReceiverStream(u){const{id:h,name:b}=u,v=this._streams.receivers;return this._newStream({id:h,name:b,type:"receiver",registry:v})}_newStream(u){const{id:h,name:b,type:v,registry:w}=u;if(this.log("new %s stream %s",v,h),v==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION))throw new TooManyOutboundProtocolStreamsError("Too many outbound streams open");if(w.has(h))throw new Error(`${v} stream ${h} already exists!`);const S=createStream({id:h,name:b,send:async x=>{this.log.enabled&&this.log.trace("%s stream %s send",v,h,printMessage(x)),this._source.push(x)},type:v,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",v,h,S.protocol),w.delete(h),this._init.onStreamEnd!=null&&this._init.onStreamEnd(S)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return w.set(h,S),S}_createSink(){return async h=>{const b=()=>{closeSource(h,this.log)};this.closeController.signal.addEventListener("abort",b);try{const v=new Decoder(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const w of h)for(const _ of v.write(w))await this._handleIncoming(_);this._source.end()}catch(v){this.log("error in sink",v),this._source.end(v)}finally{this.closeController.signal.removeEventListener("abort",b)}}}async _handleIncoming(u){const{id:h,type:b}=u;if(this.log.enabled&&this.log.trace("incoming message",printMessage(u)),u.type===MessageTypes.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)){this.log("too many inbound streams open"),this._source.push({id:h,type:MessageTypes.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}const E=this._newReceiverStream({id:h,name:toString$1(u.data instanceof Uint8Array?u.data:u.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(E);return}const w=((b&1)===1?this._streams.initiators:this._streams.receivers).get(h);if(w==null){this.log("missing stream %s for message type %s",h,MessageTypeNames[b]);try{await this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}const _=this._init.maxStreamBufferSize??MAX_STREAM_BUFFER_SIZE;try{switch(b){case MessageTypes.MESSAGE_INITIATOR:case MessageTypes.MESSAGE_RECEIVER:if(w.sourceReadableLength()>_)throw this._source.push({id:u.id,type:b===MessageTypes.MESSAGE_INITIATOR?MessageTypes.RESET_RECEIVER:MessageTypes.RESET_INITIATOR}),new StreamInputBufferError("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");w.sourcePush(u.data);break;case MessageTypes.CLOSE_INITIATOR:case MessageTypes.CLOSE_RECEIVER:w.remoteCloseWrite();break;case MessageTypes.RESET_INITIATOR:case MessageTypes.RESET_RECEIVER:w.reset();break;default:this.log("unknown message type %s",b)}}catch(E){this.log.error("error while processing message",E),w.abort(E)}}}var fh,lh;lh=Symbol.toStringTag,fh=serviceCapabilities;class Mplex{constructor(u,h={}){Z(this,"protocol","/mplex/6.7.0");Z(this,"_init");Z(this,"components");Z(this,lh,"@libp2p/mplex");Z(this,fh,["@libp2p/stream-multiplexing"]);this.components=u,this._init=h}createStreamMuxer(u={}){return new MplexStreamMuxer(this.components,{...u,...this._init})}}function mplex(y={}){return u=>new Mplex(u,y)}const PING_LENGTH$1=32,PROTOCOL_VERSION$1="1.0.0",PROTOCOL_NAME$1="ping",PROTOCOL_PREFIX$1="ipfs",TIMEOUT=1e4,MAX_INBOUND_STREAMS=2,MAX_OUTBOUND_STREAMS=1;var hh,ph;ph=Symbol.toStringTag,hh=serviceCapabilities;class Ping{constructor(u,h={}){Z(this,"protocol");Z(this,"components");Z(this,"started");Z(this,"timeout");Z(this,"maxInboundStreams");Z(this,"maxOutboundStreams");Z(this,"runOnLimitedConnection");Z(this,"log");Z(this,ph,"@libp2p/ping");Z(this,hh,["@libp2p/ping"]);this.components=u,this.log=u.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${h.protocolPrefix??PROTOCOL_PREFIX$1}/${PROTOCOL_NAME$1}/${PROTOCOL_VERSION$1}`,this.timeout=h.timeout??TIMEOUT,this.maxInboundStreams=h.maxInboundStreams??MAX_INBOUND_STREAMS,this.maxOutboundStreams=h.maxOutboundStreams??MAX_OUTBOUND_STREAMS,this.runOnLimitedConnection=h.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(u){this.log("incoming ping from %p",u.connection.remotePeer);const{stream:h}=u,b=Date.now(),v=byteStream(h);let w=!1;Promise.resolve().then(async()=>{for(;;){const _=AbortSignal.timeout(this.timeout);_.addEventListener("abort",()=>{h==null||h.abort(new TimeoutError$1("ping timeout"))});const E=await v.read({bytes:PING_LENGTH$1,signal:_});await v.write(E,{signal:_}),w=!0}}).catch(_=>{w&&_.name==="UnexpectedEOFError"&&h.readStatus!=="ready"||(this.log.error("incoming ping from %p failed with error - %e",u.connection.remotePeer,_),h==null||h.abort(_))}).finally(()=>{const _=Date.now()-b;this.log("incoming ping from %p complete in %dms",u.connection.remotePeer,_);const E=AbortSignal.timeout(this.timeout);h.close({signal:E}).catch(S=>{this.log.error("error closing ping stream from %p - %e",u.connection.remotePeer,S),h==null||h.abort(S)})})}async ping(u,h={}){this.log("pinging %p",u);const b=Date.now(),v=randomBytes$3(PING_LENGTH$1),w=await this.components.connectionManager.openConnection(u,h);let _;if(h.signal==null){const E=AbortSignal.timeout(this.timeout);h={...h,signal:E}}try{_=await w.newStream(this.protocol,{...h,runOnLimitedConnection:this.runOnLimitedConnection});const E=byteStream(_),[,S]=await Promise.all([E.write(v,h),E.read({...h,bytes:PING_LENGTH$1})]),x=Date.now()-b;if(!equals(v,S.subarray()))throw new ProtocolError$1(`Received wrong ping ack after ${x}ms`);return this.log("ping %p complete in %dms",w.remotePeer,x),x}catch(E){throw this.log.error("error while pinging %p",w.remotePeer,E),_==null||_.abort(E),E}finally{_!=null&&await _.close(h)}}}function ping(y={}){return u=>new Ping(u,y)}const ASSUME_HTTP_CODES=[CODE_TCP,CODE_DNS,CODE_DNSADDR,CODE_DNS4,CODE_DNS6];function extractSNI(y){var u;return(u=extractTuple("sni",y))==null?void 0:u.value}function extractPort(y){var h;const u=(h=extractTuple("tcp",y))==null?void 0:h.value;return u==null?"":`:${u}`}function extractTuple(y,u){return u.find(h=>h.name===y)}function hasTLS(y){return y.some(({code:u})=>u===CODE_TLS)}function interpretNext(y,u){const h=interpreters[y.name];if(h==null)throw new Error(`Can't interpret protocol ${y.name}`);const b=h(y,u);return y.code===CODE_IP6?`[${b}]`:b}const interpreters={ip4:(y,u)=>y.value,ip6:(y,u)=>u.length===0?y.value:`[${y.value}]`,tcp:(y,u)=>{const h=u.pop();if(h==null)throw new Error("Unexpected end of multiaddr");return`tcp://${interpretNext(h,u)}:${y.value}`},udp:(y,u)=>{const h=u.pop();if(h==null)throw new Error("Unexpected end of multiaddr");return`udp://${interpretNext(h,u)}:${y.value}`},dnsaddr:(y,u)=>y.value,dns4:(y,u)=>y.value,dns6:(y,u)=>y.value,dns:(y,u)=>y.value,ipfs:(y,u)=>{const h=u.pop();if(h==null)throw new Error("Unexpected end of multiaddr");return`${interpretNext(h,u)}`},p2p:(y,u)=>{const h=u.pop();if(h==null)throw new Error("Unexpected end of multiaddr");return`${interpretNext(h,u)}`},http:(y,u)=>{const h=hasTLS(u),b=extractSNI(u),v=extractPort(u);if(h&&b!=null)return`https://${b}${v}`;const w=h?"https://":"http://",_=u.pop();if(_==null)throw new Error("Unexpected end of multiaddr");let E=interpretNext(_,u);return E=E==null?void 0:E.replace("tcp://",""),`${w}${E}`},"http-path":(y,u)=>{const h=u.pop();if(h==null)throw new Error("Unexpected end of multiaddr");const b=interpretNext(h,u),v=decodeURIComponent(y.value??"");return`${b}${v}`},tls:(y,u)=>{const h=u.pop();if(h==null)throw new Error("Unexpected end of multiaddr");return interpretNext(h,u)},sni:(y,u)=>{const h=u.pop();if(h==null)throw new Error("Unexpected end of multiaddr");return interpretNext(h,u)},https:(y,u)=>{const h=u.pop();if(h==null)throw new Error("Unexpected end of multiaddr");let b=interpretNext(h,u);return b=b==null?void 0:b.replace("tcp://",""),`https://${b}`},ws:(y,u)=>{const h=hasTLS(u),b=extractSNI(u),v=extractPort(u);if(h&&b!=null)return`wss://${b}${v}`;const w=h?"wss://":"ws://",_=u.pop();if(_==null)throw new Error("Unexpected end of multiaddr");let E=interpretNext(_,u);return E=E==null?void 0:E.replace("tcp://",""),`${w}${E}`},wss:(y,u)=>{const h=u.pop();if(h==null)throw new Error("Unexpected end of multiaddr");let b=interpretNext(h,u);return b=b==null?void 0:b.replace("tcp://",""),`wss://${b}`}};function multiaddrToUri(y,u){const b=multiaddr(y).getComponents(),v=b.pop();if(v==null)throw new Error("Unexpected end of multiaddr");const w=interpreters[v.name];if(w==null)throw new Error(`No interpreter found for ${v.name}`);let _=w(v,b)??"";return ASSUME_HTTP_CODES.includes(v.code)&&(_=_.replace(/^.*:\/\//,""),v.value==="443"?_=`https://${_}`:_=`http://${_}`),(_.startsWith("http://")||_.startsWith("https://")||_.startsWith("ws://")||_.startsWith("wss://"))&&(_=new URL(_).toString(),_.endsWith("/")&&(_=_.substring(0,_.length-1))),_}const ready=async y=>{if(y.readyState>=2)throw new Error("socket closed");y.readyState!==1&&await new Promise((u,h)=>{function b(){y.removeEventListener("open",v),y.removeEventListener("error",w)}function v(){b(),u()}function w(_){b(),h(_.error??new Error(`connect ECONNREFUSED ${y.url}`))}y.addEventListener("open",v),y.addEventListener("error",w)})},sink=(y,u)=>(u=u??{},u.closeOnEnd=u.closeOnEnd!==!1,async b=>{for await(const v of b){try{await ready(y)}catch(w){if(w.message==="socket closed")break;throw w}if(y.readyState===y.CLOSING||y.readyState===y.CLOSED)break;y.send(v)}u.closeOnEnd!=null&&y.readyState<=1&&await new Promise((v,w)=>{y.addEventListener("close",_=>{if(_.wasClean||_.code===1006)v();else{const E=Object.assign(new Error("ws error"),{event:_});w(E)}}),setTimeout(()=>{y.close()})})});var dom={},eventIterator={};Object.defineProperty(eventIterator,"__esModule",{value:!0});class EventQueue{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(u){if(this.isStopped)return;const h={value:u,done:!1};if(this.pullQueue.length){const b=this.pullQueue.shift();b&&b.resolve(h)}else this.pushQueue.push(Promise.resolve(h)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const u of this.pullQueue)u.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(u){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const h of this.pullQueue)h.reject(u);this.pullQueue.length=0}else{const h=Promise.reject(u);h.catch(()=>{}),this.pushQueue.push(h)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:u=>{const h=this.pushQueue.shift();return h?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),h):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((b,v)=>{this.pullQueue.push({resolve:b,reject:v})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}let EventIterator$1=class{constructor(u,{highWaterMark:h=100,lowWaterMark:b=1}={}){const v=new EventQueue;v.highWaterMark=h,v.lowWaterMark=b,v.removeCallback=u({push:w=>v.push(w),stop:()=>v.stop(),fail:w=>v.fail(w),on:(w,_)=>{v.eventHandlers[w]=_}})||(()=>{}),this[Symbol.asyncIterator]=()=>v[Symbol.asyncIterator](),Object.freeze(this)}};eventIterator.EventIterator=EventIterator$1;eventIterator.default=EventIterator$1;Object.defineProperty(dom,"__esModule",{value:!0});const event_iterator_1=eventIterator;var EventIterator=dom.EventIterator=event_iterator_1.EventIterator;function subscribe(y,u,h){return new event_iterator_1.EventIterator(({push:b})=>(this.addEventListener(y,b,u),()=>this.removeEventListener(y,b,u)),h)}dom.subscribe=subscribe;dom.default=event_iterator_1.EventIterator;function isArrayBuffer(y){var u;return y instanceof ArrayBuffer||((u=y==null?void 0:y.constructor)==null?void 0:u.name)==="ArrayBuffer"&&typeof(y==null?void 0:y.byteLength)=="number"}const source=y=>{y.binaryType="arraybuffer";const u=async()=>{await new Promise((w,_)=>{if(b){w();return}if(v!=null){_(v);return}const E=T=>{y.removeEventListener("open",S),y.removeEventListener("error",x),T()},S=()=>{E(w)},x=T=>{E(()=>{_(T.error??new Error(`connect ECONNREFUSED ${y.url}`))})};y.addEventListener("open",S),y.addEventListener("error",x)})},h=async function*(){const w=new EventIterator(({push:_,stop:E,fail:S})=>{const x=C=>{let O=null;typeof C.data=="string"&&(O=fromString(C.data)),isArrayBuffer(C.data)&&(O=new Uint8Array(C.data)),C.data instanceof Uint8Array&&(O=C.data),O!=null&&_(O)},T=C=>{S(C.error??new Error("Socket error"))};return y.addEventListener("message",x),y.addEventListener("error",T),y.addEventListener("close",E),()=>{y.removeEventListener("message",x),y.removeEventListener("error",T),y.removeEventListener("close",E)}},{highWaterMark:1/0});await u();for await(const _ of w)yield isArrayBuffer(_)?new Uint8Array(_):_}();let b=y.readyState===1,v;return y.addEventListener("open",()=>{b=!0,v=null}),y.addEventListener("close",()=>{b=!1,v=null}),y.addEventListener("error",w=>{b||(v=w.error??new Error(`connect ECONNREFUSED ${y.url}`))}),Object.assign(h,{connected:u})},duplex=(y,u)=>{u=u??{};const h=source(y);let b=u.remoteAddress,v=u.remotePort;if(y.url!=null)try{const _=new URL(y.url);b=_.hostname,v=parseInt(_.port,10)}catch{}if(b==null||v==null)throw new Error("Remote connection did not have address and/or port");return{sink:sink(y,u),source:h,connected:async()=>{await h.connected()},close:async()=>{(y.readyState===y.CONNECTING||y.readyState===y.OPEN)&&await new Promise(_=>{y.addEventListener("close",()=>{_()}),y.close()})},destroy:()=>{y.terminate!=null?y.terminate():y.close()},remoteAddress:b,remotePort:v,socket:y}},WebSocket$1=WebSocket,map={"http:":"ws:","https:":"wss:"},defaultProtocol="ws:",wsurl=(y,u)=>{if(y.startsWith("//")&&(y=`${(u==null?void 0:u.protocol)??defaultProtocol}${y}`),y.startsWith("/")&&u!=null){const b=u.protocol??defaultProtocol,v=u.host,w=u.port!=null&&(v==null?void 0:v.endsWith(`:${u.port}`))!==!0?`:${u.port}`:"";y=`${b}//${v}${w}${y}`}const h=new URL(y);for(const[b,v]of Object.entries(map))h.protocol===b&&(h.protocol=v);return h};function connect(y,u){const h=typeof window>"u"?void 0:window.location;u=u??{};const b=wsurl(y,h),v=new WebSocket$1(b.toString(),u.websocket);return duplex(v,u)}class CustomProgressEvent extends Event{constructor(h,b){super(h);Z(this,"type");Z(this,"detail");this.type=h,this.detail=b}}function all$1(y){return y.filter(u=>WebSocketsSecure.exactMatch(u)||WebSockets$1.exactMatch(u))}function wss(y){return y.filter(u=>WebSocketsSecure.exactMatch(u))}function createListener(){throw new Error("WebSocket Servers can not be created in the browser!")}const CLOSE_TIMEOUT$1=500;function socketToMaConn(y,u,h){const b=h.logger.forComponent("libp2p:websockets:maconn"),v=h.metrics,w=h.metricPrefix??"",_={log:b,async sink(E){try{await y.sink(async function*(){for await(const S of E)S instanceof Uint8Array?yield S:yield S.subarray()}())}catch(S){S.type!=="aborted"&&b.error(S)}},source:y.source,remoteAddr:u,timeline:{open:Date.now()},async close(E={}){var T,C;const S=Date.now();if(E.signal==null){const O=AbortSignal.timeout(CLOSE_TIMEOUT$1);E={...E,signal:O}}const x=()=>{const{host:O,port:D}=_.remoteAddr.toOptions();b("timeout closing stream to %s:%s after %dms, destroying it manually",O,D,Date.now()-S),this.abort(new AbortError$5("Socket close timeout"))};(T=E.signal)==null||T.addEventListener("abort",x);try{await y.close()}catch(O){b.error("error closing WebSocket gracefully",O),this.abort(O)}finally{(C=E.signal)==null||C.removeEventListener("abort",x),_.timeline.close=Date.now()}},abort(E){const{host:S,port:x}=_.remoteAddr.toOptions();b("timeout closing stream to %s:%s due to error",S,x,E),y.destroy(),_.timeline.close=Date.now(),v==null||v.increment({[`${w}error`]:!0})}};return y.socket.addEventListener("close",()=>{v==null||v.increment({[`${w}close`]:!0}),_.timeline.close==null&&(_.timeline.close=Date.now())},{once:!0}),_}var gh,mh,yh;yh=transportSymbol,mh=Symbol.toStringTag,gh=serviceCapabilities;class WebSockets{constructor(u,h={}){Z(this,"log");Z(this,"init");Z(this,"logger");Z(this,"metrics");Z(this,"components");Z(this,yh,!0);Z(this,mh,"@libp2p/websockets");Z(this,gh,["@libp2p/transport"]);this.log=u.logger.forComponent("libp2p:websockets"),this.logger=u.logger,this.components=u,this.init=h,u.metrics!=null&&(this.metrics={dialerEvents:u.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}async dial(u,h){var _;this.log("dialing %s",u),h=h??{};const b=await this._connect(u,h),v=socketToMaConn(b,u,{logger:this.logger,metrics:(_=this.metrics)==null?void 0:_.dialerEvents});this.log("new outbound connection %s",v.remoteAddr);const w=await h.upgrader.upgradeOutbound(v,h);return this.log("outbound connection %s upgraded",v.remoteAddr),w}async _connect(u,h){var _,E,S,x,T;(_=h==null?void 0:h.signal)==null||_.throwIfAborted();const b=u.toOptions();this.log("dialing %s:%s",b.host,b.port);const v=pDefer(),w=connect(multiaddrToUri(u),this.init);w.socket.addEventListener("error",()=>{var O;const C=new ConnectionFailedError(`Could not connect to ${u.toString()}`);this.log.error("connection error:",C),(O=this.metrics)==null||O.dialerEvents.increment({error:!0}),v.reject(C)});try{(E=h.onProgress)==null||E.call(h,new CustomProgressEvent("websockets:open-connection")),await raceSignal(Promise.race([w.connected(),v.promise]),h.signal)}catch(C){throw(S=h.signal)!=null&&S.aborted&&((x=this.metrics)==null||x.dialerEvents.increment({abort:!0})),w.close().catch(O=>{this.log.error("error closing raw socket",O)}),C}return this.log("connected %s",u),(T=this.metrics)==null||T.dialerEvents.increment({connect:!0}),w}createListener(u){return createListener({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...u})}listenFilter(u){var h,b;return u=Array.isArray(u)?u:[u],((h=this.init)==null?void 0:h.filter)!=null?(b=this.init)==null?void 0:b.filter(u):all$1(u)}dialFilter(u){return this.listenFilter(u)}}function webSockets(y={}){return u=>new WebSockets(u,y)}function isPlainObject(y){if(typeof y!="object"||y===null)return!1;const u=Object.getPrototypeOf(y);return(u===null||u===Object.prototype||Object.getPrototypeOf(u)===null)&&!(Symbol.toStringTag in y)&&!(Symbol.iterator in y)}const{hasOwnProperty:hasOwnProperty$1}=Object.prototype,{propertyIsEnumerable}=Object,defineProperty=(y,u,h)=>{Object.defineProperty(y,u,{value:h,writable:!0,enumerable:!0,configurable:!0})},globalThis$1=void 0,defaultMergeOptions={concatArrays:!1,ignoreUndefined:!1},getEnumerableOwnPropertyKeys=y=>{const u=[];for(const h in y)hasOwnProperty$1.call(y,h)&&u.push(h);if(Object.getOwnPropertySymbols){const h=Object.getOwnPropertySymbols(y);for(const b of h)propertyIsEnumerable.call(y,b)&&u.push(b)}return u};function clone(y){return Array.isArray(y)?cloneArray(y):isPlainObject(y)?cloneOptionObject(y):y}function cloneArray(y){const u=y.slice(0,0);return getEnumerableOwnPropertyKeys(y).forEach(h=>{defineProperty(u,h,clone(y[h]))}),u}function cloneOptionObject(y){const u=Object.getPrototypeOf(y)===null?Object.create(null):{};return getEnumerableOwnPropertyKeys(y).forEach(h=>{defineProperty(u,h,clone(y[h]))}),u}const mergeKeys=(y,u,h,b)=>(h.forEach(v=>{typeof u[v]>"u"&&b.ignoreUndefined||(v in y&&y[v]!==Object.getPrototypeOf(y)?defineProperty(y,v,merge(y[v],u[v],b)):defineProperty(y,v,clone(u[v])))}),y),concatArrays=(y,u,h)=>{let b=y.slice(0,0),v=0;return[y,u].forEach(w=>{const _=[];for(let E=0;E<w.length;E++)hasOwnProperty$1.call(w,E)&&(_.push(String(E)),w===y?defineProperty(b,v++,w[E]):defineProperty(b,v++,clone(w[E])));b=mergeKeys(b,w,getEnumerableOwnPropertyKeys(w).filter(E=>!_.includes(E)),h)}),b};function merge(y,u,h){return h.concatArrays&&Array.isArray(y)&&Array.isArray(u)?concatArrays(y,u,h):!isPlainObject(u)||!isPlainObject(y)?clone(u):mergeKeys(y,u,getEnumerableOwnPropertyKeys(u),h)}function mergeOptions(...y){const u=merge(clone(defaultMergeOptions),this!==globalThis$1&&this||{},defaultMergeOptions);let h={_:{}};for(const b of y)if(b!==void 0){if(!isPlainObject(b))throw new TypeError("`"+b+"` is not an Option Object");h=merge(h,{_:b},u)}return h._}var eventemitter3={exports:{}};(function(y){var u=Object.prototype.hasOwnProperty,h="~";function b(){}Object.create&&(b.prototype=Object.create(null),new b().__proto__||(h=!1));function v(S,x,T){this.fn=S,this.context=x,this.once=T||!1}function w(S,x,T,C,O){if(typeof T!="function")throw new TypeError("The listener must be a function");var D=new v(T,C||S,O),U=h?h+x:x;return S._events[U]?S._events[U].fn?S._events[U]=[S._events[U],D]:S._events[U].push(D):(S._events[U]=D,S._eventsCount++),S}function _(S,x){--S._eventsCount===0?S._events=new b:delete S._events[x]}function E(){this._events=new b,this._eventsCount=0}E.prototype.eventNames=function(){var x=[],T,C;if(this._eventsCount===0)return x;for(C in T=this._events)u.call(T,C)&&x.push(h?C.slice(1):C);return Object.getOwnPropertySymbols?x.concat(Object.getOwnPropertySymbols(T)):x},E.prototype.listeners=function(x){var T=h?h+x:x,C=this._events[T];if(!C)return[];if(C.fn)return[C.fn];for(var O=0,D=C.length,U=new Array(D);O<D;O++)U[O]=C[O].fn;return U},E.prototype.listenerCount=function(x){var T=h?h+x:x,C=this._events[T];return C?C.fn?1:C.length:0},E.prototype.emit=function(x,T,C,O,D,U){var te=h?h+x:x;if(!this._events[te])return!1;var X=this._events[te],ie=arguments.length,ee,ae;if(X.fn){switch(X.once&&this.removeListener(x,X.fn,void 0,!0),ie){case 1:return X.fn.call(X.context),!0;case 2:return X.fn.call(X.context,T),!0;case 3:return X.fn.call(X.context,T,C),!0;case 4:return X.fn.call(X.context,T,C,O),!0;case 5:return X.fn.call(X.context,T,C,O,D),!0;case 6:return X.fn.call(X.context,T,C,O,D,U),!0}for(ae=1,ee=new Array(ie-1);ae<ie;ae++)ee[ae-1]=arguments[ae];X.fn.apply(X.context,ee)}else{var de=X.length,Se;for(ae=0;ae<de;ae++)switch(X[ae].once&&this.removeListener(x,X[ae].fn,void 0,!0),ie){case 1:X[ae].fn.call(X[ae].context);break;case 2:X[ae].fn.call(X[ae].context,T);break;case 3:X[ae].fn.call(X[ae].context,T,C);break;case 4:X[ae].fn.call(X[ae].context,T,C,O);break;default:if(!ee)for(Se=1,ee=new Array(ie-1);Se<ie;Se++)ee[Se-1]=arguments[Se];X[ae].fn.apply(X[ae].context,ee)}}return!0},E.prototype.on=function(x,T,C){return w(this,x,T,C,!1)},E.prototype.once=function(x,T,C){return w(this,x,T,C,!0)},E.prototype.removeListener=function(x,T,C,O){var D=h?h+x:x;if(!this._events[D])return this;if(!T)return _(this,D),this;var U=this._events[D];if(U.fn)U.fn===T&&(!O||U.once)&&(!C||U.context===C)&&_(this,D);else{for(var te=0,X=[],ie=U.length;te<ie;te++)(U[te].fn!==T||O&&!U[te].once||C&&U[te].context!==C)&&X.push(U[te]);X.length?this._events[D]=X.length===1?X[0]:X:_(this,D)}return this},E.prototype.removeAllListeners=function(x){var T;return x?(T=h?h+x:x,this._events[T]&&_(this,T)):(this._events=new b,this._eventsCount=0),this},E.prototype.off=E.prototype.removeListener,E.prototype.addListener=E.prototype.on,E.prefixed=h,E.EventEmitter=E,y.exports=E})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter$2=getDefaultExportFromCjs$1(eventemitter3Exports);class TimeoutError extends Error{constructor(u){super(u),this.name="TimeoutError"}}let AbortError$2=class extends Error{constructor(u){super(),this.name="AbortError",this.message=u}};const getDOMException=y=>globalThis.DOMException===void 0?new AbortError$2(y):new DOMException(y),getAbortedReason=y=>{const u=y.reason===void 0?getDOMException("This operation was aborted."):y.reason;return u instanceof Error?u:getDOMException(u)};function pTimeout(y,u){const{milliseconds:h,fallback:b,message:v,customTimers:w={setTimeout,clearTimeout}}=u;let _,E;const x=new Promise((T,C)=>{if(typeof h!="number"||Math.sign(h)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${h}\``);if(u.signal){const{signal:D}=u;D.aborted&&C(getAbortedReason(D)),E=()=>{C(getAbortedReason(D))},D.addEventListener("abort",E,{once:!0})}if(h===Number.POSITIVE_INFINITY){y.then(T,C);return}const O=new TimeoutError;_=w.setTimeout.call(void 0,()=>{if(b){try{T(b())}catch(D){C(D)}return}typeof y.cancel=="function"&&y.cancel(),v===!1?T():v instanceof Error?C(v):(O.message=v??`Promise timed out after ${h} milliseconds`,C(O))},h),(async()=>{try{T(await y)}catch(D){C(D)}})()}).finally(()=>{x.clear(),E&&u.signal&&u.signal.removeEventListener("abort",E)});return x.clear=()=>{w.clearTimeout.call(void 0,_),_=void 0},x}function lowerBound(y,u,h){let b=0,v=y.length;for(;v>0;){const w=Math.trunc(v/2);let _=b+w;h(y[_],u)<=0?(b=++_,v-=w+1):v=w}return b}var kn,bh;let PriorityQueue$1=(bh=class{constructor(){ur(this,kn,[])}enqueue(u,h){h={priority:0,...h};const b={priority:h.priority,id:h.id,run:u};if(this.size===0||je(this,kn)[this.size-1].priority>=h.priority){je(this,kn).push(b);return}const v=lowerBound(je(this,kn),b,(w,_)=>_.priority-w.priority);je(this,kn).splice(v,0,b)}setPriority(u,h){const b=je(this,kn).findIndex(w=>w.id===u);if(b===-1)throw new ReferenceError(`No promise function with the id "${u}" exists in the queue.`);const[v]=je(this,kn).splice(b,1);this.enqueue(v.run,{priority:h,id:u})}dequeue(){const u=je(this,kn).shift();return u==null?void 0:u.run}filter(u){return je(this,kn).filter(h=>h.priority===u.priority).map(h=>h.run)}get size(){return je(this,kn).length}},kn=new WeakMap,bh);var No,Lo,Xi,rc,Fo,nc,Nn,Uo,nn,ic,Ln,qo,Mi,sc,Vu,fr,Bh,kh,Nh,Lh,Fh,Du,ed,td,Bu,Uh,ku;class PQueue extends EventEmitter$2{constructor(h){var b,v;super();ur(this,fr);ur(this,No);ur(this,Lo);ur(this,Xi,0);ur(this,rc);ur(this,Fo);ur(this,nc,0);ur(this,Nn);ur(this,Uo);ur(this,nn);ur(this,ic);ur(this,Ln,0);ur(this,qo);ur(this,Mi);ur(this,sc);ur(this,Vu,1n);Z(this,"timeout");if(h={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:PriorityQueue$1,...h},!(typeof h.intervalCap=="number"&&h.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${((b=h.intervalCap)==null?void 0:b.toString())??""}\` (${typeof h.intervalCap})`);if(h.interval===void 0||!(Number.isFinite(h.interval)&&h.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${((v=h.interval)==null?void 0:v.toString())??""}\` (${typeof h.interval})`);Ft(this,No,h.carryoverConcurrencyCount),Ft(this,Lo,h.intervalCap===Number.POSITIVE_INFINITY||h.interval===0),Ft(this,rc,h.intervalCap),Ft(this,Fo,h.interval),Ft(this,nn,new h.queueClass),Ft(this,ic,h.queueClass),this.concurrency=h.concurrency,this.timeout=h.timeout,Ft(this,sc,h.throwOnTimeout===!0),Ft(this,Mi,h.autoStart===!1)}get concurrency(){return je(this,qo)}set concurrency(h){if(!(typeof h=="number"&&h>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${h}\` (${typeof h})`);Ft(this,qo,h),$t(this,fr,Bu).call(this)}setPriority(h,b){je(this,nn).setPriority(h,b)}async add(h,b={}){return b.id??(b.id=(Ls(this,Vu)._++).toString()),b={timeout:this.timeout,throwOnTimeout:je(this,sc),...b},new Promise((v,w)=>{je(this,nn).enqueue(async()=>{var _;Ls(this,Ln)._++;try{(_=b.signal)==null||_.throwIfAborted(),Ls(this,Xi)._++;let E=h({signal:b.signal});b.timeout&&(E=pTimeout(Promise.resolve(E),{milliseconds:b.timeout})),b.signal&&(E=Promise.race([E,$t(this,fr,Uh).call(this,b.signal)]));const S=await E;v(S),this.emit("completed",S)}catch(E){if(E instanceof TimeoutError&&!b.throwOnTimeout){v();return}w(E),this.emit("error",E)}finally{$t(this,fr,Nh).call(this)}},b),this.emit("add"),$t(this,fr,Du).call(this)})}async addAll(h,b){return Promise.all(h.map(async v=>this.add(v,b)))}start(){return je(this,Mi)?(Ft(this,Mi,!1),$t(this,fr,Bu).call(this),this):this}pause(){Ft(this,Mi,!0)}clear(){Ft(this,nn,new(je(this,ic)))}async onEmpty(){je(this,nn).size!==0&&await $t(this,fr,ku).call(this,"empty")}async onSizeLessThan(h){je(this,nn).size<h||await $t(this,fr,ku).call(this,"next",()=>je(this,nn).size<h)}async onIdle(){je(this,Ln)===0&&je(this,nn).size===0||await $t(this,fr,ku).call(this,"idle")}get size(){return je(this,nn).size}sizeBy(h){return je(this,nn).filter(h).length}get pending(){return je(this,Ln)}get isPaused(){return je(this,Mi)}}No=new WeakMap,Lo=new WeakMap,Xi=new WeakMap,rc=new WeakMap,Fo=new WeakMap,nc=new WeakMap,Nn=new WeakMap,Uo=new WeakMap,nn=new WeakMap,ic=new WeakMap,Ln=new WeakMap,qo=new WeakMap,Mi=new WeakMap,sc=new WeakMap,Vu=new WeakMap,fr=new WeakSet,Bh=function(){return je(this,Lo)||je(this,Xi)<je(this,rc)},kh=function(){return je(this,Ln)<je(this,qo)},Nh=function(){Ls(this,Ln)._--,$t(this,fr,Du).call(this),this.emit("next")},Lh=function(){$t(this,fr,td).call(this),$t(this,fr,ed).call(this),Ft(this,Uo,void 0)},Fh=function(){const h=Date.now();if(je(this,Nn)===void 0){const b=je(this,nc)-h;if(b<0)Ft(this,Xi,je(this,No)?je(this,Ln):0);else return je(this,Uo)===void 0&&Ft(this,Uo,setTimeout(()=>{$t(this,fr,Lh).call(this)},b)),!0}return!1},Du=function(){if(je(this,nn).size===0)return je(this,Nn)&&clearInterval(je(this,Nn)),Ft(this,Nn,void 0),this.emit("empty"),je(this,Ln)===0&&this.emit("idle"),!1;if(!je(this,Mi)){const h=!je(this,fr,Fh);if(je(this,fr,Bh)&&je(this,fr,kh)){const b=je(this,nn).dequeue();return b?(this.emit("active"),b(),h&&$t(this,fr,ed).call(this),!0):!1}}return!1},ed=function(){je(this,Lo)||je(this,Nn)!==void 0||(Ft(this,Nn,setInterval(()=>{$t(this,fr,td).call(this)},je(this,Fo))),Ft(this,nc,Date.now()+je(this,Fo)))},td=function(){je(this,Xi)===0&&je(this,Ln)===0&&je(this,Nn)&&(clearInterval(je(this,Nn)),Ft(this,Nn,void 0)),Ft(this,Xi,je(this,No)?je(this,Ln):0),$t(this,fr,Bu).call(this)},Bu=function(){for(;$t(this,fr,Du).call(this););},Uh=async function(h){return new Promise((b,v)=>{h.addEventListener("abort",()=>{v(h.reason)},{once:!0})})},ku=async function(h,b){return new Promise(v=>{const w=()=>{b&&!b()||(this.off(h,w),v())};this.on(h,w)})};function getTypes(y){const u=[RecordType.A];return y==null?u:Array.isArray(y)?y.length===0?u:y:[y]}const DEFAULT_TTL=60;function toDNSResponse(y){return{Status:y.Status??0,TC:y.TC??y.flag_tc??!1,RD:y.RD??y.flag_rd??!1,RA:y.RA??y.flag_ra??!1,AD:y.AD??y.flag_ad??!1,CD:y.CD??y.flag_cd??!1,Question:(y.Question??y.questions??[]).map(u=>({name:u.name,type:RecordType[u.type]})),Answer:(y.Answer??y.answers??[]).map(u=>({name:u.name,type:RecordType[u.type],TTL:u.TTL??u.ttl??DEFAULT_TTL,data:u.data instanceof Uint8Array?toString$1(u.data):u.data}))}}const DEFAULT_QUERY_CONCURRENCY=4;function dnsJsonOverHttps(y,u={}){const h=new PQueue({concurrency:u.queryConcurrency??DEFAULT_QUERY_CONCURRENCY});return async(b,v={})=>{var E;const w=new URLSearchParams;w.set("name",b),getTypes(v.types).forEach(S=>{w.append("type",RecordType[S])}),(E=v.onProgress)==null||E.call(v,new CustomProgressEvent("dns:query",b));const _=await h.add(async()=>{var T;const S=await fetch(`${y}?${w}`,{headers:{accept:"application/dns-json"},signal:v==null?void 0:v.signal});if(S.status!==200)throw new Error(`Unexpected HTTP status: ${S.status} - ${S.statusText}`);const x=toDNSResponse(await S.json());return(T=v.onProgress)==null||T.call(v,new CustomProgressEvent("dns:response",x)),x},{signal:v.signal});if(_==null)throw new Error("No DNS response received");return _}}function defaultResolver(){return[dnsJsonOverHttps("https://cloudflare-dns.com/dns-query"),dnsJsonOverHttps("https://dns.google/resolve")]}var hashlru=function(y){if(!y)throw Error("hashlru must have a max value, of type number, greater than 0");var u=0,h=Object.create(null),b=Object.create(null);function v(w,_){h[w]=_,u++,u>=y&&(u=0,b=h,h=Object.create(null))}return{has:function(w){return h[w]!==void 0||b[w]!==void 0},remove:function(w){h[w]!==void 0&&(h[w]=void 0),b[w]!==void 0&&(b[w]=void 0)},get:function(w){var _=h[w];if(_!==void 0)return _;if((_=b[w])!==void 0)return v(w,_),_},set:function(w,_){h[w]!==void 0?h[w]=_:v(w,_)},clear:function(){h=Object.create(null),b=Object.create(null)}}};const hashlru$1=getDefaultExportFromCjs$1(hashlru);class CachedAnswers{constructor(u){Z(this,"lru");this.lru=hashlru$1(u)}get(u,h){let b=!0;const v=[];for(const w of h){const _=this.getAnswers(u,w);if(_.length===0){b=!1;break}v.push(..._)}if(b)return toDNSResponse({answers:v})}getAnswers(u,h){const b=`${u.toLowerCase()}-${h}`,v=this.lru.get(b);if(v!=null){const w=v.filter(_=>_.expires>Date.now()).map(({expires:_,value:E})=>({...E,TTL:Math.round((_-Date.now())/1e3),type:RecordType[E.type]}));return w.length===0&&this.lru.remove(b),w}return[]}add(u,h){const b=`${u.toLowerCase()}-${h.type}`,v=this.lru.get(b)??[];v.push({expires:Date.now()+(h.TTL??DEFAULT_TTL)*1e3,value:h}),this.lru.set(b,v)}remove(u,h){const b=`${u.toLowerCase()}-${h}`;this.lru.remove(b)}clear(){this.lru.clear()}}function cache$1(y){return new CachedAnswers(y)}const DEFAULT_ANSWER_CACHE_SIZE=1e3;class DNS{constructor(u){Z(this,"resolvers");Z(this,"cache");this.resolvers={},this.cache=cache$1(u.cacheSize??DEFAULT_ANSWER_CACHE_SIZE),Object.entries(u.resolvers??{}).forEach(([h,b])=>{Array.isArray(b)||(b=[b]),h.endsWith(".")||(h=`${h}.`),this.resolvers[h]=b}),this.resolvers["."]==null&&(this.resolvers["."]=defaultResolver())}async query(u,h={}){var S,x,T;const b=getTypes(h.types),v=h.cached!==!1?this.cache.get(u,b):void 0;if(v!=null)return(S=h.onProgress)==null||S.call(h,new CustomProgressEvent("dns:cache",v)),v;const w=`${u.split(".").pop()}.`,_=(this.resolvers[w]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),E=[];for(const C of _){if(((x=h.signal)==null?void 0:x.aborted)===!0)break;try{const O=await C(u,{...h,types:b});for(const D of O.Answer)this.cache.add(u,D);return O}catch(O){E.push(O),(T=h.onProgress)==null||T.call(h,new CustomProgressEvent("dns:error",O))}}throw E.length===1?E[0]:new AggregateError(E,`DNS lookup of ${u} ${b} failed`)}}var RecordType;(function(y){y[y.A=1]="A",y[y.CNAME=5]="CNAME",y[y.TXT=16]="TXT",y[y.AAAA=28]="AAAA"})(RecordType||(RecordType={}));function dns(y={}){return new DNS(y)}const V=-1,names={},codes$1={},table=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,V,"ip6zone"],[43,8,"ipcidr"],[53,V,"dns",!0],[54,V,"dns4",!0],[55,V,"dns6",!0],[56,V,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,V,"unix",!1,!0],[421,V,"ipfs"],[421,V,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,V,"garlic64"],[448,0,"tls"],[449,V,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,V,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,V,"http-path"],[777,V,"memory"]];table.forEach(y=>{const u=createProtocol(...y);codes$1[u.code]=u,names[u.name]=u});function createProtocol(y,u,h,b,v){return{code:y,size:u,name:h,resolvable:!!b,path:!!v}}function getProtocol(y){{if(names[y]!=null)return names[y];throw new Error(`no protocol with name: ${y}`)}}const MAX_RECURSIVE_DEPTH=32,{code:dnsaddrCode}=getProtocol("dnsaddr");class RecursionLimitError extends Error{constructor(u="Max recursive depth reached"){super(u),this.name="RecursionLimitError"}}const dnsaddrResolver=async function(u,h={}){const b=h.maxRecursiveDepth??MAX_RECURSIVE_DEPTH;if(b===0)throw new RecursionLimitError("Max recursive depth reached");const[,v]=u.stringTuples().find(([x])=>x===dnsaddrCode)??[],_=await((h==null?void 0:h.dns)??dns()).query(`_dnsaddr.${v}`,{signal:h==null?void 0:h.signal,types:[RecordType.TXT]}),E=u.getPeerId(),S=[];for(const x of _.Answer){const T=x.data.replace(/["']/g,"").trim().split("=")[1];if(T==null||E!=null&&!T.includes(E))continue;const C=multiaddr(T);if(T.startsWith("/dnsaddr")){const O=await C.resolve({...h,maxRecursiveDepth:b-1});S.push(...O.map(D=>D.toString()))}else S.push(C.toString())}return S},DefaultConfig={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:y=>y},connectionManager:{resolvers:{dnsaddr:dnsaddrResolver}},transportManager:{faultTolerance:FaultTolerance.FATAL_ALL}};async function validateConfig(y){var h,b;const u=mergeOptions(DefaultConfig,y);if(u.connectionProtector===null&&((b=(h=globalThis.process)==null?void 0:h.env)==null?void 0:b.LIBP2P_FORCE_PNET)!=null)throw new InvalidParametersError$2("Private network is enforced, but no protector was provided");return u}const e=1e3,t=e*60,n=t*60,r$1=n*24,i=r$1*7,a=r$1*365.25,o=a/12;function s$1(y,u){if(typeof y=="string")return l(y);if(typeof y=="number")return p(y,u);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(y)}`)}var c=s$1;function l(y){if(typeof y!="string"||y.length===0||y.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(y)}`);let u=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(y);if(!(u!=null&&u.groups))return NaN;let{value:h,unit:b="ms"}=u.groups,v=parseFloat(h),w=b.toLowerCase();switch(w){case"years":case"year":case"yrs":case"yr":case"y":return v*a;case"months":case"month":case"mo":return v*o;case"weeks":case"week":case"w":return v*i;case"days":case"day":case"d":return v*r$1;case"hours":case"hour":case"hrs":case"hr":case"h":return v*n;case"minutes":case"minute":case"mins":case"min":case"m":return v*t;case"seconds":case"second":case"secs":case"sec":case"s":return v*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:throw Error(`Unknown unit "${w}" provided to ms.parse(). value=${JSON.stringify(y)}`)}}function d(y){let u=Math.abs(y);return u>=a?`${Math.round(y/a)}y`:u>=o?`${Math.round(y/o)}mo`:u>=i?`${Math.round(y/i)}w`:u>=r$1?`${Math.round(y/r$1)}d`:u>=n?`${Math.round(y/n)}h`:u>=t?`${Math.round(y/t)}m`:u>=e?`${Math.round(y/e)}s`:`${y}ms`}function f$1(y){let u=Math.abs(y);return u>=a?m(y,u,a,"year"):u>=o?m(y,u,o,"month"):u>=i?m(y,u,i,"week"):u>=r$1?m(y,u,r$1,"day"):u>=n?m(y,u,n,"hour"):u>=t?m(y,u,t,"minute"):u>=e?m(y,u,e,"second"):`${y} ms`}function p(y,u){if(typeof y!="number"||!Number.isFinite(y))throw Error("Value provided to ms.format() must be of type number.");return u!=null&&u.long?f$1(y):d(y)}function m(y,u,h,b){let v=u>=h*1.5;return`${Math.round(y/h)} ${b}${v?"s":""}`}function setup(y){h.debug=h,h.default=h,h.coerce=S,h.disable=w,h.enable=v,h.enabled=_,h.humanize=c,h.destroy=x,Object.keys(y).forEach(T=>{h[T]=y[T]}),h.names=[],h.skips=[],h.formatters={};function u(T){let C=0;for(let O=0;O<T.length;O++)C=(C<<5)-C+T.charCodeAt(O),C|=0;return h.colors[Math.abs(C)%h.colors.length]}h.selectColor=u;function h(T){let C,O=null,D,U;function te(...X){if(!te.enabled)return;const ie=te,ee=Number(new Date),ae=ee-(C||ee);ie.diff=ae,ie.prev=C,ie.curr=ee,C=ee,X[0]=h.coerce(X[0]),typeof X[0]!="string"&&X.unshift("%O");let de=0;X[0]=X[0].replace(/%([a-zA-Z%])/g,(ve,Pe)=>{if(ve==="%%")return"%";de++;const Ie=h.formatters[Pe];if(typeof Ie=="function"){const Ee=X[de];ve=Ie.call(ie,Ee),X.splice(de,1),de--}return ve}),h.formatArgs.call(ie,X),(ie.log||h.log).apply(ie,X)}return te.namespace=T,te.useColors=h.useColors(),te.color=h.selectColor(T),te.extend=b,te.destroy=h.destroy,Object.defineProperty(te,"enabled",{enumerable:!0,configurable:!1,get:()=>O!==null?O:(D!==h.namespaces&&(D=h.namespaces,U=h.enabled(T)),U),set:X=>{O=X}}),typeof h.init=="function"&&h.init(te),te}function b(T,C){const O=h(this.namespace+(typeof C>"u"?":":C)+T);return O.log=this.log,O}function v(T){h.save(T),h.namespaces=T,h.names=[],h.skips=[];let C;const O=(typeof T=="string"?T:"").split(/[\s,]+/),D=O.length;for(C=0;C<D;C++)O[C]&&(T=O[C].replace(/\*/g,".*?"),T[0]==="-"?h.skips.push(new RegExp("^"+T.substr(1)+"$")):h.names.push(new RegExp("^"+T+"$")))}function w(){const T=[...h.names.map(E),...h.skips.map(E).map(C=>"-"+C)].join(",");return h.enable(""),T}function _(T){if(T[T.length-1]==="*")return!0;let C,O;for(C=0,O=h.skips.length;C<O;C++)if(h.skips[C].test(T))return!1;for(C=0,O=h.names.length;C<O;C++)if(h.names[C].test(T))return!0;return!1}function E(T){return T.toString().substring(2,T.toString().length-2).replace(/\.\*\?$/,"*")}function S(T){return T instanceof Error?T.stack??T.message:T}function x(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return h.setupFormatters(h.formatters),h.enable(h.load()),h}const storage=localstorage(),colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){var y,u,h,b,v;return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&((y=navigator.userAgent)==null?void 0:y.toLowerCase().match(/(edge|trident)\/(\d+)/))!=null?!1:typeof document<"u"&&((h=(u=document.documentElement)==null?void 0:u.style)==null?void 0:h.WebkitAppearance)||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&((b=navigator.userAgent)==null?void 0:b.toLowerCase().match(/firefox\/(\d+)/))!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&((v=navigator.userAgent)==null?void 0:v.toLowerCase().match(/applewebkit\/(\d+)/))}function formatArgs(y){if(y[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+y[0]+(this.useColors?"%c ":" ")+"+"+c(this.diff),!this.useColors)return;const u="color: "+this.color;y.splice(1,0,u,"color: inherit");let h=0,b=0;y[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(h++,v==="%c"&&(b=h))}),y.splice(b,0,u)}const log$b=console.debug??console.log??(()=>{});function save(y){try{y?storage==null||storage.setItem("debug",y):storage==null||storage.removeItem("debug")}catch{}}function load$2(){let y;try{y=storage==null?void 0:storage.getItem("debug")}catch{}return!y&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(y=globalThis.process.env.DEBUG),y}function localstorage(){try{return localStorage}catch{}}function setupFormatters(y){y.j=function(u){try{return JSON.stringify(u)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}}const weald=setup({formatArgs,save,load:load$2,useColors,setupFormatters,colors,storage,log:log$b});weald.formatters.b=y=>y==null?"undefined":base58btc.baseEncode(y);weald.formatters.t=y=>y==null?"undefined":base32$2.baseEncode(y);weald.formatters.m=y=>y==null?"undefined":base64$2.baseEncode(y);weald.formatters.p=y=>y==null?"undefined":y.toString();weald.formatters.c=y=>y==null?"undefined":y.toString();weald.formatters.k=y=>y==null?"undefined":y.toString();weald.formatters.a=y=>y==null?"undefined":y.toString();weald.formatters.e=y=>y==null?"undefined":notEmpty(y.stack)??notEmpty(y.message)??y.toString();function createDisabledLogger(y){const u=()=>{};return u.enabled=!1,u.color="",u.diff=0,u.log=()=>{},u.namespace=y,u.destroy=()=>!0,u.extend=()=>u,u}function defaultLogger(){return{forComponent(y){return logger$2(y)}}}function logger$2(y){let u=createDisabledLogger(`${y}:trace`);return weald.enabled(`${y}:trace`)&&weald.names.map(h=>h.toString()).find(h=>h.includes(":trace"))!=null&&(u=weald(`${y}:trace`)),Object.assign(weald(y),{error:weald(`${y}:error`),trace:u,newScope:h=>logger$2(`${y}:${h}`)})}function notEmpty(y){if(y!=null&&(y=y.trim(),y.length!==0))return y}function mapIterable(y,u){const h={[Symbol.iterator]:()=>h,next:()=>{const b=y.next(),v=b.value;return b.done===!0||v==null?{done:!0,value:void 0}:{done:!1,value:u(v)}}};return h}function peerIdFromString(y){const u=decode$3(base58btc.decode(`z${y}`));return peerIdFromMultihash(u)}class PeerMap{constructor(u){Z(this,"map");if(this.map=new Map,u!=null)for(const[h,b]of u.entries())this.map.set(h.toString(),{key:h,value:b})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(u){return this.map.delete(u.toString())}entries(){return mapIterable(this.map.entries(),u=>[u[1].key,u[1].value])}forEach(u){this.map.forEach((h,b)=>{u(h.value,h.key,this)})}get(u){var h;return(h=this.map.get(u.toString()))==null?void 0:h.value}has(u){return this.map.has(u.toString())}set(u,h){this.map.set(u.toString(),{key:u,value:h})}keys(){return mapIterable(this.map.values(),u=>u.key)}values(){return mapIterable(this.map.values(),u=>u.value)}get size(){return this.map.size}}class PeerSet{constructor(u){Z(this,"set");if(this.set=new Set,u!=null)for(const h of u)this.set.add(h.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(u){this.set.add(u.toString())}clear(){this.set.clear()}delete(u){this.set.delete(u.toString())}entries(){return mapIterable(this.set.entries(),u=>{const h=peerIdFromString(u[0]);return[h,h]})}forEach(u){this.set.forEach(h=>{const b=peerIdFromString(h);u(b,b,this)})}has(u){return this.set.has(u.toString())}values(){return mapIterable(this.set.values(),u=>peerIdFromString(u))}intersection(u){const h=new PeerSet;for(const b of u)this.has(b)&&h.add(b);return h}difference(u){const h=new PeerSet;for(const b of this)u.has(b)||h.add(b);return h}union(u){const h=new PeerSet;for(const b of u)h.add(b);for(const b of this)h.add(b);return h}}const FNV_PRIMES={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},FNV_OFFSETS={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},cachedEncoder=new globalThis.TextEncoder;function fnv1aUint8Array(y,u){const h=FNV_PRIMES[u];let b=FNV_OFFSETS[u];for(let v=0;v<y.length;v++)b^=BigInt(y[v]),b=BigInt.asUintN(u,b*h);return b}function fnv1aEncodeInto(y,u,h){if(h.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");const b=FNV_PRIMES[u];let v=FNV_OFFSETS[u],w=y;for(;w.length>0;){const _=cachedEncoder.encodeInto(w,h);w=w.slice(_.read);for(let E=0;E<_.written;E++)v^=BigInt(h[E]),v=BigInt.asUintN(u,v*b)}return v}function fnv1a$1(y,{size:u=32,utf8Buffer:h}={}){if(!FNV_PRIMES[u])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof y=="string"){if(h)return fnv1aEncodeInto(y,u,h);y=cachedEncoder.encode(y)}return fnv1aUint8Array(y,u)}const fnv1a={hash:y=>Number(fnv1a$1(y,{size:32})),hashV:(y,u)=>numberToBuffer(fnv1a.hash(y,u))};function numberToBuffer(y){let u=y.toString(16);return u.length%2===1&&(u=`0${u}`),fromString(u,"base16")}const MAX_FINGERPRINT_SIZE=64;class Fingerprint{constructor(u,h,b,v=2){Z(this,"fp");Z(this,"h");Z(this,"seed");if(v>MAX_FINGERPRINT_SIZE)throw new TypeError("Invalid Fingerprint Size");const w=h.hashV(u,b),_=alloc$1(v);for(let E=0;E<_.length;E++)_[E]=w[E];_.length===0&&(_[0]=7),this.fp=_,this.h=h,this.seed=b}hash(){return this.h.hash(this.fp,this.seed)}equals(u){return(u==null?void 0:u.fp)instanceof Uint8Array?equals(this.fp,u.fp):!1}}function getRandomInt(y,u){return Math.floor(Math.random()*(u-y))+y}class Bucket{constructor(u){Z(this,"contents");this.contents=new Array(u).fill(null)}has(u){if(!(u instanceof Fingerprint))throw new TypeError("Invalid Fingerprint");return this.contents.some(h=>u.equals(h))}add(u){if(!(u instanceof Fingerprint))throw new TypeError("Invalid Fingerprint");for(let h=0;h<this.contents.length;h++)if(this.contents[h]==null)return this.contents[h]=u,!0;return!0}swap(u){if(!(u instanceof Fingerprint))throw new TypeError("Invalid Fingerprint");const h=getRandomInt(0,this.contents.length-1),b=this.contents[h];return this.contents[h]=u,b}remove(u){if(!(u instanceof Fingerprint))throw new TypeError("Invalid Fingerprint");const h=this.contents.findIndex(b=>u.equals(b));return h>-1?(this.contents[h]=null,!0):!1}}const maxCuckooCount=500;class CuckooFilter{constructor(u){Z(this,"bucketSize");Z(this,"filterSize");Z(this,"fingerprintSize");Z(this,"buckets");Z(this,"count");Z(this,"hash");Z(this,"seed");this.filterSize=u.filterSize,this.bucketSize=u.bucketSize??4,this.fingerprintSize=u.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=u.hash??fnv1a,this.seed=u.seed??getRandomInt(0,Math.pow(2,10))}add(u){typeof u=="string"&&(u=fromString(u));const h=new Fingerprint(u,this.hash,this.seed,this.fingerprintSize),b=this.hash.hash(u,this.seed)%this.filterSize,v=(b^h.hash())%this.filterSize;if(this.buckets[b]==null&&(this.buckets[b]=new Bucket(this.bucketSize)),this.buckets[v]==null&&(this.buckets[v]=new Bucket(this.bucketSize)),this.buckets[b].add(h)||this.buckets[v].add(h))return this.count++,!0;const w=[b,v];let _=w[getRandomInt(0,w.length-1)];this.buckets[_]==null&&(this.buckets[_]=new Bucket(this.bucketSize));for(let E=0;E<maxCuckooCount;E++){const S=this.buckets[_].swap(h);if(S!=null&&(_=(_^S.hash())%this.filterSize,this.buckets[_]==null&&(this.buckets[_]=new Bucket(this.bucketSize)),this.buckets[_].add(S)))return this.count++,!0}return!1}has(u){var _,E;typeof u=="string"&&(u=fromString(u));const h=new Fingerprint(u,this.hash,this.seed,this.fingerprintSize),b=this.hash.hash(u,this.seed)%this.filterSize,v=((_=this.buckets[b])==null?void 0:_.has(h))??!1;if(v)return v;const w=(b^h.hash())%this.filterSize;return((E=this.buckets[w])==null?void 0:E.has(h))??!1}remove(u){var E,S;typeof u=="string"&&(u=fromString(u));const h=new Fingerprint(u,this.hash,this.seed,this.fingerprintSize),b=this.hash.hash(u,this.seed)%this.filterSize,v=((E=this.buckets[b])==null?void 0:E.remove(h))??!1;if(v)return this.count--,v;const w=(b^h.hash())%this.filterSize,_=((S=this.buckets[w])==null?void 0:S.remove(h))??!1;return _&&this.count--,_}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}}const MAX_LOAD={1:.5,2:.84,4:.95,8:.98};function calculateBucketSize(y=.001){return y>.002?2:y>1e-5?4:8}function optimize(y,u=.001){const h=calculateBucketSize(u),b=MAX_LOAD[h],v=Math.round(y/b),w=Math.min(Math.ceil(Math.log2(1/u)+Math.log2(2*h)),MAX_FINGERPRINT_SIZE);return{filterSize:v,bucketSize:h,fingerprintSize:w}}class ScalableCuckooFilter{constructor(u){Z(this,"filterSize");Z(this,"bucketSize");Z(this,"fingerprintSize");Z(this,"scale");Z(this,"filterSeries");Z(this,"hash");Z(this,"seed");this.bucketSize=u.bucketSize??4,this.filterSize=u.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=u.fingerprintSize??2,this.scale=u.scale??2,this.hash=u.hash??fnv1a,this.seed=u.seed??getRandomInt(0,Math.pow(2,10)),this.filterSeries=[new CuckooFilter({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(u){if(typeof u=="string"&&(u=fromString(u)),this.has(u))return!0;let h=this.filterSeries.find(b=>b.reliable);if(h==null){const b=this.filterSize*Math.pow(this.scale,this.filterSeries.length);h=new CuckooFilter({filterSize:b,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(h)}return h.add(u)}has(u){typeof u=="string"&&(u=fromString(u));for(let h=0;h<this.filterSeries.length;h++)if(this.filterSeries[h].has(u))return!0;return!1}remove(u){typeof u=="string"&&(u=fromString(u));for(let h=0;h<this.filterSeries.length;h++)if(this.filterSeries[h].remove(u))return!0;return!1}get count(){return this.filterSeries.reduce((u,h)=>u+h.count,0)}}function createScalableCuckooFilter(y,u=.001,h){return new ScalableCuckooFilter({...optimize(y,u)})}class TrackedPeerMap extends PeerMap{constructor(h){super();Z(this,"metric");const{name:b,metrics:v}=h;this.metric=v.registerMetric(b),this.updateComponentMetric()}set(h,b){return super.set(h,b),this.updateComponentMetric(),this}delete(h){const b=super.delete(h);return this.updateComponentMetric(),b}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function trackedPeerMap(y){const{name:u,metrics:h}=y;let b;return h!=null?b=new TrackedPeerMap({name:u,metrics:h}):b=new PeerMap,b}var Ql;let AbortError$1=(Ql=class extends Error{constructor(h="The operation was aborted",...b){super(h,...b);Z(this,"name","AbortError")}},Z(Ql,"name","AbortError"),Ql);async function raceEvent(y,u,h,b){const v=new AbortError$1(b==null?void 0:b.errorMessage);(b==null?void 0:b.errorCode)!=null&&(v.code=b.errorCode);const w=(b==null?void 0:b.errorEvent)??"error";return(h==null?void 0:h.aborted)===!0?Promise.reject(v):new Promise((_,E)=>{function S(){removeListener(h,"abort",C),removeListener(y,u,x),removeListener(y,w,T)}const x=O=>{var D;try{if(((D=b==null?void 0:b.filter)==null?void 0:D.call(b,O))===!1)return}catch(U){S(),E(U);return}S(),_(O)},T=O=>{if(S(),O instanceof Error){E(O);return}E(O.detail??(b==null?void 0:b.error)??new Error(`The "${b==null?void 0:b.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},C=()=>{S(),E(v)};addListener(h,"abort",C),addListener(y,u,x),addListener(y,w,T)})}function addListener(y,u,h){y!=null&&(isEventTarget(y)?y.addEventListener(u,h):y.addListener(u,h))}function removeListener(y,u,h){y!=null&&(isEventTarget(y)?y.removeEventListener(u,h):y.removeListener(u,h))}function isEventTarget(y){return typeof y.addEventListener=="function"&&typeof y.removeEventListener=="function"}class QueueFullError extends Error{constructor(u="The queue was full"){super(u),this.name="QueueFullError"}}Z(QueueFullError,"name","QueueFullError");let JobRecipient$1=class{constructor(u){Z(this,"deferred");Z(this,"signal");var h;this.signal=u,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),(h=this.signal)==null||h.addEventListener("abort",this.onAbort)}onAbort(){var u;this.deferred.reject(((u=this.signal)==null?void 0:u.reason)??new AbortError$1)}cleanup(){var u;(u=this.signal)==null||u.removeEventListener("abort",this.onAbort)}};function randomId$1(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}let Job$1=class{constructor(u,h){Z(this,"id");Z(this,"fn");Z(this,"options");Z(this,"recipients");Z(this,"status");Z(this,"timeline");Z(this,"controller");this.id=randomId$1(),this.status="queued",this.fn=u,this.options=h,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(u){this.controller.abort(u)}onAbort(){this.recipients.reduce((h,b)=>{var v;return h&&((v=b.signal)==null?void 0:v.aborted)===!0},!0)&&(this.controller.abort(new AbortError$1),this.cleanup())}async join(u={}){var b;const h=new JobRecipient$1(u.signal);return this.recipients.push(h),(b=u.signal)==null||b.addEventListener("abort",this.onAbort),h.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const u=await raceSignal(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(h=>{h.deferred.resolve(u)}),this.status="complete"}catch(u){this.recipients.forEach(h=>{h.deferred.reject(u)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(u=>{var h;u.cleanup(),(h=u.signal)==null||h.removeEventListener("abort",this.onAbort)})}};function debounce(y,u){let h;const b=function(){const v=function(){h=void 0,y()};clearTimeout(h),h=setTimeout(v,u)};return b.start=()=>{},b.stop=()=>{clearTimeout(h)},b}let Queue$1=class extends TypedEventEmitter{constructor(h={}){super();Z(this,"concurrency");Z(this,"maxSize");Z(this,"queue");Z(this,"pending");Z(this,"sort");Z(this,"autoStart");this.concurrency=h.concurrency??Number.POSITIVE_INFINITY,this.maxSize=h.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=h.autoStart??!0,this.sort=h.sort,this.queue=[],this.emitEmpty=debounce(this.emitEmpty.bind(this),1),this.emitIdle=debounce(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let h;for(const b of this.queue)if(b.status==="queued"){h=b;break}return h==null?!1:(this.safeDispatchEvent("active"),this.pending++,h.run().finally(()=>{for(let b=0;b<this.queue.length;b++)if(this.queue[b]===h){this.queue.splice(b,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(h){this.queue.push(h),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(h,b){var w;if((w=b==null?void 0:b.signal)==null||w.throwIfAborted(),this.size===this.maxSize)throw new QueueFullError;const v=new Job$1(h,b);return this.enqueue(v),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),v.join(b).then(_=>(this.safeDispatchEvent("success",{detail:{job:v,result:_}}),_)).catch(_=>{if(v.status==="queued"){for(let E=0;E<this.queue.length;E++)if(this.queue[E]===v){this.queue.splice(E,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:v,error:_}}),_})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(h=>{h.abort(new AbortError$1)}),this.clear()}async onEmpty(h){this.size!==0&&await raceEvent(this,"empty",h==null?void 0:h.signal)}async onSizeLessThan(h,b){this.size<h||await raceEvent(this,"next",b==null?void 0:b.signal,{filter:()=>this.size<h})}async onIdle(h){this.pending===0&&this.size===0||await raceEvent(this,"idle",h==null?void 0:h.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(h){var x,T,C;(x=h==null?void 0:h.signal)==null||x.throwIfAborted();const b=pushable({objectMode:!0}),v=O=>{O!=null?this.abort():this.clear(),b.end(O)},w=O=>{O.detail!=null&&b.push(O.detail.result)},_=O=>{v(O.detail.error)},E=()=>{v()},S=()=>{v(new AbortError$1("Queue aborted"))};this.addEventListener("success",w),this.addEventListener("failure",_),this.addEventListener("idle",E),(T=h==null?void 0:h.signal)==null||T.addEventListener("abort",S);try{yield*b}finally{this.removeEventListener("success",w),this.removeEventListener("failure",_),this.removeEventListener("idle",E),(C=h==null?void 0:h.signal)==null||C.removeEventListener("abort",S),v()}}};const WORKER_REQUEST_READ_LOCK="lock:worker:request-read",WORKER_ABORT_READ_LOCK_REQUEST="lock:worker:abort-read-request",WORKER_RELEASE_READ_LOCK="lock:worker:release-read",MASTER_GRANT_READ_LOCK="lock:master:grant-read",MASTER_READ_LOCK_ERROR="lock:master:error-read",WORKER_REQUEST_WRITE_LOCK="lock:worker:request-write",WORKER_ABORT_WRITE_LOCK_REQUEST="lock:worker:abort-write-request",WORKER_RELEASE_WRITE_LOCK="lock:worker:release-write",MASTER_GRANT_WRITE_LOCK="lock:master:grant-write",MASTER_WRITE_LOCK_ERROR="lock:master:error-write",WORKER_FINALIZE="lock:worker:finalize",BROADCAST_CHANNEL_NAME="mortice",defaultOptions$3={singleProcess:!1},handleChannelWorkerLockRequest=(y,u,h,b,v,w,_,E,S)=>x=>{if(x.data==null)return;const T={type:x.data.type,name:x.data.name,identifier:x.data.identifier};T.type===v&&y.safeDispatchEvent(h,{detail:{name:T.name,identifier:T.identifier,handler:async()=>{u.postMessage({type:S,name:T.name,identifier:T.identifier}),await new Promise(C=>{const O=D=>{if((D==null?void 0:D.data)==null)return;const U={type:D.data.type,name:D.data.name,identifier:D.data.identifier};U.type===E&&U.identifier===T.identifier&&(u.removeEventListener("message",O),C())};u.addEventListener("message",O)})},onError:C=>{u.postMessage({type:_,name:T.name,identifier:T.identifier,error:{message:C.message,name:C.name,stack:C.stack}})}}}),T.type===w&&y.safeDispatchEvent(b,{detail:{name:T.name,identifier:T.identifier}}),T.type===WORKER_FINALIZE&&y.safeDispatchEvent("finalizeRequest",{detail:{name:T.name}})},nanoid=(y=10)=>Math.random().toString().substring(2,y+2);class MorticeChannelWorker{constructor(u){Z(this,"name");Z(this,"channel");this.name=u,this.channel=new BroadcastChannel(BROADCAST_CHANNEL_NAME)}readLock(u){return this.sendRequest(WORKER_REQUEST_READ_LOCK,WORKER_ABORT_READ_LOCK_REQUEST,MASTER_GRANT_READ_LOCK,MASTER_READ_LOCK_ERROR,WORKER_RELEASE_READ_LOCK,u)}writeLock(u){return this.sendRequest(WORKER_REQUEST_WRITE_LOCK,WORKER_ABORT_WRITE_LOCK_REQUEST,MASTER_GRANT_WRITE_LOCK,MASTER_WRITE_LOCK_ERROR,WORKER_RELEASE_WRITE_LOCK,u)}finalize(){this.channel.postMessage({type:WORKER_FINALIZE,name:this.name}),this.channel.close()}async sendRequest(u,h,b,v,w,_){var S;(S=_==null?void 0:_.signal)==null||S.throwIfAborted();const E=nanoid();return this.channel.postMessage({type:u,identifier:E,name:this.name}),new Promise((x,T)=>{var D;const C=()=>{this.channel.postMessage({type:h,identifier:E,name:this.name})};(D=_==null?void 0:_.signal)==null||D.addEventListener("abort",C,{once:!0});const O=U=>{var te,X,ie,ee;if(((te=U.data)==null?void 0:te.identifier)===E&&(((X=U.data)==null?void 0:X.type)===b&&(this.channel.removeEventListener("message",O),(ie=_==null?void 0:_.signal)==null||ie.removeEventListener("abort",C),x(()=>{this.channel.postMessage({type:w,identifier:E,name:this.name})})),U.data.type===v)){this.channel.removeEventListener("message",O),(ee=_==null?void 0:_.signal)==null||ee.removeEventListener("abort",C);const ae=new Error;U.data.error!=null&&(ae.message=U.data.error.message,ae.name=U.data.error.name,ae.stack=U.data.error.stack),T(ae)}};this.channel.addEventListener("message",O)})}}const impl=y=>{if(y=Object.assign({},defaultOptions$3,y),!!globalThis.document||y.singleProcess){const h=new BroadcastChannel(BROADCAST_CHANNEL_NAME),b=new TypedEventEmitter;return h.addEventListener("message",handleChannelWorkerLockRequest(b,h,"requestReadLock","abortReadLockRequest",WORKER_REQUEST_READ_LOCK,WORKER_ABORT_READ_LOCK_REQUEST,MASTER_READ_LOCK_ERROR,WORKER_RELEASE_READ_LOCK,MASTER_GRANT_READ_LOCK)),h.addEventListener("message",handleChannelWorkerLockRequest(b,h,"requestWriteLock","abortWriteLockRequest",WORKER_REQUEST_WRITE_LOCK,WORKER_ABORT_WRITE_LOCK_REQUEST,MASTER_WRITE_LOCK_ERROR,WORKER_RELEASE_WRITE_LOCK,MASTER_GRANT_WRITE_LOCK)),b}return new MorticeChannelWorker(y.name)},mutexes=new Map;let implementation$2;function isMortice(y){return typeof(y==null?void 0:y.readLock)=="function"&&typeof(y==null?void 0:y.writeLock)=="function"}function getImplementation(y){if(implementation$2==null&&(implementation$2=impl(y),!isMortice(implementation$2))){const u=implementation$2;u.addEventListener("requestReadLock",h=>{const b=h.detail.name,v=h.detail.identifier,w=mutexes.get(b);if(w==null)return;const _=new AbortController,E=S=>{S.detail.name!==b||S.detail.identifier!==v||_.abort()};u.addEventListener("abortReadLockRequest",E),w.readLock({signal:_.signal}).then(async S=>{await h.detail.handler().finally(()=>{S()})}).catch(S=>{h.detail.onError(S)}).finally(()=>{u.removeEventListener("abortReadLockRequest",E)})}),u.addEventListener("requestWriteLock",h=>{const b=h.detail.name,v=h.detail.identifier,w=mutexes.get(b);if(w==null)return;const _=new AbortController,E=S=>{S.detail.name!==b||S.detail.identifier!==v||_.abort()};u.addEventListener("abortWriteLockRequest",E),w.writeLock({signal:_.signal}).then(async S=>{await h.detail.handler().finally(()=>{S()})}).catch(S=>{h.detail.onError(S)}).finally(()=>{u.removeEventListener("abortWriteLockRequest",E)})}),u.addEventListener("finalizeRequest",h=>{const b=h.detail.name,v=mutexes.get(b);v!=null&&v.finalize()})}return implementation$2}async function createReleasable(y,u){var _;let h,b;const v=new Promise((E,S)=>{h=E,b=S}),w=()=>{b(new AbortError$1)};return(_=u==null?void 0:u.signal)==null||_.addEventListener("abort",w,{once:!0}),y.add(async()=>{await new Promise(E=>{h(()=>{var S;(S=u==null?void 0:u.signal)==null||S.removeEventListener("abort",w),E()})})},{signal:u==null?void 0:u.signal}).catch(E=>{b(E)}),v}const createMutex=(y,u)=>{let h=mutexes.get(y);if(h!=null)return h;const b=getImplementation(u);if(isMortice(b))return h=b,mutexes.set(y,h),h;const v=new Queue$1({concurrency:1});let w;return h={async readLock(_){if(w!=null)return createReleasable(w,_);w=new Queue$1({concurrency:u.concurrency,autoStart:!1});const E=w,S=createReleasable(w,_);return v.add(async()=>{E.start(),await E.onIdle().then(()=>{w===E&&(w=null)})}),S},async writeLock(_){return w=null,createReleasable(v,_)},finalize:()=>{mutexes.delete(y)},queue:v},mutexes.set(y,h),u.autoFinalize===!0&&v.addEventListener("idle",()=>{h.finalize()},{once:!0}),h},defaultOptions$2={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function createMortice(y){const u=Object.assign({},defaultOptions$2,y);return createMutex(u.name,u)}const MAX_ADDRESS_AGE=36e5,MAX_PEER_AGE=216e5;var Peer;(function(y){(function(h){let b;h.codec=()=>(b==null&&(b=message$1((v,w,_={})=>{_.lengthDelimited!==!1&&w.fork(),v.key!=null&&v.key!==""&&(w.uint32(10),w.string(v.key)),v.value!=null&&v.value.byteLength>0&&(w.uint32(18),w.bytes(v.value)),_.lengthDelimited!==!1&&w.ldelim()},(v,w,_={})=>{const E={key:"",value:alloc$1(0)},S=w==null?v.len:v.pos+w;for(;v.pos<S;){const x=v.uint32();switch(x>>>3){case 1:{E.key=v.string();break}case 2:{E.value=v.bytes();break}default:{v.skipType(x&7);break}}}return E})),b),h.encode=v=>encodeMessage(v,h.codec()),h.decode=(v,w)=>decodeMessage(v,h.codec(),w)})(y.Peer$metadataEntry||(y.Peer$metadataEntry={})),function(h){let b;h.codec=()=>(b==null&&(b=message$1((v,w,_={})=>{_.lengthDelimited!==!1&&w.fork(),v.key!=null&&v.key!==""&&(w.uint32(10),w.string(v.key)),v.value!=null&&(w.uint32(18),Tag.codec().encode(v.value,w)),_.lengthDelimited!==!1&&w.ldelim()},(v,w,_={})=>{var x;const E={key:""},S=w==null?v.len:v.pos+w;for(;v.pos<S;){const T=v.uint32();switch(T>>>3){case 1:{E.key=v.string();break}case 2:{E.value=Tag.codec().decode(v,v.uint32(),{limits:(x=_.limits)==null?void 0:x.value});break}default:{v.skipType(T&7);break}}}return E})),b),h.encode=v=>encodeMessage(v,h.codec()),h.decode=(v,w)=>decodeMessage(v,h.codec(),w)}(y.Peer$tagsEntry||(y.Peer$tagsEntry={}));let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{if(v.lengthDelimited!==!1&&b.fork(),h.addresses!=null)for(const w of h.addresses)b.uint32(10),Address.codec().encode(w,b);if(h.protocols!=null)for(const w of h.protocols)b.uint32(18),b.string(w);if(h.publicKey!=null&&(b.uint32(34),b.bytes(h.publicKey)),h.peerRecordEnvelope!=null&&(b.uint32(42),b.bytes(h.peerRecordEnvelope)),h.metadata!=null&&h.metadata.size!==0)for(const[w,_]of h.metadata.entries())b.uint32(50),y.Peer$metadataEntry.codec().encode({key:w,value:_},b);if(h.tags!=null&&h.tags.size!==0)for(const[w,_]of h.tags.entries())b.uint32(58),y.Peer$tagsEntry.codec().encode({key:w,value:_},b);h.updated!=null&&(b.uint32(64),b.uint64Number(h.updated)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{var E,S,x,T,C,O;const w={addresses:[],protocols:[],metadata:new Map,tags:new Map},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const D=h.uint32();switch(D>>>3){case 1:{if(((E=v.limits)==null?void 0:E.addresses)!=null&&w.addresses.length===v.limits.addresses)throw new MaxLengthError('Decode error - map field "addresses" had too many elements');w.addresses.push(Address.codec().decode(h,h.uint32(),{limits:(S=v.limits)==null?void 0:S.addresses$}));break}case 2:{if(((x=v.limits)==null?void 0:x.protocols)!=null&&w.protocols.length===v.limits.protocols)throw new MaxLengthError('Decode error - map field "protocols" had too many elements');w.protocols.push(h.string());break}case 4:{w.publicKey=h.bytes();break}case 5:{w.peerRecordEnvelope=h.bytes();break}case 6:{if(((T=v.limits)==null?void 0:T.metadata)!=null&&w.metadata.size===v.limits.metadata)throw new MaxSizeError('Decode error - map field "metadata" had too many elements');const U=y.Peer$metadataEntry.codec().decode(h,h.uint32());w.metadata.set(U.key,U.value);break}case 7:{if(((C=v.limits)==null?void 0:C.tags)!=null&&w.tags.size===v.limits.tags)throw new MaxSizeError('Decode error - map field "tags" had too many elements');const U=y.Peer$tagsEntry.codec().decode(h,h.uint32(),{limits:{value:(O=v.limits)==null?void 0:O.tags$value}});w.tags.set(U.key,U.value);break}case 8:{w.updated=h.uint64Number();break}default:{h.skipType(D&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(Peer||(Peer={}));var Address;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.multiaddr!=null&&h.multiaddr.byteLength>0&&(b.uint32(10),b.bytes(h.multiaddr)),h.isCertified!=null&&(b.uint32(16),b.bool(h.isCertified)),h.observed!=null&&(b.uint32(24),b.uint64Number(h.observed)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={multiaddr:alloc$1(0)},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.multiaddr=h.bytes();break}case 2:{w.isCertified=h.bool();break}case 3:{w.observed=h.uint64Number();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(Address||(Address={}));var Tag;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.value!=null&&h.value!==0&&(b.uint32(8),b.uint32(h.value)),h.expiry!=null&&(b.uint32(16),b.uint64(h.expiry)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={value:0},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.value=h.uint32();break}case 2:{w.expiry=h.uint64();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(Tag||(Tag={}));function populatePublicKey(y,u){if(y.publicKey!=null||u.publicKey==null)return y;let h;y.type==="RSA"&&(h=y.toMultihash());const b=publicKeyFromProtobuf(u.publicKey,h);return peerIdFromPublicKey$1(b)}function bytesToPeer(y,u,h){const b=Peer.decode(u);return pbToPeer(y,b,h)}function pbToPeer(y,u,h){const b=new Map,v=BigInt(Date.now());for(const[w,_]of u.tags.entries())_.expiry!=null&&_.expiry<v||b.set(w,_);return{...u,id:populatePublicKey(y,u),addresses:u.addresses.filter(({observed:w})=>w!=null&&w>Date.now()-h).map(({multiaddr:w,isCertified:_})=>({multiaddr:multiaddr(w),isCertified:_??!1})),metadata:u.metadata,peerRecordEnvelope:u.peerRecordEnvelope??void 0,tags:b}}function peerEquals(y,u){return addressesEqual(y.addresses,u.addresses)&&protocolsEqual(y.protocols,u.protocols)&&publicKeyEqual(y.publicKey,u.publicKey)&&peerRecordEnvelope(y.peerRecordEnvelope,u.peerRecordEnvelope)&&metadataEqual(y.metadata,u.metadata)&&tagsEqual(y.tags,u.tags)}function addressesEqual(y,u){return compareArrays(y,u,(h,b)=>!(h.isCertified!==b.isCertified||!equals(h.multiaddr,b.multiaddr)))}function protocolsEqual(y,u){return compareArrays(y,u,(h,b)=>h===b)}function publicKeyEqual(y,u){return compareOptionalUint8Arrays(y,u)}function peerRecordEnvelope(y,u){return compareOptionalUint8Arrays(y,u)}function metadataEqual(y,u){return compareMaps(y,u,(h,b)=>equals(h,b))}function tagsEqual(y,u){return compareMaps(y,u,(h,b)=>h.value===b.value&&h.expiry===b.expiry)}function compareOptionalUint8Arrays(y,u){return y==null&&u==null?!0:y!=null&&u!=null?equals(y,u):!1}function compareArrays(y,u,h){if(y.length!==u.length)return!1;for(let b=0;b<y.length;b++)if(!h(y[b],u[b]))return!1;return!0}function compareMaps(y,u,h){if(y.size!==u.size)return!1;for(const[b,v]of y.entries()){const w=u.get(b);if(w==null||!h(v,w))return!1}return!0}const pathSepS="/",pathSepB=new TextEncoder().encode(pathSepS),pathSep=pathSepB[0];class Key{constructor(u,h){Z(this,"_buf");if(typeof u=="string")this._buf=fromString(u);else if(u instanceof Uint8Array)this._buf=u;else throw new Error("Invalid key, should be String of Uint8Array");if(h==null&&(h=!0),h&&this.clean(),this._buf.byteLength===0||this._buf[0]!==pathSep)throw new Error("Invalid key")}toString(u="utf8"){return toString$1(this._buf,u)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(u){return new Key(u.join(pathSepS))}static random(){return new Key(Math.random().toString().substring(2))}static asKey(u){return u instanceof Uint8Array||typeof u=="string"?new Key(u):typeof u.uint8Array=="function"?new Key(u.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=pathSepB),this._buf[0]!==pathSep){const u=new Uint8Array(this._buf.byteLength+1);u.fill(pathSep,0,1),u.set(this._buf,1),this._buf=u}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===pathSep;)this._buf=this._buf.subarray(0,-1)}less(u){const h=this.list(),b=u.list();for(let v=0;v<h.length;v++){if(b.length<v+1)return!1;const w=h[v],_=b[v];if(w<_)return!0;if(w>_)return!1}return h.length<b.length}reverse(){return Key.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const u=this.namespaces();return u[u.length-1]}list(){return this.toString().split(pathSepS).slice(1)}type(){return namespaceType(this.baseNamespace())}name(){return namespaceValue(this.baseNamespace())}instance(u){return new Key(this.toString()+":"+u)}path(){let u=this.parent().toString();return u.endsWith(pathSepS)||(u+=pathSepS),u+=this.type(),new Key(u)}parent(){const u=this.list();return u.length===1?new Key(pathSepS):new Key(u.slice(0,-1).join(pathSepS))}child(u){return this.toString()===pathSepS?u:u.toString()===pathSepS?this:new Key(this.toString()+u.toString(),!1)}isAncestorOf(u){return u.toString()===this.toString()?!1:u.toString().startsWith(this.toString())}isDecendantOf(u){return u.toString()===this.toString()?!1:this.toString().startsWith(u.toString())}isTopLevel(){return this.list().length===1}concat(...u){return Key.withNamespaces([...this.namespaces(),...flatten(u.map(h=>h.namespaces()))])}}function namespaceType(y){const u=y.split(":");return u.length<2?"":u.slice(0,-1).join(":")}function namespaceValue(y){const u=y.split(":");return u[u.length-1]}function flatten(y){return[].concat(...y)}const NAMESPACE_COMMON="/peers/";function peerIdToDatastoreKey(y){if(!isPeerId(y)||y.type==null)throw new InvalidParametersError$2("Invalid PeerId");const u=y.toCID().toString();return new Key(`${NAMESPACE_COMMON}${u}`)}async function dedupeFilterAndSortAddresses(y,u,h,b,v){const w=new Map;for(const _ of h){if(_==null)continue;if(_.multiaddr instanceof Uint8Array&&(_.multiaddr=multiaddr(_.multiaddr)),!isMultiaddr(_.multiaddr))throw new InvalidParametersError$2("Multiaddr was invalid");if(!await u(y,_.multiaddr,v))continue;const E=_.isCertified??!1,S=_.multiaddr.toString(),x=w.get(S);x!=null?_.isCertified=x.isCertified||E:w.set(S,{multiaddr:_.multiaddr,isCertified:E})}return[...w.values()].sort((_,E)=>_.multiaddr.toString().localeCompare(E.multiaddr.toString())).map(({isCertified:_,multiaddr:E})=>{const S=E.getPeerId();return y.equals(S)&&(E=E.decapsulate(multiaddr(`/p2p/${y}`))),{isCertified:_,multiaddr:E.bytes}})}async function toPeerPB(y,u,h,b){var O,D;if(u==null)throw new InvalidParametersError$2("Invalid PeerData");if(u.publicKey!=null&&y.publicKey!=null&&!u.publicKey.equals(y.publicKey))throw new InvalidParametersError$2("publicKey bytes do not match peer id publicKey bytes");const v=(O=b.existingPeer)==null?void 0:O.peer;if(v!=null&&!y.equals(v.id))throw new InvalidParametersError$2("peer id did not match existing peer id");let w=(v==null?void 0:v.addresses)??[],_=new Set((v==null?void 0:v.protocols)??[]),E=(v==null?void 0:v.metadata)??new Map,S=(v==null?void 0:v.tags)??new Map,x=v==null?void 0:v.peerRecordEnvelope;if(h==="patch"){if((u.multiaddrs!=null||u.addresses!=null)&&(w=[],u.multiaddrs!=null&&w.push(...u.multiaddrs.map(U=>({isCertified:!1,multiaddr:U}))),u.addresses!=null&&w.push(...u.addresses)),u.protocols!=null&&(_=new Set(u.protocols)),u.metadata!=null){const U=u.metadata instanceof Map?[...u.metadata.entries()]:Object.entries(u.metadata);E=createSortedMap(U,{validate:validateMetadata})}if(u.tags!=null){const U=u.tags instanceof Map?[...u.tags.entries()]:Object.entries(u.tags);S=createSortedMap(U,{validate:validateTag,map:mapTag})}u.peerRecordEnvelope!=null&&(x=u.peerRecordEnvelope)}if(h==="merge"){if(u.multiaddrs!=null&&w.push(...u.multiaddrs.map(U=>({isCertified:!1,multiaddr:U}))),u.addresses!=null&&w.push(...u.addresses),u.protocols!=null&&(_=new Set([..._,...u.protocols])),u.metadata!=null){const U=u.metadata instanceof Map?[...u.metadata.entries()]:Object.entries(u.metadata);for(const[te,X]of U)X==null?E.delete(te):E.set(te,X);E=createSortedMap([...E.entries()],{validate:validateMetadata})}if(u.tags!=null){const U=u.tags instanceof Map?[...u.tags.entries()]:Object.entries(u.tags),te=new Map(S);for(const[X,ie]of U)ie==null?te.delete(X):te.set(X,ie);S=createSortedMap([...te.entries()],{validate:validateTag,map:mapTag})}u.peerRecordEnvelope!=null&&(x=u.peerRecordEnvelope)}let T;(v==null?void 0:v.id.publicKey)!=null?T=publicKeyToProtobuf$1(v.id.publicKey):u.publicKey!=null?T=publicKeyToProtobuf$1(u.publicKey):y.publicKey!=null&&(T=publicKeyToProtobuf$1(y.publicKey));const C={addresses:await dedupeFilterAndSortAddresses(y,b.addressFilter??(async()=>!0),w,(D=b.existingPeer)==null?void 0:D.peerPB.addresses,b),protocols:[..._.values()].sort((U,te)=>U.localeCompare(te)),metadata:E,tags:S,publicKey:T,peerRecordEnvelope:x};return C.addresses.forEach(U=>{var te,X,ie;U.observed=((ie=(X=(te=b.existingPeer)==null?void 0:te.peerPB.addresses)==null?void 0:X.find(ee=>equals(ee.multiaddr,ee.multiaddr)))==null?void 0:ie.observed)??Date.now()}),y.type!=="RSA"&&delete C.publicKey,C}function createSortedMap(y,u){var b;const h=new Map;for(const[v,w]of y)w!=null&&u.validate(v,w);for(const[v,w]of y.sort(([_],[E])=>_.localeCompare(E)))w!=null&&h.set(v,((b=u.map)==null?void 0:b.call(u,v,w))??w);return h}function validateMetadata(y,u){if(typeof y!="string")throw new InvalidParametersError$2("Metadata key must be a string");if(!(u instanceof Uint8Array))throw new InvalidParametersError$2("Metadata value must be a Uint8Array")}function validateTag(y,u){if(typeof y!="string")throw new InvalidParametersError$2("Tag name must be a string");if(u.value!=null){if(parseInt(`${u.value}`,10)!==u.value)throw new InvalidParametersError$2("Tag value must be an integer");if(u.value<0||u.value>100)throw new InvalidParametersError$2("Tag value must be between 0-100")}if(u.ttl!=null){if(parseInt(`${u.ttl}`,10)!==u.ttl)throw new InvalidParametersError$2("Tag ttl must be an integer");if(u.ttl<0)throw new InvalidParametersError$2("Tag ttl must be between greater than 0")}}function mapTag(y,u){let h;u.expiry!=null&&(h=u.expiry),u.ttl!=null&&(h=BigInt(Date.now()+Number(u.ttl)));const b={value:u.value??0};return h!=null&&(b.expiry=h),b}function keyToPeerId(y){const u=y.toString().split("/")[2],h=CID.parse(u,base32$2);return peerIdFromCID(h)}function decodePeer(y,u,h){const b=keyToPeerId(y);return bytesToPeer(b,u,h)}function mapQuery(y,u){return{prefix:NAMESPACE_COMMON,filters:(y.filters??[]).map(h=>({key:b,value:v})=>h(decodePeer(b,v,u))),orders:(y.orders??[]).map(h=>(b,v)=>h(decodePeer(b.key,b.value,u),decodePeer(v.key,v.value,u)))}}var hn,Nu,Lu,Fu;class PersistentStore{constructor(u,h={}){ur(this,hn);Z(this,"peerId");Z(this,"datastore");Z(this,"locks");Z(this,"addressFilter");Z(this,"log");Z(this,"maxAddressAge");Z(this,"maxPeerAge");this.log=u.logger.forComponent("libp2p:peer-store"),this.peerId=u.peerId,this.datastore=u.datastore,this.addressFilter=h.addressFilter,this.locks=trackedPeerMap({name:"libp2p_peer_store_locks",metrics:u.metrics}),this.maxAddressAge=h.maxAddressAge??MAX_ADDRESS_AGE,this.maxPeerAge=h.maxPeerAge??MAX_PEER_AGE}getLock(u){let h=this.locks.get(u);return h==null&&(h={refs:0,lock:createMortice({name:u.toString(),singleProcess:!0})},this.locks.set(u,h)),h.refs++,h}maybeRemoveLock(u,h){h.refs--,h.refs===0&&(h.lock.finalize(),this.locks.delete(u))}async getReadLock(u,h){const b=this.getLock(u);try{const v=await b.lock.readLock(h);return()=>{v(),this.maybeRemoveLock(u,b)}}catch(v){throw this.maybeRemoveLock(u,b),v}}async getWriteLock(u,h){const b=this.getLock(u);try{const v=await b.lock.writeLock(h);return()=>{v(),this.maybeRemoveLock(u,b)}}catch(v){throw this.maybeRemoveLock(u,b),v}}async has(u,h){try{return await this.load(u,h),!0}catch(b){if(b.name!=="NotFoundError")throw b}return!1}async delete(u,h){this.peerId.equals(u)||await this.datastore.delete(peerIdToDatastoreKey(u),h)}async load(u,h){const b=peerIdToDatastoreKey(u),v=await this.datastore.get(b,h),w=Peer.decode(v);if($t(this,hn,Fu).call(this,u,w))throw await this.datastore.delete(b,h),new NotFoundError$1;return pbToPeer(u,w,this.peerId.equals(u)?1/0:this.maxAddressAge)}async save(u,h,b){const v=await $t(this,hn,Nu).call(this,u,b),w=await toPeerPB(u,h,"patch",{...b,addressFilter:this.addressFilter});return $t(this,hn,Lu).call(this,u,w,v)}async patch(u,h,b){const v=await $t(this,hn,Nu).call(this,u,b),w=await toPeerPB(u,h,"patch",{...b,addressFilter:this.addressFilter,existingPeer:v});return $t(this,hn,Lu).call(this,u,w,v)}async merge(u,h,b){const v=await $t(this,hn,Nu).call(this,u,b),w=await toPeerPB(u,h,"merge",{addressFilter:this.addressFilter,existingPeer:v});return $t(this,hn,Lu).call(this,u,w,v)}async*all(u){for await(const{key:h,value:b}of this.datastore.query(mapQuery(u??{},this.maxAddressAge),u)){const v=keyToPeerId(h);if(v.equals(this.peerId))continue;const w=Peer.decode(b);if($t(this,hn,Fu).call(this,v,w)){await this.datastore.delete(h,u);continue}yield pbToPeer(v,w,this.peerId.equals(v)?1/0:this.maxAddressAge)}}}hn=new WeakSet,Nu=async function(u,h){try{const b=peerIdToDatastoreKey(u),v=await this.datastore.get(b,h),w=Peer.decode(v);if($t(this,hn,Fu).call(this,u,w))throw await this.datastore.delete(b,h),new NotFoundError$1;return{peerPB:w,peer:pbToPeer(u,w,this.maxAddressAge)}}catch(b){b.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",b)}},Lu=async function(u,h,b,v){h.updated=Date.now();const w=Peer.encode(h);return await this.datastore.put(peerIdToDatastoreKey(u),w,v),{peer:pbToPeer(u,h,this.maxAddressAge),previous:b==null?void 0:b.peer,updated:b==null||!peerEquals(h,b.peerPB)}},Fu=function(u,h){if(h.updated==null)return!0;if(this.peerId.equals(u))return!1;const b=h.updated<Date.now()-this.maxPeerAge,v=Date.now()-this.maxAddressAge,w=h.addresses.filter(_=>_.observed!=null&&_.observed>v);return b&&w.length===0};var vh,Ho,Uu;vh=Symbol.toStringTag;class PersistentPeerStore{constructor(u,h={}){ur(this,Ho);Z(this,"store");Z(this,"events");Z(this,"peerId");Z(this,"log");Z(this,vh,"@libp2p/peer-store");this.log=u.logger.forComponent("libp2p:peer-store"),this.events=u.events,this.peerId=u.peerId,this.store=new PersistentStore(u,h)}async forEach(u,h){for await(const b of this.store.all(h))u(b)}async all(u){return all$2(this.store.all(u))}async delete(u,h){const b=await this.store.getReadLock(u,h);try{await this.store.delete(u,h)}finally{b()}}async has(u,h){const b=await this.store.getReadLock(u,h);try{return await this.store.has(u,h)}finally{this.log.trace("has release read lock"),b==null||b()}}async get(u,h){const b=await this.store.getReadLock(u,h);try{return await this.store.load(u,h)}finally{b==null||b()}}async getInfo(u,h){const b=await this.get(u,h);return{id:b.id,multiaddrs:b.addresses.map(({multiaddr:v})=>v)}}async save(u,h,b){const v=await this.store.getWriteLock(u,b);try{const w=await this.store.save(u,h,b);return $t(this,Ho,Uu).call(this,u,w),w.peer}finally{v==null||v()}}async patch(u,h,b){const v=await this.store.getWriteLock(u,b);try{const w=await this.store.patch(u,h,b);return $t(this,Ho,Uu).call(this,u,w),w.peer}finally{v==null||v()}}async merge(u,h,b){const v=await this.store.getWriteLock(u,b);try{const w=await this.store.merge(u,h,b);return $t(this,Ho,Uu).call(this,u,w),w.peer}finally{v==null||v()}}async consumePeerRecord(u,h,b){const v=isPeerId(h)?h:isPeerId(h==null?void 0:h.expectedPeer)?h.expectedPeer:void 0,w=isPeerId(h)||h===void 0?b:h,_=await RecordEnvelope.openAndCertify(u,PeerRecord.DOMAIN,w),E=peerIdFromCID(_.publicKey.toCID());if((v==null?void 0:v.equals(E))===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",v,E),!1;const S=PeerRecord.createFromProtobuf(_.payload);let x;try{x=await this.get(E,w)}catch(T){if(T.name!=="NotFoundError")throw T}if((x==null?void 0:x.peerRecordEnvelope)!=null){const T=RecordEnvelope.createFromProtobuf(x.peerRecordEnvelope),C=PeerRecord.createFromProtobuf(T.payload);if(C.seqNumber>=S.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",C.seqNumber,S.seqNumber),!1}return await this.patch(S.peerId,{peerRecordEnvelope:u,addresses:S.multiaddrs.map(T=>({isCertified:!0,multiaddr:T}))},w),!0}}Ho=new WeakSet,Uu=function(u,h){h.updated&&(this.peerId.equals(u)?this.events.safeDispatchEvent("self:peer:update",{detail:h}):this.events.safeDispatchEvent("peer:update",{detail:h}))};function persistentPeerStore(y,u={}){return new PersistentPeerStore(y,u)}const Do=class Do extends Error{constructor(h="Not Found"){super(h);Z(this,"name",Do.name);Z(this,"code",Do.code)}};Z(Do,"name","NotFoundError"),Z(Do,"code","ERR_NOT_FOUND");let NotFoundError=Do;function peekable(y){const[u,h]=y[Symbol.asyncIterator]!=null?[y[Symbol.asyncIterator](),Symbol.asyncIterator]:[y[Symbol.iterator](),Symbol.iterator],b=[];return{peek:()=>u.next(),push:v=>{b.push(v)},next:()=>b.length>0?{done:!1,value:b.shift()}:u.next(),[h](){return this}}}function isAsyncIterable$2(y){return y[Symbol.asyncIterator]!=null}function filter(y,u){let h=0;if(isAsyncIterable$2(y))return async function*(){for await(const S of y)await u(S,h++)&&(yield S)}();const b=peekable(y),{value:v,done:w}=b.next();if(w===!0)return function*(){}();const _=u(v,h++);if(typeof _.then=="function")return async function*(){await _&&(yield v);for(const S of b)await u(S,h++)&&(yield S)}();const E=u;return function*(){_===!0&&(yield v);for(const S of b)E(S,h++)&&(yield S)}()}function isAsyncIterable$1(y){return y[Symbol.asyncIterator]!=null}function sort(y,u){return isAsyncIterable$1(y)?async function*(){yield*(await all$2(y)).sort(u)}():function*(){yield*all$2(y).sort(u)}()}function isAsyncIterable(y){return y[Symbol.asyncIterator]!=null}function take(y,u){return isAsyncIterable(y)?async function*(){let h=0;if(!(u<1)){for await(const b of y)if(yield b,h++,h===u)return}}():function*(){let h=0;if(!(u<1)){for(const b of y)if(yield b,h++,h===u)return}}()}class BaseDatastore{put(u,h,b){return Promise.reject(new Error(".put is not implemented"))}get(u,h){return Promise.reject(new Error(".get is not implemented"))}has(u,h){return Promise.reject(new Error(".has is not implemented"))}delete(u,h){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(u,h={}){for await(const{key:b,value:v}of u)await this.put(b,v,h),yield b}async*getMany(u,h={}){for await(const b of u)yield{key:b,value:await this.get(b,h)}}async*deleteMany(u,h={}){for await(const b of u)await this.delete(b,h),yield b}batch(){let u=[],h=[];return{put(b,v){u.push({key:b,value:v})},delete(b){h.push(b)},commit:async b=>{await drain(this.putMany(u,b)),u=[],await drain(this.deleteMany(h,b)),h=[]}}}async*_all(u,h){throw new Error("._all is not implemented")}async*_allKeys(u,h){throw new Error("._allKeys is not implemented")}query(u,h){let b=this._all(u,h);if(u.prefix!=null){const v=u.prefix;b=filter(b,w=>w.key.toString().startsWith(v))}if(Array.isArray(u.filters)&&(b=u.filters.reduce((v,w)=>filter(v,w),b)),Array.isArray(u.orders)&&(b=u.orders.reduce((v,w)=>sort(v,w),b)),u.offset!=null){let v=0;const w=u.offset;b=filter(b,()=>v++>=w)}return u.limit!=null&&(b=take(b,u.limit)),b}queryKeys(u,h){let b=this._allKeys(u,h);if(u.prefix!=null){const v=u.prefix;b=filter(b,w=>w.toString().startsWith(v))}if(Array.isArray(u.filters)&&(b=u.filters.reduce((v,w)=>filter(v,w),b)),Array.isArray(u.orders)&&(b=u.orders.reduce((v,w)=>sort(v,w),b)),u.offset!=null){const v=u.offset;let w=0;b=filter(b,()=>w++>=v)}return u.limit!=null&&(b=take(b,u.limit)),b}}class MemoryDatastore extends BaseDatastore{constructor(){super();Z(this,"data");this.data=new Map}put(h,b,v){var w;return(w=v==null?void 0:v.signal)==null||w.throwIfAborted(),this.data.set(h.toString(),b),h}get(h,b){var w;(w=b==null?void 0:b.signal)==null||w.throwIfAborted();const v=this.data.get(h.toString());if(v==null)throw new NotFoundError;return v}has(h,b){var v;return(v=b==null?void 0:b.signal)==null||v.throwIfAborted(),this.data.has(h.toString())}delete(h,b){var v;(v=b==null?void 0:b.signal)==null||v.throwIfAborted(),this.data.delete(h.toString())}*_all(h,b){var v,w;(v=b==null?void 0:b.signal)==null||v.throwIfAborted();for(const[_,E]of this.data.entries())yield{key:new Key(_),value:E},(w=b==null?void 0:b.signal)==null||w.throwIfAborted()}*_allKeys(h,b){var v,w;(v=b==null?void 0:b.signal)==null||v.throwIfAborted();for(const _ of this.data.keys())yield new Key(_),(w=b==null?void 0:b.signal)==null||w.throwIfAborted()}}class TrackedMap extends Map{constructor(h){super();Z(this,"metric");const{name:b,metrics:v}=h;this.metric=v.registerMetric(b),this.updateComponentMetric()}set(h,b){return super.set(h,b),this.updateComponentMetric(),this}delete(h){const b=super.delete(h);return this.updateComponentMetric(),b}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function trackedMap(y){const{name:u,metrics:h}=y;let b;return h!=null?b=new TrackedMap({name:u,metrics:h}):b=new Map,b}const MAX_DATE=864e13,CODEC_TLS=448,CODEC_SNI=449,CODEC_DNS=53,CODEC_DNS4=54,CODEC_DNS6=55,CODEC_DNSADDR=56;class DNSMappings{constructor(u,h={}){Z(this,"log");Z(this,"mappings");this.log=u.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=trackedMap({name:"libp2p_address_manager_dns_mappings",metrics:u.metrics})}has(u){const h=this.findHost(u);for(const b of this.mappings.values())if(b.domain===h)return!0;return!1}add(u,h){h.forEach(b=>{this.log("add DNS mapping %s to %s",b,u);const v=isPrivateIp(b)===!0;this.mappings.set(b,{domain:u,verified:v,expires:v?MAX_DATE-Date.now():0,lastVerified:v?MAX_DATE-Date.now():void 0})})}remove(u){const h=this.findHost(u);let b=!1;for(const[v,w]of this.mappings.entries())w.domain===h&&(this.log("removing %s to %s DNS mapping %e",v,w.domain,new Error("where")),this.mappings.delete(v),b=b||w.verified);return b}getAll(u){const h=[];for(let b=0;b<u.length;b++){const w=u[b].multiaddr.stringTuples(),_=w[0][1];if(_!=null)for(const[E,S]of this.mappings.entries()){if(_!==E)continue;this.maybeAddSNITuple(w,S.domain)&&(u.splice(b,1),b--,h.push({multiaddr:multiaddr(`/${w.map(T=>[protocols(T[0]).name,T[1]].join("/")).join("/")}`),verified:S.verified,type:"dns-mapping",expires:S.expires,lastVerified:S.lastVerified}))}}return h}maybeAddSNITuple(u,h){var b;for(let v=0;v<u.length;v++)if(u[v][0]===CODEC_TLS&&((b=u[v+1])==null?void 0:b[0])!==CODEC_SNI)return u.splice(v+1,0,[CODEC_SNI,h]),!0;return!1}confirm(u,h){const b=this.findHost(u);let v=!1;for(const[w,_]of this.mappings.entries())_.domain===b&&(this.log("marking %s to %s DNS mapping as verified",w,_.domain),v=_.verified,_.verified=!0,_.expires=Date.now()+h,_.lastVerified=Date.now());return v}unconfirm(u,h){const b=this.findHost(u);let v=!1;for(const[w,_]of this.mappings.entries())_.domain===b&&(this.log("removing verification of %s to %s DNS mapping",w,_.domain),v=v||_.verified,_.verified=!1,_.expires=Date.now()+h);return v}findHost(u){for(const h of u.stringTuples())if(h[0]===CODEC_SNI||h[0]===CODEC_DNS||h[0]===CODEC_DNS4||h[0]===CODEC_DNS6||h[0]===CODEC_DNSADDR)return h[1]}}const CODEC_IP4$1=4,CODEC_IP6$1=41,CODEC_TCP=6,CODEC_UDP=273;class IPMappings{constructor(u,h={}){Z(this,"log");Z(this,"mappings");this.log=u.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=trackedMap({name:"libp2p_address_manager_ip_mappings",metrics:u.metrics})}has(u){const h=u.stringTuples();for(const b of this.mappings.values())for(const v of b)if(v.externalIp===h[0][1])return!0;return!1}add(u,h,b,v=h,w="tcp"){const _=`${u}-${h}-${w}`,E=this.mappings.get(_)??[],S={internalIp:u,internalPort:h,externalIp:b,externalPort:v,externalFamily:isIPv4(b)?4:6,protocol:w,verified:!1,expires:0};E.push(S),this.mappings.set(_,E)}remove(u){const h=u.stringTuples(),b=h[0][1]??"",v=h[1][0]===CODEC_TCP?"tcp":"udp",w=parseInt(h[1][1]??"0");let _=!1;for(const[E,S]of this.mappings.entries()){for(let x=0;x<S.length;x++){const T=S[x];T.externalIp===b&&T.externalPort===w&&T.protocol===v&&(this.log("removing %s:%s to %s:%s %s IP mapping",T.externalIp,T.externalPort,b,w,v),_=_||T.verified,S.splice(x,1),x--)}S.length===0&&this.mappings.delete(E)}return _}getAll(u){const h=[];for(const{multiaddr:b}of u){const v=b.stringTuples();let w;if((v[0][0]===CODEC_IP4$1||v[0][0]===CODEC_IP6$1)&&v[1][0]===CODEC_TCP?w=`${v[0][1]}-${v[1][1]}-tcp`:(v[0][0]===CODEC_IP4$1||v[0][0]===CODEC_IP6$1)&&v[1][0]===CODEC_UDP&&(w=`${v[0][1]}-${v[1][1]}-udp`),w==null)continue;const _=this.mappings.get(w);if(_!=null)for(const E of _)v[0][0]=E.externalFamily===4?CODEC_IP4$1:CODEC_IP6$1,v[0][1]=E.externalIp,v[1][1]=`${E.externalPort}`,h.push({multiaddr:multiaddr(`/${v.map(S=>[protocols(S[0]).name,S[1]].join("/")).join("/")}`),verified:E.verified,type:"ip-mapping",expires:E.expires,lastVerified:E.lastVerified})}return h}confirm(u,h){const v=u.stringTuples()[0][1];let w=!1;for(const _ of this.mappings.values())for(const E of _)E.externalIp===v&&(this.log("marking %s to %s IP mapping as verified",E.internalIp,E.externalIp),w=E.verified,E.verified=!0,E.expires=Date.now()+h,E.lastVerified=Date.now());return w}unconfirm(u,h){const b=u.stringTuples(),v=b[0][1]??"",w=b[1][0]===CODEC_TCP?"tcp":"udp",_=parseInt(b[1][1]??"0");let E=!1;for(const S of this.mappings.values())for(let x=0;x<S.length;x++){const T=S[x];T.externalIp===v&&T.externalPort===_&&T.protocol===w&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",T.externalIp,T.externalPort,v,_,w),E=E||T.verified,T.verified=!1,T.expires=Date.now()+h)}return E}}function isLinkLocal(y){try{for(const{code:u,value:h}of y.getComponents())if(u!==CODE_IP6ZONE&&h!=null){if(u===CODE_IP4)return h.startsWith("169.254.");if(u===CODE_IP6)return h.toLowerCase().startsWith("fe80")}}catch{}return!1}const defaultValues$2={maxObservedAddresses:10};class ObservedAddresses{constructor(u,h={}){Z(this,"log");Z(this,"addresses");Z(this,"maxObservedAddresses");this.log=u.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=trackedMap({name:"libp2p_address_manager_observed_addresses",metrics:u.metrics}),this.maxObservedAddresses=h.maxObservedAddresses??defaultValues$2.maxObservedAddresses}has(u){return this.addresses.has(u.toString())}removePrefixed(u){for(const h of this.addresses.keys())h.toString().startsWith(u)&&this.addresses.delete(h)}add(u){this.addresses.size!==this.maxObservedAddresses&&(isPrivate(u)||isLinkLocal(u)||(this.log("adding observed address %a",u),this.addresses.set(u.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([u,h])=>({multiaddr:multiaddr(u),verified:h.verified,type:"observed",expires:h.expires,lastVerified:h.lastVerified}))}remove(u){var b;const h=((b=this.addresses.get(u.toString()))==null?void 0:b.verified)??!1;return this.log("removing observed address %a",u),this.addresses.delete(u.toString()),h}confirm(u,h){const b=u.toString(),v=this.addresses.get(b)??{verified:!1,expires:Date.now()+h,lastVerified:Date.now()},w=v.verified;return v.verified=!0,v.expires=Date.now()+h,v.lastVerified=Date.now(),this.log("marking observed address %a as verified",b),this.addresses.set(b,v),w}}const NETWORK_CODECS=[CODE_IP4,CODE_IP6,CODE_DNS,CODE_DNS4,CODE_DNS6,CODE_DNSADDR];function isNetworkAddress(y){try{for(const{code:u}of y.getComponents())if(u!==CODE_IP6ZONE)return NETWORK_CODECS.includes(u)}catch{}return!1}const defaultValues$1={maxObservedAddresses:10};class TransportAddresses{constructor(u,h={}){Z(this,"log");Z(this,"addresses");Z(this,"maxObservedAddresses");this.log=u.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=trackedMap({name:"libp2p_address_manager_transport_addresses",metrics:u.metrics}),this.maxObservedAddresses=h.maxObservedAddresses??defaultValues$1.maxObservedAddresses}get(u,h){if(isPrivate(u))return{multiaddr:u,verified:!0,type:"transport",expires:Date.now()+h,lastVerified:Date.now()};const b=this.toKey(u);let v=this.addresses.get(b);return v==null&&(v={verified:!isNetworkAddress(u),expires:0},this.addresses.set(b,v)),{multiaddr:u,verified:v.verified,type:"transport",expires:v.expires,lastVerified:v.lastVerified}}has(u){const h=this.toKey(u);return this.addresses.has(h)}remove(u){var v;const h=this.toKey(u),b=((v=this.addresses.get(h))==null?void 0:v.verified)??!1;return this.log("removing observed address %a",u),this.addresses.delete(h),b}confirm(u,h){const b=this.toKey(u),v=this.addresses.get(b)??{verified:!1,expires:0,lastVerified:0},w=v.verified;return v.verified=!0,v.expires=Date.now()+h,v.lastVerified=Date.now(),this.addresses.set(b,v),w}unconfirm(u,h){const b=this.toKey(u),v=this.addresses.get(b)??{verified:!1,expires:0},w=v.verified;return v.verified=!1,v.expires=Date.now()+h,this.addresses.set(b,v),w}toKey(u){if(isNetworkAddress(u)){const h=u.toOptions();return`${h.host}-${h.port}-${h.transport}`}return u.toString()}}const ONE_MINUTE=6e4,defaultValues={maxObservedAddresses:10,addressVerificationTTL:ONE_MINUTE*10,addressVerificationRetry:ONE_MINUTE*5},defaultAddressFilter=y=>y;function stripPeerId(y,u){const h=y.getPeerId();return h!=null&&peerIdFromString$1(h).equals(u)&&(y=y.decapsulate(multiaddr(`/p2p/${u.toString()}`))),y}var wh;wh=Symbol.toStringTag;class AddressManager{constructor(u,h={}){Z(this,"log");Z(this,"components");Z(this,"listen");Z(this,"announce");Z(this,"appendAnnounce");Z(this,"announceFilter");Z(this,"observed");Z(this,"dnsMappings");Z(this,"ipMappings");Z(this,"transportAddresses");Z(this,"observedAddressFilter");Z(this,"addressVerificationTTL");Z(this,"addressVerificationRetry");Z(this,wh,"@libp2p/address-manager");const{listen:b=[],announce:v=[],appendAnnounce:w=[]}=h;this.components=u,this.log=u.logger.forComponent("libp2p:address-manager"),this.listen=b.map(_=>_.toString()),this.announce=new Set(v.map(_=>_.toString())),this.appendAnnounce=new Set(w.map(_=>_.toString())),this.observed=new ObservedAddresses(u,h),this.dnsMappings=new DNSMappings(u,h),this.ipMappings=new IPMappings(u,h),this.transportAddresses=new TransportAddresses(u,h),this.announceFilter=h.announceFilter??defaultAddressFilter,this.observedAddressFilter=createScalableCuckooFilter(1024),this.addressVerificationTTL=h.addressVerificationTTL??defaultValues.addressVerificationTTL,this.addressVerificationRetry=h.addressVerificationRetry??defaultValues.addressVerificationRetry,this._updatePeerStoreAddresses=debounce$1(this._updatePeerStoreAddresses.bind(this),1e3),u.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),u.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){const u=this.getAddresses().map(h=>h.getPeerId()===this.components.peerId.toString()?h.decapsulate(`/p2p/${this.components.peerId.toString()}`):h);this.components.peerStore.patch(this.components.peerId,{multiaddrs:u}).catch(h=>{this.log.error("error updating addresses",h)})}getListenAddrs(){return Array.from(this.listen).map(u=>multiaddr(u))}getAnnounceAddrs(){return Array.from(this.announce).map(u=>multiaddr(u))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(u=>multiaddr(u))}getObservedAddrs(){return this.observed.getAll().map(u=>u.multiaddr)}addObservedAddr(u){const h=u.stringTuples(),b=`${h[0][1]}:${h[1][1]}`;this.observedAddressFilter.has(b)||(this.observedAddressFilter.add(b),u=stripPeerId(u,this.components.peerId),!this.ipMappings.has(u)&&(this.dnsMappings.has(u)||this.observed.add(u)))}confirmObservedAddr(u,h){u=stripPeerId(u,this.components.peerId);let b=!0;((h==null?void 0:h.type)==="transport"||this.transportAddresses.has(u))&&!this.transportAddresses.confirm(u,(h==null?void 0:h.ttl)??this.addressVerificationTTL)&&b&&(b=!1),((h==null?void 0:h.type)==="dns-mapping"||this.dnsMappings.has(u))&&!this.dnsMappings.confirm(u,(h==null?void 0:h.ttl)??this.addressVerificationTTL)&&b&&(b=!1),((h==null?void 0:h.type)==="ip-mapping"||this.ipMappings.has(u))&&!this.ipMappings.confirm(u,(h==null?void 0:h.ttl)??this.addressVerificationTTL)&&b&&(b=!1),((h==null?void 0:h.type)==="observed"||this.observed.has(u))&&(this.maybeUpgradeToIPMapping(u)?(this.ipMappings.confirm(u,(h==null?void 0:h.ttl)??this.addressVerificationTTL),b=!1):!this.observed.confirm(u,(h==null?void 0:h.ttl)??this.addressVerificationTTL)&&b&&(b=!1)),b||this._updatePeerStoreAddresses()}removeObservedAddr(u,h){u=stripPeerId(u,this.components.peerId);let b=!1;this.observed.has(u)&&!this.observed.remove(u)&&b&&(b=!1),this.transportAddresses.has(u)&&!this.transportAddresses.unconfirm(u,(h==null?void 0:h.ttl)??this.addressVerificationRetry)&&b&&(b=!1),this.dnsMappings.has(u)&&!this.dnsMappings.unconfirm(u,(h==null?void 0:h.ttl)??this.addressVerificationRetry)&&b&&(b=!1),this.ipMappings.has(u)&&!this.ipMappings.unconfirm(u,(h==null?void 0:h.ttl)??this.addressVerificationRetry)&&b&&(b=!1),b&&this._updatePeerStoreAddresses()}getAddresses(){const u=new Set,h=this.getAddressesWithMetadata().filter(b=>{if(!b.verified)return!1;const v=b.multiaddr.toString();return u.has(v)?!1:(u.add(v),!0)}).map(b=>b.multiaddr);return this.announceFilter(h.map(b=>{const v=multiaddr(b),w=v.getComponents().pop();return(w==null?void 0:w.value)===this.components.peerId.toString()?v:v.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){const u=this.getAnnounceAddrs();if(u.length>0)return this.components.transportManager.getListeners().forEach(v=>{v.updateAnnounceAddrs(u)}),u.map(v=>({multiaddr:v,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let h=[];h=h.concat(this.components.transportManager.getAddrs().map(v=>this.transportAddresses.get(v,this.addressVerificationTTL)));const b=this.getAppendAnnounceAddrs();return b.length>0&&(this.components.transportManager.getListeners().forEach(v=>{v.updateAnnounceAddrs(b)}),h=h.concat(b.map(v=>({multiaddr:v,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),h=h.concat(this.observed.getAll()),h=h.concat(this.ipMappings.getAll(h)),h=h.concat(this.dnsMappings.getAll(h)),h}addDNSMapping(u,h){this.dnsMappings.add(u,h)}removeDNSMapping(u){this.dnsMappings.remove(multiaddr(`/dns/${u}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(u,h,b,v=h,w="tcp"){this.ipMappings.add(u,h,b,v,w),this.observed.removePrefixed(`/ip${isIPv4(b)?4:6}/${b}/${w}/${v}`)}removePublicAddressMapping(u,h,b,v=h,w="tcp"){this.ipMappings.remove(multiaddr(`/ip${isIPv4(b)?4:6}/${b}/${w}/${v}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(u){if(this.ipMappings.has(u))return!1;const h=u.toOptions();if(h.family===6||h.host==="127.0.0.1"||isPrivateIp(h.host)===!0)return!1;const b=this.components.transportManager.getListeners(),v=[w=>WebSockets$1.exactMatch(w)||WebSocketsSecure.exactMatch(w),w=>TCP.exactMatch(w),w=>QUICV1.exactMatch(w)];for(const w of v){if(!w(u))continue;const _=b.filter(x=>x.getAddrs().filter(T=>T.toOptions().family===4&&w(T)).length>0);if(_.length!==1)continue;const E=_[0].getAddrs().filter(x=>x.toOptions().host!=="127.0.0.1").pop();if(E==null)continue;const S=E.toOptions();return this.observed.remove(u),this.ipMappings.add(S.host,S.port,h.host,h.port,h.transport),!0}return!1}}var messages;(function(y){y.NOT_STARTED_YET="The libp2p node is not started yet",y.NOT_FOUND="Not found"})(messages||(messages={}));class MissingServiceError extends Error{constructor(u="Missing service"){super(u),this.name="MissingServiceError"}}class UnmetServiceDependenciesError extends Error{constructor(u="Unmet service dependencies"){super(u),this.name="UnmetServiceDependenciesError"}}class NoContentRoutersError extends Error{constructor(u="No content routers available"){super(u),this.name="NoContentRoutersError"}}class NoPeerRoutersError extends Error{constructor(u="No peer routers available"){super(u),this.name="NoPeerRoutersError"}}class QueriedForSelfError extends Error{constructor(u="Should not try to find self"){super(u),this.name="QueriedForSelfError"}}class UnhandledProtocolError extends Error{constructor(u="Unhandled protocol error"){super(u),this.name="UnhandledProtocolError"}}class DuplicateProtocolHandlerError extends Error{constructor(u="Duplicate protocol handler error"){super(u),this.name="DuplicateProtocolHandlerError"}}class DialDeniedError extends Error{constructor(u="Dial denied error"){super(u),this.name="DialDeniedError"}}class UnsupportedListenAddressError extends Error{constructor(u="No transport was configured to listen on this address"){super(u),this.name="UnsupportedListenAddressError"}}class UnsupportedListenAddressesError extends Error{constructor(u="Configured listen addresses could not be listened on"){super(u),this.name="UnsupportedListenAddressesError"}}class NoValidAddressesError extends Error{constructor(u="No valid addresses"){super(u),this.name="NoValidAddressesError"}}class ConnectionInterceptedError extends Error{constructor(u="Connection intercepted"){super(u),this.name="ConnectionInterceptedError"}}class ConnectionDeniedError extends Error{constructor(u="Connection denied"){super(u),this.name="ConnectionDeniedError"}}class MuxerUnavailableError extends Error{constructor(u="Stream is not multiplexed"){super(u),this.name="MuxerUnavailableError"}}class EncryptionFailedError extends Error{constructor(u="Encryption failed"){super(u),this.name="EncryptionFailedError"}}class TransportUnavailableError extends Error{constructor(u="Transport unavailable"){super(u),this.name="TransportUnavailableError"}}class DefaultComponents{constructor(u={}){Z(this,"components",{});Z(this,"_started",!1);this.components={};for(const[h,b]of Object.entries(u))this.components[h]=b;this.components.logger==null&&(this.components.logger=defaultLogger())}isStarted(){return this._started}async _invokeStartableMethod(u){await Promise.all(Object.values(this.components).filter(h=>isStartable(h)).map(async h=>{var b;await((b=h[u])==null?void 0:b.call(h))}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const OPTIONAL_SERVICES=["metrics","connectionProtector","dns"],NON_SERVICE_PROPERTIES=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function defaultComponents(y={}){const u=new DefaultComponents(y);return new Proxy(u,{get(b,v,w){if(typeof v=="string"&&!NON_SERVICE_PROPERTIES.includes(v)){const _=u.components[v];if(_==null&&!OPTIONAL_SERVICES.includes(v))throw new MissingServiceError(`${v} not set`);return _}return Reflect.get(b,v,w)},set(b,v,w){return typeof v=="string"?u.components[v]=w:Reflect.set(b,v,w),!0}})}function checkServiceDependencies(y){const u={};for(const h of Object.values(y.components))for(const b of getServiceCapabilities(h))u[b]=!0;for(const h of Object.values(y.components))for(const b of getServiceDependencies(h))if(u[b]!==!0)throw new UnmetServiceDependenciesError(`Service "${getServiceName(h)}" required capability "${b}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function getServiceCapabilities(y){return Array.isArray(y==null?void 0:y[serviceCapabilities])?y[serviceCapabilities]:[]}function getServiceDependencies(y){return Array.isArray(y==null?void 0:y[serviceDependencies])?y[serviceDependencies]:[]}function getServiceName(y){return(y==null?void 0:y[Symbol.toStringTag])??(y==null?void 0:y.toString())??"unknown"}const CODEC_IP4=4,CODEC_IP6=41;function connectionGater(y={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async u=>{if(WebSockets$1.matches(u))return!1;const h=u.stringTuples();return h[0][0]===CODEC_IP4||h[0][0]===CODEC_IP6?!!isPrivateIp(`${h[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...y}}function getPeerAddress(y){if(isPeerId(y))return{peerId:y,multiaddrs:[]};let u=Array.isArray(y)?y:[y],h;if(u.length>0){const b=u[0].getPeerId();h=b==null?void 0:peerIdFromString$1(b),u.forEach(v=>{if(!isMultiaddr(v))throw new InvalidMultiaddrError$1("Invalid multiaddr");const w=v.getPeerId();if(w==null){if(h!=null)throw new InvalidParametersError$2("Multiaddrs must all have the same peer id or have no peer id")}else{const _=peerIdFromString$1(w);if((h==null?void 0:h.equals(_))!==!0)throw new InvalidParametersError$2("Multiaddrs must all have the same peer id or have no peer id")}})}return u=u.filter(b=>!PEER_ID.exactMatch(b)),{peerId:h,multiaddrs:u}}const DEFAULT_CLOSABLE_PROTOCOLS=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function safelyCloseConnectionIfUnused(y,u){var v;const h=((v=y==null?void 0:y.streams)==null?void 0:v.map(w=>w.protocol))??[],b=(u==null?void 0:u.closableProtocols)??DEFAULT_CLOSABLE_PROTOCOLS;if(!(h.filter(w=>w!=null&&!b.includes(w)).length>0))try{await(y==null?void 0:y.close(u))}catch(w){y==null||y.abort(w)}}async function resolveMultiaddrs(y,u){let h=!1;for(const v of resolvers.keys())if(h=y.protoNames().includes(v),h)break;if(!h)return[y];const b=await y.resolve(u);return u.log("resolved %s to",y,b.map(v=>v.toString())),b}function multiaddrToIpNet(y){try{let u;if(typeof y=="string"?u=multiaddr(y):u=y,!u.protoNames().includes("ipcidr")){const b=u.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";u=u.encapsulate(b)}return convertToIpNet(u)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${y}`)}}class ConnectionPruner{constructor(u,h={}){Z(this,"connectionManager");Z(this,"peerStore");Z(this,"allow");Z(this,"events");Z(this,"log");this.allow=(h.allow??[]).map(b=>multiaddrToIpNet(b)),this.connectionManager=u.connectionManager,this.peerStore=u.peerStore,this.events=u.events,this.log=u.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(u=>{this.log.error("error while pruning connections %e",u)})}async _maybePruneConnections(){const u=this.connectionManager.getConnections(),h=u.length,b=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",h,b),h<=b)return;const v=new PeerMap;for(const S of u){const x=S.remotePeer;if(!v.has(x)){v.set(x,0);try{const T=await this.peerStore.get(x);v.set(x,[...T.tags.values()].reduce((C,O)=>C+O.value,0))}catch(T){T.name!=="NotFoundError"&&this.log.error("error loading peer tags",T)}}}const w=this.sortConnections(u,v),_=Math.max(h-b,0),E=[];for(const S of w)if(this.log("too many connections open - closing a connection to %p",S.remotePeer),this.allow.some(T=>T.contains(S.remoteAddr.nodeAddress().address))||E.push(S),E.length===_)break;await Promise.all(E.map(async S=>{await safelyCloseConnectionIfUnused(S,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:E})}sortConnections(u,h){return u.sort((b,v)=>{const w=b.timeline.open,_=v.timeline.open;return w<_?1:w>_?-1:0}).sort((b,v)=>b.direction==="outbound"&&v.direction==="inbound"?1:b.direction==="inbound"&&v.direction==="outbound"?-1:0).sort((b,v)=>b.streams.length>v.streams.length?1:b.streams.length<v.streams.length?-1:0).sort((b,v)=>{const w=h.get(b.remotePeer)??0,_=h.get(v.remotePeer)??0;return w>_?1:w<_?-1:0})}}const DIAL_TIMEOUT=1e4,INBOUND_UPGRADE_TIMEOUT=1e4,PROTOCOL_NEGOTIATION_TIMEOUT=1e4,MAX_PEER_ADDRS_TO_DIAL=25,INBOUND_CONNECTION_THRESHOLD=5,MAX_INCOMING_PENDING_CONNECTIONS=10,MAX_PARALLEL_RECONNECTS=5,LAST_DIAL_FAILURE_KEY="last-dial-failure",LAST_DIAL_SUCCESS_KEY="last-dial-success",MAX_DIAL_QUEUE_LENGTH=500,MAX_CONNECTIONS=100,MAX_PARALLEL_DIALS=50;class JobRecipient{constructor(u){Z(this,"deferred");Z(this,"signal");var h;this.signal=u,this.deferred=pDefer(),this.onAbort=this.onAbort.bind(this),(h=this.signal)==null||h.addEventListener("abort",this.onAbort)}onAbort(){var u;this.deferred.reject(((u=this.signal)==null?void 0:u.reason)??new AbortError$5)}cleanup(){var u;(u=this.signal)==null||u.removeEventListener("abort",this.onAbort)}}function randomId(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}class Job{constructor(u,h){Z(this,"id");Z(this,"fn");Z(this,"options");Z(this,"recipients");Z(this,"status");Z(this,"timeline");Z(this,"controller");this.id=randomId(),this.status="queued",this.fn=u,this.options=h,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(u){this.controller.abort(u)}onAbort(){this.recipients.reduce((h,b)=>{var v;return h&&((v=b.signal)==null?void 0:v.aborted)===!0},!0)&&(this.controller.abort(new AbortError$5),this.cleanup())}async join(u={}){var b;const h=new JobRecipient(u.signal);return this.recipients.push(h),(b=u.signal)==null||b.addEventListener("abort",this.onAbort),h.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const u=await raceSignal(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(h=>{h.deferred.resolve(u)}),this.status="complete"}catch(u){this.recipients.forEach(h=>{h.deferred.reject(u)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(u=>{var h;u.cleanup(),(h=u.signal)==null||h.removeEventListener("abort",this.onAbort)})}}class Queue extends TypedEventEmitter{constructor(h={}){var b;super();Z(this,"concurrency");Z(this,"maxSize");Z(this,"queue");Z(this,"pending");Z(this,"sort");this.concurrency=h.concurrency??Number.POSITIVE_INFINITY,this.maxSize=h.maxSize??Number.POSITIVE_INFINITY,this.pending=0,h.metricName!=null&&((b=h.metrics)==null||b.registerMetricGroup(h.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})})),this.sort=h.sort,this.queue=[],this.emitEmpty=debounce$1(this.emitEmpty.bind(this),1),this.emitIdle=debounce$1(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let h;for(const b of this.queue)if(b.status==="queued"){h=b;break}return h==null?!1:(this.safeDispatchEvent("active"),this.pending++,h.run().finally(()=>{for(let b=0;b<this.queue.length;b++)if(this.queue[b]===h){this.queue.splice(b,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(h){this.queue.push(h),this.sort!=null&&this.queue.sort(this.sort)}async add(h,b){var w;if((w=b==null?void 0:b.signal)==null||w.throwIfAborted(),this.size===this.maxSize)throw new QueueFullError$1;const v=new Job(h,b);return this.enqueue(v),this.safeDispatchEvent("add"),this.tryToStartAnother(),v.join(b).then(_=>(this.safeDispatchEvent("completed",{detail:_}),this.safeDispatchEvent("success",{detail:{job:v,result:_}}),_)).catch(_=>{if(v.status==="queued"){for(let E=0;E<this.queue.length;E++)if(this.queue[E]===v){this.queue.splice(E,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:v,error:_}}),_})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(h=>{h.abort(new AbortError$5)}),this.clear()}async onEmpty(h){this.size!==0&&await raceEvent(this,"empty",h==null?void 0:h.signal)}async onSizeLessThan(h,b){this.size<h||await raceEvent(this,"next",b==null?void 0:b.signal,{filter:()=>this.size<h})}async onIdle(h){this.pending===0&&this.size===0||await raceEvent(this,"idle",h==null?void 0:h.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(h){var x,T,C;(x=h==null?void 0:h.signal)==null||x.throwIfAborted();const b=pushable({objectMode:!0}),v=O=>{O!=null?this.abort():this.clear(),b.end(O)},w=O=>{O.detail!=null&&b.push(O.detail)},_=O=>{v(O.detail.error)},E=()=>{v()},S=()=>{v(new AbortError$5("Queue aborted"))};this.addEventListener("completed",w),this.addEventListener("failure",_),this.addEventListener("idle",E),(T=h==null?void 0:h.signal)==null||T.addEventListener("abort",S);try{yield*b}finally{this.removeEventListener("completed",w),this.removeEventListener("failure",_),this.removeEventListener("idle",E),(C=h==null?void 0:h.signal)==null||C.removeEventListener("abort",S),v()}}}class PriorityQueue extends Queue{constructor(u={}){super({...u,sort:(h,b)=>h.options.priority>b.options.priority?-1:h.options.priority<b.options.priority?1:0})}}function anySignal(y){const u=new globalThis.AbortController;function h(){u.abort();for(const w of y)(w==null?void 0:w.removeEventListener)!=null&&w.removeEventListener("abort",h)}for(const w of y){if((w==null?void 0:w.aborted)===!0){h();break}(w==null?void 0:w.addEventListener)!=null&&w.addEventListener("abort",h)}function b(){for(const w of y)(w==null?void 0:w.removeEventListener)!=null&&w.removeEventListener("abort",h)}const v=u.signal;return v.clear=b,v}function isLoopbackAddr(y){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(y)||/^::1$/.test(y)}function isLoopback(y){if(!isIpBased(y))return!1;const{address:u}=y.nodeAddress();return isLoopbackAddr(u)}function reliableTransportsFirst(y,u){const h=TCP.exactMatch(y.multiaddr),b=TCP.exactMatch(u.multiaddr);if(h&&!b)return-1;if(!h&&b)return 1;const v=WebSocketsSecure.exactMatch(y.multiaddr),w=WebSocketsSecure.exactMatch(u.multiaddr);if(v&&!w)return-1;if(!v&&w)return 1;const _=WebSockets$1.exactMatch(y.multiaddr),E=WebSockets$1.exactMatch(u.multiaddr);if(_&&!E)return-1;if(!_&&E)return 1;const S=WebRTC.exactMatch(y.multiaddr),x=WebRTC.exactMatch(u.multiaddr);if(S&&!x)return-1;if(!S&&x)return 1;const T=WebRTCDirect.exactMatch(y.multiaddr),C=WebRTCDirect.exactMatch(u.multiaddr);if(T&&!C)return-1;if(!T&&C)return 1;const O=WebTransport.exactMatch(y.multiaddr),D=WebTransport.exactMatch(u.multiaddr);return O&&!D?-1:!O&&D?1:0}function loopbackAddressLast(y,u){const h=isLoopback(y.multiaddr),b=isLoopback(u.multiaddr);return h&&!b?1:!h&&b?-1:0}function publicAddressesFirst(y,u){const h=isPrivate(y.multiaddr),b=isPrivate(u.multiaddr);return h&&!b?1:!h&&b?-1:0}function certifiedAddressesFirst(y,u){return y.isCertified&&!u.isCertified?-1:!y.isCertified&&u.isCertified?1:0}function circuitRelayAddressesLast(y,u){const h=Circuit.exactMatch(y.multiaddr),b=Circuit.exactMatch(u.multiaddr);return h&&!b?1:!h&&b?-1:0}function defaultAddressSorter(y){return y.sort(reliableTransportsFirst).sort(certifiedAddressesFirst).sort(circuitRelayAddressesLast).sort(publicAddressesFirst).sort(loopbackAddressLast)}const defaultOptions$1={maxParallelDials:MAX_PARALLEL_DIALS,maxDialQueueLength:MAX_DIAL_QUEUE_LENGTH,maxPeerAddrsToDial:MAX_PEER_ADDRS_TO_DIAL,dialTimeout:DIAL_TIMEOUT,resolvers:{dnsaddr:dnsaddrResolver}};class DialQueue{constructor(u,h={}){Z(this,"queue");Z(this,"components");Z(this,"addressSorter");Z(this,"maxPeerAddrsToDial");Z(this,"maxDialQueueLength");Z(this,"dialTimeout");Z(this,"shutDownController");Z(this,"connections");Z(this,"log");this.addressSorter=h.addressSorter,this.maxPeerAddrsToDial=h.maxPeerAddrsToDial??defaultOptions$1.maxPeerAddrsToDial,this.maxDialQueueLength=h.maxDialQueueLength??defaultOptions$1.maxDialQueueLength,this.dialTimeout=h.dialTimeout??defaultOptions$1.dialTimeout,this.connections=h.connections??new PeerMap,this.log=u.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=u,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[b,v]of Object.entries(h.resolvers??{}))resolvers.set(b,v);this.queue=new PriorityQueue({concurrency:h.maxParallelDials??defaultOptions$1.maxParallelDials,metricName:"libp2p_dial_queue",metrics:u.metrics}),this.queue.addEventListener("error",b=>{var v;((v=b.detail)==null?void 0:v.name)!==AbortError$5.name&&this.log.error("error in dial queue - %e",b.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(u,h={}){var E,S,x;const{peerId:b,multiaddrs:v}=getPeerAddress(u),w=Array.from(this.connections.values()).flat().find(T=>h.force===!0?!1:T.remotePeer.equals(b)?!0:v.find(C=>C.equals(T.remoteAddr)));if((w==null?void 0:w.status)==="open")return this.log("already connected to %a",w.remoteAddr),(E=h.onProgress)==null||E.call(h,new CustomProgressEvent("dial-queue:already-connected")),w;const _=this.queue.queue.find(T=>{if((b==null?void 0:b.equals(T.options.peerId))===!0)return!0;const C=T.options.multiaddrs;if(C==null)return!1;for(const O of v)if(C.has(O.toString()))return!0;return!1});if(_!=null){this.log("joining existing dial target for %p",b);for(const T of v)_.options.multiaddrs.add(T.toString());return(S=h.onProgress)==null||S.call(h,new CustomProgressEvent("dial-queue:already-in-dial-queue")),_.join(h)}if(this.queue.size>=this.maxDialQueueLength)throw new DialError("Dial queue is full");return this.log("creating dial target for %p",b,v.map(T=>T.toString())),(x=h.onProgress)==null||x.call(h,new CustomProgressEvent("dial-queue:add-to-dial-queue")),this.queue.add(async T=>{var O;(O=T.onProgress)==null||O.call(T,new CustomProgressEvent("dial-queue:start-dial"));const C=anySignal([this.shutDownController.signal,T.signal]);try{return await this.dialPeer(T,C)}finally{C.clear()}},{peerId:b,priority:h.priority??DEFAULT_DIAL_PRIORITY,multiaddrs:new Set(v.map(T=>T.toString())),signal:h.signal??AbortSignal.timeout(this.dialTimeout),onProgress:h.onProgress})}async dialPeer(u,h){var T;const b=u.peerId,v=u.multiaddrs,w=new Set;let _=u.multiaddrs.size===0,E=0,S=0;const x=[];for(this.log("starting dial to %p",b);_||v.size>0;){S++,_=!1;const C=[],O=new Set(u.multiaddrs);v.clear(),this.log("calculating addrs to dial %p from %s",b,[...O]);const D=await this.calculateMultiaddrs(b,O,{...u,signal:h});for(const U of D){if(w.has(U.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",U.multiaddr,b);continue}C.push(U)}this.log("%s dial to %p with %s",S===1?"starting":"continuing",b,C.map(U=>U.multiaddr.toString())),(T=u==null?void 0:u.onProgress)==null||T.call(u,new CustomProgressEvent("dial-queue:calculated-addresses",C));for(const U of C){if(E===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",E,u.peerId),new DialError("Peer had more than maxPeerAddrsToDial");E++;try{const te=await this.components.transportManager.dial(U.multiaddr,{...u,signal:h});this.log("dial to %a succeeded",U.multiaddr);try{await this.components.peerStore.merge(te.remotePeer,{multiaddrs:[te.remoteAddr],metadata:{[LAST_DIAL_SUCCESS_KEY]:fromString(Date.now().toString())}})}catch(X){this.log.error("could not update last dial failure key for %p",b,X)}return te}catch(te){if(this.log.error("dial failed to %a",U.multiaddr,te),w.add(U.multiaddr.toString()),b!=null)try{await this.components.peerStore.merge(b,{metadata:{[LAST_DIAL_FAILURE_KEY]:fromString(Date.now().toString())}})}catch(X){this.log.error("could not update last dial failure key for %p",b,X)}if(h.aborted)throw new TimeoutError$1(te.message);x.push(te)}}}throw x.length===1?x[0]:new AggregateError(x,"All multiaddr dials failed")}async calculateMultiaddrs(u,h=new Set,b={}){var C,O;const v=[...h].map(D=>({multiaddr:multiaddr(D),isCertified:!1}));if(u!=null){if(this.components.peerId.equals(u))throw new DialError("Tried to dial self");if(await((O=(C=this.components.connectionGater).denyDialPeer)==null?void 0:O.call(C,u))===!0)throw new DialDeniedError("The dial request is blocked by gater.allowDialPeer");if(v.length===0){this.log("loading multiaddrs for %p",u);try{const D=await this.components.peerStore.get(u);v.push(...D.addresses),this.log("loaded multiaddrs for %p",u,v.map(({multiaddr:U})=>U.toString()))}catch(D){if(D.name!=="NotFoundError")throw D}}if(v.length===0){this.log("looking up multiaddrs for %p in the peer routing",u);try{const D=await this.components.peerRouting.findPeer(u,b);this.log("found multiaddrs for %p in the peer routing",u,v.map(({multiaddr:U})=>U.toString())),v.push(...D.multiaddrs.map(U=>({multiaddr:U,isCertified:!1})))}catch(D){D.name==="NoPeerRoutersError"?this.log("no peer routers configured",u):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",u,D)}}}let w=(await Promise.all(v.map(async D=>{const U=await resolveMultiaddrs(D.multiaddr,{dns:this.components.dns,...b,log:this.log});return U.length===1&&U[0].equals(D.multiaddr)?D:U.map(te=>({multiaddr:te,isCertified:!1}))}))).flat();if(u!=null){const D=`/p2p/${u.toString()}`;w=w.map(U=>{const te=U.multiaddr.getComponents().pop();return(te==null?void 0:te.name)!=="p2p"?{multiaddr:U.multiaddr.encapsulate(D),isCertified:U.isCertified}:U})}const _=w.filter(D=>{if(this.components.transportManager.dialTransportForMultiaddr(D.multiaddr)==null)return!1;const U=D.multiaddr.getPeerId();return u!=null&&U!=null?u.equals(U):!0}),E=new Map;for(const D of _){const U=D.multiaddr.toString(),te=E.get(U);if(te!=null){te.isCertified=te.isCertified||D.isCertified||!1;continue}E.set(U,D)}const S=[...E.values()];if(S.length===0)throw new NoValidAddressesError("The dial request has no valid addresses");const x=[];for(const D of S)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(D.multiaddr)||x.push(D);const T=this.addressSorter==null?defaultAddressSorter(x):x.sort(this.addressSorter);if(T.length===0)throw new DialDeniedError("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",u??"unknown peer",w.map(({multiaddr:D})=>D.toString())),this.log.trace("addresses for %p after filtering",u??"unknown peer",T.map(({multiaddr:D})=>D.toString())),T}async isDialable(u,h={}){Array.isArray(u)||(u=[u]);try{const b=await this.calculateMultiaddrs(void 0,new Set(u.map(v=>v.toString())),h);return h.runOnLimitedConnection===!1?b.find(v=>!Circuit.matches(v.multiaddr))!=null:!0}catch(b){this.log.trace("error calculating if multiaddr(s) were dialable",b)}return!1}}class PeerQueue extends Queue{has(u){return this.find(u)!=null}find(u){return this.queue.find(h=>u.equals(h.options.peerId))}}var retry$2={};function RetryOperation(y,u){typeof u=="boolean"&&(u={forever:u}),this._originalTimeouts=JSON.parse(JSON.stringify(y)),this._timeouts=y,this._options=u||{},this._maxRetryTime=u&&u.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var retry_operation=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(y){if(this._timeout&&clearTimeout(this._timeout),!y)return!1;var u=new Date().getTime();if(y&&u-this._operationStart>=this._maxRetryTime)return this._errors.push(y),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(y);var h=this._timeouts.shift();if(h===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),h=this._cachedTimeouts.slice(-1);else return!1;var b=this;return this._timer=setTimeout(function(){b._attempts++,b._operationTimeoutCb&&(b._timeout=setTimeout(function(){b._operationTimeoutCb(b._attempts)},b._operationTimeout),b._options.unref&&b._timeout.unref()),b._fn(b._attempts)},h),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(y,u){this._fn=y,u&&(u.timeout&&(this._operationTimeout=u.timeout),u.cb&&(this._operationTimeoutCb=u.cb));var h=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){h._operationTimeoutCb()},h._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(y){console.log("Using RetryOperation.try() is deprecated"),this.attempt(y)};RetryOperation.prototype.start=function(y){console.log("Using RetryOperation.start() is deprecated"),this.attempt(y)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var y={},u=null,h=0,b=0;b<this._errors.length;b++){var v=this._errors[b],w=v.message,_=(y[w]||0)+1;y[w]=_,_>=h&&(u=v,h=_)}return u};(function(y){var u=retry_operation;y.operation=function(h){var b=y.timeouts(h);return new u(b,{forever:h&&(h.forever||h.retries===1/0),unref:h&&h.unref,maxRetryTime:h&&h.maxRetryTime})},y.timeouts=function(h){if(h instanceof Array)return[].concat(h);var b={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var v in h)b[v]=h[v];if(b.minTimeout>b.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var w=[],_=0;_<b.retries;_++)w.push(this.createTimeout(_,b));return h&&h.forever&&!w.length&&w.push(this.createTimeout(_,b)),w.sort(function(E,S){return E-S}),w},y.createTimeout=function(h,b){var v=b.randomize?Math.random()+1:1,w=Math.round(v*Math.max(b.minTimeout,1)*Math.pow(b.factor,h));return w=Math.min(w,b.maxTimeout),w},y.wrap=function(h,b,v){if(b instanceof Array&&(v=b,b=null),!v){v=[];for(var w in h)typeof h[w]=="function"&&v.push(w)}for(var _=0;_<v.length;_++){var E=v[_],S=h[E];h[E]=(function(T){var C=y.operation(b),O=Array.prototype.slice.call(arguments,1),D=O.pop();O.push(function(U){C.retry(U)||(U&&(arguments[0]=C.mainError()),D.apply(this,arguments))}),C.attempt(function(){T.apply(h,O)})}).bind(h,S),h[E].options=b}}})(retry$2);var retry=retry$2;const retry$1=getDefaultExportFromCjs$1(retry),objectToString$1=Object.prototype.toString,isError$1=y=>objectToString$1.call(y)==="[object Error]",errorMessages=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function isNetworkError(y){if(!(y&&isError$1(y)&&y.name==="TypeError"&&typeof y.message=="string"))return!1;const{message:h,stack:b}=y;return h==="Load failed"?b===void 0||"__sentry_captured__"in y:h.startsWith("error sending request for url")?!0:errorMessages.has(h)}class AbortError extends Error{constructor(u){super(),u instanceof Error?(this.originalError=u,{message:u}=u):(this.originalError=new Error(u),this.originalError.stack=this.stack),this.name="AbortError",this.message=u}}const decorateErrorWithCounts=(y,u,h)=>{const b=h.retries-(u-1);return y.attemptNumber=u,y.retriesLeft=b,y};async function pRetry(y,u){return new Promise((h,b)=>{u={...u},u.onFailedAttempt??(u.onFailedAttempt=()=>{}),u.shouldRetry??(u.shouldRetry=()=>!0),u.retries??(u.retries=10);const v=retry$1.operation(u),w=()=>{var E;v.stop(),b((E=u.signal)==null?void 0:E.reason)};u.signal&&!u.signal.aborted&&u.signal.addEventListener("abort",w,{once:!0});const _=()=>{var E;(E=u.signal)==null||E.removeEventListener("abort",w),v.stop()};v.attempt(async E=>{try{const S=await y(E);_(),h(S)}catch(S){try{if(!(S instanceof Error))throw new TypeError(`Non-error was thrown: "${S}". You should only throw errors.`);if(S instanceof AbortError)throw S.originalError;if(S instanceof TypeError&&!isNetworkError(S))throw S;if(decorateErrorWithCounts(S,E,u),await u.shouldRetry(S)||(v.stop(),b(S)),await u.onFailedAttempt(S),!v.retry(S))throw v.mainError()}catch(x){decorateErrorWithCounts(x,E,u),_(),b(x)}}})})}class ReconnectQueue{constructor(u,h={}){Z(this,"log");Z(this,"queue");Z(this,"started");Z(this,"peerStore");Z(this,"retries");Z(this,"retryInterval");Z(this,"backoffFactor");Z(this,"connectionManager");Z(this,"events");this.log=u.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=u.peerStore,this.connectionManager=u.connectionManager,this.queue=new PeerQueue({concurrency:h.maxParallelReconnects??MAX_PARALLEL_RECONNECTS,metricName:"libp2p_reconnect_queue",metrics:u.metrics}),this.started=!1,this.retries=h.retries??5,this.backoffFactor=h.backoffFactor,this.retryInterval=h.retryInterval,this.events=u.events,u.events.addEventListener("peer:disconnect",b=>{this.maybeReconnect(b.detail).catch(v=>{this.log.error("failed to maybe reconnect to %p - %e",b.detail,v)})})}async maybeReconnect(u){if(!this.started)return;const h=await this.peerStore.get(u);hasKeepAliveTag(h)&&(this.queue.has(u)||this.queue.add(async b=>{await pRetry(async v=>{if(this.started)try{await this.connectionManager.openConnection(u,{signal:b==null?void 0:b.signal})}catch(w){throw this.log("reconnecting to %p attempt %d of %d failed - %e",u,v,this.retries,w),w}},{signal:b==null?void 0:b.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:u}).catch(async b=>{this.log.error("failed to reconnect to %p - %e",u,b);const v={};[...h.tags.keys()].forEach(w=>{w.startsWith(KEEP_ALIVE)&&(v[w]=void 0)}),await this.peerStore.merge(u,{tags:v}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:u})}).catch(async b=>{this.log.error("failed to remove keep-alive tag from %p - %e",u,b)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{const u=await this.peerStore.all({filters:[h=>hasKeepAliveTag(h)]});await Promise.all(u.map(async h=>{await this.connectionManager.openConnection(h.id).catch(b=>{this.log.error(b)})}))}).catch(u=>{this.log.error(u)})}stop(){this.started=!1,this.queue.abort()}}function hasKeepAliveTag(y){for(const u of y.tags.keys())if(u.startsWith(KEEP_ALIVE))return!0;return!1}const DEFAULT_DIAL_PRIORITY=50,defaultOptions={maxConnections:MAX_CONNECTIONS,inboundConnectionThreshold:INBOUND_CONNECTION_THRESHOLD,maxIncomingPendingConnections:MAX_INCOMING_PENDING_CONNECTIONS};var _h;_h=Symbol.toStringTag;class DefaultConnectionManager{constructor(u,h={}){Z(this,"started");Z(this,"connections");Z(this,"allow");Z(this,"deny");Z(this,"maxIncomingPendingConnections");Z(this,"incomingPendingConnections");Z(this,"outboundPendingConnections");Z(this,"maxConnections");Z(this,"dialQueue");Z(this,"reconnectQueue");Z(this,"connectionPruner");Z(this,"inboundConnectionRateLimiter");Z(this,"peerStore");Z(this,"metrics");Z(this,"events");Z(this,"log");Z(this,"peerId");Z(this,_h,"@libp2p/connection-manager");var b;if(this.maxConnections=h.maxConnections??defaultOptions.maxConnections,this.maxConnections<1)throw new InvalidParametersError$2("Connection Manager maxConnections must be greater than 0");this.connections=new PeerMap,this.started=!1,this.peerId=u.peerId,this.peerStore=u.peerStore,this.metrics=u.metrics,this.events=u.events,this.log=u.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(h.allow??[]).map(v=>multiaddrToIpNet(v)),this.deny=(h.deny??[]).map(v=>multiaddrToIpNet(v)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=h.maxIncomingPendingConnections??defaultOptions.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new RateLimiter({points:h.inboundConnectionThreshold??defaultOptions.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ConnectionPruner({connectionManager:this,peerStore:u.peerStore,events:u.events,logger:u.logger},{allow:(b=h.allow)==null?void 0:b.map(v=>multiaddr(v))}),this.dialQueue=new DialQueue(u,{addressSorter:h.addressSorter,maxParallelDials:h.maxParallelDials??MAX_PARALLEL_DIALS,maxDialQueueLength:h.maxDialQueueLength??MAX_DIAL_QUEUE_LENGTH,maxPeerAddrsToDial:h.maxPeerAddrsToDial??MAX_PEER_ADDRS_TO_DIAL,dialTimeout:h.dialTimeout??DIAL_TIMEOUT,resolvers:h.resolvers??{dnsaddr:dnsaddrResolver},connections:this.connections}),this.reconnectQueue=new ReconnectQueue({events:u.events,peerStore:u.peerStore,logger:u.logger,connectionManager:this},{retries:h.reconnectRetries,retryInterval:h.reconnectRetryInterval,backoffFactor:h.reconnectBackoffFactor,maxParallelReconnects:h.maxParallelReconnects})}async start(){var u,h,b;(u=this.metrics)==null||u.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const v={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const w of this.connections.values())for(const _ of w)v[_.direction]++;return v}}),(h=this.metrics)==null||h.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const v={};for(const w of this.connections.values())for(const _ of w)for(const E of _.streams){const S=`${E.direction} ${E.protocol??"unnegotiated"}`;v[S]=(v[S]??0)+1}return v}}),(b=this.metrics)==null||b.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const v={};for(const _ of this.connections.values())for(const E of _){const S={};for(const x of E.streams){const T=`${x.direction} ${x.protocol??"unnegotiated"}`;S[T]=(S[T]??0)+1}for(const[x,T]of Object.entries(S))v[x]=v[x]??[],v[x].push(T)}const w={};for(let[_,E]of Object.entries(v)){E=E.sort((x,T)=>x-T);const S=Math.floor(E.length*.9);w[_]=E[S]}return w}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await start(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await stop(this.reconnectQueue,this.dialQueue,this.connectionPruner);const u=[];for(const h of this.connections.values())for(const b of h)u.push((async()=>{try{await b.close()}catch(v){this.log.error(v)}})());this.log("closing %d connections",u.length),await Promise.all(u),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(u){if(this.maxConnections<1)throw new InvalidParametersError$2("Connection Manager maxConnections must be greater than 0");let h=!1;u<this.maxConnections&&(h=!0),this.maxConnections=u,h&&this.connectionPruner.maybePruneConnections()}onConnect(u){this._onConnect(u).catch(h=>{this.log.error(h)})}async _onConnect(u){const{detail:h}=u;if(!this.started){await h.close();return}if(h.status!=="open")return;const b=h.remotePeer,v=!this.connections.has(b),w=this.connections.get(b)??[];w.push(h),this.connections.set(b,w),b.publicKey!=null&&b.type==="RSA"&&await this.peerStore.patch(b,{publicKey:b.publicKey}),v&&this.events.safeDispatchEvent("peer:connect",{detail:h.remotePeer})}onDisconnect(u){const{detail:h}=u,b=h.remotePeer,w=(this.connections.get(b)??[]).filter(_=>_.id!==h.id);this.connections.set(b,w),w.length===0&&(this.log("onDisconnect remove all connections for peer %p",b),this.connections.delete(b),this.events.safeDispatchEvent("peer:disconnect",{detail:h.remotePeer}))}getConnections(u){if(u!=null)return this.connections.get(u)??[];let h=[];for(const b of this.connections.values())h=h.concat(b);return h}getConnectionsMap(){return this.connections}async openConnection(u,h={}){var b,v;if(!this.started)throw new NotStartedError("Not started");this.outboundPendingConnections++;try{(b=h.signal)==null||b.throwIfAborted();const{peerId:w}=getPeerAddress(u);if(this.peerId.equals(w))throw new InvalidPeerIdError("Can not dial self");if(w!=null&&h.force!==!0){this.log("dial %p",w);const x=this.getConnections(w).find(T=>T.limits==null);if(x!=null)return this.log("had an existing non-limited connection to %p",w),(v=h.onProgress)==null||v.call(h,new CustomProgressEvent("dial-queue:already-connected")),x}const _=await this.dialQueue.dial(u,{...h,priority:h.priority??DEFAULT_DIAL_PRIORITY});if(_.status!=="open")throw new ConnectionClosedError("Remote closed connection during opening");let E=this.connections.get(_.remotePeer);E==null&&(E=[],this.connections.set(_.remotePeer,E));let S=!1;for(const x of E)if(x.id===_.id&&(S=!0),h.force!==!0&&x.id!==_.id&&x.remoteAddr.equals(_.remoteAddr))return _.abort(new InvalidMultiaddrError$1("Duplicate multiaddr connection")),x;return S||E.push(_),_}finally{this.outboundPendingConnections--}}async closeConnections(u,h={}){const b=this.connections.get(u)??[];await Promise.all(b.map(async v=>{try{await v.close(h)}catch(w){v.abort(w)}}))}async acceptIncomingConnection(u){if(this.deny.some(v=>v.contains(u.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",u.remoteAddr),!1;if(this.allow.some(v=>v.contains(u.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",u.remoteAddr),!1;if(u.remoteAddr.isThinWaistAddress()){const v=u.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(v,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",u.remoteAddr,v),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",u.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const u={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(h=>({id:h.id,status:u[h.status],peerId:h.options.peerId,multiaddrs:[...h.options.multiaddrs].map(b=>multiaddr(b))}))}async isDialable(u,h={}){return this.dialQueue.isDialable(u,h)}}class MovingAverage{constructor(u){Z(this,"movingAverage");Z(this,"variance");Z(this,"deviation");Z(this,"forecast");Z(this,"timeSpan");Z(this,"previousTime");this.timeSpan=u,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(u,h){return 1-Math.exp(-(u-h)/this.timeSpan)}push(u,h=Date.now()){if(this.previousTime!=null){const b=this.alpha(h,this.previousTime),v=u-this.movingAverage,w=b*v;this.movingAverage=b*u+(1-b)*this.movingAverage,this.variance=(1-b)*(this.variance+v*w),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+b*v}else this.movingAverage=u;this.previousTime=h}}const DEFAULT_TIMEOUT_MULTIPLIER=1.2,DEFAULT_FAILURE_MULTIPLIER=2,DEFAULT_MIN_TIMEOUT=5e3,DEFAULT_MAX_TIMEOUT=6e4,DEFAULT_INTERVAL=5e3;class AdaptiveTimeout{constructor(u={}){Z(this,"success");Z(this,"failure");Z(this,"next");Z(this,"metric");Z(this,"timeoutMultiplier");Z(this,"failureMultiplier");Z(this,"minTimeout");Z(this,"maxTimeout");var b;const h=u.interval??DEFAULT_INTERVAL;this.success=new MovingAverage(h),this.failure=new MovingAverage(h),this.next=new MovingAverage(h),this.failureMultiplier=u.failureMultiplier??DEFAULT_FAILURE_MULTIPLIER,this.timeoutMultiplier=u.timeoutMultiplier??DEFAULT_TIMEOUT_MULTIPLIER,this.minTimeout=u.minTimeout??DEFAULT_MIN_TIMEOUT,this.maxTimeout=u.maxTimeout??DEFAULT_MAX_TIMEOUT,u.metricName!=null&&(this.metric=(b=u.metrics)==null?void 0:b.registerMetricGroup(u.metricName))}getTimeoutSignal(u={}){let h=Math.round(this.next.movingAverage*(u.timeoutFactor??this.timeoutMultiplier));h<this.minTimeout&&(h=this.minTimeout),h>this.maxTimeout&&(h=this.maxTimeout);const b=AbortSignal.timeout(h),v=anySignal([u.signal,b]);return v.start=Date.now(),v.timeout=h,v}cleanUp(u){var b,v;const h=Date.now()-u.start;u.aborted?(this.failure.push(h),this.next.push(h*this.failureMultiplier),(b=this.metric)==null||b.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:h})):(this.success.push(h),this.next.push(h),(v=this.metric)==null||v.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:h}))}}const DEFAULT_PING_INTERVAL_MS=1e4,PROTOCOL_VERSION="1.0.0",PROTOCOL_NAME="ping",PROTOCOL_PREFIX="ipfs",PING_LENGTH=32,DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE=!0;var Eh,Sh;Sh=Symbol.toStringTag,Eh=serviceCapabilities;class ConnectionMonitor{constructor(u,h={}){Z(this,"protocol");Z(this,"components");Z(this,"log");Z(this,"heartbeatInterval");Z(this,"pingIntervalMs");Z(this,"abortController");Z(this,"timeout");Z(this,"abortConnectionOnPingFailure");Z(this,Sh,"@libp2p/connection-monitor");Z(this,Eh,["@libp2p/connection-monitor"]);this.components=u,this.protocol=`/${h.protocolPrefix??PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`,this.log=u.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=h.pingInterval??DEFAULT_PING_INTERVAL_MS,this.abortConnectionOnPingFailure=h.abortConnectionOnPingFailure??DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE,this.timeout=new AdaptiveTimeout({...h.pingTimeout??{},metrics:u.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(u=>{Promise.resolve().then(async()=>{var b;let h=Date.now();try{const v=this.timeout.getTimeoutSignal({signal:(b=this.abortController)==null?void 0:b.signal}),w=await u.newStream(this.protocol,{signal:v,runOnLimitedConnection:!0}),_=byteStream(w);h=Date.now(),await Promise.all([_.write(randomBytes$3(PING_LENGTH),{signal:v}),_.read({bytes:PING_LENGTH,signal:v})]),u.rtt=Date.now()-h,await _.unwrap().close({signal:v})}catch(v){if(v.name!=="UnsupportedProtocolError")throw v;u.rtt=(Date.now()-h)/2}}).catch(h=>{this.log.error("error during heartbeat",h),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),u.abort(h)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){var u;(u=this.abortController)==null||u.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}}var $h;$h=Symbol.toStringTag;class CompoundContentRouting{constructor(u,h){Z(this,"routers");Z(this,"started");Z(this,"components");Z(this,$h,"@libp2p/content-routing");var b,v,w,_,E;this.routers=h.routers??[],this.started=!1,this.components=u,this.findProviders=((b=u.metrics)==null?void 0:b.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([S],x)=>({...x,cid:S.toString()}),getAttributesFromYieldedValue:(S,x)=>({...x,providers:[...Array.isArray(x.providers)?x.providers:[],S.id.toString()]})}))??this.findProviders,this.provide=((v=u.metrics)==null?void 0:v.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([S],x)=>({...x,cid:S.toString()})}))??this.provide,this.cancelReprovide=((w=u.metrics)==null?void 0:w.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([S],x)=>({...x,cid:S.toString()})}))??this.cancelReprovide,this.put=((_=u.metrics)==null?void 0:_.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([S])=>({key:toString$1(S,"base36")})}))??this.put,this.get=((E=u.metrics)==null?void 0:E.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([S])=>({key:toString$1(S,"base36")})}))??this.get}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(u,h={}){if(this.routers.length===0)throw new NoContentRoutersError("No content routers available");const b=this,v=new PeerSet;for await(const w of merge$1(...b.routers.filter(_=>_.findProviders instanceof Function).map(_=>_.findProviders(u,h))))w!=null&&(w.multiaddrs.length>0&&await this.components.peerStore.merge(w.id,{multiaddrs:w.multiaddrs},h),!v.has(w.id)&&(v.add(w.id),yield w))}async provide(u,h={}){if(this.routers.length===0)throw new NoContentRoutersError("No content routers available");await Promise.all(this.routers.filter(b=>b.provide instanceof Function).map(async b=>{await b.provide(u,h)}))}async cancelReprovide(u,h={}){if(this.routers.length===0)throw new NoContentRoutersError("No content routers available");await Promise.all(this.routers.filter(b=>b.cancelReprovide instanceof Function).map(async b=>{await b.cancelReprovide(u,h)}))}async put(u,h,b){if(!this.isStarted())throw new NotStartedError;await Promise.all(this.routers.filter(v=>v.put instanceof Function).map(async v=>{await v.put(u,h,b)}))}async get(u,h){if(!this.isStarted())throw new NotStartedError;return Promise.any(this.routers.filter(b=>b.get instanceof Function).map(async b=>b.get(u,h)))}}var xh;xh=Symbol.toStringTag;class DefaultPeerRouting{constructor(u,h={}){Z(this,"log");Z(this,"peerId");Z(this,"peerStore");Z(this,"routers");Z(this,xh,"@libp2p/peer-routing");var b,v;this.log=u.logger.forComponent("libp2p:peer-routing"),this.peerId=u.peerId,this.peerStore=u.peerStore,this.routers=h.routers??[],this.findPeer=((b=u.metrics)==null?void 0:b.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([w],_)=>({..._,peer:w.toString()})}))??this.findPeer,this.getClosestPeers=((v=u.metrics)==null?void 0:v.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([w],_)=>({..._,key:toString$1(w,"base36")}),getAttributesFromYieldedValue:(w,_)=>({..._,peers:[...Array.isArray(_.peers)?_.peers:[],w.id.toString()]})}))??this.getClosestPeers}async findPeer(u,h){if(this.routers.length===0)throw new NoPeerRoutersError("No peer routers available");if(u.toString()===this.peerId.toString())throw new QueriedForSelfError("Should not try to find self");const b=this,v=merge$1(...this.routers.filter(w=>w.findPeer instanceof Function).map(w=>async function*(){try{yield await w.findPeer(u,h)}catch(_){b.log.error(_)}}()));for await(const w of v)if(w!=null)return w.multiaddrs.length>0&&await this.peerStore.merge(w.id,{multiaddrs:w.multiaddrs},h),w;throw new NotFoundError$1}async*getClosestPeers(u,h={}){if(this.routers.length===0)throw new NoPeerRoutersError("No peer routers available");const b=this,v=createScalableCuckooFilter(1024);for await(const w of parallel(async function*(){const _=merge$1(...b.routers.filter(E=>E.getClosestPeers instanceof Function).map(E=>E.getClosestPeers(u,h)));for await(let E of _)yield async()=>{if(E.multiaddrs.length===0)try{E=await b.findPeer(E.id,{...h,useCache:!1})}catch(S){b.log.error("could not find peer multiaddrs",S);return}return E}}()))w!=null&&(w.multiaddrs.length>0&&await this.peerStore.merge(w.id,{multiaddrs:w.multiaddrs},h),!v.has(w.id.toMultihash().bytes)&&(v.add(w.id.toMultihash().bytes),yield w))}}var Ah,Th;class RandomWalk extends(Th=TypedEventEmitter,Ah=Symbol.toStringTag,Th){constructor(h){super();Z(this,"peerRouting");Z(this,"log");Z(this,"walking");Z(this,"walkers");Z(this,"shutdownController");Z(this,"walkController");Z(this,"needNext");Z(this,Ah,"@libp2p/random-walk");this.log=h.logger.forComponent("libp2p:random-walk"),this.peerRouting=h.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(h){var v,w;this.walking||this.startWalk(),this.walkers++;const b=anySignal([this.shutdownController.signal,h==null?void 0:h.signal]);try{for(;;)(v=this.needNext)==null||v.resolve(),this.needNext=pDefer(),yield(await raceEvent(this,"walk:peer",b,{errorEvent:"walk:error"})).detail}finally{b.clear(),this.walkers--,this.walkers===0&&((w=this.walkController)==null||w.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const h=anySignal([this.walkController.signal,this.shutdownController.signal]),b=Date.now();let v=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{const w=randomBytes$3(32);let _=Date.now();for await(const E of this.peerRouting.getClosestPeers(w,{signal:h}))h.aborted&&this.log("aborting walk"),h.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",E.id,Date.now()-_,this.walkers),v++,this.safeDispatchEvent("walk:peer",{detail:E}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await raceSignal(this.needNext.promise,h)),_=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",w,this.walkers,v)}catch(w){this.log.error("random walk errored",w),this.safeDispatchEvent("walk:error",{detail:w})}this.log("no walkers left, ended walk")}).catch(w=>{this.log.error("random walk errored",w)}).finally(()=>{this.log("finished walk, found %d peers after %dms",v,Date.now()-b),this.walking=!1})}}const DEFAULT_MAX_INBOUND_STREAMS=32,DEFAULT_MAX_OUTBOUND_STREAMS=64;var Ih;Ih=Symbol.toStringTag;class Registrar{constructor(u){Z(this,"log");Z(this,"topologies");Z(this,"handlers");Z(this,"components");Z(this,Ih,"@libp2p/registrar");var h;this.components=u,this.log=u.logger.forComponent("libp2p:registrar"),this.topologies=new Map,(h=u.metrics)==null||h.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const b={};for(const[v,w]of this.topologies)b[v]=w.size;return b}}),this.handlers=trackedMap({name:"libp2p_registrar_protocol_handlers",metrics:u.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(u){const h=this.handlers.get(u);if(h==null)throw new UnhandledProtocolError(`No handler registered for protocol ${u}`);return h}getTopologies(u){const h=this.topologies.get(u);return h==null?[]:[...h.values()]}async handle(u,h,b){if(this.handlers.has(u)&&(b==null?void 0:b.force)!==!0)throw new DuplicateProtocolHandlerError(`Handler already registered for protocol ${u}`);const v=mergeOptions.bind({ignoreUndefined:!0})({maxInboundStreams:DEFAULT_MAX_INBOUND_STREAMS,maxOutboundStreams:DEFAULT_MAX_OUTBOUND_STREAMS},b);this.handlers.set(u,{handler:h,options:v}),await this.components.peerStore.merge(this.components.peerId,{protocols:[u]},b)}async unhandle(u,h){(Array.isArray(u)?u:[u]).forEach(v=>{this.handlers.delete(v)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},h)}async register(u,h){if(h==null)throw new InvalidParametersError$2("invalid topology");const b=`${(Math.random()*1e9).toString(36)}${Date.now()}`;let v=this.topologies.get(u);return v==null&&(v=new Map,this.topologies.set(u,v)),v.set(b,h),b}unregister(u){for(const[h,b]of this.topologies.entries())b.has(u)&&(b.delete(u),b.size===0&&this.topologies.delete(h))}_onDisconnect(u){const h=u.detail,b={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(h,b).then(v=>{var w,_,E;for(const S of v.protocols){const x=this.topologies.get(S);if(x!=null)for(const T of x.values())((w=T.filter)==null?void 0:w.has(h))!==!1&&((_=T.filter)==null||_.remove(h),(E=T.onDisconnect)==null||E.call(T,h))}}).catch(v=>{v.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",h,v)})}_onPeerUpdate(u){var w,_,E;const{peer:h,previous:b}=u.detail,v=((b==null?void 0:b.protocols)??[]).filter(S=>!h.protocols.includes(S));for(const S of v){const x=this.topologies.get(S);if(x!=null)for(const T of x.values())((w=T.filter)==null?void 0:w.has(h.id))!==!1&&((_=T.filter)==null||_.remove(h.id),(E=T.onDisconnect)==null||E.call(T,h.id))}}_onPeerIdentify(u){var w,_,E;const h=u.detail.protocols,b=u.detail.connection,v=u.detail.peerId;for(const S of h){const x=this.topologies.get(S);if(x!=null)for(const T of x.values())b.limits!=null&&T.notifyOnLimitedConnection!==!0||((w=T.filter)==null?void 0:w.has(v))!==!0&&((_=T.filter)==null||_.add(v),(E=T.onConnect)==null||E.call(T,v,b))}}}var Ph;Ph=Symbol.toStringTag;class DefaultTransportManager{constructor(u,h={}){Z(this,"log");Z(this,"components");Z(this,"transports");Z(this,"listeners");Z(this,"faultTolerance");Z(this,"started");Z(this,Ph,"@libp2p/transport-manager");this.log=u.logger.forComponent("libp2p:transports"),this.components=u,this.started=!1,this.transports=trackedMap({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=trackedMap({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=h.faultTolerance??FaultTolerance.FATAL_ALL}add(u){const h=u[Symbol.toStringTag];if(h==null)throw new InvalidParametersError$2("Transport must have a valid tag");if(this.transports.has(h))throw new InvalidParametersError$2(`There is already a transport with the tag ${h}`);this.log("adding transport %s",h),this.transports.set(h,u),this.listeners.has(h)||this.listeners.set(h,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const u=this.components.addressManager.getListenAddrs();await this.listen(u)}async stop(){const u=[];for(const[h,b]of this.listeners)for(this.log("closing listeners for %s",h);b.length>0;){const v=b.pop();v!=null&&u.push(v.close())}await Promise.all(u),this.log("all listeners closed");for(const h of this.listeners.keys())this.listeners.set(h,[]);this.started=!1}async dial(u,h){var v;const b=this.dialTransportForMultiaddr(u);if(b==null)throw new TransportUnavailableError(`No transport available for address ${String(u)}`);return(v=h==null?void 0:h.onProgress)==null||v.call(h,new CustomProgressEvent("transport-manager:selected-transport",b[Symbol.toStringTag])),b.dial(u,{...h,upgrader:this.components.upgrader})}getAddrs(){let u=[];for(const h of this.listeners.values())for(const b of h)u=[...u,...b.getAddrs()];return u}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(u){for(const h of this.transports.values())if(h.dialFilter([u]).length>0)return h}listenTransportForMultiaddr(u){for(const h of this.transports.values())if(h.listenFilter([u]).length>0)return h}async listen(u){if(!this.isStarted())throw new NotStartedError("Not started");if(u==null||u.length===0){this.log("no addresses were provided for listening, this node is dial only");return}const h={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};u.forEach(w=>{h.errors.set(w.toString(),new UnsupportedListenAddressError)});const b=[];for(const[w,_]of this.transports.entries()){const E=_.listenFilter(u);for(const S of E){this.log("creating listener for %s on %a",w,S);const x=_.createListener({upgrader:this.components.upgrader});let T=this.listeners.get(w)??[];T==null&&(T=[],this.listeners.set(w,T)),T.push(x),x.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:x})}),x.addEventListener("close",()=>{const C=T.findIndex(O=>O===x);T.splice(C,1),this.components.events.safeDispatchEvent("transport:close",{detail:x})}),IP4.matches(S)?h.ipv4.attempts++:IP6.matches(S)&&h.ipv6.attempts++,b.push(x.listen(S).then(()=>{h.errors.delete(S.toString()),IP4.matches(S)&&h.ipv4.success++,IP6.matches(S)&&h.ipv6.success++},C=>{throw this.log.error("transport %s could not listen on address %a - %e",w,S,C),h.errors.set(S.toString(),C),C}))}}const v=await Promise.allSettled(b);if(!(v.length>0&&v.every(w=>w.status==="fulfilled"))){if(this.ipv6Unsupported(h)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===FaultTolerance.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new UnsupportedListenAddressesError(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
12
+ ${[...h.errors.entries()].map(([w,_])=>`
13
+ ${w}: ${`${_.stack??_}`.split(`
14
+ `).join(`
15
+ `)}
16
+ `).join("")}`)}}ipv6Unsupported(u){if(u.ipv4.attempts===0||u.ipv6.attempts===0)return!1;const h=u.ipv4.attempts===u.ipv4.success,b=u.ipv6.success===0;return h&&b}async remove(u){const h=this.listeners.get(u)??[];this.log.trace("removing transport %s",u);const b=[];for(this.log.trace("closing listeners for %s",u);h.length>0;){const v=h.pop();v!=null&&b.push(v.close())}await Promise.all(b),this.transports.delete(u),this.listeners.delete(u)}async removeAll(){const u=[];for(const h of this.transports.keys())u.push(this.remove(h));await Promise.all(u)}}const PROTOCOL_ID="/multistream/1.0.0",MAX_PROTOCOL_LENGTH=1024,NewLine=fromString(`
17
+ `);async function write(y,u,h){await y.write(u,h)}async function writeAll(y,u,h){await y.writeV(u,h)}async function read(y,u){const h=await y.read(u);if(h.byteLength===0||h.get(h.byteLength-1)!==NewLine[0])throw u.log.error("Invalid mss message - missing newline",h),new InvalidMessageError("Missing newline");return h.sublist(0,-1)}async function readString(y,u){const h=await read(y,u);return toString$1(h.subarray())}async function select(y,u,h){if(u=Array.isArray(u)?[...u]:[u],u.length===1&&h.negotiateFully===!1)return optimisticSelect(y,u[0],h);const b=lpStream(y,{...h,maxDataLength:MAX_PROTOCOL_LENGTH}),v=u.shift();if(v==null)throw new Error("At least one protocol must be specified");h.log.trace('select: write ["%s", "%s"]',PROTOCOL_ID,v);const w=fromString(`${PROTOCOL_ID}
18
+ `),_=fromString(`${v}
19
+ `);await writeAll(b,[w,_],h),h.log.trace("select: reading multistream-select header");let E=await readString(b,h);if(h.log.trace('select: read "%s"',E),E===PROTOCOL_ID&&(h.log.trace("select: reading protocol response"),E=await readString(b,h),h.log.trace('select: read "%s"',E)),E===v)return{stream:b.unwrap(),protocol:v};for(const S of u){h.log.trace('select: write "%s"',S),await write(b,fromString(`${S}
20
+ `),h),h.log.trace("select: reading protocol response");const x=await readString(b,h);if(h.log.trace('select: read "%s" for "%s"',x,S),x===S)return{stream:b.unwrap(),protocol:S}}throw new UnsupportedProtocolError("protocol selection failed")}function optimisticSelect(y,u,h){const b=y.sink.bind(y),v=y.source;let w=!1,_=!1;const E=pDefer();let S=!1,x=!1;const T=pDefer();let C=!1,O=!1;const D=pDefer(),U=lpStream({sink:b,source:v},{...h,maxDataLength:MAX_PROTOCOL_LENGTH});y.sink=async ee=>{const{sink:ae}=U.unwrap();await ae(async function*(){let de=!1;for await(const Se of ee){if(x&&await T.promise,S)yield Se;else{x=!0,h.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',PROTOCOL_ID,u,Se.byteLength);const ve=`${u}
21
+ `;yield new Uint8ArrayList(Uint8Array.from([19]),fromString(`${PROTOCOL_ID}
22
+ `),encode$8(ve.length),fromString(ve),Se).subarray(),h.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',PROTOCOL_ID,u,Se.byteLength),S=!0,x=!1,T.resolve(),te().catch(Pe=>{h.log.error("could not finish optimistic protocol negotiation of %s",u,Pe)})}de=!0}de||await te()}())};async function te(){if(_){h.log.trace("optimistic: already negotiating %s stream",u),await E.promise;return}_=!0;try{S||(h.log.trace("optimistic: doing send protocol for %s stream",u),await X()),C||(h.log.trace("optimistic: doing read protocol for %s stream",u),await ie())}finally{_=!1,w=!0,E.resolve()}}async function X(){if(x){await T.promise;return}x=!0;try{h.log.trace('optimistic: write ["%s", "%s", data] in source',PROTOCOL_ID,u),await U.writeV([fromString(`${PROTOCOL_ID}
23
+ `),fromString(`${u}
24
+ `)]),h.log.trace('optimistic: wrote ["%s", "%s", data] in source',PROTOCOL_ID,u)}finally{S=!0,x=!1,T.resolve()}}async function ie(){if(O){await D.promise;return}O=!0;try{h.log.trace("optimistic: reading multistream select header");let ee=await readString(U,h);if(h.log.trace('optimistic: read multistream select header "%s"',ee),ee===PROTOCOL_ID&&(ee=await readString(U,h)),h.log.trace('optimistic: read protocol "%s", expecting "%s"',ee,u),ee!==u)throw new UnsupportedProtocolError("protocol selection failed")}finally{C=!0,O=!1,D.resolve()}}if(y.source=async function*(){await te(),h.log.trace('optimistic: reading data from "%s" stream',u),yield*U.unwrap().source}(),y.closeRead!=null){const ee=y.closeRead.bind(y);y.closeRead=async ae=>{w||await te().catch(de=>{h.log.error("could not negotiate protocol before close read",de)}),await ee(ae)}}if(y.closeWrite!=null){const ee=y.closeWrite.bind(y);y.closeWrite=async ae=>{w||await te().catch(de=>{h.log.error("could not negotiate protocol before close write",de)}),await ee(ae)}}if(y.close!=null){const ee=y.close.bind(y);y.close=async ae=>{const de=[];x&&de.push(T.promise),O&&de.push(D.promise),de.length>0?await raceSignal(Promise.all(de),ae==null?void 0:ae.signal):(w=!0,_=!1,E.resolve()),await ee(ae)}}return{stream:y,protocol:u}}async function handle(y,u,h){u=Array.isArray(u)?u:[u],h.log.trace("handle: available protocols %s",u);const b=lpStream(y,{...h,maxDataLength:MAX_PROTOCOL_LENGTH,maxLengthLength:2});for(;;){h.log.trace("handle: reading incoming string");const v=await readString(b,h);if(h.log.trace('handle: read "%s"',v),v===PROTOCOL_ID){h.log.trace('handle: respond with "%s" for "%s"',PROTOCOL_ID,v),await write(b,fromString(`${PROTOCOL_ID}
25
+ `),h),h.log.trace('handle: responded with "%s" for "%s"',PROTOCOL_ID,v);continue}if(u.includes(v))return h.log.trace('handle: respond with "%s" for "%s"',v,v),await write(b,fromString(`${v}
26
+ `),h),h.log.trace('handle: responded with "%s" for "%s"',v,v),{stream:b.unwrap(),protocol:v};if(v==="ls"){const w=new Uint8ArrayList(...u.map(_=>encode$2.single(fromString(`${_}
27
+ `))),fromString(`
28
+ `));h.log.trace('handle: respond with "%s" for %s',u,v),await write(b,w,h),h.log.trace('handle: responded with "%s" for %s',u,v);continue}h.log.trace('handle: respond with "na" for "%s"',v),await write(b,fromString(`na
29
+ `),h),h.log('handle: responded with "na" for "%s"',v)}}const CLOSE_TIMEOUT=500;var Rh,Mh;Mh=Symbol.toStringTag,Rh=connectionSymbol;class ConnectionImpl{constructor(u){Z(this,"id");Z(this,"remoteAddr");Z(this,"remotePeer");Z(this,"direction");Z(this,"timeline");Z(this,"multiplexer");Z(this,"encryption");Z(this,"status");Z(this,"limits");Z(this,"log");Z(this,"tags");Z(this,"_newStream");Z(this,"_close");Z(this,"_abort");Z(this,"_getStreams");Z(this,Mh,"Connection");Z(this,Rh,!0);const{remoteAddr:h,remotePeer:b,newStream:v,close:w,abort:_,getStreams:E}=u;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=h,this.remotePeer=b,this.direction=u.direction,this.status="open",this.timeline=u.timeline,this.multiplexer=u.multiplexer,this.encryption=u.encryption,this.limits=u.limits,this.log=u.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=v,this._close=w,this._abort=_,this._getStreams=E,this.tags=[]}get streams(){return this._getStreams()}async newStream(u,h){if(this.status==="closing")throw new ConnectionClosingError("the connection is being closed");if(this.status==="closed")throw new ConnectionClosedError("the connection is closed");if(Array.isArray(u)||(u=[u]),this.limits!=null&&(h==null?void 0:h.runOnLimitedConnection)!==!0)throw new LimitedConnectionError("Cannot open protocol stream on limited connection");const b=await this._newStream(u,h);return b.direction="outbound",b}async close(u={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",u.signal==null){const h=AbortSignal.timeout(CLOSE_TIMEOUT);u={...u,signal:h}}try{this.log.trace("closing underlying transport"),await this._close(u),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(h){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,h),this.abort(h)}}}abort(u){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,u),this.status="closing",this._abort(u),this.status="closed",this.timeline.close=Date.now())}}function createConnection(y){return new ConnectionImpl(y)}function findIncomingStreamLimit(y,u){try{const{options:h}=u.getHandler(y);return h.maxInboundStreams}catch(h){if(h.name!=="UnhandledProtocolError")throw h}return DEFAULT_MAX_INBOUND_STREAMS}function findOutgoingStreamLimit(y,u,h={}){try{const{options:b}=u.getHandler(y);if(b.maxOutboundStreams!=null)return b.maxOutboundStreams}catch(b){if(b.name!=="UnhandledProtocolError")throw b}return h.maxOutboundStreams??DEFAULT_MAX_OUTBOUND_STREAMS}function countStreams(y,u,h){let b=0;return h.streams.forEach(v=>{v.direction===u&&v.protocol===y&&b++}),b}var Oh;Oh=Symbol.toStringTag;class Upgrader{constructor(u,h){Z(this,"components");Z(this,"connectionEncrypters");Z(this,"streamMuxers");Z(this,"inboundUpgradeTimeout");Z(this,"inboundStreamProtocolNegotiationTimeout");Z(this,"outboundStreamProtocolNegotiationTimeout");Z(this,"events");Z(this,"metrics");Z(this,Oh,"@libp2p/upgrader");var b,v,w,_;this.components=u,this.connectionEncrypters=trackedMap({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),h.connectionEncrypters.forEach(E=>{this.connectionEncrypters.set(E.protocol,E)}),this.streamMuxers=trackedMap({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),h.streamMuxers.forEach(E=>{this.streamMuxers.set(E.protocol,E)}),this.inboundUpgradeTimeout=h.inboundUpgradeTimeout??INBOUND_UPGRADE_TIMEOUT,this.inboundStreamProtocolNegotiationTimeout=h.inboundStreamProtocolNegotiationTimeout??PROTOCOL_NEGOTIATION_TIMEOUT,this.outboundStreamProtocolNegotiationTimeout=h.outboundStreamProtocolNegotiationTimeout??PROTOCOL_NEGOTIATION_TIMEOUT,this.events=u.events,this.metrics={dials:(b=u.metrics)==null?void 0:b.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:(v=u.metrics)==null?void 0:v.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:(w=u.metrics)==null?void 0:w.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:(_=u.metrics)==null?void 0:_.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}async shouldBlockConnection(u,...h){const b=this.components.connectionGater[u];if(b==null)return;if(await b.apply(this.components.connectionGater,h)===!0)throw new ConnectionInterceptedError(`The multiaddr connection is blocked by gater.${u}`)}createInboundAbortSignal(u){return anySignal([AbortSignal.timeout(this.inboundUpgradeTimeout),u])}async upgradeInbound(u,h){var w,_,E;let b=!1;const v=this.createInboundAbortSignal(h.signal);try{if((w=this.metrics.dials)==null||w.increment({inbound:!0}),b=await raceSignal(this.components.connectionManager.acceptIncomingConnection(u),v),!b)throw new ConnectionDeniedError("Connection denied");await raceSignal(this.shouldBlockConnection("denyInboundConnection",u),v),await this._performUpgrade(u,"inbound",{...h,signal:v})}catch(S){throw(_=this.metrics.errors)==null||_.increment({inbound:!0}),(E=this.metrics.inboundErrors)==null||E.increment({[S.name??"Error"]:!0}),S}finally{v.clear(),b&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(u,h){var b,v,w;try{(b=this.metrics.dials)==null||b.increment({outbound:!0});const _=u.remoteAddr.getPeerId();let E;_!=null&&(E=peerIdFromString$1(_),await raceSignal(this.shouldBlockConnection("denyOutboundConnection",E,u),h.signal));let S="outbound";return h.initiator===!1&&(S="inbound"),await this._performUpgrade(u,S,h)}catch(_){throw(v=this.metrics.errors)==null||v.increment({outbound:!0}),(w=this.metrics.outboundErrors)==null||w.increment({[_.name??"Error"]:!0}),_}}async _performUpgrade(u,h,b){var T,C,O;let v,w,_,E,S;(T=this.components.metrics)==null||T.trackMultiaddrConnection(u),u.log.trace("starting the %s connection upgrade",h);let x=u;if((b==null?void 0:b.skipProtection)!==!0){const D=this.components.connectionProtector;D!=null&&(u.log("protecting the %s connection",h),x=await D.protect(u,b))}try{if(v=x,(b==null?void 0:b.skipEncryption)!==!0){(C=b==null?void 0:b.onProgress)==null||C.call(b,new CustomProgressEvent(`upgrader:encrypt-${h}-connection`)),{conn:v,remotePeer:w,protocol:S,streamMuxer:E}=await(h==="inbound"?this._encryptInbound(x,b):this._encryptOutbound(x,b));const D={...x,...v};await this.shouldBlockConnection(h==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",w,D)}else{const D=u.remoteAddr.getPeerId();if(D==null)throw new InvalidMultiaddrError$1(`${h} connection that skipped encryption must have a peer id`);const U=peerIdFromString$1(D);S="native",w=U}if(w.equals(this.components.peerId)){const D=new InvalidPeerIdError("Can not dial self");throw u.abort(D),D}if(_=v,(b==null?void 0:b.muxerFactory)!=null)E=b.muxerFactory;else if(E==null&&this.streamMuxers.size>0){(O=b==null?void 0:b.onProgress)==null||O.call(b,new CustomProgressEvent(`upgrader:multiplex-${h}-connection`));const D=await(h==="inbound"?this._multiplexInbound({...x,...v},this.streamMuxers,b):this._multiplexOutbound({...x,...v},this.streamMuxers,b));E=D.muxerFactory,_=D.stream}}catch(D){throw u.log.error("failed to upgrade inbound connection %s %a - %e",h==="inbound"?"from":"to",u.remoteAddr,D),D}return await this.shouldBlockConnection(h==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",w,u),u.log("successfully upgraded %s connection",h),this._createConnection({cryptoProtocol:S,direction:h,maConn:u,upgradedConn:_,muxerFactory:E,remotePeer:w,limits:b==null?void 0:b.limits})}_createConnection(u){const{cryptoProtocol:h,direction:b,maConn:v,upgradedConn:w,remotePeer:_,muxerFactory:E,limits:S}=u;let x,T,C;E!=null&&(x=E.createStreamMuxer({direction:b,onIncomingStream:U=>{if(C==null)return;const te=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{var Se;const X=this.components.registrar.getProtocols(),{stream:ie,protocol:ee}=await handle(U,X,{signal:te,log:U.log,yieldBytes:!1});if(C==null)return;C.log("incoming stream opened on %s",ee);const ae=findIncomingStreamLimit(ee,this.components.registrar);if(countStreams(ee,"inbound",C)===ae){const ve=new TooManyInboundProtocolStreamsError(`Too many inbound protocol streams for protocol "${ee}" - limit ${ae}`);throw U.abort(ve),ve}U.source=ie.source,U.sink=ie.sink,U.protocol=ee,ie.closeWrite!=null&&(U.closeWrite=ie.closeWrite),ie.closeRead!=null&&(U.closeRead=ie.closeRead),ie.close!=null&&(U.close=ie.close),await this.components.peerStore.merge(_,{protocols:[ee]},{signal:te}),(Se=this.components.metrics)==null||Se.trackProtocolStream(U,C),this._onStream({connection:C,stream:U,protocol:ee})}).catch(async X=>{C.log.error("error handling incoming stream id %s - %e",U.id,X),U.timeline.close==null&&await U.close({signal:te}).catch(ie=>U.abort(ie))})}}),T=async(U,te={})=>{var ie;if(x==null)throw new MuxerUnavailableError("Connection is not multiplexed");C.log.trace("starting new stream for protocols %s",U);const X=await x.newStream();C.log.trace("started new stream %s for protocols %s",X.id,U);try{if(te.signal==null){X.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",U);const ve=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);te={...te,signal:ve}}X.log.trace("selecting protocol from protocols %s",U);const{stream:ee,protocol:ae}=await select(X,U,{...te,log:X.log,yieldBytes:!0});X.log.trace("selected protocol %s",ae);const de=findOutgoingStreamLimit(ae,this.components.registrar,te),Se=countStreams(ae,"outbound",C);if(Se>=de){const ve=new TooManyOutboundProtocolStreamsError(`Too many outbound protocol streams for protocol "${ae}" - ${Se}/${de}`);throw X.abort(ve),ve}return await this.components.peerStore.merge(_,{protocols:[ae]}),X.source=ee.source,X.sink=ee.sink,X.protocol=ae,ee.closeWrite!=null&&(X.closeWrite=ee.closeWrite),ee.closeRead!=null&&(X.closeRead=ee.closeRead),ee.close!=null&&(X.close=ee.close),(ie=this.components.metrics)==null||ie.trackProtocolStream(X,C),X}catch(ee){throw C.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",b==="inbound"?"from":"to",u.maConn.remoteAddr,U,ee),X.timeline.close==null&&X.abort(ee),ee}},Promise.all([x.sink(w.source),w.sink(x.source)]).catch(U=>{C.log.error("error piping data through muxer - %e",U)}));const O=v.timeline;v.timeline=new Proxy(O,{set:(...U)=>(U[1]==="close"&&U[2]!=null&&O.close==null&&(async()=>{try{C.status==="open"&&await C.close()}catch(te){C.log.error("error closing connection after timeline close %e",te)}finally{this.events.safeDispatchEvent("connection:close",{detail:C})}})().catch(te=>{C.log.error("error thrown while dispatching connection:close event %e",te)}),Reflect.set(...U))}),v.timeline.upgraded=Date.now();const D=()=>{throw new MuxerUnavailableError("Connection is not multiplexed")};return C=createConnection({remoteAddr:v.remoteAddr,remotePeer:_,status:"open",direction:b,timeline:v.timeline,multiplexer:x==null?void 0:x.protocol,encryption:h,limits:S,logger:this.components.logger,newStream:T??D,getStreams:()=>(x==null?void 0:x.streams)??[],close:async U=>{await(x==null?void 0:x.close(U)),await v.close(U)},abort:U=>{v.abort(U),x==null||x.abort(U)}}),this.events.safeDispatchEvent("connection:open",{detail:C}),C.__maConnTimeline=O,C}_onStream(u){const{connection:h,stream:b,protocol:v}=u,{handler:w,options:_}=this.components.registrar.getHandler(v);if(h.limits!=null&&_.runOnLimitedConnection!==!0)throw new LimitedConnectionError("Cannot open protocol stream on limited connection");w({connection:h,stream:b})}async _encryptInbound(u,h){const b=Array.from(this.connectionEncrypters.keys());try{const{stream:v,protocol:w}=await handle(u,b,{...h,log:u.log}),_=this.connectionEncrypters.get(w);if(_==null)throw new EncryptionFailedError(`no crypto module found for ${w}`);return u.log("encrypting inbound connection to %a using %s",u.remoteAddr,w),{...await _.secureInbound(v,h),protocol:w}}catch(v){throw u.log.error("encrypting inbound connection from %a failed",u.remoteAddr,v),new EncryptionFailedError(v.message)}}async _encryptOutbound(u,h){const b=Array.from(this.connectionEncrypters.keys());try{u.log.trace("selecting encrypter from %s",b);const{stream:v,protocol:w}=await select(u,b,{...h,log:u.log,yieldBytes:!0}),_=this.connectionEncrypters.get(w);if(_==null)throw new EncryptionFailedError(`no crypto module found for ${w}`);return u.log("encrypting outbound connection to %a using %s",u.remoteAddr,w),{...await _.secureOutbound(v,h),protocol:w}}catch(v){throw u.log.error("encrypting outbound connection to %a failed",u.remoteAddr,v),new EncryptionFailedError(v.message)}}async _multiplexOutbound(u,h,b){const v=Array.from(h.keys());u.log("outbound selecting muxer %s",v);try{u.log.trace("selecting stream muxer from %s",v);const{stream:w,protocol:_}=await select(u,v,{...b,log:u.log,yieldBytes:!0});u.log("selected %s as muxer protocol",_);const E=h.get(_);return{stream:w,muxerFactory:E}}catch(w){throw u.log.error("error multiplexing outbound connection",w),new MuxerUnavailableError(String(w))}}async _multiplexInbound(u,h,b){const v=Array.from(h.keys());u.log("inbound handling muxers %s",v);try{const{stream:w,protocol:_}=await handle(u,v,{...b,log:u.log}),E=h.get(_);return{stream:w,muxerFactory:E}}catch(w){throw u.log.error("error multiplexing inbound connection",w),new MuxerUnavailableError(String(w))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const version$4="2.8.11",name$1="js-libp2p";function userAgent(y,u){return`${y??name$1}/${u??version$4} browser/${globalThis.navigator.userAgent}`}var oc,rd;class Libp2p extends TypedEventEmitter{constructor(h){var T,C,O,D,U,te,X,ie,ee,ae,de,Se;super();ur(this,oc);Z(this,"peerId");Z(this,"peerStore");Z(this,"contentRouting");Z(this,"peerRouting");Z(this,"metrics");Z(this,"services");Z(this,"logger");Z(this,"status");Z(this,"components");Z(this,"log");this.status="stopped";const b=new TypedEventEmitter,v=b.dispatchEvent.bind(b);b.dispatchEvent=ve=>{const Pe=v(ve),Ie=this.dispatchEvent(new CustomEvent(ve.type,{detail:ve.detail}));return Pe||Ie},this.peerId=h.peerId,this.logger=h.logger??defaultLogger(),this.log=this.logger.forComponent("libp2p"),this.services={};const w=((T=h.nodeInfo)==null?void 0:T.name)??name$1,_=((C=h.nodeInfo)==null?void 0:C.version)??version$4,E=this.components=defaultComponents({peerId:h.peerId,privateKey:h.privateKey,nodeInfo:{name:w,version:_,userAgent:((O=h.nodeInfo)==null?void 0:O.userAgent)??userAgent(w,_)},logger:this.logger,events:b,datastore:h.datastore??new MemoryDatastore,connectionGater:connectionGater(h.connectionGater),dns:h.dns});h.metrics!=null&&(this.metrics=this.configureComponent("metrics",h.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",persistentPeerStore(E,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...h.peerStore})),E.events.addEventListener("peer:update",ve=>{if(ve.detail.previous==null){const Pe={id:ve.detail.peer.id,multiaddrs:ve.detail.peer.addresses.map(Ie=>Ie.multiaddr)};E.events.safeDispatchEvent("peer:discovery",{detail:Pe})}}),h.connectionProtector!=null&&this.configureComponent("connectionProtector",h.connectionProtector(E)),this.components.upgrader=new Upgrader(this.components,{connectionEncrypters:(h.connectionEncrypters??[]).map((ve,Pe)=>this.configureComponent(`connection-encryption-${Pe}`,ve(this.components))),streamMuxers:(h.streamMuxers??[]).map((ve,Pe)=>this.configureComponent(`stream-muxers-${Pe}`,ve(this.components))),inboundUpgradeTimeout:(D=h.connectionManager)==null?void 0:D.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:((U=h.connectionManager)==null?void 0:U.inboundStreamProtocolNegotiationTimeout)??((te=h.connectionManager)==null?void 0:te.protocolNegotiationTimeout),outboundStreamProtocolNegotiationTimeout:((X=h.connectionManager)==null?void 0:X.outboundStreamProtocolNegotiationTimeout)??((ie=h.connectionManager)==null?void 0:ie.protocolNegotiationTimeout)}),this.configureComponent("transportManager",new DefaultTransportManager(this.components,h.transportManager)),this.configureComponent("connectionManager",new DefaultConnectionManager(this.components,h.connectionManager)),((ee=h.connectionMonitor)==null?void 0:ee.enabled)!==!1&&this.configureComponent("connectionMonitor",new ConnectionMonitor(this.components,h.connectionMonitor)),this.configureComponent("registrar",new Registrar(this.components)),this.configureComponent("addressManager",new AddressManager(this.components,h.addresses));const S=(h.peerRouters??[]).map((ve,Pe)=>this.configureComponent(`peer-router-${Pe}`,ve(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new DefaultPeerRouting(this.components,{routers:S}));const x=(h.contentRouters??[]).map((ve,Pe)=>this.configureComponent(`content-router-${Pe}`,ve(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new CompoundContentRouting(this.components,{routers:x})),this.configureComponent("randomWalk",new RandomWalk(this.components)),(h.peerDiscovery??[]).forEach((ve,Pe)=>{this.configureComponent(`peer-discovery-${Pe}`,ve(this.components)).addEventListener("peer",Ee=>{$t(this,oc,rd).call(this,Ee)})}),(ae=h.transports)==null||ae.forEach((ve,Pe)=>{this.components.transportManager.add(this.configureComponent(`transport-${Pe}`,ve(this.components)))}),h.services!=null)for(const ve of Object.keys(h.services)){const Pe=h.services[ve],Ie=Pe(this.components);if(Ie==null){this.log.error("service factory %s returned null or undefined instance",ve);continue}this.services[ve]=Ie,this.configureComponent(ve,Ie),Ie[contentRoutingSymbol]!=null&&(this.log("registering service %s for content routing",ve),x.push(Ie[contentRoutingSymbol])),Ie[peerRoutingSymbol]!=null&&(this.log("registering service %s for peer routing",ve),S.push(Ie[peerRoutingSymbol])),Ie[peerDiscoverySymbol]!=null&&(this.log("registering service %s for peer discovery",ve),(Se=(de=Ie[peerDiscoverySymbol]).addEventListener)==null||Se.call(de,"peer",Ee=>{$t(this,oc,rd).call(this,Ee)}))}checkServiceDependencies(E)}configureComponent(h,b){return b==null&&this.log.error("component %s was null or undefined",h),this.components[h]=b,b}async start(){var h,b,v,w;if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await((b=(h=this.components).beforeStart)==null?void 0:b.call(h)),await this.components.start(),await((w=(v=this.components).afterStart)==null?void 0:w.call(v)),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(_){throw this.log.error("An error occurred starting libp2p",_),this.status="started",await this.stop(),_}}}async stop(){var h,b,v,w;this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await((b=(h=this.components).beforeStop)==null?void 0:b.call(h)),await this.components.stop(),await((w=(v=this.components).afterStop)==null?void 0:w.call(v)),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(h){return this.components.connectionManager.getConnections(h)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const h=new PeerSet;for(const b of this.components.connectionManager.getConnections())h.add(b.remotePeer);return Array.from(h)}async dial(h,b={}){return this.components.connectionManager.openConnection(h,{priority:75,...b})}async dialProtocol(h,b,v={}){if(b==null)throw new InvalidParametersError$2("no protocols were provided to open a stream");if(b=Array.isArray(b)?b:[b],b.length===0)throw new InvalidParametersError$2("no protocols were provided to open a stream");return(await this.dial(h,v)).newStream(b,v)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(h,b={}){isMultiaddr(h)&&(h=peerIdFromString$1(h.getPeerId()??"")),await this.components.connectionManager.closeConnections(h,b)}async getPublicKey(h,b={}){if(this.log("getPublicKey %p",h),h.publicKey!=null)return h.publicKey;try{const E=await this.peerStore.get(h,b);if(E.id.publicKey!=null)return E.id.publicKey}catch(E){if(E.name!=="NotFoundError")throw E}const v=concat([fromString("/pk/"),h.toMultihash().bytes]),w=await this.contentRouting.get(v,b),_=publicKeyFromProtobuf(w);return await this.peerStore.patch(h,{publicKey:_},b),_}async handle(h,b,v){Array.isArray(h)||(h=[h]),await Promise.all(h.map(async w=>{await this.components.registrar.handle(w,b,v)}))}async unhandle(h,b){Array.isArray(h)||(h=[h]),await Promise.all(h.map(async v=>{await this.components.registrar.unhandle(v,b)}))}async register(h,b,v){return this.components.registrar.register(h,b,v)}unregister(h){this.components.registrar.unregister(h)}async isDialable(h,b={}){return this.components.connectionManager.isDialable(h,b)}}oc=new WeakSet,rd=function(h){const{detail:b}=h;if(b.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(b.id,{multiaddrs:b.multiaddrs}).catch(v=>{this.log.error(v)})};async function createLibp2p(y={}){y.privateKey??(y.privateKey=await generateKeyPair());const u=new Libp2p({...await validateConfig(y),peerId:peerIdFromPrivateKey(y.privateKey)});return y.start!==!1&&await u.start(),u}function isTestEnvironment(){var y;try{return((y=process$1==null?void 0:process$1.env)==null?void 0:y.NODE_ENV)==="test"}catch{return!1}}const enrTree={SANDBOX:"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",TEST:"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"},DEFAULT_BOOTSTRAP_TAG_NAME=Tags.BOOTSTRAP,DEFAULT_BOOTSTRAP_TAG_VALUE=50,DEFAULT_BOOTSTRAP_TAG_TTL=1e8,ERR_INVALID_ID="Invalid record id",MULTIADDR_LENGTH_SIZE=2;var cryptoBrowserify={},browser$b={exports:{}},safeBuffer$2={exports:{}},dist={};(function(y){Object.defineProperties(y,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var u={},h={};h.byteLength=T,h.toByteArray=O,h.fromByteArray=te;for(var b=[],v=[],w=typeof Uint8Array<"u"?Uint8Array:Array,_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",E=0,S=_.length;E<S;++E)b[E]=_[E],v[_.charCodeAt(E)]=E;v[45]=62,v[95]=63;function x(ee){var ae=ee.length;if(ae%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var de=ee.indexOf("=");de===-1&&(de=ae);var Se=de===ae?0:4-de%4;return[de,Se]}function T(ee){var ae=x(ee),de=ae[0],Se=ae[1];return(de+Se)*3/4-Se}function C(ee,ae,de){return(ae+de)*3/4-de}function O(ee){var ae,de=x(ee),Se=de[0],ve=de[1],Pe=new w(C(ee,Se,ve)),Ie=0,Ee=ve>0?Se-4:Se,De;for(De=0;De<Ee;De+=4)ae=v[ee.charCodeAt(De)]<<18|v[ee.charCodeAt(De+1)]<<12|v[ee.charCodeAt(De+2)]<<6|v[ee.charCodeAt(De+3)],Pe[Ie++]=ae>>16&255,Pe[Ie++]=ae>>8&255,Pe[Ie++]=ae&255;return ve===2&&(ae=v[ee.charCodeAt(De)]<<2|v[ee.charCodeAt(De+1)]>>4,Pe[Ie++]=ae&255),ve===1&&(ae=v[ee.charCodeAt(De)]<<10|v[ee.charCodeAt(De+1)]<<4|v[ee.charCodeAt(De+2)]>>2,Pe[Ie++]=ae>>8&255,Pe[Ie++]=ae&255),Pe}function D(ee){return b[ee>>18&63]+b[ee>>12&63]+b[ee>>6&63]+b[ee&63]}function U(ee,ae,de){for(var Se,ve=[],Pe=ae;Pe<de;Pe+=3)Se=(ee[Pe]<<16&16711680)+(ee[Pe+1]<<8&65280)+(ee[Pe+2]&255),ve.push(D(Se));return ve.join("")}function te(ee){for(var ae,de=ee.length,Se=de%3,ve=[],Pe=16383,Ie=0,Ee=de-Se;Ie<Ee;Ie+=Pe)ve.push(U(ee,Ie,Ie+Pe>Ee?Ee:Ie+Pe));return Se===1?(ae=ee[de-1],ve.push(b[ae>>2]+b[ae<<4&63]+"==")):Se===2&&(ae=(ee[de-2]<<8)+ee[de-1],ve.push(b[ae>>10]+b[ae>>4&63]+b[ae<<2&63]+"=")),ve.join("")}var X={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */X.read=function(ee,ae,de,Se,ve){var Pe,Ie,Ee=ve*8-Se-1,De=(1<<Ee)-1,be=De>>1,B=-7,F=de?ve-1:0,M=de?-1:1,N=ee[ae+F];for(F+=M,Pe=N&(1<<-B)-1,N>>=-B,B+=Ee;B>0;Pe=Pe*256+ee[ae+F],F+=M,B-=8);for(Ie=Pe&(1<<-B)-1,Pe>>=-B,B+=Se;B>0;Ie=Ie*256+ee[ae+F],F+=M,B-=8);if(Pe===0)Pe=1-be;else{if(Pe===De)return Ie?NaN:(N?-1:1)*(1/0);Ie=Ie+Math.pow(2,Se),Pe=Pe-be}return(N?-1:1)*Ie*Math.pow(2,Pe-Se)},X.write=function(ee,ae,de,Se,ve,Pe){var Ie,Ee,De,be=Pe*8-ve-1,B=(1<<be)-1,F=B>>1,M=ve===23?Math.pow(2,-24)-Math.pow(2,-77):0,N=Se?0:Pe-1,Q=Se?1:-1,j=ae<0||ae===0&&1/ae<0?1:0;for(ae=Math.abs(ae),isNaN(ae)||ae===1/0?(Ee=isNaN(ae)?1:0,Ie=B):(Ie=Math.floor(Math.log(ae)/Math.LN2),ae*(De=Math.pow(2,-Ie))<1&&(Ie--,De*=2),Ie+F>=1?ae+=M/De:ae+=M*Math.pow(2,1-F),ae*De>=2&&(Ie++,De/=2),Ie+F>=B?(Ee=0,Ie=B):Ie+F>=1?(Ee=(ae*De-1)*Math.pow(2,ve),Ie=Ie+F):(Ee=ae*Math.pow(2,F-1)*Math.pow(2,ve),Ie=0));ve>=8;ee[de+N]=Ee&255,N+=Q,Ee/=256,ve-=8);for(Ie=Ie<<ve|Ee,be+=ve;be>0;ee[de+N]=Ie&255,N+=Q,Ie/=256,be-=8);ee[de+N-Q]|=j*128};/*!
30
+ * The buffer module from node.js, for the browser.
31
+ *
32
+ * @author Feross Aboukhadijeh <https://feross.org>
33
+ * @license MIT
34
+ */(function(ee){const ae=h,de=X,Se=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;ee.Buffer=B,ee.SlowBuffer=he,ee.INSPECT_MAX_BYTES=50;const ve=2147483647;ee.kMaxLength=ve;const{Uint8Array:Pe,ArrayBuffer:Ie,SharedArrayBuffer:Ee}=globalThis;B.TYPED_ARRAY_SUPPORT=De(),!B.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function De(){try{const we=new Pe(1),se={foo:function(){return 42}};return Object.setPrototypeOf(se,Pe.prototype),Object.setPrototypeOf(we,se),we.foo()===42}catch{return!1}}Object.defineProperty(B.prototype,"parent",{enumerable:!0,get:function(){if(B.isBuffer(this))return this.buffer}}),Object.defineProperty(B.prototype,"offset",{enumerable:!0,get:function(){if(B.isBuffer(this))return this.byteOffset}});function be(we){if(we>ve)throw new RangeError('The value "'+we+'" is invalid for option "size"');const se=new Pe(we);return Object.setPrototypeOf(se,B.prototype),se}function B(we,se,ue){if(typeof we=="number"){if(typeof se=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Q(we)}return F(we,se,ue)}B.poolSize=8192;function F(we,se,ue){if(typeof we=="string")return j(we,se);if(Ie.isView(we))return J(we);if(we==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof we);if(Bt(we,Ie)||we&&Bt(we.buffer,Ie)||typeof Ee<"u"&&(Bt(we,Ee)||we&&Bt(we.buffer,Ee)))return q(we,se,ue);if(typeof we=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const xe=we.valueOf&&we.valueOf();if(xe!=null&&xe!==we)return B.from(xe,se,ue);const ke=re(we);if(ke)return ke;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof we[Symbol.toPrimitive]=="function")return B.from(we[Symbol.toPrimitive]("string"),se,ue);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof we)}B.from=function(we,se,ue){return F(we,se,ue)},Object.setPrototypeOf(B.prototype,Pe.prototype),Object.setPrototypeOf(B,Pe);function M(we){if(typeof we!="number")throw new TypeError('"size" argument must be of type number');if(we<0)throw new RangeError('The value "'+we+'" is invalid for option "size"')}function N(we,se,ue){return M(we),we<=0?be(we):se!==void 0?typeof ue=="string"?be(we).fill(se,ue):be(we).fill(se):be(we)}B.alloc=function(we,se,ue){return N(we,se,ue)};function Q(we){return M(we),be(we<0?0:H(we)|0)}B.allocUnsafe=function(we){return Q(we)},B.allocUnsafeSlow=function(we){return Q(we)};function j(we,se){if((typeof se!="string"||se==="")&&(se="utf8"),!B.isEncoding(se))throw new TypeError("Unknown encoding: "+se);const ue=Oe(we,se)|0;let xe=be(ue);const ke=xe.write(we,se);return ke!==ue&&(xe=xe.slice(0,ke)),xe}function ne(we){const se=we.length<0?0:H(we.length)|0,ue=be(se);for(let xe=0;xe<se;xe+=1)ue[xe]=we[xe]&255;return ue}function J(we){if(Bt(we,Pe)){const se=new Pe(we);return q(se.buffer,se.byteOffset,se.byteLength)}return ne(we)}function q(we,se,ue){if(se<0||we.byteLength<se)throw new RangeError('"offset" is outside of buffer bounds');if(we.byteLength<se+(ue||0))throw new RangeError('"length" is outside of buffer bounds');let xe;return se===void 0&&ue===void 0?xe=new Pe(we):ue===void 0?xe=new Pe(we,se):xe=new Pe(we,se,ue),Object.setPrototypeOf(xe,B.prototype),xe}function re(we){if(B.isBuffer(we)){const se=H(we.length)|0,ue=be(se);return ue.length===0||we.copy(ue,0,0,se),ue}if(we.length!==void 0)return typeof we.length!="number"||Yt(we.length)?be(0):ne(we);if(we.type==="Buffer"&&Array.isArray(we.data))return ne(we.data)}function H(we){if(we>=ve)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ve.toString(16)+" bytes");return we|0}function he(we){return+we!=we&&(we=0),B.alloc(+we)}B.isBuffer=function(se){return se!=null&&se._isBuffer===!0&&se!==B.prototype},B.compare=function(se,ue){if(Bt(se,Pe)&&(se=B.from(se,se.offset,se.byteLength)),Bt(ue,Pe)&&(ue=B.from(ue,ue.offset,ue.byteLength)),!B.isBuffer(se)||!B.isBuffer(ue))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(se===ue)return 0;let xe=se.length,ke=ue.length;for(let Ke=0,We=Math.min(xe,ke);Ke<We;++Ke)if(se[Ke]!==ue[Ke]){xe=se[Ke],ke=ue[Ke];break}return xe<ke?-1:ke<xe?1:0},B.isEncoding=function(se){switch(String(se).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},B.concat=function(se,ue){if(!Array.isArray(se))throw new TypeError('"list" argument must be an Array of Buffers');if(se.length===0)return B.alloc(0);let xe;if(ue===void 0)for(ue=0,xe=0;xe<se.length;++xe)ue+=se[xe].length;const ke=B.allocUnsafe(ue);let Ke=0;for(xe=0;xe<se.length;++xe){let We=se[xe];if(Bt(We,Pe))Ke+We.length>ke.length?(B.isBuffer(We)||(We=B.from(We)),We.copy(ke,Ke)):Pe.prototype.set.call(ke,We,Ke);else if(B.isBuffer(We))We.copy(ke,Ke);else throw new TypeError('"list" argument must be an Array of Buffers');Ke+=We.length}return ke};function Oe(we,se){if(B.isBuffer(we))return we.length;if(Ie.isView(we)||Bt(we,Ie))return we.byteLength;if(typeof we!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof we);const ue=we.length,xe=arguments.length>2&&arguments[2]===!0;if(!xe&&ue===0)return 0;let ke=!1;for(;;)switch(se){case"ascii":case"latin1":case"binary":return ue;case"utf8":case"utf-8":return Gt(we).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ue*2;case"hex":return ue>>>1;case"base64":return Xt(we).length;default:if(ke)return xe?-1:Gt(we).length;se=(""+se).toLowerCase(),ke=!0}}B.byteLength=Oe;function Ne(we,se,ue){let xe=!1;if((se===void 0||se<0)&&(se=0),se>this.length||((ue===void 0||ue>this.length)&&(ue=this.length),ue<=0)||(ue>>>=0,se>>>=0,ue<=se))return"";for(we||(we="utf8");;)switch(we){case"hex":return nt(this,se,ue);case"utf8":case"utf-8":return Ue(this,se,ue);case"ascii":return tt(this,se,ue);case"latin1":case"binary":return Fe(this,se,ue);case"base64":return Re(this,se,ue);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return it(this,se,ue);default:if(xe)throw new TypeError("Unknown encoding: "+we);we=(we+"").toLowerCase(),xe=!0}}B.prototype._isBuffer=!0;function Ae(we,se,ue){const xe=we[se];we[se]=we[ue],we[ue]=xe}B.prototype.swap16=function(){const se=this.length;if(se%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let ue=0;ue<se;ue+=2)Ae(this,ue,ue+1);return this},B.prototype.swap32=function(){const se=this.length;if(se%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let ue=0;ue<se;ue+=4)Ae(this,ue,ue+3),Ae(this,ue+1,ue+2);return this},B.prototype.swap64=function(){const se=this.length;if(se%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let ue=0;ue<se;ue+=8)Ae(this,ue,ue+7),Ae(this,ue+1,ue+6),Ae(this,ue+2,ue+5),Ae(this,ue+3,ue+4);return this},B.prototype.toString=function(){const se=this.length;return se===0?"":arguments.length===0?Ue(this,0,se):Ne.apply(this,arguments)},B.prototype.toLocaleString=B.prototype.toString,B.prototype.equals=function(se){if(!B.isBuffer(se))throw new TypeError("Argument must be a Buffer");return this===se?!0:B.compare(this,se)===0},B.prototype.inspect=function(){let se="";const ue=ee.INSPECT_MAX_BYTES;return se=this.toString("hex",0,ue).replace(/(.{2})/g,"$1 ").trim(),this.length>ue&&(se+=" ... "),"<Buffer "+se+">"},Se&&(B.prototype[Se]=B.prototype.inspect),B.prototype.compare=function(se,ue,xe,ke,Ke){if(Bt(se,Pe)&&(se=B.from(se,se.offset,se.byteLength)),!B.isBuffer(se))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof se);if(ue===void 0&&(ue=0),xe===void 0&&(xe=se?se.length:0),ke===void 0&&(ke=0),Ke===void 0&&(Ke=this.length),ue<0||xe>se.length||ke<0||Ke>this.length)throw new RangeError("out of range index");if(ke>=Ke&&ue>=xe)return 0;if(ke>=Ke)return-1;if(ue>=xe)return 1;if(ue>>>=0,xe>>>=0,ke>>>=0,Ke>>>=0,this===se)return 0;let We=Ke-ke,ut=xe-ue;const _t=Math.min(We,ut),st=this.slice(ke,Ke),Et=se.slice(ue,xe);for(let gt=0;gt<_t;++gt)if(st[gt]!==Et[gt]){We=st[gt],ut=Et[gt];break}return We<ut?-1:ut<We?1:0};function le(we,se,ue,xe,ke){if(we.length===0)return-1;if(typeof ue=="string"?(xe=ue,ue=0):ue>2147483647?ue=2147483647:ue<-2147483648&&(ue=-2147483648),ue=+ue,Yt(ue)&&(ue=ke?0:we.length-1),ue<0&&(ue=we.length+ue),ue>=we.length){if(ke)return-1;ue=we.length-1}else if(ue<0)if(ke)ue=0;else return-1;if(typeof se=="string"&&(se=B.from(se,xe)),B.isBuffer(se))return se.length===0?-1:me(we,se,ue,xe,ke);if(typeof se=="number")return se=se&255,typeof Pe.prototype.indexOf=="function"?ke?Pe.prototype.indexOf.call(we,se,ue):Pe.prototype.lastIndexOf.call(we,se,ue):me(we,[se],ue,xe,ke);throw new TypeError("val must be string, number or Buffer")}function me(we,se,ue,xe,ke){let Ke=1,We=we.length,ut=se.length;if(xe!==void 0&&(xe=String(xe).toLowerCase(),xe==="ucs2"||xe==="ucs-2"||xe==="utf16le"||xe==="utf-16le")){if(we.length<2||se.length<2)return-1;Ke=2,We/=2,ut/=2,ue/=2}function _t(Et,gt){return Ke===1?Et[gt]:Et.readUInt16BE(gt*Ke)}let st;if(ke){let Et=-1;for(st=ue;st<We;st++)if(_t(we,st)===_t(se,Et===-1?0:st-Et)){if(Et===-1&&(Et=st),st-Et+1===ut)return Et*Ke}else Et!==-1&&(st-=st-Et),Et=-1}else for(ue+ut>We&&(ue=We-ut),st=ue;st>=0;st--){let Et=!0;for(let gt=0;gt<ut;gt++)if(_t(we,st+gt)!==_t(se,gt)){Et=!1;break}if(Et)return st}return-1}B.prototype.includes=function(se,ue,xe){return this.indexOf(se,ue,xe)!==-1},B.prototype.indexOf=function(se,ue,xe){return le(this,se,ue,xe,!0)},B.prototype.lastIndexOf=function(se,ue,xe){return le(this,se,ue,xe,!1)};function Me(we,se,ue,xe){ue=Number(ue)||0;const ke=we.length-ue;xe?(xe=Number(xe),xe>ke&&(xe=ke)):xe=ke;const Ke=se.length;xe>Ke/2&&(xe=Ke/2);let We;for(We=0;We<xe;++We){const ut=parseInt(se.substr(We*2,2),16);if(Yt(ut))return We;we[ue+We]=ut}return We}function fe(we,se,ue,xe){return bt(Gt(se,we.length-ue),we,ue,xe)}function ge(we,se,ue,xe){return bt(At(se),we,ue,xe)}function ce(we,se,ue,xe){return bt(Xt(se),we,ue,xe)}function _e(we,se,ue,xe){return bt(tr(se,we.length-ue),we,ue,xe)}B.prototype.write=function(se,ue,xe,ke){if(ue===void 0)ke="utf8",xe=this.length,ue=0;else if(xe===void 0&&typeof ue=="string")ke=ue,xe=this.length,ue=0;else if(isFinite(ue))ue=ue>>>0,isFinite(xe)?(xe=xe>>>0,ke===void 0&&(ke="utf8")):(ke=xe,xe=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const Ke=this.length-ue;if((xe===void 0||xe>Ke)&&(xe=Ke),se.length>0&&(xe<0||ue<0)||ue>this.length)throw new RangeError("Attempt to write outside buffer bounds");ke||(ke="utf8");let We=!1;for(;;)switch(ke){case"hex":return Me(this,se,ue,xe);case"utf8":case"utf-8":return fe(this,se,ue,xe);case"ascii":case"latin1":case"binary":return ge(this,se,ue,xe);case"base64":return ce(this,se,ue,xe);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _e(this,se,ue,xe);default:if(We)throw new TypeError("Unknown encoding: "+ke);ke=(""+ke).toLowerCase(),We=!0}},B.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Re(we,se,ue){return se===0&&ue===we.length?ae.fromByteArray(we):ae.fromByteArray(we.slice(se,ue))}function Ue(we,se,ue){ue=Math.min(we.length,ue);const xe=[];let ke=se;for(;ke<ue;){const Ke=we[ke];let We=null,ut=Ke>239?4:Ke>223?3:Ke>191?2:1;if(ke+ut<=ue){let _t,st,Et,gt;switch(ut){case 1:Ke<128&&(We=Ke);break;case 2:_t=we[ke+1],(_t&192)===128&&(gt=(Ke&31)<<6|_t&63,gt>127&&(We=gt));break;case 3:_t=we[ke+1],st=we[ke+2],(_t&192)===128&&(st&192)===128&&(gt=(Ke&15)<<12|(_t&63)<<6|st&63,gt>2047&&(gt<55296||gt>57343)&&(We=gt));break;case 4:_t=we[ke+1],st=we[ke+2],Et=we[ke+3],(_t&192)===128&&(st&192)===128&&(Et&192)===128&&(gt=(Ke&15)<<18|(_t&63)<<12|(st&63)<<6|Et&63,gt>65535&&gt<1114112&&(We=gt))}}We===null?(We=65533,ut=1):We>65535&&(We-=65536,xe.push(We>>>10&1023|55296),We=56320|We&1023),xe.push(We),ke+=ut}return Ze(xe)}const qe=4096;function Ze(we){const se=we.length;if(se<=qe)return String.fromCharCode.apply(String,we);let ue="",xe=0;for(;xe<se;)ue+=String.fromCharCode.apply(String,we.slice(xe,xe+=qe));return ue}function tt(we,se,ue){let xe="";ue=Math.min(we.length,ue);for(let ke=se;ke<ue;++ke)xe+=String.fromCharCode(we[ke]&127);return xe}function Fe(we,se,ue){let xe="";ue=Math.min(we.length,ue);for(let ke=se;ke<ue;++ke)xe+=String.fromCharCode(we[ke]);return xe}function nt(we,se,ue){const xe=we.length;(!se||se<0)&&(se=0),(!ue||ue<0||ue>xe)&&(ue=xe);let ke="";for(let Ke=se;Ke<ue;++Ke)ke+=Tt[we[Ke]];return ke}function it(we,se,ue){const xe=we.slice(se,ue);let ke="";for(let Ke=0;Ke<xe.length-1;Ke+=2)ke+=String.fromCharCode(xe[Ke]+xe[Ke+1]*256);return ke}B.prototype.slice=function(se,ue){const xe=this.length;se=~~se,ue=ue===void 0?xe:~~ue,se<0?(se+=xe,se<0&&(se=0)):se>xe&&(se=xe),ue<0?(ue+=xe,ue<0&&(ue=0)):ue>xe&&(ue=xe),ue<se&&(ue=se);const ke=this.subarray(se,ue);return Object.setPrototypeOf(ke,B.prototype),ke};function at(we,se,ue){if(we%1!==0||we<0)throw new RangeError("offset is not uint");if(we+se>ue)throw new RangeError("Trying to access beyond buffer length")}B.prototype.readUintLE=B.prototype.readUIntLE=function(se,ue,xe){se=se>>>0,ue=ue>>>0,xe||at(se,ue,this.length);let ke=this[se],Ke=1,We=0;for(;++We<ue&&(Ke*=256);)ke+=this[se+We]*Ke;return ke},B.prototype.readUintBE=B.prototype.readUIntBE=function(se,ue,xe){se=se>>>0,ue=ue>>>0,xe||at(se,ue,this.length);let ke=this[se+--ue],Ke=1;for(;ue>0&&(Ke*=256);)ke+=this[se+--ue]*Ke;return ke},B.prototype.readUint8=B.prototype.readUInt8=function(se,ue){return se=se>>>0,ue||at(se,1,this.length),this[se]},B.prototype.readUint16LE=B.prototype.readUInt16LE=function(se,ue){return se=se>>>0,ue||at(se,2,this.length),this[se]|this[se+1]<<8},B.prototype.readUint16BE=B.prototype.readUInt16BE=function(se,ue){return se=se>>>0,ue||at(se,2,this.length),this[se]<<8|this[se+1]},B.prototype.readUint32LE=B.prototype.readUInt32LE=function(se,ue){return se=se>>>0,ue||at(se,4,this.length),(this[se]|this[se+1]<<8|this[se+2]<<16)+this[se+3]*16777216},B.prototype.readUint32BE=B.prototype.readUInt32BE=function(se,ue){return se=se>>>0,ue||at(se,4,this.length),this[se]*16777216+(this[se+1]<<16|this[se+2]<<8|this[se+3])},B.prototype.readBigUInt64LE=qt(function(se){se=se>>>0,Ut(se,"offset");const ue=this[se],xe=this[se+7];(ue===void 0||xe===void 0)&&Lt(se,this.length-8);const ke=ue+this[++se]*2**8+this[++se]*2**16+this[++se]*2**24,Ke=this[++se]+this[++se]*2**8+this[++se]*2**16+xe*2**24;return BigInt(ke)+(BigInt(Ke)<<BigInt(32))}),B.prototype.readBigUInt64BE=qt(function(se){se=se>>>0,Ut(se,"offset");const ue=this[se],xe=this[se+7];(ue===void 0||xe===void 0)&&Lt(se,this.length-8);const ke=ue*2**24+this[++se]*2**16+this[++se]*2**8+this[++se],Ke=this[++se]*2**24+this[++se]*2**16+this[++se]*2**8+xe;return(BigInt(ke)<<BigInt(32))+BigInt(Ke)}),B.prototype.readIntLE=function(se,ue,xe){se=se>>>0,ue=ue>>>0,xe||at(se,ue,this.length);let ke=this[se],Ke=1,We=0;for(;++We<ue&&(Ke*=256);)ke+=this[se+We]*Ke;return Ke*=128,ke>=Ke&&(ke-=Math.pow(2,8*ue)),ke},B.prototype.readIntBE=function(se,ue,xe){se=se>>>0,ue=ue>>>0,xe||at(se,ue,this.length);let ke=ue,Ke=1,We=this[se+--ke];for(;ke>0&&(Ke*=256);)We+=this[se+--ke]*Ke;return Ke*=128,We>=Ke&&(We-=Math.pow(2,8*ue)),We},B.prototype.readInt8=function(se,ue){return se=se>>>0,ue||at(se,1,this.length),this[se]&128?(255-this[se]+1)*-1:this[se]},B.prototype.readInt16LE=function(se,ue){se=se>>>0,ue||at(se,2,this.length);const xe=this[se]|this[se+1]<<8;return xe&32768?xe|4294901760:xe},B.prototype.readInt16BE=function(se,ue){se=se>>>0,ue||at(se,2,this.length);const xe=this[se+1]|this[se]<<8;return xe&32768?xe|4294901760:xe},B.prototype.readInt32LE=function(se,ue){return se=se>>>0,ue||at(se,4,this.length),this[se]|this[se+1]<<8|this[se+2]<<16|this[se+3]<<24},B.prototype.readInt32BE=function(se,ue){return se=se>>>0,ue||at(se,4,this.length),this[se]<<24|this[se+1]<<16|this[se+2]<<8|this[se+3]},B.prototype.readBigInt64LE=qt(function(se){se=se>>>0,Ut(se,"offset");const ue=this[se],xe=this[se+7];(ue===void 0||xe===void 0)&&Lt(se,this.length-8);const ke=this[se+4]+this[se+5]*2**8+this[se+6]*2**16+(xe<<24);return(BigInt(ke)<<BigInt(32))+BigInt(ue+this[++se]*2**8+this[++se]*2**16+this[++se]*2**24)}),B.prototype.readBigInt64BE=qt(function(se){se=se>>>0,Ut(se,"offset");const ue=this[se],xe=this[se+7];(ue===void 0||xe===void 0)&&Lt(se,this.length-8);const ke=(ue<<24)+this[++se]*2**16+this[++se]*2**8+this[++se];return(BigInt(ke)<<BigInt(32))+BigInt(this[++se]*2**24+this[++se]*2**16+this[++se]*2**8+xe)}),B.prototype.readFloatLE=function(se,ue){return se=se>>>0,ue||at(se,4,this.length),de.read(this,se,!0,23,4)},B.prototype.readFloatBE=function(se,ue){return se=se>>>0,ue||at(se,4,this.length),de.read(this,se,!1,23,4)},B.prototype.readDoubleLE=function(se,ue){return se=se>>>0,ue||at(se,8,this.length),de.read(this,se,!0,52,8)},B.prototype.readDoubleBE=function(se,ue){return se=se>>>0,ue||at(se,8,this.length),de.read(this,se,!1,52,8)};function ct(we,se,ue,xe,ke,Ke){if(!B.isBuffer(we))throw new TypeError('"buffer" argument must be a Buffer instance');if(se>ke||se<Ke)throw new RangeError('"value" argument is out of bounds');if(ue+xe>we.length)throw new RangeError("Index out of range")}B.prototype.writeUintLE=B.prototype.writeUIntLE=function(se,ue,xe,ke){if(se=+se,ue=ue>>>0,xe=xe>>>0,!ke){const ut=Math.pow(2,8*xe)-1;ct(this,se,ue,xe,ut,0)}let Ke=1,We=0;for(this[ue]=se&255;++We<xe&&(Ke*=256);)this[ue+We]=se/Ke&255;return ue+xe},B.prototype.writeUintBE=B.prototype.writeUIntBE=function(se,ue,xe,ke){if(se=+se,ue=ue>>>0,xe=xe>>>0,!ke){const ut=Math.pow(2,8*xe)-1;ct(this,se,ue,xe,ut,0)}let Ke=xe-1,We=1;for(this[ue+Ke]=se&255;--Ke>=0&&(We*=256);)this[ue+Ke]=se/We&255;return ue+xe},B.prototype.writeUint8=B.prototype.writeUInt8=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,1,255,0),this[ue]=se&255,ue+1},B.prototype.writeUint16LE=B.prototype.writeUInt16LE=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,2,65535,0),this[ue]=se&255,this[ue+1]=se>>>8,ue+2},B.prototype.writeUint16BE=B.prototype.writeUInt16BE=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,2,65535,0),this[ue]=se>>>8,this[ue+1]=se&255,ue+2},B.prototype.writeUint32LE=B.prototype.writeUInt32LE=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,4,4294967295,0),this[ue+3]=se>>>24,this[ue+2]=se>>>16,this[ue+1]=se>>>8,this[ue]=se&255,ue+4},B.prototype.writeUint32BE=B.prototype.writeUInt32BE=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,4,4294967295,0),this[ue]=se>>>24,this[ue+1]=se>>>16,this[ue+2]=se>>>8,this[ue+3]=se&255,ue+4};function ht(we,se,ue,xe,ke){vt(se,xe,ke,we,ue,7);let Ke=Number(se&BigInt(4294967295));we[ue++]=Ke,Ke=Ke>>8,we[ue++]=Ke,Ke=Ke>>8,we[ue++]=Ke,Ke=Ke>>8,we[ue++]=Ke;let We=Number(se>>BigInt(32)&BigInt(4294967295));return we[ue++]=We,We=We>>8,we[ue++]=We,We=We>>8,we[ue++]=We,We=We>>8,we[ue++]=We,ue}function xt(we,se,ue,xe,ke){vt(se,xe,ke,we,ue,7);let Ke=Number(se&BigInt(4294967295));we[ue+7]=Ke,Ke=Ke>>8,we[ue+6]=Ke,Ke=Ke>>8,we[ue+5]=Ke,Ke=Ke>>8,we[ue+4]=Ke;let We=Number(se>>BigInt(32)&BigInt(4294967295));return we[ue+3]=We,We=We>>8,we[ue+2]=We,We=We>>8,we[ue+1]=We,We=We>>8,we[ue]=We,ue+8}B.prototype.writeBigUInt64LE=qt(function(se,ue=0){return ht(this,se,ue,BigInt(0),BigInt("0xffffffffffffffff"))}),B.prototype.writeBigUInt64BE=qt(function(se,ue=0){return xt(this,se,ue,BigInt(0),BigInt("0xffffffffffffffff"))}),B.prototype.writeIntLE=function(se,ue,xe,ke){if(se=+se,ue=ue>>>0,!ke){const _t=Math.pow(2,8*xe-1);ct(this,se,ue,xe,_t-1,-_t)}let Ke=0,We=1,ut=0;for(this[ue]=se&255;++Ke<xe&&(We*=256);)se<0&&ut===0&&this[ue+Ke-1]!==0&&(ut=1),this[ue+Ke]=(se/We>>0)-ut&255;return ue+xe},B.prototype.writeIntBE=function(se,ue,xe,ke){if(se=+se,ue=ue>>>0,!ke){const _t=Math.pow(2,8*xe-1);ct(this,se,ue,xe,_t-1,-_t)}let Ke=xe-1,We=1,ut=0;for(this[ue+Ke]=se&255;--Ke>=0&&(We*=256);)se<0&&ut===0&&this[ue+Ke+1]!==0&&(ut=1),this[ue+Ke]=(se/We>>0)-ut&255;return ue+xe},B.prototype.writeInt8=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,1,127,-128),se<0&&(se=255+se+1),this[ue]=se&255,ue+1},B.prototype.writeInt16LE=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,2,32767,-32768),this[ue]=se&255,this[ue+1]=se>>>8,ue+2},B.prototype.writeInt16BE=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,2,32767,-32768),this[ue]=se>>>8,this[ue+1]=se&255,ue+2},B.prototype.writeInt32LE=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,4,2147483647,-2147483648),this[ue]=se&255,this[ue+1]=se>>>8,this[ue+2]=se>>>16,this[ue+3]=se>>>24,ue+4},B.prototype.writeInt32BE=function(se,ue,xe){return se=+se,ue=ue>>>0,xe||ct(this,se,ue,4,2147483647,-2147483648),se<0&&(se=4294967295+se+1),this[ue]=se>>>24,this[ue+1]=se>>>16,this[ue+2]=se>>>8,this[ue+3]=se&255,ue+4},B.prototype.writeBigInt64LE=qt(function(se,ue=0){return ht(this,se,ue,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),B.prototype.writeBigInt64BE=qt(function(se,ue=0){return xt(this,se,ue,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Ot(we,se,ue,xe,ke,Ke){if(ue+xe>we.length)throw new RangeError("Index out of range");if(ue<0)throw new RangeError("Index out of range")}function dt(we,se,ue,xe,ke){return se=+se,ue=ue>>>0,ke||Ot(we,se,ue,4),de.write(we,se,ue,xe,23,4),ue+4}B.prototype.writeFloatLE=function(se,ue,xe){return dt(this,se,ue,!0,xe)},B.prototype.writeFloatBE=function(se,ue,xe){return dt(this,se,ue,!1,xe)};function Rt(we,se,ue,xe,ke){return se=+se,ue=ue>>>0,ke||Ot(we,se,ue,8),de.write(we,se,ue,xe,52,8),ue+8}B.prototype.writeDoubleLE=function(se,ue,xe){return Rt(this,se,ue,!0,xe)},B.prototype.writeDoubleBE=function(se,ue,xe){return Rt(this,se,ue,!1,xe)},B.prototype.copy=function(se,ue,xe,ke){if(!B.isBuffer(se))throw new TypeError("argument should be a Buffer");if(xe||(xe=0),!ke&&ke!==0&&(ke=this.length),ue>=se.length&&(ue=se.length),ue||(ue=0),ke>0&&ke<xe&&(ke=xe),ke===xe||se.length===0||this.length===0)return 0;if(ue<0)throw new RangeError("targetStart out of bounds");if(xe<0||xe>=this.length)throw new RangeError("Index out of range");if(ke<0)throw new RangeError("sourceEnd out of bounds");ke>this.length&&(ke=this.length),se.length-ue<ke-xe&&(ke=se.length-ue+xe);const Ke=ke-xe;return this===se&&typeof Pe.prototype.copyWithin=="function"?this.copyWithin(ue,xe,ke):Pe.prototype.set.call(se,this.subarray(xe,ke),ue),Ke},B.prototype.fill=function(se,ue,xe,ke){if(typeof se=="string"){if(typeof ue=="string"?(ke=ue,ue=0,xe=this.length):typeof xe=="string"&&(ke=xe,xe=this.length),ke!==void 0&&typeof ke!="string")throw new TypeError("encoding must be a string");if(typeof ke=="string"&&!B.isEncoding(ke))throw new TypeError("Unknown encoding: "+ke);if(se.length===1){const We=se.charCodeAt(0);(ke==="utf8"&&We<128||ke==="latin1")&&(se=We)}}else typeof se=="number"?se=se&255:typeof se=="boolean"&&(se=Number(se));if(ue<0||this.length<ue||this.length<xe)throw new RangeError("Out of range index");if(xe<=ue)return this;ue=ue>>>0,xe=xe===void 0?this.length:xe>>>0,se||(se=0);let Ke;if(typeof se=="number")for(Ke=ue;Ke<xe;++Ke)this[Ke]=se;else{const We=B.isBuffer(se)?se:B.from(se,ke),ut=We.length;if(ut===0)throw new TypeError('The value "'+se+'" is invalid for argument "value"');for(Ke=0;Ke<xe-ue;++Ke)this[Ke+ue]=We[Ke%ut]}return this};const Nt={};function yt(we,se,ue){Nt[we]=class extends ue{constructor(){super(),Object.defineProperty(this,"message",{value:se.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${we}]`,this.stack,delete this.name}get code(){return we}set code(ke){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:ke,writable:!0})}toString(){return`${this.name} [${we}]: ${this.message}`}}}yt("ERR_BUFFER_OUT_OF_BOUNDS",function(we){return we?`${we} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),yt("ERR_INVALID_ARG_TYPE",function(we,se){return`The "${we}" argument must be of type number. Received type ${typeof se}`},TypeError),yt("ERR_OUT_OF_RANGE",function(we,se,ue){let xe=`The value of "${we}" is out of range.`,ke=ue;return Number.isInteger(ue)&&Math.abs(ue)>2**32?ke=zt(String(ue)):typeof ue=="bigint"&&(ke=String(ue),(ue>BigInt(2)**BigInt(32)||ue<-(BigInt(2)**BigInt(32)))&&(ke=zt(ke)),ke+="n"),xe+=` It must be ${se}. Received ${ke}`,xe},RangeError);function zt(we){let se="",ue=we.length;const xe=we[0]==="-"?1:0;for(;ue>=xe+4;ue-=3)se=`_${we.slice(ue-3,ue)}${se}`;return`${we.slice(0,ue)}${se}`}function Vt(we,se,ue){Ut(se,"offset"),(we[se]===void 0||we[se+ue]===void 0)&&Lt(se,we.length-(ue+1))}function vt(we,se,ue,xe,ke,Ke){if(we>ue||we<se){const We=typeof se=="bigint"?"n":"";let ut;throw se===0||se===BigInt(0)?ut=`>= 0${We} and < 2${We} ** ${(Ke+1)*8}${We}`:ut=`>= -(2${We} ** ${(Ke+1)*8-1}${We}) and < 2 ** ${(Ke+1)*8-1}${We}`,new Nt.ERR_OUT_OF_RANGE("value",ut,we)}Vt(xe,ke,Ke)}function Ut(we,se){if(typeof we!="number")throw new Nt.ERR_INVALID_ARG_TYPE(se,"number",we)}function Lt(we,se,ue){throw Math.floor(we)!==we?(Ut(we,ue),new Nt.ERR_OUT_OF_RANGE("offset","an integer",we)):se<0?new Nt.ERR_BUFFER_OUT_OF_BOUNDS:new Nt.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${se}`,we)}const wt=/[^+/0-9A-Za-z-_]/g;function Wt(we){if(we=we.split("=")[0],we=we.trim().replace(wt,""),we.length<2)return"";for(;we.length%4!==0;)we=we+"=";return we}function Gt(we,se){se=se||1/0;let ue;const xe=we.length;let ke=null;const Ke=[];for(let We=0;We<xe;++We){if(ue=we.charCodeAt(We),ue>55295&&ue<57344){if(!ke){if(ue>56319){(se-=3)>-1&&Ke.push(239,191,189);continue}else if(We+1===xe){(se-=3)>-1&&Ke.push(239,191,189);continue}ke=ue;continue}if(ue<56320){(se-=3)>-1&&Ke.push(239,191,189),ke=ue;continue}ue=(ke-55296<<10|ue-56320)+65536}else ke&&(se-=3)>-1&&Ke.push(239,191,189);if(ke=null,ue<128){if((se-=1)<0)break;Ke.push(ue)}else if(ue<2048){if((se-=2)<0)break;Ke.push(ue>>6|192,ue&63|128)}else if(ue<65536){if((se-=3)<0)break;Ke.push(ue>>12|224,ue>>6&63|128,ue&63|128)}else if(ue<1114112){if((se-=4)<0)break;Ke.push(ue>>18|240,ue>>12&63|128,ue>>6&63|128,ue&63|128)}else throw new Error("Invalid code point")}return Ke}function At(we){const se=[];for(let ue=0;ue<we.length;++ue)se.push(we.charCodeAt(ue)&255);return se}function tr(we,se){let ue,xe,ke;const Ke=[];for(let We=0;We<we.length&&!((se-=2)<0);++We)ue=we.charCodeAt(We),xe=ue>>8,ke=ue%256,Ke.push(ke),Ke.push(xe);return Ke}function Xt(we){return ae.toByteArray(Wt(we))}function bt(we,se,ue,xe){let ke;for(ke=0;ke<xe&&!(ke+ue>=se.length||ke>=we.length);++ke)se[ke+ue]=we[ke];return ke}function Bt(we,se){return we instanceof se||we!=null&&we.constructor!=null&&we.constructor.name!=null&&we.constructor.name===se.name}function Yt(we){return we!==we}const Tt=function(){const we="0123456789abcdef",se=new Array(256);for(let ue=0;ue<16;++ue){const xe=ue*16;for(let ke=0;ke<16;++ke)se[xe+ke]=we[ue]+we[ke]}return se}();function qt(we){return typeof BigInt>"u"?Jt:we}function Jt(){throw new Error("BigInt not supported")}})(u);const ie=u.Buffer;y.Buffer=u.Buffer,y.default=ie})(dist);const Buffer$C=getDefaultExportFromCjs$1(dist);/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(y,u){var h=dist,b=h.Buffer;function v(_,E){for(var S in _)E[S]=_[S]}b.from&&b.alloc&&b.allocUnsafe&&b.allocUnsafeSlow?y.exports=h:(v(h,u),u.Buffer=w);function w(_,E,S){return b(_,E,S)}w.prototype=Object.create(b.prototype),v(b,w),w.from=function(_,E,S){if(typeof _=="number")throw new TypeError("Argument must not be a number");return b(_,E,S)},w.alloc=function(_,E,S){if(typeof _!="number")throw new TypeError("Argument must be a number");var x=b(_);return E!==void 0?typeof S=="string"?x.fill(E,S):x.fill(E):x.fill(0),x},w.allocUnsafe=function(_){if(typeof _!="number")throw new TypeError("Argument must be a number");return b(_)},w.allocUnsafeSlow=function(_){if(typeof _!="number")throw new TypeError("Argument must be a number");return h.SlowBuffer(_)}})(safeBuffer$2,safeBuffer$2.exports);var safeBufferExports$1=safeBuffer$2.exports,MAX_BYTES=65536,MAX_UINT32=4294967295;function oldBrowser$1(){throw new Error(`Secure random number generation is not supported by this browser.
35
+ Use Chrome, Firefox or Internet Explorer 11`)}var Buffer$B=safeBufferExports$1.Buffer,crypto$3=commonjsGlobal.crypto||commonjsGlobal.msCrypto;crypto$3&&crypto$3.getRandomValues?browser$b.exports=randomBytes$2:browser$b.exports=oldBrowser$1;function randomBytes$2(y,u){if(y>MAX_UINT32)throw new RangeError("requested too many random bytes");var h=Buffer$B.allocUnsafe(y);if(y>0)if(y>MAX_BYTES)for(var b=0;b<y;b+=MAX_BYTES)crypto$3.getRandomValues(h.slice(b,b+MAX_BYTES));else crypto$3.getRandomValues(h);return typeof u=="function"?process$1.nextTick(function(){u(null,h)}):h}var browserExports=browser$b.exports,inherits_browser={exports:{}};typeof Object.create=="function"?inherits_browser.exports=function(u,h){h&&(u.super_=h,u.prototype=Object.create(h.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}))}:inherits_browser.exports=function(u,h){if(h){u.super_=h;var b=function(){};b.prototype=h.prototype,u.prototype=new b,u.prototype.constructor=u}};var inherits_browserExports=inherits_browser.exports,readableBrowser$1={exports:{}},events={exports:{}},R=typeof Reflect=="object"?Reflect:null,ReflectApply=R&&typeof R.apply=="function"?R.apply:function(u,h,b){return Function.prototype.apply.call(u,h,b)},ReflectOwnKeys;R&&typeof R.ownKeys=="function"?ReflectOwnKeys=R.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(u){return Object.getOwnPropertyNames(u).concat(Object.getOwnPropertySymbols(u))}:ReflectOwnKeys=function(u){return Object.getOwnPropertyNames(u)};function ProcessEmitWarning(y){console&&console.warn&&console.warn(y)}var NumberIsNaN=Number.isNaN||function(u){return u!==u};function EventEmitter$1(){EventEmitter$1.init.call(this)}events.exports=EventEmitter$1;events.exports.once=once$2;EventEmitter$1.EventEmitter=EventEmitter$1;EventEmitter$1.prototype._events=void 0;EventEmitter$1.prototype._eventsCount=0;EventEmitter$1.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(EventEmitter$1,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function(y){if(typeof y!="number"||y<0||NumberIsNaN(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");defaultMaxListeners=y}});EventEmitter$1.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};EventEmitter$1.prototype.setMaxListeners=function(u){if(typeof u!="number"||u<0||NumberIsNaN(u))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+u+".");return this._maxListeners=u,this};function _getMaxListeners(y){return y._maxListeners===void 0?EventEmitter$1.defaultMaxListeners:y._maxListeners}EventEmitter$1.prototype.getMaxListeners=function(){return _getMaxListeners(this)};EventEmitter$1.prototype.emit=function(u){for(var h=[],b=1;b<arguments.length;b++)h.push(arguments[b]);var v=u==="error",w=this._events;if(w!==void 0)v=v&&w.error===void 0;else if(!v)return!1;if(v){var _;if(h.length>0&&(_=h[0]),_ instanceof Error)throw _;var E=new Error("Unhandled error."+(_?" ("+_.message+")":""));throw E.context=_,E}var S=w[u];if(S===void 0)return!1;if(typeof S=="function")ReflectApply(S,this,h);else for(var x=S.length,T=arrayClone(S,x),b=0;b<x;++b)ReflectApply(T[b],this,h);return!0};function _addListener(y,u,h,b){var v,w,_;if(checkListener(h),w=y._events,w===void 0?(w=y._events=Object.create(null),y._eventsCount=0):(w.newListener!==void 0&&(y.emit("newListener",u,h.listener?h.listener:h),w=y._events),_=w[u]),_===void 0)_=w[u]=h,++y._eventsCount;else if(typeof _=="function"?_=w[u]=b?[h,_]:[_,h]:b?_.unshift(h):_.push(h),v=_getMaxListeners(y),v>0&&_.length>v&&!_.warned){_.warned=!0;var E=new Error("Possible EventEmitter memory leak detected. "+_.length+" "+String(u)+" listeners added. Use emitter.setMaxListeners() to increase limit");E.name="MaxListenersExceededWarning",E.emitter=y,E.type=u,E.count=_.length,ProcessEmitWarning(E)}return y}EventEmitter$1.prototype.addListener=function(u,h){return _addListener(this,u,h,!1)};EventEmitter$1.prototype.on=EventEmitter$1.prototype.addListener;EventEmitter$1.prototype.prependListener=function(u,h){return _addListener(this,u,h,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(y,u,h){var b={fired:!1,wrapFn:void 0,target:y,type:u,listener:h},v=onceWrapper.bind(b);return v.listener=h,b.wrapFn=v,v}EventEmitter$1.prototype.once=function(u,h){return checkListener(h),this.on(u,_onceWrap(this,u,h)),this};EventEmitter$1.prototype.prependOnceListener=function(u,h){return checkListener(h),this.prependListener(u,_onceWrap(this,u,h)),this};EventEmitter$1.prototype.removeListener=function(u,h){var b,v,w,_,E;if(checkListener(h),v=this._events,v===void 0)return this;if(b=v[u],b===void 0)return this;if(b===h||b.listener===h)--this._eventsCount===0?this._events=Object.create(null):(delete v[u],v.removeListener&&this.emit("removeListener",u,b.listener||h));else if(typeof b!="function"){for(w=-1,_=b.length-1;_>=0;_--)if(b[_]===h||b[_].listener===h){E=b[_].listener,w=_;break}if(w<0)return this;w===0?b.shift():spliceOne(b,w),b.length===1&&(v[u]=b[0]),v.removeListener!==void 0&&this.emit("removeListener",u,E||h)}return this};EventEmitter$1.prototype.off=EventEmitter$1.prototype.removeListener;EventEmitter$1.prototype.removeAllListeners=function(u){var h,b,v;if(b=this._events,b===void 0)return this;if(b.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):b[u]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete b[u]),this;if(arguments.length===0){var w=Object.keys(b),_;for(v=0;v<w.length;++v)_=w[v],_!=="removeListener"&&this.removeAllListeners(_);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(h=b[u],typeof h=="function")this.removeListener(u,h);else if(h!==void 0)for(v=h.length-1;v>=0;v--)this.removeListener(u,h[v]);return this};function _listeners(y,u,h){var b=y._events;if(b===void 0)return[];var v=b[u];return v===void 0?[]:typeof v=="function"?h?[v.listener||v]:[v]:h?unwrapListeners(v):arrayClone(v,v.length)}EventEmitter$1.prototype.listeners=function(u){return _listeners(this,u,!0)};EventEmitter$1.prototype.rawListeners=function(u){return _listeners(this,u,!1)};EventEmitter$1.listenerCount=function(y,u){return typeof y.listenerCount=="function"?y.listenerCount(u):listenerCount.call(y,u)};EventEmitter$1.prototype.listenerCount=listenerCount;function listenerCount(y){var u=this._events;if(u!==void 0){var h=u[y];if(typeof h=="function")return 1;if(h!==void 0)return h.length}return 0}EventEmitter$1.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(y,u){for(var h=new Array(u),b=0;b<u;++b)h[b]=y[b];return h}function spliceOne(y,u){for(;u+1<y.length;u++)y[u]=y[u+1];y.pop()}function unwrapListeners(y){for(var u=new Array(y.length),h=0;h<u.length;++h)u[h]=y[h].listener||y[h];return u}function once$2(y,u){return new Promise(function(h,b){function v(_){y.removeListener(u,w),b(_)}function w(){typeof y.removeListener=="function"&&y.removeListener("error",v),h([].slice.call(arguments))}eventTargetAgnosticAddListener(y,u,w,{once:!0}),u!=="error"&&addErrorHandlerIfEventEmitter(y,v,{once:!0})})}function addErrorHandlerIfEventEmitter(y,u,h){typeof y.on=="function"&&eventTargetAgnosticAddListener(y,"error",u,h)}function eventTargetAgnosticAddListener(y,u,h,b){if(typeof y.on=="function")b.once?y.once(u,h):y.on(u,h);else if(typeof y.addEventListener=="function")y.addEventListener(u,function v(w){b.once&&y.removeEventListener(u,v),h(w)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}var eventsExports=events.exports,streamBrowser$1=eventsExports.EventEmitter,util$b={},types$2={},shams$1=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var u={},h=Symbol("test"),b=Object(h);if(typeof h=="string"||Object.prototype.toString.call(h)!=="[object Symbol]"||Object.prototype.toString.call(b)!=="[object Symbol]")return!1;var v=42;u[h]=v;for(h in u)return!1;if(typeof Object.keys=="function"&&Object.keys(u).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(u).length!==0)return!1;var w=Object.getOwnPropertySymbols(u);if(w.length!==1||w[0]!==h||!Object.prototype.propertyIsEnumerable.call(u,h))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var _=Object.getOwnPropertyDescriptor(u,h);if(_.value!==v||_.enumerable!==!0)return!1}return!0},hasSymbols$2=shams$1,shams=function(){return hasSymbols$2()&&!!Symbol.toStringTag},esErrors=Error,_eval=EvalError,range=RangeError,ref=ReferenceError,syntax=SyntaxError,type$1=TypeError,uri=URIError,origSymbol=typeof Symbol<"u"&&Symbol,hasSymbolSham=shams$1,hasSymbols$1=function(){return typeof origSymbol!="function"||typeof Symbol!="function"||typeof origSymbol("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:hasSymbolSham()},test={__proto__:null,foo:{}},$Object=Object,hasProto$1=function(){return{__proto__:test}.foo===test.foo&&!(test instanceof $Object)},ERROR_MESSAGE="Function.prototype.bind called on incompatible ",toStr$3=Object.prototype.toString,max=Math.max,funcType="[object Function]",concatty=function(u,h){for(var b=[],v=0;v<u.length;v+=1)b[v]=u[v];for(var w=0;w<h.length;w+=1)b[w+u.length]=h[w];return b},slicy=function(u,h){for(var b=[],v=h,w=0;v<u.length;v+=1,w+=1)b[w]=u[v];return b},joiny=function(y,u){for(var h="",b=0;b<y.length;b+=1)h+=y[b],b+1<y.length&&(h+=u);return h},implementation$1=function(u){var h=this;if(typeof h!="function"||toStr$3.apply(h)!==funcType)throw new TypeError(ERROR_MESSAGE+h);for(var b=slicy(arguments,1),v,w=function(){if(this instanceof v){var T=h.apply(this,concatty(b,arguments));return Object(T)===T?T:this}return h.apply(u,concatty(b,arguments))},_=max(0,h.length-b.length),E=[],S=0;S<_;S++)E[S]="$"+S;if(v=Function("binder","return function ("+joiny(E,",")+"){ return binder.apply(this,arguments); }")(w),h.prototype){var x=function(){};x.prototype=h.prototype,v.prototype=new x,x.prototype=null}return v},implementation=implementation$1,functionBind=Function.prototype.bind||implementation,call$1=Function.prototype.call,$hasOwn=Object.prototype.hasOwnProperty,bind$1=functionBind,hasown=bind$1.call(call$1,$hasOwn),undefined$1,$Error=esErrors,$EvalError=_eval,$RangeError=range,$ReferenceError=ref,$SyntaxError$1=syntax,$TypeError$2=type$1,$URIError=uri,$Function=Function,getEvalledConstructor=function(y){try{return $Function('"use strict"; return ('+y+").constructor;")()}catch{}},$gOPD$1=Object.getOwnPropertyDescriptor;if($gOPD$1)try{$gOPD$1({},"")}catch{$gOPD$1=null}var throwTypeError=function(){throw new $TypeError$2},ThrowTypeError=$gOPD$1?function(){try{return arguments.callee,throwTypeError}catch{try{return $gOPD$1(arguments,"callee").get}catch{return throwTypeError}}}():throwTypeError,hasSymbols=hasSymbols$1(),hasProto=hasProto$1(),getProto$1=Object.getPrototypeOf||(hasProto?function(y){return y.__proto__}:null),needsEval={},TypedArray=typeof Uint8Array>"u"||!getProto$1?undefined$1:getProto$1(Uint8Array),INTRINSICS={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?undefined$1:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?undefined$1:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols&&getProto$1?getProto$1([][Symbol.iterator]()):undefined$1,"%AsyncFromSyncIteratorPrototype%":undefined$1,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":typeof Atomics>"u"?undefined$1:Atomics,"%BigInt%":typeof BigInt>"u"?undefined$1:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?undefined$1:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?undefined$1:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?undefined$1:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":$Error,"%eval%":eval,"%EvalError%":$EvalError,"%Float32Array%":typeof Float32Array>"u"?undefined$1:Float32Array,"%Float64Array%":typeof Float64Array>"u"?undefined$1:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?undefined$1:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":typeof Int8Array>"u"?undefined$1:Int8Array,"%Int16Array%":typeof Int16Array>"u"?undefined$1:Int16Array,"%Int32Array%":typeof Int32Array>"u"?undefined$1:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols&&getProto$1?getProto$1(getProto$1([][Symbol.iterator]())):undefined$1,"%JSON%":typeof JSON=="object"?JSON:undefined$1,"%Map%":typeof Map>"u"?undefined$1:Map,"%MapIteratorPrototype%":typeof Map>"u"||!hasSymbols||!getProto$1?undefined$1:getProto$1(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?undefined$1:Promise,"%Proxy%":typeof Proxy>"u"?undefined$1:Proxy,"%RangeError%":$RangeError,"%ReferenceError%":$ReferenceError,"%Reflect%":typeof Reflect>"u"?undefined$1:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?undefined$1:Set,"%SetIteratorPrototype%":typeof Set>"u"||!hasSymbols||!getProto$1?undefined$1:getProto$1(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?undefined$1:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols&&getProto$1?getProto$1(""[Symbol.iterator]()):undefined$1,"%Symbol%":hasSymbols?Symbol:undefined$1,"%SyntaxError%":$SyntaxError$1,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError$2,"%Uint8Array%":typeof Uint8Array>"u"?undefined$1:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?undefined$1:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?undefined$1:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?undefined$1:Uint32Array,"%URIError%":$URIError,"%WeakMap%":typeof WeakMap>"u"?undefined$1:WeakMap,"%WeakRef%":typeof WeakRef>"u"?undefined$1:WeakRef,"%WeakSet%":typeof WeakSet>"u"?undefined$1:WeakSet};if(getProto$1)try{null.error}catch(y){var errorProto=getProto$1(getProto$1(y));INTRINSICS["%Error.prototype%"]=errorProto}var doEval=function y(u){var h;if(u==="%AsyncFunction%")h=getEvalledConstructor("async function () {}");else if(u==="%GeneratorFunction%")h=getEvalledConstructor("function* () {}");else if(u==="%AsyncGeneratorFunction%")h=getEvalledConstructor("async function* () {}");else if(u==="%AsyncGenerator%"){var b=y("%AsyncGeneratorFunction%");b&&(h=b.prototype)}else if(u==="%AsyncIteratorPrototype%"){var v=y("%AsyncGenerator%");v&&getProto$1&&(h=getProto$1(v.prototype))}return INTRINSICS[u]=h,h},LEGACY_ALIASES={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=functionBind,hasOwn=hasown,$concat=bind.call(Function.call,Array.prototype.concat),$spliceApply=bind.call(Function.apply,Array.prototype.splice),$replace=bind.call(Function.call,String.prototype.replace),$strSlice=bind.call(Function.call,String.prototype.slice),$exec=bind.call(Function.call,RegExp.prototype.exec),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=function(u){var h=$strSlice(u,0,1),b=$strSlice(u,-1);if(h==="%"&&b!=="%")throw new $SyntaxError$1("invalid intrinsic syntax, expected closing `%`");if(b==="%"&&h!=="%")throw new $SyntaxError$1("invalid intrinsic syntax, expected opening `%`");var v=[];return $replace(u,rePropName,function(w,_,E,S){v[v.length]=E?$replace(S,reEscapeChar,"$1"):_||w}),v},getBaseIntrinsic=function(u,h){var b=u,v;if(hasOwn(LEGACY_ALIASES,b)&&(v=LEGACY_ALIASES[b],b="%"+v[0]+"%"),hasOwn(INTRINSICS,b)){var w=INTRINSICS[b];if(w===needsEval&&(w=doEval(b)),typeof w>"u"&&!h)throw new $TypeError$2("intrinsic "+u+" exists, but is not available. Please file an issue!");return{alias:v,name:b,value:w}}throw new $SyntaxError$1("intrinsic "+u+" does not exist!")},getIntrinsic=function(u,h){if(typeof u!="string"||u.length===0)throw new $TypeError$2("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof h!="boolean")throw new $TypeError$2('"allowMissing" argument must be a boolean');if($exec(/^%?[^%]*%?$/,u)===null)throw new $SyntaxError$1("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var b=stringToPath(u),v=b.length>0?b[0]:"",w=getBaseIntrinsic("%"+v+"%",h),_=w.name,E=w.value,S=!1,x=w.alias;x&&(v=x[0],$spliceApply(b,$concat([0,1],x)));for(var T=1,C=!0;T<b.length;T+=1){var O=b[T],D=$strSlice(O,0,1),U=$strSlice(O,-1);if((D==='"'||D==="'"||D==="`"||U==='"'||U==="'"||U==="`")&&D!==U)throw new $SyntaxError$1("property names with quotes must have matching quotes");if((O==="constructor"||!C)&&(S=!0),v+="."+O,_="%"+v+"%",hasOwn(INTRINSICS,_))E=INTRINSICS[_];else if(E!=null){if(!(O in E)){if(!h)throw new $TypeError$2("base intrinsic for "+u+" exists, but the property is not available.");return}if($gOPD$1&&T+1>=b.length){var te=$gOPD$1(E,O);C=!!te,C&&"get"in te&&!("originalValue"in te.get)?E=te.get:E=E[O]}else C=hasOwn(E,O),E=E[O];C&&!S&&(INTRINSICS[_]=E)}}return E},callBind$2={exports:{}},esDefineProperty,hasRequiredEsDefineProperty;function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var y=getIntrinsic,u=y("%Object.defineProperty%",!0)||!1;if(u)try{u({},"a",{value:1})}catch{u=!1}return esDefineProperty=u,esDefineProperty}var GetIntrinsic$2=getIntrinsic,$gOPD=GetIntrinsic$2("%Object.getOwnPropertyDescriptor%",!0);if($gOPD)try{$gOPD([],"length")}catch{$gOPD=null}var gopd$1=$gOPD,$defineProperty$1=requireEsDefineProperty(),$SyntaxError=syntax,$TypeError$1=type$1,gopd=gopd$1,defineDataProperty=function(u,h,b){if(!u||typeof u!="object"&&typeof u!="function")throw new $TypeError$1("`obj` must be an object or a function`");if(typeof h!="string"&&typeof h!="symbol")throw new $TypeError$1("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new $TypeError$1("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new $TypeError$1("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new $TypeError$1("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new $TypeError$1("`loose`, if provided, must be a boolean");var v=arguments.length>3?arguments[3]:null,w=arguments.length>4?arguments[4]:null,_=arguments.length>5?arguments[5]:null,E=arguments.length>6?arguments[6]:!1,S=!!gopd&&gopd(u,h);if($defineProperty$1)$defineProperty$1(u,h,{configurable:_===null&&S?S.configurable:!_,enumerable:v===null&&S?S.enumerable:!v,value:b,writable:w===null&&S?S.writable:!w});else if(E||!v&&!w&&!_)u[h]=b;else throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},$defineProperty=requireEsDefineProperty(),hasPropertyDescriptors=function(){return!!$defineProperty};hasPropertyDescriptors.hasArrayLengthDefineBug=function(){if(!$defineProperty)return null;try{return $defineProperty([],"length",{value:1}).length!==1}catch{return!0}};var hasPropertyDescriptors_1=hasPropertyDescriptors,GetIntrinsic$1=getIntrinsic,define=defineDataProperty,hasDescriptors=hasPropertyDescriptors_1(),gOPD$1=gopd$1,$TypeError=type$1,$floor=GetIntrinsic$1("%Math.floor%"),setFunctionLength=function(u,h){if(typeof u!="function")throw new $TypeError("`fn` is not a function");if(typeof h!="number"||h<0||h>4294967295||$floor(h)!==h)throw new $TypeError("`length` must be a positive 32-bit integer");var b=arguments.length>2&&!!arguments[2],v=!0,w=!0;if("length"in u&&gOPD$1){var _=gOPD$1(u,"length");_&&!_.configurable&&(v=!1),_&&!_.writable&&(w=!1)}return(v||w||!b)&&(hasDescriptors?define(u,"length",h,!0,!0):define(u,"length",h)),u};(function(y){var u=functionBind,h=getIntrinsic,b=setFunctionLength,v=type$1,w=h("%Function.prototype.apply%"),_=h("%Function.prototype.call%"),E=h("%Reflect.apply%",!0)||u.call(_,w),S=requireEsDefineProperty(),x=h("%Math.max%");y.exports=function(O){if(typeof O!="function")throw new v("a function is required");var D=E(u,_,arguments);return b(D,1+x(0,O.length-(arguments.length-1)),!0)};var T=function(){return E(u,w,arguments)};S?S(y.exports,"apply",{value:T}):y.exports.apply=T})(callBind$2);var callBindExports=callBind$2.exports,GetIntrinsic=getIntrinsic,callBind$1=callBindExports,$indexOf$1=callBind$1(GetIntrinsic("String.prototype.indexOf")),callBound$2=function(u,h){var b=GetIntrinsic(u,!!h);return typeof b=="function"&&$indexOf$1(u,".prototype.")>-1?callBind$1(b):b},hasToStringTag$3=shams(),callBound$1=callBound$2,$toString$1=callBound$1("Object.prototype.toString"),isStandardArguments=function(u){return hasToStringTag$3&&u&&typeof u=="object"&&Symbol.toStringTag in u?!1:$toString$1(u)==="[object Arguments]"},isLegacyArguments=function(u){return isStandardArguments(u)?!0:u!==null&&typeof u=="object"&&typeof u.length=="number"&&u.length>=0&&$toString$1(u)!=="[object Array]"&&$toString$1(u.callee)==="[object Function]"},supportsStandardArguments=function(){return isStandardArguments(arguments)}();isStandardArguments.isLegacyArguments=isLegacyArguments;var isArguments=supportsStandardArguments?isStandardArguments:isLegacyArguments,toStr$2=Object.prototype.toString,fnToStr$1=Function.prototype.toString,isFnRegex=/^\s*(?:function)?\*/,hasToStringTag$2=shams(),getProto=Object.getPrototypeOf,getGeneratorFunc=function(){if(!hasToStringTag$2)return!1;try{return Function("return function*() {}")()}catch{}},GeneratorFunction,isGeneratorFunction=function(u){if(typeof u!="function")return!1;if(isFnRegex.test(fnToStr$1.call(u)))return!0;if(!hasToStringTag$2){var h=toStr$2.call(u);return h==="[object GeneratorFunction]"}if(!getProto)return!1;if(typeof GeneratorFunction>"u"){var b=getGeneratorFunc();GeneratorFunction=b?getProto(b):!1}return getProto(u)===GeneratorFunction},fnToStr=Function.prototype.toString,reflectApply=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,badArrayLike,isCallableMarker;if(typeof reflectApply=="function"&&typeof Object.defineProperty=="function")try{badArrayLike=Object.defineProperty({},"length",{get:function(){throw isCallableMarker}}),isCallableMarker={},reflectApply(function(){throw 42},null,badArrayLike)}catch(y){y!==isCallableMarker&&(reflectApply=null)}else reflectApply=null;var constructorRegex=/^\s*class\b/,isES6ClassFn=function(u){try{var h=fnToStr.call(u);return constructorRegex.test(h)}catch{return!1}},tryFunctionObject=function(u){try{return isES6ClassFn(u)?!1:(fnToStr.call(u),!0)}catch{return!1}},toStr$1=Object.prototype.toString,objectClass="[object Object]",fnClass="[object Function]",genClass="[object GeneratorFunction]",ddaClass="[object HTMLAllCollection]",ddaClass2="[object HTML document.all class]",ddaClass3="[object HTMLCollection]",hasToStringTag$1=typeof Symbol=="function"&&!!Symbol.toStringTag,isIE68=!(0 in[,]),isDDA=function(){return!1};if(typeof document=="object"){var all=document.all;toStr$1.call(all)===toStr$1.call(document.all)&&(isDDA=function(u){if((isIE68||!u)&&(typeof u>"u"||typeof u=="object"))try{var h=toStr$1.call(u);return(h===ddaClass||h===ddaClass2||h===ddaClass3||h===objectClass)&&u("")==null}catch{}return!1})}var isCallable$1=reflectApply?function(u){if(isDDA(u))return!0;if(!u||typeof u!="function"&&typeof u!="object")return!1;try{reflectApply(u,null,badArrayLike)}catch(h){if(h!==isCallableMarker)return!1}return!isES6ClassFn(u)&&tryFunctionObject(u)}:function(u){if(isDDA(u))return!0;if(!u||typeof u!="function"&&typeof u!="object")return!1;if(hasToStringTag$1)return tryFunctionObject(u);if(isES6ClassFn(u))return!1;var h=toStr$1.call(u);return h!==fnClass&&h!==genClass&&!/^\[object HTML/.test(h)?!1:tryFunctionObject(u)},isCallable=isCallable$1,toStr=Object.prototype.toString,hasOwnProperty=Object.prototype.hasOwnProperty,forEachArray=function(u,h,b){for(var v=0,w=u.length;v<w;v++)hasOwnProperty.call(u,v)&&(b==null?h(u[v],v,u):h.call(b,u[v],v,u))},forEachString=function(u,h,b){for(var v=0,w=u.length;v<w;v++)b==null?h(u.charAt(v),v,u):h.call(b,u.charAt(v),v,u)},forEachObject=function(u,h,b){for(var v in u)hasOwnProperty.call(u,v)&&(b==null?h(u[v],v,u):h.call(b,u[v],v,u))},forEach$1=function(u,h,b){if(!isCallable(h))throw new TypeError("iterator must be a function");var v;arguments.length>=3&&(v=b),toStr.call(u)==="[object Array]"?forEachArray(u,h,v):typeof u=="string"?forEachString(u,h,v):forEachObject(u,h,v)},forEach_1=forEach$1,possibleTypedArrayNames=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],possibleNames=possibleTypedArrayNames,g$1=typeof globalThis>"u"?commonjsGlobal:globalThis,availableTypedArrays$1=function(){for(var u=[],h=0;h<possibleNames.length;h++)typeof g$1[possibleNames[h]]=="function"&&(u[u.length]=possibleNames[h]);return u},forEach=forEach_1,availableTypedArrays=availableTypedArrays$1,callBind=callBindExports,callBound=callBound$2,gOPD=gopd$1,$toString=callBound("Object.prototype.toString"),hasToStringTag=shams(),g=typeof globalThis>"u"?commonjsGlobal:globalThis,typedArrays=availableTypedArrays(),$slice=callBound("String.prototype.slice"),getPrototypeOf=Object.getPrototypeOf,$indexOf=callBound("Array.prototype.indexOf",!0)||function(u,h){for(var b=0;b<u.length;b+=1)if(u[b]===h)return b;return-1},cache={__proto__:null};hasToStringTag&&gOPD&&getPrototypeOf?forEach(typedArrays,function(y){var u=new g[y];if(Symbol.toStringTag in u){var h=getPrototypeOf(u),b=gOPD(h,Symbol.toStringTag);if(!b){var v=getPrototypeOf(h);b=gOPD(v,Symbol.toStringTag)}cache["$"+y]=callBind(b.get)}}):forEach(typedArrays,function(y){var u=new g[y],h=u.slice||u.set;h&&(cache["$"+y]=callBind(h))});var tryTypedArrays=function(u){var h=!1;return forEach(cache,function(b,v){if(!h)try{"$"+b(u)===v&&(h=$slice(v,1))}catch{}}),h},trySlices=function(u){var h=!1;return forEach(cache,function(b,v){if(!h)try{b(u),h=$slice(v,1)}catch{}}),h},whichTypedArray$1=function(u){if(!u||typeof u!="object")return!1;if(!hasToStringTag){var h=$slice($toString(u),8,-1);return $indexOf(typedArrays,h)>-1?h:h!=="Object"?!1:trySlices(u)}return gOPD?tryTypedArrays(u):null},whichTypedArray=whichTypedArray$1,isTypedArray=function(u){return!!whichTypedArray(u)};(function(y){var u=isArguments,h=isGeneratorFunction,b=whichTypedArray$1,v=isTypedArray;function w(Fe){return Fe.call.bind(Fe)}var _=typeof BigInt<"u",E=typeof Symbol<"u",S=w(Object.prototype.toString),x=w(Number.prototype.valueOf),T=w(String.prototype.valueOf),C=w(Boolean.prototype.valueOf);if(_)var O=w(BigInt.prototype.valueOf);if(E)var D=w(Symbol.prototype.valueOf);function U(Fe,nt){if(typeof Fe!="object")return!1;try{return nt(Fe),!0}catch{return!1}}y.isArgumentsObject=u,y.isGeneratorFunction=h,y.isTypedArray=v;function te(Fe){return typeof Promise<"u"&&Fe instanceof Promise||Fe!==null&&typeof Fe=="object"&&typeof Fe.then=="function"&&typeof Fe.catch=="function"}y.isPromise=te;function X(Fe){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(Fe):v(Fe)||he(Fe)}y.isArrayBufferView=X;function ie(Fe){return b(Fe)==="Uint8Array"}y.isUint8Array=ie;function ee(Fe){return b(Fe)==="Uint8ClampedArray"}y.isUint8ClampedArray=ee;function ae(Fe){return b(Fe)==="Uint16Array"}y.isUint16Array=ae;function de(Fe){return b(Fe)==="Uint32Array"}y.isUint32Array=de;function Se(Fe){return b(Fe)==="Int8Array"}y.isInt8Array=Se;function ve(Fe){return b(Fe)==="Int16Array"}y.isInt16Array=ve;function Pe(Fe){return b(Fe)==="Int32Array"}y.isInt32Array=Pe;function Ie(Fe){return b(Fe)==="Float32Array"}y.isFloat32Array=Ie;function Ee(Fe){return b(Fe)==="Float64Array"}y.isFloat64Array=Ee;function De(Fe){return b(Fe)==="BigInt64Array"}y.isBigInt64Array=De;function be(Fe){return b(Fe)==="BigUint64Array"}y.isBigUint64Array=be;function B(Fe){return S(Fe)==="[object Map]"}B.working=typeof Map<"u"&&B(new Map);function F(Fe){return typeof Map>"u"?!1:B.working?B(Fe):Fe instanceof Map}y.isMap=F;function M(Fe){return S(Fe)==="[object Set]"}M.working=typeof Set<"u"&&M(new Set);function N(Fe){return typeof Set>"u"?!1:M.working?M(Fe):Fe instanceof Set}y.isSet=N;function Q(Fe){return S(Fe)==="[object WeakMap]"}Q.working=typeof WeakMap<"u"&&Q(new WeakMap);function j(Fe){return typeof WeakMap>"u"?!1:Q.working?Q(Fe):Fe instanceof WeakMap}y.isWeakMap=j;function ne(Fe){return S(Fe)==="[object WeakSet]"}ne.working=typeof WeakSet<"u"&&ne(new WeakSet);function J(Fe){return ne(Fe)}y.isWeakSet=J;function q(Fe){return S(Fe)==="[object ArrayBuffer]"}q.working=typeof ArrayBuffer<"u"&&q(new ArrayBuffer);function re(Fe){return typeof ArrayBuffer>"u"?!1:q.working?q(Fe):Fe instanceof ArrayBuffer}y.isArrayBuffer=re;function H(Fe){return S(Fe)==="[object DataView]"}H.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&H(new DataView(new ArrayBuffer(1),0,1));function he(Fe){return typeof DataView>"u"?!1:H.working?H(Fe):Fe instanceof DataView}y.isDataView=he;var Oe=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function Ne(Fe){return S(Fe)==="[object SharedArrayBuffer]"}function Ae(Fe){return typeof Oe>"u"?!1:(typeof Ne.working>"u"&&(Ne.working=Ne(new Oe)),Ne.working?Ne(Fe):Fe instanceof Oe)}y.isSharedArrayBuffer=Ae;function le(Fe){return S(Fe)==="[object AsyncFunction]"}y.isAsyncFunction=le;function me(Fe){return S(Fe)==="[object Map Iterator]"}y.isMapIterator=me;function Me(Fe){return S(Fe)==="[object Set Iterator]"}y.isSetIterator=Me;function fe(Fe){return S(Fe)==="[object Generator]"}y.isGeneratorObject=fe;function ge(Fe){return S(Fe)==="[object WebAssembly.Module]"}y.isWebAssemblyCompiledModule=ge;function ce(Fe){return U(Fe,x)}y.isNumberObject=ce;function _e(Fe){return U(Fe,T)}y.isStringObject=_e;function Re(Fe){return U(Fe,C)}y.isBooleanObject=Re;function Ue(Fe){return _&&U(Fe,O)}y.isBigIntObject=Ue;function qe(Fe){return E&&U(Fe,D)}y.isSymbolObject=qe;function Ze(Fe){return ce(Fe)||_e(Fe)||Re(Fe)||Ue(Fe)||qe(Fe)}y.isBoxedPrimitive=Ze;function tt(Fe){return typeof Uint8Array<"u"&&(re(Fe)||Ae(Fe))}y.isAnyArrayBuffer=tt,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(Fe){Object.defineProperty(y,Fe,{enumerable:!1,value:function(){throw new Error(Fe+" is not supported in userland")}})})})(types$2);var isBufferBrowser=function(u){return u&&typeof u=="object"&&typeof u.copy=="function"&&typeof u.fill=="function"&&typeof u.readUInt8=="function"};(function(y){var u=Object.getOwnPropertyDescriptors||function(he){for(var Oe=Object.keys(he),Ne={},Ae=0;Ae<Oe.length;Ae++)Ne[Oe[Ae]]=Object.getOwnPropertyDescriptor(he,Oe[Ae]);return Ne},h=/%[sdj%]/g;y.format=function(H){if(!Se(H)){for(var he=[],Oe=0;Oe<arguments.length;Oe++)he.push(_(arguments[Oe]));return he.join(" ")}for(var Oe=1,Ne=arguments,Ae=Ne.length,le=String(H).replace(h,function(Me){if(Me==="%%")return"%";if(Oe>=Ae)return Me;switch(Me){case"%s":return String(Ne[Oe++]);case"%d":return Number(Ne[Oe++]);case"%j":try{return JSON.stringify(Ne[Oe++])}catch{return"[Circular]"}default:return Me}}),me=Ne[Oe];Oe<Ae;me=Ne[++Oe])ee(me)||!Ee(me)?le+=" "+me:le+=" "+_(me);return le},y.deprecate=function(H,he){if(typeof process$1<"u"&&process$1.noDeprecation===!0)return H;if(typeof process$1>"u")return function(){return y.deprecate(H,he).apply(this,arguments)};var Oe=!1;function Ne(){if(!Oe){if(process$1.throwDeprecation)throw new Error(he);process$1.traceDeprecation?console.trace(he):console.error(he),Oe=!0}return H.apply(this,arguments)}return Ne};var b={},v=/^$/;if(process$1.env.NODE_DEBUG){var w=process$1.env.NODE_DEBUG;w=w.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),v=new RegExp("^"+w+"$","i")}y.debuglog=function(H){if(H=H.toUpperCase(),!b[H])if(v.test(H)){var he=process$1.pid;b[H]=function(){var Oe=y.format.apply(y,arguments);console.error("%s %d: %s",H,he,Oe)}}else b[H]=function(){};return b[H]};function _(H,he){var Oe={seen:[],stylize:S};return arguments.length>=3&&(Oe.depth=arguments[2]),arguments.length>=4&&(Oe.colors=arguments[3]),ie(he)?Oe.showHidden=he:he&&y._extend(Oe,he),Pe(Oe.showHidden)&&(Oe.showHidden=!1),Pe(Oe.depth)&&(Oe.depth=2),Pe(Oe.colors)&&(Oe.colors=!1),Pe(Oe.customInspect)&&(Oe.customInspect=!0),Oe.colors&&(Oe.stylize=E),T(Oe,H,Oe.depth)}y.inspect=_,_.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},_.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function E(H,he){var Oe=_.styles[he];return Oe?"\x1B["+_.colors[Oe][0]+"m"+H+"\x1B["+_.colors[Oe][1]+"m":H}function S(H,he){return H}function x(H){var he={};return H.forEach(function(Oe,Ne){he[Oe]=!0}),he}function T(H,he,Oe){if(H.customInspect&&he&&B(he.inspect)&&he.inspect!==y.inspect&&!(he.constructor&&he.constructor.prototype===he)){var Ne=he.inspect(Oe,H);return Se(Ne)||(Ne=T(H,Ne,Oe)),Ne}var Ae=C(H,he);if(Ae)return Ae;var le=Object.keys(he),me=x(le);if(H.showHidden&&(le=Object.getOwnPropertyNames(he)),be(he)&&(le.indexOf("message")>=0||le.indexOf("description")>=0))return O(he);if(le.length===0){if(B(he)){var Me=he.name?": "+he.name:"";return H.stylize("[Function"+Me+"]","special")}if(Ie(he))return H.stylize(RegExp.prototype.toString.call(he),"regexp");if(De(he))return H.stylize(Date.prototype.toString.call(he),"date");if(be(he))return O(he)}var fe="",ge=!1,ce=["{","}"];if(X(he)&&(ge=!0,ce=["[","]"]),B(he)){var _e=he.name?": "+he.name:"";fe=" [Function"+_e+"]"}if(Ie(he)&&(fe=" "+RegExp.prototype.toString.call(he)),De(he)&&(fe=" "+Date.prototype.toUTCString.call(he)),be(he)&&(fe=" "+O(he)),le.length===0&&(!ge||he.length==0))return ce[0]+fe+ce[1];if(Oe<0)return Ie(he)?H.stylize(RegExp.prototype.toString.call(he),"regexp"):H.stylize("[Object]","special");H.seen.push(he);var Re;return ge?Re=D(H,he,Oe,me,le):Re=le.map(function(Ue){return U(H,he,Oe,me,Ue,ge)}),H.seen.pop(),te(Re,fe,ce)}function C(H,he){if(Pe(he))return H.stylize("undefined","undefined");if(Se(he)){var Oe="'"+JSON.stringify(he).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return H.stylize(Oe,"string")}if(de(he))return H.stylize(""+he,"number");if(ie(he))return H.stylize(""+he,"boolean");if(ee(he))return H.stylize("null","null")}function O(H){return"["+Error.prototype.toString.call(H)+"]"}function D(H,he,Oe,Ne,Ae){for(var le=[],me=0,Me=he.length;me<Me;++me)ne(he,String(me))?le.push(U(H,he,Oe,Ne,String(me),!0)):le.push("");return Ae.forEach(function(fe){fe.match(/^\d+$/)||le.push(U(H,he,Oe,Ne,fe,!0))}),le}function U(H,he,Oe,Ne,Ae,le){var me,Me,fe;if(fe=Object.getOwnPropertyDescriptor(he,Ae)||{value:he[Ae]},fe.get?fe.set?Me=H.stylize("[Getter/Setter]","special"):Me=H.stylize("[Getter]","special"):fe.set&&(Me=H.stylize("[Setter]","special")),ne(Ne,Ae)||(me="["+Ae+"]"),Me||(H.seen.indexOf(fe.value)<0?(ee(Oe)?Me=T(H,fe.value,null):Me=T(H,fe.value,Oe-1),Me.indexOf(`
36
+ `)>-1&&(le?Me=Me.split(`
37
+ `).map(function(ge){return" "+ge}).join(`
38
+ `).slice(2):Me=`
39
+ `+Me.split(`
40
+ `).map(function(ge){return" "+ge}).join(`
41
+ `))):Me=H.stylize("[Circular]","special")),Pe(me)){if(le&&Ae.match(/^\d+$/))return Me;me=JSON.stringify(""+Ae),me.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(me=me.slice(1,-1),me=H.stylize(me,"name")):(me=me.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),me=H.stylize(me,"string"))}return me+": "+Me}function te(H,he,Oe){var Ne=H.reduce(function(Ae,le){return le.indexOf(`
42
+ `)>=0,Ae+le.replace(/\u001b\[\d\d?m/g,"").length+1},0);return Ne>60?Oe[0]+(he===""?"":he+`
43
+ `)+" "+H.join(`,
44
+ `)+" "+Oe[1]:Oe[0]+he+" "+H.join(", ")+" "+Oe[1]}y.types=types$2;function X(H){return Array.isArray(H)}y.isArray=X;function ie(H){return typeof H=="boolean"}y.isBoolean=ie;function ee(H){return H===null}y.isNull=ee;function ae(H){return H==null}y.isNullOrUndefined=ae;function de(H){return typeof H=="number"}y.isNumber=de;function Se(H){return typeof H=="string"}y.isString=Se;function ve(H){return typeof H=="symbol"}y.isSymbol=ve;function Pe(H){return H===void 0}y.isUndefined=Pe;function Ie(H){return Ee(H)&&M(H)==="[object RegExp]"}y.isRegExp=Ie,y.types.isRegExp=Ie;function Ee(H){return typeof H=="object"&&H!==null}y.isObject=Ee;function De(H){return Ee(H)&&M(H)==="[object Date]"}y.isDate=De,y.types.isDate=De;function be(H){return Ee(H)&&(M(H)==="[object Error]"||H instanceof Error)}y.isError=be,y.types.isNativeError=be;function B(H){return typeof H=="function"}y.isFunction=B;function F(H){return H===null||typeof H=="boolean"||typeof H=="number"||typeof H=="string"||typeof H=="symbol"||typeof H>"u"}y.isPrimitive=F,y.isBuffer=isBufferBrowser;function M(H){return Object.prototype.toString.call(H)}function N(H){return H<10?"0"+H.toString(10):H.toString(10)}var Q=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function j(){var H=new Date,he=[N(H.getHours()),N(H.getMinutes()),N(H.getSeconds())].join(":");return[H.getDate(),Q[H.getMonth()],he].join(" ")}y.log=function(){console.log("%s - %s",j(),y.format.apply(y,arguments))},y.inherits=inherits_browserExports,y._extend=function(H,he){if(!he||!Ee(he))return H;for(var Oe=Object.keys(he),Ne=Oe.length;Ne--;)H[Oe[Ne]]=he[Oe[Ne]];return H};function ne(H,he){return Object.prototype.hasOwnProperty.call(H,he)}var J=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;y.promisify=function(he){if(typeof he!="function")throw new TypeError('The "original" argument must be of type Function');if(J&&he[J]){var Oe=he[J];if(typeof Oe!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(Oe,J,{value:Oe,enumerable:!1,writable:!1,configurable:!0}),Oe}function Oe(){for(var Ne,Ae,le=new Promise(function(fe,ge){Ne=fe,Ae=ge}),me=[],Me=0;Me<arguments.length;Me++)me.push(arguments[Me]);me.push(function(fe,ge){fe?Ae(fe):Ne(ge)});try{he.apply(this,me)}catch(fe){Ae(fe)}return le}return Object.setPrototypeOf(Oe,Object.getPrototypeOf(he)),J&&Object.defineProperty(Oe,J,{value:Oe,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(Oe,u(he))},y.promisify.custom=J;function q(H,he){if(!H){var Oe=new Error("Promise was rejected with a falsy value");Oe.reason=H,H=Oe}return he(H)}function re(H){if(typeof H!="function")throw new TypeError('The "original" argument must be of type Function');function he(){for(var Oe=[],Ne=0;Ne<arguments.length;Ne++)Oe.push(arguments[Ne]);var Ae=Oe.pop();if(typeof Ae!="function")throw new TypeError("The last argument must be of type Function");var le=this,me=function(){return Ae.apply(le,arguments)};H.apply(this,Oe).then(function(Me){process$1.nextTick(me.bind(null,null,Me))},function(Me){process$1.nextTick(q.bind(null,Me,me))})}return Object.setPrototypeOf(he,Object.getPrototypeOf(H)),Object.defineProperties(he,u(H)),he}y.callbackify=re})(util$b);var buffer_list,hasRequiredBuffer_list;function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;hasRequiredBuffer_list=1;function y(U,te){var X=Object.keys(U);if(Object.getOwnPropertySymbols){var ie=Object.getOwnPropertySymbols(U);te&&(ie=ie.filter(function(ee){return Object.getOwnPropertyDescriptor(U,ee).enumerable})),X.push.apply(X,ie)}return X}function u(U){for(var te=1;te<arguments.length;te++){var X=arguments[te]!=null?arguments[te]:{};te%2?y(Object(X),!0).forEach(function(ie){h(U,ie,X[ie])}):Object.getOwnPropertyDescriptors?Object.defineProperties(U,Object.getOwnPropertyDescriptors(X)):y(Object(X)).forEach(function(ie){Object.defineProperty(U,ie,Object.getOwnPropertyDescriptor(X,ie))})}return U}function h(U,te,X){return te=_(te),te in U?Object.defineProperty(U,te,{value:X,enumerable:!0,configurable:!0,writable:!0}):U[te]=X,U}function b(U,te){if(!(U instanceof te))throw new TypeError("Cannot call a class as a function")}function v(U,te){for(var X=0;X<te.length;X++){var ie=te[X];ie.enumerable=ie.enumerable||!1,ie.configurable=!0,"value"in ie&&(ie.writable=!0),Object.defineProperty(U,_(ie.key),ie)}}function w(U,te,X){return te&&v(U.prototype,te),Object.defineProperty(U,"prototype",{writable:!1}),U}function _(U){var te=E(U,"string");return typeof te=="symbol"?te:String(te)}function E(U,te){if(typeof U!="object"||U===null)return U;var X=U[Symbol.toPrimitive];if(X!==void 0){var ie=X.call(U,te||"default");if(typeof ie!="object")return ie;throw new TypeError("@@toPrimitive must return a primitive value.")}return(te==="string"?String:Number)(U)}var S=dist,x=S.Buffer,T=util$b,C=T.inspect,O=C&&C.custom||"inspect";function D(U,te,X){x.prototype.copy.call(U,te,X)}return buffer_list=function(){function U(){b(this,U),this.head=null,this.tail=null,this.length=0}return w(U,[{key:"push",value:function(X){var ie={data:X,next:null};this.length>0?this.tail.next=ie:this.head=ie,this.tail=ie,++this.length}},{key:"unshift",value:function(X){var ie={data:X,next:this.head};this.length===0&&(this.tail=ie),this.head=ie,++this.length}},{key:"shift",value:function(){if(this.length!==0){var X=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,X}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(X){if(this.length===0)return"";for(var ie=this.head,ee=""+ie.data;ie=ie.next;)ee+=X+ie.data;return ee}},{key:"concat",value:function(X){if(this.length===0)return x.alloc(0);for(var ie=x.allocUnsafe(X>>>0),ee=this.head,ae=0;ee;)D(ee.data,ie,ae),ae+=ee.data.length,ee=ee.next;return ie}},{key:"consume",value:function(X,ie){var ee;return X<this.head.data.length?(ee=this.head.data.slice(0,X),this.head.data=this.head.data.slice(X)):X===this.head.data.length?ee=this.shift():ee=ie?this._getString(X):this._getBuffer(X),ee}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(X){var ie=this.head,ee=1,ae=ie.data;for(X-=ae.length;ie=ie.next;){var de=ie.data,Se=X>de.length?de.length:X;if(Se===de.length?ae+=de:ae+=de.slice(0,X),X-=Se,X===0){Se===de.length?(++ee,ie.next?this.head=ie.next:this.head=this.tail=null):(this.head=ie,ie.data=de.slice(Se));break}++ee}return this.length-=ee,ae}},{key:"_getBuffer",value:function(X){var ie=x.allocUnsafe(X),ee=this.head,ae=1;for(ee.data.copy(ie),X-=ee.data.length;ee=ee.next;){var de=ee.data,Se=X>de.length?de.length:X;if(de.copy(ie,ie.length-X,0,Se),X-=Se,X===0){Se===de.length?(++ae,ee.next?this.head=ee.next:this.head=this.tail=null):(this.head=ee,ee.data=de.slice(Se));break}++ae}return this.length-=ae,ie}},{key:O,value:function(X,ie){return C(this,u(u({},ie),{},{depth:0,customInspect:!1}))}}]),U}(),buffer_list}function destroy$1(y,u){var h=this,b=this._readableState&&this._readableState.destroyed,v=this._writableState&&this._writableState.destroyed;return b||v?(u?u(y):y&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process$1.nextTick(emitErrorNT$1,this,y)):process$1.nextTick(emitErrorNT$1,this,y)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(y||null,function(w){!u&&w?h._writableState?h._writableState.errorEmitted?process$1.nextTick(emitCloseNT,h):(h._writableState.errorEmitted=!0,process$1.nextTick(emitErrorAndCloseNT,h,w)):process$1.nextTick(emitErrorAndCloseNT,h,w):u?(process$1.nextTick(emitCloseNT,h),u(w)):process$1.nextTick(emitCloseNT,h)}),this)}function emitErrorAndCloseNT(y,u){emitErrorNT$1(y,u),emitCloseNT(y)}function emitCloseNT(y){y._writableState&&!y._writableState.emitClose||y._readableState&&!y._readableState.emitClose||y.emit("close")}function undestroy$1(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT$1(y,u){y.emit("error",u)}function errorOrDestroy(y,u){var h=y._readableState,b=y._writableState;h&&h.autoDestroy||b&&b.autoDestroy?y.destroy(u):y.emit("error",u)}var destroy_1$1={destroy:destroy$1,undestroy:undestroy$1,errorOrDestroy},errorsBrowser={};function _inheritsLoose(y,u){y.prototype=Object.create(u.prototype),y.prototype.constructor=y,y.__proto__=u}var codes={};function createErrorType(y,u,h){h||(h=Error);function b(w,_,E){return typeof u=="string"?u:u(w,_,E)}var v=function(w){_inheritsLoose(_,w);function _(E,S,x){return w.call(this,b(E,S,x))||this}return _}(h);v.prototype.name=h.name,v.prototype.code=y,codes[y]=v}function oneOf(y,u){if(Array.isArray(y)){var h=y.length;return y=y.map(function(b){return String(b)}),h>2?"one of ".concat(u," ").concat(y.slice(0,h-1).join(", "),", or ")+y[h-1]:h===2?"one of ".concat(u," ").concat(y[0]," or ").concat(y[1]):"of ".concat(u," ").concat(y[0])}else return"of ".concat(u," ").concat(String(y))}function startsWith(y,u,h){return y.substr(0,u.length)===u}function endsWith(y,u,h){return(h===void 0||h>y.length)&&(h=y.length),y.substring(h-u.length,h)===u}function includes(y,u,h){return typeof h!="number"&&(h=0),h+u.length>y.length?!1:y.indexOf(u,h)!==-1}createErrorType("ERR_INVALID_OPT_VALUE",function(y,u){return'The value "'+u+'" is invalid for option "'+y+'"'},TypeError);createErrorType("ERR_INVALID_ARG_TYPE",function(y,u,h){var b;typeof u=="string"&&startsWith(u,"not ")?(b="must not be",u=u.replace(/^not /,"")):b="must be";var v;if(endsWith(y," argument"))v="The ".concat(y," ").concat(b," ").concat(oneOf(u,"type"));else{var w=includes(y,".")?"property":"argument";v='The "'.concat(y,'" ').concat(w," ").concat(b," ").concat(oneOf(u,"type"))}return v+=". Received type ".concat(typeof h),v},TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(y){return"The "+y+" method is not implemented"});createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",function(y){return"Cannot call "+y+" after a stream was destroyed"});createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",function(y){return"Unknown encoding: "+y},TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");errorsBrowser.codes=codes;var ERR_INVALID_OPT_VALUE=errorsBrowser.codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(y,u,h){return y.highWaterMark!=null?y.highWaterMark:u?y[h]:null}function getHighWaterMark(y,u,h,b){var v=highWaterMarkFrom(u,b,h);if(v!=null){if(!(isFinite(v)&&Math.floor(v)===v)||v<0){var w=b?h:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(w,v)}return Math.floor(v)}return y.objectMode?16:16*1024}var state={getHighWaterMark},browser$a=deprecate;function deprecate(y,u){if(config("noDeprecation"))return y;var h=!1;function b(){if(!h){if(config("throwDeprecation"))throw new Error(u);config("traceDeprecation")?console.trace(u):console.warn(u),h=!0}return y.apply(this,arguments)}return b}function config(y){try{if(!commonjsGlobal.localStorage)return!1}catch{return!1}var u=commonjsGlobal.localStorage[y];return u==null?!1:String(u).toLowerCase()==="true"}var _stream_writable$1,hasRequired_stream_writable$1;function require_stream_writable$1(){if(hasRequired_stream_writable$1)return _stream_writable$1;hasRequired_stream_writable$1=1,_stream_writable$1=Ie;function y(Ae){var le=this;this.next=null,this.entry=null,this.finish=function(){Ne(le,Ae)}}var u;Ie.WritableState=ve;var h={deprecate:browser$a},b=streamBrowser$1,v=dist.Buffer,w=(typeof commonjsGlobal<"u"?commonjsGlobal:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function _(Ae){return v.from(Ae)}function E(Ae){return v.isBuffer(Ae)||Ae instanceof w}var S=destroy_1$1,x=state,T=x.getHighWaterMark,C=errorsBrowser.codes,O=C.ERR_INVALID_ARG_TYPE,D=C.ERR_METHOD_NOT_IMPLEMENTED,U=C.ERR_MULTIPLE_CALLBACK,te=C.ERR_STREAM_CANNOT_PIPE,X=C.ERR_STREAM_DESTROYED,ie=C.ERR_STREAM_NULL_VALUES,ee=C.ERR_STREAM_WRITE_AFTER_END,ae=C.ERR_UNKNOWN_ENCODING,de=S.errorOrDestroy;inherits_browserExports(Ie,b);function Se(){}function ve(Ae,le,me){u=u||require_stream_duplex$1(),Ae=Ae||{},typeof me!="boolean"&&(me=le instanceof u),this.objectMode=!!Ae.objectMode,me&&(this.objectMode=this.objectMode||!!Ae.writableObjectMode),this.highWaterMark=T(this,Ae,"writableHighWaterMark",me),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var Me=Ae.decodeStrings===!1;this.decodeStrings=!Me,this.defaultEncoding=Ae.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(fe){Q(le,fe)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=Ae.emitClose!==!1,this.autoDestroy=!!Ae.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new y(this)}ve.prototype.getBuffer=function(){for(var le=this.bufferedRequest,me=[];le;)me.push(le),le=le.next;return me},function(){try{Object.defineProperty(ve.prototype,"buffer",{get:h.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var Pe;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(Pe=Function.prototype[Symbol.hasInstance],Object.defineProperty(Ie,Symbol.hasInstance,{value:function(le){return Pe.call(this,le)?!0:this!==Ie?!1:le&&le._writableState instanceof ve}})):Pe=function(le){return le instanceof this};function Ie(Ae){u=u||require_stream_duplex$1();var le=this instanceof u;if(!le&&!Pe.call(Ie,this))return new Ie(Ae);this._writableState=new ve(Ae,this,le),this.writable=!0,Ae&&(typeof Ae.write=="function"&&(this._write=Ae.write),typeof Ae.writev=="function"&&(this._writev=Ae.writev),typeof Ae.destroy=="function"&&(this._destroy=Ae.destroy),typeof Ae.final=="function"&&(this._final=Ae.final)),b.call(this)}Ie.prototype.pipe=function(){de(this,new te)};function Ee(Ae,le){var me=new ee;de(Ae,me),process$1.nextTick(le,me)}function De(Ae,le,me,Me){var fe;return me===null?fe=new ie:typeof me!="string"&&!le.objectMode&&(fe=new O("chunk",["string","Buffer"],me)),fe?(de(Ae,fe),process$1.nextTick(Me,fe),!1):!0}Ie.prototype.write=function(Ae,le,me){var Me=this._writableState,fe=!1,ge=!Me.objectMode&&E(Ae);return ge&&!v.isBuffer(Ae)&&(Ae=_(Ae)),typeof le=="function"&&(me=le,le=null),ge?le="buffer":le||(le=Me.defaultEncoding),typeof me!="function"&&(me=Se),Me.ending?Ee(this,me):(ge||De(this,Me,Ae,me))&&(Me.pendingcb++,fe=B(this,Me,ge,Ae,le,me)),fe},Ie.prototype.cork=function(){this._writableState.corked++},Ie.prototype.uncork=function(){var Ae=this._writableState;Ae.corked&&(Ae.corked--,!Ae.writing&&!Ae.corked&&!Ae.bufferProcessing&&Ae.bufferedRequest&&J(this,Ae))},Ie.prototype.setDefaultEncoding=function(le){if(typeof le=="string"&&(le=le.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((le+"").toLowerCase())>-1))throw new ae(le);return this._writableState.defaultEncoding=le,this},Object.defineProperty(Ie.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function be(Ae,le,me){return!Ae.objectMode&&Ae.decodeStrings!==!1&&typeof le=="string"&&(le=v.from(le,me)),le}Object.defineProperty(Ie.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function B(Ae,le,me,Me,fe,ge){if(!me){var ce=be(le,Me,fe);Me!==ce&&(me=!0,fe="buffer",Me=ce)}var _e=le.objectMode?1:Me.length;le.length+=_e;var Re=le.length<le.highWaterMark;if(Re||(le.needDrain=!0),le.writing||le.corked){var Ue=le.lastBufferedRequest;le.lastBufferedRequest={chunk:Me,encoding:fe,isBuf:me,callback:ge,next:null},Ue?Ue.next=le.lastBufferedRequest:le.bufferedRequest=le.lastBufferedRequest,le.bufferedRequestCount+=1}else F(Ae,le,!1,_e,Me,fe,ge);return Re}function F(Ae,le,me,Me,fe,ge,ce){le.writelen=Me,le.writecb=ce,le.writing=!0,le.sync=!0,le.destroyed?le.onwrite(new X("write")):me?Ae._writev(fe,le.onwrite):Ae._write(fe,ge,le.onwrite),le.sync=!1}function M(Ae,le,me,Me,fe){--le.pendingcb,me?(process$1.nextTick(fe,Me),process$1.nextTick(he,Ae,le),Ae._writableState.errorEmitted=!0,de(Ae,Me)):(fe(Me),Ae._writableState.errorEmitted=!0,de(Ae,Me),he(Ae,le))}function N(Ae){Ae.writing=!1,Ae.writecb=null,Ae.length-=Ae.writelen,Ae.writelen=0}function Q(Ae,le){var me=Ae._writableState,Me=me.sync,fe=me.writecb;if(typeof fe!="function")throw new U;if(N(me),le)M(Ae,me,Me,le,fe);else{var ge=q(me)||Ae.destroyed;!ge&&!me.corked&&!me.bufferProcessing&&me.bufferedRequest&&J(Ae,me),Me?process$1.nextTick(j,Ae,me,ge,fe):j(Ae,me,ge,fe)}}function j(Ae,le,me,Me){me||ne(Ae,le),le.pendingcb--,Me(),he(Ae,le)}function ne(Ae,le){le.length===0&&le.needDrain&&(le.needDrain=!1,Ae.emit("drain"))}function J(Ae,le){le.bufferProcessing=!0;var me=le.bufferedRequest;if(Ae._writev&&me&&me.next){var Me=le.bufferedRequestCount,fe=new Array(Me),ge=le.corkedRequestsFree;ge.entry=me;for(var ce=0,_e=!0;me;)fe[ce]=me,me.isBuf||(_e=!1),me=me.next,ce+=1;fe.allBuffers=_e,F(Ae,le,!0,le.length,fe,"",ge.finish),le.pendingcb++,le.lastBufferedRequest=null,ge.next?(le.corkedRequestsFree=ge.next,ge.next=null):le.corkedRequestsFree=new y(le),le.bufferedRequestCount=0}else{for(;me;){var Re=me.chunk,Ue=me.encoding,qe=me.callback,Ze=le.objectMode?1:Re.length;if(F(Ae,le,!1,Ze,Re,Ue,qe),me=me.next,le.bufferedRequestCount--,le.writing)break}me===null&&(le.lastBufferedRequest=null)}le.bufferedRequest=me,le.bufferProcessing=!1}Ie.prototype._write=function(Ae,le,me){me(new D("_write()"))},Ie.prototype._writev=null,Ie.prototype.end=function(Ae,le,me){var Me=this._writableState;return typeof Ae=="function"?(me=Ae,Ae=null,le=null):typeof le=="function"&&(me=le,le=null),Ae!=null&&this.write(Ae,le),Me.corked&&(Me.corked=1,this.uncork()),Me.ending||Oe(this,Me,me),this},Object.defineProperty(Ie.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function q(Ae){return Ae.ending&&Ae.length===0&&Ae.bufferedRequest===null&&!Ae.finished&&!Ae.writing}function re(Ae,le){Ae._final(function(me){le.pendingcb--,me&&de(Ae,me),le.prefinished=!0,Ae.emit("prefinish"),he(Ae,le)})}function H(Ae,le){!le.prefinished&&!le.finalCalled&&(typeof Ae._final=="function"&&!le.destroyed?(le.pendingcb++,le.finalCalled=!0,process$1.nextTick(re,Ae,le)):(le.prefinished=!0,Ae.emit("prefinish")))}function he(Ae,le){var me=q(le);if(me&&(H(Ae,le),le.pendingcb===0&&(le.finished=!0,Ae.emit("finish"),le.autoDestroy))){var Me=Ae._readableState;(!Me||Me.autoDestroy&&Me.endEmitted)&&Ae.destroy()}return me}function Oe(Ae,le,me){le.ending=!0,he(Ae,le),me&&(le.finished?process$1.nextTick(me):Ae.once("finish",me)),le.ended=!0,Ae.writable=!1}function Ne(Ae,le,me){var Me=Ae.entry;for(Ae.entry=null;Me;){var fe=Me.callback;le.pendingcb--,fe(me),Me=Me.next}le.corkedRequestsFree.next=Ae}return Object.defineProperty(Ie.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(le){this._writableState&&(this._writableState.destroyed=le)}}),Ie.prototype.destroy=S.destroy,Ie.prototype._undestroy=S.undestroy,Ie.prototype._destroy=function(Ae,le){le(Ae)},_stream_writable$1}var _stream_duplex$1,hasRequired_stream_duplex$1;function require_stream_duplex$1(){if(hasRequired_stream_duplex$1)return _stream_duplex$1;hasRequired_stream_duplex$1=1;var y=Object.keys||function(x){var T=[];for(var C in x)T.push(C);return T};_stream_duplex$1=_;var u=require_stream_readable$1(),h=require_stream_writable$1();inherits_browserExports(_,u);for(var b=y(h.prototype),v=0;v<b.length;v++){var w=b[v];_.prototype[w]||(_.prototype[w]=h.prototype[w])}function _(x){if(!(this instanceof _))return new _(x);u.call(this,x),h.call(this,x),this.allowHalfOpen=!0,x&&(x.readable===!1&&(this.readable=!1),x.writable===!1&&(this.writable=!1),x.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",E)))}Object.defineProperty(_.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(_.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(_.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function E(){this._writableState.ended||process$1.nextTick(S,this)}function S(x){x.end()}return Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(T){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=T,this._writableState.destroyed=T)}}),_stream_duplex$1}var string_decoder={},Buffer$A=safeBufferExports$1.Buffer,isEncoding=Buffer$A.isEncoding||function(y){switch(y=""+y,y&&y.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function _normalizeEncoding(y){if(!y)return"utf8";for(var u;;)switch(y){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return y;default:if(u)return;y=(""+y).toLowerCase(),u=!0}}function normalizeEncoding(y){var u=_normalizeEncoding(y);if(typeof u!="string"&&(Buffer$A.isEncoding===isEncoding||!isEncoding(y)))throw new Error("Unknown encoding: "+y);return u||y}string_decoder.StringDecoder=StringDecoder$1;function StringDecoder$1(y){this.encoding=normalizeEncoding(y);var u;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,u=4;break;case"utf8":this.fillLast=utf8FillLast,u=4;break;case"base64":this.text=base64Text,this.end=base64End,u=3;break;default:this.write=simpleWrite,this.end=simpleEnd;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer$A.allocUnsafe(u)}StringDecoder$1.prototype.write=function(y){if(y.length===0)return"";var u,h;if(this.lastNeed){if(u=this.fillLast(y),u===void 0)return"";h=this.lastNeed,this.lastNeed=0}else h=0;return h<y.length?u?u+this.text(y,h):this.text(y,h):u||""};StringDecoder$1.prototype.end=utf8End;StringDecoder$1.prototype.text=utf8Text;StringDecoder$1.prototype.fillLast=function(y){if(this.lastNeed<=y.length)return y.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);y.copy(this.lastChar,this.lastTotal-this.lastNeed,0,y.length),this.lastNeed-=y.length};function utf8CheckByte(y){return y<=127?0:y>>5===6?2:y>>4===14?3:y>>3===30?4:y>>6===2?-1:-2}function utf8CheckIncomplete(y,u,h){var b=u.length-1;if(b<h)return 0;var v=utf8CheckByte(u[b]);return v>=0?(v>0&&(y.lastNeed=v-1),v):--b<h||v===-2?0:(v=utf8CheckByte(u[b]),v>=0?(v>0&&(y.lastNeed=v-2),v):--b<h||v===-2?0:(v=utf8CheckByte(u[b]),v>=0?(v>0&&(v===2?v=0:y.lastNeed=v-3),v):0))}function utf8CheckExtraBytes(y,u,h){if((u[0]&192)!==128)return y.lastNeed=0,"�";if(y.lastNeed>1&&u.length>1){if((u[1]&192)!==128)return y.lastNeed=1,"�";if(y.lastNeed>2&&u.length>2&&(u[2]&192)!==128)return y.lastNeed=2,"�"}}function utf8FillLast(y){var u=this.lastTotal-this.lastNeed,h=utf8CheckExtraBytes(this,y);if(h!==void 0)return h;if(this.lastNeed<=y.length)return y.copy(this.lastChar,u,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);y.copy(this.lastChar,u,0,y.length),this.lastNeed-=y.length}function utf8Text(y,u){var h=utf8CheckIncomplete(this,y,u);if(!this.lastNeed)return y.toString("utf8",u);this.lastTotal=h;var b=y.length-(h-this.lastNeed);return y.copy(this.lastChar,0,b),y.toString("utf8",u,b)}function utf8End(y){var u=y&&y.length?this.write(y):"";return this.lastNeed?u+"�":u}function utf16Text(y,u){if((y.length-u)%2===0){var h=y.toString("utf16le",u);if(h){var b=h.charCodeAt(h.length-1);if(b>=55296&&b<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=y[y.length-2],this.lastChar[1]=y[y.length-1],h.slice(0,-1)}return h}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=y[y.length-1],y.toString("utf16le",u,y.length-1)}function utf16End(y){var u=y&&y.length?this.write(y):"";if(this.lastNeed){var h=this.lastTotal-this.lastNeed;return u+this.lastChar.toString("utf16le",0,h)}return u}function base64Text(y,u){var h=(y.length-u)%3;return h===0?y.toString("base64",u):(this.lastNeed=3-h,this.lastTotal=3,h===1?this.lastChar[0]=y[y.length-1]:(this.lastChar[0]=y[y.length-2],this.lastChar[1]=y[y.length-1]),y.toString("base64",u,y.length-h))}function base64End(y){var u=y&&y.length?this.write(y):"";return this.lastNeed?u+this.lastChar.toString("base64",0,3-this.lastNeed):u}function simpleWrite(y){return y.toString(this.encoding)}function simpleEnd(y){return y&&y.length?this.write(y):""}var ERR_STREAM_PREMATURE_CLOSE=errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE;function once$1(y){var u=!1;return function(){if(!u){u=!0;for(var h=arguments.length,b=new Array(h),v=0;v<h;v++)b[v]=arguments[v];y.apply(this,b)}}}function noop$2(){}function isRequest$1(y){return y.setHeader&&typeof y.abort=="function"}function eos$1(y,u,h){if(typeof u=="function")return eos$1(y,null,u);u||(u={}),h=once$1(h||noop$2);var b=u.readable||u.readable!==!1&&y.readable,v=u.writable||u.writable!==!1&&y.writable,w=function(){y.writable||E()},_=y._writableState&&y._writableState.finished,E=function(){v=!1,_=!0,b||h.call(y)},S=y._readableState&&y._readableState.endEmitted,x=function(){b=!1,S=!0,v||h.call(y)},T=function(U){h.call(y,U)},C=function(){var U;if(b&&!S)return(!y._readableState||!y._readableState.ended)&&(U=new ERR_STREAM_PREMATURE_CLOSE),h.call(y,U);if(v&&!_)return(!y._writableState||!y._writableState.ended)&&(U=new ERR_STREAM_PREMATURE_CLOSE),h.call(y,U)},O=function(){y.req.on("finish",E)};return isRequest$1(y)?(y.on("complete",E),y.on("abort",C),y.req?O():y.on("request",O)):v&&!y._writableState&&(y.on("end",w),y.on("close",w)),y.on("end",x),y.on("finish",E),u.error!==!1&&y.on("error",T),y.on("close",C),function(){y.removeListener("complete",E),y.removeListener("abort",C),y.removeListener("request",O),y.req&&y.req.removeListener("finish",E),y.removeListener("end",w),y.removeListener("close",w),y.removeListener("finish",E),y.removeListener("end",x),y.removeListener("error",T),y.removeListener("close",C)}}var endOfStream=eos$1,async_iterator,hasRequiredAsync_iterator;function requireAsync_iterator(){if(hasRequiredAsync_iterator)return async_iterator;hasRequiredAsync_iterator=1;var y;function u(ae,de,Se){return de=h(de),de in ae?Object.defineProperty(ae,de,{value:Se,enumerable:!0,configurable:!0,writable:!0}):ae[de]=Se,ae}function h(ae){var de=b(ae,"string");return typeof de=="symbol"?de:String(de)}function b(ae,de){if(typeof ae!="object"||ae===null)return ae;var Se=ae[Symbol.toPrimitive];if(Se!==void 0){var ve=Se.call(ae,de||"default");if(typeof ve!="object")return ve;throw new TypeError("@@toPrimitive must return a primitive value.")}return(de==="string"?String:Number)(ae)}var v=endOfStream,w=Symbol("lastResolve"),_=Symbol("lastReject"),E=Symbol("error"),S=Symbol("ended"),x=Symbol("lastPromise"),T=Symbol("handlePromise"),C=Symbol("stream");function O(ae,de){return{value:ae,done:de}}function D(ae){var de=ae[w];if(de!==null){var Se=ae[C].read();Se!==null&&(ae[x]=null,ae[w]=null,ae[_]=null,de(O(Se,!1)))}}function U(ae){process$1.nextTick(D,ae)}function te(ae,de){return function(Se,ve){ae.then(function(){if(de[S]){Se(O(void 0,!0));return}de[T](Se,ve)},ve)}}var X=Object.getPrototypeOf(function(){}),ie=Object.setPrototypeOf((y={get stream(){return this[C]},next:function(){var de=this,Se=this[E];if(Se!==null)return Promise.reject(Se);if(this[S])return Promise.resolve(O(void 0,!0));if(this[C].destroyed)return new Promise(function(Ee,De){process$1.nextTick(function(){de[E]?De(de[E]):Ee(O(void 0,!0))})});var ve=this[x],Pe;if(ve)Pe=new Promise(te(ve,this));else{var Ie=this[C].read();if(Ie!==null)return Promise.resolve(O(Ie,!1));Pe=new Promise(this[T])}return this[x]=Pe,Pe}},u(y,Symbol.asyncIterator,function(){return this}),u(y,"return",function(){var de=this;return new Promise(function(Se,ve){de[C].destroy(null,function(Pe){if(Pe){ve(Pe);return}Se(O(void 0,!0))})})}),y),X),ee=function(de){var Se,ve=Object.create(ie,(Se={},u(Se,C,{value:de,writable:!0}),u(Se,w,{value:null,writable:!0}),u(Se,_,{value:null,writable:!0}),u(Se,E,{value:null,writable:!0}),u(Se,S,{value:de._readableState.endEmitted,writable:!0}),u(Se,T,{value:function(Ie,Ee){var De=ve[C].read();De?(ve[x]=null,ve[w]=null,ve[_]=null,Ie(O(De,!1))):(ve[w]=Ie,ve[_]=Ee)},writable:!0}),Se));return ve[x]=null,v(de,function(Pe){if(Pe&&Pe.code!=="ERR_STREAM_PREMATURE_CLOSE"){var Ie=ve[_];Ie!==null&&(ve[x]=null,ve[w]=null,ve[_]=null,Ie(Pe)),ve[E]=Pe;return}var Ee=ve[w];Ee!==null&&(ve[x]=null,ve[w]=null,ve[_]=null,Ee(O(void 0,!0))),ve[S]=!0}),de.on("readable",U.bind(null,ve)),ve};return async_iterator=ee,async_iterator}var fromBrowser,hasRequiredFromBrowser;function requireFromBrowser(){return hasRequiredFromBrowser||(hasRequiredFromBrowser=1,fromBrowser=function(){throw new Error("Readable.from is not available in the browser")}),fromBrowser}var _stream_readable$1,hasRequired_stream_readable$1;function require_stream_readable$1(){if(hasRequired_stream_readable$1)return _stream_readable$1;hasRequired_stream_readable$1=1,_stream_readable$1=Ee;var y;Ee.ReadableState=Ie,eventsExports.EventEmitter;var u=function(ce,_e){return ce.listeners(_e).length},h=streamBrowser$1,b=dist.Buffer,v=(typeof commonjsGlobal<"u"?commonjsGlobal:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function w(ge){return b.from(ge)}function _(ge){return b.isBuffer(ge)||ge instanceof v}var E=util$b,S;E&&E.debuglog?S=E.debuglog("stream"):S=function(){};var x=requireBuffer_list(),T=destroy_1$1,C=state,O=C.getHighWaterMark,D=errorsBrowser.codes,U=D.ERR_INVALID_ARG_TYPE,te=D.ERR_STREAM_PUSH_AFTER_EOF,X=D.ERR_METHOD_NOT_IMPLEMENTED,ie=D.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,ee,ae,de;inherits_browserExports(Ee,h);var Se=T.errorOrDestroy,ve=["error","close","destroy","pause","resume"];function Pe(ge,ce,_e){if(typeof ge.prependListener=="function")return ge.prependListener(ce,_e);!ge._events||!ge._events[ce]?ge.on(ce,_e):Array.isArray(ge._events[ce])?ge._events[ce].unshift(_e):ge._events[ce]=[_e,ge._events[ce]]}function Ie(ge,ce,_e){y=y||require_stream_duplex$1(),ge=ge||{},typeof _e!="boolean"&&(_e=ce instanceof y),this.objectMode=!!ge.objectMode,_e&&(this.objectMode=this.objectMode||!!ge.readableObjectMode),this.highWaterMark=O(this,ge,"readableHighWaterMark",_e),this.buffer=new x,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=ge.emitClose!==!1,this.autoDestroy=!!ge.autoDestroy,this.destroyed=!1,this.defaultEncoding=ge.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,ge.encoding&&(ee||(ee=string_decoder.StringDecoder),this.decoder=new ee(ge.encoding),this.encoding=ge.encoding)}function Ee(ge){if(y=y||require_stream_duplex$1(),!(this instanceof Ee))return new Ee(ge);var ce=this instanceof y;this._readableState=new Ie(ge,this,ce),this.readable=!0,ge&&(typeof ge.read=="function"&&(this._read=ge.read),typeof ge.destroy=="function"&&(this._destroy=ge.destroy)),h.call(this)}Object.defineProperty(Ee.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(ce){this._readableState&&(this._readableState.destroyed=ce)}}),Ee.prototype.destroy=T.destroy,Ee.prototype._undestroy=T.undestroy,Ee.prototype._destroy=function(ge,ce){ce(ge)},Ee.prototype.push=function(ge,ce){var _e=this._readableState,Re;return _e.objectMode?Re=!0:typeof ge=="string"&&(ce=ce||_e.defaultEncoding,ce!==_e.encoding&&(ge=b.from(ge,ce),ce=""),Re=!0),De(this,ge,ce,!1,Re)},Ee.prototype.unshift=function(ge){return De(this,ge,null,!0,!1)};function De(ge,ce,_e,Re,Ue){S("readableAddChunk",ce);var qe=ge._readableState;if(ce===null)qe.reading=!1,Q(ge,qe);else{var Ze;if(Ue||(Ze=B(qe,ce)),Ze)Se(ge,Ze);else if(qe.objectMode||ce&&ce.length>0)if(typeof ce!="string"&&!qe.objectMode&&Object.getPrototypeOf(ce)!==b.prototype&&(ce=w(ce)),Re)qe.endEmitted?Se(ge,new ie):be(ge,qe,ce,!0);else if(qe.ended)Se(ge,new te);else{if(qe.destroyed)return!1;qe.reading=!1,qe.decoder&&!_e?(ce=qe.decoder.write(ce),qe.objectMode||ce.length!==0?be(ge,qe,ce,!1):J(ge,qe)):be(ge,qe,ce,!1)}else Re||(qe.reading=!1,J(ge,qe))}return!qe.ended&&(qe.length<qe.highWaterMark||qe.length===0)}function be(ge,ce,_e,Re){ce.flowing&&ce.length===0&&!ce.sync?(ce.awaitDrain=0,ge.emit("data",_e)):(ce.length+=ce.objectMode?1:_e.length,Re?ce.buffer.unshift(_e):ce.buffer.push(_e),ce.needReadable&&j(ge)),J(ge,ce)}function B(ge,ce){var _e;return!_(ce)&&typeof ce!="string"&&ce!==void 0&&!ge.objectMode&&(_e=new U("chunk",["string","Buffer","Uint8Array"],ce)),_e}Ee.prototype.isPaused=function(){return this._readableState.flowing===!1},Ee.prototype.setEncoding=function(ge){ee||(ee=string_decoder.StringDecoder);var ce=new ee(ge);this._readableState.decoder=ce,this._readableState.encoding=this._readableState.decoder.encoding;for(var _e=this._readableState.buffer.head,Re="";_e!==null;)Re+=ce.write(_e.data),_e=_e.next;return this._readableState.buffer.clear(),Re!==""&&this._readableState.buffer.push(Re),this._readableState.length=Re.length,this};var F=1073741824;function M(ge){return ge>=F?ge=F:(ge--,ge|=ge>>>1,ge|=ge>>>2,ge|=ge>>>4,ge|=ge>>>8,ge|=ge>>>16,ge++),ge}function N(ge,ce){return ge<=0||ce.length===0&&ce.ended?0:ce.objectMode?1:ge!==ge?ce.flowing&&ce.length?ce.buffer.head.data.length:ce.length:(ge>ce.highWaterMark&&(ce.highWaterMark=M(ge)),ge<=ce.length?ge:ce.ended?ce.length:(ce.needReadable=!0,0))}Ee.prototype.read=function(ge){S("read",ge),ge=parseInt(ge,10);var ce=this._readableState,_e=ge;if(ge!==0&&(ce.emittedReadable=!1),ge===0&&ce.needReadable&&((ce.highWaterMark!==0?ce.length>=ce.highWaterMark:ce.length>0)||ce.ended))return S("read: emitReadable",ce.length,ce.ended),ce.length===0&&ce.ended?me(this):j(this),null;if(ge=N(ge,ce),ge===0&&ce.ended)return ce.length===0&&me(this),null;var Re=ce.needReadable;S("need readable",Re),(ce.length===0||ce.length-ge<ce.highWaterMark)&&(Re=!0,S("length less than watermark",Re)),ce.ended||ce.reading?(Re=!1,S("reading or ended",Re)):Re&&(S("do read"),ce.reading=!0,ce.sync=!0,ce.length===0&&(ce.needReadable=!0),this._read(ce.highWaterMark),ce.sync=!1,ce.reading||(ge=N(_e,ce)));var Ue;return ge>0?Ue=le(ge,ce):Ue=null,Ue===null?(ce.needReadable=ce.length<=ce.highWaterMark,ge=0):(ce.length-=ge,ce.awaitDrain=0),ce.length===0&&(ce.ended||(ce.needReadable=!0),_e!==ge&&ce.ended&&me(this)),Ue!==null&&this.emit("data",Ue),Ue};function Q(ge,ce){if(S("onEofChunk"),!ce.ended){if(ce.decoder){var _e=ce.decoder.end();_e&&_e.length&&(ce.buffer.push(_e),ce.length+=ce.objectMode?1:_e.length)}ce.ended=!0,ce.sync?j(ge):(ce.needReadable=!1,ce.emittedReadable||(ce.emittedReadable=!0,ne(ge)))}}function j(ge){var ce=ge._readableState;S("emitReadable",ce.needReadable,ce.emittedReadable),ce.needReadable=!1,ce.emittedReadable||(S("emitReadable",ce.flowing),ce.emittedReadable=!0,process$1.nextTick(ne,ge))}function ne(ge){var ce=ge._readableState;S("emitReadable_",ce.destroyed,ce.length,ce.ended),!ce.destroyed&&(ce.length||ce.ended)&&(ge.emit("readable"),ce.emittedReadable=!1),ce.needReadable=!ce.flowing&&!ce.ended&&ce.length<=ce.highWaterMark,Ae(ge)}function J(ge,ce){ce.readingMore||(ce.readingMore=!0,process$1.nextTick(q,ge,ce))}function q(ge,ce){for(;!ce.reading&&!ce.ended&&(ce.length<ce.highWaterMark||ce.flowing&&ce.length===0);){var _e=ce.length;if(S("maybeReadMore read 0"),ge.read(0),_e===ce.length)break}ce.readingMore=!1}Ee.prototype._read=function(ge){Se(this,new X("_read()"))},Ee.prototype.pipe=function(ge,ce){var _e=this,Re=this._readableState;switch(Re.pipesCount){case 0:Re.pipes=ge;break;case 1:Re.pipes=[Re.pipes,ge];break;default:Re.pipes.push(ge);break}Re.pipesCount+=1,S("pipe count=%d opts=%j",Re.pipesCount,ce);var Ue=(!ce||ce.end!==!1)&&ge!==process$1.stdout&&ge!==process$1.stderr,qe=Ue?tt:Ot;Re.endEmitted?process$1.nextTick(qe):_e.once("end",qe),ge.on("unpipe",Ze);function Ze(dt,Rt){S("onunpipe"),dt===_e&&Rt&&Rt.hasUnpiped===!1&&(Rt.hasUnpiped=!0,it())}function tt(){S("onend"),ge.end()}var Fe=re(_e);ge.on("drain",Fe);var nt=!1;function it(){S("cleanup"),ge.removeListener("close",ht),ge.removeListener("finish",xt),ge.removeListener("drain",Fe),ge.removeListener("error",ct),ge.removeListener("unpipe",Ze),_e.removeListener("end",tt),_e.removeListener("end",Ot),_e.removeListener("data",at),nt=!0,Re.awaitDrain&&(!ge._writableState||ge._writableState.needDrain)&&Fe()}_e.on("data",at);function at(dt){S("ondata");var Rt=ge.write(dt);S("dest.write",Rt),Rt===!1&&((Re.pipesCount===1&&Re.pipes===ge||Re.pipesCount>1&&fe(Re.pipes,ge)!==-1)&&!nt&&(S("false write response, pause",Re.awaitDrain),Re.awaitDrain++),_e.pause())}function ct(dt){S("onerror",dt),Ot(),ge.removeListener("error",ct),u(ge,"error")===0&&Se(ge,dt)}Pe(ge,"error",ct);function ht(){ge.removeListener("finish",xt),Ot()}ge.once("close",ht);function xt(){S("onfinish"),ge.removeListener("close",ht),Ot()}ge.once("finish",xt);function Ot(){S("unpipe"),_e.unpipe(ge)}return ge.emit("pipe",_e),Re.flowing||(S("pipe resume"),_e.resume()),ge};function re(ge){return function(){var _e=ge._readableState;S("pipeOnDrain",_e.awaitDrain),_e.awaitDrain&&_e.awaitDrain--,_e.awaitDrain===0&&u(ge,"data")&&(_e.flowing=!0,Ae(ge))}}Ee.prototype.unpipe=function(ge){var ce=this._readableState,_e={hasUnpiped:!1};if(ce.pipesCount===0)return this;if(ce.pipesCount===1)return ge&&ge!==ce.pipes?this:(ge||(ge=ce.pipes),ce.pipes=null,ce.pipesCount=0,ce.flowing=!1,ge&&ge.emit("unpipe",this,_e),this);if(!ge){var Re=ce.pipes,Ue=ce.pipesCount;ce.pipes=null,ce.pipesCount=0,ce.flowing=!1;for(var qe=0;qe<Ue;qe++)Re[qe].emit("unpipe",this,{hasUnpiped:!1});return this}var Ze=fe(ce.pipes,ge);return Ze===-1?this:(ce.pipes.splice(Ze,1),ce.pipesCount-=1,ce.pipesCount===1&&(ce.pipes=ce.pipes[0]),ge.emit("unpipe",this,_e),this)},Ee.prototype.on=function(ge,ce){var _e=h.prototype.on.call(this,ge,ce),Re=this._readableState;return ge==="data"?(Re.readableListening=this.listenerCount("readable")>0,Re.flowing!==!1&&this.resume()):ge==="readable"&&!Re.endEmitted&&!Re.readableListening&&(Re.readableListening=Re.needReadable=!0,Re.flowing=!1,Re.emittedReadable=!1,S("on readable",Re.length,Re.reading),Re.length?j(this):Re.reading||process$1.nextTick(he,this)),_e},Ee.prototype.addListener=Ee.prototype.on,Ee.prototype.removeListener=function(ge,ce){var _e=h.prototype.removeListener.call(this,ge,ce);return ge==="readable"&&process$1.nextTick(H,this),_e},Ee.prototype.removeAllListeners=function(ge){var ce=h.prototype.removeAllListeners.apply(this,arguments);return(ge==="readable"||ge===void 0)&&process$1.nextTick(H,this),ce};function H(ge){var ce=ge._readableState;ce.readableListening=ge.listenerCount("readable")>0,ce.resumeScheduled&&!ce.paused?ce.flowing=!0:ge.listenerCount("data")>0&&ge.resume()}function he(ge){S("readable nexttick read 0"),ge.read(0)}Ee.prototype.resume=function(){var ge=this._readableState;return ge.flowing||(S("resume"),ge.flowing=!ge.readableListening,Oe(this,ge)),ge.paused=!1,this};function Oe(ge,ce){ce.resumeScheduled||(ce.resumeScheduled=!0,process$1.nextTick(Ne,ge,ce))}function Ne(ge,ce){S("resume",ce.reading),ce.reading||ge.read(0),ce.resumeScheduled=!1,ge.emit("resume"),Ae(ge),ce.flowing&&!ce.reading&&ge.read(0)}Ee.prototype.pause=function(){return S("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(S("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function Ae(ge){var ce=ge._readableState;for(S("flow",ce.flowing);ce.flowing&&ge.read()!==null;);}Ee.prototype.wrap=function(ge){var ce=this,_e=this._readableState,Re=!1;ge.on("end",function(){if(S("wrapped end"),_e.decoder&&!_e.ended){var Ze=_e.decoder.end();Ze&&Ze.length&&ce.push(Ze)}ce.push(null)}),ge.on("data",function(Ze){if(S("wrapped data"),_e.decoder&&(Ze=_e.decoder.write(Ze)),!(_e.objectMode&&Ze==null)&&!(!_e.objectMode&&(!Ze||!Ze.length))){var tt=ce.push(Ze);tt||(Re=!0,ge.pause())}});for(var Ue in ge)this[Ue]===void 0&&typeof ge[Ue]=="function"&&(this[Ue]=function(tt){return function(){return ge[tt].apply(ge,arguments)}}(Ue));for(var qe=0;qe<ve.length;qe++)ge.on(ve[qe],this.emit.bind(this,ve[qe]));return this._read=function(Ze){S("wrapped _read",Ze),Re&&(Re=!1,ge.resume())},this},typeof Symbol=="function"&&(Ee.prototype[Symbol.asyncIterator]=function(){return ae===void 0&&(ae=requireAsync_iterator()),ae(this)}),Object.defineProperty(Ee.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(Ee.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(Ee.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(ce){this._readableState&&(this._readableState.flowing=ce)}}),Ee._fromList=le,Object.defineProperty(Ee.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function le(ge,ce){if(ce.length===0)return null;var _e;return ce.objectMode?_e=ce.buffer.shift():!ge||ge>=ce.length?(ce.decoder?_e=ce.buffer.join(""):ce.buffer.length===1?_e=ce.buffer.first():_e=ce.buffer.concat(ce.length),ce.buffer.clear()):_e=ce.buffer.consume(ge,ce.decoder),_e}function me(ge){var ce=ge._readableState;S("endReadable",ce.endEmitted),ce.endEmitted||(ce.ended=!0,process$1.nextTick(Me,ce,ge))}function Me(ge,ce){if(S("endReadableNT",ge.endEmitted,ge.length),!ge.endEmitted&&ge.length===0&&(ge.endEmitted=!0,ce.readable=!1,ce.emit("end"),ge.autoDestroy)){var _e=ce._writableState;(!_e||_e.autoDestroy&&_e.finished)&&ce.destroy()}}typeof Symbol=="function"&&(Ee.from=function(ge,ce){return de===void 0&&(de=requireFromBrowser()),de(Ee,ge,ce)});function fe(ge,ce){for(var _e=0,Re=ge.length;_e<Re;_e++)if(ge[_e]===ce)return _e;return-1}return _stream_readable$1}var _stream_transform$1=Transform$9,_require$codes$1=errorsBrowser.codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes$1.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes$1.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0,Duplex$1=require_stream_duplex$1();inherits_browserExports(Transform$9,Duplex$1);function afterTransform$1(y,u){var h=this._transformState;h.transforming=!1;var b=h.writecb;if(b===null)return this.emit("error",new ERR_MULTIPLE_CALLBACK);h.writechunk=null,h.writecb=null,u!=null&&this.push(u),b(y);var v=this._readableState;v.reading=!1,(v.needReadable||v.length<v.highWaterMark)&&this._read(v.highWaterMark)}function Transform$9(y){if(!(this instanceof Transform$9))return new Transform$9(y);Duplex$1.call(this,y),this._transformState={afterTransform:afterTransform$1.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,y&&(typeof y.transform=="function"&&(this._transform=y.transform),typeof y.flush=="function"&&(this._flush=y.flush)),this.on("prefinish",prefinish$1)}function prefinish$1(){var y=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(u,h){done$1(y,u,h)}):done$1(this,null,null)}Transform$9.prototype.push=function(y,u){return this._transformState.needTransform=!1,Duplex$1.prototype.push.call(this,y,u)};Transform$9.prototype._transform=function(y,u,h){h(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))};Transform$9.prototype._write=function(y,u,h){var b=this._transformState;if(b.writecb=h,b.writechunk=y,b.writeencoding=u,!b.transforming){var v=this._readableState;(b.needTransform||v.needReadable||v.length<v.highWaterMark)&&this._read(v.highWaterMark)}};Transform$9.prototype._read=function(y){var u=this._transformState;u.writechunk!==null&&!u.transforming?(u.transforming=!0,this._transform(u.writechunk,u.writeencoding,u.afterTransform)):u.needTransform=!0};Transform$9.prototype._destroy=function(y,u){Duplex$1.prototype._destroy.call(this,y,function(h){u(h)})};function done$1(y,u,h){if(u)return y.emit("error",u);if(h!=null&&y.push(h),y._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if(y._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return y.push(null)}var _stream_passthrough$1=PassThrough$1,Transform$8=_stream_transform$1;inherits_browserExports(PassThrough$1,Transform$8);function PassThrough$1(y){if(!(this instanceof PassThrough$1))return new PassThrough$1(y);Transform$8.call(this,y)}PassThrough$1.prototype._transform=function(y,u,h){h(null,y)};var eos;function once(y){var u=!1;return function(){u||(u=!0,y.apply(void 0,arguments))}}var _require$codes=errorsBrowser.codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop$1(y){if(y)throw y}function isRequest(y){return y.setHeader&&typeof y.abort=="function"}function destroyer(y,u,h,b){b=once(b);var v=!1;y.on("close",function(){v=!0}),eos===void 0&&(eos=endOfStream),eos(y,{readable:u,writable:h},function(_){if(_)return b(_);v=!0,b()});var w=!1;return function(_){if(!v&&!w){if(w=!0,isRequest(y))return y.abort();if(typeof y.destroy=="function")return y.destroy();b(_||new ERR_STREAM_DESTROYED("pipe"))}}}function call(y){y()}function pipe(y,u){return y.pipe(u)}function popCallback(y){return!y.length||typeof y[y.length-1]!="function"?noop$1:y.pop()}function pipeline(){for(var y=arguments.length,u=new Array(y),h=0;h<y;h++)u[h]=arguments[h];var b=popCallback(u);if(Array.isArray(u[0])&&(u=u[0]),u.length<2)throw new ERR_MISSING_ARGS("streams");var v,w=u.map(function(_,E){var S=E<u.length-1,x=E>0;return destroyer(_,S,x,function(T){v||(v=T),T&&w.forEach(call),!S&&(w.forEach(call),b(v))})});return u.reduce(pipe)}var pipeline_1=pipeline;(function(y,u){u=y.exports=require_stream_readable$1(),u.Stream=u,u.Readable=u,u.Writable=require_stream_writable$1(),u.Duplex=require_stream_duplex$1(),u.Transform=_stream_transform$1,u.PassThrough=_stream_passthrough$1,u.finished=endOfStream,u.pipeline=pipeline_1})(readableBrowser$1,readableBrowser$1.exports);var readableBrowserExports$1=readableBrowser$1.exports,Buffer$z=safeBufferExports$1.Buffer,Transform$7=readableBrowserExports$1.Transform,inherits$q=inherits_browserExports;function throwIfNotStringOrBuffer(y,u){if(!Buffer$z.isBuffer(y)&&typeof y!="string")throw new TypeError(u+" must be a string or a buffer")}function HashBase$2(y){Transform$7.call(this),this._block=Buffer$z.allocUnsafe(y),this._blockSize=y,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}inherits$q(HashBase$2,Transform$7);HashBase$2.prototype._transform=function(y,u,h){var b=null;try{this.update(y,u)}catch(v){b=v}h(b)};HashBase$2.prototype._flush=function(y){var u=null;try{this.push(this.digest())}catch(h){u=h}y(u)};HashBase$2.prototype.update=function(y,u){if(throwIfNotStringOrBuffer(y,"Data"),this._finalized)throw new Error("Digest already called");Buffer$z.isBuffer(y)||(y=Buffer$z.from(y,u));for(var h=this._block,b=0;this._blockOffset+y.length-b>=this._blockSize;){for(var v=this._blockOffset;v<this._blockSize;)h[v++]=y[b++];this._update(),this._blockOffset=0}for(;b<y.length;)h[this._blockOffset++]=y[b++];for(var w=0,_=y.length*8;_>0;++w)this._length[w]+=_,_=this._length[w]/4294967296|0,_>0&&(this._length[w]-=4294967296*_);return this};HashBase$2.prototype._update=function(){throw new Error("_update is not implemented")};HashBase$2.prototype.digest=function(y){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var u=this._digest();y!==void 0&&(u=u.toString(y)),this._block.fill(0),this._blockOffset=0;for(var h=0;h<4;++h)this._length[h]=0;return u};HashBase$2.prototype._digest=function(){throw new Error("_digest is not implemented")};var hashBase=HashBase$2,inherits$p=inherits_browserExports,HashBase$1=hashBase,Buffer$y=safeBufferExports$1.Buffer,ARRAY16$1=new Array(16);function MD5$3(){HashBase$1.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}inherits$p(MD5$3,HashBase$1);MD5$3.prototype._update=function(){for(var y=ARRAY16$1,u=0;u<16;++u)y[u]=this._block.readInt32LE(u*4);var h=this._a,b=this._b,v=this._c,w=this._d;h=fnF(h,b,v,w,y[0],3614090360,7),w=fnF(w,h,b,v,y[1],3905402710,12),v=fnF(v,w,h,b,y[2],606105819,17),b=fnF(b,v,w,h,y[3],3250441966,22),h=fnF(h,b,v,w,y[4],4118548399,7),w=fnF(w,h,b,v,y[5],1200080426,12),v=fnF(v,w,h,b,y[6],2821735955,17),b=fnF(b,v,w,h,y[7],4249261313,22),h=fnF(h,b,v,w,y[8],1770035416,7),w=fnF(w,h,b,v,y[9],2336552879,12),v=fnF(v,w,h,b,y[10],4294925233,17),b=fnF(b,v,w,h,y[11],2304563134,22),h=fnF(h,b,v,w,y[12],1804603682,7),w=fnF(w,h,b,v,y[13],4254626195,12),v=fnF(v,w,h,b,y[14],2792965006,17),b=fnF(b,v,w,h,y[15],1236535329,22),h=fnG(h,b,v,w,y[1],4129170786,5),w=fnG(w,h,b,v,y[6],3225465664,9),v=fnG(v,w,h,b,y[11],643717713,14),b=fnG(b,v,w,h,y[0],3921069994,20),h=fnG(h,b,v,w,y[5],3593408605,5),w=fnG(w,h,b,v,y[10],38016083,9),v=fnG(v,w,h,b,y[15],3634488961,14),b=fnG(b,v,w,h,y[4],3889429448,20),h=fnG(h,b,v,w,y[9],568446438,5),w=fnG(w,h,b,v,y[14],3275163606,9),v=fnG(v,w,h,b,y[3],4107603335,14),b=fnG(b,v,w,h,y[8],1163531501,20),h=fnG(h,b,v,w,y[13],2850285829,5),w=fnG(w,h,b,v,y[2],4243563512,9),v=fnG(v,w,h,b,y[7],1735328473,14),b=fnG(b,v,w,h,y[12],2368359562,20),h=fnH(h,b,v,w,y[5],4294588738,4),w=fnH(w,h,b,v,y[8],2272392833,11),v=fnH(v,w,h,b,y[11],1839030562,16),b=fnH(b,v,w,h,y[14],4259657740,23),h=fnH(h,b,v,w,y[1],2763975236,4),w=fnH(w,h,b,v,y[4],1272893353,11),v=fnH(v,w,h,b,y[7],4139469664,16),b=fnH(b,v,w,h,y[10],3200236656,23),h=fnH(h,b,v,w,y[13],681279174,4),w=fnH(w,h,b,v,y[0],3936430074,11),v=fnH(v,w,h,b,y[3],3572445317,16),b=fnH(b,v,w,h,y[6],76029189,23),h=fnH(h,b,v,w,y[9],3654602809,4),w=fnH(w,h,b,v,y[12],3873151461,11),v=fnH(v,w,h,b,y[15],530742520,16),b=fnH(b,v,w,h,y[2],3299628645,23),h=fnI(h,b,v,w,y[0],4096336452,6),w=fnI(w,h,b,v,y[7],1126891415,10),v=fnI(v,w,h,b,y[14],2878612391,15),b=fnI(b,v,w,h,y[5],4237533241,21),h=fnI(h,b,v,w,y[12],1700485571,6),w=fnI(w,h,b,v,y[3],2399980690,10),v=fnI(v,w,h,b,y[10],4293915773,15),b=fnI(b,v,w,h,y[1],2240044497,21),h=fnI(h,b,v,w,y[8],1873313359,6),w=fnI(w,h,b,v,y[15],4264355552,10),v=fnI(v,w,h,b,y[6],2734768916,15),b=fnI(b,v,w,h,y[13],1309151649,21),h=fnI(h,b,v,w,y[4],4149444226,6),w=fnI(w,h,b,v,y[11],3174756917,10),v=fnI(v,w,h,b,y[2],718787259,15),b=fnI(b,v,w,h,y[9],3951481745,21),this._a=this._a+h|0,this._b=this._b+b|0,this._c=this._c+v|0,this._d=this._d+w|0};MD5$3.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var y=Buffer$y.allocUnsafe(16);return y.writeInt32LE(this._a,0),y.writeInt32LE(this._b,4),y.writeInt32LE(this._c,8),y.writeInt32LE(this._d,12),y};function rotl$1(y,u){return y<<u|y>>>32-u}function fnF(y,u,h,b,v,w,_){return rotl$1(y+(u&h|~u&b)+v+w|0,_)+u|0}function fnG(y,u,h,b,v,w,_){return rotl$1(y+(u&b|h&~b)+v+w|0,_)+u|0}function fnH(y,u,h,b,v,w,_){return rotl$1(y+(u^h^b)+v+w|0,_)+u|0}function fnI(y,u,h,b,v,w,_){return rotl$1(y+(h^(u|~b))+v+w|0,_)+u|0}var md5_js=MD5$3,Buffer$x=dist.Buffer,inherits$o=inherits_browserExports,HashBase=hashBase,ARRAY16=new Array(16),zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];function RIPEMD160$4(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}inherits$o(RIPEMD160$4,HashBase);RIPEMD160$4.prototype._update=function(){for(var y=ARRAY16,u=0;u<16;++u)y[u]=this._block.readInt32LE(u*4);for(var h=this._a|0,b=this._b|0,v=this._c|0,w=this._d|0,_=this._e|0,E=this._a|0,S=this._b|0,x=this._c|0,T=this._d|0,C=this._e|0,O=0;O<80;O+=1){var D,U;O<16?(D=fn1(h,b,v,w,_,y[zl[O]],hl[0],sl[O]),U=fn5(E,S,x,T,C,y[zr[O]],hr[0],sr[O])):O<32?(D=fn2(h,b,v,w,_,y[zl[O]],hl[1],sl[O]),U=fn4(E,S,x,T,C,y[zr[O]],hr[1],sr[O])):O<48?(D=fn3(h,b,v,w,_,y[zl[O]],hl[2],sl[O]),U=fn3(E,S,x,T,C,y[zr[O]],hr[2],sr[O])):O<64?(D=fn4(h,b,v,w,_,y[zl[O]],hl[3],sl[O]),U=fn2(E,S,x,T,C,y[zr[O]],hr[3],sr[O])):(D=fn5(h,b,v,w,_,y[zl[O]],hl[4],sl[O]),U=fn1(E,S,x,T,C,y[zr[O]],hr[4],sr[O])),h=_,_=w,w=rotl(v,10),v=b,b=D,E=C,C=T,T=rotl(x,10),x=S,S=U}var te=this._b+v+T|0;this._b=this._c+w+C|0,this._c=this._d+_+E|0,this._d=this._e+h+S|0,this._e=this._a+b+x|0,this._a=te};RIPEMD160$4.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var y=Buffer$x.alloc?Buffer$x.alloc(20):new Buffer$x(20);return y.writeInt32LE(this._a,0),y.writeInt32LE(this._b,4),y.writeInt32LE(this._c,8),y.writeInt32LE(this._d,12),y.writeInt32LE(this._e,16),y};function rotl(y,u){return y<<u|y>>>32-u}function fn1(y,u,h,b,v,w,_,E){return rotl(y+(u^h^b)+w+_|0,E)+v|0}function fn2(y,u,h,b,v,w,_,E){return rotl(y+(u&h|~u&b)+w+_|0,E)+v|0}function fn3(y,u,h,b,v,w,_,E){return rotl(y+((u|~h)^b)+w+_|0,E)+v|0}function fn4(y,u,h,b,v,w,_,E){return rotl(y+(u&b|h&~b)+w+_|0,E)+v|0}function fn5(y,u,h,b,v,w,_,E){return rotl(y+(u^(h|~b))+w+_|0,E)+v|0}var ripemd160=RIPEMD160$4,sha_js={exports:{}},Buffer$w=safeBufferExports$1.Buffer;function Hash$7(y,u){this._block=Buffer$w.alloc(y),this._finalSize=u,this._blockSize=y,this._len=0}Hash$7.prototype.update=function(y,u){typeof y=="string"&&(u=u||"utf8",y=Buffer$w.from(y,u));for(var h=this._block,b=this._blockSize,v=y.length,w=this._len,_=0;_<v;){for(var E=w%b,S=Math.min(v-_,b-E),x=0;x<S;x++)h[E+x]=y[_+x];w+=S,_+=S,w%b===0&&this._update(h)}return this._len+=v,this};Hash$7.prototype.digest=function(y){var u=this._len%this._blockSize;this._block[u]=128,this._block.fill(0,u+1),u>=this._finalSize&&(this._update(this._block),this._block.fill(0));var h=this._len*8;if(h<=4294967295)this._block.writeUInt32BE(h,this._blockSize-4);else{var b=(h&4294967295)>>>0,v=(h-b)/4294967296;this._block.writeUInt32BE(v,this._blockSize-8),this._block.writeUInt32BE(b,this._blockSize-4)}this._update(this._block);var w=this._hash();return y?w.toString(y):w};Hash$7.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var hash$3=Hash$7,inherits$n=inherits_browserExports,Hash$6=hash$3,Buffer$v=safeBufferExports$1.Buffer,K$4=[1518500249,1859775393,-1894007588,-899497514],W$5=new Array(80);function Sha(){this.init(),this._w=W$5,Hash$6.call(this,64,56)}inherits$n(Sha,Hash$6);Sha.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function rotl5$1(y){return y<<5|y>>>27}function rotl30$1(y){return y<<30|y>>>2}function ft$1(y,u,h,b){return y===0?u&h|~u&b:y===2?u&h|u&b|h&b:u^h^b}Sha.prototype._update=function(y){for(var u=this._w,h=this._a|0,b=this._b|0,v=this._c|0,w=this._d|0,_=this._e|0,E=0;E<16;++E)u[E]=y.readInt32BE(E*4);for(;E<80;++E)u[E]=u[E-3]^u[E-8]^u[E-14]^u[E-16];for(var S=0;S<80;++S){var x=~~(S/20),T=rotl5$1(h)+ft$1(x,b,v,w)+_+u[S]+K$4[x]|0;_=w,w=v,v=rotl30$1(b),b=h,h=T}this._a=h+this._a|0,this._b=b+this._b|0,this._c=v+this._c|0,this._d=w+this._d|0,this._e=_+this._e|0};Sha.prototype._hash=function(){var y=Buffer$v.allocUnsafe(20);return y.writeInt32BE(this._a|0,0),y.writeInt32BE(this._b|0,4),y.writeInt32BE(this._c|0,8),y.writeInt32BE(this._d|0,12),y.writeInt32BE(this._e|0,16),y};var sha$4=Sha,inherits$m=inherits_browserExports,Hash$5=hash$3,Buffer$u=safeBufferExports$1.Buffer,K$3=[1518500249,1859775393,-1894007588,-899497514],W$4=new Array(80);function Sha1(){this.init(),this._w=W$4,Hash$5.call(this,64,56)}inherits$m(Sha1,Hash$5);Sha1.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function rotl1(y){return y<<1|y>>>31}function rotl5(y){return y<<5|y>>>27}function rotl30(y){return y<<30|y>>>2}function ft(y,u,h,b){return y===0?u&h|~u&b:y===2?u&h|u&b|h&b:u^h^b}Sha1.prototype._update=function(y){for(var u=this._w,h=this._a|0,b=this._b|0,v=this._c|0,w=this._d|0,_=this._e|0,E=0;E<16;++E)u[E]=y.readInt32BE(E*4);for(;E<80;++E)u[E]=rotl1(u[E-3]^u[E-8]^u[E-14]^u[E-16]);for(var S=0;S<80;++S){var x=~~(S/20),T=rotl5(h)+ft(x,b,v,w)+_+u[S]+K$3[x]|0;_=w,w=v,v=rotl30(b),b=h,h=T}this._a=h+this._a|0,this._b=b+this._b|0,this._c=v+this._c|0,this._d=w+this._d|0,this._e=_+this._e|0};Sha1.prototype._hash=function(){var y=Buffer$u.allocUnsafe(20);return y.writeInt32BE(this._a|0,0),y.writeInt32BE(this._b|0,4),y.writeInt32BE(this._c|0,8),y.writeInt32BE(this._d|0,12),y.writeInt32BE(this._e|0,16),y};var sha1=Sha1,inherits$l=inherits_browserExports,Hash$4=hash$3,Buffer$t=safeBufferExports$1.Buffer,K$2=[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],W$3=new Array(64);function Sha256$1(){this.init(),this._w=W$3,Hash$4.call(this,64,56)}inherits$l(Sha256$1,Hash$4);Sha256$1.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function ch(y,u,h){return h^y&(u^h)}function maj$1(y,u,h){return y&u|h&(y|u)}function sigma0$1(y){return(y>>>2|y<<30)^(y>>>13|y<<19)^(y>>>22|y<<10)}function sigma1$1(y){return(y>>>6|y<<26)^(y>>>11|y<<21)^(y>>>25|y<<7)}function gamma0(y){return(y>>>7|y<<25)^(y>>>18|y<<14)^y>>>3}function gamma1(y){return(y>>>17|y<<15)^(y>>>19|y<<13)^y>>>10}Sha256$1.prototype._update=function(y){for(var u=this._w,h=this._a|0,b=this._b|0,v=this._c|0,w=this._d|0,_=this._e|0,E=this._f|0,S=this._g|0,x=this._h|0,T=0;T<16;++T)u[T]=y.readInt32BE(T*4);for(;T<64;++T)u[T]=gamma1(u[T-2])+u[T-7]+gamma0(u[T-15])+u[T-16]|0;for(var C=0;C<64;++C){var O=x+sigma1$1(_)+ch(_,E,S)+K$2[C]+u[C]|0,D=sigma0$1(h)+maj$1(h,b,v)|0;x=S,S=E,E=_,_=w+O|0,w=v,v=b,b=h,h=O+D|0}this._a=h+this._a|0,this._b=b+this._b|0,this._c=v+this._c|0,this._d=w+this._d|0,this._e=_+this._e|0,this._f=E+this._f|0,this._g=S+this._g|0,this._h=x+this._h|0};Sha256$1.prototype._hash=function(){var y=Buffer$t.allocUnsafe(32);return y.writeInt32BE(this._a,0),y.writeInt32BE(this._b,4),y.writeInt32BE(this._c,8),y.writeInt32BE(this._d,12),y.writeInt32BE(this._e,16),y.writeInt32BE(this._f,20),y.writeInt32BE(this._g,24),y.writeInt32BE(this._h,28),y};var sha256$1=Sha256$1,inherits$k=inherits_browserExports,Sha256=sha256$1,Hash$3=hash$3,Buffer$s=safeBufferExports$1.Buffer,W$2=new Array(64);function Sha224(){this.init(),this._w=W$2,Hash$3.call(this,64,56)}inherits$k(Sha224,Sha256);Sha224.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this};Sha224.prototype._hash=function(){var y=Buffer$s.allocUnsafe(28);return y.writeInt32BE(this._a,0),y.writeInt32BE(this._b,4),y.writeInt32BE(this._c,8),y.writeInt32BE(this._d,12),y.writeInt32BE(this._e,16),y.writeInt32BE(this._f,20),y.writeInt32BE(this._g,24),y};var sha224$1=Sha224,inherits$j=inherits_browserExports,Hash$2=hash$3,Buffer$r=safeBufferExports$1.Buffer,K$1=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],W$1=new Array(160);function Sha512(){this.init(),this._w=W$1,Hash$2.call(this,128,112)}inherits$j(Sha512,Hash$2);Sha512.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function Ch(y,u,h){return h^y&(u^h)}function maj(y,u,h){return y&u|h&(y|u)}function sigma0(y,u){return(y>>>28|u<<4)^(u>>>2|y<<30)^(u>>>7|y<<25)}function sigma1(y,u){return(y>>>14|u<<18)^(y>>>18|u<<14)^(u>>>9|y<<23)}function Gamma0(y,u){return(y>>>1|u<<31)^(y>>>8|u<<24)^y>>>7}function Gamma0l(y,u){return(y>>>1|u<<31)^(y>>>8|u<<24)^(y>>>7|u<<25)}function Gamma1(y,u){return(y>>>19|u<<13)^(u>>>29|y<<3)^y>>>6}function Gamma1l(y,u){return(y>>>19|u<<13)^(u>>>29|y<<3)^(y>>>6|u<<26)}function getCarry(y,u){return y>>>0<u>>>0?1:0}Sha512.prototype._update=function(y){for(var u=this._w,h=this._ah|0,b=this._bh|0,v=this._ch|0,w=this._dh|0,_=this._eh|0,E=this._fh|0,S=this._gh|0,x=this._hh|0,T=this._al|0,C=this._bl|0,O=this._cl|0,D=this._dl|0,U=this._el|0,te=this._fl|0,X=this._gl|0,ie=this._hl|0,ee=0;ee<32;ee+=2)u[ee]=y.readInt32BE(ee*4),u[ee+1]=y.readInt32BE(ee*4+4);for(;ee<160;ee+=2){var ae=u[ee-30],de=u[ee-15*2+1],Se=Gamma0(ae,de),ve=Gamma0l(de,ae);ae=u[ee-2*2],de=u[ee-2*2+1];var Pe=Gamma1(ae,de),Ie=Gamma1l(de,ae),Ee=u[ee-7*2],De=u[ee-7*2+1],be=u[ee-16*2],B=u[ee-16*2+1],F=ve+De|0,M=Se+Ee+getCarry(F,ve)|0;F=F+Ie|0,M=M+Pe+getCarry(F,Ie)|0,F=F+B|0,M=M+be+getCarry(F,B)|0,u[ee]=M,u[ee+1]=F}for(var N=0;N<160;N+=2){M=u[N],F=u[N+1];var Q=maj(h,b,v),j=maj(T,C,O),ne=sigma0(h,T),J=sigma0(T,h),q=sigma1(_,U),re=sigma1(U,_),H=K$1[N],he=K$1[N+1],Oe=Ch(_,E,S),Ne=Ch(U,te,X),Ae=ie+re|0,le=x+q+getCarry(Ae,ie)|0;Ae=Ae+Ne|0,le=le+Oe+getCarry(Ae,Ne)|0,Ae=Ae+he|0,le=le+H+getCarry(Ae,he)|0,Ae=Ae+F|0,le=le+M+getCarry(Ae,F)|0;var me=J+j|0,Me=ne+Q+getCarry(me,J)|0;x=S,ie=X,S=E,X=te,E=_,te=U,U=D+Ae|0,_=w+le+getCarry(U,D)|0,w=v,D=O,v=b,O=C,b=h,C=T,T=Ae+me|0,h=le+Me+getCarry(T,Ae)|0}this._al=this._al+T|0,this._bl=this._bl+C|0,this._cl=this._cl+O|0,this._dl=this._dl+D|0,this._el=this._el+U|0,this._fl=this._fl+te|0,this._gl=this._gl+X|0,this._hl=this._hl+ie|0,this._ah=this._ah+h+getCarry(this._al,T)|0,this._bh=this._bh+b+getCarry(this._bl,C)|0,this._ch=this._ch+v+getCarry(this._cl,O)|0,this._dh=this._dh+w+getCarry(this._dl,D)|0,this._eh=this._eh+_+getCarry(this._el,U)|0,this._fh=this._fh+E+getCarry(this._fl,te)|0,this._gh=this._gh+S+getCarry(this._gl,X)|0,this._hh=this._hh+x+getCarry(this._hl,ie)|0};Sha512.prototype._hash=function(){var y=Buffer$r.allocUnsafe(64);function u(h,b,v){y.writeInt32BE(h,v),y.writeInt32BE(b,v+4)}return u(this._ah,this._al,0),u(this._bh,this._bl,8),u(this._ch,this._cl,16),u(this._dh,this._dl,24),u(this._eh,this._el,32),u(this._fh,this._fl,40),u(this._gh,this._gl,48),u(this._hh,this._hl,56),y};var sha512$1=Sha512,inherits$i=inherits_browserExports,SHA512$2=sha512$1,Hash$1=hash$3,Buffer$q=safeBufferExports$1.Buffer,W=new Array(160);function Sha384(){this.init(),this._w=W,Hash$1.call(this,128,112)}inherits$i(Sha384,SHA512$2);Sha384.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this};Sha384.prototype._hash=function(){var y=Buffer$q.allocUnsafe(48);function u(h,b,v){y.writeInt32BE(h,v),y.writeInt32BE(b,v+4)}return u(this._ah,this._al,0),u(this._bh,this._bl,8),u(this._ch,this._cl,16),u(this._dh,this._dl,24),u(this._eh,this._el,32),u(this._fh,this._fl,40),y};var sha384$1=Sha384,exports$1=sha_js.exports=function(u){u=u.toLowerCase();var h=exports$1[u];if(!h)throw new Error(u+" is not supported (we accept pull requests)");return new h};exports$1.sha=sha$4;exports$1.sha1=sha1;exports$1.sha224=sha224$1;exports$1.sha256=sha256$1;exports$1.sha384=sha384$1;exports$1.sha512=sha512$1;var sha_jsExports=sha_js.exports,streamBrowserify=Stream,EE=eventsExports.EventEmitter,inherits$h=inherits_browserExports;inherits$h(Stream,EE);Stream.Readable=require_stream_readable$1();Stream.Writable=require_stream_writable$1();Stream.Duplex=require_stream_duplex$1();Stream.Transform=_stream_transform$1;Stream.PassThrough=_stream_passthrough$1;Stream.finished=endOfStream;Stream.pipeline=pipeline_1;Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(y,u){var h=this;function b(T){y.writable&&y.write(T)===!1&&h.pause&&h.pause()}h.on("data",b);function v(){h.readable&&h.resume&&h.resume()}y.on("drain",v),!y._isStdio&&(!u||u.end!==!1)&&(h.on("end",_),h.on("close",E));var w=!1;function _(){w||(w=!0,y.end())}function E(){w||(w=!0,typeof y.destroy=="function"&&y.destroy())}function S(T){if(x(),EE.listenerCount(this,"error")===0)throw T}h.on("error",S),y.on("error",S);function x(){h.removeListener("data",b),y.removeListener("drain",v),h.removeListener("end",_),h.removeListener("close",E),h.removeListener("error",S),y.removeListener("error",S),h.removeListener("end",x),h.removeListener("close",x),y.removeListener("close",x)}return h.on("end",x),h.on("close",x),y.on("close",x),y.emit("pipe",h),y};var Buffer$p=safeBufferExports$1.Buffer,Transform$6=streamBrowserify.Transform,StringDecoder=string_decoder.StringDecoder,inherits$g=inherits_browserExports;function CipherBase$1(y){Transform$6.call(this),this.hashMode=typeof y=="string",this.hashMode?this[y]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}inherits$g(CipherBase$1,Transform$6);CipherBase$1.prototype.update=function(y,u,h){typeof y=="string"&&(y=Buffer$p.from(y,u));var b=this._update(y);return this.hashMode?this:(h&&(b=this._toString(b,h)),b)};CipherBase$1.prototype.setAutoPadding=function(){};CipherBase$1.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")};CipherBase$1.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")};CipherBase$1.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")};CipherBase$1.prototype._transform=function(y,u,h){var b;try{this.hashMode?this._update(y):this.push(this._update(y))}catch(v){b=v}finally{h(b)}};CipherBase$1.prototype._flush=function(y){var u;try{this.push(this.__final())}catch(h){u=h}y(u)};CipherBase$1.prototype._finalOrDigest=function(y){var u=this.__final()||Buffer$p.alloc(0);return y&&(u=this._toString(u,y,!0)),u};CipherBase$1.prototype._toString=function(y,u,h){if(this._decoder||(this._decoder=new StringDecoder(u),this._encoding=u),this._encoding!==u)throw new Error("can't switch encodings");var b=this._decoder.write(y);return h&&(b+=this._decoder.end()),b};var cipherBase=CipherBase$1,inherits$f=inherits_browserExports,MD5$2=md5_js,RIPEMD160$3=ripemd160,sha$3=sha_jsExports,Base$5=cipherBase;function Hash(y){Base$5.call(this,"digest"),this._hash=y}inherits$f(Hash,Base$5);Hash.prototype._update=function(y){this._hash.update(y)};Hash.prototype._final=function(){return this._hash.digest()};var browser$9=function(u){return u=u.toLowerCase(),u==="md5"?new MD5$2:u==="rmd160"||u==="ripemd160"?new RIPEMD160$3:new Hash(sha$3(u))},inherits$e=inherits_browserExports,Buffer$o=safeBufferExports$1.Buffer,Base$4=cipherBase,ZEROS$2=Buffer$o.alloc(128),blocksize=64;function Hmac$3(y,u){Base$4.call(this,"digest"),typeof u=="string"&&(u=Buffer$o.from(u)),this._alg=y,this._key=u,u.length>blocksize?u=y(u):u.length<blocksize&&(u=Buffer$o.concat([u,ZEROS$2],blocksize));for(var h=this._ipad=Buffer$o.allocUnsafe(blocksize),b=this._opad=Buffer$o.allocUnsafe(blocksize),v=0;v<blocksize;v++)h[v]=u[v]^54,b[v]=u[v]^92;this._hash=[h]}inherits$e(Hmac$3,Base$4);Hmac$3.prototype._update=function(y){this._hash.push(y)};Hmac$3.prototype._final=function(){var y=this._alg(Buffer$o.concat(this._hash));return this._alg(Buffer$o.concat([this._opad,y]))};var legacy=Hmac$3,MD5$1=md5_js,md5$2=function(y){return new MD5$1().update(y).digest()},inherits$d=inherits_browserExports,Legacy=legacy,Base$3=cipherBase,Buffer$n=safeBufferExports$1.Buffer,md5$1=md5$2,RIPEMD160$2=ripemd160,sha$2=sha_jsExports,ZEROS$1=Buffer$n.alloc(128);function Hmac$2(y,u){Base$3.call(this,"digest"),typeof u=="string"&&(u=Buffer$n.from(u));var h=y==="sha512"||y==="sha384"?128:64;if(this._alg=y,this._key=u,u.length>h){var b=y==="rmd160"?new RIPEMD160$2:sha$2(y);u=b.update(u).digest()}else u.length<h&&(u=Buffer$n.concat([u,ZEROS$1],h));for(var v=this._ipad=Buffer$n.allocUnsafe(h),w=this._opad=Buffer$n.allocUnsafe(h),_=0;_<h;_++)v[_]=u[_]^54,w[_]=u[_]^92;this._hash=y==="rmd160"?new RIPEMD160$2:sha$2(y),this._hash.update(v)}inherits$d(Hmac$2,Base$3);Hmac$2.prototype._update=function(y){this._hash.update(y)};Hmac$2.prototype._final=function(){var y=this._hash.digest(),u=this._alg==="rmd160"?new RIPEMD160$2:sha$2(this._alg);return u.update(this._opad).update(y).digest()};var browser$8=function(u,h){return u=u.toLowerCase(),u==="rmd160"||u==="ripemd160"?new Hmac$2("rmd160",h):u==="md5"?new Legacy(md5$1,h):new Hmac$2(u,h)};const sha224WithRSAEncryption={sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption={sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption={sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption={sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},sha256={sign:"ecdsa",hash:"sha256",id:""},sha224={sign:"ecdsa",hash:"sha224",id:""},sha384={sign:"ecdsa",hash:"sha384",id:""},sha512={sign:"ecdsa",hash:"sha512",id:""},DSA={sign:"dsa",hash:"sha1",id:""},ripemd160WithRSA={sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption={sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},require$$6={sha224WithRSAEncryption,"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption,"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption,"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption,"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256,sha224,sha384,sha512,"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA,"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA,"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption,"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}};var algos=require$$6,browser$7={},MAX_ALLOC=Math.pow(2,30)-1,precondition=function(y,u){if(typeof y!="number")throw new TypeError("Iterations not a number");if(y<0)throw new TypeError("Bad iterations");if(typeof u!="number")throw new TypeError("Key length not a number");if(u<0||u>MAX_ALLOC||u!==u)throw new TypeError("Bad key length")},defaultEncoding$2;if(commonjsGlobal.process&&commonjsGlobal.process.browser)defaultEncoding$2="utf-8";else if(commonjsGlobal.process&&commonjsGlobal.process.version){var pVersionMajor=parseInt(process$1.version.split(".")[0].slice(1),10);defaultEncoding$2=pVersionMajor>=6?"utf-8":"binary"}else defaultEncoding$2="utf-8";var defaultEncoding_1=defaultEncoding$2,Buffer$m=safeBufferExports$1.Buffer,toBuffer$2=function(y,u,h){if(Buffer$m.isBuffer(y))return y;if(typeof y=="string")return Buffer$m.from(y,u);if(ArrayBuffer.isView(y))return Buffer$m.from(y.buffer);throw new TypeError(h+" must be a string, a Buffer, a typed array or a DataView")},md5=md5$2,RIPEMD160$1=ripemd160,sha$1=sha_jsExports,Buffer$l=safeBufferExports$1.Buffer,checkParameters$1=precondition,defaultEncoding$1=defaultEncoding_1,toBuffer$1=toBuffer$2,ZEROS=Buffer$l.alloc(128),sizes={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function Hmac$1(y,u,h){var b=getDigest(y),v=y==="sha512"||y==="sha384"?128:64;u.length>v?u=b(u):u.length<v&&(u=Buffer$l.concat([u,ZEROS],v));for(var w=Buffer$l.allocUnsafe(v+sizes[y]),_=Buffer$l.allocUnsafe(v+sizes[y]),E=0;E<v;E++)w[E]=u[E]^54,_[E]=u[E]^92;var S=Buffer$l.allocUnsafe(v+h+4);w.copy(S,0,0,v),this.ipad1=S,this.ipad2=w,this.opad=_,this.alg=y,this.blocksize=v,this.hash=b,this.size=sizes[y]}Hmac$1.prototype.run=function(y,u){y.copy(u,this.blocksize);var h=this.hash(u);return h.copy(this.opad,this.blocksize),this.hash(this.opad)};function getDigest(y){function u(b){return sha$1(y).update(b).digest()}function h(b){return new RIPEMD160$1().update(b).digest()}return y==="rmd160"||y==="ripemd160"?h:y==="md5"?md5:u}function pbkdf2(y,u,h,b,v){checkParameters$1(h,b),y=toBuffer$1(y,defaultEncoding$1,"Password"),u=toBuffer$1(u,defaultEncoding$1,"Salt"),v=v||"sha1";var w=new Hmac$1(v,y,u.length),_=Buffer$l.allocUnsafe(b),E=Buffer$l.allocUnsafe(u.length+4);u.copy(E,0,0,u.length);for(var S=0,x=sizes[v],T=Math.ceil(b/x),C=1;C<=T;C++){E.writeUInt32BE(C,u.length);for(var O=w.run(E,w.ipad1),D=O,U=1;U<h;U++){D=w.run(D,w.ipad2);for(var te=0;te<x;te++)O[te]^=D[te]}O.copy(_,S),S+=x}return _}var syncBrowser=pbkdf2,Buffer$k=safeBufferExports$1.Buffer,checkParameters=precondition,defaultEncoding=defaultEncoding_1,sync=syncBrowser,toBuffer=toBuffer$2,ZERO_BUF,subtle=commonjsGlobal.crypto&&commonjsGlobal.crypto.subtle,toBrowser={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},checks=[];function checkNative(y){if(commonjsGlobal.process&&!commonjsGlobal.process.browser||!subtle||!subtle.importKey||!subtle.deriveBits)return Promise.resolve(!1);if(checks[y]!==void 0)return checks[y];ZERO_BUF=ZERO_BUF||Buffer$k.alloc(8);var u=browserPbkdf2(ZERO_BUF,ZERO_BUF,10,128,y).then(function(){return!0}).catch(function(){return!1});return checks[y]=u,u}var nextTick$1;function getNextTick(){return nextTick$1||(commonjsGlobal.process&&commonjsGlobal.process.nextTick?nextTick$1=commonjsGlobal.process.nextTick:commonjsGlobal.queueMicrotask?nextTick$1=commonjsGlobal.queueMicrotask:commonjsGlobal.setImmediate?nextTick$1=commonjsGlobal.setImmediate:nextTick$1=commonjsGlobal.setTimeout,nextTick$1)}function browserPbkdf2(y,u,h,b,v){return subtle.importKey("raw",y,{name:"PBKDF2"},!1,["deriveBits"]).then(function(w){return subtle.deriveBits({name:"PBKDF2",salt:u,iterations:h,hash:{name:v}},w,b<<3)}).then(function(w){return Buffer$k.from(w)})}function resolvePromise(y,u){y.then(function(h){getNextTick()(function(){u(null,h)})},function(h){getNextTick()(function(){u(h)})})}var async=function(y,u,h,b,v,w){typeof v=="function"&&(w=v,v=void 0),v=v||"sha1";var _=toBrowser[v.toLowerCase()];if(!_||typeof commonjsGlobal.Promise!="function"){getNextTick()(function(){var E;try{E=sync(y,u,h,b,v)}catch(S){return w(S)}w(null,E)});return}if(checkParameters(h,b),y=toBuffer(y,defaultEncoding,"Password"),u=toBuffer(u,defaultEncoding,"Salt"),typeof w!="function")throw new Error("No callback provided to pbkdf2");resolvePromise(checkNative(_).then(function(E){return E?browserPbkdf2(y,u,h,b,_):sync(y,u,h,b,v)}),w)};browser$7.pbkdf2=async;browser$7.pbkdf2Sync=syncBrowser;var browser$6={},des$2={},utils$o={};utils$o.readUInt32BE=function(u,h){var b=u[0+h]<<24|u[1+h]<<16|u[2+h]<<8|u[3+h];return b>>>0};utils$o.writeUInt32BE=function(u,h,b){u[0+b]=h>>>24,u[1+b]=h>>>16&255,u[2+b]=h>>>8&255,u[3+b]=h&255};utils$o.ip=function(u,h,b,v){for(var w=0,_=0,E=6;E>=0;E-=2){for(var S=0;S<=24;S+=8)w<<=1,w|=h>>>S+E&1;for(var S=0;S<=24;S+=8)w<<=1,w|=u>>>S+E&1}for(var E=6;E>=0;E-=2){for(var S=1;S<=25;S+=8)_<<=1,_|=h>>>S+E&1;for(var S=1;S<=25;S+=8)_<<=1,_|=u>>>S+E&1}b[v+0]=w>>>0,b[v+1]=_>>>0};utils$o.rip=function(u,h,b,v){for(var w=0,_=0,E=0;E<4;E++)for(var S=24;S>=0;S-=8)w<<=1,w|=h>>>S+E&1,w<<=1,w|=u>>>S+E&1;for(var E=4;E<8;E++)for(var S=24;S>=0;S-=8)_<<=1,_|=h>>>S+E&1,_<<=1,_|=u>>>S+E&1;b[v+0]=w>>>0,b[v+1]=_>>>0};utils$o.pc1=function(u,h,b,v){for(var w=0,_=0,E=7;E>=5;E--){for(var S=0;S<=24;S+=8)w<<=1,w|=h>>S+E&1;for(var S=0;S<=24;S+=8)w<<=1,w|=u>>S+E&1}for(var S=0;S<=24;S+=8)w<<=1,w|=h>>S+E&1;for(var E=1;E<=3;E++){for(var S=0;S<=24;S+=8)_<<=1,_|=h>>S+E&1;for(var S=0;S<=24;S+=8)_<<=1,_|=u>>S+E&1}for(var S=0;S<=24;S+=8)_<<=1,_|=u>>S+E&1;b[v+0]=w>>>0,b[v+1]=_>>>0};utils$o.r28shl=function(u,h){return u<<h&268435455|u>>>28-h};var pc2table=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];utils$o.pc2=function(u,h,b,v){for(var w=0,_=0,E=pc2table.length>>>1,S=0;S<E;S++)w<<=1,w|=u>>>pc2table[S]&1;for(var S=E;S<pc2table.length;S++)_<<=1,_|=h>>>pc2table[S]&1;b[v+0]=w>>>0,b[v+1]=_>>>0};utils$o.expand=function(u,h,b){var v=0,w=0;v=(u&1)<<5|u>>>27;for(var _=23;_>=15;_-=4)v<<=6,v|=u>>>_&63;for(var _=11;_>=3;_-=4)w|=u>>>_&63,w<<=6;w|=(u&31)<<1|u>>>31,h[b+0]=v>>>0,h[b+1]=w>>>0};var sTable=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];utils$o.substitute=function(u,h){for(var b=0,v=0;v<4;v++){var w=u>>>18-v*6&63,_=sTable[v*64+w];b<<=4,b|=_}for(var v=0;v<4;v++){var w=h>>>18-v*6&63,_=sTable[4*64+v*64+w];b<<=4,b|=_}return b>>>0};var permuteTable=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];utils$o.permute=function(u){for(var h=0,b=0;b<permuteTable.length;b++)h<<=1,h|=u>>>permuteTable[b]&1;return h>>>0};utils$o.padSplit=function(u,h,b){for(var v=u.toString(2);v.length<h;)v="0"+v;for(var w=[],_=0;_<h;_+=b)w.push(v.slice(_,_+b));return w.join(" ")};var minimalisticAssert=assert$i;function assert$i(y,u){if(!y)throw new Error(u||"Assertion failed")}assert$i.equal=function(u,h,b){if(u!=h)throw new Error(b||"Assertion failed: "+u+" != "+h)};var assert$h=minimalisticAssert;function Cipher$3(y){this.options=y,this.type=this.options.type,this.blockSize=8,this._init(),this.buffer=new Array(this.blockSize),this.bufferOff=0,this.padding=y.padding!==!1}var cipher=Cipher$3;Cipher$3.prototype._init=function(){};Cipher$3.prototype.update=function(u){return u.length===0?[]:this.type==="decrypt"?this._updateDecrypt(u):this._updateEncrypt(u)};Cipher$3.prototype._buffer=function(u,h){for(var b=Math.min(this.buffer.length-this.bufferOff,u.length-h),v=0;v<b;v++)this.buffer[this.bufferOff+v]=u[h+v];return this.bufferOff+=b,b};Cipher$3.prototype._flushBuffer=function(u,h){return this._update(this.buffer,0,u,h),this.bufferOff=0,this.blockSize};Cipher$3.prototype._updateEncrypt=function(u){var h=0,b=0,v=(this.bufferOff+u.length)/this.blockSize|0,w=new Array(v*this.blockSize);this.bufferOff!==0&&(h+=this._buffer(u,h),this.bufferOff===this.buffer.length&&(b+=this._flushBuffer(w,b)));for(var _=u.length-(u.length-h)%this.blockSize;h<_;h+=this.blockSize)this._update(u,h,w,b),b+=this.blockSize;for(;h<u.length;h++,this.bufferOff++)this.buffer[this.bufferOff]=u[h];return w};Cipher$3.prototype._updateDecrypt=function(u){for(var h=0,b=0,v=Math.ceil((this.bufferOff+u.length)/this.blockSize)-1,w=new Array(v*this.blockSize);v>0;v--)h+=this._buffer(u,h),b+=this._flushBuffer(w,b);return h+=this._buffer(u,h),w};Cipher$3.prototype.final=function(u){var h;u&&(h=this.update(u));var b;return this.type==="encrypt"?b=this._finalEncrypt():b=this._finalDecrypt(),h?h.concat(b):b};Cipher$3.prototype._pad=function(u,h){if(h===0)return!1;for(;h<u.length;)u[h++]=0;return!0};Cipher$3.prototype._finalEncrypt=function(){if(!this._pad(this.buffer,this.bufferOff))return[];var u=new Array(this.blockSize);return this._update(this.buffer,0,u,0),u};Cipher$3.prototype._unpad=function(u){return u};Cipher$3.prototype._finalDecrypt=function(){assert$h.equal(this.bufferOff,this.blockSize,"Not enough data to decrypt");var u=new Array(this.blockSize);return this._flushBuffer(u,0),this._unpad(u)};var assert$g=minimalisticAssert,inherits$c=inherits_browserExports,utils$n=utils$o,Cipher$2=cipher;function DESState(){this.tmp=new Array(2),this.keys=null}function DES$3(y){Cipher$2.call(this,y);var u=new DESState;this._desState=u,this.deriveKeys(u,y.key)}inherits$c(DES$3,Cipher$2);var des$1=DES$3;DES$3.create=function(u){return new DES$3(u)};var shiftTable=[1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1];DES$3.prototype.deriveKeys=function(u,h){u.keys=new Array(16*2),assert$g.equal(h.length,this.blockSize,"Invalid key length");var b=utils$n.readUInt32BE(h,0),v=utils$n.readUInt32BE(h,4);utils$n.pc1(b,v,u.tmp,0),b=u.tmp[0],v=u.tmp[1];for(var w=0;w<u.keys.length;w+=2){var _=shiftTable[w>>>1];b=utils$n.r28shl(b,_),v=utils$n.r28shl(v,_),utils$n.pc2(b,v,u.keys,w)}};DES$3.prototype._update=function(u,h,b,v){var w=this._desState,_=utils$n.readUInt32BE(u,h),E=utils$n.readUInt32BE(u,h+4);utils$n.ip(_,E,w.tmp,0),_=w.tmp[0],E=w.tmp[1],this.type==="encrypt"?this._encrypt(w,_,E,w.tmp,0):this._decrypt(w,_,E,w.tmp,0),_=w.tmp[0],E=w.tmp[1],utils$n.writeUInt32BE(b,_,v),utils$n.writeUInt32BE(b,E,v+4)};DES$3.prototype._pad=function(u,h){if(this.padding===!1)return!1;for(var b=u.length-h,v=h;v<u.length;v++)u[v]=b;return!0};DES$3.prototype._unpad=function(u){if(this.padding===!1)return u;for(var h=u[u.length-1],b=u.length-h;b<u.length;b++)assert$g.equal(u[b],h);return u.slice(0,u.length-h)};DES$3.prototype._encrypt=function(u,h,b,v,w){for(var _=h,E=b,S=0;S<u.keys.length;S+=2){var x=u.keys[S],T=u.keys[S+1];utils$n.expand(E,u.tmp,0),x^=u.tmp[0],T^=u.tmp[1];var C=utils$n.substitute(x,T),O=utils$n.permute(C),D=E;E=(_^O)>>>0,_=D}utils$n.rip(E,_,v,w)};DES$3.prototype._decrypt=function(u,h,b,v,w){for(var _=b,E=h,S=u.keys.length-2;S>=0;S-=2){var x=u.keys[S],T=u.keys[S+1];utils$n.expand(_,u.tmp,0),x^=u.tmp[0],T^=u.tmp[1];var C=utils$n.substitute(x,T),O=utils$n.permute(C),D=_;_=(E^O)>>>0,E=D}utils$n.rip(_,E,v,w)};var cbc$1={},assert$f=minimalisticAssert,inherits$b=inherits_browserExports,proto={};function CBCState(y){assert$f.equal(y.length,8,"Invalid IV length"),this.iv=new Array(8);for(var u=0;u<this.iv.length;u++)this.iv[u]=y[u]}function instantiate(y){function u(w){y.call(this,w),this._cbcInit()}inherits$b(u,y);for(var h=Object.keys(proto),b=0;b<h.length;b++){var v=h[b];u.prototype[v]=proto[v]}return u.create=function(_){return new u(_)},u}cbc$1.instantiate=instantiate;proto._cbcInit=function(){var u=new CBCState(this.options.iv);this._cbcState=u};proto._update=function(u,h,b,v){var w=this._cbcState,_=this.constructor.super_.prototype,E=w.iv;if(this.type==="encrypt"){for(var S=0;S<this.blockSize;S++)E[S]^=u[h+S];_._update.call(this,E,0,b,v);for(var S=0;S<this.blockSize;S++)E[S]=b[v+S]}else{_._update.call(this,u,h,b,v);for(var S=0;S<this.blockSize;S++)b[v+S]^=E[S];for(var S=0;S<this.blockSize;S++)E[S]=u[h+S]}};var assert$e=minimalisticAssert,inherits$a=inherits_browserExports,Cipher$1=cipher,DES$2=des$1;function EDEState(y,u){assert$e.equal(u.length,24,"Invalid key length");var h=u.slice(0,8),b=u.slice(8,16),v=u.slice(16,24);y==="encrypt"?this.ciphers=[DES$2.create({type:"encrypt",key:h}),DES$2.create({type:"decrypt",key:b}),DES$2.create({type:"encrypt",key:v})]:this.ciphers=[DES$2.create({type:"decrypt",key:v}),DES$2.create({type:"encrypt",key:b}),DES$2.create({type:"decrypt",key:h})]}function EDE(y){Cipher$1.call(this,y);var u=new EDEState(this.type,this.options.key);this._edeState=u}inherits$a(EDE,Cipher$1);var ede=EDE;EDE.create=function(u){return new EDE(u)};EDE.prototype._update=function(u,h,b,v){var w=this._edeState;w.ciphers[0]._update(u,h,b,v),w.ciphers[1]._update(b,v,b,v),w.ciphers[2]._update(b,v,b,v)};EDE.prototype._pad=DES$2.prototype._pad;EDE.prototype._unpad=DES$2.prototype._unpad;des$2.utils=utils$o;des$2.Cipher=cipher;des$2.DES=des$1;des$2.CBC=cbc$1;des$2.EDE=ede;var CipherBase=cipherBase,des=des$2,inherits$9=inherits_browserExports,Buffer$j=safeBufferExports$1.Buffer,modes$3={"des-ede3-cbc":des.CBC.instantiate(des.EDE),"des-ede3":des.EDE,"des-ede-cbc":des.CBC.instantiate(des.EDE),"des-ede":des.EDE,"des-cbc":des.CBC.instantiate(des.DES),"des-ecb":des.DES};modes$3.des=modes$3["des-cbc"];modes$3.des3=modes$3["des-ede3-cbc"];var browserifyDes=DES$1;inherits$9(DES$1,CipherBase);function DES$1(y){CipherBase.call(this);var u=y.mode.toLowerCase(),h=modes$3[u],b;y.decrypt?b="decrypt":b="encrypt";var v=y.key;Buffer$j.isBuffer(v)||(v=Buffer$j.from(v)),(u==="des-ede"||u==="des-ede-cbc")&&(v=Buffer$j.concat([v,v.slice(0,8)]));var w=y.iv;Buffer$j.isBuffer(w)||(w=Buffer$j.from(w)),this._des=h.create({key:v,iv:w,type:b})}DES$1.prototype._update=function(y){return Buffer$j.from(this._des.update(y))};DES$1.prototype._final=function(){return Buffer$j.from(this._des.final())};var browser$5={},encrypter={},ecb={};ecb.encrypt=function(y,u){return y._cipher.encryptBlock(u)};ecb.decrypt=function(y,u){return y._cipher.decryptBlock(u)};var cbc={},bufferXor=function(u,h){for(var b=Math.min(u.length,h.length),v=new Buffer$C(b),w=0;w<b;++w)v[w]=u[w]^h[w];return v},xor$7=bufferXor;cbc.encrypt=function(y,u){var h=xor$7(u,y._prev);return y._prev=y._cipher.encryptBlock(h),y._prev};cbc.decrypt=function(y,u){var h=y._prev;y._prev=u;var b=y._cipher.decryptBlock(u);return xor$7(b,h)};var cfb={},Buffer$i=safeBufferExports$1.Buffer,xor$6=bufferXor;function encryptStart(y,u,h){var b=u.length,v=xor$6(u,y._cache);return y._cache=y._cache.slice(b),y._prev=Buffer$i.concat([y._prev,h?u:v]),v}cfb.encrypt=function(y,u,h){for(var b=Buffer$i.allocUnsafe(0),v;u.length;)if(y._cache.length===0&&(y._cache=y._cipher.encryptBlock(y._prev),y._prev=Buffer$i.allocUnsafe(0)),y._cache.length<=u.length)v=y._cache.length,b=Buffer$i.concat([b,encryptStart(y,u.slice(0,v),h)]),u=u.slice(v);else{b=Buffer$i.concat([b,encryptStart(y,u,h)]);break}return b};var cfb8={},Buffer$h=safeBufferExports$1.Buffer;function encryptByte$1(y,u,h){var b=y._cipher.encryptBlock(y._prev),v=b[0]^u;return y._prev=Buffer$h.concat([y._prev.slice(1),Buffer$h.from([h?u:v])]),v}cfb8.encrypt=function(y,u,h){for(var b=u.length,v=Buffer$h.allocUnsafe(b),w=-1;++w<b;)v[w]=encryptByte$1(y,u[w],h);return v};var cfb1={},Buffer$g=safeBufferExports$1.Buffer;function encryptByte(y,u,h){for(var b,v=-1,w=8,_=0,E,S;++v<w;)b=y._cipher.encryptBlock(y._prev),E=u&1<<7-v?128:0,S=b[0]^E,_+=(S&128)>>v%8,y._prev=shiftIn(y._prev,h?E:S);return _}function shiftIn(y,u){var h=y.length,b=-1,v=Buffer$g.allocUnsafe(y.length);for(y=Buffer$g.concat([y,Buffer$g.from([u])]);++b<h;)v[b]=y[b]<<1|y[b+1]>>7;return v}cfb1.encrypt=function(y,u,h){for(var b=u.length,v=Buffer$g.allocUnsafe(b),w=-1;++w<b;)v[w]=encryptByte(y,u[w],h);return v};var ofb={},xor$5=bufferXor;function getBlock$1(y){return y._prev=y._cipher.encryptBlock(y._prev),y._prev}ofb.encrypt=function(y,u){for(;y._cache.length<u.length;)y._cache=Buffer$C.concat([y._cache,getBlock$1(y)]);var h=y._cache.slice(0,u.length);return y._cache=y._cache.slice(u.length),xor$5(u,h)};var ctr={};function incr32$2(y){for(var u=y.length,h;u--;)if(h=y.readUInt8(u),h===255)y.writeUInt8(0,u);else{h++,y.writeUInt8(h,u);break}}var incr32_1=incr32$2,xor$4=bufferXor,Buffer$f=safeBufferExports$1.Buffer,incr32$1=incr32_1;function getBlock(y){var u=y._cipher.encryptBlockRaw(y._prev);return incr32$1(y._prev),u}var blockSize=16;ctr.encrypt=function(y,u){var h=Math.ceil(u.length/blockSize),b=y._cache.length;y._cache=Buffer$f.concat([y._cache,Buffer$f.allocUnsafe(h*blockSize)]);for(var v=0;v<h;v++){var w=getBlock(y),_=b+v*blockSize;y._cache.writeUInt32BE(w[0],_+0),y._cache.writeUInt32BE(w[1],_+4),y._cache.writeUInt32BE(w[2],_+8),y._cache.writeUInt32BE(w[3],_+12)}var E=y._cache.slice(0,u.length);return y._cache=y._cache.slice(u.length),xor$4(u,E)};const aes128={cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},aes192={cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},aes256={cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},require$$2={"aes-128-ecb":{cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"},"aes-192-ecb":{cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"},"aes-256-ecb":{cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"},"aes-128-cbc":{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},"aes-192-cbc":{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},"aes-256-cbc":{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},aes128,aes192,aes256,"aes-128-cfb":{cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"},"aes-192-cfb":{cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"},"aes-256-cfb":{cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"},"aes-128-cfb8":{cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"},"aes-192-cfb8":{cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"},"aes-256-cfb8":{cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"},"aes-128-cfb1":{cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"},"aes-192-cfb1":{cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"},"aes-256-cfb1":{cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"},"aes-128-ofb":{cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"},"aes-192-ofb":{cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"},"aes-256-ofb":{cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"},"aes-128-ctr":{cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"},"aes-192-ctr":{cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"},"aes-256-ctr":{cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"},"aes-128-gcm":{cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"},"aes-192-gcm":{cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"},"aes-256-gcm":{cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}};var modeModules={ECB:ecb,CBC:cbc,CFB:cfb,CFB8:cfb8,CFB1:cfb1,OFB:ofb,CTR:ctr,GCM:ctr},modes$2=require$$2;for(var key$2 in modes$2)modes$2[key$2].module=modeModules[modes$2[key$2].mode];var modes_1=modes$2,aes$5={},Buffer$e=safeBufferExports$1.Buffer;function asUInt32Array(y){Buffer$e.isBuffer(y)||(y=Buffer$e.from(y));for(var u=y.length/4|0,h=new Array(u),b=0;b<u;b++)h[b]=y.readUInt32BE(b*4);return h}function scrubVec(y){for(var u=0;u<y.length;y++)y[u]=0}function cryptBlock(y,u,h,b,v){for(var w=h[0],_=h[1],E=h[2],S=h[3],x=y[0]^u[0],T=y[1]^u[1],C=y[2]^u[2],O=y[3]^u[3],D,U,te,X,ie=4,ee=1;ee<v;ee++)D=w[x>>>24]^_[T>>>16&255]^E[C>>>8&255]^S[O&255]^u[ie++],U=w[T>>>24]^_[C>>>16&255]^E[O>>>8&255]^S[x&255]^u[ie++],te=w[C>>>24]^_[O>>>16&255]^E[x>>>8&255]^S[T&255]^u[ie++],X=w[O>>>24]^_[x>>>16&255]^E[T>>>8&255]^S[C&255]^u[ie++],x=D,T=U,C=te,O=X;return D=(b[x>>>24]<<24|b[T>>>16&255]<<16|b[C>>>8&255]<<8|b[O&255])^u[ie++],U=(b[T>>>24]<<24|b[C>>>16&255]<<16|b[O>>>8&255]<<8|b[x&255])^u[ie++],te=(b[C>>>24]<<24|b[O>>>16&255]<<16|b[x>>>8&255]<<8|b[T&255])^u[ie++],X=(b[O>>>24]<<24|b[x>>>16&255]<<16|b[T>>>8&255]<<8|b[C&255])^u[ie++],D=D>>>0,U=U>>>0,te=te>>>0,X=X>>>0,[D,U,te,X]}var RCON=[0,1,2,4,8,16,32,64,128,27,54],G=function(){for(var y=new Array(256),u=0;u<256;u++)u<128?y[u]=u<<1:y[u]=u<<1^283;for(var h=[],b=[],v=[[],[],[],[]],w=[[],[],[],[]],_=0,E=0,S=0;S<256;++S){var x=E^E<<1^E<<2^E<<3^E<<4;x=x>>>8^x&255^99,h[_]=x,b[x]=_;var T=y[_],C=y[T],O=y[C],D=y[x]*257^x*16843008;v[0][_]=D<<24|D>>>8,v[1][_]=D<<16|D>>>16,v[2][_]=D<<8|D>>>24,v[3][_]=D,D=O*16843009^C*65537^T*257^_*16843008,w[0][x]=D<<24|D>>>8,w[1][x]=D<<16|D>>>16,w[2][x]=D<<8|D>>>24,w[3][x]=D,_===0?_=E=1:(_=T^y[y[y[O^T]]],E^=y[y[E]])}return{SBOX:h,INV_SBOX:b,SUB_MIX:v,INV_SUB_MIX:w}}();function AES(y){this._key=asUInt32Array(y),this._reset()}AES.blockSize=4*4;AES.keySize=256/8;AES.prototype.blockSize=AES.blockSize;AES.prototype.keySize=AES.keySize;AES.prototype._reset=function(){for(var y=this._key,u=y.length,h=u+6,b=(h+1)*4,v=[],w=0;w<u;w++)v[w]=y[w];for(w=u;w<b;w++){var _=v[w-1];w%u===0?(_=_<<8|_>>>24,_=G.SBOX[_>>>24]<<24|G.SBOX[_>>>16&255]<<16|G.SBOX[_>>>8&255]<<8|G.SBOX[_&255],_^=RCON[w/u|0]<<24):u>6&&w%u===4&&(_=G.SBOX[_>>>24]<<24|G.SBOX[_>>>16&255]<<16|G.SBOX[_>>>8&255]<<8|G.SBOX[_&255]),v[w]=v[w-u]^_}for(var E=[],S=0;S<b;S++){var x=b-S,T=v[x-(S%4?0:4)];S<4||x<=4?E[S]=T:E[S]=G.INV_SUB_MIX[0][G.SBOX[T>>>24]]^G.INV_SUB_MIX[1][G.SBOX[T>>>16&255]]^G.INV_SUB_MIX[2][G.SBOX[T>>>8&255]]^G.INV_SUB_MIX[3][G.SBOX[T&255]]}this._nRounds=h,this._keySchedule=v,this._invKeySchedule=E};AES.prototype.encryptBlockRaw=function(y){return y=asUInt32Array(y),cryptBlock(y,this._keySchedule,G.SUB_MIX,G.SBOX,this._nRounds)};AES.prototype.encryptBlock=function(y){var u=this.encryptBlockRaw(y),h=Buffer$e.allocUnsafe(16);return h.writeUInt32BE(u[0],0),h.writeUInt32BE(u[1],4),h.writeUInt32BE(u[2],8),h.writeUInt32BE(u[3],12),h};AES.prototype.decryptBlock=function(y){y=asUInt32Array(y);var u=y[1];y[1]=y[3],y[3]=u;var h=cryptBlock(y,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX,this._nRounds),b=Buffer$e.allocUnsafe(16);return b.writeUInt32BE(h[0],0),b.writeUInt32BE(h[3],4),b.writeUInt32BE(h[2],8),b.writeUInt32BE(h[1],12),b};AES.prototype.scrub=function(){scrubVec(this._keySchedule),scrubVec(this._invKeySchedule),scrubVec(this._key)};aes$5.AES=AES;var Buffer$d=safeBufferExports$1.Buffer,ZEROES=Buffer$d.alloc(16,0);function toArray$1(y){return[y.readUInt32BE(0),y.readUInt32BE(4),y.readUInt32BE(8),y.readUInt32BE(12)]}function fromArray(y){var u=Buffer$d.allocUnsafe(16);return u.writeUInt32BE(y[0]>>>0,0),u.writeUInt32BE(y[1]>>>0,4),u.writeUInt32BE(y[2]>>>0,8),u.writeUInt32BE(y[3]>>>0,12),u}function GHASH$1(y){this.h=y,this.state=Buffer$d.alloc(16,0),this.cache=Buffer$d.allocUnsafe(0)}GHASH$1.prototype.ghash=function(y){for(var u=-1;++u<y.length;)this.state[u]^=y[u];this._multiply()};GHASH$1.prototype._multiply=function(){for(var y=toArray$1(this.h),u=[0,0,0,0],h,b,v,w=-1;++w<128;){for(b=(this.state[~~(w/8)]&1<<7-w%8)!==0,b&&(u[0]^=y[0],u[1]^=y[1],u[2]^=y[2],u[3]^=y[3]),v=(y[3]&1)!==0,h=3;h>0;h--)y[h]=y[h]>>>1|(y[h-1]&1)<<31;y[0]=y[0]>>>1,v&&(y[0]=y[0]^225<<24)}this.state=fromArray(u)};GHASH$1.prototype.update=function(y){this.cache=Buffer$d.concat([this.cache,y]);for(var u;this.cache.length>=16;)u=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(u)};GHASH$1.prototype.final=function(y,u){return this.cache.length&&this.ghash(Buffer$d.concat([this.cache,ZEROES],16)),this.ghash(fromArray([0,y,0,u])),this.state};var ghash=GHASH$1,aes$4=aes$5,Buffer$c=safeBufferExports$1.Buffer,Transform$5=cipherBase,inherits$8=inherits_browserExports,GHASH=ghash,xor$3=bufferXor,incr32=incr32_1;function xorTest(y,u){var h=0;y.length!==u.length&&h++;for(var b=Math.min(y.length,u.length),v=0;v<b;++v)h+=y[v]^u[v];return h}function calcIv(y,u,h){if(u.length===12)return y._finID=Buffer$c.concat([u,Buffer$c.from([0,0,0,1])]),Buffer$c.concat([u,Buffer$c.from([0,0,0,2])]);var b=new GHASH(h),v=u.length,w=v%16;b.update(u),w&&(w=16-w,b.update(Buffer$c.alloc(w,0))),b.update(Buffer$c.alloc(8,0));var _=v*8,E=Buffer$c.alloc(8);E.writeUIntBE(_,0,8),b.update(E),y._finID=b.state;var S=Buffer$c.from(y._finID);return incr32(S),S}function StreamCipher$3(y,u,h,b){Transform$5.call(this);var v=Buffer$c.alloc(4,0);this._cipher=new aes$4.AES(u);var w=this._cipher.encryptBlock(v);this._ghash=new GHASH(w),h=calcIv(this,h,w),this._prev=Buffer$c.from(h),this._cache=Buffer$c.allocUnsafe(0),this._secCache=Buffer$c.allocUnsafe(0),this._decrypt=b,this._alen=0,this._len=0,this._mode=y,this._authTag=null,this._called=!1}inherits$8(StreamCipher$3,Transform$5);StreamCipher$3.prototype._update=function(y){if(!this._called&&this._alen){var u=16-this._alen%16;u<16&&(u=Buffer$c.alloc(u,0),this._ghash.update(u))}this._called=!0;var h=this._mode.encrypt(this,y);return this._decrypt?this._ghash.update(y):this._ghash.update(h),this._len+=y.length,h};StreamCipher$3.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var y=xor$3(this._ghash.final(this._alen*8,this._len*8),this._cipher.encryptBlock(this._finID));if(this._decrypt&&xorTest(y,this._authTag))throw new Error("Unsupported state or unable to authenticate data");this._authTag=y,this._cipher.scrub()};StreamCipher$3.prototype.getAuthTag=function(){if(this._decrypt||!Buffer$c.isBuffer(this._authTag))throw new Error("Attempting to get auth tag in unsupported state");return this._authTag};StreamCipher$3.prototype.setAuthTag=function(u){if(!this._decrypt)throw new Error("Attempting to set auth tag in unsupported state");this._authTag=u};StreamCipher$3.prototype.setAAD=function(u){if(this._called)throw new Error("Attempting to set AAD in unsupported state");this._ghash.update(u),this._alen+=u.length};var authCipher=StreamCipher$3,aes$3=aes$5,Buffer$b=safeBufferExports$1.Buffer,Transform$4=cipherBase,inherits$7=inherits_browserExports;function StreamCipher$2(y,u,h,b){Transform$4.call(this),this._cipher=new aes$3.AES(u),this._prev=Buffer$b.from(h),this._cache=Buffer$b.allocUnsafe(0),this._secCache=Buffer$b.allocUnsafe(0),this._decrypt=b,this._mode=y}inherits$7(StreamCipher$2,Transform$4);StreamCipher$2.prototype._update=function(y){return this._mode.encrypt(this,y,this._decrypt)};StreamCipher$2.prototype._final=function(){this._cipher.scrub()};var streamCipher=StreamCipher$2,Buffer$a=safeBufferExports$1.Buffer,MD5=md5_js;function EVP_BytesToKey(y,u,h,b){if(Buffer$a.isBuffer(y)||(y=Buffer$a.from(y,"binary")),u&&(Buffer$a.isBuffer(u)||(u=Buffer$a.from(u,"binary")),u.length!==8))throw new RangeError("salt should be Buffer with 8 byte length");for(var v=h/8,w=Buffer$a.alloc(v),_=Buffer$a.alloc(b||0),E=Buffer$a.alloc(0);v>0||b>0;){var S=new MD5;S.update(E),S.update(y),u&&S.update(u),E=S.digest();var x=0;if(v>0){var T=w.length-v;x=Math.min(v,E.length),E.copy(w,T,0,x),v-=x}if(x<E.length&&b>0){var C=_.length-b,O=Math.min(b,E.length-x);E.copy(_,C,x,x+O),b-=O}}return E.fill(0),{key:w,iv:_}}var evp_bytestokey=EVP_BytesToKey,MODES$1=modes_1,AuthCipher$1=authCipher,Buffer$9=safeBufferExports$1.Buffer,StreamCipher$1=streamCipher,Transform$3=cipherBase,aes$2=aes$5,ebtk$2=evp_bytestokey,inherits$6=inherits_browserExports;function Cipher(y,u,h){Transform$3.call(this),this._cache=new Splitter$1,this._cipher=new aes$2.AES(u),this._prev=Buffer$9.from(h),this._mode=y,this._autopadding=!0}inherits$6(Cipher,Transform$3);Cipher.prototype._update=function(y){this._cache.add(y);for(var u,h,b=[];u=this._cache.get();)h=this._mode.encrypt(this,u),b.push(h);return Buffer$9.concat(b)};var PADDING=Buffer$9.alloc(16,16);Cipher.prototype._final=function(){var y=this._cache.flush();if(this._autopadding)return y=this._mode.encrypt(this,y),this._cipher.scrub(),y;if(!y.equals(PADDING))throw this._cipher.scrub(),new Error("data not multiple of block length")};Cipher.prototype.setAutoPadding=function(y){return this._autopadding=!!y,this};function Splitter$1(){this.cache=Buffer$9.allocUnsafe(0)}Splitter$1.prototype.add=function(y){this.cache=Buffer$9.concat([this.cache,y])};Splitter$1.prototype.get=function(){if(this.cache.length>15){var y=this.cache.slice(0,16);return this.cache=this.cache.slice(16),y}return null};Splitter$1.prototype.flush=function(){for(var y=16-this.cache.length,u=Buffer$9.allocUnsafe(y),h=-1;++h<y;)u.writeUInt8(y,h);return Buffer$9.concat([this.cache,u])};function createCipheriv$1(y,u,h){var b=MODES$1[y.toLowerCase()];if(!b)throw new TypeError("invalid suite type");if(typeof u=="string"&&(u=Buffer$9.from(u)),u.length!==b.key/8)throw new TypeError("invalid key length "+u.length);if(typeof h=="string"&&(h=Buffer$9.from(h)),b.mode!=="GCM"&&h.length!==b.iv)throw new TypeError("invalid iv length "+h.length);return b.type==="stream"?new StreamCipher$1(b.module,u,h):b.type==="auth"?new AuthCipher$1(b.module,u,h):new Cipher(b.module,u,h)}function createCipher$1(y,u){var h=MODES$1[y.toLowerCase()];if(!h)throw new TypeError("invalid suite type");var b=ebtk$2(u,!1,h.key,h.iv);return createCipheriv$1(y,b.key,b.iv)}encrypter.createCipheriv=createCipheriv$1;encrypter.createCipher=createCipher$1;var decrypter={},AuthCipher=authCipher,Buffer$8=safeBufferExports$1.Buffer,MODES=modes_1,StreamCipher=streamCipher,Transform$2=cipherBase,aes$1=aes$5,ebtk$1=evp_bytestokey,inherits$5=inherits_browserExports;function Decipher(y,u,h){Transform$2.call(this),this._cache=new Splitter,this._last=void 0,this._cipher=new aes$1.AES(u),this._prev=Buffer$8.from(h),this._mode=y,this._autopadding=!0}inherits$5(Decipher,Transform$2);Decipher.prototype._update=function(y){this._cache.add(y);for(var u,h,b=[];u=this._cache.get(this._autopadding);)h=this._mode.decrypt(this,u),b.push(h);return Buffer$8.concat(b)};Decipher.prototype._final=function(){var y=this._cache.flush();if(this._autopadding)return unpad(this._mode.decrypt(this,y));if(y)throw new Error("data not multiple of block length")};Decipher.prototype.setAutoPadding=function(y){return this._autopadding=!!y,this};function Splitter(){this.cache=Buffer$8.allocUnsafe(0)}Splitter.prototype.add=function(y){this.cache=Buffer$8.concat([this.cache,y])};Splitter.prototype.get=function(y){var u;if(y){if(this.cache.length>16)return u=this.cache.slice(0,16),this.cache=this.cache.slice(16),u}else if(this.cache.length>=16)return u=this.cache.slice(0,16),this.cache=this.cache.slice(16),u;return null};Splitter.prototype.flush=function(){if(this.cache.length)return this.cache};function unpad(y){var u=y[15];if(u<1||u>16)throw new Error("unable to decrypt data");for(var h=-1;++h<u;)if(y[h+(16-u)]!==u)throw new Error("unable to decrypt data");if(u!==16)return y.slice(0,16-u)}function createDecipheriv$1(y,u,h){var b=MODES[y.toLowerCase()];if(!b)throw new TypeError("invalid suite type");if(typeof h=="string"&&(h=Buffer$8.from(h)),b.mode!=="GCM"&&h.length!==b.iv)throw new TypeError("invalid iv length "+h.length);if(typeof u=="string"&&(u=Buffer$8.from(u)),u.length!==b.key/8)throw new TypeError("invalid key length "+u.length);return b.type==="stream"?new StreamCipher(b.module,u,h,!0):b.type==="auth"?new AuthCipher(b.module,u,h,!0):new Decipher(b.module,u,h)}function createDecipher$1(y,u){var h=MODES[y.toLowerCase()];if(!h)throw new TypeError("invalid suite type");var b=ebtk$1(u,!1,h.key,h.iv);return createDecipheriv$1(y,b.key,b.iv)}decrypter.createDecipher=createDecipher$1;decrypter.createDecipheriv=createDecipheriv$1;var ciphers$2=encrypter,deciphers=decrypter,modes$1=require$$2;function getCiphers$1(){return Object.keys(modes$1)}browser$5.createCipher=browser$5.Cipher=ciphers$2.createCipher;browser$5.createCipheriv=browser$5.Cipheriv=ciphers$2.createCipheriv;browser$5.createDecipher=browser$5.Decipher=deciphers.createDecipher;browser$5.createDecipheriv=browser$5.Decipheriv=deciphers.createDecipheriv;browser$5.listCiphers=browser$5.getCiphers=getCiphers$1;var modes={};(function(y){y["des-ecb"]={key:8,iv:0},y["des-cbc"]=y.des={key:8,iv:8},y["des-ede3-cbc"]=y.des3={key:24,iv:8},y["des-ede3"]={key:24,iv:0},y["des-ede-cbc"]={key:16,iv:8},y["des-ede"]={key:16,iv:0}})(modes);var DES=browserifyDes,aes=browser$5,aesModes=modes_1,desModes=modes,ebtk=evp_bytestokey;function createCipher(y,u){y=y.toLowerCase();var h,b;if(aesModes[y])h=aesModes[y].key,b=aesModes[y].iv;else if(desModes[y])h=desModes[y].key*8,b=desModes[y].iv;else throw new TypeError("invalid suite type");var v=ebtk(u,!1,h,b);return createCipheriv(y,v.key,v.iv)}function createDecipher(y,u){y=y.toLowerCase();var h,b;if(aesModes[y])h=aesModes[y].key,b=aesModes[y].iv;else if(desModes[y])h=desModes[y].key*8,b=desModes[y].iv;else throw new TypeError("invalid suite type");var v=ebtk(u,!1,h,b);return createDecipheriv(y,v.key,v.iv)}function createCipheriv(y,u,h){if(y=y.toLowerCase(),aesModes[y])return aes.createCipheriv(y,u,h);if(desModes[y])return new DES({key:u,iv:h,mode:y});throw new TypeError("invalid suite type")}function createDecipheriv(y,u,h){if(y=y.toLowerCase(),aesModes[y])return aes.createDecipheriv(y,u,h);if(desModes[y])return new DES({key:u,iv:h,mode:y,decrypt:!0});throw new TypeError("invalid suite type")}function getCiphers(){return Object.keys(desModes).concat(aes.getCiphers())}browser$6.createCipher=browser$6.Cipher=createCipher;browser$6.createCipheriv=browser$6.Cipheriv=createCipheriv;browser$6.createDecipher=browser$6.Decipher=createDecipher;browser$6.createDecipheriv=browser$6.Decipheriv=createDecipheriv;browser$6.listCiphers=browser$6.getCiphers=getCiphers;var browser$4={},bn$1={exports:{}};bn$1.exports;(function(y){(function(u,h){function b(be,B){if(!be)throw new Error(B||"Assertion failed")}function v(be,B){be.super_=B;var F=function(){};F.prototype=B.prototype,be.prototype=new F,be.prototype.constructor=be}function w(be,B,F){if(w.isBN(be))return be;this.negative=0,this.words=null,this.length=0,this.red=null,be!==null&&((B==="le"||B==="be")&&(F=B,B=10),this._init(be||0,B||10,F||"be"))}typeof u=="object"?u.exports=w:h.BN=w,w.BN=w,w.wordSize=26;var _;try{typeof window<"u"&&typeof window.Buffer<"u"?_=window.Buffer:_=dist.Buffer}catch{}w.isBN=function(B){return B instanceof w?!0:B!==null&&typeof B=="object"&&B.constructor.wordSize===w.wordSize&&Array.isArray(B.words)},w.max=function(B,F){return B.cmp(F)>0?B:F},w.min=function(B,F){return B.cmp(F)<0?B:F},w.prototype._init=function(B,F,M){if(typeof B=="number")return this._initNumber(B,F,M);if(typeof B=="object")return this._initArray(B,F,M);F==="hex"&&(F=16),b(F===(F|0)&&F>=2&&F<=36),B=B.toString().replace(/\s+/g,"");var N=0;B[0]==="-"&&(N++,this.negative=1),N<B.length&&(F===16?this._parseHex(B,N,M):(this._parseBase(B,F,N),M==="le"&&this._initArray(this.toArray(),F,M)))},w.prototype._initNumber=function(B,F,M){B<0&&(this.negative=1,B=-B),B<67108864?(this.words=[B&67108863],this.length=1):B<4503599627370496?(this.words=[B&67108863,B/67108864&67108863],this.length=2):(b(B<9007199254740992),this.words=[B&67108863,B/67108864&67108863,1],this.length=3),M==="le"&&this._initArray(this.toArray(),F,M)},w.prototype._initArray=function(B,F,M){if(b(typeof B.length=="number"),B.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(B.length/3),this.words=new Array(this.length);for(var N=0;N<this.length;N++)this.words[N]=0;var Q,j,ne=0;if(M==="be")for(N=B.length-1,Q=0;N>=0;N-=3)j=B[N]|B[N-1]<<8|B[N-2]<<16,this.words[Q]|=j<<ne&67108863,this.words[Q+1]=j>>>26-ne&67108863,ne+=24,ne>=26&&(ne-=26,Q++);else if(M==="le")for(N=0,Q=0;N<B.length;N+=3)j=B[N]|B[N+1]<<8|B[N+2]<<16,this.words[Q]|=j<<ne&67108863,this.words[Q+1]=j>>>26-ne&67108863,ne+=24,ne>=26&&(ne-=26,Q++);return this.strip()};function E(be,B){var F=be.charCodeAt(B);return F>=65&&F<=70?F-55:F>=97&&F<=102?F-87:F-48&15}function S(be,B,F){var M=E(be,F);return F-1>=B&&(M|=E(be,F-1)<<4),M}w.prototype._parseHex=function(B,F,M){this.length=Math.ceil((B.length-F)/6),this.words=new Array(this.length);for(var N=0;N<this.length;N++)this.words[N]=0;var Q=0,j=0,ne;if(M==="be")for(N=B.length-1;N>=F;N-=2)ne=S(B,F,N)<<Q,this.words[j]|=ne&67108863,Q>=18?(Q-=18,j+=1,this.words[j]|=ne>>>26):Q+=8;else{var J=B.length-F;for(N=J%2===0?F+1:F;N<B.length;N+=2)ne=S(B,F,N)<<Q,this.words[j]|=ne&67108863,Q>=18?(Q-=18,j+=1,this.words[j]|=ne>>>26):Q+=8}this.strip()};function x(be,B,F,M){for(var N=0,Q=Math.min(be.length,F),j=B;j<Q;j++){var ne=be.charCodeAt(j)-48;N*=M,ne>=49?N+=ne-49+10:ne>=17?N+=ne-17+10:N+=ne}return N}w.prototype._parseBase=function(B,F,M){this.words=[0],this.length=1;for(var N=0,Q=1;Q<=67108863;Q*=F)N++;N--,Q=Q/F|0;for(var j=B.length-M,ne=j%N,J=Math.min(j,j-ne)+M,q=0,re=M;re<J;re+=N)q=x(B,re,re+N,F),this.imuln(Q),this.words[0]+q<67108864?this.words[0]+=q:this._iaddn(q);if(ne!==0){var H=1;for(q=x(B,re,B.length,F),re=0;re<ne;re++)H*=F;this.imuln(H),this.words[0]+q<67108864?this.words[0]+=q:this._iaddn(q)}this.strip()},w.prototype.copy=function(B){B.words=new Array(this.length);for(var F=0;F<this.length;F++)B.words[F]=this.words[F];B.length=this.length,B.negative=this.negative,B.red=this.red},w.prototype.clone=function(){var B=new w(null);return this.copy(B),B},w.prototype._expand=function(B){for(;this.length<B;)this.words[this.length++]=0;return this},w.prototype.strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},w.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},w.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var T=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],C=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],O=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];w.prototype.toString=function(B,F){B=B||10,F=F|0||1;var M;if(B===16||B==="hex"){M="";for(var N=0,Q=0,j=0;j<this.length;j++){var ne=this.words[j],J=((ne<<N|Q)&16777215).toString(16);Q=ne>>>24-N&16777215,Q!==0||j!==this.length-1?M=T[6-J.length]+J+M:M=J+M,N+=2,N>=26&&(N-=26,j--)}for(Q!==0&&(M=Q.toString(16)+M);M.length%F!==0;)M="0"+M;return this.negative!==0&&(M="-"+M),M}if(B===(B|0)&&B>=2&&B<=36){var q=C[B],re=O[B];M="";var H=this.clone();for(H.negative=0;!H.isZero();){var he=H.modn(re).toString(B);H=H.idivn(re),H.isZero()?M=he+M:M=T[q-he.length]+he+M}for(this.isZero()&&(M="0"+M);M.length%F!==0;)M="0"+M;return this.negative!==0&&(M="-"+M),M}b(!1,"Base should be between 2 and 36")},w.prototype.toNumber=function(){var B=this.words[0];return this.length===2?B+=this.words[1]*67108864:this.length===3&&this.words[2]===1?B+=4503599627370496+this.words[1]*67108864:this.length>2&&b(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-B:B},w.prototype.toJSON=function(){return this.toString(16)},w.prototype.toBuffer=function(B,F){return b(typeof _<"u"),this.toArrayLike(_,B,F)},w.prototype.toArray=function(B,F){return this.toArrayLike(Array,B,F)},w.prototype.toArrayLike=function(B,F,M){var N=this.byteLength(),Q=M||Math.max(1,N);b(N<=Q,"byte array longer than desired length"),b(Q>0,"Requested array length <= 0"),this.strip();var j=F==="le",ne=new B(Q),J,q,re=this.clone();if(j){for(q=0;!re.isZero();q++)J=re.andln(255),re.iushrn(8),ne[q]=J;for(;q<Q;q++)ne[q]=0}else{for(q=0;q<Q-N;q++)ne[q]=0;for(q=0;!re.isZero();q++)J=re.andln(255),re.iushrn(8),ne[Q-q-1]=J}return ne},Math.clz32?w.prototype._countBits=function(B){return 32-Math.clz32(B)}:w.prototype._countBits=function(B){var F=B,M=0;return F>=4096&&(M+=13,F>>>=13),F>=64&&(M+=7,F>>>=7),F>=8&&(M+=4,F>>>=4),F>=2&&(M+=2,F>>>=2),M+F},w.prototype._zeroBits=function(B){if(B===0)return 26;var F=B,M=0;return F&8191||(M+=13,F>>>=13),F&127||(M+=7,F>>>=7),F&15||(M+=4,F>>>=4),F&3||(M+=2,F>>>=2),F&1||M++,M},w.prototype.bitLength=function(){var B=this.words[this.length-1],F=this._countBits(B);return(this.length-1)*26+F};function D(be){for(var B=new Array(be.bitLength()),F=0;F<B.length;F++){var M=F/26|0,N=F%26;B[F]=(be.words[M]&1<<N)>>>N}return B}w.prototype.zeroBits=function(){if(this.isZero())return 0;for(var B=0,F=0;F<this.length;F++){var M=this._zeroBits(this.words[F]);if(B+=M,M!==26)break}return B},w.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},w.prototype.toTwos=function(B){return this.negative!==0?this.abs().inotn(B).iaddn(1):this.clone()},w.prototype.fromTwos=function(B){return this.testn(B-1)?this.notn(B).iaddn(1).ineg():this.clone()},w.prototype.isNeg=function(){return this.negative!==0},w.prototype.neg=function(){return this.clone().ineg()},w.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},w.prototype.iuor=function(B){for(;this.length<B.length;)this.words[this.length++]=0;for(var F=0;F<B.length;F++)this.words[F]=this.words[F]|B.words[F];return this.strip()},w.prototype.ior=function(B){return b((this.negative|B.negative)===0),this.iuor(B)},w.prototype.or=function(B){return this.length>B.length?this.clone().ior(B):B.clone().ior(this)},w.prototype.uor=function(B){return this.length>B.length?this.clone().iuor(B):B.clone().iuor(this)},w.prototype.iuand=function(B){var F;this.length>B.length?F=B:F=this;for(var M=0;M<F.length;M++)this.words[M]=this.words[M]&B.words[M];return this.length=F.length,this.strip()},w.prototype.iand=function(B){return b((this.negative|B.negative)===0),this.iuand(B)},w.prototype.and=function(B){return this.length>B.length?this.clone().iand(B):B.clone().iand(this)},w.prototype.uand=function(B){return this.length>B.length?this.clone().iuand(B):B.clone().iuand(this)},w.prototype.iuxor=function(B){var F,M;this.length>B.length?(F=this,M=B):(F=B,M=this);for(var N=0;N<M.length;N++)this.words[N]=F.words[N]^M.words[N];if(this!==F)for(;N<F.length;N++)this.words[N]=F.words[N];return this.length=F.length,this.strip()},w.prototype.ixor=function(B){return b((this.negative|B.negative)===0),this.iuxor(B)},w.prototype.xor=function(B){return this.length>B.length?this.clone().ixor(B):B.clone().ixor(this)},w.prototype.uxor=function(B){return this.length>B.length?this.clone().iuxor(B):B.clone().iuxor(this)},w.prototype.inotn=function(B){b(typeof B=="number"&&B>=0);var F=Math.ceil(B/26)|0,M=B%26;this._expand(F),M>0&&F--;for(var N=0;N<F;N++)this.words[N]=~this.words[N]&67108863;return M>0&&(this.words[N]=~this.words[N]&67108863>>26-M),this.strip()},w.prototype.notn=function(B){return this.clone().inotn(B)},w.prototype.setn=function(B,F){b(typeof B=="number"&&B>=0);var M=B/26|0,N=B%26;return this._expand(M+1),F?this.words[M]=this.words[M]|1<<N:this.words[M]=this.words[M]&~(1<<N),this.strip()},w.prototype.iadd=function(B){var F;if(this.negative!==0&&B.negative===0)return this.negative=0,F=this.isub(B),this.negative^=1,this._normSign();if(this.negative===0&&B.negative!==0)return B.negative=0,F=this.isub(B),B.negative=1,F._normSign();var M,N;this.length>B.length?(M=this,N=B):(M=B,N=this);for(var Q=0,j=0;j<N.length;j++)F=(M.words[j]|0)+(N.words[j]|0)+Q,this.words[j]=F&67108863,Q=F>>>26;for(;Q!==0&&j<M.length;j++)F=(M.words[j]|0)+Q,this.words[j]=F&67108863,Q=F>>>26;if(this.length=M.length,Q!==0)this.words[this.length]=Q,this.length++;else if(M!==this)for(;j<M.length;j++)this.words[j]=M.words[j];return this},w.prototype.add=function(B){var F;return B.negative!==0&&this.negative===0?(B.negative=0,F=this.sub(B),B.negative^=1,F):B.negative===0&&this.negative!==0?(this.negative=0,F=B.sub(this),this.negative=1,F):this.length>B.length?this.clone().iadd(B):B.clone().iadd(this)},w.prototype.isub=function(B){if(B.negative!==0){B.negative=0;var F=this.iadd(B);return B.negative=1,F._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(B),this.negative=1,this._normSign();var M=this.cmp(B);if(M===0)return this.negative=0,this.length=1,this.words[0]=0,this;var N,Q;M>0?(N=this,Q=B):(N=B,Q=this);for(var j=0,ne=0;ne<Q.length;ne++)F=(N.words[ne]|0)-(Q.words[ne]|0)+j,j=F>>26,this.words[ne]=F&67108863;for(;j!==0&&ne<N.length;ne++)F=(N.words[ne]|0)+j,j=F>>26,this.words[ne]=F&67108863;if(j===0&&ne<N.length&&N!==this)for(;ne<N.length;ne++)this.words[ne]=N.words[ne];return this.length=Math.max(this.length,ne),N!==this&&(this.negative=1),this.strip()},w.prototype.sub=function(B){return this.clone().isub(B)};function U(be,B,F){F.negative=B.negative^be.negative;var M=be.length+B.length|0;F.length=M,M=M-1|0;var N=be.words[0]|0,Q=B.words[0]|0,j=N*Q,ne=j&67108863,J=j/67108864|0;F.words[0]=ne;for(var q=1;q<M;q++){for(var re=J>>>26,H=J&67108863,he=Math.min(q,B.length-1),Oe=Math.max(0,q-be.length+1);Oe<=he;Oe++){var Ne=q-Oe|0;N=be.words[Ne]|0,Q=B.words[Oe]|0,j=N*Q+H,re+=j/67108864|0,H=j&67108863}F.words[q]=H|0,J=re|0}return J!==0?F.words[q]=J|0:F.length--,F.strip()}var te=function(B,F,M){var N=B.words,Q=F.words,j=M.words,ne=0,J,q,re,H=N[0]|0,he=H&8191,Oe=H>>>13,Ne=N[1]|0,Ae=Ne&8191,le=Ne>>>13,me=N[2]|0,Me=me&8191,fe=me>>>13,ge=N[3]|0,ce=ge&8191,_e=ge>>>13,Re=N[4]|0,Ue=Re&8191,qe=Re>>>13,Ze=N[5]|0,tt=Ze&8191,Fe=Ze>>>13,nt=N[6]|0,it=nt&8191,at=nt>>>13,ct=N[7]|0,ht=ct&8191,xt=ct>>>13,Ot=N[8]|0,dt=Ot&8191,Rt=Ot>>>13,Nt=N[9]|0,yt=Nt&8191,zt=Nt>>>13,Vt=Q[0]|0,vt=Vt&8191,Ut=Vt>>>13,Lt=Q[1]|0,wt=Lt&8191,Wt=Lt>>>13,Gt=Q[2]|0,At=Gt&8191,tr=Gt>>>13,Xt=Q[3]|0,bt=Xt&8191,Bt=Xt>>>13,Yt=Q[4]|0,Tt=Yt&8191,qt=Yt>>>13,Jt=Q[5]|0,we=Jt&8191,se=Jt>>>13,ue=Q[6]|0,xe=ue&8191,ke=ue>>>13,Ke=Q[7]|0,We=Ke&8191,ut=Ke>>>13,_t=Q[8]|0,st=_t&8191,Et=_t>>>13,gt=Q[9]|0,It=gt&8191,Qt=gt>>>13;M.negative=B.negative^F.negative,M.length=19,J=Math.imul(he,vt),q=Math.imul(he,Ut),q=q+Math.imul(Oe,vt)|0,re=Math.imul(Oe,Ut);var rr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(rr>>>26)|0,rr&=67108863,J=Math.imul(Ae,vt),q=Math.imul(Ae,Ut),q=q+Math.imul(le,vt)|0,re=Math.imul(le,Ut),J=J+Math.imul(he,wt)|0,q=q+Math.imul(he,Wt)|0,q=q+Math.imul(Oe,wt)|0,re=re+Math.imul(Oe,Wt)|0;var ar=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(ar>>>26)|0,ar&=67108863,J=Math.imul(Me,vt),q=Math.imul(Me,Ut),q=q+Math.imul(fe,vt)|0,re=Math.imul(fe,Ut),J=J+Math.imul(Ae,wt)|0,q=q+Math.imul(Ae,Wt)|0,q=q+Math.imul(le,wt)|0,re=re+Math.imul(le,Wt)|0,J=J+Math.imul(he,At)|0,q=q+Math.imul(he,tr)|0,q=q+Math.imul(Oe,At)|0,re=re+Math.imul(Oe,tr)|0;var Gr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Gr>>>26)|0,Gr&=67108863,J=Math.imul(ce,vt),q=Math.imul(ce,Ut),q=q+Math.imul(_e,vt)|0,re=Math.imul(_e,Ut),J=J+Math.imul(Me,wt)|0,q=q+Math.imul(Me,Wt)|0,q=q+Math.imul(fe,wt)|0,re=re+Math.imul(fe,Wt)|0,J=J+Math.imul(Ae,At)|0,q=q+Math.imul(Ae,tr)|0,q=q+Math.imul(le,At)|0,re=re+Math.imul(le,tr)|0,J=J+Math.imul(he,bt)|0,q=q+Math.imul(he,Bt)|0,q=q+Math.imul(Oe,bt)|0,re=re+Math.imul(Oe,Bt)|0;var Hr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Hr>>>26)|0,Hr&=67108863,J=Math.imul(Ue,vt),q=Math.imul(Ue,Ut),q=q+Math.imul(qe,vt)|0,re=Math.imul(qe,Ut),J=J+Math.imul(ce,wt)|0,q=q+Math.imul(ce,Wt)|0,q=q+Math.imul(_e,wt)|0,re=re+Math.imul(_e,Wt)|0,J=J+Math.imul(Me,At)|0,q=q+Math.imul(Me,tr)|0,q=q+Math.imul(fe,At)|0,re=re+Math.imul(fe,tr)|0,J=J+Math.imul(Ae,bt)|0,q=q+Math.imul(Ae,Bt)|0,q=q+Math.imul(le,bt)|0,re=re+Math.imul(le,Bt)|0,J=J+Math.imul(he,Tt)|0,q=q+Math.imul(he,qt)|0,q=q+Math.imul(Oe,Tt)|0,re=re+Math.imul(Oe,qt)|0;var jr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(jr>>>26)|0,jr&=67108863,J=Math.imul(tt,vt),q=Math.imul(tt,Ut),q=q+Math.imul(Fe,vt)|0,re=Math.imul(Fe,Ut),J=J+Math.imul(Ue,wt)|0,q=q+Math.imul(Ue,Wt)|0,q=q+Math.imul(qe,wt)|0,re=re+Math.imul(qe,Wt)|0,J=J+Math.imul(ce,At)|0,q=q+Math.imul(ce,tr)|0,q=q+Math.imul(_e,At)|0,re=re+Math.imul(_e,tr)|0,J=J+Math.imul(Me,bt)|0,q=q+Math.imul(Me,Bt)|0,q=q+Math.imul(fe,bt)|0,re=re+Math.imul(fe,Bt)|0,J=J+Math.imul(Ae,Tt)|0,q=q+Math.imul(Ae,qt)|0,q=q+Math.imul(le,Tt)|0,re=re+Math.imul(le,qt)|0,J=J+Math.imul(he,we)|0,q=q+Math.imul(he,se)|0,q=q+Math.imul(Oe,we)|0,re=re+Math.imul(Oe,se)|0;var Xr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,J=Math.imul(it,vt),q=Math.imul(it,Ut),q=q+Math.imul(at,vt)|0,re=Math.imul(at,Ut),J=J+Math.imul(tt,wt)|0,q=q+Math.imul(tt,Wt)|0,q=q+Math.imul(Fe,wt)|0,re=re+Math.imul(Fe,Wt)|0,J=J+Math.imul(Ue,At)|0,q=q+Math.imul(Ue,tr)|0,q=q+Math.imul(qe,At)|0,re=re+Math.imul(qe,tr)|0,J=J+Math.imul(ce,bt)|0,q=q+Math.imul(ce,Bt)|0,q=q+Math.imul(_e,bt)|0,re=re+Math.imul(_e,Bt)|0,J=J+Math.imul(Me,Tt)|0,q=q+Math.imul(Me,qt)|0,q=q+Math.imul(fe,Tt)|0,re=re+Math.imul(fe,qt)|0,J=J+Math.imul(Ae,we)|0,q=q+Math.imul(Ae,se)|0,q=q+Math.imul(le,we)|0,re=re+Math.imul(le,se)|0,J=J+Math.imul(he,xe)|0,q=q+Math.imul(he,ke)|0,q=q+Math.imul(Oe,xe)|0,re=re+Math.imul(Oe,ke)|0;var Yr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Yr>>>26)|0,Yr&=67108863,J=Math.imul(ht,vt),q=Math.imul(ht,Ut),q=q+Math.imul(xt,vt)|0,re=Math.imul(xt,Ut),J=J+Math.imul(it,wt)|0,q=q+Math.imul(it,Wt)|0,q=q+Math.imul(at,wt)|0,re=re+Math.imul(at,Wt)|0,J=J+Math.imul(tt,At)|0,q=q+Math.imul(tt,tr)|0,q=q+Math.imul(Fe,At)|0,re=re+Math.imul(Fe,tr)|0,J=J+Math.imul(Ue,bt)|0,q=q+Math.imul(Ue,Bt)|0,q=q+Math.imul(qe,bt)|0,re=re+Math.imul(qe,Bt)|0,J=J+Math.imul(ce,Tt)|0,q=q+Math.imul(ce,qt)|0,q=q+Math.imul(_e,Tt)|0,re=re+Math.imul(_e,qt)|0,J=J+Math.imul(Me,we)|0,q=q+Math.imul(Me,se)|0,q=q+Math.imul(fe,we)|0,re=re+Math.imul(fe,se)|0,J=J+Math.imul(Ae,xe)|0,q=q+Math.imul(Ae,ke)|0,q=q+Math.imul(le,xe)|0,re=re+Math.imul(le,ke)|0,J=J+Math.imul(he,We)|0,q=q+Math.imul(he,ut)|0,q=q+Math.imul(Oe,We)|0,re=re+Math.imul(Oe,ut)|0;var Br=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Br>>>26)|0,Br&=67108863,J=Math.imul(dt,vt),q=Math.imul(dt,Ut),q=q+Math.imul(Rt,vt)|0,re=Math.imul(Rt,Ut),J=J+Math.imul(ht,wt)|0,q=q+Math.imul(ht,Wt)|0,q=q+Math.imul(xt,wt)|0,re=re+Math.imul(xt,Wt)|0,J=J+Math.imul(it,At)|0,q=q+Math.imul(it,tr)|0,q=q+Math.imul(at,At)|0,re=re+Math.imul(at,tr)|0,J=J+Math.imul(tt,bt)|0,q=q+Math.imul(tt,Bt)|0,q=q+Math.imul(Fe,bt)|0,re=re+Math.imul(Fe,Bt)|0,J=J+Math.imul(Ue,Tt)|0,q=q+Math.imul(Ue,qt)|0,q=q+Math.imul(qe,Tt)|0,re=re+Math.imul(qe,qt)|0,J=J+Math.imul(ce,we)|0,q=q+Math.imul(ce,se)|0,q=q+Math.imul(_e,we)|0,re=re+Math.imul(_e,se)|0,J=J+Math.imul(Me,xe)|0,q=q+Math.imul(Me,ke)|0,q=q+Math.imul(fe,xe)|0,re=re+Math.imul(fe,ke)|0,J=J+Math.imul(Ae,We)|0,q=q+Math.imul(Ae,ut)|0,q=q+Math.imul(le,We)|0,re=re+Math.imul(le,ut)|0,J=J+Math.imul(he,st)|0,q=q+Math.imul(he,Et)|0,q=q+Math.imul(Oe,st)|0,re=re+Math.imul(Oe,Et)|0;var Kr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Kr>>>26)|0,Kr&=67108863,J=Math.imul(yt,vt),q=Math.imul(yt,Ut),q=q+Math.imul(zt,vt)|0,re=Math.imul(zt,Ut),J=J+Math.imul(dt,wt)|0,q=q+Math.imul(dt,Wt)|0,q=q+Math.imul(Rt,wt)|0,re=re+Math.imul(Rt,Wt)|0,J=J+Math.imul(ht,At)|0,q=q+Math.imul(ht,tr)|0,q=q+Math.imul(xt,At)|0,re=re+Math.imul(xt,tr)|0,J=J+Math.imul(it,bt)|0,q=q+Math.imul(it,Bt)|0,q=q+Math.imul(at,bt)|0,re=re+Math.imul(at,Bt)|0,J=J+Math.imul(tt,Tt)|0,q=q+Math.imul(tt,qt)|0,q=q+Math.imul(Fe,Tt)|0,re=re+Math.imul(Fe,qt)|0,J=J+Math.imul(Ue,we)|0,q=q+Math.imul(Ue,se)|0,q=q+Math.imul(qe,we)|0,re=re+Math.imul(qe,se)|0,J=J+Math.imul(ce,xe)|0,q=q+Math.imul(ce,ke)|0,q=q+Math.imul(_e,xe)|0,re=re+Math.imul(_e,ke)|0,J=J+Math.imul(Me,We)|0,q=q+Math.imul(Me,ut)|0,q=q+Math.imul(fe,We)|0,re=re+Math.imul(fe,ut)|0,J=J+Math.imul(Ae,st)|0,q=q+Math.imul(Ae,Et)|0,q=q+Math.imul(le,st)|0,re=re+Math.imul(le,Et)|0,J=J+Math.imul(he,It)|0,q=q+Math.imul(he,Qt)|0,q=q+Math.imul(Oe,It)|0,re=re+Math.imul(Oe,Qt)|0;var kr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(kr>>>26)|0,kr&=67108863,J=Math.imul(yt,wt),q=Math.imul(yt,Wt),q=q+Math.imul(zt,wt)|0,re=Math.imul(zt,Wt),J=J+Math.imul(dt,At)|0,q=q+Math.imul(dt,tr)|0,q=q+Math.imul(Rt,At)|0,re=re+Math.imul(Rt,tr)|0,J=J+Math.imul(ht,bt)|0,q=q+Math.imul(ht,Bt)|0,q=q+Math.imul(xt,bt)|0,re=re+Math.imul(xt,Bt)|0,J=J+Math.imul(it,Tt)|0,q=q+Math.imul(it,qt)|0,q=q+Math.imul(at,Tt)|0,re=re+Math.imul(at,qt)|0,J=J+Math.imul(tt,we)|0,q=q+Math.imul(tt,se)|0,q=q+Math.imul(Fe,we)|0,re=re+Math.imul(Fe,se)|0,J=J+Math.imul(Ue,xe)|0,q=q+Math.imul(Ue,ke)|0,q=q+Math.imul(qe,xe)|0,re=re+Math.imul(qe,ke)|0,J=J+Math.imul(ce,We)|0,q=q+Math.imul(ce,ut)|0,q=q+Math.imul(_e,We)|0,re=re+Math.imul(_e,ut)|0,J=J+Math.imul(Me,st)|0,q=q+Math.imul(Me,Et)|0,q=q+Math.imul(fe,st)|0,re=re+Math.imul(fe,Et)|0,J=J+Math.imul(Ae,It)|0,q=q+Math.imul(Ae,Qt)|0,q=q+Math.imul(le,It)|0,re=re+Math.imul(le,Qt)|0;var Mr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Mr>>>26)|0,Mr&=67108863,J=Math.imul(yt,At),q=Math.imul(yt,tr),q=q+Math.imul(zt,At)|0,re=Math.imul(zt,tr),J=J+Math.imul(dt,bt)|0,q=q+Math.imul(dt,Bt)|0,q=q+Math.imul(Rt,bt)|0,re=re+Math.imul(Rt,Bt)|0,J=J+Math.imul(ht,Tt)|0,q=q+Math.imul(ht,qt)|0,q=q+Math.imul(xt,Tt)|0,re=re+Math.imul(xt,qt)|0,J=J+Math.imul(it,we)|0,q=q+Math.imul(it,se)|0,q=q+Math.imul(at,we)|0,re=re+Math.imul(at,se)|0,J=J+Math.imul(tt,xe)|0,q=q+Math.imul(tt,ke)|0,q=q+Math.imul(Fe,xe)|0,re=re+Math.imul(Fe,ke)|0,J=J+Math.imul(Ue,We)|0,q=q+Math.imul(Ue,ut)|0,q=q+Math.imul(qe,We)|0,re=re+Math.imul(qe,ut)|0,J=J+Math.imul(ce,st)|0,q=q+Math.imul(ce,Et)|0,q=q+Math.imul(_e,st)|0,re=re+Math.imul(_e,Et)|0,J=J+Math.imul(Me,It)|0,q=q+Math.imul(Me,Qt)|0,q=q+Math.imul(fe,It)|0,re=re+Math.imul(fe,Qt)|0;var Jr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Jr>>>26)|0,Jr&=67108863,J=Math.imul(yt,bt),q=Math.imul(yt,Bt),q=q+Math.imul(zt,bt)|0,re=Math.imul(zt,Bt),J=J+Math.imul(dt,Tt)|0,q=q+Math.imul(dt,qt)|0,q=q+Math.imul(Rt,Tt)|0,re=re+Math.imul(Rt,qt)|0,J=J+Math.imul(ht,we)|0,q=q+Math.imul(ht,se)|0,q=q+Math.imul(xt,we)|0,re=re+Math.imul(xt,se)|0,J=J+Math.imul(it,xe)|0,q=q+Math.imul(it,ke)|0,q=q+Math.imul(at,xe)|0,re=re+Math.imul(at,ke)|0,J=J+Math.imul(tt,We)|0,q=q+Math.imul(tt,ut)|0,q=q+Math.imul(Fe,We)|0,re=re+Math.imul(Fe,ut)|0,J=J+Math.imul(Ue,st)|0,q=q+Math.imul(Ue,Et)|0,q=q+Math.imul(qe,st)|0,re=re+Math.imul(qe,Et)|0,J=J+Math.imul(ce,It)|0,q=q+Math.imul(ce,Qt)|0,q=q+Math.imul(_e,It)|0,re=re+Math.imul(_e,Qt)|0;var Vr=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Vr>>>26)|0,Vr&=67108863,J=Math.imul(yt,Tt),q=Math.imul(yt,qt),q=q+Math.imul(zt,Tt)|0,re=Math.imul(zt,qt),J=J+Math.imul(dt,we)|0,q=q+Math.imul(dt,se)|0,q=q+Math.imul(Rt,we)|0,re=re+Math.imul(Rt,se)|0,J=J+Math.imul(ht,xe)|0,q=q+Math.imul(ht,ke)|0,q=q+Math.imul(xt,xe)|0,re=re+Math.imul(xt,ke)|0,J=J+Math.imul(it,We)|0,q=q+Math.imul(it,ut)|0,q=q+Math.imul(at,We)|0,re=re+Math.imul(at,ut)|0,J=J+Math.imul(tt,st)|0,q=q+Math.imul(tt,Et)|0,q=q+Math.imul(Fe,st)|0,re=re+Math.imul(Fe,Et)|0,J=J+Math.imul(Ue,It)|0,q=q+Math.imul(Ue,Qt)|0,q=q+Math.imul(qe,It)|0,re=re+Math.imul(qe,Qt)|0;var Tn=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Tn>>>26)|0,Tn&=67108863,J=Math.imul(yt,we),q=Math.imul(yt,se),q=q+Math.imul(zt,we)|0,re=Math.imul(zt,se),J=J+Math.imul(dt,xe)|0,q=q+Math.imul(dt,ke)|0,q=q+Math.imul(Rt,xe)|0,re=re+Math.imul(Rt,ke)|0,J=J+Math.imul(ht,We)|0,q=q+Math.imul(ht,ut)|0,q=q+Math.imul(xt,We)|0,re=re+Math.imul(xt,ut)|0,J=J+Math.imul(it,st)|0,q=q+Math.imul(it,Et)|0,q=q+Math.imul(at,st)|0,re=re+Math.imul(at,Et)|0,J=J+Math.imul(tt,It)|0,q=q+Math.imul(tt,Qt)|0,q=q+Math.imul(Fe,It)|0,re=re+Math.imul(Fe,Qt)|0;var In=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(In>>>26)|0,In&=67108863,J=Math.imul(yt,xe),q=Math.imul(yt,ke),q=q+Math.imul(zt,xe)|0,re=Math.imul(zt,ke),J=J+Math.imul(dt,We)|0,q=q+Math.imul(dt,ut)|0,q=q+Math.imul(Rt,We)|0,re=re+Math.imul(Rt,ut)|0,J=J+Math.imul(ht,st)|0,q=q+Math.imul(ht,Et)|0,q=q+Math.imul(xt,st)|0,re=re+Math.imul(xt,Et)|0,J=J+Math.imul(it,It)|0,q=q+Math.imul(it,Qt)|0,q=q+Math.imul(at,It)|0,re=re+Math.imul(at,Qt)|0;var pn=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(pn>>>26)|0,pn&=67108863,J=Math.imul(yt,We),q=Math.imul(yt,ut),q=q+Math.imul(zt,We)|0,re=Math.imul(zt,ut),J=J+Math.imul(dt,st)|0,q=q+Math.imul(dt,Et)|0,q=q+Math.imul(Rt,st)|0,re=re+Math.imul(Rt,Et)|0,J=J+Math.imul(ht,It)|0,q=q+Math.imul(ht,Qt)|0,q=q+Math.imul(xt,It)|0,re=re+Math.imul(xt,Qt)|0;var Fn=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Fn>>>26)|0,Fn&=67108863,J=Math.imul(yt,st),q=Math.imul(yt,Et),q=q+Math.imul(zt,st)|0,re=Math.imul(zt,Et),J=J+Math.imul(dt,It)|0,q=q+Math.imul(dt,Qt)|0,q=q+Math.imul(Rt,It)|0,re=re+Math.imul(Rt,Qt)|0;var Un=(ne+J|0)+((q&8191)<<13)|0;ne=(re+(q>>>13)|0)+(Un>>>26)|0,Un&=67108863,J=Math.imul(yt,It),q=Math.imul(yt,Qt),q=q+Math.imul(zt,It)|0,re=Math.imul(zt,Qt);var qn=(ne+J|0)+((q&8191)<<13)|0;return ne=(re+(q>>>13)|0)+(qn>>>26)|0,qn&=67108863,j[0]=rr,j[1]=ar,j[2]=Gr,j[3]=Hr,j[4]=jr,j[5]=Xr,j[6]=Yr,j[7]=Br,j[8]=Kr,j[9]=kr,j[10]=Mr,j[11]=Jr,j[12]=Vr,j[13]=Tn,j[14]=In,j[15]=pn,j[16]=Fn,j[17]=Un,j[18]=qn,ne!==0&&(j[19]=ne,M.length++),M};Math.imul||(te=U);function X(be,B,F){F.negative=B.negative^be.negative,F.length=be.length+B.length;for(var M=0,N=0,Q=0;Q<F.length-1;Q++){var j=N;N=0;for(var ne=M&67108863,J=Math.min(Q,B.length-1),q=Math.max(0,Q-be.length+1);q<=J;q++){var re=Q-q,H=be.words[re]|0,he=B.words[q]|0,Oe=H*he,Ne=Oe&67108863;j=j+(Oe/67108864|0)|0,Ne=Ne+ne|0,ne=Ne&67108863,j=j+(Ne>>>26)|0,N+=j>>>26,j&=67108863}F.words[Q]=ne,M=j,j=N}return M!==0?F.words[Q]=M:F.length--,F.strip()}function ie(be,B,F){var M=new ee;return M.mulp(be,B,F)}w.prototype.mulTo=function(B,F){var M,N=this.length+B.length;return this.length===10&&B.length===10?M=te(this,B,F):N<63?M=U(this,B,F):N<1024?M=X(this,B,F):M=ie(this,B,F),M};function ee(be,B){this.x=be,this.y=B}ee.prototype.makeRBT=function(B){for(var F=new Array(B),M=w.prototype._countBits(B)-1,N=0;N<B;N++)F[N]=this.revBin(N,M,B);return F},ee.prototype.revBin=function(B,F,M){if(B===0||B===M-1)return B;for(var N=0,Q=0;Q<F;Q++)N|=(B&1)<<F-Q-1,B>>=1;return N},ee.prototype.permute=function(B,F,M,N,Q,j){for(var ne=0;ne<j;ne++)N[ne]=F[B[ne]],Q[ne]=M[B[ne]]},ee.prototype.transform=function(B,F,M,N,Q,j){this.permute(j,B,F,M,N,Q);for(var ne=1;ne<Q;ne<<=1)for(var J=ne<<1,q=Math.cos(2*Math.PI/J),re=Math.sin(2*Math.PI/J),H=0;H<Q;H+=J)for(var he=q,Oe=re,Ne=0;Ne<ne;Ne++){var Ae=M[H+Ne],le=N[H+Ne],me=M[H+Ne+ne],Me=N[H+Ne+ne],fe=he*me-Oe*Me;Me=he*Me+Oe*me,me=fe,M[H+Ne]=Ae+me,N[H+Ne]=le+Me,M[H+Ne+ne]=Ae-me,N[H+Ne+ne]=le-Me,Ne!==J&&(fe=q*he-re*Oe,Oe=q*Oe+re*he,he=fe)}},ee.prototype.guessLen13b=function(B,F){var M=Math.max(F,B)|1,N=M&1,Q=0;for(M=M/2|0;M;M=M>>>1)Q++;return 1<<Q+1+N},ee.prototype.conjugate=function(B,F,M){if(!(M<=1))for(var N=0;N<M/2;N++){var Q=B[N];B[N]=B[M-N-1],B[M-N-1]=Q,Q=F[N],F[N]=-F[M-N-1],F[M-N-1]=-Q}},ee.prototype.normalize13b=function(B,F){for(var M=0,N=0;N<F/2;N++){var Q=Math.round(B[2*N+1]/F)*8192+Math.round(B[2*N]/F)+M;B[N]=Q&67108863,Q<67108864?M=0:M=Q/67108864|0}return B},ee.prototype.convert13b=function(B,F,M,N){for(var Q=0,j=0;j<F;j++)Q=Q+(B[j]|0),M[2*j]=Q&8191,Q=Q>>>13,M[2*j+1]=Q&8191,Q=Q>>>13;for(j=2*F;j<N;++j)M[j]=0;b(Q===0),b((Q&-8192)===0)},ee.prototype.stub=function(B){for(var F=new Array(B),M=0;M<B;M++)F[M]=0;return F},ee.prototype.mulp=function(B,F,M){var N=2*this.guessLen13b(B.length,F.length),Q=this.makeRBT(N),j=this.stub(N),ne=new Array(N),J=new Array(N),q=new Array(N),re=new Array(N),H=new Array(N),he=new Array(N),Oe=M.words;Oe.length=N,this.convert13b(B.words,B.length,ne,N),this.convert13b(F.words,F.length,re,N),this.transform(ne,j,J,q,N,Q),this.transform(re,j,H,he,N,Q);for(var Ne=0;Ne<N;Ne++){var Ae=J[Ne]*H[Ne]-q[Ne]*he[Ne];q[Ne]=J[Ne]*he[Ne]+q[Ne]*H[Ne],J[Ne]=Ae}return this.conjugate(J,q,N),this.transform(J,q,Oe,j,N,Q),this.conjugate(Oe,j,N),this.normalize13b(Oe,N),M.negative=B.negative^F.negative,M.length=B.length+F.length,M.strip()},w.prototype.mul=function(B){var F=new w(null);return F.words=new Array(this.length+B.length),this.mulTo(B,F)},w.prototype.mulf=function(B){var F=new w(null);return F.words=new Array(this.length+B.length),ie(this,B,F)},w.prototype.imul=function(B){return this.clone().mulTo(B,this)},w.prototype.imuln=function(B){b(typeof B=="number"),b(B<67108864);for(var F=0,M=0;M<this.length;M++){var N=(this.words[M]|0)*B,Q=(N&67108863)+(F&67108863);F>>=26,F+=N/67108864|0,F+=Q>>>26,this.words[M]=Q&67108863}return F!==0&&(this.words[M]=F,this.length++),this},w.prototype.muln=function(B){return this.clone().imuln(B)},w.prototype.sqr=function(){return this.mul(this)},w.prototype.isqr=function(){return this.imul(this.clone())},w.prototype.pow=function(B){var F=D(B);if(F.length===0)return new w(1);for(var M=this,N=0;N<F.length&&F[N]===0;N++,M=M.sqr());if(++N<F.length)for(var Q=M.sqr();N<F.length;N++,Q=Q.sqr())F[N]!==0&&(M=M.mul(Q));return M},w.prototype.iushln=function(B){b(typeof B=="number"&&B>=0);var F=B%26,M=(B-F)/26,N=67108863>>>26-F<<26-F,Q;if(F!==0){var j=0;for(Q=0;Q<this.length;Q++){var ne=this.words[Q]&N,J=(this.words[Q]|0)-ne<<F;this.words[Q]=J|j,j=ne>>>26-F}j&&(this.words[Q]=j,this.length++)}if(M!==0){for(Q=this.length-1;Q>=0;Q--)this.words[Q+M]=this.words[Q];for(Q=0;Q<M;Q++)this.words[Q]=0;this.length+=M}return this.strip()},w.prototype.ishln=function(B){return b(this.negative===0),this.iushln(B)},w.prototype.iushrn=function(B,F,M){b(typeof B=="number"&&B>=0);var N;F?N=(F-F%26)/26:N=0;var Q=B%26,j=Math.min((B-Q)/26,this.length),ne=67108863^67108863>>>Q<<Q,J=M;if(N-=j,N=Math.max(0,N),J){for(var q=0;q<j;q++)J.words[q]=this.words[q];J.length=j}if(j!==0)if(this.length>j)for(this.length-=j,q=0;q<this.length;q++)this.words[q]=this.words[q+j];else this.words[0]=0,this.length=1;var re=0;for(q=this.length-1;q>=0&&(re!==0||q>=N);q--){var H=this.words[q]|0;this.words[q]=re<<26-Q|H>>>Q,re=H&ne}return J&&re!==0&&(J.words[J.length++]=re),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},w.prototype.ishrn=function(B,F,M){return b(this.negative===0),this.iushrn(B,F,M)},w.prototype.shln=function(B){return this.clone().ishln(B)},w.prototype.ushln=function(B){return this.clone().iushln(B)},w.prototype.shrn=function(B){return this.clone().ishrn(B)},w.prototype.ushrn=function(B){return this.clone().iushrn(B)},w.prototype.testn=function(B){b(typeof B=="number"&&B>=0);var F=B%26,M=(B-F)/26,N=1<<F;if(this.length<=M)return!1;var Q=this.words[M];return!!(Q&N)},w.prototype.imaskn=function(B){b(typeof B=="number"&&B>=0);var F=B%26,M=(B-F)/26;if(b(this.negative===0,"imaskn works only with positive numbers"),this.length<=M)return this;if(F!==0&&M++,this.length=Math.min(M,this.length),F!==0){var N=67108863^67108863>>>F<<F;this.words[this.length-1]&=N}return this.strip()},w.prototype.maskn=function(B){return this.clone().imaskn(B)},w.prototype.iaddn=function(B){return b(typeof B=="number"),b(B<67108864),B<0?this.isubn(-B):this.negative!==0?this.length===1&&(this.words[0]|0)<B?(this.words[0]=B-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(B),this.negative=1,this):this._iaddn(B)},w.prototype._iaddn=function(B){this.words[0]+=B;for(var F=0;F<this.length&&this.words[F]>=67108864;F++)this.words[F]-=67108864,F===this.length-1?this.words[F+1]=1:this.words[F+1]++;return this.length=Math.max(this.length,F+1),this},w.prototype.isubn=function(B){if(b(typeof B=="number"),b(B<67108864),B<0)return this.iaddn(-B);if(this.negative!==0)return this.negative=0,this.iaddn(B),this.negative=1,this;if(this.words[0]-=B,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var F=0;F<this.length&&this.words[F]<0;F++)this.words[F]+=67108864,this.words[F+1]-=1;return this.strip()},w.prototype.addn=function(B){return this.clone().iaddn(B)},w.prototype.subn=function(B){return this.clone().isubn(B)},w.prototype.iabs=function(){return this.negative=0,this},w.prototype.abs=function(){return this.clone().iabs()},w.prototype._ishlnsubmul=function(B,F,M){var N=B.length+M,Q;this._expand(N);var j,ne=0;for(Q=0;Q<B.length;Q++){j=(this.words[Q+M]|0)+ne;var J=(B.words[Q]|0)*F;j-=J&67108863,ne=(j>>26)-(J/67108864|0),this.words[Q+M]=j&67108863}for(;Q<this.length-M;Q++)j=(this.words[Q+M]|0)+ne,ne=j>>26,this.words[Q+M]=j&67108863;if(ne===0)return this.strip();for(b(ne===-1),ne=0,Q=0;Q<this.length;Q++)j=-(this.words[Q]|0)+ne,ne=j>>26,this.words[Q]=j&67108863;return this.negative=1,this.strip()},w.prototype._wordDiv=function(B,F){var M=this.length-B.length,N=this.clone(),Q=B,j=Q.words[Q.length-1]|0,ne=this._countBits(j);M=26-ne,M!==0&&(Q=Q.ushln(M),N.iushln(M),j=Q.words[Q.length-1]|0);var J=N.length-Q.length,q;if(F!=="mod"){q=new w(null),q.length=J+1,q.words=new Array(q.length);for(var re=0;re<q.length;re++)q.words[re]=0}var H=N.clone()._ishlnsubmul(Q,1,J);H.negative===0&&(N=H,q&&(q.words[J]=1));for(var he=J-1;he>=0;he--){var Oe=(N.words[Q.length+he]|0)*67108864+(N.words[Q.length+he-1]|0);for(Oe=Math.min(Oe/j|0,67108863),N._ishlnsubmul(Q,Oe,he);N.negative!==0;)Oe--,N.negative=0,N._ishlnsubmul(Q,1,he),N.isZero()||(N.negative^=1);q&&(q.words[he]=Oe)}return q&&q.strip(),N.strip(),F!=="div"&&M!==0&&N.iushrn(M),{div:q||null,mod:N}},w.prototype.divmod=function(B,F,M){if(b(!B.isZero()),this.isZero())return{div:new w(0),mod:new w(0)};var N,Q,j;return this.negative!==0&&B.negative===0?(j=this.neg().divmod(B,F),F!=="mod"&&(N=j.div.neg()),F!=="div"&&(Q=j.mod.neg(),M&&Q.negative!==0&&Q.iadd(B)),{div:N,mod:Q}):this.negative===0&&B.negative!==0?(j=this.divmod(B.neg(),F),F!=="mod"&&(N=j.div.neg()),{div:N,mod:j.mod}):this.negative&B.negative?(j=this.neg().divmod(B.neg(),F),F!=="div"&&(Q=j.mod.neg(),M&&Q.negative!==0&&Q.isub(B)),{div:j.div,mod:Q}):B.length>this.length||this.cmp(B)<0?{div:new w(0),mod:this}:B.length===1?F==="div"?{div:this.divn(B.words[0]),mod:null}:F==="mod"?{div:null,mod:new w(this.modn(B.words[0]))}:{div:this.divn(B.words[0]),mod:new w(this.modn(B.words[0]))}:this._wordDiv(B,F)},w.prototype.div=function(B){return this.divmod(B,"div",!1).div},w.prototype.mod=function(B){return this.divmod(B,"mod",!1).mod},w.prototype.umod=function(B){return this.divmod(B,"mod",!0).mod},w.prototype.divRound=function(B){var F=this.divmod(B);if(F.mod.isZero())return F.div;var M=F.div.negative!==0?F.mod.isub(B):F.mod,N=B.ushrn(1),Q=B.andln(1),j=M.cmp(N);return j<0||Q===1&&j===0?F.div:F.div.negative!==0?F.div.isubn(1):F.div.iaddn(1)},w.prototype.modn=function(B){b(B<=67108863);for(var F=(1<<26)%B,M=0,N=this.length-1;N>=0;N--)M=(F*M+(this.words[N]|0))%B;return M},w.prototype.idivn=function(B){b(B<=67108863);for(var F=0,M=this.length-1;M>=0;M--){var N=(this.words[M]|0)+F*67108864;this.words[M]=N/B|0,F=N%B}return this.strip()},w.prototype.divn=function(B){return this.clone().idivn(B)},w.prototype.egcd=function(B){b(B.negative===0),b(!B.isZero());var F=this,M=B.clone();F.negative!==0?F=F.umod(B):F=F.clone();for(var N=new w(1),Q=new w(0),j=new w(0),ne=new w(1),J=0;F.isEven()&&M.isEven();)F.iushrn(1),M.iushrn(1),++J;for(var q=M.clone(),re=F.clone();!F.isZero();){for(var H=0,he=1;!(F.words[0]&he)&&H<26;++H,he<<=1);if(H>0)for(F.iushrn(H);H-- >0;)(N.isOdd()||Q.isOdd())&&(N.iadd(q),Q.isub(re)),N.iushrn(1),Q.iushrn(1);for(var Oe=0,Ne=1;!(M.words[0]&Ne)&&Oe<26;++Oe,Ne<<=1);if(Oe>0)for(M.iushrn(Oe);Oe-- >0;)(j.isOdd()||ne.isOdd())&&(j.iadd(q),ne.isub(re)),j.iushrn(1),ne.iushrn(1);F.cmp(M)>=0?(F.isub(M),N.isub(j),Q.isub(ne)):(M.isub(F),j.isub(N),ne.isub(Q))}return{a:j,b:ne,gcd:M.iushln(J)}},w.prototype._invmp=function(B){b(B.negative===0),b(!B.isZero());var F=this,M=B.clone();F.negative!==0?F=F.umod(B):F=F.clone();for(var N=new w(1),Q=new w(0),j=M.clone();F.cmpn(1)>0&&M.cmpn(1)>0;){for(var ne=0,J=1;!(F.words[0]&J)&&ne<26;++ne,J<<=1);if(ne>0)for(F.iushrn(ne);ne-- >0;)N.isOdd()&&N.iadd(j),N.iushrn(1);for(var q=0,re=1;!(M.words[0]&re)&&q<26;++q,re<<=1);if(q>0)for(M.iushrn(q);q-- >0;)Q.isOdd()&&Q.iadd(j),Q.iushrn(1);F.cmp(M)>=0?(F.isub(M),N.isub(Q)):(M.isub(F),Q.isub(N))}var H;return F.cmpn(1)===0?H=N:H=Q,H.cmpn(0)<0&&H.iadd(B),H},w.prototype.gcd=function(B){if(this.isZero())return B.abs();if(B.isZero())return this.abs();var F=this.clone(),M=B.clone();F.negative=0,M.negative=0;for(var N=0;F.isEven()&&M.isEven();N++)F.iushrn(1),M.iushrn(1);do{for(;F.isEven();)F.iushrn(1);for(;M.isEven();)M.iushrn(1);var Q=F.cmp(M);if(Q<0){var j=F;F=M,M=j}else if(Q===0||M.cmpn(1)===0)break;F.isub(M)}while(!0);return M.iushln(N)},w.prototype.invm=function(B){return this.egcd(B).a.umod(B)},w.prototype.isEven=function(){return(this.words[0]&1)===0},w.prototype.isOdd=function(){return(this.words[0]&1)===1},w.prototype.andln=function(B){return this.words[0]&B},w.prototype.bincn=function(B){b(typeof B=="number");var F=B%26,M=(B-F)/26,N=1<<F;if(this.length<=M)return this._expand(M+1),this.words[M]|=N,this;for(var Q=N,j=M;Q!==0&&j<this.length;j++){var ne=this.words[j]|0;ne+=Q,Q=ne>>>26,ne&=67108863,this.words[j]=ne}return Q!==0&&(this.words[j]=Q,this.length++),this},w.prototype.isZero=function(){return this.length===1&&this.words[0]===0},w.prototype.cmpn=function(B){var F=B<0;if(this.negative!==0&&!F)return-1;if(this.negative===0&&F)return 1;this.strip();var M;if(this.length>1)M=1;else{F&&(B=-B),b(B<=67108863,"Number is too big");var N=this.words[0]|0;M=N===B?0:N<B?-1:1}return this.negative!==0?-M|0:M},w.prototype.cmp=function(B){if(this.negative!==0&&B.negative===0)return-1;if(this.negative===0&&B.negative!==0)return 1;var F=this.ucmp(B);return this.negative!==0?-F|0:F},w.prototype.ucmp=function(B){if(this.length>B.length)return 1;if(this.length<B.length)return-1;for(var F=0,M=this.length-1;M>=0;M--){var N=this.words[M]|0,Q=B.words[M]|0;if(N!==Q){N<Q?F=-1:N>Q&&(F=1);break}}return F},w.prototype.gtn=function(B){return this.cmpn(B)===1},w.prototype.gt=function(B){return this.cmp(B)===1},w.prototype.gten=function(B){return this.cmpn(B)>=0},w.prototype.gte=function(B){return this.cmp(B)>=0},w.prototype.ltn=function(B){return this.cmpn(B)===-1},w.prototype.lt=function(B){return this.cmp(B)===-1},w.prototype.lten=function(B){return this.cmpn(B)<=0},w.prototype.lte=function(B){return this.cmp(B)<=0},w.prototype.eqn=function(B){return this.cmpn(B)===0},w.prototype.eq=function(B){return this.cmp(B)===0},w.red=function(B){return new Ee(B)},w.prototype.toRed=function(B){return b(!this.red,"Already a number in reduction context"),b(this.negative===0,"red works only with positives"),B.convertTo(this)._forceRed(B)},w.prototype.fromRed=function(){return b(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},w.prototype._forceRed=function(B){return this.red=B,this},w.prototype.forceRed=function(B){return b(!this.red,"Already a number in reduction context"),this._forceRed(B)},w.prototype.redAdd=function(B){return b(this.red,"redAdd works only with red numbers"),this.red.add(this,B)},w.prototype.redIAdd=function(B){return b(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,B)},w.prototype.redSub=function(B){return b(this.red,"redSub works only with red numbers"),this.red.sub(this,B)},w.prototype.redISub=function(B){return b(this.red,"redISub works only with red numbers"),this.red.isub(this,B)},w.prototype.redShl=function(B){return b(this.red,"redShl works only with red numbers"),this.red.shl(this,B)},w.prototype.redMul=function(B){return b(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.mul(this,B)},w.prototype.redIMul=function(B){return b(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.imul(this,B)},w.prototype.redSqr=function(){return b(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},w.prototype.redISqr=function(){return b(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},w.prototype.redSqrt=function(){return b(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},w.prototype.redInvm=function(){return b(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},w.prototype.redNeg=function(){return b(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},w.prototype.redPow=function(B){return b(this.red&&!B.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,B)};var ae={k256:null,p224:null,p192:null,p25519:null};function de(be,B){this.name=be,this.p=new w(B,16),this.n=this.p.bitLength(),this.k=new w(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}de.prototype._tmp=function(){var B=new w(null);return B.words=new Array(Math.ceil(this.n/13)),B},de.prototype.ireduce=function(B){var F=B,M;do this.split(F,this.tmp),F=this.imulK(F),F=F.iadd(this.tmp),M=F.bitLength();while(M>this.n);var N=M<this.n?-1:F.ucmp(this.p);return N===0?(F.words[0]=0,F.length=1):N>0?F.isub(this.p):F.strip!==void 0?F.strip():F._strip(),F},de.prototype.split=function(B,F){B.iushrn(this.n,0,F)},de.prototype.imulK=function(B){return B.imul(this.k)};function Se(){de.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}v(Se,de),Se.prototype.split=function(B,F){for(var M=4194303,N=Math.min(B.length,9),Q=0;Q<N;Q++)F.words[Q]=B.words[Q];if(F.length=N,B.length<=9){B.words[0]=0,B.length=1;return}var j=B.words[9];for(F.words[F.length++]=j&M,Q=10;Q<B.length;Q++){var ne=B.words[Q]|0;B.words[Q-10]=(ne&M)<<4|j>>>22,j=ne}j>>>=22,B.words[Q-10]=j,j===0&&B.length>10?B.length-=10:B.length-=9},Se.prototype.imulK=function(B){B.words[B.length]=0,B.words[B.length+1]=0,B.length+=2;for(var F=0,M=0;M<B.length;M++){var N=B.words[M]|0;F+=N*977,B.words[M]=F&67108863,F=N*64+(F/67108864|0)}return B.words[B.length-1]===0&&(B.length--,B.words[B.length-1]===0&&B.length--),B};function ve(){de.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}v(ve,de);function Pe(){de.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}v(Pe,de);function Ie(){de.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}v(Ie,de),Ie.prototype.imulK=function(B){for(var F=0,M=0;M<B.length;M++){var N=(B.words[M]|0)*19+F,Q=N&67108863;N>>>=26,B.words[M]=Q,F=N}return F!==0&&(B.words[B.length++]=F),B},w._prime=function(B){if(ae[B])return ae[B];var F;if(B==="k256")F=new Se;else if(B==="p224")F=new ve;else if(B==="p192")F=new Pe;else if(B==="p25519")F=new Ie;else throw new Error("Unknown prime "+B);return ae[B]=F,F};function Ee(be){if(typeof be=="string"){var B=w._prime(be);this.m=B.p,this.prime=B}else b(be.gtn(1),"modulus must be greater than 1"),this.m=be,this.prime=null}Ee.prototype._verify1=function(B){b(B.negative===0,"red works only with positives"),b(B.red,"red works only with red numbers")},Ee.prototype._verify2=function(B,F){b((B.negative|F.negative)===0,"red works only with positives"),b(B.red&&B.red===F.red,"red works only with red numbers")},Ee.prototype.imod=function(B){return this.prime?this.prime.ireduce(B)._forceRed(this):B.umod(this.m)._forceRed(this)},Ee.prototype.neg=function(B){return B.isZero()?B.clone():this.m.sub(B)._forceRed(this)},Ee.prototype.add=function(B,F){this._verify2(B,F);var M=B.add(F);return M.cmp(this.m)>=0&&M.isub(this.m),M._forceRed(this)},Ee.prototype.iadd=function(B,F){this._verify2(B,F);var M=B.iadd(F);return M.cmp(this.m)>=0&&M.isub(this.m),M},Ee.prototype.sub=function(B,F){this._verify2(B,F);var M=B.sub(F);return M.cmpn(0)<0&&M.iadd(this.m),M._forceRed(this)},Ee.prototype.isub=function(B,F){this._verify2(B,F);var M=B.isub(F);return M.cmpn(0)<0&&M.iadd(this.m),M},Ee.prototype.shl=function(B,F){return this._verify1(B),this.imod(B.ushln(F))},Ee.prototype.imul=function(B,F){return this._verify2(B,F),this.imod(B.imul(F))},Ee.prototype.mul=function(B,F){return this._verify2(B,F),this.imod(B.mul(F))},Ee.prototype.isqr=function(B){return this.imul(B,B.clone())},Ee.prototype.sqr=function(B){return this.mul(B,B)},Ee.prototype.sqrt=function(B){if(B.isZero())return B.clone();var F=this.m.andln(3);if(b(F%2===1),F===3){var M=this.m.add(new w(1)).iushrn(2);return this.pow(B,M)}for(var N=this.m.subn(1),Q=0;!N.isZero()&&N.andln(1)===0;)Q++,N.iushrn(1);b(!N.isZero());var j=new w(1).toRed(this),ne=j.redNeg(),J=this.m.subn(1).iushrn(1),q=this.m.bitLength();for(q=new w(2*q*q).toRed(this);this.pow(q,J).cmp(ne)!==0;)q.redIAdd(ne);for(var re=this.pow(q,N),H=this.pow(B,N.addn(1).iushrn(1)),he=this.pow(B,N),Oe=Q;he.cmp(j)!==0;){for(var Ne=he,Ae=0;Ne.cmp(j)!==0;Ae++)Ne=Ne.redSqr();b(Ae<Oe);var le=this.pow(re,new w(1).iushln(Oe-Ae-1));H=H.redMul(le),re=le.redSqr(),he=he.redMul(re),Oe=Ae}return H},Ee.prototype.invm=function(B){var F=B._invmp(this.m);return F.negative!==0?(F.negative=0,this.imod(F).redNeg()):this.imod(F)},Ee.prototype.pow=function(B,F){if(F.isZero())return new w(1).toRed(this);if(F.cmpn(1)===0)return B.clone();var M=4,N=new Array(1<<M);N[0]=new w(1).toRed(this),N[1]=B;for(var Q=2;Q<N.length;Q++)N[Q]=this.mul(N[Q-1],B);var j=N[0],ne=0,J=0,q=F.bitLength()%26;for(q===0&&(q=26),Q=F.length-1;Q>=0;Q--){for(var re=F.words[Q],H=q-1;H>=0;H--){var he=re>>H&1;if(j!==N[0]&&(j=this.sqr(j)),he===0&&ne===0){J=0;continue}ne<<=1,ne|=he,J++,!(J!==M&&(Q!==0||H!==0))&&(j=this.mul(j,N[ne]),J=0,ne=0)}q=26}return j},Ee.prototype.convertTo=function(B){var F=B.umod(this.m);return F===B?F.clone():F},Ee.prototype.convertFrom=function(B){var F=B.clone();return F.red=null,F},w.mont=function(B){return new De(B)};function De(be){Ee.call(this,be),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new w(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}v(De,Ee),De.prototype.convertTo=function(B){return this.imod(B.ushln(this.shift))},De.prototype.convertFrom=function(B){var F=this.imod(B.mul(this.rinv));return F.red=null,F},De.prototype.imul=function(B,F){if(B.isZero()||F.isZero())return B.words[0]=0,B.length=1,B;var M=B.imul(F),N=M.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Q=M.isub(N).iushrn(this.shift),j=Q;return Q.cmp(this.m)>=0?j=Q.isub(this.m):Q.cmpn(0)<0&&(j=Q.iadd(this.m)),j._forceRed(this)},De.prototype.mul=function(B,F){if(B.isZero()||F.isZero())return new w(0)._forceRed(this);var M=B.mul(F),N=M.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Q=M.isub(N).iushrn(this.shift),j=Q;return Q.cmp(this.m)>=0?j=Q.isub(this.m):Q.cmpn(0)<0&&(j=Q.iadd(this.m)),j._forceRed(this)},De.prototype.invm=function(B){var F=this.imod(B._invmp(this.m).mul(this.r2));return F._forceRed(this)}})(y,commonjsGlobal)})(bn$1);var bnExports$1=bn$1.exports,brorand={exports:{}},hasRequiredBrorand;function requireBrorand(){if(hasRequiredBrorand)return brorand.exports;hasRequiredBrorand=1;var y;brorand.exports=function(v){return y||(y=new u(null)),y.generate(v)};function u(b){this.rand=b}if(brorand.exports.Rand=u,u.prototype.generate=function(v){return this._rand(v)},u.prototype._rand=function(v){if(this.rand.getBytes)return this.rand.getBytes(v);for(var w=new Uint8Array(v),_=0;_<w.length;_++)w[_]=this.rand.getByte();return w},typeof self=="object")self.crypto&&self.crypto.getRandomValues?u.prototype._rand=function(v){var w=new Uint8Array(v);return self.crypto.getRandomValues(w),w}:self.msCrypto&&self.msCrypto.getRandomValues?u.prototype._rand=function(v){var w=new Uint8Array(v);return self.msCrypto.getRandomValues(w),w}:typeof window=="object"&&(u.prototype._rand=function(){throw new Error("Not implemented yet")});else try{var h=requireCryptoBrowserify();if(typeof h.randomBytes!="function")throw new Error("Not supported");u.prototype._rand=function(v){return h.randomBytes(v)}}catch{}return brorand.exports}var mr,hasRequiredMr;function requireMr(){if(hasRequiredMr)return mr;hasRequiredMr=1;var y=bnExports$1,u=requireBrorand();function h(b){this.rand=b||new u.Rand}return mr=h,h.create=function(v){return new h(v)},h.prototype._randbelow=function(v){var w=v.bitLength(),_=Math.ceil(w/8);do var E=new y(this.rand.generate(_));while(E.cmp(v)>=0);return E},h.prototype._randrange=function(v,w){var _=w.sub(v);return v.add(this._randbelow(_))},h.prototype.test=function(v,w,_){var E=v.bitLength(),S=y.mont(v),x=new y(1).toRed(S);w||(w=Math.max(1,E/48|0));for(var T=v.subn(1),C=0;!T.testn(C);C++);for(var O=v.shrn(C),D=T.toRed(S),U=!0;w>0;w--){var te=this._randrange(new y(2),T);_&&_(te);var X=te.toRed(S).redPow(O);if(!(X.cmp(x)===0||X.cmp(D)===0)){for(var ie=1;ie<C;ie++){if(X=X.redSqr(),X.cmp(x)===0)return!1;if(X.cmp(D)===0)break}if(ie===C)return!1}}return U},h.prototype.getDivisor=function(v,w){var _=v.bitLength(),E=y.mont(v),S=new y(1).toRed(E);w||(w=Math.max(1,_/48|0));for(var x=v.subn(1),T=0;!x.testn(T);T++);for(var C=v.shrn(T),O=x.toRed(E);w>0;w--){var D=this._randrange(new y(2),x),U=v.gcd(D);if(U.cmpn(1)!==0)return U;var te=D.toRed(E).redPow(C);if(!(te.cmp(S)===0||te.cmp(O)===0)){for(var X=1;X<T;X++){if(te=te.redSqr(),te.cmp(S)===0)return te.fromRed().subn(1).gcd(v);if(te.cmp(O)===0)break}if(X===T)return te=te.redSqr(),te.fromRed().subn(1).gcd(v)}}return!1},mr}var generatePrime,hasRequiredGeneratePrime;function requireGeneratePrime(){if(hasRequiredGeneratePrime)return generatePrime;hasRequiredGeneratePrime=1;var y=browserExports;generatePrime=X,X.simpleSieve=U,X.fermatTest=te;var u=bnExports$1,h=new u(24),b=requireMr(),v=new b,w=new u(1),_=new u(2),E=new u(5);new u(16),new u(8);var S=new u(10),x=new u(3);new u(7);var T=new u(11),C=new u(4);new u(12);var O=null;function D(){if(O!==null)return O;var ie=1048576,ee=[];ee[0]=2;for(var ae=1,de=3;de<ie;de+=2){for(var Se=Math.ceil(Math.sqrt(de)),ve=0;ve<ae&&ee[ve]<=Se&&de%ee[ve]!==0;ve++);ae!==ve&&ee[ve]<=Se||(ee[ae++]=de)}return O=ee,ee}function U(ie){for(var ee=D(),ae=0;ae<ee.length;ae++)if(ie.modn(ee[ae])===0)return ie.cmpn(ee[ae])===0;return!0}function te(ie){var ee=u.mont(ie);return _.toRed(ee).redPow(ie.subn(1)).fromRed().cmpn(1)===0}function X(ie,ee){if(ie<16)return ee===2||ee===5?new u([140,123]):new u([140,39]);ee=new u(ee);for(var ae,de;;){for(ae=new u(y(Math.ceil(ie/8)));ae.bitLength()>ie;)ae.ishrn(1);if(ae.isEven()&&ae.iadd(w),ae.testn(1)||ae.iadd(_),ee.cmp(_)){if(!ee.cmp(E))for(;ae.mod(S).cmp(x);)ae.iadd(C)}else for(;ae.mod(h).cmp(T);)ae.iadd(C);if(de=ae.shrn(1),U(de)&&U(ae)&&te(de)&&te(ae)&&v.test(de)&&v.test(ae))return ae}}return generatePrime}const modp1={gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2={gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5={gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14={gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15={gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16={gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17={gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18={gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"},require$$1$1={modp1,modp2,modp5,modp14,modp15,modp16,modp17,modp18};var dh,hasRequiredDh;function requireDh(){if(hasRequiredDh)return dh;hasRequiredDh=1;var y=bnExports$1,u=requireMr(),h=new u,b=new y(24),v=new y(11),w=new y(10),_=new y(3),E=new y(7),S=requireGeneratePrime(),x=browserExports;dh=U;function T(X,ie){return ie=ie||"utf8",Buffer$C.isBuffer(X)||(X=new Buffer$C(X,ie)),this._pub=new y(X),this}function C(X,ie){return ie=ie||"utf8",Buffer$C.isBuffer(X)||(X=new Buffer$C(X,ie)),this._priv=new y(X),this}var O={};function D(X,ie){var ee=ie.toString("hex"),ae=[ee,X.toString(16)].join("_");if(ae in O)return O[ae];var de=0;if(X.isEven()||!S.simpleSieve||!S.fermatTest(X)||!h.test(X))return de+=1,ee==="02"||ee==="05"?de+=8:de+=4,O[ae]=de,de;h.test(X.shrn(1))||(de+=2);var Se;switch(ee){case"02":X.mod(b).cmp(v)&&(de+=8);break;case"05":Se=X.mod(w),Se.cmp(_)&&Se.cmp(E)&&(de+=8);break;default:de+=4}return O[ae]=de,de}function U(X,ie,ee){this.setGenerator(ie),this.__prime=new y(X),this._prime=y.mont(this.__prime),this._primeLen=X.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,ee?(this.setPublicKey=T,this.setPrivateKey=C):this._primeCode=8}Object.defineProperty(U.prototype,"verifyError",{enumerable:!0,get:function(){return typeof this._primeCode!="number"&&(this._primeCode=D(this.__prime,this.__gen)),this._primeCode}}),U.prototype.generateKeys=function(){return this._priv||(this._priv=new y(x(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},U.prototype.computeSecret=function(X){X=new y(X),X=X.toRed(this._prime);var ie=X.redPow(this._priv).fromRed(),ee=new Buffer$C(ie.toArray()),ae=this.getPrime();if(ee.length<ae.length){var de=new Buffer$C(ae.length-ee.length);de.fill(0),ee=Buffer$C.concat([de,ee])}return ee},U.prototype.getPublicKey=function(ie){return te(this._pub,ie)},U.prototype.getPrivateKey=function(ie){return te(this._priv,ie)},U.prototype.getPrime=function(X){return te(this.__prime,X)},U.prototype.getGenerator=function(X){return te(this._gen,X)},U.prototype.setGenerator=function(X,ie){return ie=ie||"utf8",Buffer$C.isBuffer(X)||(X=new Buffer$C(X,ie)),this.__gen=X,this._gen=new y(X),this};function te(X,ie){var ee=new Buffer$C(X.toArray());return ie?ee.toString(ie):ee}return dh}var hasRequiredBrowser$2;function requireBrowser$2(){if(hasRequiredBrowser$2)return browser$4;hasRequiredBrowser$2=1;var y=requireGeneratePrime(),u=require$$1$1,h=requireDh();function b(_){var E=new Buffer$C(u[_].prime,"hex"),S=new Buffer$C(u[_].gen,"hex");return new h(E,S)}var v={binary:!0,hex:!0,base64:!0};function w(_,E,S,x){return Buffer$C.isBuffer(E)||v[E]===void 0?w(_,"binary",E,S):(E=E||"binary",x=x||"binary",S=S||new Buffer$C([2]),Buffer$C.isBuffer(S)||(S=new Buffer$C(S,x)),typeof _=="number"?new h(y(_,S),S,!0):(Buffer$C.isBuffer(_)||(_=new Buffer$C(_,E)),new h(_,S,!0)))}return browser$4.DiffieHellmanGroup=browser$4.createDiffieHellmanGroup=browser$4.getDiffieHellman=b,browser$4.createDiffieHellman=browser$4.DiffieHellman=w,browser$4}var readableBrowser={exports:{}},processNextickArgs={exports:{}};typeof process$1>"u"||!process$1.version||process$1.version.indexOf("v0.")===0||process$1.version.indexOf("v1.")===0&&process$1.version.indexOf("v1.8.")!==0?processNextickArgs.exports={nextTick}:processNextickArgs.exports=process$1;function nextTick(y,u,h,b){if(typeof y!="function")throw new TypeError('"callback" argument must be a function');var v=arguments.length,w,_;switch(v){case 0:case 1:return process$1.nextTick(y);case 2:return process$1.nextTick(function(){y.call(null,u)});case 3:return process$1.nextTick(function(){y.call(null,u,h)});case 4:return process$1.nextTick(function(){y.call(null,u,h,b)});default:for(w=new Array(v-1),_=0;_<w.length;)w[_++]=arguments[_];return process$1.nextTick(function(){y.apply(null,w)})}}var processNextickArgsExports=processNextickArgs.exports,toString={}.toString,isarray=Array.isArray||function(y){return toString.call(y)=="[object Array]"},streamBrowser=eventsExports.EventEmitter,safeBuffer$1={exports:{}};(function(y,u){var h=dist,b=h.Buffer;function v(_,E){for(var S in _)E[S]=_[S]}b.from&&b.alloc&&b.allocUnsafe&&b.allocUnsafeSlow?y.exports=h:(v(h,u),u.Buffer=w);function w(_,E,S){return b(_,E,S)}v(b,w),w.from=function(_,E,S){if(typeof _=="number")throw new TypeError("Argument must not be a number");return b(_,E,S)},w.alloc=function(_,E,S){if(typeof _!="number")throw new TypeError("Argument must be a number");var x=b(_);return E!==void 0?typeof S=="string"?x.fill(E,S):x.fill(E):x.fill(0),x},w.allocUnsafe=function(_){if(typeof _!="number")throw new TypeError("Argument must be a number");return b(_)},w.allocUnsafeSlow=function(_){if(typeof _!="number")throw new TypeError("Argument must be a number");return h.SlowBuffer(_)}})(safeBuffer$1,safeBuffer$1.exports);var safeBufferExports=safeBuffer$1.exports,util$a={};function isArray(y){return Array.isArray?Array.isArray(y):objectToString(y)==="[object Array]"}util$a.isArray=isArray;function isBoolean(y){return typeof y=="boolean"}util$a.isBoolean=isBoolean;function isNull(y){return y===null}util$a.isNull=isNull;function isNullOrUndefined(y){return y==null}util$a.isNullOrUndefined=isNullOrUndefined;function isNumber(y){return typeof y=="number"}util$a.isNumber=isNumber;function isString(y){return typeof y=="string"}util$a.isString=isString;function isSymbol(y){return typeof y=="symbol"}util$a.isSymbol=isSymbol;function isUndefined(y){return y===void 0}util$a.isUndefined=isUndefined;function isRegExp(y){return objectToString(y)==="[object RegExp]"}util$a.isRegExp=isRegExp;function isObject(y){return typeof y=="object"&&y!==null}util$a.isObject=isObject;function isDate(y){return objectToString(y)==="[object Date]"}util$a.isDate=isDate;function isError(y){return objectToString(y)==="[object Error]"||y instanceof Error}util$a.isError=isError;function isFunction(y){return typeof y=="function"}util$a.isFunction=isFunction;function isPrimitive(y){return y===null||typeof y=="boolean"||typeof y=="number"||typeof y=="string"||typeof y=="symbol"||typeof y>"u"}util$a.isPrimitive=isPrimitive;util$a.isBuffer=dist.Buffer.isBuffer;function objectToString(y){return Object.prototype.toString.call(y)}var BufferList={exports:{}},hasRequiredBufferList;function requireBufferList(){return hasRequiredBufferList||(hasRequiredBufferList=1,function(y){function u(w,_){if(!(w instanceof _))throw new TypeError("Cannot call a class as a function")}var h=safeBufferExports.Buffer,b=util$b;function v(w,_,E){w.copy(_,E)}y.exports=function(){function w(){u(this,w),this.head=null,this.tail=null,this.length=0}return w.prototype.push=function(E){var S={data:E,next:null};this.length>0?this.tail.next=S:this.head=S,this.tail=S,++this.length},w.prototype.unshift=function(E){var S={data:E,next:this.head};this.length===0&&(this.tail=S),this.head=S,++this.length},w.prototype.shift=function(){if(this.length!==0){var E=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,E}},w.prototype.clear=function(){this.head=this.tail=null,this.length=0},w.prototype.join=function(E){if(this.length===0)return"";for(var S=this.head,x=""+S.data;S=S.next;)x+=E+S.data;return x},w.prototype.concat=function(E){if(this.length===0)return h.alloc(0);for(var S=h.allocUnsafe(E>>>0),x=this.head,T=0;x;)v(x.data,S,T),T+=x.data.length,x=x.next;return S},w}(),b&&b.inspect&&b.inspect.custom&&(y.exports.prototype[b.inspect.custom]=function(){var w=b.inspect({length:this.length});return this.constructor.name+" "+w})}(BufferList)),BufferList.exports}var pna=processNextickArgsExports;function destroy(y,u){var h=this,b=this._readableState&&this._readableState.destroyed,v=this._writableState&&this._writableState.destroyed;return b||v?(u?u(y):y&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,pna.nextTick(emitErrorNT,this,y)):pna.nextTick(emitErrorNT,this,y)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(y||null,function(w){!u&&w?h._writableState?h._writableState.errorEmitted||(h._writableState.errorEmitted=!0,pna.nextTick(emitErrorNT,h,w)):pna.nextTick(emitErrorNT,h,w):u&&u(w)}),this)}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(y,u){y.emit("error",u)}var destroy_1={destroy,undestroy},_stream_writable,hasRequired_stream_writable;function require_stream_writable(){if(hasRequired_stream_writable)return _stream_writable;hasRequired_stream_writable=1;var y=processNextickArgsExports;_stream_writable=te;function u(j){var ne=this;this.next=null,this.entry=null,this.finish=function(){Q(ne,j)}}var h=!process$1.browser&&["v0.10","v0.9."].indexOf(process$1.version.slice(0,5))>-1?setImmediate:y.nextTick,b;te.WritableState=D;var v=Object.create(util$a);v.inherits=inherits_browserExports;var w={deprecate:browser$a},_=streamBrowser,E=safeBufferExports.Buffer,S=(typeof commonjsGlobal<"u"?commonjsGlobal:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function x(j){return E.from(j)}function T(j){return E.isBuffer(j)||j instanceof S}var C=destroy_1;v.inherits(te,_);function O(){}function D(j,ne){b=b||require_stream_duplex(),j=j||{};var J=ne instanceof b;this.objectMode=!!j.objectMode,J&&(this.objectMode=this.objectMode||!!j.writableObjectMode);var q=j.highWaterMark,re=j.writableHighWaterMark,H=this.objectMode?16:16*1024;q||q===0?this.highWaterMark=q:J&&(re||re===0)?this.highWaterMark=re:this.highWaterMark=H,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var he=j.decodeStrings===!1;this.decodeStrings=!he,this.defaultEncoding=j.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(Oe){Pe(ne,Oe)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new u(this)}D.prototype.getBuffer=function(){for(var ne=this.bufferedRequest,J=[];ne;)J.push(ne),ne=ne.next;return J},function(){try{Object.defineProperty(D.prototype,"buffer",{get:w.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var U;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(U=Function.prototype[Symbol.hasInstance],Object.defineProperty(te,Symbol.hasInstance,{value:function(j){return U.call(this,j)?!0:this!==te?!1:j&&j._writableState instanceof D}})):U=function(j){return j instanceof this};function te(j){if(b=b||require_stream_duplex(),!U.call(te,this)&&!(this instanceof b))return new te(j);this._writableState=new D(j,this),this.writable=!0,j&&(typeof j.write=="function"&&(this._write=j.write),typeof j.writev=="function"&&(this._writev=j.writev),typeof j.destroy=="function"&&(this._destroy=j.destroy),typeof j.final=="function"&&(this._final=j.final)),_.call(this)}te.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function X(j,ne){var J=new Error("write after end");j.emit("error",J),y.nextTick(ne,J)}function ie(j,ne,J,q){var re=!0,H=!1;return J===null?H=new TypeError("May not write null values to stream"):typeof J!="string"&&J!==void 0&&!ne.objectMode&&(H=new TypeError("Invalid non-string/buffer chunk")),H&&(j.emit("error",H),y.nextTick(q,H),re=!1),re}te.prototype.write=function(j,ne,J){var q=this._writableState,re=!1,H=!q.objectMode&&T(j);return H&&!E.isBuffer(j)&&(j=x(j)),typeof ne=="function"&&(J=ne,ne=null),H?ne="buffer":ne||(ne=q.defaultEncoding),typeof J!="function"&&(J=O),q.ended?X(this,J):(H||ie(this,q,j,J))&&(q.pendingcb++,re=ae(this,q,H,j,ne,J)),re},te.prototype.cork=function(){var j=this._writableState;j.corked++},te.prototype.uncork=function(){var j=this._writableState;j.corked&&(j.corked--,!j.writing&&!j.corked&&!j.bufferProcessing&&j.bufferedRequest&&De(this,j))},te.prototype.setDefaultEncoding=function(ne){if(typeof ne=="string"&&(ne=ne.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((ne+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+ne);return this._writableState.defaultEncoding=ne,this};function ee(j,ne,J){return!j.objectMode&&j.decodeStrings!==!1&&typeof ne=="string"&&(ne=E.from(ne,J)),ne}Object.defineProperty(te.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function ae(j,ne,J,q,re,H){if(!J){var he=ee(ne,q,re);q!==he&&(J=!0,re="buffer",q=he)}var Oe=ne.objectMode?1:q.length;ne.length+=Oe;var Ne=ne.length<ne.highWaterMark;if(Ne||(ne.needDrain=!0),ne.writing||ne.corked){var Ae=ne.lastBufferedRequest;ne.lastBufferedRequest={chunk:q,encoding:re,isBuf:J,callback:H,next:null},Ae?Ae.next=ne.lastBufferedRequest:ne.bufferedRequest=ne.lastBufferedRequest,ne.bufferedRequestCount+=1}else de(j,ne,!1,Oe,q,re,H);return Ne}function de(j,ne,J,q,re,H,he){ne.writelen=q,ne.writecb=he,ne.writing=!0,ne.sync=!0,J?j._writev(re,ne.onwrite):j._write(re,H,ne.onwrite),ne.sync=!1}function Se(j,ne,J,q,re){--ne.pendingcb,J?(y.nextTick(re,q),y.nextTick(M,j,ne),j._writableState.errorEmitted=!0,j.emit("error",q)):(re(q),j._writableState.errorEmitted=!0,j.emit("error",q),M(j,ne))}function ve(j){j.writing=!1,j.writecb=null,j.length-=j.writelen,j.writelen=0}function Pe(j,ne){var J=j._writableState,q=J.sync,re=J.writecb;if(ve(J),ne)Se(j,J,q,ne,re);else{var H=be(J);!H&&!J.corked&&!J.bufferProcessing&&J.bufferedRequest&&De(j,J),q?h(Ie,j,J,H,re):Ie(j,J,H,re)}}function Ie(j,ne,J,q){J||Ee(j,ne),ne.pendingcb--,q(),M(j,ne)}function Ee(j,ne){ne.length===0&&ne.needDrain&&(ne.needDrain=!1,j.emit("drain"))}function De(j,ne){ne.bufferProcessing=!0;var J=ne.bufferedRequest;if(j._writev&&J&&J.next){var q=ne.bufferedRequestCount,re=new Array(q),H=ne.corkedRequestsFree;H.entry=J;for(var he=0,Oe=!0;J;)re[he]=J,J.isBuf||(Oe=!1),J=J.next,he+=1;re.allBuffers=Oe,de(j,ne,!0,ne.length,re,"",H.finish),ne.pendingcb++,ne.lastBufferedRequest=null,H.next?(ne.corkedRequestsFree=H.next,H.next=null):ne.corkedRequestsFree=new u(ne),ne.bufferedRequestCount=0}else{for(;J;){var Ne=J.chunk,Ae=J.encoding,le=J.callback,me=ne.objectMode?1:Ne.length;if(de(j,ne,!1,me,Ne,Ae,le),J=J.next,ne.bufferedRequestCount--,ne.writing)break}J===null&&(ne.lastBufferedRequest=null)}ne.bufferedRequest=J,ne.bufferProcessing=!1}te.prototype._write=function(j,ne,J){J(new Error("_write() is not implemented"))},te.prototype._writev=null,te.prototype.end=function(j,ne,J){var q=this._writableState;typeof j=="function"?(J=j,j=null,ne=null):typeof ne=="function"&&(J=ne,ne=null),j!=null&&this.write(j,ne),q.corked&&(q.corked=1,this.uncork()),q.ending||N(this,q,J)};function be(j){return j.ending&&j.length===0&&j.bufferedRequest===null&&!j.finished&&!j.writing}function B(j,ne){j._final(function(J){ne.pendingcb--,J&&j.emit("error",J),ne.prefinished=!0,j.emit("prefinish"),M(j,ne)})}function F(j,ne){!ne.prefinished&&!ne.finalCalled&&(typeof j._final=="function"?(ne.pendingcb++,ne.finalCalled=!0,y.nextTick(B,j,ne)):(ne.prefinished=!0,j.emit("prefinish")))}function M(j,ne){var J=be(ne);return J&&(F(j,ne),ne.pendingcb===0&&(ne.finished=!0,j.emit("finish"))),J}function N(j,ne,J){ne.ending=!0,M(j,ne),J&&(ne.finished?y.nextTick(J):j.once("finish",J)),ne.ended=!0,j.writable=!1}function Q(j,ne,J){var q=j.entry;for(j.entry=null;q;){var re=q.callback;ne.pendingcb--,re(J),q=q.next}ne.corkedRequestsFree.next=j}return Object.defineProperty(te.prototype,"destroyed",{get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(j){this._writableState&&(this._writableState.destroyed=j)}}),te.prototype.destroy=C.destroy,te.prototype._undestroy=C.undestroy,te.prototype._destroy=function(j,ne){this.end(),ne(j)},_stream_writable}var _stream_duplex,hasRequired_stream_duplex;function require_stream_duplex(){if(hasRequired_stream_duplex)return _stream_duplex;hasRequired_stream_duplex=1;var y=processNextickArgsExports,u=Object.keys||function(C){var O=[];for(var D in C)O.push(D);return O};_stream_duplex=S;var h=Object.create(util$a);h.inherits=inherits_browserExports;var b=require_stream_readable(),v=require_stream_writable();h.inherits(S,b);for(var w=u(v.prototype),_=0;_<w.length;_++){var E=w[_];S.prototype[E]||(S.prototype[E]=v.prototype[E])}function S(C){if(!(this instanceof S))return new S(C);b.call(this,C),v.call(this,C),C&&C.readable===!1&&(this.readable=!1),C&&C.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,C&&C.allowHalfOpen===!1&&(this.allowHalfOpen=!1),this.once("end",x)}Object.defineProperty(S.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function x(){this.allowHalfOpen||this._writableState.ended||y.nextTick(T,this)}function T(C){C.end()}return Object.defineProperty(S.prototype,"destroyed",{get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(C){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=C,this._writableState.destroyed=C)}}),S.prototype._destroy=function(C,O){this.push(null),this.end(),y.nextTick(O,C)},_stream_duplex}var _stream_readable,hasRequired_stream_readable;function require_stream_readable(){if(hasRequired_stream_readable)return _stream_readable;hasRequired_stream_readable=1;var y=processNextickArgsExports;_stream_readable=ee;var u=isarray,h;ee.ReadableState=ie,eventsExports.EventEmitter;var b=function(le,me){return le.listeners(me).length},v=streamBrowser,w=safeBufferExports.Buffer,_=(typeof commonjsGlobal<"u"?commonjsGlobal:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function E(le){return w.from(le)}function S(le){return w.isBuffer(le)||le instanceof _}var x=Object.create(util$a);x.inherits=inherits_browserExports;var T=util$b,C=void 0;T&&T.debuglog?C=T.debuglog("stream"):C=function(){};var O=requireBufferList(),D=destroy_1,U;x.inherits(ee,v);var te=["error","close","destroy","pause","resume"];function X(le,me,Me){if(typeof le.prependListener=="function")return le.prependListener(me,Me);!le._events||!le._events[me]?le.on(me,Me):u(le._events[me])?le._events[me].unshift(Me):le._events[me]=[Me,le._events[me]]}function ie(le,me){h=h||require_stream_duplex(),le=le||{};var Me=me instanceof h;this.objectMode=!!le.objectMode,Me&&(this.objectMode=this.objectMode||!!le.readableObjectMode);var fe=le.highWaterMark,ge=le.readableHighWaterMark,ce=this.objectMode?16:16*1024;fe||fe===0?this.highWaterMark=fe:Me&&(ge||ge===0)?this.highWaterMark=ge:this.highWaterMark=ce,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new O,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=le.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,le.encoding&&(U||(U=string_decoder.StringDecoder),this.decoder=new U(le.encoding),this.encoding=le.encoding)}function ee(le){if(h=h||require_stream_duplex(),!(this instanceof ee))return new ee(le);this._readableState=new ie(le,this),this.readable=!0,le&&(typeof le.read=="function"&&(this._read=le.read),typeof le.destroy=="function"&&(this._destroy=le.destroy)),v.call(this)}Object.defineProperty(ee.prototype,"destroyed",{get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(le){this._readableState&&(this._readableState.destroyed=le)}}),ee.prototype.destroy=D.destroy,ee.prototype._undestroy=D.undestroy,ee.prototype._destroy=function(le,me){this.push(null),me(le)},ee.prototype.push=function(le,me){var Me=this._readableState,fe;return Me.objectMode?fe=!0:typeof le=="string"&&(me=me||Me.defaultEncoding,me!==Me.encoding&&(le=w.from(le,me),me=""),fe=!0),ae(this,le,me,!1,fe)},ee.prototype.unshift=function(le){return ae(this,le,null,!0,!1)};function ae(le,me,Me,fe,ge){var ce=le._readableState;if(me===null)ce.reading=!1,De(le,ce);else{var _e;ge||(_e=Se(ce,me)),_e?le.emit("error",_e):ce.objectMode||me&&me.length>0?(typeof me!="string"&&!ce.objectMode&&Object.getPrototypeOf(me)!==w.prototype&&(me=E(me)),fe?ce.endEmitted?le.emit("error",new Error("stream.unshift() after end event")):de(le,ce,me,!0):ce.ended?le.emit("error",new Error("stream.push() after EOF")):(ce.reading=!1,ce.decoder&&!Me?(me=ce.decoder.write(me),ce.objectMode||me.length!==0?de(le,ce,me,!1):F(le,ce)):de(le,ce,me,!1))):fe||(ce.reading=!1)}return ve(ce)}function de(le,me,Me,fe){me.flowing&&me.length===0&&!me.sync?(le.emit("data",Me),le.read(0)):(me.length+=me.objectMode?1:Me.length,fe?me.buffer.unshift(Me):me.buffer.push(Me),me.needReadable&&be(le)),F(le,me)}function Se(le,me){var Me;return!S(me)&&typeof me!="string"&&me!==void 0&&!le.objectMode&&(Me=new TypeError("Invalid non-string/buffer chunk")),Me}function ve(le){return!le.ended&&(le.needReadable||le.length<le.highWaterMark||le.length===0)}ee.prototype.isPaused=function(){return this._readableState.flowing===!1},ee.prototype.setEncoding=function(le){return U||(U=string_decoder.StringDecoder),this._readableState.decoder=new U(le),this._readableState.encoding=le,this};var Pe=8388608;function Ie(le){return le>=Pe?le=Pe:(le--,le|=le>>>1,le|=le>>>2,le|=le>>>4,le|=le>>>8,le|=le>>>16,le++),le}function Ee(le,me){return le<=0||me.length===0&&me.ended?0:me.objectMode?1:le!==le?me.flowing&&me.length?me.buffer.head.data.length:me.length:(le>me.highWaterMark&&(me.highWaterMark=Ie(le)),le<=me.length?le:me.ended?me.length:(me.needReadable=!0,0))}ee.prototype.read=function(le){C("read",le),le=parseInt(le,10);var me=this._readableState,Me=le;if(le!==0&&(me.emittedReadable=!1),le===0&&me.needReadable&&(me.length>=me.highWaterMark||me.ended))return C("read: emitReadable",me.length,me.ended),me.length===0&&me.ended?Oe(this):be(this),null;if(le=Ee(le,me),le===0&&me.ended)return me.length===0&&Oe(this),null;var fe=me.needReadable;C("need readable",fe),(me.length===0||me.length-le<me.highWaterMark)&&(fe=!0,C("length less than watermark",fe)),me.ended||me.reading?(fe=!1,C("reading or ended",fe)):fe&&(C("do read"),me.reading=!0,me.sync=!0,me.length===0&&(me.needReadable=!0),this._read(me.highWaterMark),me.sync=!1,me.reading||(le=Ee(Me,me)));var ge;return le>0?ge=q(le,me):ge=null,ge===null?(me.needReadable=!0,le=0):me.length-=le,me.length===0&&(me.ended||(me.needReadable=!0),Me!==le&&me.ended&&Oe(this)),ge!==null&&this.emit("data",ge),ge};function De(le,me){if(!me.ended){if(me.decoder){var Me=me.decoder.end();Me&&Me.length&&(me.buffer.push(Me),me.length+=me.objectMode?1:Me.length)}me.ended=!0,be(le)}}function be(le){var me=le._readableState;me.needReadable=!1,me.emittedReadable||(C("emitReadable",me.flowing),me.emittedReadable=!0,me.sync?y.nextTick(B,le):B(le))}function B(le){C("emit readable"),le.emit("readable"),J(le)}function F(le,me){me.readingMore||(me.readingMore=!0,y.nextTick(M,le,me))}function M(le,me){for(var Me=me.length;!me.reading&&!me.flowing&&!me.ended&&me.length<me.highWaterMark&&(C("maybeReadMore read 0"),le.read(0),Me!==me.length);)Me=me.length;me.readingMore=!1}ee.prototype._read=function(le){this.emit("error",new Error("_read() is not implemented"))},ee.prototype.pipe=function(le,me){var Me=this,fe=this._readableState;switch(fe.pipesCount){case 0:fe.pipes=le;break;case 1:fe.pipes=[fe.pipes,le];break;default:fe.pipes.push(le);break}fe.pipesCount+=1,C("pipe count=%d opts=%j",fe.pipesCount,me);var ge=(!me||me.end!==!1)&&le!==process$1.stdout&&le!==process$1.stderr,ce=ge?Re:ct;fe.endEmitted?y.nextTick(ce):Me.once("end",ce),le.on("unpipe",_e);function _e(ht,xt){C("onunpipe"),ht===Me&&xt&&xt.hasUnpiped===!1&&(xt.hasUnpiped=!0,Ze())}function Re(){C("onend"),le.end()}var Ue=N(Me);le.on("drain",Ue);var qe=!1;function Ze(){C("cleanup"),le.removeListener("close",it),le.removeListener("finish",at),le.removeListener("drain",Ue),le.removeListener("error",nt),le.removeListener("unpipe",_e),Me.removeListener("end",Re),Me.removeListener("end",ct),Me.removeListener("data",Fe),qe=!0,fe.awaitDrain&&(!le._writableState||le._writableState.needDrain)&&Ue()}var tt=!1;Me.on("data",Fe);function Fe(ht){C("ondata"),tt=!1;var xt=le.write(ht);xt===!1&&!tt&&((fe.pipesCount===1&&fe.pipes===le||fe.pipesCount>1&&Ae(fe.pipes,le)!==-1)&&!qe&&(C("false write response, pause",fe.awaitDrain),fe.awaitDrain++,tt=!0),Me.pause())}function nt(ht){C("onerror",ht),ct(),le.removeListener("error",nt),b(le,"error")===0&&le.emit("error",ht)}X(le,"error",nt);function it(){le.removeListener("finish",at),ct()}le.once("close",it);function at(){C("onfinish"),le.removeListener("close",it),ct()}le.once("finish",at);function ct(){C("unpipe"),Me.unpipe(le)}return le.emit("pipe",Me),fe.flowing||(C("pipe resume"),Me.resume()),le};function N(le){return function(){var me=le._readableState;C("pipeOnDrain",me.awaitDrain),me.awaitDrain&&me.awaitDrain--,me.awaitDrain===0&&b(le,"data")&&(me.flowing=!0,J(le))}}ee.prototype.unpipe=function(le){var me=this._readableState,Me={hasUnpiped:!1};if(me.pipesCount===0)return this;if(me.pipesCount===1)return le&&le!==me.pipes?this:(le||(le=me.pipes),me.pipes=null,me.pipesCount=0,me.flowing=!1,le&&le.emit("unpipe",this,Me),this);if(!le){var fe=me.pipes,ge=me.pipesCount;me.pipes=null,me.pipesCount=0,me.flowing=!1;for(var ce=0;ce<ge;ce++)fe[ce].emit("unpipe",this,{hasUnpiped:!1});return this}var _e=Ae(me.pipes,le);return _e===-1?this:(me.pipes.splice(_e,1),me.pipesCount-=1,me.pipesCount===1&&(me.pipes=me.pipes[0]),le.emit("unpipe",this,Me),this)},ee.prototype.on=function(le,me){var Me=v.prototype.on.call(this,le,me);if(le==="data")this._readableState.flowing!==!1&&this.resume();else if(le==="readable"){var fe=this._readableState;!fe.endEmitted&&!fe.readableListening&&(fe.readableListening=fe.needReadable=!0,fe.emittedReadable=!1,fe.reading?fe.length&&be(this):y.nextTick(Q,this))}return Me},ee.prototype.addListener=ee.prototype.on;function Q(le){C("readable nexttick read 0"),le.read(0)}ee.prototype.resume=function(){var le=this._readableState;return le.flowing||(C("resume"),le.flowing=!0,j(this,le)),this};function j(le,me){me.resumeScheduled||(me.resumeScheduled=!0,y.nextTick(ne,le,me))}function ne(le,me){me.reading||(C("resume read 0"),le.read(0)),me.resumeScheduled=!1,me.awaitDrain=0,le.emit("resume"),J(le),me.flowing&&!me.reading&&le.read(0)}ee.prototype.pause=function(){return C("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(C("pause"),this._readableState.flowing=!1,this.emit("pause")),this};function J(le){var me=le._readableState;for(C("flow",me.flowing);me.flowing&&le.read()!==null;);}ee.prototype.wrap=function(le){var me=this,Me=this._readableState,fe=!1;le.on("end",function(){if(C("wrapped end"),Me.decoder&&!Me.ended){var _e=Me.decoder.end();_e&&_e.length&&me.push(_e)}me.push(null)}),le.on("data",function(_e){if(C("wrapped data"),Me.decoder&&(_e=Me.decoder.write(_e)),!(Me.objectMode&&_e==null)&&!(!Me.objectMode&&(!_e||!_e.length))){var Re=me.push(_e);Re||(fe=!0,le.pause())}});for(var ge in le)this[ge]===void 0&&typeof le[ge]=="function"&&(this[ge]=function(_e){return function(){return le[_e].apply(le,arguments)}}(ge));for(var ce=0;ce<te.length;ce++)le.on(te[ce],this.emit.bind(this,te[ce]));return this._read=function(_e){C("wrapped _read",_e),fe&&(fe=!1,le.resume())},this},Object.defineProperty(ee.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),ee._fromList=q;function q(le,me){if(me.length===0)return null;var Me;return me.objectMode?Me=me.buffer.shift():!le||le>=me.length?(me.decoder?Me=me.buffer.join(""):me.buffer.length===1?Me=me.buffer.head.data:Me=me.buffer.concat(me.length),me.buffer.clear()):Me=re(le,me.buffer,me.decoder),Me}function re(le,me,Me){var fe;return le<me.head.data.length?(fe=me.head.data.slice(0,le),me.head.data=me.head.data.slice(le)):le===me.head.data.length?fe=me.shift():fe=Me?H(le,me):he(le,me),fe}function H(le,me){var Me=me.head,fe=1,ge=Me.data;for(le-=ge.length;Me=Me.next;){var ce=Me.data,_e=le>ce.length?ce.length:le;if(_e===ce.length?ge+=ce:ge+=ce.slice(0,le),le-=_e,le===0){_e===ce.length?(++fe,Me.next?me.head=Me.next:me.head=me.tail=null):(me.head=Me,Me.data=ce.slice(_e));break}++fe}return me.length-=fe,ge}function he(le,me){var Me=w.allocUnsafe(le),fe=me.head,ge=1;for(fe.data.copy(Me),le-=fe.data.length;fe=fe.next;){var ce=fe.data,_e=le>ce.length?ce.length:le;if(ce.copy(Me,Me.length-le,0,_e),le-=_e,le===0){_e===ce.length?(++ge,fe.next?me.head=fe.next:me.head=me.tail=null):(me.head=fe,fe.data=ce.slice(_e));break}++ge}return me.length-=ge,Me}function Oe(le){var me=le._readableState;if(me.length>0)throw new Error('"endReadable()" called on non-empty stream');me.endEmitted||(me.ended=!0,y.nextTick(Ne,me,le))}function Ne(le,me){!le.endEmitted&&le.length===0&&(le.endEmitted=!0,me.readable=!1,me.emit("end"))}function Ae(le,me){for(var Me=0,fe=le.length;Me<fe;Me++)if(le[Me]===me)return Me;return-1}return _stream_readable}var _stream_transform=Transform$1,Duplex=require_stream_duplex(),util$9=Object.create(util$a);util$9.inherits=inherits_browserExports;util$9.inherits(Transform$1,Duplex);function afterTransform(y,u){var h=this._transformState;h.transforming=!1;var b=h.writecb;if(!b)return this.emit("error",new Error("write callback called multiple times"));h.writechunk=null,h.writecb=null,u!=null&&this.push(u),b(y);var v=this._readableState;v.reading=!1,(v.needReadable||v.length<v.highWaterMark)&&this._read(v.highWaterMark)}function Transform$1(y){if(!(this instanceof Transform$1))return new Transform$1(y);Duplex.call(this,y),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,y&&(typeof y.transform=="function"&&(this._transform=y.transform),typeof y.flush=="function"&&(this._flush=y.flush)),this.on("prefinish",prefinish)}function prefinish(){var y=this;typeof this._flush=="function"?this._flush(function(u,h){done(y,u,h)}):done(this,null,null)}Transform$1.prototype.push=function(y,u){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,y,u)};Transform$1.prototype._transform=function(y,u,h){throw new Error("_transform() is not implemented")};Transform$1.prototype._write=function(y,u,h){var b=this._transformState;if(b.writecb=h,b.writechunk=y,b.writeencoding=u,!b.transforming){var v=this._readableState;(b.needTransform||v.needReadable||v.length<v.highWaterMark)&&this._read(v.highWaterMark)}};Transform$1.prototype._read=function(y){var u=this._transformState;u.writechunk!==null&&u.writecb&&!u.transforming?(u.transforming=!0,this._transform(u.writechunk,u.writeencoding,u.afterTransform)):u.needTransform=!0};Transform$1.prototype._destroy=function(y,u){var h=this;Duplex.prototype._destroy.call(this,y,function(b){u(b),h.emit("close")})};function done(y,u,h){if(u)return y.emit("error",u);if(h!=null&&y.push(h),y._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(y._transformState.transforming)throw new Error("Calling transform done when still transforming");return y.push(null)}var _stream_passthrough=PassThrough,Transform=_stream_transform,util$8=Object.create(util$a);util$8.inherits=inherits_browserExports;util$8.inherits(PassThrough,Transform);function PassThrough(y){if(!(this instanceof PassThrough))return new PassThrough(y);Transform.call(this,y)}PassThrough.prototype._transform=function(y,u,h){h(null,y)};(function(y,u){u=y.exports=require_stream_readable(),u.Stream=u,u.Readable=u,u.Writable=require_stream_writable(),u.Duplex=require_stream_duplex(),u.Transform=_stream_transform,u.PassThrough=_stream_passthrough})(readableBrowser,readableBrowser.exports);var readableBrowserExports=readableBrowser.exports,sign$2={exports:{}},bn={exports:{}};bn.exports;(function(y){(function(u,h){function b(F,M){if(!F)throw new Error(M||"Assertion failed")}function v(F,M){F.super_=M;var N=function(){};N.prototype=M.prototype,F.prototype=new N,F.prototype.constructor=F}function w(F,M,N){if(w.isBN(F))return F;this.negative=0,this.words=null,this.length=0,this.red=null,F!==null&&((M==="le"||M==="be")&&(N=M,M=10),this._init(F||0,M||10,N||"be"))}typeof u=="object"?u.exports=w:h.BN=w,w.BN=w,w.wordSize=26;var _;try{typeof window<"u"&&typeof window.Buffer<"u"?_=window.Buffer:_=dist.Buffer}catch{}w.isBN=function(M){return M instanceof w?!0:M!==null&&typeof M=="object"&&M.constructor.wordSize===w.wordSize&&Array.isArray(M.words)},w.max=function(M,N){return M.cmp(N)>0?M:N},w.min=function(M,N){return M.cmp(N)<0?M:N},w.prototype._init=function(M,N,Q){if(typeof M=="number")return this._initNumber(M,N,Q);if(typeof M=="object")return this._initArray(M,N,Q);N==="hex"&&(N=16),b(N===(N|0)&&N>=2&&N<=36),M=M.toString().replace(/\s+/g,"");var j=0;M[0]==="-"&&(j++,this.negative=1),j<M.length&&(N===16?this._parseHex(M,j,Q):(this._parseBase(M,N,j),Q==="le"&&this._initArray(this.toArray(),N,Q)))},w.prototype._initNumber=function(M,N,Q){M<0&&(this.negative=1,M=-M),M<67108864?(this.words=[M&67108863],this.length=1):M<4503599627370496?(this.words=[M&67108863,M/67108864&67108863],this.length=2):(b(M<9007199254740992),this.words=[M&67108863,M/67108864&67108863,1],this.length=3),Q==="le"&&this._initArray(this.toArray(),N,Q)},w.prototype._initArray=function(M,N,Q){if(b(typeof M.length=="number"),M.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(M.length/3),this.words=new Array(this.length);for(var j=0;j<this.length;j++)this.words[j]=0;var ne,J,q=0;if(Q==="be")for(j=M.length-1,ne=0;j>=0;j-=3)J=M[j]|M[j-1]<<8|M[j-2]<<16,this.words[ne]|=J<<q&67108863,this.words[ne+1]=J>>>26-q&67108863,q+=24,q>=26&&(q-=26,ne++);else if(Q==="le")for(j=0,ne=0;j<M.length;j+=3)J=M[j]|M[j+1]<<8|M[j+2]<<16,this.words[ne]|=J<<q&67108863,this.words[ne+1]=J>>>26-q&67108863,q+=24,q>=26&&(q-=26,ne++);return this._strip()};function E(F,M){var N=F.charCodeAt(M);if(N>=48&&N<=57)return N-48;if(N>=65&&N<=70)return N-55;if(N>=97&&N<=102)return N-87;b(!1,"Invalid character in "+F)}function S(F,M,N){var Q=E(F,N);return N-1>=M&&(Q|=E(F,N-1)<<4),Q}w.prototype._parseHex=function(M,N,Q){this.length=Math.ceil((M.length-N)/6),this.words=new Array(this.length);for(var j=0;j<this.length;j++)this.words[j]=0;var ne=0,J=0,q;if(Q==="be")for(j=M.length-1;j>=N;j-=2)q=S(M,N,j)<<ne,this.words[J]|=q&67108863,ne>=18?(ne-=18,J+=1,this.words[J]|=q>>>26):ne+=8;else{var re=M.length-N;for(j=re%2===0?N+1:N;j<M.length;j+=2)q=S(M,N,j)<<ne,this.words[J]|=q&67108863,ne>=18?(ne-=18,J+=1,this.words[J]|=q>>>26):ne+=8}this._strip()};function x(F,M,N,Q){for(var j=0,ne=0,J=Math.min(F.length,N),q=M;q<J;q++){var re=F.charCodeAt(q)-48;j*=Q,re>=49?ne=re-49+10:re>=17?ne=re-17+10:ne=re,b(re>=0&&ne<Q,"Invalid character"),j+=ne}return j}w.prototype._parseBase=function(M,N,Q){this.words=[0],this.length=1;for(var j=0,ne=1;ne<=67108863;ne*=N)j++;j--,ne=ne/N|0;for(var J=M.length-Q,q=J%j,re=Math.min(J,J-q)+Q,H=0,he=Q;he<re;he+=j)H=x(M,he,he+j,N),this.imuln(ne),this.words[0]+H<67108864?this.words[0]+=H:this._iaddn(H);if(q!==0){var Oe=1;for(H=x(M,he,M.length,N),he=0;he<q;he++)Oe*=N;this.imuln(Oe),this.words[0]+H<67108864?this.words[0]+=H:this._iaddn(H)}this._strip()},w.prototype.copy=function(M){M.words=new Array(this.length);for(var N=0;N<this.length;N++)M.words[N]=this.words[N];M.length=this.length,M.negative=this.negative,M.red=this.red};function T(F,M){F.words=M.words,F.length=M.length,F.negative=M.negative,F.red=M.red}if(w.prototype._move=function(M){T(M,this)},w.prototype.clone=function(){var M=new w(null);return this.copy(M),M},w.prototype._expand=function(M){for(;this.length<M;)this.words[this.length++]=0;return this},w.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},w.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{w.prototype[Symbol.for("nodejs.util.inspect.custom")]=C}catch{w.prototype.inspect=C}else w.prototype.inspect=C;function C(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var O=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],D=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],U=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];w.prototype.toString=function(M,N){M=M||10,N=N|0||1;var Q;if(M===16||M==="hex"){Q="";for(var j=0,ne=0,J=0;J<this.length;J++){var q=this.words[J],re=((q<<j|ne)&16777215).toString(16);ne=q>>>24-j&16777215,j+=2,j>=26&&(j-=26,J--),ne!==0||J!==this.length-1?Q=O[6-re.length]+re+Q:Q=re+Q}for(ne!==0&&(Q=ne.toString(16)+Q);Q.length%N!==0;)Q="0"+Q;return this.negative!==0&&(Q="-"+Q),Q}if(M===(M|0)&&M>=2&&M<=36){var H=D[M],he=U[M];Q="";var Oe=this.clone();for(Oe.negative=0;!Oe.isZero();){var Ne=Oe.modrn(he).toString(M);Oe=Oe.idivn(he),Oe.isZero()?Q=Ne+Q:Q=O[H-Ne.length]+Ne+Q}for(this.isZero()&&(Q="0"+Q);Q.length%N!==0;)Q="0"+Q;return this.negative!==0&&(Q="-"+Q),Q}b(!1,"Base should be between 2 and 36")},w.prototype.toNumber=function(){var M=this.words[0];return this.length===2?M+=this.words[1]*67108864:this.length===3&&this.words[2]===1?M+=4503599627370496+this.words[1]*67108864:this.length>2&&b(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-M:M},w.prototype.toJSON=function(){return this.toString(16,2)},_&&(w.prototype.toBuffer=function(M,N){return this.toArrayLike(_,M,N)}),w.prototype.toArray=function(M,N){return this.toArrayLike(Array,M,N)};var te=function(M,N){return M.allocUnsafe?M.allocUnsafe(N):new M(N)};w.prototype.toArrayLike=function(M,N,Q){this._strip();var j=this.byteLength(),ne=Q||Math.max(1,j);b(j<=ne,"byte array longer than desired length"),b(ne>0,"Requested array length <= 0");var J=te(M,ne),q=N==="le"?"LE":"BE";return this["_toArrayLike"+q](J,j),J},w.prototype._toArrayLikeLE=function(M,N){for(var Q=0,j=0,ne=0,J=0;ne<this.length;ne++){var q=this.words[ne]<<J|j;M[Q++]=q&255,Q<M.length&&(M[Q++]=q>>8&255),Q<M.length&&(M[Q++]=q>>16&255),J===6?(Q<M.length&&(M[Q++]=q>>24&255),j=0,J=0):(j=q>>>24,J+=2)}if(Q<M.length)for(M[Q++]=j;Q<M.length;)M[Q++]=0},w.prototype._toArrayLikeBE=function(M,N){for(var Q=M.length-1,j=0,ne=0,J=0;ne<this.length;ne++){var q=this.words[ne]<<J|j;M[Q--]=q&255,Q>=0&&(M[Q--]=q>>8&255),Q>=0&&(M[Q--]=q>>16&255),J===6?(Q>=0&&(M[Q--]=q>>24&255),j=0,J=0):(j=q>>>24,J+=2)}if(Q>=0)for(M[Q--]=j;Q>=0;)M[Q--]=0},Math.clz32?w.prototype._countBits=function(M){return 32-Math.clz32(M)}:w.prototype._countBits=function(M){var N=M,Q=0;return N>=4096&&(Q+=13,N>>>=13),N>=64&&(Q+=7,N>>>=7),N>=8&&(Q+=4,N>>>=4),N>=2&&(Q+=2,N>>>=2),Q+N},w.prototype._zeroBits=function(M){if(M===0)return 26;var N=M,Q=0;return N&8191||(Q+=13,N>>>=13),N&127||(Q+=7,N>>>=7),N&15||(Q+=4,N>>>=4),N&3||(Q+=2,N>>>=2),N&1||Q++,Q},w.prototype.bitLength=function(){var M=this.words[this.length-1],N=this._countBits(M);return(this.length-1)*26+N};function X(F){for(var M=new Array(F.bitLength()),N=0;N<M.length;N++){var Q=N/26|0,j=N%26;M[N]=F.words[Q]>>>j&1}return M}w.prototype.zeroBits=function(){if(this.isZero())return 0;for(var M=0,N=0;N<this.length;N++){var Q=this._zeroBits(this.words[N]);if(M+=Q,Q!==26)break}return M},w.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},w.prototype.toTwos=function(M){return this.negative!==0?this.abs().inotn(M).iaddn(1):this.clone()},w.prototype.fromTwos=function(M){return this.testn(M-1)?this.notn(M).iaddn(1).ineg():this.clone()},w.prototype.isNeg=function(){return this.negative!==0},w.prototype.neg=function(){return this.clone().ineg()},w.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},w.prototype.iuor=function(M){for(;this.length<M.length;)this.words[this.length++]=0;for(var N=0;N<M.length;N++)this.words[N]=this.words[N]|M.words[N];return this._strip()},w.prototype.ior=function(M){return b((this.negative|M.negative)===0),this.iuor(M)},w.prototype.or=function(M){return this.length>M.length?this.clone().ior(M):M.clone().ior(this)},w.prototype.uor=function(M){return this.length>M.length?this.clone().iuor(M):M.clone().iuor(this)},w.prototype.iuand=function(M){var N;this.length>M.length?N=M:N=this;for(var Q=0;Q<N.length;Q++)this.words[Q]=this.words[Q]&M.words[Q];return this.length=N.length,this._strip()},w.prototype.iand=function(M){return b((this.negative|M.negative)===0),this.iuand(M)},w.prototype.and=function(M){return this.length>M.length?this.clone().iand(M):M.clone().iand(this)},w.prototype.uand=function(M){return this.length>M.length?this.clone().iuand(M):M.clone().iuand(this)},w.prototype.iuxor=function(M){var N,Q;this.length>M.length?(N=this,Q=M):(N=M,Q=this);for(var j=0;j<Q.length;j++)this.words[j]=N.words[j]^Q.words[j];if(this!==N)for(;j<N.length;j++)this.words[j]=N.words[j];return this.length=N.length,this._strip()},w.prototype.ixor=function(M){return b((this.negative|M.negative)===0),this.iuxor(M)},w.prototype.xor=function(M){return this.length>M.length?this.clone().ixor(M):M.clone().ixor(this)},w.prototype.uxor=function(M){return this.length>M.length?this.clone().iuxor(M):M.clone().iuxor(this)},w.prototype.inotn=function(M){b(typeof M=="number"&&M>=0);var N=Math.ceil(M/26)|0,Q=M%26;this._expand(N),Q>0&&N--;for(var j=0;j<N;j++)this.words[j]=~this.words[j]&67108863;return Q>0&&(this.words[j]=~this.words[j]&67108863>>26-Q),this._strip()},w.prototype.notn=function(M){return this.clone().inotn(M)},w.prototype.setn=function(M,N){b(typeof M=="number"&&M>=0);var Q=M/26|0,j=M%26;return this._expand(Q+1),N?this.words[Q]=this.words[Q]|1<<j:this.words[Q]=this.words[Q]&~(1<<j),this._strip()},w.prototype.iadd=function(M){var N;if(this.negative!==0&&M.negative===0)return this.negative=0,N=this.isub(M),this.negative^=1,this._normSign();if(this.negative===0&&M.negative!==0)return M.negative=0,N=this.isub(M),M.negative=1,N._normSign();var Q,j;this.length>M.length?(Q=this,j=M):(Q=M,j=this);for(var ne=0,J=0;J<j.length;J++)N=(Q.words[J]|0)+(j.words[J]|0)+ne,this.words[J]=N&67108863,ne=N>>>26;for(;ne!==0&&J<Q.length;J++)N=(Q.words[J]|0)+ne,this.words[J]=N&67108863,ne=N>>>26;if(this.length=Q.length,ne!==0)this.words[this.length]=ne,this.length++;else if(Q!==this)for(;J<Q.length;J++)this.words[J]=Q.words[J];return this},w.prototype.add=function(M){var N;return M.negative!==0&&this.negative===0?(M.negative=0,N=this.sub(M),M.negative^=1,N):M.negative===0&&this.negative!==0?(this.negative=0,N=M.sub(this),this.negative=1,N):this.length>M.length?this.clone().iadd(M):M.clone().iadd(this)},w.prototype.isub=function(M){if(M.negative!==0){M.negative=0;var N=this.iadd(M);return M.negative=1,N._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(M),this.negative=1,this._normSign();var Q=this.cmp(M);if(Q===0)return this.negative=0,this.length=1,this.words[0]=0,this;var j,ne;Q>0?(j=this,ne=M):(j=M,ne=this);for(var J=0,q=0;q<ne.length;q++)N=(j.words[q]|0)-(ne.words[q]|0)+J,J=N>>26,this.words[q]=N&67108863;for(;J!==0&&q<j.length;q++)N=(j.words[q]|0)+J,J=N>>26,this.words[q]=N&67108863;if(J===0&&q<j.length&&j!==this)for(;q<j.length;q++)this.words[q]=j.words[q];return this.length=Math.max(this.length,q),j!==this&&(this.negative=1),this._strip()},w.prototype.sub=function(M){return this.clone().isub(M)};function ie(F,M,N){N.negative=M.negative^F.negative;var Q=F.length+M.length|0;N.length=Q,Q=Q-1|0;var j=F.words[0]|0,ne=M.words[0]|0,J=j*ne,q=J&67108863,re=J/67108864|0;N.words[0]=q;for(var H=1;H<Q;H++){for(var he=re>>>26,Oe=re&67108863,Ne=Math.min(H,M.length-1),Ae=Math.max(0,H-F.length+1);Ae<=Ne;Ae++){var le=H-Ae|0;j=F.words[le]|0,ne=M.words[Ae]|0,J=j*ne+Oe,he+=J/67108864|0,Oe=J&67108863}N.words[H]=Oe|0,re=he|0}return re!==0?N.words[H]=re|0:N.length--,N._strip()}var ee=function(M,N,Q){var j=M.words,ne=N.words,J=Q.words,q=0,re,H,he,Oe=j[0]|0,Ne=Oe&8191,Ae=Oe>>>13,le=j[1]|0,me=le&8191,Me=le>>>13,fe=j[2]|0,ge=fe&8191,ce=fe>>>13,_e=j[3]|0,Re=_e&8191,Ue=_e>>>13,qe=j[4]|0,Ze=qe&8191,tt=qe>>>13,Fe=j[5]|0,nt=Fe&8191,it=Fe>>>13,at=j[6]|0,ct=at&8191,ht=at>>>13,xt=j[7]|0,Ot=xt&8191,dt=xt>>>13,Rt=j[8]|0,Nt=Rt&8191,yt=Rt>>>13,zt=j[9]|0,Vt=zt&8191,vt=zt>>>13,Ut=ne[0]|0,Lt=Ut&8191,wt=Ut>>>13,Wt=ne[1]|0,Gt=Wt&8191,At=Wt>>>13,tr=ne[2]|0,Xt=tr&8191,bt=tr>>>13,Bt=ne[3]|0,Yt=Bt&8191,Tt=Bt>>>13,qt=ne[4]|0,Jt=qt&8191,we=qt>>>13,se=ne[5]|0,ue=se&8191,xe=se>>>13,ke=ne[6]|0,Ke=ke&8191,We=ke>>>13,ut=ne[7]|0,_t=ut&8191,st=ut>>>13,Et=ne[8]|0,gt=Et&8191,It=Et>>>13,Qt=ne[9]|0,rr=Qt&8191,ar=Qt>>>13;Q.negative=M.negative^N.negative,Q.length=19,re=Math.imul(Ne,Lt),H=Math.imul(Ne,wt),H=H+Math.imul(Ae,Lt)|0,he=Math.imul(Ae,wt);var Gr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Gr>>>26)|0,Gr&=67108863,re=Math.imul(me,Lt),H=Math.imul(me,wt),H=H+Math.imul(Me,Lt)|0,he=Math.imul(Me,wt),re=re+Math.imul(Ne,Gt)|0,H=H+Math.imul(Ne,At)|0,H=H+Math.imul(Ae,Gt)|0,he=he+Math.imul(Ae,At)|0;var Hr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Hr>>>26)|0,Hr&=67108863,re=Math.imul(ge,Lt),H=Math.imul(ge,wt),H=H+Math.imul(ce,Lt)|0,he=Math.imul(ce,wt),re=re+Math.imul(me,Gt)|0,H=H+Math.imul(me,At)|0,H=H+Math.imul(Me,Gt)|0,he=he+Math.imul(Me,At)|0,re=re+Math.imul(Ne,Xt)|0,H=H+Math.imul(Ne,bt)|0,H=H+Math.imul(Ae,Xt)|0,he=he+Math.imul(Ae,bt)|0;var jr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(jr>>>26)|0,jr&=67108863,re=Math.imul(Re,Lt),H=Math.imul(Re,wt),H=H+Math.imul(Ue,Lt)|0,he=Math.imul(Ue,wt),re=re+Math.imul(ge,Gt)|0,H=H+Math.imul(ge,At)|0,H=H+Math.imul(ce,Gt)|0,he=he+Math.imul(ce,At)|0,re=re+Math.imul(me,Xt)|0,H=H+Math.imul(me,bt)|0,H=H+Math.imul(Me,Xt)|0,he=he+Math.imul(Me,bt)|0,re=re+Math.imul(Ne,Yt)|0,H=H+Math.imul(Ne,Tt)|0,H=H+Math.imul(Ae,Yt)|0,he=he+Math.imul(Ae,Tt)|0;var Xr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,re=Math.imul(Ze,Lt),H=Math.imul(Ze,wt),H=H+Math.imul(tt,Lt)|0,he=Math.imul(tt,wt),re=re+Math.imul(Re,Gt)|0,H=H+Math.imul(Re,At)|0,H=H+Math.imul(Ue,Gt)|0,he=he+Math.imul(Ue,At)|0,re=re+Math.imul(ge,Xt)|0,H=H+Math.imul(ge,bt)|0,H=H+Math.imul(ce,Xt)|0,he=he+Math.imul(ce,bt)|0,re=re+Math.imul(me,Yt)|0,H=H+Math.imul(me,Tt)|0,H=H+Math.imul(Me,Yt)|0,he=he+Math.imul(Me,Tt)|0,re=re+Math.imul(Ne,Jt)|0,H=H+Math.imul(Ne,we)|0,H=H+Math.imul(Ae,Jt)|0,he=he+Math.imul(Ae,we)|0;var Yr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Yr>>>26)|0,Yr&=67108863,re=Math.imul(nt,Lt),H=Math.imul(nt,wt),H=H+Math.imul(it,Lt)|0,he=Math.imul(it,wt),re=re+Math.imul(Ze,Gt)|0,H=H+Math.imul(Ze,At)|0,H=H+Math.imul(tt,Gt)|0,he=he+Math.imul(tt,At)|0,re=re+Math.imul(Re,Xt)|0,H=H+Math.imul(Re,bt)|0,H=H+Math.imul(Ue,Xt)|0,he=he+Math.imul(Ue,bt)|0,re=re+Math.imul(ge,Yt)|0,H=H+Math.imul(ge,Tt)|0,H=H+Math.imul(ce,Yt)|0,he=he+Math.imul(ce,Tt)|0,re=re+Math.imul(me,Jt)|0,H=H+Math.imul(me,we)|0,H=H+Math.imul(Me,Jt)|0,he=he+Math.imul(Me,we)|0,re=re+Math.imul(Ne,ue)|0,H=H+Math.imul(Ne,xe)|0,H=H+Math.imul(Ae,ue)|0,he=he+Math.imul(Ae,xe)|0;var Br=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Br>>>26)|0,Br&=67108863,re=Math.imul(ct,Lt),H=Math.imul(ct,wt),H=H+Math.imul(ht,Lt)|0,he=Math.imul(ht,wt),re=re+Math.imul(nt,Gt)|0,H=H+Math.imul(nt,At)|0,H=H+Math.imul(it,Gt)|0,he=he+Math.imul(it,At)|0,re=re+Math.imul(Ze,Xt)|0,H=H+Math.imul(Ze,bt)|0,H=H+Math.imul(tt,Xt)|0,he=he+Math.imul(tt,bt)|0,re=re+Math.imul(Re,Yt)|0,H=H+Math.imul(Re,Tt)|0,H=H+Math.imul(Ue,Yt)|0,he=he+Math.imul(Ue,Tt)|0,re=re+Math.imul(ge,Jt)|0,H=H+Math.imul(ge,we)|0,H=H+Math.imul(ce,Jt)|0,he=he+Math.imul(ce,we)|0,re=re+Math.imul(me,ue)|0,H=H+Math.imul(me,xe)|0,H=H+Math.imul(Me,ue)|0,he=he+Math.imul(Me,xe)|0,re=re+Math.imul(Ne,Ke)|0,H=H+Math.imul(Ne,We)|0,H=H+Math.imul(Ae,Ke)|0,he=he+Math.imul(Ae,We)|0;var Kr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Kr>>>26)|0,Kr&=67108863,re=Math.imul(Ot,Lt),H=Math.imul(Ot,wt),H=H+Math.imul(dt,Lt)|0,he=Math.imul(dt,wt),re=re+Math.imul(ct,Gt)|0,H=H+Math.imul(ct,At)|0,H=H+Math.imul(ht,Gt)|0,he=he+Math.imul(ht,At)|0,re=re+Math.imul(nt,Xt)|0,H=H+Math.imul(nt,bt)|0,H=H+Math.imul(it,Xt)|0,he=he+Math.imul(it,bt)|0,re=re+Math.imul(Ze,Yt)|0,H=H+Math.imul(Ze,Tt)|0,H=H+Math.imul(tt,Yt)|0,he=he+Math.imul(tt,Tt)|0,re=re+Math.imul(Re,Jt)|0,H=H+Math.imul(Re,we)|0,H=H+Math.imul(Ue,Jt)|0,he=he+Math.imul(Ue,we)|0,re=re+Math.imul(ge,ue)|0,H=H+Math.imul(ge,xe)|0,H=H+Math.imul(ce,ue)|0,he=he+Math.imul(ce,xe)|0,re=re+Math.imul(me,Ke)|0,H=H+Math.imul(me,We)|0,H=H+Math.imul(Me,Ke)|0,he=he+Math.imul(Me,We)|0,re=re+Math.imul(Ne,_t)|0,H=H+Math.imul(Ne,st)|0,H=H+Math.imul(Ae,_t)|0,he=he+Math.imul(Ae,st)|0;var kr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(kr>>>26)|0,kr&=67108863,re=Math.imul(Nt,Lt),H=Math.imul(Nt,wt),H=H+Math.imul(yt,Lt)|0,he=Math.imul(yt,wt),re=re+Math.imul(Ot,Gt)|0,H=H+Math.imul(Ot,At)|0,H=H+Math.imul(dt,Gt)|0,he=he+Math.imul(dt,At)|0,re=re+Math.imul(ct,Xt)|0,H=H+Math.imul(ct,bt)|0,H=H+Math.imul(ht,Xt)|0,he=he+Math.imul(ht,bt)|0,re=re+Math.imul(nt,Yt)|0,H=H+Math.imul(nt,Tt)|0,H=H+Math.imul(it,Yt)|0,he=he+Math.imul(it,Tt)|0,re=re+Math.imul(Ze,Jt)|0,H=H+Math.imul(Ze,we)|0,H=H+Math.imul(tt,Jt)|0,he=he+Math.imul(tt,we)|0,re=re+Math.imul(Re,ue)|0,H=H+Math.imul(Re,xe)|0,H=H+Math.imul(Ue,ue)|0,he=he+Math.imul(Ue,xe)|0,re=re+Math.imul(ge,Ke)|0,H=H+Math.imul(ge,We)|0,H=H+Math.imul(ce,Ke)|0,he=he+Math.imul(ce,We)|0,re=re+Math.imul(me,_t)|0,H=H+Math.imul(me,st)|0,H=H+Math.imul(Me,_t)|0,he=he+Math.imul(Me,st)|0,re=re+Math.imul(Ne,gt)|0,H=H+Math.imul(Ne,It)|0,H=H+Math.imul(Ae,gt)|0,he=he+Math.imul(Ae,It)|0;var Mr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Mr>>>26)|0,Mr&=67108863,re=Math.imul(Vt,Lt),H=Math.imul(Vt,wt),H=H+Math.imul(vt,Lt)|0,he=Math.imul(vt,wt),re=re+Math.imul(Nt,Gt)|0,H=H+Math.imul(Nt,At)|0,H=H+Math.imul(yt,Gt)|0,he=he+Math.imul(yt,At)|0,re=re+Math.imul(Ot,Xt)|0,H=H+Math.imul(Ot,bt)|0,H=H+Math.imul(dt,Xt)|0,he=he+Math.imul(dt,bt)|0,re=re+Math.imul(ct,Yt)|0,H=H+Math.imul(ct,Tt)|0,H=H+Math.imul(ht,Yt)|0,he=he+Math.imul(ht,Tt)|0,re=re+Math.imul(nt,Jt)|0,H=H+Math.imul(nt,we)|0,H=H+Math.imul(it,Jt)|0,he=he+Math.imul(it,we)|0,re=re+Math.imul(Ze,ue)|0,H=H+Math.imul(Ze,xe)|0,H=H+Math.imul(tt,ue)|0,he=he+Math.imul(tt,xe)|0,re=re+Math.imul(Re,Ke)|0,H=H+Math.imul(Re,We)|0,H=H+Math.imul(Ue,Ke)|0,he=he+Math.imul(Ue,We)|0,re=re+Math.imul(ge,_t)|0,H=H+Math.imul(ge,st)|0,H=H+Math.imul(ce,_t)|0,he=he+Math.imul(ce,st)|0,re=re+Math.imul(me,gt)|0,H=H+Math.imul(me,It)|0,H=H+Math.imul(Me,gt)|0,he=he+Math.imul(Me,It)|0,re=re+Math.imul(Ne,rr)|0,H=H+Math.imul(Ne,ar)|0,H=H+Math.imul(Ae,rr)|0,he=he+Math.imul(Ae,ar)|0;var Jr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Jr>>>26)|0,Jr&=67108863,re=Math.imul(Vt,Gt),H=Math.imul(Vt,At),H=H+Math.imul(vt,Gt)|0,he=Math.imul(vt,At),re=re+Math.imul(Nt,Xt)|0,H=H+Math.imul(Nt,bt)|0,H=H+Math.imul(yt,Xt)|0,he=he+Math.imul(yt,bt)|0,re=re+Math.imul(Ot,Yt)|0,H=H+Math.imul(Ot,Tt)|0,H=H+Math.imul(dt,Yt)|0,he=he+Math.imul(dt,Tt)|0,re=re+Math.imul(ct,Jt)|0,H=H+Math.imul(ct,we)|0,H=H+Math.imul(ht,Jt)|0,he=he+Math.imul(ht,we)|0,re=re+Math.imul(nt,ue)|0,H=H+Math.imul(nt,xe)|0,H=H+Math.imul(it,ue)|0,he=he+Math.imul(it,xe)|0,re=re+Math.imul(Ze,Ke)|0,H=H+Math.imul(Ze,We)|0,H=H+Math.imul(tt,Ke)|0,he=he+Math.imul(tt,We)|0,re=re+Math.imul(Re,_t)|0,H=H+Math.imul(Re,st)|0,H=H+Math.imul(Ue,_t)|0,he=he+Math.imul(Ue,st)|0,re=re+Math.imul(ge,gt)|0,H=H+Math.imul(ge,It)|0,H=H+Math.imul(ce,gt)|0,he=he+Math.imul(ce,It)|0,re=re+Math.imul(me,rr)|0,H=H+Math.imul(me,ar)|0,H=H+Math.imul(Me,rr)|0,he=he+Math.imul(Me,ar)|0;var Vr=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Vr>>>26)|0,Vr&=67108863,re=Math.imul(Vt,Xt),H=Math.imul(Vt,bt),H=H+Math.imul(vt,Xt)|0,he=Math.imul(vt,bt),re=re+Math.imul(Nt,Yt)|0,H=H+Math.imul(Nt,Tt)|0,H=H+Math.imul(yt,Yt)|0,he=he+Math.imul(yt,Tt)|0,re=re+Math.imul(Ot,Jt)|0,H=H+Math.imul(Ot,we)|0,H=H+Math.imul(dt,Jt)|0,he=he+Math.imul(dt,we)|0,re=re+Math.imul(ct,ue)|0,H=H+Math.imul(ct,xe)|0,H=H+Math.imul(ht,ue)|0,he=he+Math.imul(ht,xe)|0,re=re+Math.imul(nt,Ke)|0,H=H+Math.imul(nt,We)|0,H=H+Math.imul(it,Ke)|0,he=he+Math.imul(it,We)|0,re=re+Math.imul(Ze,_t)|0,H=H+Math.imul(Ze,st)|0,H=H+Math.imul(tt,_t)|0,he=he+Math.imul(tt,st)|0,re=re+Math.imul(Re,gt)|0,H=H+Math.imul(Re,It)|0,H=H+Math.imul(Ue,gt)|0,he=he+Math.imul(Ue,It)|0,re=re+Math.imul(ge,rr)|0,H=H+Math.imul(ge,ar)|0,H=H+Math.imul(ce,rr)|0,he=he+Math.imul(ce,ar)|0;var Tn=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Tn>>>26)|0,Tn&=67108863,re=Math.imul(Vt,Yt),H=Math.imul(Vt,Tt),H=H+Math.imul(vt,Yt)|0,he=Math.imul(vt,Tt),re=re+Math.imul(Nt,Jt)|0,H=H+Math.imul(Nt,we)|0,H=H+Math.imul(yt,Jt)|0,he=he+Math.imul(yt,we)|0,re=re+Math.imul(Ot,ue)|0,H=H+Math.imul(Ot,xe)|0,H=H+Math.imul(dt,ue)|0,he=he+Math.imul(dt,xe)|0,re=re+Math.imul(ct,Ke)|0,H=H+Math.imul(ct,We)|0,H=H+Math.imul(ht,Ke)|0,he=he+Math.imul(ht,We)|0,re=re+Math.imul(nt,_t)|0,H=H+Math.imul(nt,st)|0,H=H+Math.imul(it,_t)|0,he=he+Math.imul(it,st)|0,re=re+Math.imul(Ze,gt)|0,H=H+Math.imul(Ze,It)|0,H=H+Math.imul(tt,gt)|0,he=he+Math.imul(tt,It)|0,re=re+Math.imul(Re,rr)|0,H=H+Math.imul(Re,ar)|0,H=H+Math.imul(Ue,rr)|0,he=he+Math.imul(Ue,ar)|0;var In=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(In>>>26)|0,In&=67108863,re=Math.imul(Vt,Jt),H=Math.imul(Vt,we),H=H+Math.imul(vt,Jt)|0,he=Math.imul(vt,we),re=re+Math.imul(Nt,ue)|0,H=H+Math.imul(Nt,xe)|0,H=H+Math.imul(yt,ue)|0,he=he+Math.imul(yt,xe)|0,re=re+Math.imul(Ot,Ke)|0,H=H+Math.imul(Ot,We)|0,H=H+Math.imul(dt,Ke)|0,he=he+Math.imul(dt,We)|0,re=re+Math.imul(ct,_t)|0,H=H+Math.imul(ct,st)|0,H=H+Math.imul(ht,_t)|0,he=he+Math.imul(ht,st)|0,re=re+Math.imul(nt,gt)|0,H=H+Math.imul(nt,It)|0,H=H+Math.imul(it,gt)|0,he=he+Math.imul(it,It)|0,re=re+Math.imul(Ze,rr)|0,H=H+Math.imul(Ze,ar)|0,H=H+Math.imul(tt,rr)|0,he=he+Math.imul(tt,ar)|0;var pn=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(pn>>>26)|0,pn&=67108863,re=Math.imul(Vt,ue),H=Math.imul(Vt,xe),H=H+Math.imul(vt,ue)|0,he=Math.imul(vt,xe),re=re+Math.imul(Nt,Ke)|0,H=H+Math.imul(Nt,We)|0,H=H+Math.imul(yt,Ke)|0,he=he+Math.imul(yt,We)|0,re=re+Math.imul(Ot,_t)|0,H=H+Math.imul(Ot,st)|0,H=H+Math.imul(dt,_t)|0,he=he+Math.imul(dt,st)|0,re=re+Math.imul(ct,gt)|0,H=H+Math.imul(ct,It)|0,H=H+Math.imul(ht,gt)|0,he=he+Math.imul(ht,It)|0,re=re+Math.imul(nt,rr)|0,H=H+Math.imul(nt,ar)|0,H=H+Math.imul(it,rr)|0,he=he+Math.imul(it,ar)|0;var Fn=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Fn>>>26)|0,Fn&=67108863,re=Math.imul(Vt,Ke),H=Math.imul(Vt,We),H=H+Math.imul(vt,Ke)|0,he=Math.imul(vt,We),re=re+Math.imul(Nt,_t)|0,H=H+Math.imul(Nt,st)|0,H=H+Math.imul(yt,_t)|0,he=he+Math.imul(yt,st)|0,re=re+Math.imul(Ot,gt)|0,H=H+Math.imul(Ot,It)|0,H=H+Math.imul(dt,gt)|0,he=he+Math.imul(dt,It)|0,re=re+Math.imul(ct,rr)|0,H=H+Math.imul(ct,ar)|0,H=H+Math.imul(ht,rr)|0,he=he+Math.imul(ht,ar)|0;var Un=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Un>>>26)|0,Un&=67108863,re=Math.imul(Vt,_t),H=Math.imul(Vt,st),H=H+Math.imul(vt,_t)|0,he=Math.imul(vt,st),re=re+Math.imul(Nt,gt)|0,H=H+Math.imul(Nt,It)|0,H=H+Math.imul(yt,gt)|0,he=he+Math.imul(yt,It)|0,re=re+Math.imul(Ot,rr)|0,H=H+Math.imul(Ot,ar)|0,H=H+Math.imul(dt,rr)|0,he=he+Math.imul(dt,ar)|0;var qn=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(qn>>>26)|0,qn&=67108863,re=Math.imul(Vt,gt),H=Math.imul(Vt,It),H=H+Math.imul(vt,gt)|0,he=Math.imul(vt,It),re=re+Math.imul(Nt,rr)|0,H=H+Math.imul(Nt,ar)|0,H=H+Math.imul(yt,rr)|0,he=he+Math.imul(yt,ar)|0;var Qi=(q+re|0)+((H&8191)<<13)|0;q=(he+(H>>>13)|0)+(Qi>>>26)|0,Qi&=67108863,re=Math.imul(Vt,rr),H=Math.imul(Vt,ar),H=H+Math.imul(vt,rr)|0,he=Math.imul(vt,ar);var Hn=(q+re|0)+((H&8191)<<13)|0;return q=(he+(H>>>13)|0)+(Hn>>>26)|0,Hn&=67108863,J[0]=Gr,J[1]=Hr,J[2]=jr,J[3]=Xr,J[4]=Yr,J[5]=Br,J[6]=Kr,J[7]=kr,J[8]=Mr,J[9]=Jr,J[10]=Vr,J[11]=Tn,J[12]=In,J[13]=pn,J[14]=Fn,J[15]=Un,J[16]=qn,J[17]=Qi,J[18]=Hn,q!==0&&(J[19]=q,Q.length++),Q};Math.imul||(ee=ie);function ae(F,M,N){N.negative=M.negative^F.negative,N.length=F.length+M.length;for(var Q=0,j=0,ne=0;ne<N.length-1;ne++){var J=j;j=0;for(var q=Q&67108863,re=Math.min(ne,M.length-1),H=Math.max(0,ne-F.length+1);H<=re;H++){var he=ne-H,Oe=F.words[he]|0,Ne=M.words[H]|0,Ae=Oe*Ne,le=Ae&67108863;J=J+(Ae/67108864|0)|0,le=le+q|0,q=le&67108863,J=J+(le>>>26)|0,j+=J>>>26,J&=67108863}N.words[ne]=q,Q=J,J=j}return Q!==0?N.words[ne]=Q:N.length--,N._strip()}function de(F,M,N){return ae(F,M,N)}w.prototype.mulTo=function(M,N){var Q,j=this.length+M.length;return this.length===10&&M.length===10?Q=ee(this,M,N):j<63?Q=ie(this,M,N):j<1024?Q=ae(this,M,N):Q=de(this,M,N),Q},w.prototype.mul=function(M){var N=new w(null);return N.words=new Array(this.length+M.length),this.mulTo(M,N)},w.prototype.mulf=function(M){var N=new w(null);return N.words=new Array(this.length+M.length),de(this,M,N)},w.prototype.imul=function(M){return this.clone().mulTo(M,this)},w.prototype.imuln=function(M){var N=M<0;N&&(M=-M),b(typeof M=="number"),b(M<67108864);for(var Q=0,j=0;j<this.length;j++){var ne=(this.words[j]|0)*M,J=(ne&67108863)+(Q&67108863);Q>>=26,Q+=ne/67108864|0,Q+=J>>>26,this.words[j]=J&67108863}return Q!==0&&(this.words[j]=Q,this.length++),N?this.ineg():this},w.prototype.muln=function(M){return this.clone().imuln(M)},w.prototype.sqr=function(){return this.mul(this)},w.prototype.isqr=function(){return this.imul(this.clone())},w.prototype.pow=function(M){var N=X(M);if(N.length===0)return new w(1);for(var Q=this,j=0;j<N.length&&N[j]===0;j++,Q=Q.sqr());if(++j<N.length)for(var ne=Q.sqr();j<N.length;j++,ne=ne.sqr())N[j]!==0&&(Q=Q.mul(ne));return Q},w.prototype.iushln=function(M){b(typeof M=="number"&&M>=0);var N=M%26,Q=(M-N)/26,j=67108863>>>26-N<<26-N,ne;if(N!==0){var J=0;for(ne=0;ne<this.length;ne++){var q=this.words[ne]&j,re=(this.words[ne]|0)-q<<N;this.words[ne]=re|J,J=q>>>26-N}J&&(this.words[ne]=J,this.length++)}if(Q!==0){for(ne=this.length-1;ne>=0;ne--)this.words[ne+Q]=this.words[ne];for(ne=0;ne<Q;ne++)this.words[ne]=0;this.length+=Q}return this._strip()},w.prototype.ishln=function(M){return b(this.negative===0),this.iushln(M)},w.prototype.iushrn=function(M,N,Q){b(typeof M=="number"&&M>=0);var j;N?j=(N-N%26)/26:j=0;var ne=M%26,J=Math.min((M-ne)/26,this.length),q=67108863^67108863>>>ne<<ne,re=Q;if(j-=J,j=Math.max(0,j),re){for(var H=0;H<J;H++)re.words[H]=this.words[H];re.length=J}if(J!==0)if(this.length>J)for(this.length-=J,H=0;H<this.length;H++)this.words[H]=this.words[H+J];else this.words[0]=0,this.length=1;var he=0;for(H=this.length-1;H>=0&&(he!==0||H>=j);H--){var Oe=this.words[H]|0;this.words[H]=he<<26-ne|Oe>>>ne,he=Oe&q}return re&&he!==0&&(re.words[re.length++]=he),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},w.prototype.ishrn=function(M,N,Q){return b(this.negative===0),this.iushrn(M,N,Q)},w.prototype.shln=function(M){return this.clone().ishln(M)},w.prototype.ushln=function(M){return this.clone().iushln(M)},w.prototype.shrn=function(M){return this.clone().ishrn(M)},w.prototype.ushrn=function(M){return this.clone().iushrn(M)},w.prototype.testn=function(M){b(typeof M=="number"&&M>=0);var N=M%26,Q=(M-N)/26,j=1<<N;if(this.length<=Q)return!1;var ne=this.words[Q];return!!(ne&j)},w.prototype.imaskn=function(M){b(typeof M=="number"&&M>=0);var N=M%26,Q=(M-N)/26;if(b(this.negative===0,"imaskn works only with positive numbers"),this.length<=Q)return this;if(N!==0&&Q++,this.length=Math.min(Q,this.length),N!==0){var j=67108863^67108863>>>N<<N;this.words[this.length-1]&=j}return this._strip()},w.prototype.maskn=function(M){return this.clone().imaskn(M)},w.prototype.iaddn=function(M){return b(typeof M=="number"),b(M<67108864),M<0?this.isubn(-M):this.negative!==0?this.length===1&&(this.words[0]|0)<=M?(this.words[0]=M-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(M),this.negative=1,this):this._iaddn(M)},w.prototype._iaddn=function(M){this.words[0]+=M;for(var N=0;N<this.length&&this.words[N]>=67108864;N++)this.words[N]-=67108864,N===this.length-1?this.words[N+1]=1:this.words[N+1]++;return this.length=Math.max(this.length,N+1),this},w.prototype.isubn=function(M){if(b(typeof M=="number"),b(M<67108864),M<0)return this.iaddn(-M);if(this.negative!==0)return this.negative=0,this.iaddn(M),this.negative=1,this;if(this.words[0]-=M,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var N=0;N<this.length&&this.words[N]<0;N++)this.words[N]+=67108864,this.words[N+1]-=1;return this._strip()},w.prototype.addn=function(M){return this.clone().iaddn(M)},w.prototype.subn=function(M){return this.clone().isubn(M)},w.prototype.iabs=function(){return this.negative=0,this},w.prototype.abs=function(){return this.clone().iabs()},w.prototype._ishlnsubmul=function(M,N,Q){var j=M.length+Q,ne;this._expand(j);var J,q=0;for(ne=0;ne<M.length;ne++){J=(this.words[ne+Q]|0)+q;var re=(M.words[ne]|0)*N;J-=re&67108863,q=(J>>26)-(re/67108864|0),this.words[ne+Q]=J&67108863}for(;ne<this.length-Q;ne++)J=(this.words[ne+Q]|0)+q,q=J>>26,this.words[ne+Q]=J&67108863;if(q===0)return this._strip();for(b(q===-1),q=0,ne=0;ne<this.length;ne++)J=-(this.words[ne]|0)+q,q=J>>26,this.words[ne]=J&67108863;return this.negative=1,this._strip()},w.prototype._wordDiv=function(M,N){var Q=this.length-M.length,j=this.clone(),ne=M,J=ne.words[ne.length-1]|0,q=this._countBits(J);Q=26-q,Q!==0&&(ne=ne.ushln(Q),j.iushln(Q),J=ne.words[ne.length-1]|0);var re=j.length-ne.length,H;if(N!=="mod"){H=new w(null),H.length=re+1,H.words=new Array(H.length);for(var he=0;he<H.length;he++)H.words[he]=0}var Oe=j.clone()._ishlnsubmul(ne,1,re);Oe.negative===0&&(j=Oe,H&&(H.words[re]=1));for(var Ne=re-1;Ne>=0;Ne--){var Ae=(j.words[ne.length+Ne]|0)*67108864+(j.words[ne.length+Ne-1]|0);for(Ae=Math.min(Ae/J|0,67108863),j._ishlnsubmul(ne,Ae,Ne);j.negative!==0;)Ae--,j.negative=0,j._ishlnsubmul(ne,1,Ne),j.isZero()||(j.negative^=1);H&&(H.words[Ne]=Ae)}return H&&H._strip(),j._strip(),N!=="div"&&Q!==0&&j.iushrn(Q),{div:H||null,mod:j}},w.prototype.divmod=function(M,N,Q){if(b(!M.isZero()),this.isZero())return{div:new w(0),mod:new w(0)};var j,ne,J;return this.negative!==0&&M.negative===0?(J=this.neg().divmod(M,N),N!=="mod"&&(j=J.div.neg()),N!=="div"&&(ne=J.mod.neg(),Q&&ne.negative!==0&&ne.iadd(M)),{div:j,mod:ne}):this.negative===0&&M.negative!==0?(J=this.divmod(M.neg(),N),N!=="mod"&&(j=J.div.neg()),{div:j,mod:J.mod}):this.negative&M.negative?(J=this.neg().divmod(M.neg(),N),N!=="div"&&(ne=J.mod.neg(),Q&&ne.negative!==0&&ne.isub(M)),{div:J.div,mod:ne}):M.length>this.length||this.cmp(M)<0?{div:new w(0),mod:this}:M.length===1?N==="div"?{div:this.divn(M.words[0]),mod:null}:N==="mod"?{div:null,mod:new w(this.modrn(M.words[0]))}:{div:this.divn(M.words[0]),mod:new w(this.modrn(M.words[0]))}:this._wordDiv(M,N)},w.prototype.div=function(M){return this.divmod(M,"div",!1).div},w.prototype.mod=function(M){return this.divmod(M,"mod",!1).mod},w.prototype.umod=function(M){return this.divmod(M,"mod",!0).mod},w.prototype.divRound=function(M){var N=this.divmod(M);if(N.mod.isZero())return N.div;var Q=N.div.negative!==0?N.mod.isub(M):N.mod,j=M.ushrn(1),ne=M.andln(1),J=Q.cmp(j);return J<0||ne===1&&J===0?N.div:N.div.negative!==0?N.div.isubn(1):N.div.iaddn(1)},w.prototype.modrn=function(M){var N=M<0;N&&(M=-M),b(M<=67108863);for(var Q=(1<<26)%M,j=0,ne=this.length-1;ne>=0;ne--)j=(Q*j+(this.words[ne]|0))%M;return N?-j:j},w.prototype.modn=function(M){return this.modrn(M)},w.prototype.idivn=function(M){var N=M<0;N&&(M=-M),b(M<=67108863);for(var Q=0,j=this.length-1;j>=0;j--){var ne=(this.words[j]|0)+Q*67108864;this.words[j]=ne/M|0,Q=ne%M}return this._strip(),N?this.ineg():this},w.prototype.divn=function(M){return this.clone().idivn(M)},w.prototype.egcd=function(M){b(M.negative===0),b(!M.isZero());var N=this,Q=M.clone();N.negative!==0?N=N.umod(M):N=N.clone();for(var j=new w(1),ne=new w(0),J=new w(0),q=new w(1),re=0;N.isEven()&&Q.isEven();)N.iushrn(1),Q.iushrn(1),++re;for(var H=Q.clone(),he=N.clone();!N.isZero();){for(var Oe=0,Ne=1;!(N.words[0]&Ne)&&Oe<26;++Oe,Ne<<=1);if(Oe>0)for(N.iushrn(Oe);Oe-- >0;)(j.isOdd()||ne.isOdd())&&(j.iadd(H),ne.isub(he)),j.iushrn(1),ne.iushrn(1);for(var Ae=0,le=1;!(Q.words[0]&le)&&Ae<26;++Ae,le<<=1);if(Ae>0)for(Q.iushrn(Ae);Ae-- >0;)(J.isOdd()||q.isOdd())&&(J.iadd(H),q.isub(he)),J.iushrn(1),q.iushrn(1);N.cmp(Q)>=0?(N.isub(Q),j.isub(J),ne.isub(q)):(Q.isub(N),J.isub(j),q.isub(ne))}return{a:J,b:q,gcd:Q.iushln(re)}},w.prototype._invmp=function(M){b(M.negative===0),b(!M.isZero());var N=this,Q=M.clone();N.negative!==0?N=N.umod(M):N=N.clone();for(var j=new w(1),ne=new w(0),J=Q.clone();N.cmpn(1)>0&&Q.cmpn(1)>0;){for(var q=0,re=1;!(N.words[0]&re)&&q<26;++q,re<<=1);if(q>0)for(N.iushrn(q);q-- >0;)j.isOdd()&&j.iadd(J),j.iushrn(1);for(var H=0,he=1;!(Q.words[0]&he)&&H<26;++H,he<<=1);if(H>0)for(Q.iushrn(H);H-- >0;)ne.isOdd()&&ne.iadd(J),ne.iushrn(1);N.cmp(Q)>=0?(N.isub(Q),j.isub(ne)):(Q.isub(N),ne.isub(j))}var Oe;return N.cmpn(1)===0?Oe=j:Oe=ne,Oe.cmpn(0)<0&&Oe.iadd(M),Oe},w.prototype.gcd=function(M){if(this.isZero())return M.abs();if(M.isZero())return this.abs();var N=this.clone(),Q=M.clone();N.negative=0,Q.negative=0;for(var j=0;N.isEven()&&Q.isEven();j++)N.iushrn(1),Q.iushrn(1);do{for(;N.isEven();)N.iushrn(1);for(;Q.isEven();)Q.iushrn(1);var ne=N.cmp(Q);if(ne<0){var J=N;N=Q,Q=J}else if(ne===0||Q.cmpn(1)===0)break;N.isub(Q)}while(!0);return Q.iushln(j)},w.prototype.invm=function(M){return this.egcd(M).a.umod(M)},w.prototype.isEven=function(){return(this.words[0]&1)===0},w.prototype.isOdd=function(){return(this.words[0]&1)===1},w.prototype.andln=function(M){return this.words[0]&M},w.prototype.bincn=function(M){b(typeof M=="number");var N=M%26,Q=(M-N)/26,j=1<<N;if(this.length<=Q)return this._expand(Q+1),this.words[Q]|=j,this;for(var ne=j,J=Q;ne!==0&&J<this.length;J++){var q=this.words[J]|0;q+=ne,ne=q>>>26,q&=67108863,this.words[J]=q}return ne!==0&&(this.words[J]=ne,this.length++),this},w.prototype.isZero=function(){return this.length===1&&this.words[0]===0},w.prototype.cmpn=function(M){var N=M<0;if(this.negative!==0&&!N)return-1;if(this.negative===0&&N)return 1;this._strip();var Q;if(this.length>1)Q=1;else{N&&(M=-M),b(M<=67108863,"Number is too big");var j=this.words[0]|0;Q=j===M?0:j<M?-1:1}return this.negative!==0?-Q|0:Q},w.prototype.cmp=function(M){if(this.negative!==0&&M.negative===0)return-1;if(this.negative===0&&M.negative!==0)return 1;var N=this.ucmp(M);return this.negative!==0?-N|0:N},w.prototype.ucmp=function(M){if(this.length>M.length)return 1;if(this.length<M.length)return-1;for(var N=0,Q=this.length-1;Q>=0;Q--){var j=this.words[Q]|0,ne=M.words[Q]|0;if(j!==ne){j<ne?N=-1:j>ne&&(N=1);break}}return N},w.prototype.gtn=function(M){return this.cmpn(M)===1},w.prototype.gt=function(M){return this.cmp(M)===1},w.prototype.gten=function(M){return this.cmpn(M)>=0},w.prototype.gte=function(M){return this.cmp(M)>=0},w.prototype.ltn=function(M){return this.cmpn(M)===-1},w.prototype.lt=function(M){return this.cmp(M)===-1},w.prototype.lten=function(M){return this.cmpn(M)<=0},w.prototype.lte=function(M){return this.cmp(M)<=0},w.prototype.eqn=function(M){return this.cmpn(M)===0},w.prototype.eq=function(M){return this.cmp(M)===0},w.red=function(M){return new be(M)},w.prototype.toRed=function(M){return b(!this.red,"Already a number in reduction context"),b(this.negative===0,"red works only with positives"),M.convertTo(this)._forceRed(M)},w.prototype.fromRed=function(){return b(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},w.prototype._forceRed=function(M){return this.red=M,this},w.prototype.forceRed=function(M){return b(!this.red,"Already a number in reduction context"),this._forceRed(M)},w.prototype.redAdd=function(M){return b(this.red,"redAdd works only with red numbers"),this.red.add(this,M)},w.prototype.redIAdd=function(M){return b(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,M)},w.prototype.redSub=function(M){return b(this.red,"redSub works only with red numbers"),this.red.sub(this,M)},w.prototype.redISub=function(M){return b(this.red,"redISub works only with red numbers"),this.red.isub(this,M)},w.prototype.redShl=function(M){return b(this.red,"redShl works only with red numbers"),this.red.shl(this,M)},w.prototype.redMul=function(M){return b(this.red,"redMul works only with red numbers"),this.red._verify2(this,M),this.red.mul(this,M)},w.prototype.redIMul=function(M){return b(this.red,"redMul works only with red numbers"),this.red._verify2(this,M),this.red.imul(this,M)},w.prototype.redSqr=function(){return b(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},w.prototype.redISqr=function(){return b(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},w.prototype.redSqrt=function(){return b(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},w.prototype.redInvm=function(){return b(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},w.prototype.redNeg=function(){return b(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},w.prototype.redPow=function(M){return b(this.red&&!M.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,M)};var Se={k256:null,p224:null,p192:null,p25519:null};function ve(F,M){this.name=F,this.p=new w(M,16),this.n=this.p.bitLength(),this.k=new w(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}ve.prototype._tmp=function(){var M=new w(null);return M.words=new Array(Math.ceil(this.n/13)),M},ve.prototype.ireduce=function(M){var N=M,Q;do this.split(N,this.tmp),N=this.imulK(N),N=N.iadd(this.tmp),Q=N.bitLength();while(Q>this.n);var j=Q<this.n?-1:N.ucmp(this.p);return j===0?(N.words[0]=0,N.length=1):j>0?N.isub(this.p):N.strip!==void 0?N.strip():N._strip(),N},ve.prototype.split=function(M,N){M.iushrn(this.n,0,N)},ve.prototype.imulK=function(M){return M.imul(this.k)};function Pe(){ve.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}v(Pe,ve),Pe.prototype.split=function(M,N){for(var Q=4194303,j=Math.min(M.length,9),ne=0;ne<j;ne++)N.words[ne]=M.words[ne];if(N.length=j,M.length<=9){M.words[0]=0,M.length=1;return}var J=M.words[9];for(N.words[N.length++]=J&Q,ne=10;ne<M.length;ne++){var q=M.words[ne]|0;M.words[ne-10]=(q&Q)<<4|J>>>22,J=q}J>>>=22,M.words[ne-10]=J,J===0&&M.length>10?M.length-=10:M.length-=9},Pe.prototype.imulK=function(M){M.words[M.length]=0,M.words[M.length+1]=0,M.length+=2;for(var N=0,Q=0;Q<M.length;Q++){var j=M.words[Q]|0;N+=j*977,M.words[Q]=N&67108863,N=j*64+(N/67108864|0)}return M.words[M.length-1]===0&&(M.length--,M.words[M.length-1]===0&&M.length--),M};function Ie(){ve.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}v(Ie,ve);function Ee(){ve.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}v(Ee,ve);function De(){ve.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}v(De,ve),De.prototype.imulK=function(M){for(var N=0,Q=0;Q<M.length;Q++){var j=(M.words[Q]|0)*19+N,ne=j&67108863;j>>>=26,M.words[Q]=ne,N=j}return N!==0&&(M.words[M.length++]=N),M},w._prime=function(M){if(Se[M])return Se[M];var N;if(M==="k256")N=new Pe;else if(M==="p224")N=new Ie;else if(M==="p192")N=new Ee;else if(M==="p25519")N=new De;else throw new Error("Unknown prime "+M);return Se[M]=N,N};function be(F){if(typeof F=="string"){var M=w._prime(F);this.m=M.p,this.prime=M}else b(F.gtn(1),"modulus must be greater than 1"),this.m=F,this.prime=null}be.prototype._verify1=function(M){b(M.negative===0,"red works only with positives"),b(M.red,"red works only with red numbers")},be.prototype._verify2=function(M,N){b((M.negative|N.negative)===0,"red works only with positives"),b(M.red&&M.red===N.red,"red works only with red numbers")},be.prototype.imod=function(M){return this.prime?this.prime.ireduce(M)._forceRed(this):(T(M,M.umod(this.m)._forceRed(this)),M)},be.prototype.neg=function(M){return M.isZero()?M.clone():this.m.sub(M)._forceRed(this)},be.prototype.add=function(M,N){this._verify2(M,N);var Q=M.add(N);return Q.cmp(this.m)>=0&&Q.isub(this.m),Q._forceRed(this)},be.prototype.iadd=function(M,N){this._verify2(M,N);var Q=M.iadd(N);return Q.cmp(this.m)>=0&&Q.isub(this.m),Q},be.prototype.sub=function(M,N){this._verify2(M,N);var Q=M.sub(N);return Q.cmpn(0)<0&&Q.iadd(this.m),Q._forceRed(this)},be.prototype.isub=function(M,N){this._verify2(M,N);var Q=M.isub(N);return Q.cmpn(0)<0&&Q.iadd(this.m),Q},be.prototype.shl=function(M,N){return this._verify1(M),this.imod(M.ushln(N))},be.prototype.imul=function(M,N){return this._verify2(M,N),this.imod(M.imul(N))},be.prototype.mul=function(M,N){return this._verify2(M,N),this.imod(M.mul(N))},be.prototype.isqr=function(M){return this.imul(M,M.clone())},be.prototype.sqr=function(M){return this.mul(M,M)},be.prototype.sqrt=function(M){if(M.isZero())return M.clone();var N=this.m.andln(3);if(b(N%2===1),N===3){var Q=this.m.add(new w(1)).iushrn(2);return this.pow(M,Q)}for(var j=this.m.subn(1),ne=0;!j.isZero()&&j.andln(1)===0;)ne++,j.iushrn(1);b(!j.isZero());var J=new w(1).toRed(this),q=J.redNeg(),re=this.m.subn(1).iushrn(1),H=this.m.bitLength();for(H=new w(2*H*H).toRed(this);this.pow(H,re).cmp(q)!==0;)H.redIAdd(q);for(var he=this.pow(H,j),Oe=this.pow(M,j.addn(1).iushrn(1)),Ne=this.pow(M,j),Ae=ne;Ne.cmp(J)!==0;){for(var le=Ne,me=0;le.cmp(J)!==0;me++)le=le.redSqr();b(me<Ae);var Me=this.pow(he,new w(1).iushln(Ae-me-1));Oe=Oe.redMul(Me),he=Me.redSqr(),Ne=Ne.redMul(he),Ae=me}return Oe},be.prototype.invm=function(M){var N=M._invmp(this.m);return N.negative!==0?(N.negative=0,this.imod(N).redNeg()):this.imod(N)},be.prototype.pow=function(M,N){if(N.isZero())return new w(1).toRed(this);if(N.cmpn(1)===0)return M.clone();var Q=4,j=new Array(1<<Q);j[0]=new w(1).toRed(this),j[1]=M;for(var ne=2;ne<j.length;ne++)j[ne]=this.mul(j[ne-1],M);var J=j[0],q=0,re=0,H=N.bitLength()%26;for(H===0&&(H=26),ne=N.length-1;ne>=0;ne--){for(var he=N.words[ne],Oe=H-1;Oe>=0;Oe--){var Ne=he>>Oe&1;if(J!==j[0]&&(J=this.sqr(J)),Ne===0&&q===0){re=0;continue}q<<=1,q|=Ne,re++,!(re!==Q&&(ne!==0||Oe!==0))&&(J=this.mul(J,j[q]),re=0,q=0)}H=26}return J},be.prototype.convertTo=function(M){var N=M.umod(this.m);return N===M?N.clone():N},be.prototype.convertFrom=function(M){var N=M.clone();return N.red=null,N},w.mont=function(M){return new B(M)};function B(F){be.call(this,F),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new w(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}v(B,be),B.prototype.convertTo=function(M){return this.imod(M.ushln(this.shift))},B.prototype.convertFrom=function(M){var N=this.imod(M.mul(this.rinv));return N.red=null,N},B.prototype.imul=function(M,N){if(M.isZero()||N.isZero())return M.words[0]=0,M.length=1,M;var Q=M.imul(N),j=Q.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),ne=Q.isub(j).iushrn(this.shift),J=ne;return ne.cmp(this.m)>=0?J=ne.isub(this.m):ne.cmpn(0)<0&&(J=ne.iadd(this.m)),J._forceRed(this)},B.prototype.mul=function(M,N){if(M.isZero()||N.isZero())return new w(0)._forceRed(this);var Q=M.mul(N),j=Q.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),ne=Q.isub(j).iushrn(this.shift),J=ne;return ne.cmp(this.m)>=0?J=ne.isub(this.m):ne.cmpn(0)<0&&(J=ne.iadd(this.m)),J._forceRed(this)},B.prototype.invm=function(M){var N=this.imod(M._invmp(this.m).mul(this.r2));return N._forceRed(this)}})(y,commonjsGlobal)})(bn);var bnExports=bn.exports,BN$a=bnExports,randomBytes$1=browserExports,Buffer$7=safeBufferExports$1.Buffer;function getr(y){var u=y.modulus.byteLength(),h;do h=new BN$a(randomBytes$1(u));while(h.cmp(y.modulus)>=0||!h.umod(y.prime1)||!h.umod(y.prime2));return h}function blind(y){var u=getr(y),h=u.toRed(BN$a.mont(y.modulus)).redPow(new BN$a(y.publicExponent)).fromRed();return{blinder:h,unblinder:u.invm(y.modulus)}}function crt$2(y,u){var h=blind(u),b=u.modulus.byteLength(),v=new BN$a(y).mul(h.blinder).umod(u.modulus),w=v.toRed(BN$a.mont(u.prime1)),_=v.toRed(BN$a.mont(u.prime2)),E=u.coefficient,S=u.prime1,x=u.prime2,T=w.redPow(u.exponent1).fromRed(),C=_.redPow(u.exponent2).fromRed(),O=T.isub(C).imul(E).umod(S).imul(x);return C.iadd(O).imul(h.unblinder).umod(u.modulus).toArrayLike(Buffer$7,"be",b)}crt$2.getr=getr;var browserifyRsa=crt$2,elliptic={};const name="elliptic",version$3="6.5.7",description="EC cryptography",main="lib/elliptic.js",files=["lib"],scripts={lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository={type:"git",url:"git@github.com:indutny/elliptic"},keywords=["EC","Elliptic","curve","Cryptography"],author="Fedor Indutny <fedor@indutny.com>",license="MIT",bugs={url:"https://github.com/indutny/elliptic/issues"},homepage="https://github.com/indutny/elliptic",devDependencies={brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},dependencies={"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"},require$$0={name,version:version$3,description,main,files,scripts,repository,keywords,author,license,bugs,homepage,devDependencies,dependencies};var utils$m={},utils$l={};(function(y){var u=y;function h(w,_){if(Array.isArray(w))return w.slice();if(!w)return[];var E=[];if(typeof w!="string"){for(var S=0;S<w.length;S++)E[S]=w[S]|0;return E}if(_==="hex"){w=w.replace(/[^a-z0-9]+/ig,""),w.length%2!==0&&(w="0"+w);for(var S=0;S<w.length;S+=2)E.push(parseInt(w[S]+w[S+1],16))}else for(var S=0;S<w.length;S++){var x=w.charCodeAt(S),T=x>>8,C=x&255;T?E.push(T,C):E.push(C)}return E}u.toArray=h;function b(w){return w.length===1?"0"+w:w}u.zero2=b;function v(w){for(var _="",E=0;E<w.length;E++)_+=b(w[E].toString(16));return _}u.toHex=v,u.encode=function(_,E){return E==="hex"?v(_):_}})(utils$l);(function(y){var u=y,h=bnExports$1,b=minimalisticAssert,v=utils$l;u.assert=b,u.toArray=v.toArray,u.zero2=v.zero2,u.toHex=v.toHex,u.encode=v.encode;function w(T,C,O){var D=new Array(Math.max(T.bitLength(),O)+1),U;for(U=0;U<D.length;U+=1)D[U]=0;var te=1<<C+1,X=T.clone();for(U=0;U<D.length;U++){var ie,ee=X.andln(te-1);X.isOdd()?(ee>(te>>1)-1?ie=(te>>1)-ee:ie=ee,X.isubn(ie)):ie=0,D[U]=ie,X.iushrn(1)}return D}u.getNAF=w;function _(T,C){var O=[[],[]];T=T.clone(),C=C.clone();for(var D=0,U=0,te;T.cmpn(-D)>0||C.cmpn(-U)>0;){var X=T.andln(3)+D&3,ie=C.andln(3)+U&3;X===3&&(X=-1),ie===3&&(ie=-1);var ee;X&1?(te=T.andln(7)+D&7,(te===3||te===5)&&ie===2?ee=-X:ee=X):ee=0,O[0].push(ee);var ae;ie&1?(te=C.andln(7)+U&7,(te===3||te===5)&&X===2?ae=-ie:ae=ie):ae=0,O[1].push(ae),2*D===ee+1&&(D=1-D),2*U===ae+1&&(U=1-U),T.iushrn(1),C.iushrn(1)}return O}u.getJSF=_;function E(T,C,O){var D="_"+C;T.prototype[C]=function(){return this[D]!==void 0?this[D]:this[D]=O.call(this)}}u.cachedProperty=E;function S(T){return typeof T=="string"?u.toArray(T,"hex"):T}u.parseBytes=S;function x(T){return new h(T,"hex","le")}u.intFromLE=x})(utils$m);var curve={},BN$9=bnExports$1,utils$k=utils$m,getNAF=utils$k.getNAF,getJSF=utils$k.getJSF,assert$d=utils$k.assert;function BaseCurve(y,u){this.type=y,this.p=new BN$9(u.p,16),this.red=u.prime?BN$9.red(u.prime):BN$9.mont(this.p),this.zero=new BN$9(0).toRed(this.red),this.one=new BN$9(1).toRed(this.red),this.two=new BN$9(2).toRed(this.red),this.n=u.n&&new BN$9(u.n,16),this.g=u.g&&this.pointFromJSON(u.g,u.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var h=this.n&&this.p.div(this.n);!h||h.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var base$1=BaseCurve;BaseCurve.prototype.point=function(){throw new Error("Not implemented")};BaseCurve.prototype.validate=function(){throw new Error("Not implemented")};BaseCurve.prototype._fixedNafMul=function(u,h){assert$d(u.precomputed);var b=u._getDoubles(),v=getNAF(h,1,this._bitLength),w=(1<<b.step+1)-(b.step%2===0?2:1);w/=3;var _=[],E,S;for(E=0;E<v.length;E+=b.step){S=0;for(var x=E+b.step-1;x>=E;x--)S=(S<<1)+v[x];_.push(S)}for(var T=this.jpoint(null,null,null),C=this.jpoint(null,null,null),O=w;O>0;O--){for(E=0;E<_.length;E++)S=_[E],S===O?C=C.mixedAdd(b.points[E]):S===-O&&(C=C.mixedAdd(b.points[E].neg()));T=T.add(C)}return T.toP()};BaseCurve.prototype._wnafMul=function(u,h){var b=4,v=u._getNAFPoints(b);b=v.wnd;for(var w=v.points,_=getNAF(h,b,this._bitLength),E=this.jpoint(null,null,null),S=_.length-1;S>=0;S--){for(var x=0;S>=0&&_[S]===0;S--)x++;if(S>=0&&x++,E=E.dblp(x),S<0)break;var T=_[S];assert$d(T!==0),u.type==="affine"?T>0?E=E.mixedAdd(w[T-1>>1]):E=E.mixedAdd(w[-T-1>>1].neg()):T>0?E=E.add(w[T-1>>1]):E=E.add(w[-T-1>>1].neg())}return u.type==="affine"?E.toP():E};BaseCurve.prototype._wnafMulAdd=function(u,h,b,v,w){var _=this._wnafT1,E=this._wnafT2,S=this._wnafT3,x=0,T,C,O;for(T=0;T<v;T++){O=h[T];var D=O._getNAFPoints(u);_[T]=D.wnd,E[T]=D.points}for(T=v-1;T>=1;T-=2){var U=T-1,te=T;if(_[U]!==1||_[te]!==1){S[U]=getNAF(b[U],_[U],this._bitLength),S[te]=getNAF(b[te],_[te],this._bitLength),x=Math.max(S[U].length,x),x=Math.max(S[te].length,x);continue}var X=[h[U],null,null,h[te]];h[U].y.cmp(h[te].y)===0?(X[1]=h[U].add(h[te]),X[2]=h[U].toJ().mixedAdd(h[te].neg())):h[U].y.cmp(h[te].y.redNeg())===0?(X[1]=h[U].toJ().mixedAdd(h[te]),X[2]=h[U].add(h[te].neg())):(X[1]=h[U].toJ().mixedAdd(h[te]),X[2]=h[U].toJ().mixedAdd(h[te].neg()));var ie=[-3,-1,-5,-7,0,7,5,1,3],ee=getJSF(b[U],b[te]);for(x=Math.max(ee[0].length,x),S[U]=new Array(x),S[te]=new Array(x),C=0;C<x;C++){var ae=ee[0][C]|0,de=ee[1][C]|0;S[U][C]=ie[(ae+1)*3+(de+1)],S[te][C]=0,E[U]=X}}var Se=this.jpoint(null,null,null),ve=this._wnafT4;for(T=x;T>=0;T--){for(var Pe=0;T>=0;){var Ie=!0;for(C=0;C<v;C++)ve[C]=S[C][T]|0,ve[C]!==0&&(Ie=!1);if(!Ie)break;Pe++,T--}if(T>=0&&Pe++,Se=Se.dblp(Pe),T<0)break;for(C=0;C<v;C++){var Ee=ve[C];Ee!==0&&(Ee>0?O=E[C][Ee-1>>1]:Ee<0&&(O=E[C][-Ee-1>>1].neg()),O.type==="affine"?Se=Se.mixedAdd(O):Se=Se.add(O))}}for(T=0;T<v;T++)E[T]=null;return w?Se:Se.toP()};function BasePoint(y,u){this.curve=y,this.type=u,this.precomputed=null}BaseCurve.BasePoint=BasePoint;BasePoint.prototype.eq=function(){throw new Error("Not implemented")};BasePoint.prototype.validate=function(){return this.curve.validate(this)};BaseCurve.prototype.decodePoint=function(u,h){u=utils$k.toArray(u,h);var b=this.p.byteLength();if((u[0]===4||u[0]===6||u[0]===7)&&u.length-1===2*b){u[0]===6?assert$d(u[u.length-1]%2===0):u[0]===7&&assert$d(u[u.length-1]%2===1);var v=this.point(u.slice(1,1+b),u.slice(1+b,1+2*b));return v}else if((u[0]===2||u[0]===3)&&u.length-1===b)return this.pointFromX(u.slice(1,1+b),u[0]===3);throw new Error("Unknown point format")};BasePoint.prototype.encodeCompressed=function(u){return this.encode(u,!0)};BasePoint.prototype._encode=function(u){var h=this.curve.p.byteLength(),b=this.getX().toArray("be",h);return u?[this.getY().isEven()?2:3].concat(b):[4].concat(b,this.getY().toArray("be",h))};BasePoint.prototype.encode=function(u,h){return utils$k.encode(this._encode(h),u)};BasePoint.prototype.precompute=function(u){if(this.precomputed)return this;var h={doubles:null,naf:null,beta:null};return h.naf=this._getNAFPoints(8),h.doubles=this._getDoubles(4,u),h.beta=this._getBeta(),this.precomputed=h,this};BasePoint.prototype._hasDoubles=function(u){if(!this.precomputed)return!1;var h=this.precomputed.doubles;return h?h.points.length>=Math.ceil((u.bitLength()+1)/h.step):!1};BasePoint.prototype._getDoubles=function(u,h){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var b=[this],v=this,w=0;w<h;w+=u){for(var _=0;_<u;_++)v=v.dbl();b.push(v)}return{step:u,points:b}};BasePoint.prototype._getNAFPoints=function(u){if(this.precomputed&&this.precomputed.naf)return this.precomputed.naf;for(var h=[this],b=(1<<u)-1,v=b===1?null:this.dbl(),w=1;w<b;w++)h[w]=h[w-1].add(v);return{wnd:u,points:h}};BasePoint.prototype._getBeta=function(){return null};BasePoint.prototype.dblp=function(u){for(var h=this,b=0;b<u;b++)h=h.dbl();return h};var utils$j=utils$m,BN$8=bnExports$1,inherits$4=inherits_browserExports,Base$2=base$1,assert$c=utils$j.assert;function ShortCurve(y){Base$2.call(this,"short",y),this.a=new BN$8(y.a,16).toRed(this.red),this.b=new BN$8(y.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=this.a.fromRed().cmpn(0)===0,this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0,this.endo=this._getEndomorphism(y),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}inherits$4(ShortCurve,Base$2);var short=ShortCurve;ShortCurve.prototype._getEndomorphism=function(u){if(!(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)){var h,b;if(u.beta)h=new BN$8(u.beta,16).toRed(this.red);else{var v=this._getEndoRoots(this.p);h=v[0].cmp(v[1])<0?v[0]:v[1],h=h.toRed(this.red)}if(u.lambda)b=new BN$8(u.lambda,16);else{var w=this._getEndoRoots(this.n);this.g.mul(w[0]).x.cmp(this.g.x.redMul(h))===0?b=w[0]:(b=w[1],assert$c(this.g.mul(b).x.cmp(this.g.x.redMul(h))===0))}var _;return u.basis?_=u.basis.map(function(E){return{a:new BN$8(E.a,16),b:new BN$8(E.b,16)}}):_=this._getEndoBasis(b),{beta:h,lambda:b,basis:_}}};ShortCurve.prototype._getEndoRoots=function(u){var h=u===this.p?this.red:BN$8.mont(u),b=new BN$8(2).toRed(h).redInvm(),v=b.redNeg(),w=new BN$8(3).toRed(h).redNeg().redSqrt().redMul(b),_=v.redAdd(w).fromRed(),E=v.redSub(w).fromRed();return[_,E]};ShortCurve.prototype._getEndoBasis=function(u){for(var h=this.n.ushrn(Math.floor(this.n.bitLength()/2)),b=u,v=this.n.clone(),w=new BN$8(1),_=new BN$8(0),E=new BN$8(0),S=new BN$8(1),x,T,C,O,D,U,te,X=0,ie,ee;b.cmpn(0)!==0;){var ae=v.div(b);ie=v.sub(ae.mul(b)),ee=E.sub(ae.mul(w));var de=S.sub(ae.mul(_));if(!C&&ie.cmp(h)<0)x=te.neg(),T=w,C=ie.neg(),O=ee;else if(C&&++X===2)break;te=ie,v=b,b=ie,E=w,w=ee,S=_,_=de}D=ie.neg(),U=ee;var Se=C.sqr().add(O.sqr()),ve=D.sqr().add(U.sqr());return ve.cmp(Se)>=0&&(D=x,U=T),C.negative&&(C=C.neg(),O=O.neg()),D.negative&&(D=D.neg(),U=U.neg()),[{a:C,b:O},{a:D,b:U}]};ShortCurve.prototype._endoSplit=function(u){var h=this.endo.basis,b=h[0],v=h[1],w=v.b.mul(u).divRound(this.n),_=b.b.neg().mul(u).divRound(this.n),E=w.mul(b.a),S=_.mul(v.a),x=w.mul(b.b),T=_.mul(v.b),C=u.sub(E).sub(S),O=x.add(T).neg();return{k1:C,k2:O}};ShortCurve.prototype.pointFromX=function(u,h){u=new BN$8(u,16),u.red||(u=u.toRed(this.red));var b=u.redSqr().redMul(u).redIAdd(u.redMul(this.a)).redIAdd(this.b),v=b.redSqrt();if(v.redSqr().redSub(b).cmp(this.zero)!==0)throw new Error("invalid point");var w=v.fromRed().isOdd();return(h&&!w||!h&&w)&&(v=v.redNeg()),this.point(u,v)};ShortCurve.prototype.validate=function(u){if(u.inf)return!0;var h=u.x,b=u.y,v=this.a.redMul(h),w=h.redSqr().redMul(h).redIAdd(v).redIAdd(this.b);return b.redSqr().redISub(w).cmpn(0)===0};ShortCurve.prototype._endoWnafMulAdd=function(u,h,b){for(var v=this._endoWnafT1,w=this._endoWnafT2,_=0;_<u.length;_++){var E=this._endoSplit(h[_]),S=u[_],x=S._getBeta();E.k1.negative&&(E.k1.ineg(),S=S.neg(!0)),E.k2.negative&&(E.k2.ineg(),x=x.neg(!0)),v[_*2]=S,v[_*2+1]=x,w[_*2]=E.k1,w[_*2+1]=E.k2}for(var T=this._wnafMulAdd(1,v,w,_*2,b),C=0;C<_*2;C++)v[C]=null,w[C]=null;return T};function Point$3(y,u,h,b){Base$2.BasePoint.call(this,y,"affine"),u===null&&h===null?(this.x=null,this.y=null,this.inf=!0):(this.x=new BN$8(u,16),this.y=new BN$8(h,16),b&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}inherits$4(Point$3,Base$2.BasePoint);ShortCurve.prototype.point=function(u,h,b){return new Point$3(this,u,h,b)};ShortCurve.prototype.pointFromJSON=function(u,h){return Point$3.fromJSON(this,u,h)};Point$3.prototype._getBeta=function(){if(this.curve.endo){var u=this.precomputed;if(u&&u.beta)return u.beta;var h=this.curve.point(this.x.redMul(this.curve.endo.beta),this.y);if(u){var b=this.curve,v=function(w){return b.point(w.x.redMul(b.endo.beta),w.y)};u.beta=h,h.precomputed={beta:null,naf:u.naf&&{wnd:u.naf.wnd,points:u.naf.points.map(v)},doubles:u.doubles&&{step:u.doubles.step,points:u.doubles.points.map(v)}}}return h}};Point$3.prototype.toJSON=function(){return this.precomputed?[this.x,this.y,this.precomputed&&{doubles:this.precomputed.doubles&&{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf&&{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}]:[this.x,this.y]};Point$3.fromJSON=function(u,h,b){typeof h=="string"&&(h=JSON.parse(h));var v=u.point(h[0],h[1],b);if(!h[2])return v;function w(E){return u.point(E[0],E[1],b)}var _=h[2];return v.precomputed={beta:null,doubles:_.doubles&&{step:_.doubles.step,points:[v].concat(_.doubles.points.map(w))},naf:_.naf&&{wnd:_.naf.wnd,points:[v].concat(_.naf.points.map(w))}},v};Point$3.prototype.inspect=function(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+">"};Point$3.prototype.isInfinity=function(){return this.inf};Point$3.prototype.add=function(u){if(this.inf)return u;if(u.inf)return this;if(this.eq(u))return this.dbl();if(this.neg().eq(u))return this.curve.point(null,null);if(this.x.cmp(u.x)===0)return this.curve.point(null,null);var h=this.y.redSub(u.y);h.cmpn(0)!==0&&(h=h.redMul(this.x.redSub(u.x).redInvm()));var b=h.redSqr().redISub(this.x).redISub(u.x),v=h.redMul(this.x.redSub(b)).redISub(this.y);return this.curve.point(b,v)};Point$3.prototype.dbl=function(){if(this.inf)return this;var u=this.y.redAdd(this.y);if(u.cmpn(0)===0)return this.curve.point(null,null);var h=this.curve.a,b=this.x.redSqr(),v=u.redInvm(),w=b.redAdd(b).redIAdd(b).redIAdd(h).redMul(v),_=w.redSqr().redISub(this.x.redAdd(this.x)),E=w.redMul(this.x.redSub(_)).redISub(this.y);return this.curve.point(_,E)};Point$3.prototype.getX=function(){return this.x.fromRed()};Point$3.prototype.getY=function(){return this.y.fromRed()};Point$3.prototype.mul=function(u){return u=new BN$8(u,16),this.isInfinity()?this:this._hasDoubles(u)?this.curve._fixedNafMul(this,u):this.curve.endo?this.curve._endoWnafMulAdd([this],[u]):this.curve._wnafMul(this,u)};Point$3.prototype.mulAdd=function(u,h,b){var v=[this,h],w=[u,b];return this.curve.endo?this.curve._endoWnafMulAdd(v,w):this.curve._wnafMulAdd(1,v,w,2)};Point$3.prototype.jmulAdd=function(u,h,b){var v=[this,h],w=[u,b];return this.curve.endo?this.curve._endoWnafMulAdd(v,w,!0):this.curve._wnafMulAdd(1,v,w,2,!0)};Point$3.prototype.eq=function(u){return this===u||this.inf===u.inf&&(this.inf||this.x.cmp(u.x)===0&&this.y.cmp(u.y)===0)};Point$3.prototype.neg=function(u){if(this.inf)return this;var h=this.curve.point(this.x,this.y.redNeg());if(u&&this.precomputed){var b=this.precomputed,v=function(w){return w.neg()};h.precomputed={naf:b.naf&&{wnd:b.naf.wnd,points:b.naf.points.map(v)},doubles:b.doubles&&{step:b.doubles.step,points:b.doubles.points.map(v)}}}return h};Point$3.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var u=this.curve.jpoint(this.x,this.y,this.curve.one);return u};function JPoint(y,u,h,b){Base$2.BasePoint.call(this,y,"jacobian"),u===null&&h===null&&b===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new BN$8(0)):(this.x=new BN$8(u,16),this.y=new BN$8(h,16),this.z=new BN$8(b,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}inherits$4(JPoint,Base$2.BasePoint);ShortCurve.prototype.jpoint=function(u,h,b){return new JPoint(this,u,h,b)};JPoint.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var u=this.z.redInvm(),h=u.redSqr(),b=this.x.redMul(h),v=this.y.redMul(h).redMul(u);return this.curve.point(b,v)};JPoint.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)};JPoint.prototype.add=function(u){if(this.isInfinity())return u;if(u.isInfinity())return this;var h=u.z.redSqr(),b=this.z.redSqr(),v=this.x.redMul(h),w=u.x.redMul(b),_=this.y.redMul(h.redMul(u.z)),E=u.y.redMul(b.redMul(this.z)),S=v.redSub(w),x=_.redSub(E);if(S.cmpn(0)===0)return x.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var T=S.redSqr(),C=T.redMul(S),O=v.redMul(T),D=x.redSqr().redIAdd(C).redISub(O).redISub(O),U=x.redMul(O.redISub(D)).redISub(_.redMul(C)),te=this.z.redMul(u.z).redMul(S);return this.curve.jpoint(D,U,te)};JPoint.prototype.mixedAdd=function(u){if(this.isInfinity())return u.toJ();if(u.isInfinity())return this;var h=this.z.redSqr(),b=this.x,v=u.x.redMul(h),w=this.y,_=u.y.redMul(h).redMul(this.z),E=b.redSub(v),S=w.redSub(_);if(E.cmpn(0)===0)return S.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var x=E.redSqr(),T=x.redMul(E),C=b.redMul(x),O=S.redSqr().redIAdd(T).redISub(C).redISub(C),D=S.redMul(C.redISub(O)).redISub(w.redMul(T)),U=this.z.redMul(E);return this.curve.jpoint(O,D,U)};JPoint.prototype.dblp=function(u){if(u===0)return this;if(this.isInfinity())return this;if(!u)return this.dbl();var h;if(this.curve.zeroA||this.curve.threeA){var b=this;for(h=0;h<u;h++)b=b.dbl();return b}var v=this.curve.a,w=this.curve.tinv,_=this.x,E=this.y,S=this.z,x=S.redSqr().redSqr(),T=E.redAdd(E);for(h=0;h<u;h++){var C=_.redSqr(),O=T.redSqr(),D=O.redSqr(),U=C.redAdd(C).redIAdd(C).redIAdd(v.redMul(x)),te=_.redMul(O),X=U.redSqr().redISub(te.redAdd(te)),ie=te.redISub(X),ee=U.redMul(ie);ee=ee.redIAdd(ee).redISub(D);var ae=T.redMul(S);h+1<u&&(x=x.redMul(D)),_=X,S=ae,T=ee}return this.curve.jpoint(_,T.redMul(w),S)};JPoint.prototype.dbl=function(){return this.isInfinity()?this:this.curve.zeroA?this._zeroDbl():this.curve.threeA?this._threeDbl():this._dbl()};JPoint.prototype._zeroDbl=function(){var u,h,b;if(this.zOne){var v=this.x.redSqr(),w=this.y.redSqr(),_=w.redSqr(),E=this.x.redAdd(w).redSqr().redISub(v).redISub(_);E=E.redIAdd(E);var S=v.redAdd(v).redIAdd(v),x=S.redSqr().redISub(E).redISub(E),T=_.redIAdd(_);T=T.redIAdd(T),T=T.redIAdd(T),u=x,h=S.redMul(E.redISub(x)).redISub(T),b=this.y.redAdd(this.y)}else{var C=this.x.redSqr(),O=this.y.redSqr(),D=O.redSqr(),U=this.x.redAdd(O).redSqr().redISub(C).redISub(D);U=U.redIAdd(U);var te=C.redAdd(C).redIAdd(C),X=te.redSqr(),ie=D.redIAdd(D);ie=ie.redIAdd(ie),ie=ie.redIAdd(ie),u=X.redISub(U).redISub(U),h=te.redMul(U.redISub(u)).redISub(ie),b=this.y.redMul(this.z),b=b.redIAdd(b)}return this.curve.jpoint(u,h,b)};JPoint.prototype._threeDbl=function(){var u,h,b;if(this.zOne){var v=this.x.redSqr(),w=this.y.redSqr(),_=w.redSqr(),E=this.x.redAdd(w).redSqr().redISub(v).redISub(_);E=E.redIAdd(E);var S=v.redAdd(v).redIAdd(v).redIAdd(this.curve.a),x=S.redSqr().redISub(E).redISub(E);u=x;var T=_.redIAdd(_);T=T.redIAdd(T),T=T.redIAdd(T),h=S.redMul(E.redISub(x)).redISub(T),b=this.y.redAdd(this.y)}else{var C=this.z.redSqr(),O=this.y.redSqr(),D=this.x.redMul(O),U=this.x.redSub(C).redMul(this.x.redAdd(C));U=U.redAdd(U).redIAdd(U);var te=D.redIAdd(D);te=te.redIAdd(te);var X=te.redAdd(te);u=U.redSqr().redISub(X),b=this.y.redAdd(this.z).redSqr().redISub(O).redISub(C);var ie=O.redSqr();ie=ie.redIAdd(ie),ie=ie.redIAdd(ie),ie=ie.redIAdd(ie),h=U.redMul(te.redISub(u)).redISub(ie)}return this.curve.jpoint(u,h,b)};JPoint.prototype._dbl=function(){var u=this.curve.a,h=this.x,b=this.y,v=this.z,w=v.redSqr().redSqr(),_=h.redSqr(),E=b.redSqr(),S=_.redAdd(_).redIAdd(_).redIAdd(u.redMul(w)),x=h.redAdd(h);x=x.redIAdd(x);var T=x.redMul(E),C=S.redSqr().redISub(T.redAdd(T)),O=T.redISub(C),D=E.redSqr();D=D.redIAdd(D),D=D.redIAdd(D),D=D.redIAdd(D);var U=S.redMul(O).redISub(D),te=b.redAdd(b).redMul(v);return this.curve.jpoint(C,U,te)};JPoint.prototype.trpl=function(){if(!this.curve.zeroA)return this.dbl().add(this);var u=this.x.redSqr(),h=this.y.redSqr(),b=this.z.redSqr(),v=h.redSqr(),w=u.redAdd(u).redIAdd(u),_=w.redSqr(),E=this.x.redAdd(h).redSqr().redISub(u).redISub(v);E=E.redIAdd(E),E=E.redAdd(E).redIAdd(E),E=E.redISub(_);var S=E.redSqr(),x=v.redIAdd(v);x=x.redIAdd(x),x=x.redIAdd(x),x=x.redIAdd(x);var T=w.redIAdd(E).redSqr().redISub(_).redISub(S).redISub(x),C=h.redMul(T);C=C.redIAdd(C),C=C.redIAdd(C);var O=this.x.redMul(S).redISub(C);O=O.redIAdd(O),O=O.redIAdd(O);var D=this.y.redMul(T.redMul(x.redISub(T)).redISub(E.redMul(S)));D=D.redIAdd(D),D=D.redIAdd(D),D=D.redIAdd(D);var U=this.z.redAdd(E).redSqr().redISub(b).redISub(S);return this.curve.jpoint(O,D,U)};JPoint.prototype.mul=function(u,h){return u=new BN$8(u,h),this.curve._wnafMul(this,u)};JPoint.prototype.eq=function(u){if(u.type==="affine")return this.eq(u.toJ());if(this===u)return!0;var h=this.z.redSqr(),b=u.z.redSqr();if(this.x.redMul(b).redISub(u.x.redMul(h)).cmpn(0)!==0)return!1;var v=h.redMul(this.z),w=b.redMul(u.z);return this.y.redMul(w).redISub(u.y.redMul(v)).cmpn(0)===0};JPoint.prototype.eqXToP=function(u){var h=this.z.redSqr(),b=u.toRed(this.curve.red).redMul(h);if(this.x.cmp(b)===0)return!0;for(var v=u.clone(),w=this.curve.redN.redMul(h);;){if(v.iadd(this.curve.n),v.cmp(this.curve.p)>=0)return!1;if(b.redIAdd(w),this.x.cmp(b)===0)return!0}};JPoint.prototype.inspect=function(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"};JPoint.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var BN$7=bnExports$1,inherits$3=inherits_browserExports,Base$1=base$1,utils$i=utils$m;function MontCurve(y){Base$1.call(this,"mont",y),this.a=new BN$7(y.a,16).toRed(this.red),this.b=new BN$7(y.b,16).toRed(this.red),this.i4=new BN$7(4).toRed(this.red).redInvm(),this.two=new BN$7(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}inherits$3(MontCurve,Base$1);var mont=MontCurve;MontCurve.prototype.validate=function(u){var h=u.normalize().x,b=h.redSqr(),v=b.redMul(h).redAdd(b.redMul(this.a)).redAdd(h),w=v.redSqrt();return w.redSqr().cmp(v)===0};function Point$2(y,u,h){Base$1.BasePoint.call(this,y,"projective"),u===null&&h===null?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new BN$7(u,16),this.z=new BN$7(h,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}inherits$3(Point$2,Base$1.BasePoint);MontCurve.prototype.decodePoint=function(u,h){return this.point(utils$i.toArray(u,h),1)};MontCurve.prototype.point=function(u,h){return new Point$2(this,u,h)};MontCurve.prototype.pointFromJSON=function(u){return Point$2.fromJSON(this,u)};Point$2.prototype.precompute=function(){};Point$2.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())};Point$2.fromJSON=function(u,h){return new Point$2(u,h[0],h[1]||u.one)};Point$2.prototype.inspect=function(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+this.x.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"};Point$2.prototype.isInfinity=function(){return this.z.cmpn(0)===0};Point$2.prototype.dbl=function(){var u=this.x.redAdd(this.z),h=u.redSqr(),b=this.x.redSub(this.z),v=b.redSqr(),w=h.redSub(v),_=h.redMul(v),E=w.redMul(v.redAdd(this.curve.a24.redMul(w)));return this.curve.point(_,E)};Point$2.prototype.add=function(){throw new Error("Not supported on Montgomery curve")};Point$2.prototype.diffAdd=function(u,h){var b=this.x.redAdd(this.z),v=this.x.redSub(this.z),w=u.x.redAdd(u.z),_=u.x.redSub(u.z),E=_.redMul(b),S=w.redMul(v),x=h.z.redMul(E.redAdd(S).redSqr()),T=h.x.redMul(E.redISub(S).redSqr());return this.curve.point(x,T)};Point$2.prototype.mul=function(u){for(var h=u.clone(),b=this,v=this.curve.point(null,null),w=this,_=[];h.cmpn(0)!==0;h.iushrn(1))_.push(h.andln(1));for(var E=_.length-1;E>=0;E--)_[E]===0?(b=b.diffAdd(v,w),v=v.dbl()):(v=b.diffAdd(v,w),b=b.dbl());return v};Point$2.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")};Point$2.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")};Point$2.prototype.eq=function(u){return this.getX().cmp(u.getX())===0};Point$2.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this};Point$2.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var utils$h=utils$m,BN$6=bnExports$1,inherits$2=inherits_browserExports,Base=base$1,assert$b=utils$h.assert;function EdwardsCurve(y){this.twisted=(y.a|0)!==1,this.mOneA=this.twisted&&(y.a|0)===-1,this.extended=this.mOneA,Base.call(this,"edwards",y),this.a=new BN$6(y.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new BN$6(y.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new BN$6(y.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),assert$b(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(y.c|0)===1}inherits$2(EdwardsCurve,Base);var edwards=EdwardsCurve;EdwardsCurve.prototype._mulA=function(u){return this.mOneA?u.redNeg():this.a.redMul(u)};EdwardsCurve.prototype._mulC=function(u){return this.oneC?u:this.c.redMul(u)};EdwardsCurve.prototype.jpoint=function(u,h,b,v){return this.point(u,h,b,v)};EdwardsCurve.prototype.pointFromX=function(u,h){u=new BN$6(u,16),u.red||(u=u.toRed(this.red));var b=u.redSqr(),v=this.c2.redSub(this.a.redMul(b)),w=this.one.redSub(this.c2.redMul(this.d).redMul(b)),_=v.redMul(w.redInvm()),E=_.redSqrt();if(E.redSqr().redSub(_).cmp(this.zero)!==0)throw new Error("invalid point");var S=E.fromRed().isOdd();return(h&&!S||!h&&S)&&(E=E.redNeg()),this.point(u,E)};EdwardsCurve.prototype.pointFromY=function(u,h){u=new BN$6(u,16),u.red||(u=u.toRed(this.red));var b=u.redSqr(),v=b.redSub(this.c2),w=b.redMul(this.d).redMul(this.c2).redSub(this.a),_=v.redMul(w.redInvm());if(_.cmp(this.zero)===0){if(h)throw new Error("invalid point");return this.point(this.zero,u)}var E=_.redSqrt();if(E.redSqr().redSub(_).cmp(this.zero)!==0)throw new Error("invalid point");return E.fromRed().isOdd()!==h&&(E=E.redNeg()),this.point(E,u)};EdwardsCurve.prototype.validate=function(u){if(u.isInfinity())return!0;u.normalize();var h=u.x.redSqr(),b=u.y.redSqr(),v=h.redMul(this.a).redAdd(b),w=this.c2.redMul(this.one.redAdd(this.d.redMul(h).redMul(b)));return v.cmp(w)===0};function Point$1(y,u,h,b,v){Base.BasePoint.call(this,y,"projective"),u===null&&h===null&&b===null?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new BN$6(u,16),this.y=new BN$6(h,16),this.z=b?new BN$6(b,16):this.curve.one,this.t=v&&new BN$6(v,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}inherits$2(Point$1,Base.BasePoint);EdwardsCurve.prototype.pointFromJSON=function(u){return Point$1.fromJSON(this,u)};EdwardsCurve.prototype.point=function(u,h,b,v){return new Point$1(this,u,h,b,v)};Point$1.fromJSON=function(u,h){return new Point$1(u,h[0],h[1],h[2])};Point$1.prototype.inspect=function(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"};Point$1.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)};Point$1.prototype._extDbl=function(){var u=this.x.redSqr(),h=this.y.redSqr(),b=this.z.redSqr();b=b.redIAdd(b);var v=this.curve._mulA(u),w=this.x.redAdd(this.y).redSqr().redISub(u).redISub(h),_=v.redAdd(h),E=_.redSub(b),S=v.redSub(h),x=w.redMul(E),T=_.redMul(S),C=w.redMul(S),O=E.redMul(_);return this.curve.point(x,T,O,C)};Point$1.prototype._projDbl=function(){var u=this.x.redAdd(this.y).redSqr(),h=this.x.redSqr(),b=this.y.redSqr(),v,w,_,E,S,x;if(this.curve.twisted){E=this.curve._mulA(h);var T=E.redAdd(b);this.zOne?(v=u.redSub(h).redSub(b).redMul(T.redSub(this.curve.two)),w=T.redMul(E.redSub(b)),_=T.redSqr().redSub(T).redSub(T)):(S=this.z.redSqr(),x=T.redSub(S).redISub(S),v=u.redSub(h).redISub(b).redMul(x),w=T.redMul(E.redSub(b)),_=T.redMul(x))}else E=h.redAdd(b),S=this.curve._mulC(this.z).redSqr(),x=E.redSub(S).redSub(S),v=this.curve._mulC(u.redISub(E)).redMul(x),w=this.curve._mulC(E).redMul(h.redISub(b)),_=E.redMul(x);return this.curve.point(v,w,_)};Point$1.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()};Point$1.prototype._extAdd=function(u){var h=this.y.redSub(this.x).redMul(u.y.redSub(u.x)),b=this.y.redAdd(this.x).redMul(u.y.redAdd(u.x)),v=this.t.redMul(this.curve.dd).redMul(u.t),w=this.z.redMul(u.z.redAdd(u.z)),_=b.redSub(h),E=w.redSub(v),S=w.redAdd(v),x=b.redAdd(h),T=_.redMul(E),C=S.redMul(x),O=_.redMul(x),D=E.redMul(S);return this.curve.point(T,C,D,O)};Point$1.prototype._projAdd=function(u){var h=this.z.redMul(u.z),b=h.redSqr(),v=this.x.redMul(u.x),w=this.y.redMul(u.y),_=this.curve.d.redMul(v).redMul(w),E=b.redSub(_),S=b.redAdd(_),x=this.x.redAdd(this.y).redMul(u.x.redAdd(u.y)).redISub(v).redISub(w),T=h.redMul(E).redMul(x),C,O;return this.curve.twisted?(C=h.redMul(S).redMul(w.redSub(this.curve._mulA(v))),O=E.redMul(S)):(C=h.redMul(S).redMul(w.redSub(v)),O=this.curve._mulC(E).redMul(S)),this.curve.point(T,C,O)};Point$1.prototype.add=function(u){return this.isInfinity()?u:u.isInfinity()?this:this.curve.extended?this._extAdd(u):this._projAdd(u)};Point$1.prototype.mul=function(u){return this._hasDoubles(u)?this.curve._fixedNafMul(this,u):this.curve._wnafMul(this,u)};Point$1.prototype.mulAdd=function(u,h,b){return this.curve._wnafMulAdd(1,[this,h],[u,b],2,!1)};Point$1.prototype.jmulAdd=function(u,h,b){return this.curve._wnafMulAdd(1,[this,h],[u,b],2,!0)};Point$1.prototype.normalize=function(){if(this.zOne)return this;var u=this.z.redInvm();return this.x=this.x.redMul(u),this.y=this.y.redMul(u),this.t&&(this.t=this.t.redMul(u)),this.z=this.curve.one,this.zOne=!0,this};Point$1.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())};Point$1.prototype.getX=function(){return this.normalize(),this.x.fromRed()};Point$1.prototype.getY=function(){return this.normalize(),this.y.fromRed()};Point$1.prototype.eq=function(u){return this===u||this.getX().cmp(u.getX())===0&&this.getY().cmp(u.getY())===0};Point$1.prototype.eqXToP=function(u){var h=u.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(h)===0)return!0;for(var b=u.clone(),v=this.curve.redN.redMul(this.z);;){if(b.iadd(this.curve.n),b.cmp(this.curve.p)>=0)return!1;if(h.redIAdd(v),this.x.cmp(h)===0)return!0}};Point$1.prototype.toP=Point$1.prototype.normalize;Point$1.prototype.mixedAdd=Point$1.prototype.add;(function(y){var u=y;u.base=base$1,u.short=short,u.mont=mont,u.edwards=edwards})(curve);var curves$1={},hash$2={},utils$g={},assert$a=minimalisticAssert,inherits$1=inherits_browserExports;utils$g.inherits=inherits$1;function isSurrogatePair(y,u){return(y.charCodeAt(u)&64512)!==55296||u<0||u+1>=y.length?!1:(y.charCodeAt(u+1)&64512)===56320}function toArray(y,u){if(Array.isArray(y))return y.slice();if(!y)return[];var h=[];if(typeof y=="string")if(u){if(u==="hex")for(y=y.replace(/[^a-z0-9]+/ig,""),y.length%2!==0&&(y="0"+y),v=0;v<y.length;v+=2)h.push(parseInt(y[v]+y[v+1],16))}else for(var b=0,v=0;v<y.length;v++){var w=y.charCodeAt(v);w<128?h[b++]=w:w<2048?(h[b++]=w>>6|192,h[b++]=w&63|128):isSurrogatePair(y,v)?(w=65536+((w&1023)<<10)+(y.charCodeAt(++v)&1023),h[b++]=w>>18|240,h[b++]=w>>12&63|128,h[b++]=w>>6&63|128,h[b++]=w&63|128):(h[b++]=w>>12|224,h[b++]=w>>6&63|128,h[b++]=w&63|128)}else for(v=0;v<y.length;v++)h[v]=y[v]|0;return h}utils$g.toArray=toArray;function toHex(y){for(var u="",h=0;h<y.length;h++)u+=zero2(y[h].toString(16));return u}utils$g.toHex=toHex;function htonl(y){var u=y>>>24|y>>>8&65280|y<<8&16711680|(y&255)<<24;return u>>>0}utils$g.htonl=htonl;function toHex32(y,u){for(var h="",b=0;b<y.length;b++){var v=y[b];u==="little"&&(v=htonl(v)),h+=zero8(v.toString(16))}return h}utils$g.toHex32=toHex32;function zero2(y){return y.length===1?"0"+y:y}utils$g.zero2=zero2;function zero8(y){return y.length===7?"0"+y:y.length===6?"00"+y:y.length===5?"000"+y:y.length===4?"0000"+y:y.length===3?"00000"+y:y.length===2?"000000"+y:y.length===1?"0000000"+y:y}utils$g.zero8=zero8;function join32(y,u,h,b){var v=h-u;assert$a(v%4===0);for(var w=new Array(v/4),_=0,E=u;_<w.length;_++,E+=4){var S;b==="big"?S=y[E]<<24|y[E+1]<<16|y[E+2]<<8|y[E+3]:S=y[E+3]<<24|y[E+2]<<16|y[E+1]<<8|y[E],w[_]=S>>>0}return w}utils$g.join32=join32;function split32(y,u){for(var h=new Array(y.length*4),b=0,v=0;b<y.length;b++,v+=4){var w=y[b];u==="big"?(h[v]=w>>>24,h[v+1]=w>>>16&255,h[v+2]=w>>>8&255,h[v+3]=w&255):(h[v+3]=w>>>24,h[v+2]=w>>>16&255,h[v+1]=w>>>8&255,h[v]=w&255)}return h}utils$g.split32=split32;function rotr32$1(y,u){return y>>>u|y<<32-u}utils$g.rotr32=rotr32$1;function rotl32$2(y,u){return y<<u|y>>>32-u}utils$g.rotl32=rotl32$2;function sum32$3(y,u){return y+u>>>0}utils$g.sum32=sum32$3;function sum32_3$1(y,u,h){return y+u+h>>>0}utils$g.sum32_3=sum32_3$1;function sum32_4$2(y,u,h,b){return y+u+h+b>>>0}utils$g.sum32_4=sum32_4$2;function sum32_5$2(y,u,h,b,v){return y+u+h+b+v>>>0}utils$g.sum32_5=sum32_5$2;function sum64$1(y,u,h,b){var v=y[u],w=y[u+1],_=b+w>>>0,E=(_<b?1:0)+h+v;y[u]=E>>>0,y[u+1]=_}utils$g.sum64=sum64$1;function sum64_hi$1(y,u,h,b){var v=u+b>>>0,w=(v<u?1:0)+y+h;return w>>>0}utils$g.sum64_hi=sum64_hi$1;function sum64_lo$1(y,u,h,b){var v=u+b;return v>>>0}utils$g.sum64_lo=sum64_lo$1;function sum64_4_hi$1(y,u,h,b,v,w,_,E){var S=0,x=u;x=x+b>>>0,S+=x<u?1:0,x=x+w>>>0,S+=x<w?1:0,x=x+E>>>0,S+=x<E?1:0;var T=y+h+v+_+S;return T>>>0}utils$g.sum64_4_hi=sum64_4_hi$1;function sum64_4_lo$1(y,u,h,b,v,w,_,E){var S=u+b+w+E;return S>>>0}utils$g.sum64_4_lo=sum64_4_lo$1;function sum64_5_hi$1(y,u,h,b,v,w,_,E,S,x){var T=0,C=u;C=C+b>>>0,T+=C<u?1:0,C=C+w>>>0,T+=C<w?1:0,C=C+E>>>0,T+=C<E?1:0,C=C+x>>>0,T+=C<x?1:0;var O=y+h+v+_+S+T;return O>>>0}utils$g.sum64_5_hi=sum64_5_hi$1;function sum64_5_lo$1(y,u,h,b,v,w,_,E,S,x){var T=u+b+w+E+x;return T>>>0}utils$g.sum64_5_lo=sum64_5_lo$1;function rotr64_hi$1(y,u,h){var b=u<<32-h|y>>>h;return b>>>0}utils$g.rotr64_hi=rotr64_hi$1;function rotr64_lo$1(y,u,h){var b=y<<32-h|u>>>h;return b>>>0}utils$g.rotr64_lo=rotr64_lo$1;function shr64_hi$1(y,u,h){return y>>>h}utils$g.shr64_hi=shr64_hi$1;function shr64_lo$1(y,u,h){var b=y<<32-h|u>>>h;return b>>>0}utils$g.shr64_lo=shr64_lo$1;var common$6={},utils$f=utils$g,assert$9=minimalisticAssert;function BlockHash$4(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}common$6.BlockHash=BlockHash$4;BlockHash$4.prototype.update=function(u,h){if(u=utils$f.toArray(u,h),this.pending?this.pending=this.pending.concat(u):this.pending=u,this.pendingTotal+=u.length,this.pending.length>=this._delta8){u=this.pending;var b=u.length%this._delta8;this.pending=u.slice(u.length-b,u.length),this.pending.length===0&&(this.pending=null),u=utils$f.join32(u,0,u.length-b,this.endian);for(var v=0;v<u.length;v+=this._delta32)this._update(u,v,v+this._delta32)}return this};BlockHash$4.prototype.digest=function(u){return this.update(this._pad()),assert$9(this.pending===null),this._digest(u)};BlockHash$4.prototype._pad=function(){var u=this.pendingTotal,h=this._delta8,b=h-(u+this.padLength)%h,v=new Array(b+this.padLength);v[0]=128;for(var w=1;w<b;w++)v[w]=0;if(u<<=3,this.endian==="big"){for(var _=8;_<this.padLength;_++)v[w++]=0;v[w++]=0,v[w++]=0,v[w++]=0,v[w++]=0,v[w++]=u>>>24&255,v[w++]=u>>>16&255,v[w++]=u>>>8&255,v[w++]=u&255}else for(v[w++]=u&255,v[w++]=u>>>8&255,v[w++]=u>>>16&255,v[w++]=u>>>24&255,v[w++]=0,v[w++]=0,v[w++]=0,v[w++]=0,_=8;_<this.padLength;_++)v[w++]=0;return v};var sha={},common$5={},utils$e=utils$g,rotr32=utils$e.rotr32;function ft_1$1(y,u,h,b){if(y===0)return ch32$1(u,h,b);if(y===1||y===3)return p32(u,h,b);if(y===2)return maj32$1(u,h,b)}common$5.ft_1=ft_1$1;function ch32$1(y,u,h){return y&u^~y&h}common$5.ch32=ch32$1;function maj32$1(y,u,h){return y&u^y&h^u&h}common$5.maj32=maj32$1;function p32(y,u,h){return y^u^h}common$5.p32=p32;function s0_256$1(y){return rotr32(y,2)^rotr32(y,13)^rotr32(y,22)}common$5.s0_256=s0_256$1;function s1_256$1(y){return rotr32(y,6)^rotr32(y,11)^rotr32(y,25)}common$5.s1_256=s1_256$1;function g0_256$1(y){return rotr32(y,7)^rotr32(y,18)^y>>>3}common$5.g0_256=g0_256$1;function g1_256$1(y){return rotr32(y,17)^rotr32(y,19)^y>>>10}common$5.g1_256=g1_256$1;var utils$d=utils$g,common$4=common$6,shaCommon$1=common$5,rotl32$1=utils$d.rotl32,sum32$2=utils$d.sum32,sum32_5$1=utils$d.sum32_5,ft_1=shaCommon$1.ft_1,BlockHash$3=common$4.BlockHash,sha1_K=[1518500249,1859775393,2400959708,3395469782];function SHA1(){if(!(this instanceof SHA1))return new SHA1;BlockHash$3.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}utils$d.inherits(SHA1,BlockHash$3);var _1=SHA1;SHA1.blockSize=512;SHA1.outSize=160;SHA1.hmacStrength=80;SHA1.padLength=64;SHA1.prototype._update=function(u,h){for(var b=this.W,v=0;v<16;v++)b[v]=u[h+v];for(;v<b.length;v++)b[v]=rotl32$1(b[v-3]^b[v-8]^b[v-14]^b[v-16],1);var w=this.h[0],_=this.h[1],E=this.h[2],S=this.h[3],x=this.h[4];for(v=0;v<b.length;v++){var T=~~(v/20),C=sum32_5$1(rotl32$1(w,5),ft_1(T,_,E,S),x,b[v],sha1_K[T]);x=S,S=E,E=rotl32$1(_,30),_=w,w=C}this.h[0]=sum32$2(this.h[0],w),this.h[1]=sum32$2(this.h[1],_),this.h[2]=sum32$2(this.h[2],E),this.h[3]=sum32$2(this.h[3],S),this.h[4]=sum32$2(this.h[4],x)};SHA1.prototype._digest=function(u){return u==="hex"?utils$d.toHex32(this.h,"big"):utils$d.split32(this.h,"big")};var utils$c=utils$g,common$3=common$6,shaCommon=common$5,assert$8=minimalisticAssert,sum32$1=utils$c.sum32,sum32_4$1=utils$c.sum32_4,sum32_5=utils$c.sum32_5,ch32=shaCommon.ch32,maj32=shaCommon.maj32,s0_256=shaCommon.s0_256,s1_256=shaCommon.s1_256,g0_256=shaCommon.g0_256,g1_256=shaCommon.g1_256,BlockHash$2=common$3.BlockHash,sha256_K=[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];function SHA256$1(){if(!(this instanceof SHA256$1))return new SHA256$1;BlockHash$2.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=sha256_K,this.W=new Array(64)}utils$c.inherits(SHA256$1,BlockHash$2);var _256=SHA256$1;SHA256$1.blockSize=512;SHA256$1.outSize=256;SHA256$1.hmacStrength=192;SHA256$1.padLength=64;SHA256$1.prototype._update=function(u,h){for(var b=this.W,v=0;v<16;v++)b[v]=u[h+v];for(;v<b.length;v++)b[v]=sum32_4$1(g1_256(b[v-2]),b[v-7],g0_256(b[v-15]),b[v-16]);var w=this.h[0],_=this.h[1],E=this.h[2],S=this.h[3],x=this.h[4],T=this.h[5],C=this.h[6],O=this.h[7];for(assert$8(this.k.length===b.length),v=0;v<b.length;v++){var D=sum32_5(O,s1_256(x),ch32(x,T,C),this.k[v],b[v]),U=sum32$1(s0_256(w),maj32(w,_,E));O=C,C=T,T=x,x=sum32$1(S,D),S=E,E=_,_=w,w=sum32$1(D,U)}this.h[0]=sum32$1(this.h[0],w),this.h[1]=sum32$1(this.h[1],_),this.h[2]=sum32$1(this.h[2],E),this.h[3]=sum32$1(this.h[3],S),this.h[4]=sum32$1(this.h[4],x),this.h[5]=sum32$1(this.h[5],T),this.h[6]=sum32$1(this.h[6],C),this.h[7]=sum32$1(this.h[7],O)};SHA256$1.prototype._digest=function(u){return u==="hex"?utils$c.toHex32(this.h,"big"):utils$c.split32(this.h,"big")};var utils$b=utils$g,SHA256=_256;function SHA224(){if(!(this instanceof SHA224))return new SHA224;SHA256.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}utils$b.inherits(SHA224,SHA256);var _224=SHA224;SHA224.blockSize=512;SHA224.outSize=224;SHA224.hmacStrength=192;SHA224.padLength=64;SHA224.prototype._digest=function(u){return u==="hex"?utils$b.toHex32(this.h.slice(0,7),"big"):utils$b.split32(this.h.slice(0,7),"big")};var utils$a=utils$g,common$2=common$6,assert$7=minimalisticAssert,rotr64_hi=utils$a.rotr64_hi,rotr64_lo=utils$a.rotr64_lo,shr64_hi=utils$a.shr64_hi,shr64_lo=utils$a.shr64_lo,sum64=utils$a.sum64,sum64_hi=utils$a.sum64_hi,sum64_lo=utils$a.sum64_lo,sum64_4_hi=utils$a.sum64_4_hi,sum64_4_lo=utils$a.sum64_4_lo,sum64_5_hi=utils$a.sum64_5_hi,sum64_5_lo=utils$a.sum64_5_lo,BlockHash$1=common$2.BlockHash,sha512_K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function SHA512$1(){if(!(this instanceof SHA512$1))return new SHA512$1;BlockHash$1.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=sha512_K,this.W=new Array(160)}utils$a.inherits(SHA512$1,BlockHash$1);var _512=SHA512$1;SHA512$1.blockSize=1024;SHA512$1.outSize=512;SHA512$1.hmacStrength=192;SHA512$1.padLength=128;SHA512$1.prototype._prepareBlock=function(u,h){for(var b=this.W,v=0;v<32;v++)b[v]=u[h+v];for(;v<b.length;v+=2){var w=g1_512_hi(b[v-4],b[v-3]),_=g1_512_lo(b[v-4],b[v-3]),E=b[v-14],S=b[v-13],x=g0_512_hi(b[v-30],b[v-29]),T=g0_512_lo(b[v-30],b[v-29]),C=b[v-32],O=b[v-31];b[v]=sum64_4_hi(w,_,E,S,x,T,C,O),b[v+1]=sum64_4_lo(w,_,E,S,x,T,C,O)}};SHA512$1.prototype._update=function(u,h){this._prepareBlock(u,h);var b=this.W,v=this.h[0],w=this.h[1],_=this.h[2],E=this.h[3],S=this.h[4],x=this.h[5],T=this.h[6],C=this.h[7],O=this.h[8],D=this.h[9],U=this.h[10],te=this.h[11],X=this.h[12],ie=this.h[13],ee=this.h[14],ae=this.h[15];assert$7(this.k.length===b.length);for(var de=0;de<b.length;de+=2){var Se=ee,ve=ae,Pe=s1_512_hi(O,D),Ie=s1_512_lo(O,D),Ee=ch64_hi(O,D,U,te,X),De=ch64_lo(O,D,U,te,X,ie),be=this.k[de],B=this.k[de+1],F=b[de],M=b[de+1],N=sum64_5_hi(Se,ve,Pe,Ie,Ee,De,be,B,F,M),Q=sum64_5_lo(Se,ve,Pe,Ie,Ee,De,be,B,F,M);Se=s0_512_hi(v,w),ve=s0_512_lo(v,w),Pe=maj64_hi(v,w,_,E,S),Ie=maj64_lo(v,w,_,E,S,x);var j=sum64_hi(Se,ve,Pe,Ie),ne=sum64_lo(Se,ve,Pe,Ie);ee=X,ae=ie,X=U,ie=te,U=O,te=D,O=sum64_hi(T,C,N,Q),D=sum64_lo(C,C,N,Q),T=S,C=x,S=_,x=E,_=v,E=w,v=sum64_hi(N,Q,j,ne),w=sum64_lo(N,Q,j,ne)}sum64(this.h,0,v,w),sum64(this.h,2,_,E),sum64(this.h,4,S,x),sum64(this.h,6,T,C),sum64(this.h,8,O,D),sum64(this.h,10,U,te),sum64(this.h,12,X,ie),sum64(this.h,14,ee,ae)};SHA512$1.prototype._digest=function(u){return u==="hex"?utils$a.toHex32(this.h,"big"):utils$a.split32(this.h,"big")};function ch64_hi(y,u,h,b,v){var w=y&h^~y&v;return w<0&&(w+=4294967296),w}function ch64_lo(y,u,h,b,v,w){var _=u&b^~u&w;return _<0&&(_+=4294967296),_}function maj64_hi(y,u,h,b,v){var w=y&h^y&v^h&v;return w<0&&(w+=4294967296),w}function maj64_lo(y,u,h,b,v,w){var _=u&b^u&w^b&w;return _<0&&(_+=4294967296),_}function s0_512_hi(y,u){var h=rotr64_hi(y,u,28),b=rotr64_hi(u,y,2),v=rotr64_hi(u,y,7),w=h^b^v;return w<0&&(w+=4294967296),w}function s0_512_lo(y,u){var h=rotr64_lo(y,u,28),b=rotr64_lo(u,y,2),v=rotr64_lo(u,y,7),w=h^b^v;return w<0&&(w+=4294967296),w}function s1_512_hi(y,u){var h=rotr64_hi(y,u,14),b=rotr64_hi(y,u,18),v=rotr64_hi(u,y,9),w=h^b^v;return w<0&&(w+=4294967296),w}function s1_512_lo(y,u){var h=rotr64_lo(y,u,14),b=rotr64_lo(y,u,18),v=rotr64_lo(u,y,9),w=h^b^v;return w<0&&(w+=4294967296),w}function g0_512_hi(y,u){var h=rotr64_hi(y,u,1),b=rotr64_hi(y,u,8),v=shr64_hi(y,u,7),w=h^b^v;return w<0&&(w+=4294967296),w}function g0_512_lo(y,u){var h=rotr64_lo(y,u,1),b=rotr64_lo(y,u,8),v=shr64_lo(y,u,7),w=h^b^v;return w<0&&(w+=4294967296),w}function g1_512_hi(y,u){var h=rotr64_hi(y,u,19),b=rotr64_hi(u,y,29),v=shr64_hi(y,u,6),w=h^b^v;return w<0&&(w+=4294967296),w}function g1_512_lo(y,u){var h=rotr64_lo(y,u,19),b=rotr64_lo(u,y,29),v=shr64_lo(y,u,6),w=h^b^v;return w<0&&(w+=4294967296),w}var utils$9=utils$g,SHA512=_512;function SHA384(){if(!(this instanceof SHA384))return new SHA384;SHA512.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}utils$9.inherits(SHA384,SHA512);var _384=SHA384;SHA384.blockSize=1024;SHA384.outSize=384;SHA384.hmacStrength=192;SHA384.padLength=128;SHA384.prototype._digest=function(u){return u==="hex"?utils$9.toHex32(this.h.slice(0,12),"big"):utils$9.split32(this.h.slice(0,12),"big")};sha.sha1=_1;sha.sha224=_224;sha.sha256=_256;sha.sha384=_384;sha.sha512=_512;var ripemd={},utils$8=utils$g,common$1=common$6,rotl32=utils$8.rotl32,sum32=utils$8.sum32,sum32_3=utils$8.sum32_3,sum32_4=utils$8.sum32_4,BlockHash=common$1.BlockHash;function RIPEMD160(){if(!(this instanceof RIPEMD160))return new RIPEMD160;BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}utils$8.inherits(RIPEMD160,BlockHash);ripemd.ripemd160=RIPEMD160;RIPEMD160.blockSize=512;RIPEMD160.outSize=160;RIPEMD160.hmacStrength=192;RIPEMD160.padLength=64;RIPEMD160.prototype._update=function(u,h){for(var b=this.h[0],v=this.h[1],w=this.h[2],_=this.h[3],E=this.h[4],S=b,x=v,T=w,C=_,O=E,D=0;D<80;D++){var U=sum32(rotl32(sum32_4(b,f(D,v,w,_),u[r[D]+h],K(D)),s[D]),E);b=E,E=_,_=rotl32(w,10),w=v,v=U,U=sum32(rotl32(sum32_4(S,f(79-D,x,T,C),u[rh[D]+h],Kh(D)),sh[D]),O),S=O,O=C,C=rotl32(T,10),T=x,x=U}U=sum32_3(this.h[1],w,C),this.h[1]=sum32_3(this.h[2],_,O),this.h[2]=sum32_3(this.h[3],E,S),this.h[3]=sum32_3(this.h[4],b,x),this.h[4]=sum32_3(this.h[0],v,T),this.h[0]=U};RIPEMD160.prototype._digest=function(u){return u==="hex"?utils$8.toHex32(this.h,"little"):utils$8.split32(this.h,"little")};function f(y,u,h,b){return y<=15?u^h^b:y<=31?u&h|~u&b:y<=47?(u|~h)^b:y<=63?u&b|h&~b:u^(h|~b)}function K(y){return y<=15?0:y<=31?1518500249:y<=47?1859775393:y<=63?2400959708:2840853838}function Kh(y){return y<=15?1352829926:y<=31?1548603684:y<=47?1836072691:y<=63?2053994217:0}var r=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],rh=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],s=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sh=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],utils$7=utils$g,assert$6=minimalisticAssert;function Hmac(y,u,h){if(!(this instanceof Hmac))return new Hmac(y,u,h);this.Hash=y,this.blockSize=y.blockSize/8,this.outSize=y.outSize/8,this.inner=null,this.outer=null,this._init(utils$7.toArray(u,h))}var hmac=Hmac;Hmac.prototype._init=function(u){u.length>this.blockSize&&(u=new this.Hash().update(u).digest()),assert$6(u.length<=this.blockSize);for(var h=u.length;h<this.blockSize;h++)u.push(0);for(h=0;h<u.length;h++)u[h]^=54;for(this.inner=new this.Hash().update(u),h=0;h<u.length;h++)u[h]^=106;this.outer=new this.Hash().update(u)};Hmac.prototype.update=function(u,h){return this.inner.update(u,h),this};Hmac.prototype.digest=function(u){return this.outer.update(this.inner.digest()),this.outer.digest(u)};(function(y){var u=y;u.utils=utils$g,u.common=common$6,u.sha=sha,u.ripemd=ripemd,u.hmac=hmac,u.sha1=u.sha.sha1,u.sha256=u.sha.sha256,u.sha224=u.sha.sha224,u.sha384=u.sha.sha384,u.sha512=u.sha.sha512,u.ripemd160=u.ripemd.ripemd160})(hash$2);var secp256k1,hasRequiredSecp256k1;function requireSecp256k1(){return hasRequiredSecp256k1||(hasRequiredSecp256k1=1,secp256k1={doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}),secp256k1}(function(y){var u=y,h=hash$2,b=curve,v=utils$m,w=v.assert;function _(x){x.type==="short"?this.curve=new b.short(x):x.type==="edwards"?this.curve=new b.edwards(x):this.curve=new b.mont(x),this.g=this.curve.g,this.n=this.curve.n,this.hash=x.hash,w(this.g.validate(),"Invalid curve"),w(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}u.PresetCurve=_;function E(x,T){Object.defineProperty(u,x,{configurable:!0,enumerable:!0,get:function(){var C=new _(T);return Object.defineProperty(u,x,{configurable:!0,enumerable:!0,value:C}),C}})}E("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:h.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),E("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:h.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),E("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:h.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),E("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:h.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),E("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:h.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),E("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:h.sha256,gRed:!1,g:["9"]}),E("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:h.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var S;try{S=requireSecp256k1()}catch{S=void 0}E("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:h.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",S]})})(curves$1);var hash$1=hash$2,utils$6=utils$l,assert$5=minimalisticAssert;function HmacDRBG(y){if(!(this instanceof HmacDRBG))return new HmacDRBG(y);this.hash=y.hash,this.predResist=!!y.predResist,this.outLen=this.hash.outSize,this.minEntropy=y.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var u=utils$6.toArray(y.entropy,y.entropyEnc||"hex"),h=utils$6.toArray(y.nonce,y.nonceEnc||"hex"),b=utils$6.toArray(y.pers,y.persEnc||"hex");assert$5(u.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(u,h,b)}var hmacDrbg=HmacDRBG;HmacDRBG.prototype._init=function(u,h,b){var v=u.concat(h).concat(b);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var w=0;w<this.V.length;w++)this.K[w]=0,this.V[w]=1;this._update(v),this._reseed=1,this.reseedInterval=281474976710656};HmacDRBG.prototype._hmac=function(){return new hash$1.hmac(this.hash,this.K)};HmacDRBG.prototype._update=function(u){var h=this._hmac().update(this.V).update([0]);u&&(h=h.update(u)),this.K=h.digest(),this.V=this._hmac().update(this.V).digest(),u&&(this.K=this._hmac().update(this.V).update([1]).update(u).digest(),this.V=this._hmac().update(this.V).digest())};HmacDRBG.prototype.reseed=function(u,h,b,v){typeof h!="string"&&(v=b,b=h,h=null),u=utils$6.toArray(u,h),b=utils$6.toArray(b,v),assert$5(u.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(u.concat(b||[])),this._reseed=1};HmacDRBG.prototype.generate=function(u,h,b,v){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof h!="string"&&(v=b,b=h,h=null),b&&(b=utils$6.toArray(b,v||"hex"),this._update(b));for(var w=[];w.length<u;)this.V=this._hmac().update(this.V).digest(),w=w.concat(this.V);var _=w.slice(0,u);return this._update(b),this._reseed++,utils$6.encode(_,h)};var BN$5=bnExports$1,utils$5=utils$m,assert$4=utils$5.assert;function KeyPair$2(y,u){this.ec=y,this.priv=null,this.pub=null,u.priv&&this._importPrivate(u.priv,u.privEnc),u.pub&&this._importPublic(u.pub,u.pubEnc)}var key$1=KeyPair$2;KeyPair$2.fromPublic=function(u,h,b){return h instanceof KeyPair$2?h:new KeyPair$2(u,{pub:h,pubEnc:b})};KeyPair$2.fromPrivate=function(u,h,b){return h instanceof KeyPair$2?h:new KeyPair$2(u,{priv:h,privEnc:b})};KeyPair$2.prototype.validate=function(){var u=this.getPublic();return u.isInfinity()?{result:!1,reason:"Invalid public key"}:u.validate()?u.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}};KeyPair$2.prototype.getPublic=function(u,h){return typeof u=="string"&&(h=u,u=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),h?this.pub.encode(h,u):this.pub};KeyPair$2.prototype.getPrivate=function(u){return u==="hex"?this.priv.toString(16,2):this.priv};KeyPair$2.prototype._importPrivate=function(u,h){this.priv=new BN$5(u,h||16),this.priv=this.priv.umod(this.ec.curve.n)};KeyPair$2.prototype._importPublic=function(u,h){if(u.x||u.y){this.ec.curve.type==="mont"?assert$4(u.x,"Need x coordinate"):(this.ec.curve.type==="short"||this.ec.curve.type==="edwards")&&assert$4(u.x&&u.y,"Need both x and y coordinate"),this.pub=this.ec.curve.point(u.x,u.y);return}this.pub=this.ec.curve.decodePoint(u,h)};KeyPair$2.prototype.derive=function(u){return u.validate()||assert$4(u.validate(),"public point not validated"),u.mul(this.priv).getX()};KeyPair$2.prototype.sign=function(u,h,b){return this.ec.sign(u,this,h,b)};KeyPair$2.prototype.verify=function(u,h){return this.ec.verify(u,h,this)};KeyPair$2.prototype.inspect=function(){return"<Key priv: "+(this.priv&&this.priv.toString(16,2))+" pub: "+(this.pub&&this.pub.inspect())+" >"};var BN$4=bnExports$1,utils$4=utils$m,assert$3=utils$4.assert;function Signature$3(y,u){if(y instanceof Signature$3)return y;this._importDER(y,u)||(assert$3(y.r&&y.s,"Signature without r or s"),this.r=new BN$4(y.r,16),this.s=new BN$4(y.s,16),y.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=y.recoveryParam)}var signature$1=Signature$3;function Position(){this.place=0}function getLength(y,u){var h=y[u.place++];if(!(h&128))return h;var b=h&15;if(b===0||b>4||y[u.place]===0)return!1;for(var v=0,w=0,_=u.place;w<b;w++,_++)v<<=8,v|=y[_],v>>>=0;return v<=127?!1:(u.place=_,v)}function rmPadding(y){for(var u=0,h=y.length-1;!y[u]&&!(y[u+1]&128)&&u<h;)u++;return u===0?y:y.slice(u)}Signature$3.prototype._importDER=function(u,h){u=utils$4.toArray(u,h);var b=new Position;if(u[b.place++]!==48)return!1;var v=getLength(u,b);if(v===!1||v+b.place!==u.length||u[b.place++]!==2)return!1;var w=getLength(u,b);if(w===!1||u[b.place]&128)return!1;var _=u.slice(b.place,w+b.place);if(b.place+=w,u[b.place++]!==2)return!1;var E=getLength(u,b);if(E===!1||u.length!==E+b.place||u[b.place]&128)return!1;var S=u.slice(b.place,E+b.place);if(_[0]===0)if(_[1]&128)_=_.slice(1);else return!1;if(S[0]===0)if(S[1]&128)S=S.slice(1);else return!1;return this.r=new BN$4(_),this.s=new BN$4(S),this.recoveryParam=null,!0};function constructLength(y,u){if(u<128){y.push(u);return}var h=1+(Math.log(u)/Math.LN2>>>3);for(y.push(h|128);--h;)y.push(u>>>(h<<3)&255);y.push(u)}Signature$3.prototype.toDER=function(u){var h=this.r.toArray(),b=this.s.toArray();for(h[0]&128&&(h=[0].concat(h)),b[0]&128&&(b=[0].concat(b)),h=rmPadding(h),b=rmPadding(b);!b[0]&&!(b[1]&128);)b=b.slice(1);var v=[2];constructLength(v,h.length),v=v.concat(h),v.push(2),constructLength(v,b.length);var w=v.concat(b),_=[48];return constructLength(_,w.length),_=_.concat(w),utils$4.encode(_,u)};var ec,hasRequiredEc;function requireEc(){if(hasRequiredEc)return ec;hasRequiredEc=1;var y=bnExports$1,u=hmacDrbg,h=utils$m,b=curves$1,v=requireBrorand(),w=h.assert,_=key$1,E=signature$1;function S(x){if(!(this instanceof S))return new S(x);typeof x=="string"&&(w(Object.prototype.hasOwnProperty.call(b,x),"Unknown curve "+x),x=b[x]),x instanceof b.PresetCurve&&(x={curve:x}),this.curve=x.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=x.curve.g,this.g.precompute(x.curve.n.bitLength()+1),this.hash=x.hash||x.curve.hash}return ec=S,S.prototype.keyPair=function(T){return new _(this,T)},S.prototype.keyFromPrivate=function(T,C){return _.fromPrivate(this,T,C)},S.prototype.keyFromPublic=function(T,C){return _.fromPublic(this,T,C)},S.prototype.genKeyPair=function(T){T||(T={});for(var C=new u({hash:this.hash,pers:T.pers,persEnc:T.persEnc||"utf8",entropy:T.entropy||v(this.hash.hmacStrength),entropyEnc:T.entropy&&T.entropyEnc||"utf8",nonce:this.n.toArray()}),O=this.n.byteLength(),D=this.n.sub(new y(2));;){var U=new y(C.generate(O));if(!(U.cmp(D)>0))return U.iaddn(1),this.keyFromPrivate(U)}},S.prototype._truncateToN=function(T,C){var O=T.byteLength()*8-this.n.bitLength();return O>0&&(T=T.ushrn(O)),!C&&T.cmp(this.n)>=0?T.sub(this.n):T},S.prototype.sign=function(T,C,O,D){typeof O=="object"&&(D=O,O=null),D||(D={}),C=this.keyFromPrivate(C,O),T=this._truncateToN(new y(T,16));for(var U=this.n.byteLength(),te=C.getPrivate().toArray("be",U),X=T.toArray("be",U),ie=new u({hash:this.hash,entropy:te,nonce:X,pers:D.pers,persEnc:D.persEnc||"utf8"}),ee=this.n.sub(new y(1)),ae=0;;ae++){var de=D.k?D.k(ae):new y(ie.generate(this.n.byteLength()));if(de=this._truncateToN(de,!0),!(de.cmpn(1)<=0||de.cmp(ee)>=0)){var Se=this.g.mul(de);if(!Se.isInfinity()){var ve=Se.getX(),Pe=ve.umod(this.n);if(Pe.cmpn(0)!==0){var Ie=de.invm(this.n).mul(Pe.mul(C.getPrivate()).iadd(T));if(Ie=Ie.umod(this.n),Ie.cmpn(0)!==0){var Ee=(Se.getY().isOdd()?1:0)|(ve.cmp(Pe)!==0?2:0);return D.canonical&&Ie.cmp(this.nh)>0&&(Ie=this.n.sub(Ie),Ee^=1),new E({r:Pe,s:Ie,recoveryParam:Ee})}}}}}},S.prototype.verify=function(T,C,O,D){T=this._truncateToN(new y(T,16)),O=this.keyFromPublic(O,D),C=new E(C,"hex");var U=C.r,te=C.s;if(U.cmpn(1)<0||U.cmp(this.n)>=0||te.cmpn(1)<0||te.cmp(this.n)>=0)return!1;var X=te.invm(this.n),ie=X.mul(T).umod(this.n),ee=X.mul(U).umod(this.n),ae;return this.curve._maxwellTrick?(ae=this.g.jmulAdd(ie,O.getPublic(),ee),ae.isInfinity()?!1:ae.eqXToP(U)):(ae=this.g.mulAdd(ie,O.getPublic(),ee),ae.isInfinity()?!1:ae.getX().umod(this.n).cmp(U)===0)},S.prototype.recoverPubKey=function(x,T,C,O){w((3&C)===C,"The recovery param is more than two bits"),T=new E(T,O);var D=this.n,U=new y(x),te=T.r,X=T.s,ie=C&1,ee=C>>1;if(te.cmp(this.curve.p.umod(this.curve.n))>=0&&ee)throw new Error("Unable to find sencond key candinate");ee?te=this.curve.pointFromX(te.add(this.curve.n),ie):te=this.curve.pointFromX(te,ie);var ae=T.r.invm(D),de=D.sub(U).mul(ae).umod(D),Se=X.mul(ae).umod(D);return this.g.mulAdd(de,te,Se)},S.prototype.getKeyRecoveryParam=function(x,T,C,O){if(T=new E(T,O),T.recoveryParam!==null)return T.recoveryParam;for(var D=0;D<4;D++){var U;try{U=this.recoverPubKey(x,T,D)}catch{continue}if(U.eq(C))return D}throw new Error("Unable to find valid recovery factor")},ec}var utils$3=utils$m,assert$2=utils$3.assert,parseBytes$2=utils$3.parseBytes,cachedProperty$1=utils$3.cachedProperty;function KeyPair$1(y,u){this.eddsa=y,this._secret=parseBytes$2(u.secret),y.isPoint(u.pub)?this._pub=u.pub:this._pubBytes=parseBytes$2(u.pub)}KeyPair$1.fromPublic=function(u,h){return h instanceof KeyPair$1?h:new KeyPair$1(u,{pub:h})};KeyPair$1.fromSecret=function(u,h){return h instanceof KeyPair$1?h:new KeyPair$1(u,{secret:h})};KeyPair$1.prototype.secret=function(){return this._secret};cachedProperty$1(KeyPair$1,"pubBytes",function(){return this.eddsa.encodePoint(this.pub())});cachedProperty$1(KeyPair$1,"pub",function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())});cachedProperty$1(KeyPair$1,"privBytes",function(){var u=this.eddsa,h=this.hash(),b=u.encodingLength-1,v=h.slice(0,u.encodingLength);return v[0]&=248,v[b]&=127,v[b]|=64,v});cachedProperty$1(KeyPair$1,"priv",function(){return this.eddsa.decodeInt(this.privBytes())});cachedProperty$1(KeyPair$1,"hash",function(){return this.eddsa.hash().update(this.secret()).digest()});cachedProperty$1(KeyPair$1,"messagePrefix",function(){return this.hash().slice(this.eddsa.encodingLength)});KeyPair$1.prototype.sign=function(u){return assert$2(this._secret,"KeyPair can only verify"),this.eddsa.sign(u,this)};KeyPair$1.prototype.verify=function(u,h){return this.eddsa.verify(u,h,this)};KeyPair$1.prototype.getSecret=function(u){return assert$2(this._secret,"KeyPair is public only"),utils$3.encode(this.secret(),u)};KeyPair$1.prototype.getPublic=function(u){return utils$3.encode(this.pubBytes(),u)};var key=KeyPair$1,BN$3=bnExports$1,utils$2=utils$m,assert$1=utils$2.assert,cachedProperty=utils$2.cachedProperty,parseBytes$1=utils$2.parseBytes;function Signature$2(y,u){this.eddsa=y,typeof u!="object"&&(u=parseBytes$1(u)),Array.isArray(u)&&(assert$1(u.length===y.encodingLength*2,"Signature has invalid size"),u={R:u.slice(0,y.encodingLength),S:u.slice(y.encodingLength)}),assert$1(u.R&&u.S,"Signature without R or S"),y.isPoint(u.R)&&(this._R=u.R),u.S instanceof BN$3&&(this._S=u.S),this._Rencoded=Array.isArray(u.R)?u.R:u.Rencoded,this._Sencoded=Array.isArray(u.S)?u.S:u.Sencoded}cachedProperty(Signature$2,"S",function(){return this.eddsa.decodeInt(this.Sencoded())});cachedProperty(Signature$2,"R",function(){return this.eddsa.decodePoint(this.Rencoded())});cachedProperty(Signature$2,"Rencoded",function(){return this.eddsa.encodePoint(this.R())});cachedProperty(Signature$2,"Sencoded",function(){return this.eddsa.encodeInt(this.S())});Signature$2.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())};Signature$2.prototype.toHex=function(){return utils$2.encode(this.toBytes(),"hex").toUpperCase()};var signature=Signature$2,hash=hash$2,curves=curves$1,utils$1=utils$m,assert=utils$1.assert,parseBytes=utils$1.parseBytes,KeyPair=key,Signature$1=signature;function EDDSA(y){if(assert(y==="ed25519","only tested with ed25519 so far"),!(this instanceof EDDSA))return new EDDSA(y);y=curves[y].curve,this.curve=y,this.g=y.g,this.g.precompute(y.n.bitLength()+1),this.pointClass=y.point().constructor,this.encodingLength=Math.ceil(y.n.bitLength()/8),this.hash=hash.sha512}var eddsa=EDDSA;EDDSA.prototype.sign=function(u,h){u=parseBytes(u);var b=this.keyFromSecret(h),v=this.hashInt(b.messagePrefix(),u),w=this.g.mul(v),_=this.encodePoint(w),E=this.hashInt(_,b.pubBytes(),u).mul(b.priv()),S=v.add(E).umod(this.curve.n);return this.makeSignature({R:w,S,Rencoded:_})};EDDSA.prototype.verify=function(u,h,b){if(u=parseBytes(u),h=this.makeSignature(h),h.S().gte(h.eddsa.curve.n)||h.S().isNeg())return!1;var v=this.keyFromPublic(b),w=this.hashInt(h.Rencoded(),v.pubBytes(),u),_=this.g.mul(h.S()),E=h.R().add(v.pub().mul(w));return E.eq(_)};EDDSA.prototype.hashInt=function(){for(var u=this.hash(),h=0;h<arguments.length;h++)u.update(arguments[h]);return utils$1.intFromLE(u.digest()).umod(this.curve.n)};EDDSA.prototype.keyFromPublic=function(u){return KeyPair.fromPublic(this,u)};EDDSA.prototype.keyFromSecret=function(u){return KeyPair.fromSecret(this,u)};EDDSA.prototype.makeSignature=function(u){return u instanceof Signature$1?u:new Signature$1(this,u)};EDDSA.prototype.encodePoint=function(u){var h=u.getY().toArray("le",this.encodingLength);return h[this.encodingLength-1]|=u.getX().isOdd()?128:0,h};EDDSA.prototype.decodePoint=function(u){u=utils$1.parseBytes(u);var h=u.length-1,b=u.slice(0,h).concat(u[h]&-129),v=(u[h]&128)!==0,w=utils$1.intFromLE(b);return this.curve.pointFromY(w,v)};EDDSA.prototype.encodeInt=function(u){return u.toArray("le",this.encodingLength)};EDDSA.prototype.decodeInt=function(u){return utils$1.intFromLE(u)};EDDSA.prototype.isPoint=function(u){return u instanceof this.pointClass};var hasRequiredElliptic;function requireElliptic(){return hasRequiredElliptic||(hasRequiredElliptic=1,function(y){var u=y;u.version=require$$0.version,u.utils=utils$m,u.rand=requireBrorand(),u.curve=curve,u.curves=curves$1,u.ec=requireEc(),u.eddsa=eddsa}(elliptic)),elliptic}var asn1$3={},asn1$2={},api={},vmBrowserify={},hasRequiredVmBrowserify;function requireVmBrowserify(){return hasRequiredVmBrowserify||(hasRequiredVmBrowserify=1,function(exports){var indexOf=function(y,u){if(y.indexOf)return y.indexOf(u);for(var h=0;h<y.length;h++)if(y[h]===u)return h;return-1},Object_keys=function(y){if(Object.keys)return Object.keys(y);var u=[];for(var h in y)u.push(h);return u},forEach=function(y,u){if(y.forEach)return y.forEach(u);for(var h=0;h<y.length;h++)u(y[h],h,y)},defineProp=function(){try{return Object.defineProperty({},"_",{}),function(y,u,h){Object.defineProperty(y,u,{writable:!0,enumerable:!1,configurable:!0,value:h})}}catch{return function(u,h,b){u[h]=b}}}(),globals=["Array","Boolean","Date","Error","EvalError","Function","Infinity","JSON","Math","NaN","Number","Object","RangeError","ReferenceError","RegExp","String","SyntaxError","TypeError","URIError","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","eval","isFinite","isNaN","parseFloat","parseInt","undefined","unescape"];function Context(){}Context.prototype={};var Script=exports.Script=function(u){if(!(this instanceof Script))return new Script(u);this.code=u};Script.prototype.runInContext=function(y){if(!(y instanceof Context))throw new TypeError("needs a 'context' argument.");var u=document.createElement("iframe");u.style||(u.style={}),u.style.display="none",document.body.appendChild(u);var h=u.contentWindow,b=h.eval,v=h.execScript;!b&&v&&(v.call(h,"null"),b=h.eval),forEach(Object_keys(y),function(E){h[E]=y[E]}),forEach(globals,function(E){y[E]&&(h[E]=y[E])});var w=Object_keys(h),_=b.call(h,this.code);return forEach(Object_keys(h),function(E){(E in y||indexOf(w,E)===-1)&&(y[E]=h[E])}),forEach(globals,function(E){E in y||defineProp(y,E,h[E])}),document.body.removeChild(u),_},Script.prototype.runInThisContext=function(){return eval(this.code)},Script.prototype.runInNewContext=function(y){var u=Script.createContext(y),h=this.runInContext(u);return y&&forEach(Object_keys(u),function(b){y[b]=u[b]}),h},forEach(Object_keys(Script.prototype),function(y){exports[y]=Script[y]=function(u){var h=Script(u);return h[y].apply(h,[].slice.call(arguments,1))}}),exports.isContext=function(y){return y instanceof Context},exports.createScript=function(y){return exports.Script(y)},exports.createContext=Script.createContext=function(y){var u=new Context;return typeof y=="object"&&forEach(Object_keys(y),function(h){u[h]=y[h]}),u}}(vmBrowserify)),vmBrowserify}var hasRequiredApi;function requireApi(){return hasRequiredApi||(hasRequiredApi=1,function(y){var u=requireAsn1(),h=inherits_browserExports,b=y;b.define=function(_,E){return new v(_,E)};function v(w,_){this.name=w,this.body=_,this.decoders={},this.encoders={}}v.prototype._createNamed=function(_){var E;try{E=requireVmBrowserify().runInThisContext("(function "+this.name+`(entity) {
45
+ this._initNamed(entity);
46
+ })`)}catch{E=function(x){this._initNamed(x)}}return h(E,_),E.prototype._initNamed=function(x){_.call(this,x)},new E(this)},v.prototype._getDecoder=function(_){return _=_||"der",this.decoders.hasOwnProperty(_)||(this.decoders[_]=this._createNamed(u.decoders[_])),this.decoders[_]},v.prototype.decode=function(_,E,S){return this._getDecoder(E).decode(_,S)},v.prototype._getEncoder=function(_){return _=_||"der",this.encoders.hasOwnProperty(_)||(this.encoders[_]=this._createNamed(u.encoders[_])),this.encoders[_]},v.prototype.encode=function(_,E,S){return this._getEncoder(E).encode(_,S)}}(api)),api}var base={},reporter={},inherits=inherits_browserExports;function Reporter(y){this._reporterState={obj:null,path:[],options:y||{},errors:[]}}reporter.Reporter=Reporter;Reporter.prototype.isError=function y(u){return u instanceof ReporterError};Reporter.prototype.save=function y(){var u=this._reporterState;return{obj:u.obj,pathLen:u.path.length}};Reporter.prototype.restore=function y(u){var h=this._reporterState;h.obj=u.obj,h.path=h.path.slice(0,u.pathLen)};Reporter.prototype.enterKey=function y(u){return this._reporterState.path.push(u)};Reporter.prototype.exitKey=function y(u){var h=this._reporterState;h.path=h.path.slice(0,u-1)};Reporter.prototype.leaveKey=function y(u,h,b){var v=this._reporterState;this.exitKey(u),v.obj!==null&&(v.obj[h]=b)};Reporter.prototype.path=function y(){return this._reporterState.path.join("/")};Reporter.prototype.enterObject=function y(){var u=this._reporterState,h=u.obj;return u.obj={},h};Reporter.prototype.leaveObject=function y(u){var h=this._reporterState,b=h.obj;return h.obj=u,b};Reporter.prototype.error=function y(u){var h,b=this._reporterState,v=u instanceof ReporterError;if(v?h=u:h=new ReporterError(b.path.map(function(w){return"["+JSON.stringify(w)+"]"}).join(""),u.message||u,u.stack),!b.options.partial)throw h;return v||b.errors.push(h),h};Reporter.prototype.wrapResult=function y(u){var h=this._reporterState;return h.options.partial?{result:this.isError(u)?null:u,errors:h.errors}:u};function ReporterError(y,u){this.path=y,this.rethrow(u)}inherits(ReporterError,Error);ReporterError.prototype.rethrow=function y(u){if(this.message=u+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(h){this.stack=h.stack}return this};var buffer={},hasRequiredBuffer;function requireBuffer(){if(hasRequiredBuffer)return buffer;hasRequiredBuffer=1;var y=inherits_browserExports,u=requireBase().Reporter,h=dist.Buffer;function b(w,_){if(u.call(this,_),!h.isBuffer(w)){this.error("Input not Buffer");return}this.base=w,this.offset=0,this.length=w.length}y(b,u),buffer.DecoderBuffer=b,b.prototype.save=function(){return{offset:this.offset,reporter:u.prototype.save.call(this)}},b.prototype.restore=function(_){var E=new b(this.base);return E.offset=_.offset,E.length=this.offset,this.offset=_.offset,u.prototype.restore.call(this,_.reporter),E},b.prototype.isEmpty=function(){return this.offset===this.length},b.prototype.readUInt8=function(_){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(_||"DecoderBuffer overrun")},b.prototype.skip=function(_,E){if(!(this.offset+_<=this.length))return this.error(E||"DecoderBuffer overrun");var S=new b(this.base);return S._reporterState=this._reporterState,S.offset=this.offset,S.length=this.offset+_,this.offset+=_,S},b.prototype.raw=function(_){return this.base.slice(_?_.offset:this.offset,this.length)};function v(w,_){if(Array.isArray(w))this.length=0,this.value=w.map(function(E){return E instanceof v||(E=new v(E,_)),this.length+=E.length,E},this);else if(typeof w=="number"){if(!(0<=w&&w<=255))return _.error("non-byte EncoderBuffer value");this.value=w,this.length=1}else if(typeof w=="string")this.value=w,this.length=h.byteLength(w);else if(h.isBuffer(w))this.value=w,this.length=w.length;else return _.error("Unsupported type: "+typeof w)}return buffer.EncoderBuffer=v,v.prototype.join=function(_,E){return _||(_=new h(this.length)),E||(E=0),this.length===0||(Array.isArray(this.value)?this.value.forEach(function(S){S.join(_,E),E+=S.length}):(typeof this.value=="number"?_[E]=this.value:typeof this.value=="string"?_.write(this.value,E):h.isBuffer(this.value)&&this.value.copy(_,E),E+=this.length)),_},buffer}var node,hasRequiredNode;function requireNode(){if(hasRequiredNode)return node;hasRequiredNode=1;var y=requireBase().Reporter,u=requireBase().EncoderBuffer,h=requireBase().DecoderBuffer,b=minimalisticAssert,v=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],w=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(v),_=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function E(x,T){var C={};this._baseState=C,C.enc=x,C.parent=T||null,C.children=null,C.tag=null,C.args=null,C.reverseArgs=null,C.choice=null,C.optional=!1,C.any=!1,C.obj=!1,C.use=null,C.useDecoder=null,C.key=null,C.default=null,C.explicit=null,C.implicit=null,C.contains=null,C.parent||(C.children=[],this._wrap())}node=E;var S=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];return E.prototype.clone=function(){var T=this._baseState,C={};S.forEach(function(D){C[D]=T[D]});var O=new this.constructor(C.parent);return O._baseState=C,O},E.prototype._wrap=function(){var T=this._baseState;w.forEach(function(C){this[C]=function(){var D=new this.constructor(this);return T.children.push(D),D[C].apply(D,arguments)}},this)},E.prototype._init=function(T){var C=this._baseState;b(C.parent===null),T.call(this),C.children=C.children.filter(function(O){return O._baseState.parent===this},this),b.equal(C.children.length,1,"Root node can have only one child")},E.prototype._useArgs=function(T){var C=this._baseState,O=T.filter(function(D){return D instanceof this.constructor},this);T=T.filter(function(D){return!(D instanceof this.constructor)},this),O.length!==0&&(b(C.children===null),C.children=O,O.forEach(function(D){D._baseState.parent=this},this)),T.length!==0&&(b(C.args===null),C.args=T,C.reverseArgs=T.map(function(D){if(typeof D!="object"||D.constructor!==Object)return D;var U={};return Object.keys(D).forEach(function(te){te==(te|0)&&(te|=0);var X=D[te];U[X]=te}),U}))},_.forEach(function(x){E.prototype[x]=function(){var C=this._baseState;throw new Error(x+" not implemented for encoding: "+C.enc)}}),v.forEach(function(x){E.prototype[x]=function(){var C=this._baseState,O=Array.prototype.slice.call(arguments);return b(C.tag===null),C.tag=x,this._useArgs(O),this}}),E.prototype.use=function(T){b(T);var C=this._baseState;return b(C.use===null),C.use=T,this},E.prototype.optional=function(){var T=this._baseState;return T.optional=!0,this},E.prototype.def=function(T){var C=this._baseState;return b(C.default===null),C.default=T,C.optional=!0,this},E.prototype.explicit=function(T){var C=this._baseState;return b(C.explicit===null&&C.implicit===null),C.explicit=T,this},E.prototype.implicit=function(T){var C=this._baseState;return b(C.explicit===null&&C.implicit===null),C.implicit=T,this},E.prototype.obj=function(){var T=this._baseState,C=Array.prototype.slice.call(arguments);return T.obj=!0,C.length!==0&&this._useArgs(C),this},E.prototype.key=function(T){var C=this._baseState;return b(C.key===null),C.key=T,this},E.prototype.any=function(){var T=this._baseState;return T.any=!0,this},E.prototype.choice=function(T){var C=this._baseState;return b(C.choice===null),C.choice=T,this._useArgs(Object.keys(T).map(function(O){return T[O]})),this},E.prototype.contains=function(T){var C=this._baseState;return b(C.use===null),C.contains=T,this},E.prototype._decode=function(T,C){var O=this._baseState;if(O.parent===null)return T.wrapResult(O.children[0]._decode(T,C));var D=O.default,U=!0,te=null;if(O.key!==null&&(te=T.enterKey(O.key)),O.optional){var X=null;if(O.explicit!==null?X=O.explicit:O.implicit!==null?X=O.implicit:O.tag!==null&&(X=O.tag),X===null&&!O.any){var ie=T.save();try{O.choice===null?this._decodeGeneric(O.tag,T,C):this._decodeChoice(T,C),U=!0}catch{U=!1}T.restore(ie)}else if(U=this._peekTag(T,X,O.any),T.isError(U))return U}var ee;if(O.obj&&U&&(ee=T.enterObject()),U){if(O.explicit!==null){var ae=this._decodeTag(T,O.explicit);if(T.isError(ae))return ae;T=ae}var de=T.offset;if(O.use===null&&O.choice===null){if(O.any)var ie=T.save();var Se=this._decodeTag(T,O.implicit!==null?O.implicit:O.tag,O.any);if(T.isError(Se))return Se;O.any?D=T.raw(ie):T=Se}if(C&&C.track&&O.tag!==null&&C.track(T.path(),de,T.length,"tagged"),C&&C.track&&O.tag!==null&&C.track(T.path(),T.offset,T.length,"content"),O.any?D=D:O.choice===null?D=this._decodeGeneric(O.tag,T,C):D=this._decodeChoice(T,C),T.isError(D))return D;if(!O.any&&O.choice===null&&O.children!==null&&O.children.forEach(function(Ie){Ie._decode(T,C)}),O.contains&&(O.tag==="octstr"||O.tag==="bitstr")){var ve=new h(D);D=this._getUse(O.contains,T._reporterState.obj)._decode(ve,C)}}return O.obj&&U&&(D=T.leaveObject(ee)),O.key!==null&&(D!==null||U===!0)?T.leaveKey(te,O.key,D):te!==null&&T.exitKey(te),D},E.prototype._decodeGeneric=function(T,C,O){var D=this._baseState;return T==="seq"||T==="set"?null:T==="seqof"||T==="setof"?this._decodeList(C,T,D.args[0],O):/str$/.test(T)?this._decodeStr(C,T,O):T==="objid"&&D.args?this._decodeObjid(C,D.args[0],D.args[1],O):T==="objid"?this._decodeObjid(C,null,null,O):T==="gentime"||T==="utctime"?this._decodeTime(C,T,O):T==="null_"?this._decodeNull(C,O):T==="bool"?this._decodeBool(C,O):T==="objDesc"?this._decodeStr(C,T,O):T==="int"||T==="enum"?this._decodeInt(C,D.args&&D.args[0],O):D.use!==null?this._getUse(D.use,C._reporterState.obj)._decode(C,O):C.error("unknown tag: "+T)},E.prototype._getUse=function(T,C){var O=this._baseState;return O.useDecoder=this._use(T,C),b(O.useDecoder._baseState.parent===null),O.useDecoder=O.useDecoder._baseState.children[0],O.implicit!==O.useDecoder._baseState.implicit&&(O.useDecoder=O.useDecoder.clone(),O.useDecoder._baseState.implicit=O.implicit),O.useDecoder},E.prototype._decodeChoice=function(T,C){var O=this._baseState,D=null,U=!1;return Object.keys(O.choice).some(function(te){var X=T.save(),ie=O.choice[te];try{var ee=ie._decode(T,C);if(T.isError(ee))return!1;D={type:te,value:ee},U=!0}catch{return T.restore(X),!1}return!0},this),U?D:T.error("Choice not matched")},E.prototype._createEncoderBuffer=function(T){return new u(T,this.reporter)},E.prototype._encode=function(T,C,O){var D=this._baseState;if(!(D.default!==null&&D.default===T)){var U=this._encodeValue(T,C,O);if(U!==void 0&&!this._skipDefault(U,C,O))return U}},E.prototype._encodeValue=function(T,C,O){var D=this._baseState;if(D.parent===null)return D.children[0]._encode(T,C||new y);var ie=null;if(this.reporter=C,D.optional&&T===void 0)if(D.default!==null)T=D.default;else return;var U=null,te=!1;if(D.any)ie=this._createEncoderBuffer(T);else if(D.choice)ie=this._encodeChoice(T,C);else if(D.contains)U=this._getUse(D.contains,O)._encode(T,C),te=!0;else if(D.children)U=D.children.map(function(de){if(de._baseState.tag==="null_")return de._encode(null,C,T);if(de._baseState.key===null)return C.error("Child should have a key");var Se=C.enterKey(de._baseState.key);if(typeof T!="object")return C.error("Child expected, but input is not object");var ve=de._encode(T[de._baseState.key],C,T);return C.leaveKey(Se),ve},this).filter(function(de){return de}),U=this._createEncoderBuffer(U);else if(D.tag==="seqof"||D.tag==="setof"){if(!(D.args&&D.args.length===1))return C.error("Too many args for : "+D.tag);if(!Array.isArray(T))return C.error("seqof/setof, but data is not Array");var X=this.clone();X._baseState.implicit=null,U=this._createEncoderBuffer(T.map(function(de){var Se=this._baseState;return this._getUse(Se.args[0],T)._encode(de,C)},X))}else D.use!==null?ie=this._getUse(D.use,O)._encode(T,C):(U=this._encodePrimitive(D.tag,T),te=!0);var ie;if(!D.any&&D.choice===null){var ee=D.implicit!==null?D.implicit:D.tag,ae=D.implicit===null?"universal":"context";ee===null?D.use===null&&C.error("Tag could be omitted only for .use()"):D.use===null&&(ie=this._encodeComposite(ee,te,ae,U))}return D.explicit!==null&&(ie=this._encodeComposite(D.explicit,!1,"context",ie)),ie},E.prototype._encodeChoice=function(T,C){var O=this._baseState,D=O.choice[T.type];return D||b(!1,T.type+" not found in "+JSON.stringify(Object.keys(O.choice))),D._encode(T.value,C)},E.prototype._encodePrimitive=function(T,C){var O=this._baseState;if(/str$/.test(T))return this._encodeStr(C,T);if(T==="objid"&&O.args)return this._encodeObjid(C,O.reverseArgs[0],O.args[1]);if(T==="objid")return this._encodeObjid(C,null,null);if(T==="gentime"||T==="utctime")return this._encodeTime(C,T);if(T==="null_")return this._encodeNull();if(T==="int"||T==="enum")return this._encodeInt(C,O.args&&O.reverseArgs[0]);if(T==="bool")return this._encodeBool(C);if(T==="objDesc")return this._encodeStr(C,T);throw new Error("Unsupported tag: "+T)},E.prototype._isNumstr=function(T){return/^[0-9 ]*$/.test(T)},E.prototype._isPrintstr=function(T){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(T)},node}var hasRequiredBase;function requireBase(){return hasRequiredBase||(hasRequiredBase=1,function(y){var u=y;u.Reporter=reporter.Reporter,u.DecoderBuffer=requireBuffer().DecoderBuffer,u.EncoderBuffer=requireBuffer().EncoderBuffer,u.Node=requireNode()}(base)),base}var constants={},der={},hasRequiredDer$2;function requireDer$2(){return hasRequiredDer$2||(hasRequiredDer$2=1,function(y){var u=requireConstants();y.tagClass={0:"universal",1:"application",2:"context",3:"private"},y.tagClassByName=u._reverse(y.tagClass),y.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},y.tagByName=u._reverse(y.tag)}(der)),der}var hasRequiredConstants;function requireConstants(){return hasRequiredConstants||(hasRequiredConstants=1,function(y){var u=y;u._reverse=function(b){var v={};return Object.keys(b).forEach(function(w){(w|0)==w&&(w=w|0);var _=b[w];v[_]=w}),v},u.der=requireDer$2()}(constants)),constants}var decoders$1={},der_1$1,hasRequiredDer$1;function requireDer$1(){if(hasRequiredDer$1)return der_1$1;hasRequiredDer$1=1;var y=inherits_browserExports,u=requireAsn1(),h=u.base,b=u.bignum,v=u.constants.der;function w(x){this.enc="der",this.name=x.name,this.entity=x,this.tree=new _,this.tree._init(x.body)}der_1$1=w,w.prototype.decode=function(T,C){return T instanceof h.DecoderBuffer||(T=new h.DecoderBuffer(T,C)),this.tree._decode(T,C)};function _(x){h.Node.call(this,"der",x)}y(_,h.Node),_.prototype._peekTag=function(T,C,O){if(T.isEmpty())return!1;var D=T.save(),U=E(T,'Failed to peek tag: "'+C+'"');return T.isError(U)?U:(T.restore(D),U.tag===C||U.tagStr===C||U.tagStr+"of"===C||O)},_.prototype._decodeTag=function(T,C,O){var D=E(T,'Failed to decode tag of "'+C+'"');if(T.isError(D))return D;var U=S(T,D.primitive,'Failed to get length of "'+C+'"');if(T.isError(U))return U;if(!O&&D.tag!==C&&D.tagStr!==C&&D.tagStr+"of"!==C)return T.error('Failed to match tag: "'+C+'"');if(D.primitive||U!==null)return T.skip(U,'Failed to match body of: "'+C+'"');var te=T.save(),X=this._skipUntilEnd(T,'Failed to skip indefinite length body: "'+this.tag+'"');return T.isError(X)?X:(U=T.offset-te.offset,T.restore(te),T.skip(U,'Failed to match body of: "'+C+'"'))},_.prototype._skipUntilEnd=function(T,C){for(;;){var O=E(T,C);if(T.isError(O))return O;var D=S(T,O.primitive,C);if(T.isError(D))return D;var U;if(O.primitive||D!==null?U=T.skip(D):U=this._skipUntilEnd(T,C),T.isError(U))return U;if(O.tagStr==="end")break}},_.prototype._decodeList=function(T,C,O,D){for(var U=[];!T.isEmpty();){var te=this._peekTag(T,"end");if(T.isError(te))return te;var X=O.decode(T,"der",D);if(T.isError(X)&&te)break;U.push(X)}return U},_.prototype._decodeStr=function(T,C){if(C==="bitstr"){var O=T.readUInt8();return T.isError(O)?O:{unused:O,data:T.raw()}}else if(C==="bmpstr"){var D=T.raw();if(D.length%2===1)return T.error("Decoding of string type: bmpstr length mismatch");for(var U="",te=0;te<D.length/2;te++)U+=String.fromCharCode(D.readUInt16BE(te*2));return U}else if(C==="numstr"){var X=T.raw().toString("ascii");return this._isNumstr(X)?X:T.error("Decoding of string type: numstr unsupported characters")}else{if(C==="octstr")return T.raw();if(C==="objDesc")return T.raw();if(C==="printstr"){var ie=T.raw().toString("ascii");return this._isPrintstr(ie)?ie:T.error("Decoding of string type: printstr unsupported characters")}else return/str$/.test(C)?T.raw().toString():T.error("Decoding of string type: "+C+" unsupported")}},_.prototype._decodeObjid=function(T,C,O){for(var D,U=[],te=0;!T.isEmpty();){var X=T.readUInt8();te<<=7,te|=X&127,X&128||(U.push(te),te=0)}X&128&&U.push(te);var ie=U[0]/40|0,ee=U[0]%40;if(O?D=U:D=[ie,ee].concat(U.slice(1)),C){var ae=C[D.join(" ")];ae===void 0&&(ae=C[D.join(".")]),ae!==void 0&&(D=ae)}return D},_.prototype._decodeTime=function(T,C){var O=T.raw().toString();if(C==="gentime")var D=O.slice(0,4)|0,U=O.slice(4,6)|0,te=O.slice(6,8)|0,X=O.slice(8,10)|0,ie=O.slice(10,12)|0,ee=O.slice(12,14)|0;else if(C==="utctime"){var D=O.slice(0,2)|0,U=O.slice(2,4)|0,te=O.slice(4,6)|0,X=O.slice(6,8)|0,ie=O.slice(8,10)|0,ee=O.slice(10,12)|0;D<70?D=2e3+D:D=1900+D}else return T.error("Decoding "+C+" time is not supported yet");return Date.UTC(D,U-1,te,X,ie,ee,0)},_.prototype._decodeNull=function(T){return null},_.prototype._decodeBool=function(T){var C=T.readUInt8();return T.isError(C)?C:C!==0},_.prototype._decodeInt=function(T,C){var O=T.raw(),D=new b(O);return C&&(D=C[D.toString(10)]||D),D},_.prototype._use=function(T,C){return typeof T=="function"&&(T=T(C)),T._getDecoder("der").tree};function E(x,T){var C=x.readUInt8(T);if(x.isError(C))return C;var O=v.tagClass[C>>6],D=(C&32)===0;if((C&31)===31){var U=C;for(C=0;(U&128)===128;){if(U=x.readUInt8(T),x.isError(U))return U;C<<=7,C|=U&127}}else C&=31;var te=v.tag[C];return{cls:O,primitive:D,tag:C,tagStr:te}}function S(x,T,C){var O=x.readUInt8(C);if(x.isError(O))return O;if(!T&&O===128)return null;if(!(O&128))return O;var D=O&127;if(D>4)return x.error("length octect is too long");O=0;for(var U=0;U<D;U++){O<<=8;var te=x.readUInt8(C);if(x.isError(te))return te;O|=te}return O}return der_1$1}var pem$1,hasRequiredPem$1;function requirePem$1(){if(hasRequiredPem$1)return pem$1;hasRequiredPem$1=1;var y=inherits_browserExports,u=dist.Buffer,h=requireDer$1();function b(v){h.call(this,v),this.enc="pem"}return y(b,h),pem$1=b,b.prototype.decode=function(w,_){for(var E=w.toString().split(/[\r\n]+/g),S=_.label.toUpperCase(),x=/^-----(BEGIN|END) ([^-]+)-----$/,T=-1,C=-1,O=0;O<E.length;O++){var D=E[O].match(x);if(D!==null&&D[2]===S)if(T===-1){if(D[1]!=="BEGIN")break;T=O}else{if(D[1]!=="END")break;C=O;break}}if(T===-1||C===-1)throw new Error("PEM section not found for: "+S);var U=E.slice(T+1,C).join("");U.replace(/[^a-z0-9\+\/=]+/gi,"");var te=new u(U,"base64");return h.prototype.decode.call(this,te,_)},pem$1}var hasRequiredDecoders;function requireDecoders(){return hasRequiredDecoders||(hasRequiredDecoders=1,function(y){var u=y;u.der=requireDer$1(),u.pem=requirePem$1()}(decoders$1)),decoders$1}var encoders={},der_1,hasRequiredDer;function requireDer(){if(hasRequiredDer)return der_1;hasRequiredDer=1;var y=inherits_browserExports,u=dist.Buffer,h=requireAsn1(),b=h.base,v=h.constants.der;function w(x){this.enc="der",this.name=x.name,this.entity=x,this.tree=new _,this.tree._init(x.body)}der_1=w,w.prototype.encode=function(T,C){return this.tree._encode(T,C).join()};function _(x){b.Node.call(this,"der",x)}y(_,b.Node),_.prototype._encodeComposite=function(T,C,O,D){var U=S(T,C,O,this.reporter);if(D.length<128){var ie=new u(2);return ie[0]=U,ie[1]=D.length,this._createEncoderBuffer([ie,D])}for(var te=1,X=D.length;X>=256;X>>=8)te++;var ie=new u(2+te);ie[0]=U,ie[1]=128|te;for(var X=1+te,ee=D.length;ee>0;X--,ee>>=8)ie[X]=ee&255;return this._createEncoderBuffer([ie,D])},_.prototype._encodeStr=function(T,C){if(C==="bitstr")return this._createEncoderBuffer([T.unused|0,T.data]);if(C==="bmpstr"){for(var O=new u(T.length*2),D=0;D<T.length;D++)O.writeUInt16BE(T.charCodeAt(D),D*2);return this._createEncoderBuffer(O)}else return C==="numstr"?this._isNumstr(T)?this._createEncoderBuffer(T):this.reporter.error("Encoding of string type: numstr supports only digits and space"):C==="printstr"?this._isPrintstr(T)?this._createEncoderBuffer(T):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"):/str$/.test(C)?this._createEncoderBuffer(T):C==="objDesc"?this._createEncoderBuffer(T):this.reporter.error("Encoding of string type: "+C+" unsupported")},_.prototype._encodeObjid=function(T,C,O){if(typeof T=="string"){if(!C)return this.reporter.error("string objid given, but no values map found");if(!C.hasOwnProperty(T))return this.reporter.error("objid not found in values map");T=C[T].split(/[\s\.]+/g);for(var D=0;D<T.length;D++)T[D]|=0}else if(Array.isArray(T)){T=T.slice();for(var D=0;D<T.length;D++)T[D]|=0}if(!Array.isArray(T))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(T));if(!O){if(T[1]>=40)return this.reporter.error("Second objid identifier OOB");T.splice(0,2,T[0]*40+T[1])}for(var U=0,D=0;D<T.length;D++){var te=T[D];for(U++;te>=128;te>>=7)U++}for(var X=new u(U),ie=X.length-1,D=T.length-1;D>=0;D--){var te=T[D];for(X[ie--]=te&127;(te>>=7)>0;)X[ie--]=128|te&127}return this._createEncoderBuffer(X)};function E(x){return x<10?"0"+x:x}_.prototype._encodeTime=function(T,C){var O,D=new Date(T);return C==="gentime"?O=[E(D.getFullYear()),E(D.getUTCMonth()+1),E(D.getUTCDate()),E(D.getUTCHours()),E(D.getUTCMinutes()),E(D.getUTCSeconds()),"Z"].join(""):C==="utctime"?O=[E(D.getFullYear()%100),E(D.getUTCMonth()+1),E(D.getUTCDate()),E(D.getUTCHours()),E(D.getUTCMinutes()),E(D.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+C+" time is not supported yet"),this._encodeStr(O,"octstr")},_.prototype._encodeNull=function(){return this._createEncoderBuffer("")},_.prototype._encodeInt=function(T,C){if(typeof T=="string"){if(!C)return this.reporter.error("String int or enum given, but no values map");if(!C.hasOwnProperty(T))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(T));T=C[T]}if(typeof T!="number"&&!u.isBuffer(T)){var O=T.toArray();!T.sign&&O[0]&128&&O.unshift(0),T=new u(O)}if(u.isBuffer(T)){var D=T.length;T.length===0&&D++;var te=new u(D);return T.copy(te),T.length===0&&(te[0]=0),this._createEncoderBuffer(te)}if(T<128)return this._createEncoderBuffer(T);if(T<256)return this._createEncoderBuffer([0,T]);for(var D=1,U=T;U>=256;U>>=8)D++;for(var te=new Array(D),U=te.length-1;U>=0;U--)te[U]=T&255,T>>=8;return te[0]&128&&te.unshift(0),this._createEncoderBuffer(new u(te))},_.prototype._encodeBool=function(T){return this._createEncoderBuffer(T?255:0)},_.prototype._use=function(T,C){return typeof T=="function"&&(T=T(C)),T._getEncoder("der").tree},_.prototype._skipDefault=function(T,C,O){var D=this._baseState,U;if(D.default===null)return!1;var te=T.join();if(D.defaultBuffer===void 0&&(D.defaultBuffer=this._encodeValue(D.default,C,O).join()),te.length!==D.defaultBuffer.length)return!1;for(U=0;U<te.length;U++)if(te[U]!==D.defaultBuffer[U])return!1;return!0};function S(x,T,C,O){var D;if(x==="seqof"?x="seq":x==="setof"&&(x="set"),v.tagByName.hasOwnProperty(x))D=v.tagByName[x];else if(typeof x=="number"&&(x|0)===x)D=x;else return O.error("Unknown tag: "+x);return D>=31?O.error("Multi-octet tag encoding unsupported"):(T||(D|=32),D|=v.tagClassByName[C||"universal"]<<6,D)}return der_1}var pem,hasRequiredPem;function requirePem(){if(hasRequiredPem)return pem;hasRequiredPem=1;var y=inherits_browserExports,u=requireDer();function h(b){u.call(this,b),this.enc="pem"}return y(h,u),pem=h,h.prototype.encode=function(v,w){for(var _=u.prototype.encode.call(this,v),E=_.toString("base64"),S=["-----BEGIN "+w.label+"-----"],x=0;x<E.length;x+=64)S.push(E.slice(x,x+64));return S.push("-----END "+w.label+"-----"),S.join(`
47
+ `)},pem}var hasRequiredEncoders;function requireEncoders(){return hasRequiredEncoders||(hasRequiredEncoders=1,function(y){var u=y;u.der=requireDer(),u.pem=requirePem()}(encoders)),encoders}var hasRequiredAsn1;function requireAsn1(){return hasRequiredAsn1||(hasRequiredAsn1=1,function(y){var u=y;u.bignum=bnExports$1,u.define=requireApi().define,u.base=requireBase(),u.constants=requireConstants(),u.decoders=requireDecoders(),u.encoders=requireEncoders()}(asn1$2)),asn1$2}var asn=requireAsn1(),Time=asn.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),AttributeTypeValue=asn.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),AlgorithmIdentifier$1=asn.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())}),SubjectPublicKeyInfo=asn.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier$1),this.key("subjectPublicKey").bitstr())}),RelativeDistinguishedName=asn.define("RelativeDistinguishedName",function(){this.setof(AttributeTypeValue)}),RDNSequence=asn.define("RDNSequence",function(){this.seqof(RelativeDistinguishedName)}),Name=asn.define("Name",function(){this.choice({rdnSequence:this.use(RDNSequence)})}),Validity=asn.define("Validity",function(){this.seq().obj(this.key("notBefore").use(Time),this.key("notAfter").use(Time))}),Extension=asn.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),TBSCertificate=asn.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(AlgorithmIdentifier$1),this.key("issuer").use(Name),this.key("validity").use(Validity),this.key("subject").use(Name),this.key("subjectPublicKeyInfo").use(SubjectPublicKeyInfo),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(Extension).optional())}),X509Certificate=asn.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(TBSCertificate),this.key("signatureAlgorithm").use(AlgorithmIdentifier$1),this.key("signatureValue").bitstr())}),certificate=X509Certificate,asn1$1=requireAsn1();asn1$3.certificate=certificate;var RSAPrivateKey=asn1$1.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});asn1$3.RSAPrivateKey=RSAPrivateKey;var RSAPublicKey$1=asn1$1.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});asn1$3.RSAPublicKey=RSAPublicKey$1;var AlgorithmIdentifier=asn1$1.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),PublicKey$1=asn1$1.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPublicKey").bitstr())});asn1$3.PublicKey=PublicKey$1;var PrivateKeyInfo=asn1$1.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPrivateKey").octstr())});asn1$3.PrivateKey=PrivateKeyInfo;var EncryptedPrivateKeyInfo=asn1$1.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});asn1$3.EncryptedPrivateKey=EncryptedPrivateKeyInfo;var DSAPrivateKey=asn1$1.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});asn1$3.DSAPrivateKey=DSAPrivateKey;asn1$3.DSAparam=asn1$1.define("DSAparam",function(){this.int()});var ECParameters=asn1$1.define("ECParameters",function(){this.choice({namedCurve:this.objid()})}),ECPrivateKey=asn1$1.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(ECParameters),this.key("publicKey").optional().explicit(1).bitstr())});asn1$3.ECPrivateKey=ECPrivateKey;asn1$3.signature=asn1$1.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())});const require$$1={"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"};var findProc=/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m,startRegex=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m,fullRegex=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m,evp=evp_bytestokey,ciphers$1=browser$5,Buffer$6=safeBufferExports$1.Buffer,fixProc$1=function(y,u){var h=y.toString(),b=h.match(findProc),v;if(b){var _="aes"+b[1],E=Buffer$6.from(b[2],"hex"),S=Buffer$6.from(b[3].replace(/[\r\n]/g,""),"base64"),x=evp(u,E.slice(0,8),parseInt(b[1],10)).key,T=[],C=ciphers$1.createDecipheriv(_,x,E);T.push(C.update(S)),T.push(C.final()),v=Buffer$6.concat(T)}else{var w=h.match(fullRegex);v=Buffer$6.from(w[2].replace(/[\r\n]/g,""),"base64")}var O=h.match(startRegex)[1];return{tag:O,data:v}},asn1=asn1$3,aesid=require$$1,fixProc=fixProc$1,ciphers=browser$5,compat=browser$7,Buffer$5=safeBufferExports$1.Buffer;function decrypt(y,u){var h=y.algorithm.decrypt.kde.kdeparams.salt,b=parseInt(y.algorithm.decrypt.kde.kdeparams.iters.toString(),10),v=aesid[y.algorithm.decrypt.cipher.algo.join(".")],w=y.algorithm.decrypt.cipher.iv,_=y.subjectPrivateKey,E=parseInt(v.split("-")[1],10)/8,S=compat.pbkdf2Sync(u,h,b,E,"sha1"),x=ciphers.createDecipheriv(v,S,w),T=[];return T.push(x.update(_)),T.push(x.final()),Buffer$5.concat(T)}function parseKeys$2(y){var u;typeof y=="object"&&!Buffer$5.isBuffer(y)&&(u=y.passphrase,y=y.key),typeof y=="string"&&(y=Buffer$5.from(y));var h=fixProc(y,u),b=h.tag,v=h.data,w,_;switch(b){case"CERTIFICATE":_=asn1.certificate.decode(v,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(_||(_=asn1.PublicKey.decode(v,"der")),w=_.algorithm.algorithm.join("."),w){case"1.2.840.113549.1.1.1":return asn1.RSAPublicKey.decode(_.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return _.subjectPrivateKey=_.subjectPublicKey,{type:"ec",data:_};case"1.2.840.10040.4.1":return _.algorithm.params.pub_key=asn1.DSAparam.decode(_.subjectPublicKey.data,"der"),{type:"dsa",data:_.algorithm.params};default:throw new Error("unknown key id "+w)}case"ENCRYPTED PRIVATE KEY":v=asn1.EncryptedPrivateKey.decode(v,"der"),v=decrypt(v,u);case"PRIVATE KEY":switch(_=asn1.PrivateKey.decode(v,"der"),w=_.algorithm.algorithm.join("."),w){case"1.2.840.113549.1.1.1":return asn1.RSAPrivateKey.decode(_.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:_.algorithm.curve,privateKey:asn1.ECPrivateKey.decode(_.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return _.algorithm.params.priv_key=asn1.DSAparam.decode(_.subjectPrivateKey,"der"),{type:"dsa",params:_.algorithm.params};default:throw new Error("unknown key id "+w)}case"RSA PUBLIC KEY":return asn1.RSAPublicKey.decode(v,"der");case"RSA PRIVATE KEY":return asn1.RSAPrivateKey.decode(v,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:asn1.DSAPrivateKey.decode(v,"der")};case"EC PRIVATE KEY":return v=asn1.ECPrivateKey.decode(v,"der"),{curve:v.parameters.value,privateKey:v.privateKey};default:throw new Error("unknown key type "+b)}}parseKeys$2.signature=asn1.signature;var parseAsn1=parseKeys$2;const require$$4={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"};var hasRequiredSign;function requireSign(){if(hasRequiredSign)return sign$2.exports;hasRequiredSign=1;var y=safeBufferExports$1.Buffer,u=browser$8,h=browserifyRsa,b=requireElliptic().ec,v=bnExports,w=parseAsn1,_=require$$4,E=1;function S(ie,ee,ae,de,Se){var ve=w(ee);if(ve.curve){if(de!=="ecdsa"&&de!=="ecdsa/rsa")throw new Error("wrong private key type");return x(ie,ve)}else if(ve.type==="dsa"){if(de!=="dsa")throw new Error("wrong private key type");return T(ie,ve,ae)}if(de!=="rsa"&&de!=="ecdsa/rsa")throw new Error("wrong private key type");if(ee.padding!==void 0&&ee.padding!==E)throw new Error("illegal or unsupported padding mode");ie=y.concat([Se,ie]);for(var Pe=ve.modulus.byteLength(),Ie=[0,1];ie.length+Ie.length+1<Pe;)Ie.push(255);Ie.push(0);for(var Ee=-1;++Ee<ie.length;)Ie.push(ie[Ee]);var De=h(Ie,ve);return De}function x(ie,ee){var ae=_[ee.curve.join(".")];if(!ae)throw new Error("unknown curve "+ee.curve.join("."));var de=new b(ae),Se=de.keyFromPrivate(ee.privateKey),ve=Se.sign(ie);return y.from(ve.toDER())}function T(ie,ee,ae){for(var de=ee.params.priv_key,Se=ee.params.p,ve=ee.params.q,Pe=ee.params.g,Ie=new v(0),Ee,De=D(ie,ve).mod(ve),be=!1,B=O(de,ve,ie,ae);be===!1;)Ee=te(ve,B,ae),Ie=X(Pe,Ee,Se,ve),be=Ee.invm(ve).imul(De.add(de.mul(Ie))).mod(ve),be.cmpn(0)===0&&(be=!1,Ie=new v(0));return C(Ie,be)}function C(ie,ee){ie=ie.toArray(),ee=ee.toArray(),ie[0]&128&&(ie=[0].concat(ie)),ee[0]&128&&(ee=[0].concat(ee));var ae=ie.length+ee.length+4,de=[48,ae,2,ie.length];return de=de.concat(ie,[2,ee.length],ee),y.from(de)}function O(ie,ee,ae,de){if(ie=y.from(ie.toArray()),ie.length<ee.byteLength()){var Se=y.alloc(ee.byteLength()-ie.length);ie=y.concat([Se,ie])}var ve=ae.length,Pe=U(ae,ee),Ie=y.alloc(ve);Ie.fill(1);var Ee=y.alloc(ve);return Ee=u(de,Ee).update(Ie).update(y.from([0])).update(ie).update(Pe).digest(),Ie=u(de,Ee).update(Ie).digest(),Ee=u(de,Ee).update(Ie).update(y.from([1])).update(ie).update(Pe).digest(),Ie=u(de,Ee).update(Ie).digest(),{k:Ee,v:Ie}}function D(ie,ee){var ae=new v(ie),de=(ie.length<<3)-ee.bitLength();return de>0&&ae.ishrn(de),ae}function U(ie,ee){ie=D(ie,ee),ie=ie.mod(ee);var ae=y.from(ie.toArray());if(ae.length<ee.byteLength()){var de=y.alloc(ee.byteLength()-ae.length);ae=y.concat([de,ae])}return ae}function te(ie,ee,ae){var de,Se;do{for(de=y.alloc(0);de.length*8<ie.bitLength();)ee.v=u(ae,ee.k).update(ee.v).digest(),de=y.concat([de,ee.v]);Se=D(de,ie),ee.k=u(ae,ee.k).update(ee.v).update(y.from([0])).digest(),ee.v=u(ae,ee.k).update(ee.v).digest()}while(Se.cmp(ie)!==-1);return Se}function X(ie,ee,ae,de){return ie.toRed(v.mont(ae)).redPow(ee).fromRed().mod(de)}return sign$2.exports=S,sign$2.exports.getKey=O,sign$2.exports.makeKey=te,sign$2.exports}var verify_1,hasRequiredVerify;function requireVerify(){if(hasRequiredVerify)return verify_1;hasRequiredVerify=1;var y=safeBufferExports$1.Buffer,u=bnExports,h=requireElliptic().ec,b=parseAsn1,v=require$$4;function w(x,T,C,O,D){var U=b(C);if(U.type==="ec"){if(O!=="ecdsa"&&O!=="ecdsa/rsa")throw new Error("wrong public key type");return _(x,T,U)}else if(U.type==="dsa"){if(O!=="dsa")throw new Error("wrong public key type");return E(x,T,U)}if(O!=="rsa"&&O!=="ecdsa/rsa")throw new Error("wrong public key type");T=y.concat([D,T]);for(var te=U.modulus.byteLength(),X=[1],ie=0;T.length+X.length+2<te;)X.push(255),ie+=1;X.push(0);for(var ee=-1;++ee<T.length;)X.push(T[ee]);X=y.from(X);var ae=u.mont(U.modulus);x=new u(x).toRed(ae),x=x.redPow(new u(U.publicExponent)),x=y.from(x.fromRed().toArray());var de=ie<8?1:0;for(te=Math.min(x.length,X.length),x.length!==X.length&&(de=1),ee=-1;++ee<te;)de|=x[ee]^X[ee];return de===0}function _(x,T,C){var O=v[C.data.algorithm.curve.join(".")];if(!O)throw new Error("unknown curve "+C.data.algorithm.curve.join("."));var D=new h(O),U=C.data.subjectPrivateKey.data;return D.verify(T,x,U)}function E(x,T,C){var O=C.data.p,D=C.data.q,U=C.data.g,te=C.data.pub_key,X=b.signature.decode(x,"der"),ie=X.s,ee=X.r;S(ie,D),S(ee,D);var ae=u.mont(O),de=ie.invm(D),Se=U.toRed(ae).redPow(new u(T).mul(de).mod(D)).fromRed().mul(te.toRed(ae).redPow(ee.mul(de).mod(D)).fromRed()).mod(O).mod(D);return Se.cmp(ee)===0}function S(x,T){if(x.cmpn(0)<=0)throw new Error("invalid sig");if(x.cmp(T)>=0)throw new Error("invalid sig")}return verify_1=w,verify_1}var browser$3,hasRequiredBrowser$1;function requireBrowser$1(){if(hasRequiredBrowser$1)return browser$3;hasRequiredBrowser$1=1;var y=safeBufferExports$1.Buffer,u=browser$9,h=readableBrowserExports,b=inherits_browserExports,v=requireSign(),w=requireVerify(),_=require$$6;Object.keys(_).forEach(function(C){_[C].id=y.from(_[C].id,"hex"),_[C.toLowerCase()]=_[C]});function E(C){h.Writable.call(this);var O=_[C];if(!O)throw new Error("Unknown message digest");this._hashType=O.hash,this._hash=u(O.hash),this._tag=O.id,this._signType=O.sign}b(E,h.Writable),E.prototype._write=function(O,D,U){this._hash.update(O),U()},E.prototype.update=function(O,D){return this._hash.update(typeof O=="string"?y.from(O,D):O),this},E.prototype.sign=function(O,D){this.end();var U=this._hash.digest(),te=v(U,O,this._hashType,this._signType,this._tag);return D?te.toString(D):te};function S(C){h.Writable.call(this);var O=_[C];if(!O)throw new Error("Unknown message digest");this._hash=u(O.hash),this._tag=O.id,this._signType=O.sign}b(S,h.Writable),S.prototype._write=function(O,D,U){this._hash.update(O),U()},S.prototype.update=function(O,D){return this._hash.update(typeof O=="string"?y.from(O,D):O),this},S.prototype.verify=function(O,D,U){var te=typeof D=="string"?y.from(D,U):D;this.end();var X=this._hash.digest();return w(te,X,O,this._signType,this._tag)};function x(C){return new E(C)}function T(C){return new S(C)}return browser$3={Sign:x,Verify:T,createSign:x,createVerify:T},browser$3}var browser$2,hasRequiredBrowser;function requireBrowser(){if(hasRequiredBrowser)return browser$2;hasRequiredBrowser=1;var y=requireElliptic(),u=bnExports$1;browser$2=function(_){return new b(_)};var h={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};h.p224=h.secp224r1,h.p256=h.secp256r1=h.prime256v1,h.p192=h.secp192r1=h.prime192v1,h.p384=h.secp384r1,h.p521=h.secp521r1;function b(w){this.curveType=h[w],this.curveType||(this.curveType={name:w}),this.curve=new y.ec(this.curveType.name),this.keys=void 0}b.prototype.generateKeys=function(w,_){return this.keys=this.curve.genKeyPair(),this.getPublicKey(w,_)},b.prototype.computeSecret=function(w,_,E){_=_||"utf8",Buffer$C.isBuffer(w)||(w=new Buffer$C(w,_));var S=this.curve.keyFromPublic(w).getPublic(),x=S.mul(this.keys.getPrivate()).getX();return v(x,E,this.curveType.byteLength)},b.prototype.getPublicKey=function(w,_){var E=this.keys.getPublic(_==="compressed",!0);return _==="hybrid"&&(E[E.length-1]%2?E[0]=7:E[0]=6),v(E,w)},b.prototype.getPrivateKey=function(w){return v(this.keys.getPrivate(),w)},b.prototype.setPublicKey=function(w,_){return _=_||"utf8",Buffer$C.isBuffer(w)||(w=new Buffer$C(w,_)),this.keys._importPublic(w),this},b.prototype.setPrivateKey=function(w,_){_=_||"utf8",Buffer$C.isBuffer(w)||(w=new Buffer$C(w,_));var E=new u(w);return E=E.toString(16),this.keys=this.curve.genKeyPair(),this.keys._importPrivate(E),this};function v(w,_,E){Array.isArray(w)||(w=w.toArray());var S=new Buffer$C(w);if(E&&S.length<E){var x=new Buffer$C(E-S.length);x.fill(0),S=Buffer$C.concat([x,S])}return _?S.toString(_):S}return browser$2}var browser$1={},createHash$2=browser$9,Buffer$4=safeBufferExports$1.Buffer,mgf$2=function(y,u){for(var h=Buffer$4.alloc(0),b=0,v;h.length<u;)v=i2ops(b++),h=Buffer$4.concat([h,createHash$2("sha1").update(y).update(v).digest()]);return h.slice(0,u)};function i2ops(y){var u=Buffer$4.allocUnsafe(4);return u.writeUInt32BE(y,0),u}var xor$2=function y(u,h){for(var b=u.length,v=-1;++v<b;)u[v]^=h[v];return u},BN$2=bnExports$1,Buffer$3=safeBufferExports$1.Buffer;function withPublic$2(y,u){return Buffer$3.from(y.toRed(BN$2.mont(u.modulus)).redPow(new BN$2(u.publicExponent)).fromRed().toArray())}var withPublic_1=withPublic$2,parseKeys$1=parseAsn1,randomBytes=browserExports,createHash$1=browser$9,mgf$1=mgf$2,xor$1=xor$2,BN$1=bnExports$1,withPublic$1=withPublic_1,crt$1=browserifyRsa,Buffer$2=safeBufferExports$1.Buffer,publicEncrypt=function y(u,h,b){var v;u.padding?v=u.padding:b?v=1:v=4;var w=parseKeys$1(u),_;if(v===4)_=oaep$1(w,h);else if(v===1)_=pkcs1$1(w,h,b);else if(v===3){if(_=new BN$1(h),_.cmp(w.modulus)>=0)throw new Error("data too long for modulus")}else throw new Error("unknown padding");return b?crt$1(_,w):withPublic$1(_,w)};function oaep$1(y,u){var h=y.modulus.byteLength(),b=u.length,v=createHash$1("sha1").update(Buffer$2.alloc(0)).digest(),w=v.length,_=2*w;if(b>h-_-2)throw new Error("message too long");var E=Buffer$2.alloc(h-b-_-2),S=h-w-1,x=randomBytes(w),T=xor$1(Buffer$2.concat([v,E,Buffer$2.alloc(1,1),u],S),mgf$1(x,S)),C=xor$1(x,mgf$1(T,w));return new BN$1(Buffer$2.concat([Buffer$2.alloc(1),C,T],h))}function pkcs1$1(y,u,h){var b=u.length,v=y.modulus.byteLength();if(b>v-11)throw new Error("message too long");var w;return h?w=Buffer$2.alloc(v-b-3,255):w=nonZero(v-b-3),new BN$1(Buffer$2.concat([Buffer$2.from([0,h?1:2]),w,Buffer$2.alloc(1),u],v))}function nonZero(y){for(var u=Buffer$2.allocUnsafe(y),h=0,b=randomBytes(y*2),v=0,w;h<y;)v===b.length&&(b=randomBytes(y*2),v=0),w=b[v++],w&&(u[h++]=w);return u}var parseKeys=parseAsn1,mgf=mgf$2,xor=xor$2,BN=bnExports$1,crt=browserifyRsa,createHash=browser$9,withPublic=withPublic_1,Buffer$1=safeBufferExports$1.Buffer,privateDecrypt=function y(u,h,b){var v;u.padding?v=u.padding:b?v=1:v=4;var w=parseKeys(u),_=w.modulus.byteLength();if(h.length>_||new BN(h).cmp(w.modulus)>=0)throw new Error("decryption error");var E;b?E=withPublic(new BN(h),w):E=crt(h,w);var S=Buffer$1.alloc(_-E.length);if(E=Buffer$1.concat([S,E],_),v===4)return oaep(w,E);if(v===1)return pkcs1(w,E,b);if(v===3)return E;throw new Error("unknown padding")};function oaep(y,u){var h=y.modulus.byteLength(),b=createHash("sha1").update(Buffer$1.alloc(0)).digest(),v=b.length;if(u[0]!==0)throw new Error("decryption error");var w=u.slice(1,v+1),_=u.slice(v+1),E=xor(w,mgf(_,v)),S=xor(_,mgf(E,h-v-1));if(compare(b,S.slice(0,v)))throw new Error("decryption error");for(var x=v;S[x]===0;)x++;if(S[x++]!==1)throw new Error("decryption error");return S.slice(x)}function pkcs1(y,u,h){for(var b=u.slice(0,2),v=2,w=0;u[v++]!==0;)if(v>=u.length){w++;break}var _=u.slice(2,v-1);if((b.toString("hex")!=="0002"&&!h||b.toString("hex")!=="0001"&&h)&&w++,_.length<8&&w++,w)throw new Error("decryption error");return u.slice(v)}function compare(y,u){y=Buffer$1.from(y),u=Buffer$1.from(u);var h=0,b=y.length;y.length!==u.length&&(h++,b=Math.min(y.length,u.length));for(var v=-1;++v<b;)h+=y[v]^u[v];return h}(function(y){y.publicEncrypt=publicEncrypt,y.privateDecrypt=privateDecrypt,y.privateEncrypt=function(h,b){return y.publicEncrypt(h,b,!0)},y.publicDecrypt=function(h,b){return y.privateDecrypt(h,b,!0)}})(browser$1);var browser={};function oldBrowser(){throw new Error(`secure random number generation not supported by this browser
48
+ use chrome, FireFox or Internet Explorer 11`)}var safeBuffer=safeBufferExports$1,randombytes=browserExports,Buffer=safeBuffer.Buffer,kBufferMaxLength=safeBuffer.kMaxLength,crypto$2=commonjsGlobal.crypto||commonjsGlobal.msCrypto,kMaxUint32=Math.pow(2,32)-1;function assertOffset(y,u){if(typeof y!="number"||y!==y)throw new TypeError("offset must be a number");if(y>kMaxUint32||y<0)throw new TypeError("offset must be a uint32");if(y>kBufferMaxLength||y>u)throw new RangeError("offset out of range")}function assertSize(y,u,h){if(typeof y!="number"||y!==y)throw new TypeError("size must be a number");if(y>kMaxUint32||y<0)throw new TypeError("size must be a uint32");if(y+u>h||y>kBufferMaxLength)throw new RangeError("buffer too small")}crypto$2&&crypto$2.getRandomValues||!process$1.browser?(browser.randomFill=randomFill,browser.randomFillSync=randomFillSync):(browser.randomFill=oldBrowser,browser.randomFillSync=oldBrowser);function randomFill(y,u,h,b){if(!Buffer.isBuffer(y)&&!(y instanceof commonjsGlobal.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if(typeof u=="function")b=u,u=0,h=y.length;else if(typeof h=="function")b=h,h=y.length-u;else if(typeof b!="function")throw new TypeError('"cb" argument must be a function');return assertOffset(u,y.length),assertSize(h,u,y.length),actualFill(y,u,h,b)}function actualFill(y,u,h,b){if(process$1.browser){var v=y.buffer,w=new Uint8Array(v,u,h);if(crypto$2.getRandomValues(w),b){process$1.nextTick(function(){b(null,y)});return}return y}if(b){randombytes(h,function(E,S){if(E)return b(E);S.copy(y,u),b(null,y)});return}var _=randombytes(h);return _.copy(y,u),y}function randomFillSync(y,u,h){if(typeof u>"u"&&(u=0),!Buffer.isBuffer(y)&&!(y instanceof commonjsGlobal.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');return assertOffset(u,y.length),h===void 0&&(h=y.length-u),assertSize(h,u,y.length),actualFill(y,u,h)}var hasRequiredCryptoBrowserify;function requireCryptoBrowserify(){if(hasRequiredCryptoBrowserify)return cryptoBrowserify;hasRequiredCryptoBrowserify=1,cryptoBrowserify.randomBytes=cryptoBrowserify.rng=cryptoBrowserify.pseudoRandomBytes=cryptoBrowserify.prng=browserExports,cryptoBrowserify.createHash=cryptoBrowserify.Hash=browser$9,cryptoBrowserify.createHmac=cryptoBrowserify.Hmac=browser$8;var y=algos,u=Object.keys(y),h=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(u);cryptoBrowserify.getHashes=function(){return h};var b=browser$7;cryptoBrowserify.pbkdf2=b.pbkdf2,cryptoBrowserify.pbkdf2Sync=b.pbkdf2Sync;var v=browser$6;cryptoBrowserify.Cipher=v.Cipher,cryptoBrowserify.createCipher=v.createCipher,cryptoBrowserify.Cipheriv=v.Cipheriv,cryptoBrowserify.createCipheriv=v.createCipheriv,cryptoBrowserify.Decipher=v.Decipher,cryptoBrowserify.createDecipher=v.createDecipher,cryptoBrowserify.Decipheriv=v.Decipheriv,cryptoBrowserify.createDecipheriv=v.createDecipheriv,cryptoBrowserify.getCiphers=v.getCiphers,cryptoBrowserify.listCiphers=v.listCiphers;var w=requireBrowser$2();cryptoBrowserify.DiffieHellmanGroup=w.DiffieHellmanGroup,cryptoBrowserify.createDiffieHellmanGroup=w.createDiffieHellmanGroup,cryptoBrowserify.getDiffieHellman=w.getDiffieHellman,cryptoBrowserify.createDiffieHellman=w.createDiffieHellman,cryptoBrowserify.DiffieHellman=w.DiffieHellman;var _=requireBrowser$1();cryptoBrowserify.createSign=_.createSign,cryptoBrowserify.Sign=_.Sign,cryptoBrowserify.createVerify=_.createVerify,cryptoBrowserify.Verify=_.Verify,cryptoBrowserify.createECDH=requireBrowser();var E=browser$1;cryptoBrowserify.publicEncrypt=E.publicEncrypt,cryptoBrowserify.privateEncrypt=E.privateEncrypt,cryptoBrowserify.publicDecrypt=E.publicDecrypt,cryptoBrowserify.privateDecrypt=E.privateDecrypt;var S=browser;return cryptoBrowserify.randomFill=S.randomFill,cryptoBrowserify.randomFillSync=S.randomFillSync,cryptoBrowserify.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join(`
49
+ `))},cryptoBrowserify.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6},cryptoBrowserify}var cryptoBrowserifyExports=requireCryptoBrowserify();const index=getDefaultExportFromCjs$1(cryptoBrowserifyExports),nodeCrypto=_mergeNamespaces({__proto__:null,default:index},[cryptoBrowserifyExports]);/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const _0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_3n=BigInt(3),_8n=BigInt(8),CURVE=Object.freeze({a:_0n,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:_1n,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),divNearest=(y,u)=>(y+u/_2n)/u,endo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(y){const{n:u}=CURVE,h=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),b=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),v=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),w=h,_=BigInt("0x100000000000000000000000000000000"),E=divNearest(w*y,u),S=divNearest(-b*y,u);let x=mod(y-E*h-S*v,u),T=mod(-E*b-S*w,u);const C=x>_,O=T>_;if(C&&(x=u-x),O&&(T=u-T),x>_||T>_)throw new Error("splitScalarEndo: Endomorphism failed, k="+y);return{k1neg:C,k1:x,k2neg:O,k2:T}}},fieldLen=32,groupLen=32,hashLen=32,compressedLen=fieldLen+1,uncompressedLen=2*fieldLen+1;function weierstrass(y){const{a:u,b:h}=CURVE,b=mod(y*y),v=mod(b*y);return mod(v+u*y+h)}const USE_ENDOMORPHISM=CURVE.a===_0n;class ShaError extends Error{constructor(u){super(u)}}function assertJacPoint(y){if(!(y instanceof JacobianPoint))throw new TypeError("JacobianPoint expected")}class JacobianPoint{constructor(u,h,b){this.x=u,this.y=h,this.z=b}static fromAffine(u){if(!(u instanceof Point))throw new TypeError("JacobianPoint#fromAffine: expected Point");return u.equals(Point.ZERO)?JacobianPoint.ZERO:new JacobianPoint(u.x,u.y,_1n)}static toAffineBatch(u){const h=invertBatch(u.map(b=>b.z));return u.map((b,v)=>b.toAffine(h[v]))}static normalizeZ(u){return JacobianPoint.toAffineBatch(u).map(JacobianPoint.fromAffine)}equals(u){assertJacPoint(u);const{x:h,y:b,z:v}=this,{x:w,y:_,z:E}=u,S=mod(v*v),x=mod(E*E),T=mod(h*x),C=mod(w*S),O=mod(mod(b*E)*x),D=mod(mod(_*v)*S);return T===C&&O===D}negate(){return new JacobianPoint(this.x,mod(-this.y),this.z)}double(){const{x:u,y:h,z:b}=this,v=mod(u*u),w=mod(h*h),_=mod(w*w),E=u+w,S=mod(_2n*(mod(E*E)-v-_)),x=mod(_3n*v),T=mod(x*x),C=mod(T-_2n*S),O=mod(x*(S-C)-_8n*_),D=mod(_2n*h*b);return new JacobianPoint(C,O,D)}add(u){assertJacPoint(u);const{x:h,y:b,z:v}=this,{x:w,y:_,z:E}=u;if(w===_0n||_===_0n)return this;if(h===_0n||b===_0n)return u;const S=mod(v*v),x=mod(E*E),T=mod(h*x),C=mod(w*S),O=mod(mod(b*E)*x),D=mod(mod(_*v)*S),U=mod(C-T),te=mod(D-O);if(U===_0n)return te===_0n?this.double():JacobianPoint.ZERO;const X=mod(U*U),ie=mod(U*X),ee=mod(T*X),ae=mod(te*te-ie-_2n*ee),de=mod(te*(ee-ae)-O*ie),Se=mod(v*E*U);return new JacobianPoint(ae,de,Se)}subtract(u){return this.add(u.negate())}multiplyUnsafe(u){const h=JacobianPoint.ZERO;if(typeof u=="bigint"&&u===_0n)return h;let b=normalizeScalar(u);if(b===_1n)return this;if(!USE_ENDOMORPHISM){let C=h,O=this;for(;b>_0n;)b&_1n&&(C=C.add(O)),O=O.double(),b>>=_1n;return C}let{k1neg:v,k1:w,k2neg:_,k2:E}=endo.splitScalar(b),S=h,x=h,T=this;for(;w>_0n||E>_0n;)w&_1n&&(S=S.add(T)),E&_1n&&(x=x.add(T)),T=T.double(),w>>=_1n,E>>=_1n;return v&&(S=S.negate()),_&&(x=x.negate()),x=new JacobianPoint(mod(x.x*endo.beta),x.y,x.z),S.add(x)}precomputeWindow(u){const h=USE_ENDOMORPHISM?128/u+1:256/u+1,b=[];let v=this,w=v;for(let _=0;_<h;_++){w=v,b.push(w);for(let E=1;E<2**(u-1);E++)w=w.add(v),b.push(w);v=w.double()}return b}wNAF(u,h){!h&&this.equals(JacobianPoint.BASE)&&(h=Point.BASE);const b=h&&h._WINDOW_SIZE||1;if(256%b)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let v=h&&pointPrecomputes.get(h);v||(v=this.precomputeWindow(b),h&&b!==1&&(v=JacobianPoint.normalizeZ(v),pointPrecomputes.set(h,v)));let w=JacobianPoint.ZERO,_=JacobianPoint.BASE;const E=1+(USE_ENDOMORPHISM?128/b:256/b),S=2**(b-1),x=BigInt(2**b-1),T=2**b,C=BigInt(b);for(let O=0;O<E;O++){const D=O*S;let U=Number(u&x);u>>=C,U>S&&(U-=T,u+=_1n);const te=D,X=D+Math.abs(U)-1,ie=O%2!==0,ee=U<0;U===0?_=_.add(constTimeNegate(ie,v[te])):w=w.add(constTimeNegate(ee,v[X]))}return{p:w,f:_}}multiply(u,h){let b=normalizeScalar(u),v,w;if(USE_ENDOMORPHISM){const{k1neg:_,k1:E,k2neg:S,k2:x}=endo.splitScalar(b);let{p:T,f:C}=this.wNAF(E,h),{p:O,f:D}=this.wNAF(x,h);T=constTimeNegate(_,T),O=constTimeNegate(S,O),O=new JacobianPoint(mod(O.x*endo.beta),O.y,O.z),v=T.add(O),w=C.add(D)}else{const{p:_,f:E}=this.wNAF(b,h);v=_,w=E}return JacobianPoint.normalizeZ([v,w])[0]}toAffine(u){const{x:h,y:b,z:v}=this,w=this.equals(JacobianPoint.ZERO);u==null&&(u=w?_8n:invert(v));const _=u,E=mod(_*_),S=mod(E*_),x=mod(h*E),T=mod(b*S),C=mod(v*_);if(w)return Point.ZERO;if(C!==_1n)throw new Error("invZ was invalid");return new Point(x,T)}}JacobianPoint.BASE=new JacobianPoint(CURVE.Gx,CURVE.Gy,_1n);JacobianPoint.ZERO=new JacobianPoint(_0n,_1n,_0n);function constTimeNegate(y,u){const h=u.negate();return y?h:u}const pointPrecomputes=new WeakMap;class Point{constructor(u,h){this.x=u,this.y=h}_setWindowSize(u){this._WINDOW_SIZE=u,pointPrecomputes.delete(this)}hasEvenY(){return this.y%_2n===_0n}static fromCompressedHex(u){const h=u.length===32,b=bytesToNumber(h?u:u.subarray(1));if(!isValidFieldElement(b))throw new Error("Point is not on curve");const v=weierstrass(b);let w=sqrtMod(v);const _=(w&_1n)===_1n;h?_&&(w=mod(-w)):(u[0]&1)===1!==_&&(w=mod(-w));const E=new Point(b,w);return E.assertValidity(),E}static fromUncompressedHex(u){const h=bytesToNumber(u.subarray(1,fieldLen+1)),b=bytesToNumber(u.subarray(fieldLen+1,fieldLen*2+1)),v=new Point(h,b);return v.assertValidity(),v}static fromHex(u){const h=ensureBytes(u),b=h.length,v=h[0];if(b===fieldLen)return this.fromCompressedHex(h);if(b===compressedLen&&(v===2||v===3))return this.fromCompressedHex(h);if(b===uncompressedLen&&v===4)return this.fromUncompressedHex(h);throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${b}`)}static fromPrivateKey(u){return Point.BASE.multiply(normalizePrivateKey(u))}static fromSignature(u,h,b){const{r:v,s:w}=normalizeSignature(h);if(![0,1,2,3].includes(b))throw new Error("Cannot recover: invalid recovery bit");const _=truncateHash(ensureBytes(u)),{n:E}=CURVE,S=b===2||b===3?v+E:v,x=invert(S,E),T=mod(-_*x,E),C=mod(w*x,E),O=b&1?"03":"02",D=Point.fromHex(O+numTo32bStr(S)),U=Point.BASE.multiplyAndAddUnsafe(D,T,C);if(!U)throw new Error("Cannot recover signature: point at infinify");return U.assertValidity(),U}toRawBytes(u=!1){return hexToBytes(this.toHex(u))}toHex(u=!1){const h=numTo32bStr(this.x);return u?`${this.hasEvenY()?"02":"03"}${h}`:`04${h}${numTo32bStr(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const u="Point is not on elliptic curve",{x:h,y:b}=this;if(!isValidFieldElement(h)||!isValidFieldElement(b))throw new Error(u);const v=mod(b*b),w=weierstrass(h);if(mod(v-w)!==_0n)throw new Error(u)}equals(u){return this.x===u.x&&this.y===u.y}negate(){return new Point(this.x,mod(-this.y))}double(){return JacobianPoint.fromAffine(this).double().toAffine()}add(u){return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(u)).toAffine()}subtract(u){return this.add(u.negate())}multiply(u){return JacobianPoint.fromAffine(this).multiply(u,this).toAffine()}multiplyAndAddUnsafe(u,h,b){const v=JacobianPoint.fromAffine(this),w=h===_0n||h===_1n||this!==Point.BASE?v.multiplyUnsafe(h):v.multiply(h),_=JacobianPoint.fromAffine(u).multiplyUnsafe(b),E=w.add(_);return E.equals(JacobianPoint.ZERO)?void 0:E.toAffine()}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy);Point.ZERO=new Point(_0n,_0n);function sliceDER(y){return Number.parseInt(y[0],16)>=8?"00"+y:y}function parseDERInt(y){if(y.length<2||y[0]!==2)throw new Error(`Invalid signature integer tag: ${bytesToHex(y)}`);const u=y[1],h=y.subarray(2,u+2);if(!u||h.length!==u)throw new Error("Invalid signature integer: wrong length");if(h[0]===0&&h[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:bytesToNumber(h),left:y.subarray(u+2)}}function parseDERSignature(y){if(y.length<2||y[0]!=48)throw new Error(`Invalid signature tag: ${bytesToHex(y)}`);if(y[1]!==y.length-2)throw new Error("Invalid signature: incorrect length");const{data:u,left:h}=parseDERInt(y.subarray(2)),{data:b,left:v}=parseDERInt(h);if(v.length)throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(v)}`);return{r:u,s:b}}class Signature{constructor(u,h){this.r=u,this.s=h,this.assertValidity()}static fromCompact(u){const h=isBytes$1(u),b="Signature.fromCompact";if(typeof u!="string"&&!h)throw new TypeError(`${b}: Expected string or Uint8Array`);const v=h?bytesToHex(u):u;if(v.length!==128)throw new Error(`${b}: Expected 64-byte hex`);return new Signature(hexToNumber(v.slice(0,64)),hexToNumber(v.slice(64,128)))}static fromDER(u){const h=isBytes$1(u);if(typeof u!="string"&&!h)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:b,s:v}=parseDERSignature(h?u:hexToBytes(u));return new Signature(b,v)}static fromHex(u){return this.fromDER(u)}assertValidity(){const{r:u,s:h}=this;if(!isWithinCurveOrder(u))throw new Error("Invalid Signature: r must be 0 < r < n");if(!isWithinCurveOrder(h))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const u=CURVE.n>>_1n;return this.s>u}normalizeS(){return this.hasHighS()?new Signature(this.r,mod(-this.s,CURVE.n)):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){const u=sliceDER(numberToHexUnpadded(this.s)),h=sliceDER(numberToHexUnpadded(this.r)),b=u.length/2,v=h.length/2,w=numberToHexUnpadded(b),_=numberToHexUnpadded(v);return`30${numberToHexUnpadded(v+b+4)}02${_}${h}02${w}${u}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}}function isBytes$1(y){return y instanceof Uint8Array||ArrayBuffer.isView(y)&&y.constructor.name==="Uint8Array"}function abytes(y){if(!isBytes$1(y))throw new Error("Uint8Array expected")}function concatBytes(...y){if(y.every(abytes),y.length===1)return y[0];const u=y.reduce((b,v)=>b+v.length,0),h=new Uint8Array(u);for(let b=0,v=0;b<y.length;b++){const w=y[b];h.set(w,v),v+=w.length}return h}const hexes=Array.from({length:256},(y,u)=>u.toString(16).padStart(2,"0"));function bytesToHex(y){abytes(y);let u="";for(let h=0;h<y.length;h++)u+=hexes[y[h]];return u}const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(y){if(y>=asciis._0&&y<=asciis._9)return y-asciis._0;if(y>=asciis.A&&y<=asciis.F)return y-(asciis.A-10);if(y>=asciis.a&&y<=asciis.f)return y-(asciis.a-10)}function hexToBytes(y){if(typeof y!="string")throw new Error("hex string expected, got "+typeof y);const u=y.length,h=u/2;if(u%2)throw new Error("hex string expected, got unpadded hex of length "+u);const b=new Uint8Array(h);for(let v=0,w=0;v<h;v++,w+=2){const _=asciiToBase16(y.charCodeAt(w)),E=asciiToBase16(y.charCodeAt(w+1));if(_===void 0||E===void 0){const S=y[w]+y[w+1];throw new Error('hex string expected, got non-hex character "'+S+'" at index '+w)}b[v]=_*16+E}return b}const POW_2_256=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function numTo32bStr(y){if(typeof y!="bigint")throw new Error("Expected bigint");if(!(_0n<=y&&y<POW_2_256))throw new Error("Expected number 0 <= n < 2^256");return y.toString(16).padStart(64,"0")}function numTo32b(y){const u=hexToBytes(numTo32bStr(y));if(u.length!==32)throw new Error("Error: expected 32 bytes");return u}function numberToHexUnpadded(y){const u=y.toString(16);return u.length&1?`0${u}`:u}function hexToNumber(y){if(typeof y!="string")throw new TypeError("hexToNumber: expected string, got "+typeof y);return BigInt(`0x${y}`)}function bytesToNumber(y){return hexToNumber(bytesToHex(y))}function ensureBytes(y){return isBytes$1(y)?Uint8Array.from(y):hexToBytes(y)}function normalizeScalar(y){if(typeof y=="number"&&Number.isSafeInteger(y)&&y>0)return BigInt(y);if(typeof y=="bigint"&&isWithinCurveOrder(y))return y;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function mod(y,u=CURVE.P){const h=y%u;return h>=_0n?h:u+h}function pow2(y,u){const{P:h}=CURVE;let b=y;for(;u-- >_0n;)b*=b,b%=h;return b}function sqrtMod(y){const{P:u}=CURVE,h=BigInt(6),b=BigInt(11),v=BigInt(22),w=BigInt(23),_=BigInt(44),E=BigInt(88),S=y*y*y%u,x=S*S*y%u,T=pow2(x,_3n)*x%u,C=pow2(T,_3n)*x%u,O=pow2(C,_2n)*S%u,D=pow2(O,b)*O%u,U=pow2(D,v)*D%u,te=pow2(U,_)*U%u,X=pow2(te,E)*te%u,ie=pow2(X,_)*U%u,ee=pow2(ie,_3n)*x%u,ae=pow2(ee,w)*D%u,de=pow2(ae,h)*S%u,Se=pow2(de,_2n);if(Se*Se%u!==y)throw new Error("Cannot find square root");return Se}function invert(y,u=CURVE.P){if(y===_0n||u<=_0n)throw new Error(`invert: expected positive integers, got n=${y} mod=${u}`);let h=mod(y,u),b=u,v=_0n,w=_1n;for(;h!==_0n;){const E=b/h,S=b%h,x=v-w*E;b=h,h=S,v=w,w=x}if(b!==_1n)throw new Error("invert: does not exist");return mod(v,u)}function invertBatch(y,u=CURVE.P){const h=new Array(y.length),b=y.reduce((w,_,E)=>_===_0n?w:(h[E]=w,mod(w*_,u)),_1n),v=invert(b,u);return y.reduceRight((w,_,E)=>_===_0n?w:(h[E]=mod(w*h[E],u),mod(w*_,u)),v),h}function bits2int_2(y){const u=y.length*8-groupLen*8,h=bytesToNumber(y);return u>0?h>>BigInt(u):h}function truncateHash(y,u=!1){const h=bits2int_2(y);if(u)return h;const{n:b}=CURVE;return h>=b?h-b:h}let _sha256Sync,_hmacSha256Sync;class HmacDrbg{constructor(u,h){if(this.hashLen=u,this.qByteLen=h,typeof u!="number"||u<2)throw new Error("hashLen must be a number");if(typeof h!="number"||h<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(u).fill(1),this.k=new Uint8Array(u).fill(0),this.counter=0}hmac(...u){return utils.hmacSha256(this.k,...u)}hmacSync(...u){return _hmacSha256Sync(this.k,...u)}checkSync(){if(typeof _hmacSha256Sync!="function")throw new ShaError("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(u=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),u),this.v=await this.hmac(this.v),u.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),u),this.v=await this.hmac(this.v))}reseedSync(u=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),u),this.v=this.hmacSync(this.v),u.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),u),this.v=this.hmacSync(this.v))}async generate(){this.incr();let u=0;const h=[];for(;u<this.qByteLen;){this.v=await this.hmac(this.v);const b=this.v.slice();h.push(b),u+=this.v.length}return concatBytes(...h)}generateSync(){this.checkSync(),this.incr();let u=0;const h=[];for(;u<this.qByteLen;){this.v=this.hmacSync(this.v);const b=this.v.slice();h.push(b),u+=this.v.length}return concatBytes(...h)}}function isWithinCurveOrder(y){return _0n<y&&y<CURVE.n}function isValidFieldElement(y){return _0n<y&&y<CURVE.P}function kmdToSig(y,u,h,b=!0){const{n:v}=CURVE,w=truncateHash(y,!0);if(!isWithinCurveOrder(w))return;const _=invert(w,v),E=Point.BASE.multiply(w),S=mod(E.x,v);if(S===_0n)return;const x=mod(_*mod(u+h*S,v),v);if(x===_0n)return;let T=new Signature(S,x),C=(E.x===T.r?0:2)|Number(E.y&_1n);return b&&T.hasHighS()&&(T=T.normalizeS(),C^=1),{sig:T,recovery:C}}function normalizePrivateKey(y){let u;if(typeof y=="bigint")u=y;else if(typeof y=="number"&&Number.isSafeInteger(y)&&y>0)u=BigInt(y);else if(typeof y=="string"){if(y.length!==2*groupLen)throw new Error("Expected 32 bytes of private key");u=hexToNumber(y)}else if(isBytes$1(y)){if(y.length!==groupLen)throw new Error("Expected 32 bytes of private key");u=bytesToNumber(y)}else throw new TypeError("Expected valid private key");if(!isWithinCurveOrder(u))throw new Error("Expected private key: 0 < key < n");return u}function normalizePublicKey(y){return y instanceof Point?(y.assertValidity(),y):Point.fromHex(y)}function normalizeSignature(y){if(y instanceof Signature)return y.assertValidity(),y;try{return Signature.fromDER(y)}catch{return Signature.fromCompact(y)}}function bits2int(y){const u=y.length>fieldLen?y.slice(0,fieldLen):y;return bytesToNumber(u)}function bits2octets(y){const u=bits2int(y),h=mod(u,CURVE.n);return int2octets(h<_0n?u:h)}function int2octets(y){return numTo32b(y)}function initSigArgs(y,u,h){if(y==null)throw new Error(`sign: expected valid message hash, not "${y}"`);const b=ensureBytes(y),v=normalizePrivateKey(u),w=[int2octets(v),bits2octets(b)];if(h!=null){h===!0&&(h=utils.randomBytes(fieldLen));const S=ensureBytes(h);if(S.length!==fieldLen)throw new Error(`sign: Expected ${fieldLen} bytes of extra data`);w.push(S)}const _=concatBytes(...w),E=bits2int(b);return{seed:_,m:E,d:v}}function finalizeSig(y,u){const{sig:h,recovery:b}=y,{der:v,recovered:w}=Object.assign({canonical:!0,der:!0},u),_=v?h.toDERRawBytes():h.toCompactRawBytes();return w?[_,b]:_}async function sign$1(y,u,h={}){const{seed:b,m:v,d:w}=initSigArgs(y,u,h.extraEntropy),_=new HmacDrbg(hashLen,groupLen);await _.reseed(b);let E;for(;!(E=kmdToSig(await _.generate(),v,w,h.canonical));)await _.reseed();return finalizeSig(E,h)}const vopts={strict:!0};function verify(y,u,h,b=vopts){let v;try{v=normalizeSignature(y),u=ensureBytes(u)}catch{return!1}const{r:w,s:_}=v;if(b.strict&&v.hasHighS())return!1;const E=truncateHash(u);let S;try{S=normalizePublicKey(h)}catch{return!1}const{n:x}=CURVE,T=invert(_,x),C=mod(E*T,x),O=mod(w*T,x),D=Point.BASE.multiplyAndAddUnsafe(S,C,O);return D?mod(D.x,x)===w:!1}Point.BASE._setWindowSize(8);const crypto$1={node:nodeCrypto,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0},TAGGED_HASH_PREFIXES={},utils={bytesToHex,hexToBytes,concatBytes,mod,invert,isValidPrivateKey(y){try{return normalizePrivateKey(y),!0}catch{return!1}},_bigintTo32Bytes:numTo32b,_normalizePrivateKey:normalizePrivateKey,hashToPrivateKey:y=>{y=ensureBytes(y);const u=groupLen+8;if(y.length<u||y.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");const h=mod(bytesToNumber(y),CURVE.n-_1n)+_1n;return numTo32b(h)},randomBytes:(y=32)=>{if(crypto$1.web)return crypto$1.web.getRandomValues(new Uint8Array(y));if(crypto$1.node){const{randomBytes:u}=crypto$1.node;return Uint8Array.from(u(y))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>utils.hashToPrivateKey(utils.randomBytes(groupLen+8)),precompute(y=8,u=Point.BASE){const h=u===Point.BASE?u:new Point(u.x,u.y);return h._setWindowSize(y),h.multiply(_3n),h},sha256:async(...y)=>{if(crypto$1.web){const u=await crypto$1.web.subtle.digest("SHA-256",concatBytes(...y));return new Uint8Array(u)}else if(crypto$1.node){const{createHash:u}=crypto$1.node,h=u("sha256");return y.forEach(b=>h.update(b)),Uint8Array.from(h.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(y,...u)=>{if(crypto$1.web){const h=await crypto$1.web.subtle.importKey("raw",y,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),b=concatBytes(...u),v=await crypto$1.web.subtle.sign("HMAC",h,b);return new Uint8Array(v)}else if(crypto$1.node){const{createHmac:h}=crypto$1.node,b=h("sha256",y);return u.forEach(v=>b.update(v)),Uint8Array.from(b.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(y,...u)=>{let h=TAGGED_HASH_PREFIXES[y];if(h===void 0){const b=await utils.sha256(Uint8Array.from(y,v=>v.charCodeAt(0)));h=concatBytes(b,b),TAGGED_HASH_PREFIXES[y]=h}return utils.sha256(h,...u)},taggedHashSync:(y,...u)=>{if(typeof _sha256Sync!="function")throw new ShaError("sha256Sync is undefined, you need to set it");let h=TAGGED_HASH_PREFIXES[y];if(h===void 0){const b=_sha256Sync(Uint8Array.from(y,v=>v.charCodeAt(0)));h=concatBytes(b,b),TAGGED_HASH_PREFIXES[y]=h}return _sha256Sync(h,...u)},_JacobianPoint:JacobianPoint};Object.defineProperties(utils,{sha256Sync:{configurable:!1,get(){return _sha256Sync},set(y){_sha256Sync||(_sha256Sync=y)}},hmacSha256Sync:{configurable:!1,get(){return _hmacSha256Sync},set(y){_hmacSha256Sync||(_hmacSha256Sync=y)}}});var sha3$1={exports:{}};(function(y){(function(){var u="input is invalid type",h="finalize already called",b=typeof window=="object",v=b?window:{};v.JS_SHA3_NO_WINDOW&&(b=!1);var w=!b&&typeof self=="object",_=!v.JS_SHA3_NO_NODE_JS&&typeof process$1=="object"&&process$1.versions&&process$1.versions.node;_?v=commonjsGlobal:w&&(v=self);for(var E=!v.JS_SHA3_NO_COMMON_JS&&!0&&y.exports,S=!v.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",x="0123456789abcdef".split(""),T=[31,7936,2031616,520093696],C=[4,1024,262144,67108864],O=[1,256,65536,16777216],D=[6,1536,393216,100663296],U=[0,8,16,24],te=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],X=[224,256,384,512],ie=[128,256],ee=["hex","buffer","arrayBuffer","array","digest"],ae={128:168,256:136},de=v.JS_SHA3_NO_NODE_JS||!Array.isArray?function(fe){return Object.prototype.toString.call(fe)==="[object Array]"}:Array.isArray,Se=S&&(v.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)?function(fe){return typeof fe=="object"&&fe.buffer&&fe.buffer.constructor===ArrayBuffer}:ArrayBuffer.isView,ve=function(fe){var ge=typeof fe;if(ge==="string")return[fe,!0];if(ge!=="object"||fe===null)throw new Error(u);if(S&&fe.constructor===ArrayBuffer)return[new Uint8Array(fe),!1];if(!de(fe)&&!Se(fe))throw new Error(u);return[fe,!1]},Pe=function(fe){return ve(fe)[0].length===0},Ie=function(fe){for(var ge=[],ce=0;ce<fe.length;++ce)ge[ce]=fe[ce];return ge},Ee=function(fe,ge,ce){return function(_e){return new le(fe,ge,fe).update(_e)[ce]()}},De=function(fe,ge,ce){return function(_e,Re){return new le(fe,ge,Re).update(_e)[ce]()}},be=function(fe,ge,ce){return function(_e,Re,Ue,qe){return J["cshake"+fe].update(_e,Re,Ue,qe)[ce]()}},B=function(fe,ge,ce){return function(_e,Re,Ue,qe){return J["kmac"+fe].update(_e,Re,Ue,qe)[ce]()}},F=function(fe,ge,ce,_e){for(var Re=0;Re<ee.length;++Re){var Ue=ee[Re];fe[Ue]=ge(ce,_e,Ue)}return fe},M=function(fe,ge){var ce=Ee(fe,ge,"hex");return ce.create=function(){return new le(fe,ge,fe)},ce.update=function(_e){return ce.create().update(_e)},F(ce,Ee,fe,ge)},N=function(fe,ge){var ce=De(fe,ge,"hex");return ce.create=function(_e){return new le(fe,ge,_e)},ce.update=function(_e,Re){return ce.create(Re).update(_e)},F(ce,De,fe,ge)},Q=function(fe,ge){var ce=ae[fe],_e=be(fe,ge,"hex");return _e.create=function(Re,Ue,qe){return Pe(Ue)&&Pe(qe)?J["shake"+fe].create(Re):new le(fe,ge,Re).bytepad([Ue,qe],ce)},_e.update=function(Re,Ue,qe,Ze){return _e.create(Ue,qe,Ze).update(Re)},F(_e,be,fe,ge)},j=function(fe,ge){var ce=ae[fe],_e=B(fe,ge,"hex");return _e.create=function(Re,Ue,qe){return new me(fe,ge,Ue).bytepad(["KMAC",qe],ce).bytepad([Re],ce)},_e.update=function(Re,Ue,qe,Ze){return _e.create(Re,qe,Ze).update(Ue)},F(_e,B,fe,ge)},ne=[{name:"keccak",padding:O,bits:X,createMethod:M},{name:"sha3",padding:D,bits:X,createMethod:M},{name:"shake",padding:T,bits:ie,createMethod:N},{name:"cshake",padding:C,bits:ie,createMethod:Q},{name:"kmac",padding:C,bits:ie,createMethod:j}],J={},q=[],re=0;re<ne.length;++re)for(var H=ne[re],he=H.bits,Oe=0;Oe<he.length;++Oe){var Ne=H.name+"_"+he[Oe];if(q.push(Ne),J[Ne]=H.createMethod(he[Oe],H.padding),H.name!=="sha3"){var Ae=H.name+he[Oe];q.push(Ae),J[Ae]=J[Ne]}}function le(fe,ge,ce){this.blocks=[],this.s=[],this.padding=ge,this.outputBits=ce,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(fe<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=ce>>5,this.extraBytes=(ce&31)>>3;for(var _e=0;_e<50;++_e)this.s[_e]=0}le.prototype.update=function(fe){if(this.finalized)throw new Error(h);var ge=ve(fe);fe=ge[0];for(var ce=ge[1],_e=this.blocks,Re=this.byteCount,Ue=fe.length,qe=this.blockCount,Ze=0,tt=this.s,Fe,nt;Ze<Ue;){if(this.reset)for(this.reset=!1,_e[0]=this.block,Fe=1;Fe<qe+1;++Fe)_e[Fe]=0;if(ce)for(Fe=this.start;Ze<Ue&&Fe<Re;++Ze)nt=fe.charCodeAt(Ze),nt<128?_e[Fe>>2]|=nt<<U[Fe++&3]:nt<2048?(_e[Fe>>2]|=(192|nt>>6)<<U[Fe++&3],_e[Fe>>2]|=(128|nt&63)<<U[Fe++&3]):nt<55296||nt>=57344?(_e[Fe>>2]|=(224|nt>>12)<<U[Fe++&3],_e[Fe>>2]|=(128|nt>>6&63)<<U[Fe++&3],_e[Fe>>2]|=(128|nt&63)<<U[Fe++&3]):(nt=65536+((nt&1023)<<10|fe.charCodeAt(++Ze)&1023),_e[Fe>>2]|=(240|nt>>18)<<U[Fe++&3],_e[Fe>>2]|=(128|nt>>12&63)<<U[Fe++&3],_e[Fe>>2]|=(128|nt>>6&63)<<U[Fe++&3],_e[Fe>>2]|=(128|nt&63)<<U[Fe++&3]);else for(Fe=this.start;Ze<Ue&&Fe<Re;++Ze)_e[Fe>>2]|=fe[Ze]<<U[Fe++&3];if(this.lastByteIndex=Fe,Fe>=Re){for(this.start=Fe-Re,this.block=_e[qe],Fe=0;Fe<qe;++Fe)tt[Fe]^=_e[Fe];Me(tt),this.reset=!0}else this.start=Fe}return this},le.prototype.encode=function(fe,ge){var ce=fe&255,_e=1,Re=[ce];for(fe=fe>>8,ce=fe&255;ce>0;)Re.unshift(ce),fe=fe>>8,ce=fe&255,++_e;return ge?Re.push(_e):Re.unshift(_e),this.update(Re),Re.length},le.prototype.encodeString=function(fe){var ge=ve(fe);fe=ge[0];var ce=ge[1],_e=0,Re=fe.length;if(ce)for(var Ue=0;Ue<fe.length;++Ue){var qe=fe.charCodeAt(Ue);qe<128?_e+=1:qe<2048?_e+=2:qe<55296||qe>=57344?_e+=3:(qe=65536+((qe&1023)<<10|fe.charCodeAt(++Ue)&1023),_e+=4)}else _e=Re;return _e+=this.encode(_e*8),this.update(fe),_e},le.prototype.bytepad=function(fe,ge){for(var ce=this.encode(ge),_e=0;_e<fe.length;++_e)ce+=this.encodeString(fe[_e]);var Re=(ge-ce%ge)%ge,Ue=[];return Ue.length=Re,this.update(Ue),this},le.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var fe=this.blocks,ge=this.lastByteIndex,ce=this.blockCount,_e=this.s;if(fe[ge>>2]|=this.padding[ge&3],this.lastByteIndex===this.byteCount)for(fe[0]=fe[ce],ge=1;ge<ce+1;++ge)fe[ge]=0;for(fe[ce-1]|=2147483648,ge=0;ge<ce;++ge)_e[ge]^=fe[ge];Me(_e)}},le.prototype.toString=le.prototype.hex=function(){this.finalize();for(var fe=this.blockCount,ge=this.s,ce=this.outputBlocks,_e=this.extraBytes,Re=0,Ue=0,qe="",Ze;Ue<ce;){for(Re=0;Re<fe&&Ue<ce;++Re,++Ue)Ze=ge[Re],qe+=x[Ze>>4&15]+x[Ze&15]+x[Ze>>12&15]+x[Ze>>8&15]+x[Ze>>20&15]+x[Ze>>16&15]+x[Ze>>28&15]+x[Ze>>24&15];Ue%fe===0&&(ge=Ie(ge),Me(ge),Re=0)}return _e&&(Ze=ge[Re],qe+=x[Ze>>4&15]+x[Ze&15],_e>1&&(qe+=x[Ze>>12&15]+x[Ze>>8&15]),_e>2&&(qe+=x[Ze>>20&15]+x[Ze>>16&15])),qe},le.prototype.arrayBuffer=function(){this.finalize();var fe=this.blockCount,ge=this.s,ce=this.outputBlocks,_e=this.extraBytes,Re=0,Ue=0,qe=this.outputBits>>3,Ze;_e?Ze=new ArrayBuffer(ce+1<<2):Ze=new ArrayBuffer(qe);for(var tt=new Uint32Array(Ze);Ue<ce;){for(Re=0;Re<fe&&Ue<ce;++Re,++Ue)tt[Ue]=ge[Re];Ue%fe===0&&(ge=Ie(ge),Me(ge))}return _e&&(tt[Ue]=ge[Re],Ze=Ze.slice(0,qe)),Ze},le.prototype.buffer=le.prototype.arrayBuffer,le.prototype.digest=le.prototype.array=function(){this.finalize();for(var fe=this.blockCount,ge=this.s,ce=this.outputBlocks,_e=this.extraBytes,Re=0,Ue=0,qe=[],Ze,tt;Ue<ce;){for(Re=0;Re<fe&&Ue<ce;++Re,++Ue)Ze=Ue<<2,tt=ge[Re],qe[Ze]=tt&255,qe[Ze+1]=tt>>8&255,qe[Ze+2]=tt>>16&255,qe[Ze+3]=tt>>24&255;Ue%fe===0&&(ge=Ie(ge),Me(ge))}return _e&&(Ze=Ue<<2,tt=ge[Re],qe[Ze]=tt&255,_e>1&&(qe[Ze+1]=tt>>8&255),_e>2&&(qe[Ze+2]=tt>>16&255)),qe};function me(fe,ge,ce){le.call(this,fe,ge,ce)}me.prototype=new le,me.prototype.finalize=function(){return this.encode(this.outputBits,!0),le.prototype.finalize.call(this)};var Me=function(fe){var ge,ce,_e,Re,Ue,qe,Ze,tt,Fe,nt,it,at,ct,ht,xt,Ot,dt,Rt,Nt,yt,zt,Vt,vt,Ut,Lt,wt,Wt,Gt,At,tr,Xt,bt,Bt,Yt,Tt,qt,Jt,we,se,ue,xe,ke,Ke,We,ut,_t,st,Et,gt,It,Qt,rr,ar,Gr,Hr,jr,Xr,Yr,Br,Kr,kr,Mr,Jr;for(_e=0;_e<48;_e+=2)Re=fe[0]^fe[10]^fe[20]^fe[30]^fe[40],Ue=fe[1]^fe[11]^fe[21]^fe[31]^fe[41],qe=fe[2]^fe[12]^fe[22]^fe[32]^fe[42],Ze=fe[3]^fe[13]^fe[23]^fe[33]^fe[43],tt=fe[4]^fe[14]^fe[24]^fe[34]^fe[44],Fe=fe[5]^fe[15]^fe[25]^fe[35]^fe[45],nt=fe[6]^fe[16]^fe[26]^fe[36]^fe[46],it=fe[7]^fe[17]^fe[27]^fe[37]^fe[47],at=fe[8]^fe[18]^fe[28]^fe[38]^fe[48],ct=fe[9]^fe[19]^fe[29]^fe[39]^fe[49],ge=at^(qe<<1|Ze>>>31),ce=ct^(Ze<<1|qe>>>31),fe[0]^=ge,fe[1]^=ce,fe[10]^=ge,fe[11]^=ce,fe[20]^=ge,fe[21]^=ce,fe[30]^=ge,fe[31]^=ce,fe[40]^=ge,fe[41]^=ce,ge=Re^(tt<<1|Fe>>>31),ce=Ue^(Fe<<1|tt>>>31),fe[2]^=ge,fe[3]^=ce,fe[12]^=ge,fe[13]^=ce,fe[22]^=ge,fe[23]^=ce,fe[32]^=ge,fe[33]^=ce,fe[42]^=ge,fe[43]^=ce,ge=qe^(nt<<1|it>>>31),ce=Ze^(it<<1|nt>>>31),fe[4]^=ge,fe[5]^=ce,fe[14]^=ge,fe[15]^=ce,fe[24]^=ge,fe[25]^=ce,fe[34]^=ge,fe[35]^=ce,fe[44]^=ge,fe[45]^=ce,ge=tt^(at<<1|ct>>>31),ce=Fe^(ct<<1|at>>>31),fe[6]^=ge,fe[7]^=ce,fe[16]^=ge,fe[17]^=ce,fe[26]^=ge,fe[27]^=ce,fe[36]^=ge,fe[37]^=ce,fe[46]^=ge,fe[47]^=ce,ge=nt^(Re<<1|Ue>>>31),ce=it^(Ue<<1|Re>>>31),fe[8]^=ge,fe[9]^=ce,fe[18]^=ge,fe[19]^=ce,fe[28]^=ge,fe[29]^=ce,fe[38]^=ge,fe[39]^=ce,fe[48]^=ge,fe[49]^=ce,ht=fe[0],xt=fe[1],_t=fe[11]<<4|fe[10]>>>28,st=fe[10]<<4|fe[11]>>>28,Gt=fe[20]<<3|fe[21]>>>29,At=fe[21]<<3|fe[20]>>>29,Kr=fe[31]<<9|fe[30]>>>23,kr=fe[30]<<9|fe[31]>>>23,ke=fe[40]<<18|fe[41]>>>14,Ke=fe[41]<<18|fe[40]>>>14,Yt=fe[2]<<1|fe[3]>>>31,Tt=fe[3]<<1|fe[2]>>>31,Ot=fe[13]<<12|fe[12]>>>20,dt=fe[12]<<12|fe[13]>>>20,Et=fe[22]<<10|fe[23]>>>22,gt=fe[23]<<10|fe[22]>>>22,tr=fe[33]<<13|fe[32]>>>19,Xt=fe[32]<<13|fe[33]>>>19,Mr=fe[42]<<2|fe[43]>>>30,Jr=fe[43]<<2|fe[42]>>>30,Gr=fe[5]<<30|fe[4]>>>2,Hr=fe[4]<<30|fe[5]>>>2,qt=fe[14]<<6|fe[15]>>>26,Jt=fe[15]<<6|fe[14]>>>26,Rt=fe[25]<<11|fe[24]>>>21,Nt=fe[24]<<11|fe[25]>>>21,It=fe[34]<<15|fe[35]>>>17,Qt=fe[35]<<15|fe[34]>>>17,bt=fe[45]<<29|fe[44]>>>3,Bt=fe[44]<<29|fe[45]>>>3,Ut=fe[6]<<28|fe[7]>>>4,Lt=fe[7]<<28|fe[6]>>>4,jr=fe[17]<<23|fe[16]>>>9,Xr=fe[16]<<23|fe[17]>>>9,we=fe[26]<<25|fe[27]>>>7,se=fe[27]<<25|fe[26]>>>7,yt=fe[36]<<21|fe[37]>>>11,zt=fe[37]<<21|fe[36]>>>11,rr=fe[47]<<24|fe[46]>>>8,ar=fe[46]<<24|fe[47]>>>8,We=fe[8]<<27|fe[9]>>>5,ut=fe[9]<<27|fe[8]>>>5,wt=fe[18]<<20|fe[19]>>>12,Wt=fe[19]<<20|fe[18]>>>12,Yr=fe[29]<<7|fe[28]>>>25,Br=fe[28]<<7|fe[29]>>>25,ue=fe[38]<<8|fe[39]>>>24,xe=fe[39]<<8|fe[38]>>>24,Vt=fe[48]<<14|fe[49]>>>18,vt=fe[49]<<14|fe[48]>>>18,fe[0]=ht^~Ot&Rt,fe[1]=xt^~dt&Nt,fe[10]=Ut^~wt&Gt,fe[11]=Lt^~Wt&At,fe[20]=Yt^~qt&we,fe[21]=Tt^~Jt&se,fe[30]=We^~_t&Et,fe[31]=ut^~st&gt,fe[40]=Gr^~jr&Yr,fe[41]=Hr^~Xr&Br,fe[2]=Ot^~Rt&yt,fe[3]=dt^~Nt&zt,fe[12]=wt^~Gt&tr,fe[13]=Wt^~At&Xt,fe[22]=qt^~we&ue,fe[23]=Jt^~se&xe,fe[32]=_t^~Et&It,fe[33]=st^~gt&Qt,fe[42]=jr^~Yr&Kr,fe[43]=Xr^~Br&kr,fe[4]=Rt^~yt&Vt,fe[5]=Nt^~zt&vt,fe[14]=Gt^~tr&bt,fe[15]=At^~Xt&Bt,fe[24]=we^~ue&ke,fe[25]=se^~xe&Ke,fe[34]=Et^~It&rr,fe[35]=gt^~Qt&ar,fe[44]=Yr^~Kr&Mr,fe[45]=Br^~kr&Jr,fe[6]=yt^~Vt&ht,fe[7]=zt^~vt&xt,fe[16]=tr^~bt&Ut,fe[17]=Xt^~Bt&Lt,fe[26]=ue^~ke&Yt,fe[27]=xe^~Ke&Tt,fe[36]=It^~rr&We,fe[37]=Qt^~ar&ut,fe[46]=Kr^~Mr&Gr,fe[47]=kr^~Jr&Hr,fe[8]=Vt^~ht&Ot,fe[9]=vt^~xt&dt,fe[18]=bt^~Ut&wt,fe[19]=Bt^~Lt&Wt,fe[28]=ke^~Yt&qt,fe[29]=Ke^~Tt&Jt,fe[38]=rr^~We&_t,fe[39]=ar^~ut&st,fe[48]=Mr^~Gr&jr,fe[49]=Jr^~Hr&Xr,fe[0]^=te[_e],fe[1]^=te[_e+1]};if(E)y.exports=J;else for(re=0;re<q.length;++re)v[q[re]]=J[q[re]]})()})(sha3$1);var sha3Exports=sha3$1.exports;const sha3=getDefaultExportFromCjs$1(sha3Exports);function keccak256(y){return new Uint8Array(sha3.keccak256.arrayBuffer(y))}function verifySignature(y,u,h){try{const b=Signature.fromCompact(y.slice(0,64));return verify(b,u,h)}catch{return!1}}function multiaddrFromFields(y,u,h,b){let v=multiaddr("/"+y+"/"+convertToString(y,h));return v=v.encapsulate(multiaddr("/"+u+"/"+convertToString(u,b))),v}function locationMultiaddrFromEnrFields(y,u){switch(u){case"udp":return locationMultiaddrFromEnrFields(y,"udp4")||locationMultiaddrFromEnrFields(y,"udp6");case"tcp":return locationMultiaddrFromEnrFields(y,"tcp4")||locationMultiaddrFromEnrFields(y,"tcp6")}const h=u.endsWith("6"),b=y.get(h?"ip6":"ip");if(!b)return;const v=u.slice(0,3);let w;switch(v){case"udp":w=h?y.get("udp6"):y.get("udp");break;case"tcp":w=h?y.get("tcp6"):y.get("tcp");break;default:return}if(w)return multiaddrFromFields(h?"ip6":"ip4",v,b,w)}const TAG_MASK=parseInt("11111",2),LONG_LENGTH_MASK=parseInt("10000000",2),LONG_LENGTH_BYTES_MASK=parseInt("01111111",2),decoders={0:readSequence,1:readSequence,2:readInteger,3:readBitString,4:readOctetString,5:readNull,6:readObjectIdentifier,16:readSequence,22:readSequence,48:readSequence};function decodeDer(y,u={offset:0}){const h=y[u.offset]&TAG_MASK;if(u.offset++,decoders[h]!=null)return decoders[h](y,u);throw new Error("No decoder for tag "+h)}function readLength(y,u){let h=0;if((y[u.offset]&LONG_LENGTH_MASK)===LONG_LENGTH_MASK){const b=y[u.offset]&LONG_LENGTH_BYTES_MASK;let v="0x";u.offset++;for(let w=0;w<b;w++,u.offset++)v+=y[u.offset].toString(16).padStart(2,"0");h=parseInt(v,16)}else h=y[u.offset],u.offset++;return h}function readSequence(y,u){readLength(y,u);const h=[];for(;!(u.offset>=y.byteLength);){const b=decodeDer(y,u);if(b===null)break;h.push(b)}return h}function readInteger(y,u){const h=readLength(y,u),b=u.offset,v=u.offset+h,w=[];for(let _=b;_<v;_++)_===b&&y[_]===0||w.push(y[_]);return u.offset+=h,Uint8Array.from(w)}function readObjectIdentifier(y,u){const h=readLength(y,u),b=u.offset+h,v=y[u.offset];u.offset++;let w=0,_=0;v<40?(w=0,_=v):v<80?(w=1,_=v-40):(w=2,_=v-80);let E=`${w}.${_}`,S=[];for(;u.offset<b;){const x=y[u.offset];if(u.offset++,S.push(x&127),x<128){S.reverse();let T=0;for(let C=0;C<S.length;C++)T+=S[C]<<C*7;E+=`.${T}`,S=[]}}return E}function readNull(y,u){return u.offset++,null}function readBitString(y,u){const h=readLength(y,u),b=y[u.offset];u.offset++;const v=y.subarray(u.offset,u.offset+h-1);if(u.offset+=h,b!==0)throw new Error("Unused bits in bit string is unimplemented");return v}function readOctetString(y,u){const h=readLength(y,u),b=y.subarray(u.offset,u.offset+h);return u.offset+=h,b}function encodeNumber(y){let u=y.toString(16);u.length%2===1&&(u="0"+u);const h=new Uint8ArrayList;for(let b=0;b<u.length;b+=2)h.append(Uint8Array.from([parseInt(`${u[b]}${u[b+1]}`,16)]));return h}function encodeLength(y){if(y.byteLength<128)return Uint8Array.from([y.byteLength]);const u=encodeNumber(y.byteLength);return new Uint8ArrayList(Uint8Array.from([u.byteLength|LONG_LENGTH_MASK]),u)}function encodeInteger(y){const u=new Uint8ArrayList,h=128;return(y.subarray()[0]&h)===h&&u.append(Uint8Array.from([0])),u.append(y),new Uint8ArrayList(Uint8Array.from([2]),encodeLength(u),u)}function encodeBitString(y){const u=Uint8Array.from([0]),h=new Uint8ArrayList(u,y);return new Uint8ArrayList(Uint8Array.from([3]),encodeLength(h),h)}function encodeSequence(y,u=48){const h=new Uint8ArrayList;for(const b of y)h.append(b);return new Uint8ArrayList(Uint8Array.from([u]),encodeLength(h),h)}const ECDSA_P_256_OID="1.2.840.10045.3.1.7",ECDSA_P_384_OID="1.3.132.0.34",ECDSA_P_521_OID="1.3.132.0.35";async function hashAndVerify$3(y,u,h,b){var _,E;const v=await crypto.subtle.importKey("jwk",y,{name:"ECDSA",namedCurve:y.crv??"P-256"},!1,["verify"]);(_=b==null?void 0:b.signal)==null||_.throwIfAborted();const w=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},v,u,h.subarray());return(E=b==null?void 0:b.signal)==null||E.throwIfAborted(),w}const OID_256=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),OID_384=Uint8Array.from([6,5,43,129,4,0,34]),OID_521=Uint8Array.from([6,5,43,129,4,0,35]),P_256_KEY_JWK={ext:!0,kty:"EC",crv:"P-256"},P_384_KEY_JWK={ext:!0,kty:"EC",crv:"P-384"},P_521_KEY_JWK={ext:!0,kty:"EC",crv:"P-521"},P_256_KEY_LENGTH=32,P_384_KEY_LENGTH=48,P_521_KEY_LENGTH=66;function pkiMessageToECDSAPublicKey(y){const u=y[1][1][0],h=1;let b,v;if(u.byteLength===P_256_KEY_LENGTH*2+1)return b=toString$1(u.subarray(h,h+P_256_KEY_LENGTH),"base64url"),v=toString$1(u.subarray(h+P_256_KEY_LENGTH),"base64url"),new ECDSAPublicKey({...P_256_KEY_JWK,key_ops:["verify"],x:b,y:v});if(u.byteLength===P_384_KEY_LENGTH*2+1)return b=toString$1(u.subarray(h,h+P_384_KEY_LENGTH),"base64url"),v=toString$1(u.subarray(h+P_384_KEY_LENGTH),"base64url"),new ECDSAPublicKey({...P_384_KEY_JWK,key_ops:["verify"],x:b,y:v});if(u.byteLength===P_521_KEY_LENGTH*2+1)return b=toString$1(u.subarray(h,h+P_521_KEY_LENGTH),"base64url"),v=toString$1(u.subarray(h+P_521_KEY_LENGTH),"base64url"),new ECDSAPublicKey({...P_521_KEY_JWK,key_ops:["verify"],x:b,y:v});throw new InvalidParametersError$2(`coordinates were wrong length, got ${u.byteLength}, expected 65, 97 or 133`)}function publicKeyToPKIMessage(y){return encodeSequence([encodeInteger(Uint8Array.from([1])),encodeSequence([getOID(y.crv)],160),encodeSequence([encodeBitString(new Uint8ArrayList(Uint8Array.from([4]),fromString(y.x??"","base64url"),fromString(y.y??"","base64url")))],161)]).subarray()}function getOID(y){if(y==="P-256")return OID_256;if(y==="P-384")return OID_384;if(y==="P-521")return OID_521;throw new InvalidParametersError$2(`Invalid curve ${y}`)}class ECDSAPublicKey{constructor(u){Z(this,"type","ECDSA");Z(this,"jwk");Z(this,"_raw");this.jwk=u}get raw(){return this._raw==null&&(this._raw=publicKeyToPKIMessage(this.jwk)),this._raw}toMultihash(){return identity.digest(publicKeyToProtobuf(this))}toCID(){return CID.createV1(114,this.toMultihash())}toString(){return base58btc.encode(this.toMultihash().bytes).substring(1)}equals(u){return u==null||!(u.raw instanceof Uint8Array)?!1:equals(this.raw,u.raw)}async verify(u,h,b){return hashAndVerify$3(this.jwk,h,u,b)}}class VerificationError extends Error{constructor(u="An error occurred while verifying a message"){super(u),this.name="VerificationError"}}class WebCryptoMissingError extends Error{constructor(u="Missing Web Crypto API"){super(u),this.name="WebCryptoMissingError"}}const webcrypto={get(y=globalThis){const u=y.crypto;if((u==null?void 0:u.subtle)==null)throw new WebCryptoMissingError("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return u}},PUBLIC_KEY_BYTE_LENGTH$1=32;let ed25519Supported;const webCryptoEd25519SupportedPromise=(async()=>{try{return await webcrypto.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function hashAndVerifyWebCrypto(y,u,h){if(y.buffer instanceof ArrayBuffer){const b=await webcrypto.get().subtle.importKey("raw",y.buffer,{name:"Ed25519"},!1,["verify"]);return await webcrypto.get().subtle.verify({name:"Ed25519"},b,u,h instanceof Uint8Array?h:h.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function hashAndVerifyNoble(y,u,h){return ed25519.verify(u,h instanceof Uint8Array?h:h.subarray(),y)}async function hashAndVerify$2(y,u,h){return ed25519Supported==null&&(ed25519Supported=await webCryptoEd25519SupportedPromise),ed25519Supported?hashAndVerifyWebCrypto(y,u,h):hashAndVerifyNoble(y,u,h)}function isPromise(y){return y==null?!1:typeof y.then=="function"&&typeof y.catch=="function"&&typeof y.finally=="function"}class Ed25519PublicKey{constructor(u){Z(this,"type","Ed25519");Z(this,"raw");this.raw=ensureEd25519Key(u,PUBLIC_KEY_BYTE_LENGTH$1)}toMultihash(){return identity.digest(publicKeyToProtobuf(this))}toCID(){return CID.createV1(114,this.toMultihash())}toString(){return base58btc.encode(this.toMultihash().bytes).substring(1)}equals(u){return u==null||!(u.raw instanceof Uint8Array)?!1:equals(this.raw,u.raw)}verify(u,h,b){var w;(w=b==null?void 0:b.signal)==null||w.throwIfAborted();const v=hashAndVerify$2(this.raw,h,u);return isPromise(v)?v.then(_=>{var E;return(E=b==null?void 0:b.signal)==null||E.throwIfAborted(),_}):v}}function unmarshalEd25519PublicKey(y){return y=ensureEd25519Key(y,PUBLIC_KEY_BYTE_LENGTH$1),new Ed25519PublicKey(y)}function ensureEd25519Key(y,u){if(y=Uint8Array.from(y??[]),y.length!==u)throw new InvalidParametersError$2(`Key must be a Uint8Array of length ${u}, got ${y.length}`);return y}var KeyType;(function(y){y.RSA="RSA",y.Ed25519="Ed25519",y.secp256k1="secp256k1",y.ECDSA="ECDSA"})(KeyType||(KeyType={}));var __KeyTypeValues;(function(y){y[y.RSA=0]="RSA",y[y.Ed25519=1]="Ed25519",y[y.secp256k1=2]="secp256k1",y[y.ECDSA=3]="ECDSA"})(__KeyTypeValues||(__KeyTypeValues={}));(function(y){y.codec=()=>enumeration(__KeyTypeValues)})(KeyType||(KeyType={}));var PublicKey;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.Type!=null&&(b.uint32(8),KeyType.codec().encode(h.Type,b)),h.Data!=null&&(b.uint32(18),b.bytes(h.Data)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.Type=KeyType.codec().decode(h);break}case 2:{w.Data=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PublicKey||(PublicKey={}));var PrivateKey;(function(y){let u;y.codec=()=>(u==null&&(u=message$1((h,b,v={})=>{v.lengthDelimited!==!1&&b.fork(),h.Type!=null&&(b.uint32(8),KeyType.codec().encode(h.Type,b)),h.Data!=null&&(b.uint32(18),b.bytes(h.Data)),v.lengthDelimited!==!1&&b.ldelim()},(h,b,v={})=>{const w={},_=b==null?h.len:h.pos+b;for(;h.pos<_;){const E=h.uint32();switch(E>>>3){case 1:{w.Type=KeyType.codec().decode(h);break}case 2:{w.Data=h.bytes();break}default:{h.skipType(E&7);break}}}return w})),u),y.encode=h=>encodeMessage(h,y.codec()),y.decode=(h,b)=>decodeMessage(h,y.codec(),b)})(PrivateKey||(PrivateKey={}));class RSAPublicKey{constructor(u,h){Z(this,"type","RSA");Z(this,"jwk");Z(this,"_raw");Z(this,"_multihash");this.jwk=u,this._multihash=h}get raw(){return this._raw==null&&(this._raw=jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return CID.createV1(114,this._multihash)}toString(){return base58btc.encode(this.toMultihash().bytes).substring(1)}equals(u){return u==null||!(u.raw instanceof Uint8Array)?!1:equals(this.raw,u.raw)}verify(u,h,b){return hashAndVerify$1(this.jwk,h,u,b)}}const SHA2_256_CODE=18,RSA_ALGORITHM_IDENTIFIER=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function pkixMessageToJwk(y){const u=decodeDer(y[1],{offset:0});return{kty:"RSA",n:toString$1(u[0],"base64url"),e:toString$1(u[1],"base64url")}}function jwkToPkix(y){if(y.n==null||y.e==null)throw new InvalidParametersError$2("JWK was missing components");return encodeSequence([RSA_ALGORITHM_IDENTIFIER,encodeBitString(encodeSequence([encodeInteger(fromString(y.n,"base64url")),encodeInteger(fromString(y.e,"base64url"))]))]).subarray()}function pkixMessageToRSAPublicKey(y,u,h){const b=pkixMessageToJwk(y);if(h==null){const v=sha256$2(PublicKey.encode({Type:KeyType.RSA,Data:u}));h=create$2(SHA2_256_CODE,v)}return new RSAPublicKey(b,h)}const RSAES_PKCS1_V1_5_OID="1.2.840.113549.1.1.1";async function hashAndVerify$1(y,u,h,b){var _,E;const v=await webcrypto.get().subtle.importKey("jwk",y,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);(_=b==null?void 0:b.signal)==null||_.throwIfAborted();const w=await webcrypto.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},v,u,h instanceof Uint8Array?h:h.subarray());return(E=b==null?void 0:b.signal)==null||E.throwIfAborted(),w}const PUBLIC_KEY_BYTE_LENGTH=33;function hashAndVerify(y,u,h,b){var w;const v=sha256$4.digest(h instanceof Uint8Array?h:h.subarray());if(isPromise(v))return v.then(({digest:_})=>{var E;return(E=b==null?void 0:b.signal)==null||E.throwIfAborted(),secp256k1$1.verify(u,_,y)}).catch(_=>{throw _.name==="AbortError"?_:new VerificationError(String(_))});try{return(w=b==null?void 0:b.signal)==null||w.throwIfAborted(),secp256k1$1.verify(u,v.digest,y)}catch(_){throw new VerificationError(String(_))}}class Secp256k1PublicKey{constructor(u){Z(this,"type","secp256k1");Z(this,"raw");Z(this,"_key");this._key=validateSecp256k1PublicKey(u),this.raw=compressSecp256k1PublicKey(this._key)}toMultihash(){return identity.digest(publicKeyToProtobuf(this))}toCID(){return CID.createV1(114,this.toMultihash())}toString(){return base58btc.encode(this.toMultihash().bytes).substring(1)}equals(u){return u==null||!(u.raw instanceof Uint8Array)?!1:equals(this.raw,u.raw)}verify(u,h,b){return hashAndVerify(this._key,h,u,b)}}function unmarshalSecp256k1PublicKey(y){return new Secp256k1PublicKey(y)}function compressSecp256k1PublicKey(y){return secp256k1$1.ProjectivePoint.fromHex(y).toRawBytes(!0)}function validateSecp256k1PublicKey(y){try{return secp256k1$1.ProjectivePoint.fromHex(y),y}catch(u){throw new InvalidPublicKeyError$1(String(u))}}function publicKeyFromRaw(y){var b,v;if(y.byteLength===PUBLIC_KEY_BYTE_LENGTH$1)return unmarshalEd25519PublicKey(y);if(y.byteLength===PUBLIC_KEY_BYTE_LENGTH)return unmarshalSecp256k1PublicKey(y);const u=decodeDer(y),h=(b=u[1])==null?void 0:b[0];if(h===ECDSA_P_256_OID||h===ECDSA_P_384_OID||h===ECDSA_P_521_OID)return pkiMessageToECDSAPublicKey(u);if(((v=u[0])==null?void 0:v[0])===RSAES_PKCS1_V1_5_OID)return pkixMessageToRSAPublicKey(u,y);throw new InvalidParametersError$2("Could not extract public key from raw bytes")}function publicKeyToProtobuf(y){return PublicKey.encode({Type:KeyType[y.type],Data:y.raw})}const inspect=Symbol.for("nodejs.util.inspect.custom"),LIBP2P_KEY_CODE=114;var Dh;class PeerIdImpl{constructor(u){Z(this,"type");Z(this,"multihash");Z(this,"publicKey");Z(this,"string");Z(this,Dh,!0);this.type=u.type,this.multihash=u.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}toString(){return this.string==null&&(this.string=base58btc.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return CID.createV1(LIBP2P_KEY_CODE,this.multihash)}toJSON(){return this.toString()}equals(u){var h;if(u==null)return!1;if(u instanceof Uint8Array)return equals(this.multihash.bytes,u);if(typeof u=="string")return this.toString()===u;if(((h=u==null?void 0:u.toMultihash())==null?void 0:h.bytes)!=null)return equals(this.multihash.bytes,u.toMultihash().bytes);throw new Error("not valid Id")}[(Dh=peerIdSymbol,inspect)](){return`PeerId(${this.toString()})`}}class RSAPeerId extends PeerIdImpl{constructor(h){super({...h,type:"RSA"});Z(this,"type","RSA");Z(this,"publicKey");this.publicKey=h.publicKey}}class Ed25519PeerId extends PeerIdImpl{constructor(h){super({...h,type:"Ed25519"});Z(this,"type","Ed25519");Z(this,"publicKey");this.publicKey=h.publicKey}}class Secp256k1PeerId extends PeerIdImpl{constructor(h){super({...h,type:"secp256k1"});Z(this,"type","secp256k1");Z(this,"publicKey");this.publicKey=h.publicKey}}function peerIdFromPublicKey(y){if(y.type==="Ed25519")return new Ed25519PeerId({multihash:y.toCID().multihash,publicKey:y});if(y.type==="secp256k1")return new Secp256k1PeerId({multihash:y.toCID().multihash,publicKey:y});if(y.type==="RSA")return new RSAPeerId({multihash:y.toCID().multihash,publicKey:y});throw new UnsupportedKeyTypeError$1}const ERR_TYPE_NOT_IMPLEMENTED="Keypair type not implemented";function createPeerIdFromPublicKey(y){const u=publicKeyFromRaw(y);if(u.type!=="secp256k1")throw new Error(ERR_TYPE_NOT_IMPLEMENTED);return peerIdFromPublicKey(u)}function decodeMultiaddrs(y){const u=[];let h=0;for(;h<y.length;){const v=new DataView(y.buffer,h,MULTIADDR_LENGTH_SIZE).getUint16(0);h+=MULTIADDR_LENGTH_SIZE;const w=y.slice(h,h+v);h+=v,u.push(multiaddr(w))}return u}function encodeMultiaddrs(y){const u=y.reduce((w,_)=>w+MULTIADDR_LENGTH_SIZE+_.bytes.length,0),h=new Uint8Array(u),b=new DataView(h.buffer);let v=0;return y.forEach(w=>{if(w.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");b.setUint16(v,w.bytes.length),v+=MULTIADDR_LENGTH_SIZE,h.set(w.bytes,v),v+=w.bytes.length}),h}function encodeWaku2(y){let u=0;return y.lightPush&&(u+=1),u=u<<1,y.filter&&(u+=1),u=u<<1,y.store&&(u+=1),u=u<<1,y.relay&&(u+=1),u}function decodeWaku2(y){const u={relay:!1,store:!1,filter:!1,lightPush:!1};return y%2&&(u.relay=!0),y=y>>1,y%2&&(u.store=!0),y=y>>1,y%2&&(u.filter=!0),y=y>>1,y%2&&(u.lightPush=!0),u}class RawEnr extends Map{constructor(h={},b=BigInt(1),v){super(Object.entries(h));Z(this,"seq");Z(this,"signature");this.seq=b,this.signature=v}set(h,b){return this.signature=void 0,this.seq++,super.set(h,b)}get id(){const h=this.get("id");if(!h)throw new Error("id not found.");return bytesToUtf8(h)}get publicKey(){switch(this.id){case"v4":return this.get("secp256k1");default:throw new Error(ERR_INVALID_ID)}}get rs(){const h=this.get("rs");if(h)return decodeRelayShard(h)}get rsv(){const h=this.get("rsv");if(h)return decodeRelayShard(h)}get ip(){return getStringValue(this,"ip","ip4")}set ip(h){setStringValue(this,"ip","ip4",h)}get tcp(){return getNumberAsStringValue(this,"tcp","tcp")}set tcp(h){setNumberAsStringValue(this,"tcp","tcp",h)}get udp(){return getNumberAsStringValue(this,"udp","udp")}set udp(h){setNumberAsStringValue(this,"udp","udp",h)}get ip6(){return getStringValue(this,"ip6","ip6")}set ip6(h){setStringValue(this,"ip6","ip6",h)}get tcp6(){return getNumberAsStringValue(this,"tcp6","tcp")}set tcp6(h){setNumberAsStringValue(this,"tcp6","tcp",h)}get udp6(){return getNumberAsStringValue(this,"udp6","udp")}set udp6(h){setNumberAsStringValue(this,"udp6","udp",h)}get multiaddrs(){const h=this.get("multiaddrs");if(h)return decodeMultiaddrs(h)}set multiaddrs(h){deleteUndefined(this,"multiaddrs",h,encodeMultiaddrs)}get waku2(){const h=this.get("waku2");if(h)return decodeWaku2(h[0])}set waku2(h){deleteUndefined(this,"waku2",h,b=>new Uint8Array([encodeWaku2(b)]))}}function getStringValue(y,u,h){const b=y.get(u);if(b)return convertToString(h,b)}function getNumberAsStringValue(y,u,h){const b=y.get(u);if(b)return Number(convertToString(h,b))}function setStringValue(y,u,h,b){deleteUndefined(y,u,b,convertToBytes.bind({},h))}function setNumberAsStringValue(y,u,h,b){setStringValue(y,u,h,b==null?void 0:b.toString(10))}function deleteUndefined(y,u,h,b){h!==void 0?y.set(u,b(h)):y.delete(u)}async function sign(y,u){return sign$1(keccak256(u),y,{der:!1})}function nodeId(y){const h=Point.fromHex(y).toRawBytes(!1);return bytesToHex$1(keccak256(h.slice(1)))}const log$a=new Logger$1("enr");var TransportProtocol;(function(y){y.TCP="tcp",y.UDP="udp"})(TransportProtocol||(TransportProtocol={}));var TransportProtocolPerIpVersion;(function(y){y.TCP4="tcp4",y.UDP4="udp4",y.TCP6="tcp6",y.UDP6="udp6"})(TransportProtocolPerIpVersion||(TransportProtocolPerIpVersion={}));const Zu=class Zu extends RawEnr{constructor(){super(...arguments);Z(this,"peerId");Z(this,"getLocationMultiaddr",locationMultiaddrFromEnrFields.bind({},this))}static create(h={},b=BigInt(1),v){const w=new Zu(h,b,v);try{const _=w.publicKey;_&&(w.peerId=createPeerIdFromPublicKey(_))}catch(_){log$a.error("Could not calculate peer id for ENR",_)}return w}get nodeId(){switch(this.id){case"v4":return this.publicKey?nodeId(this.publicKey):void 0;default:throw new Error(ERR_INVALID_ID)}}get shardInfo(){return this.rs&&this.rsv&&log$a.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(h){const b=h.protoNames();if(b.length!==2&&b[1]!=="udp"&&b[1]!=="tcp")throw new Error("Invalid multiaddr");const v=h.tuples();if(!v[0][1]||!v[1][1])throw new Error("Invalid multiaddr");v[0][0]===4?(this.set("ip",v[0][1]),this.set(b[1],v[1][1])):(this.set("ip6",v[0][1]),this.set(b[1]+"6",v[1][1]))}getAllLocationMultiaddrs(){const h=[];for(const v of Object.values(TransportProtocolPerIpVersion)){const w=this.getLocationMultiaddr(v);w&&h.push(w)}const b=this.multiaddrs??[];return h.concat(b).map(v=>this.peerId?v.encapsulate(`/p2p/${this.peerId.toString()}`):v)}get peerInfo(){const h=this.peerId;if(h)return{id:h,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(h){if(this.peerId){const b=this.getLocationMultiaddr(h);if(b)return b.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const h=this.peerId;return this.multiaddrs.map(b=>b.encapsulate(`/p2p/${h.toString()}`))}return[]}verify(h,b){if(!this.get("id")||this.id!=="v4")throw new Error(ERR_INVALID_ID);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return verifySignature(b,keccak256(h),this.publicKey)}async sign(h,b){switch(this.id){case"v4":this.signature=await sign(b,h);break;default:throw new Error(ERR_INVALID_ID)}return this.signature}};Z(Zu,"RECORD_PREFIX","enr:");let ENR=Zu;const version$2="logger/5.8.0";let _permanentCensorErrors=!1,_censorErrors=!1;const LogLevels={debug:1,default:2,info:2,warning:3,error:4,off:5};let _logLevel=LogLevels.default,_globalLogger=null;function _checkNormalize(){try{const y=[];if(["NFD","NFC","NFKD","NFKC"].forEach(u=>{try{if("test".normalize(u)!=="test")throw new Error("bad normalize")}catch{y.push(u)}}),y.length)throw new Error("missing "+y.join(", "));if("é".normalize("NFD")!=="é")throw new Error("broken implementation")}catch(y){return y.message}return null}const _normalizeError=_checkNormalize();var LogLevel;(function(y){y.DEBUG="DEBUG",y.INFO="INFO",y.WARNING="WARNING",y.ERROR="ERROR",y.OFF="OFF"})(LogLevel||(LogLevel={}));var ErrorCode;(function(y){y.UNKNOWN_ERROR="UNKNOWN_ERROR",y.NOT_IMPLEMENTED="NOT_IMPLEMENTED",y.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",y.NETWORK_ERROR="NETWORK_ERROR",y.SERVER_ERROR="SERVER_ERROR",y.TIMEOUT="TIMEOUT",y.BUFFER_OVERRUN="BUFFER_OVERRUN",y.NUMERIC_FAULT="NUMERIC_FAULT",y.MISSING_NEW="MISSING_NEW",y.INVALID_ARGUMENT="INVALID_ARGUMENT",y.MISSING_ARGUMENT="MISSING_ARGUMENT",y.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",y.CALL_EXCEPTION="CALL_EXCEPTION",y.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",y.NONCE_EXPIRED="NONCE_EXPIRED",y.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",y.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",y.TRANSACTION_REPLACED="TRANSACTION_REPLACED",y.ACTION_REJECTED="ACTION_REJECTED"})(ErrorCode||(ErrorCode={}));const HEX="0123456789abcdef";class Logger{constructor(u){Object.defineProperty(this,"version",{enumerable:!0,value:u,writable:!1})}_log(u,h){const b=u.toLowerCase();LogLevels[b]==null&&this.throwArgumentError("invalid log level name","logLevel",u),!(_logLevel>LogLevels[b])&&console.log.apply(console,h)}debug(...u){this._log(Logger.levels.DEBUG,u)}info(...u){this._log(Logger.levels.INFO,u)}warn(...u){this._log(Logger.levels.WARNING,u)}makeError(u,h,b){if(_censorErrors)return this.makeError("censored error",h,{});h||(h=Logger.errors.UNKNOWN_ERROR),b||(b={});const v=[];Object.keys(b).forEach(S=>{const x=b[S];try{if(x instanceof Uint8Array){let T="";for(let C=0;C<x.length;C++)T+=HEX[x[C]>>4],T+=HEX[x[C]&15];v.push(S+"=Uint8Array(0x"+T+")")}else v.push(S+"="+JSON.stringify(x))}catch{v.push(S+"="+JSON.stringify(b[S].toString()))}}),v.push(`code=${h}`),v.push(`version=${this.version}`);const w=u;let _="";switch(h){case ErrorCode.NUMERIC_FAULT:{_="NUMERIC_FAULT";const S=u;switch(S){case"overflow":case"underflow":case"division-by-zero":_+="-"+S;break;case"negative-power":case"negative-width":_+="-unsupported";break;case"unbound-bitwise-result":_+="-unbound-result";break}break}case ErrorCode.CALL_EXCEPTION:case ErrorCode.INSUFFICIENT_FUNDS:case ErrorCode.MISSING_NEW:case ErrorCode.NONCE_EXPIRED:case ErrorCode.REPLACEMENT_UNDERPRICED:case ErrorCode.TRANSACTION_REPLACED:case ErrorCode.UNPREDICTABLE_GAS_LIMIT:_=h;break}_&&(u+=" [ See: https://links.ethers.org/v5-errors-"+_+" ]"),v.length&&(u+=" ("+v.join(", ")+")");const E=new Error(u);return E.reason=w,E.code=h,Object.keys(b).forEach(function(S){E[S]=b[S]}),E}throwError(u,h,b){throw this.makeError(u,h,b)}throwArgumentError(u,h,b){return this.throwError(u,Logger.errors.INVALID_ARGUMENT,{argument:h,value:b})}assert(u,h,b,v){u||this.throwError(h,b,v)}assertArgument(u,h,b,v){u||this.throwArgumentError(h,b,v)}checkNormalize(u){_normalizeError&&this.throwError("platform missing String.prototype.normalize",Logger.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:_normalizeError})}checkSafeUint53(u,h){typeof u=="number"&&(h==null&&(h="value not safe"),(u<0||u>=9007199254740991)&&this.throwError(h,Logger.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:u}),u%1&&this.throwError(h,Logger.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:u}))}checkArgumentCount(u,h,b){b?b=": "+b:b="",u<h&&this.throwError("missing argument"+b,Logger.errors.MISSING_ARGUMENT,{count:u,expectedCount:h}),u>h&&this.throwError("too many arguments"+b,Logger.errors.UNEXPECTED_ARGUMENT,{count:u,expectedCount:h})}checkNew(u,h){(u===Object||u==null)&&this.throwError("missing new",Logger.errors.MISSING_NEW,{name:h.name})}checkAbstract(u,h){u===h?this.throwError("cannot instantiate abstract class "+JSON.stringify(h.name)+" directly; use a sub-class",Logger.errors.UNSUPPORTED_OPERATION,{name:u.name,operation:"new"}):(u===Object||u==null)&&this.throwError("missing new",Logger.errors.MISSING_NEW,{name:h.name})}static globalLogger(){return _globalLogger||(_globalLogger=new Logger(version$2)),_globalLogger}static setCensorship(u,h){if(!u&&h&&this.globalLogger().throwError("cannot permanently disable censorship",Logger.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),_permanentCensorErrors){if(!u)return;this.globalLogger().throwError("error censorship permanent",Logger.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}_censorErrors=!!u,_permanentCensorErrors=!!h}static setLogLevel(u){const h=LogLevels[u.toLowerCase()];if(h==null){Logger.globalLogger().warn("invalid log level - "+u);return}_logLevel=h}static from(u){return new Logger(u)}}Logger.errors=ErrorCode;Logger.levels=LogLevel;const version$1="bytes/5.8.0",logger$1=new Logger(version$1);function isHexable(y){return!!y.toHexString}function addSlice(y){return y.slice||(y.slice=function(){const u=Array.prototype.slice.call(arguments);return addSlice(new Uint8Array(Array.prototype.slice.apply(y,u)))}),y}function isBytesLike(y){return isHexString(y)&&!(y.length%2)||isBytes(y)}function isInteger(y){return typeof y=="number"&&y==y&&y%1===0}function isBytes(y){if(y==null)return!1;if(y.constructor===Uint8Array)return!0;if(typeof y=="string"||!isInteger(y.length)||y.length<0)return!1;for(let u=0;u<y.length;u++){const h=y[u];if(!isInteger(h)||h<0||h>=256)return!1}return!0}function arrayify(y,u){if(u||(u={}),typeof y=="number"){logger$1.checkSafeUint53(y,"invalid arrayify value");const h=[];for(;y;)h.unshift(y&255),y=parseInt(String(y/256));return h.length===0&&h.push(0),addSlice(new Uint8Array(h))}if(u.allowMissingPrefix&&typeof y=="string"&&y.substring(0,2)!=="0x"&&(y="0x"+y),isHexable(y)&&(y=y.toHexString()),isHexString(y)){let h=y.substring(2);h.length%2&&(u.hexPad==="left"?h="0"+h:u.hexPad==="right"?h+="0":logger$1.throwArgumentError("hex data is odd-length","value",y));const b=[];for(let v=0;v<h.length;v+=2)b.push(parseInt(h.substring(v,v+2),16));return addSlice(new Uint8Array(b))}return isBytes(y)?addSlice(new Uint8Array(y)):logger$1.throwArgumentError("invalid arrayify value","value",y)}function isHexString(y,u){return!(typeof y!="string"||!y.match(/^0x[0-9A-Fa-f]*$/))}const HexCharacters="0123456789abcdef";function hexlify(y,u){if(u||(u={}),typeof y=="number"){logger$1.checkSafeUint53(y,"invalid hexlify value");let h="";for(;y;)h=HexCharacters[y&15]+h,y=Math.floor(y/16);return h.length?(h.length%2&&(h="0"+h),"0x"+h):"0x00"}if(typeof y=="bigint")return y=y.toString(16),y.length%2?"0x0"+y:"0x"+y;if(u.allowMissingPrefix&&typeof y=="string"&&y.substring(0,2)!=="0x"&&(y="0x"+y),isHexable(y))return y.toHexString();if(isHexString(y))return y.length%2&&(u.hexPad==="left"?y="0x0"+y.substring(2):u.hexPad==="right"?y+="0":logger$1.throwArgumentError("hex data is odd-length","value",y)),y.toLowerCase();if(isBytes(y)){let h="0x";for(let b=0;b<y.length;b++){let v=y[b];h+=HexCharacters[(v&240)>>4]+HexCharacters[v&15]}return h}return logger$1.throwArgumentError("invalid hexlify value","value",y)}const version="rlp/5.8.0",logger=new Logger(version);function arrayifyInteger(y){const u=[];for(;y;)u.unshift(y&255),y>>=8;return u}function unarrayifyInteger(y,u,h){let b=0;for(let v=0;v<h;v++)b=b*256+y[u+v];return b}function _encode(y){if(Array.isArray(y)){let b=[];if(y.forEach(function(w){b=b.concat(_encode(w))}),b.length<=55)return b.unshift(192+b.length),b;const v=arrayifyInteger(b.length);return v.unshift(247+v.length),v.concat(b)}isBytesLike(y)||logger.throwArgumentError("RLP object must be BytesLike","object",y);const u=Array.prototype.slice.call(arrayify(y));if(u.length===1&&u[0]<=127)return u;if(u.length<=55)return u.unshift(128+u.length),u;const h=arrayifyInteger(u.length);return h.unshift(183+h.length),h.concat(u)}function encode(y){return hexlify(_encode(y))}function _decodeChildren(y,u,h,b){const v=[];for(;h<u+1+b;){const w=_decode(y,h);v.push(w.result),h+=w.consumed,h>u+1+b&&logger.throwError("child data too short",Logger.errors.BUFFER_OVERRUN,{})}return{consumed:1+b,result:v}}function _decode(y,u){if(y.length===0&&logger.throwError("data too short",Logger.errors.BUFFER_OVERRUN,{}),y[u]>=248){const h=y[u]-247;u+1+h>y.length&&logger.throwError("data short segment too short",Logger.errors.BUFFER_OVERRUN,{});const b=unarrayifyInteger(y,u+1,h);return u+1+h+b>y.length&&logger.throwError("data long segment too short",Logger.errors.BUFFER_OVERRUN,{}),_decodeChildren(y,u,u+1+h,h+b)}else if(y[u]>=192){const h=y[u]-192;return u+1+h>y.length&&logger.throwError("data array too short",Logger.errors.BUFFER_OVERRUN,{}),_decodeChildren(y,u,u+1,h)}else if(y[u]>=184){const h=y[u]-183;u+1+h>y.length&&logger.throwError("data array too short",Logger.errors.BUFFER_OVERRUN,{});const b=unarrayifyInteger(y,u+1,h);u+1+h+b>y.length&&logger.throwError("data array too short",Logger.errors.BUFFER_OVERRUN,{});const v=hexlify(y.slice(u+1+h,u+1+h+b));return{consumed:1+h+b,result:v}}else if(y[u]>=128){const h=y[u]-128;u+1+h>y.length&&logger.throwError("data too short",Logger.errors.BUFFER_OVERRUN,{});const b=hexlify(y.slice(u+1,u+1+h));return{consumed:1+h,result:b}}return{consumed:1,result:hexlify(y[u])}}function decode(y){const u=arrayify(y),h=_decode(u,0);return h.consumed!==u.length&&logger.throwArgumentError("invalid rlp data","data",y),h.result}const log$9=new Logger$1("enr:decoder");class EnrDecoder{static fromString(u){if(!u.startsWith(ENR.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${ENR.RECORD_PREFIX}'`);return EnrDecoder.fromRLP(fromString(u.slice(4),"base64url"))}static fromRLP(u){const h=decode(u).map(hexToBytes$1);return fromValues(h)}}async function fromValues(y){const{signature:u,seq:h,kvs:b}=checkValues(y),v={};for(let E=0;E<b.length;E+=2)try{v[bytesToUtf8(b[E])]=b[E+1]}catch(S){log$9.error("Failed to decode ENR key to UTF-8, skipping it",b[E],S)}const w=decodeSeq(h),_=ENR.create(v,w,u);return checkSignature(h,b,_,u),_}function decodeSeq(y){return y.length?BigInt("0x"+bytesToHex$1(y)):BigInt(0)}function checkValues(y){if(!Array.isArray(y))throw new Error("Decoded ENR must be an array");if(y.length%2!==0)throw new Error("Decoded ENR must have an even number of elements");const[u,h,...b]=y;if(!u||Array.isArray(u))throw new Error("Decoded ENR invalid signature: must be a byte array");if(!h||Array.isArray(h))throw new Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:u,seq:h,kvs:b}}function checkSignature(y,u,h,b){const v=hexToBytes$1(encode([y,...u]));if(!h.verify(v,b))throw new Error("Unable to verify ENR signature")}var An,vr,Er,Yi,ac,Ji,ir,qu,Jn,qh,nd,id,sd,Hh,Hu;class QuickLRU extends Map{constructor(h={}){super();ur(this,ir);ur(this,An,0);ur(this,vr,new Map);ur(this,Er,new Map);ur(this,Yi);ur(this,ac);ur(this,Ji);if(!(h.maxSize&&h.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof h.maxAge=="number"&&h.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");Ft(this,Yi,h.maxSize),Ft(this,ac,h.maxAge||Number.POSITIVE_INFINITY),Ft(this,Ji,h.onEviction)}get __oldCache(){return je(this,Er)}get(h){if(je(this,vr).has(h)){const b=je(this,vr).get(h);return $t(this,ir,nd).call(this,h,b)}if(je(this,Er).has(h)){const b=je(this,Er).get(h);if($t(this,ir,Jn).call(this,h,b)===!1)return $t(this,ir,Hh).call(this,h,b),b.value}}set(h,b,{maxAge:v=je(this,ac)}={}){const w=typeof v=="number"&&v!==Number.POSITIVE_INFINITY?Date.now()+v:void 0;return je(this,vr).has(h)?je(this,vr).set(h,{value:b,expiry:w}):$t(this,ir,sd).call(this,h,{value:b,expiry:w}),this}has(h){return je(this,vr).has(h)?!$t(this,ir,Jn).call(this,h,je(this,vr).get(h)):je(this,Er).has(h)?!$t(this,ir,Jn).call(this,h,je(this,Er).get(h)):!1}peek(h){if(je(this,vr).has(h))return $t(this,ir,id).call(this,h,je(this,vr));if(je(this,Er).has(h))return $t(this,ir,id).call(this,h,je(this,Er))}expiresIn(h){const b=je(this,vr).get(h)??je(this,Er).get(h);if(b)return b.expiry?b.expiry-Date.now():Number.POSITIVE_INFINITY}delete(h){const b=je(this,vr).delete(h);return b&&Ls(this,An)._--,je(this,Er).delete(h)||b}clear(){je(this,vr).clear(),je(this,Er).clear(),Ft(this,An,0)}resize(h){if(!(h&&h>0))throw new TypeError("`maxSize` must be a number greater than 0");const b=[...$t(this,ir,Hu).call(this)],v=b.length-h;v<0?(Ft(this,vr,new Map(b)),Ft(this,Er,new Map),Ft(this,An,b.length)):(v>0&&$t(this,ir,qu).call(this,b.slice(0,v)),Ft(this,Er,new Map(b.slice(v))),Ft(this,vr,new Map),Ft(this,An,0)),Ft(this,Yi,h)}evict(h=1){const b=Number(h);if(!b||b<=0)return;const v=[...$t(this,ir,Hu).call(this)],w=Math.trunc(Math.min(b,Math.max(v.length-1,0)));w<=0||($t(this,ir,qu).call(this,v.slice(0,w)),Ft(this,Er,new Map(v.slice(w))),Ft(this,vr,new Map),Ft(this,An,0))}*keys(){for(const[h]of this)yield h}*values(){for(const[,h]of this)yield h}*[Symbol.iterator](){for(const h of je(this,vr)){const[b,v]=h;$t(this,ir,Jn).call(this,b,v)===!1&&(yield[b,v.value])}for(const h of je(this,Er)){const[b,v]=h;je(this,vr).has(b)||$t(this,ir,Jn).call(this,b,v)===!1&&(yield[b,v.value])}}*entriesDescending(){let h=[...je(this,vr)];for(let b=h.length-1;b>=0;--b){const v=h[b],[w,_]=v;$t(this,ir,Jn).call(this,w,_)===!1&&(yield[w,_.value])}h=[...je(this,Er)];for(let b=h.length-1;b>=0;--b){const v=h[b],[w,_]=v;je(this,vr).has(w)||$t(this,ir,Jn).call(this,w,_)===!1&&(yield[w,_.value])}}*entriesAscending(){for(const[h,b]of $t(this,ir,Hu).call(this))yield[h,b.value]}get size(){if(!je(this,An))return je(this,Er).size;let h=0;for(const b of je(this,Er).keys())je(this,vr).has(b)||h++;return Math.min(je(this,An)+h,je(this,Yi))}get maxSize(){return je(this,Yi)}entries(){return this.entriesAscending()}forEach(h,b=this){for(const[v,w]of this.entriesAscending())h.call(b,w,v,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}An=new WeakMap,vr=new WeakMap,Er=new WeakMap,Yi=new WeakMap,ac=new WeakMap,Ji=new WeakMap,ir=new WeakSet,qu=function(h){if(typeof je(this,Ji)=="function")for(const[b,v]of h)je(this,Ji).call(this,b,v.value)},Jn=function(h,b){return typeof b.expiry=="number"&&b.expiry<=Date.now()?(typeof je(this,Ji)=="function"&&je(this,Ji).call(this,h,b.value),this.delete(h)):!1},qh=function(h,b){if($t(this,ir,Jn).call(this,h,b)===!1)return b.value},nd=function(h,b){return b.expiry?$t(this,ir,qh).call(this,h,b):b.value},id=function(h,b){const v=b.get(h);return $t(this,ir,nd).call(this,h,v)},sd=function(h,b){je(this,vr).set(h,b),Ls(this,An)._++,je(this,An)>=je(this,Yi)&&(Ft(this,An,0),$t(this,ir,qu).call(this,je(this,Er)),Ft(this,Er,je(this,vr)),Ft(this,vr,new Map))},Hh=function(h,b){je(this,Er).delete(h),$t(this,ir,sd).call(this,h,b)},Hu=function*(){for(const h of je(this,Er)){const[b,v]=h;je(this,vr).has(b)||$t(this,ir,Jn).call(this,b,v)===!1&&(yield h)}for(const h of je(this,vr)){const[b,v]=h;$t(this,ir,Jn).call(this,b,v)===!1&&(yield h)}};function buildResource(y,u,h){return`${y}?name=${u}&type=${h}`}async function request(y,u){return await(await fetch(y,{headers:new Headers({accept:"application/dns-json"}),signal:u})).json()}function getCacheKey(y,u){return`${u}_${y}`}const log$8=Object.assign(weald("dns-over-http-resolver"),{error:weald("dns-over-http-resolver:error")});class Resolver{constructor(u={}){Z(this,"_cache");Z(this,"_TXTcache");Z(this,"_servers");Z(this,"_request");Z(this,"_abortControllers");this._cache=new QuickLRU({maxSize:(u==null?void 0:u.maxCache)??100}),this._TXTcache=new QuickLRU({maxSize:(u==null?void 0:u.maxCache)??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=u.request??request,this._abortControllers=[]}cancel(){this._abortControllers.forEach(u=>{u.abort()})}getServers(){return this._servers}_getShuffledServers(){const u=[...this._servers];for(let h=u.length-1;h>0;h--){const b=Math.floor(Math.random()*h),v=u[h];u[h]=u[b],u[b]=v}return u}setServers(u){this._servers=u}async resolve(u,h="A"){switch(h){case"A":return this.resolve4(u);case"AAAA":return this.resolve6(u);case"TXT":return this.resolveTxt(u);default:throw new Error(`${h} is not supported`)}}async resolve4(u){const h="A",b=this._cache.get(getCacheKey(u,h));if(b!=null)return b;let v=!1;for(const w of this._getShuffledServers()){const _=new AbortController;this._abortControllers.push(_);try{const E=await this._request(buildResource(w,u,h),_.signal),S=E.Answer.map(T=>T.data),x=Math.min(...E.Answer.map(T=>T.TTL));return this._cache.set(getCacheKey(u,h),S,{maxAge:x}),S}catch{_.signal.aborted&&(v=!0),log$8.error(`${w} could not resolve ${u} record ${h}`)}finally{this._abortControllers=this._abortControllers.filter(E=>E!==_)}}throw v?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${u} record ${h}`)}async resolve6(u){const h="AAAA",b=this._cache.get(getCacheKey(u,h));if(b!=null)return b;let v=!1;for(const w of this._getShuffledServers()){const _=new AbortController;this._abortControllers.push(_);try{const E=await this._request(buildResource(w,u,h),_.signal),S=E.Answer.map(T=>T.data),x=Math.min(...E.Answer.map(T=>T.TTL));return this._cache.set(getCacheKey(u,h),S,{maxAge:x}),S}catch{_.signal.aborted&&(v=!0),log$8.error(`${w} could not resolve ${u} record ${h}`)}finally{this._abortControllers=this._abortControllers.filter(E=>E!==_)}}throw v?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${u} record ${h}`)}async resolveTxt(u){const h="TXT",b=this._TXTcache.get(getCacheKey(u,h));if(b!=null)return b;let v=!1;for(const w of this._getShuffledServers()){const _=new AbortController;this._abortControllers.push(_);try{const E=await this._request(buildResource(w,u,h),_.signal),S=E.Answer.map(T=>[T.data.replace(/['"]+/g,"")]),x=Math.min(...E.Answer.map(T=>T.TTL));return this._TXTcache.set(getCacheKey(u,h),S,{maxAge:x}),S}catch{_.signal.aborted&&(v=!0),log$8.error(`${w} could not resolve ${u} record ${h}`)}finally{this._abortControllers=this._abortControllers.filter(E=>E!==_)}}throw v?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${u} record ${h}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}}const log$7=new Logger$1("dns-over-https");class DnsOverHttps{constructor(u=new Resolver){Z(this,"resolver");this.resolver=u}static async create(){return new DnsOverHttps}async resolveTXT(u){let h;try{h=await this.resolver.resolveTxt(u)}catch(v){throw log$7.error("query failed: ",v),new Error("DNS query failed")}if(!h)throw new Error(`Could not resolve ${u}`);const b=[];return h.forEach(v=>{typeof v=="string"?b.push(v):Array.isArray(v)?v.forEach(w=>{typeof w=="string"?b.push(w):b.push(bytesToUtf8(w))}):b.push(bytesToUtf8(v))}),b}}var base32$1={exports:{}};(function(y){(function(){var u=typeof window=="object"?window:{},h=!u.HI_BASE32_NO_NODE_JS&&typeof process$1=="object"&&process$1.versions&&process$1.versions.node;h&&(u=commonjsGlobal);var b=!u.HI_BASE32_NO_COMMON_JS&&!0&&y.exports,v="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),w={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},_=[0,0,0,0,0,0,0,0],E=function(X,ie){ie.length>10&&(ie="..."+ie.substr(-10));var ee=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+X+" bytes: "+ie+" <-");throw ee.position=X,ee},S=function(X){for(var ie="",ee=X.length,ae=0,de=0,Se,ve;ae<ee;){if(Se=X[ae++],Se<=127){ie+=String.fromCharCode(Se);continue}else Se>191&&Se<=223?(ve=Se&31,de=1):Se<=239?(ve=Se&15,de=2):Se<=247?(ve=Se&7,de=3):E(ae,ie);for(var Pe=0;Pe<de;++Pe)Se=X[ae++],(Se<128||Se>191)&&E(ae,ie),ve<<=6,ve+=Se&63;ve>=55296&&ve<=57343&&E(ae,ie),ve>1114111&&E(ae,ie),ve<=65535?ie+=String.fromCharCode(ve):(ve-=65536,ie+=String.fromCharCode((ve>>10)+55296),ie+=String.fromCharCode((ve&1023)+56320))}return ie},x=function(X){if(X==="")return[];if(!/^[A-Z2-7=]+$/.test(X))throw new Error("Invalid base32 characters");X=X.replace(/=/g,"");for(var ie,ee,ae,de,Se,ve,Pe,Ie,Ee=[],De=0,be=X.length,B=0,F=be>>3<<3;B<F;)ie=w[X.charAt(B++)],ee=w[X.charAt(B++)],ae=w[X.charAt(B++)],de=w[X.charAt(B++)],Se=w[X.charAt(B++)],ve=w[X.charAt(B++)],Pe=w[X.charAt(B++)],Ie=w[X.charAt(B++)],Ee[De++]=(ie<<3|ee>>>2)&255,Ee[De++]=(ee<<6|ae<<1|de>>>4)&255,Ee[De++]=(de<<4|Se>>>1)&255,Ee[De++]=(Se<<7|ve<<2|Pe>>>3)&255,Ee[De++]=(Pe<<5|Ie)&255;var M=be-F;return M===2?(ie=w[X.charAt(B++)],ee=w[X.charAt(B++)],Ee[De++]=(ie<<3|ee>>>2)&255):M===4?(ie=w[X.charAt(B++)],ee=w[X.charAt(B++)],ae=w[X.charAt(B++)],de=w[X.charAt(B++)],Ee[De++]=(ie<<3|ee>>>2)&255,Ee[De++]=(ee<<6|ae<<1|de>>>4)&255):M===5?(ie=w[X.charAt(B++)],ee=w[X.charAt(B++)],ae=w[X.charAt(B++)],de=w[X.charAt(B++)],Se=w[X.charAt(B++)],Ee[De++]=(ie<<3|ee>>>2)&255,Ee[De++]=(ee<<6|ae<<1|de>>>4)&255,Ee[De++]=(de<<4|Se>>>1)&255):M===7&&(ie=w[X.charAt(B++)],ee=w[X.charAt(B++)],ae=w[X.charAt(B++)],de=w[X.charAt(B++)],Se=w[X.charAt(B++)],ve=w[X.charAt(B++)],Pe=w[X.charAt(B++)],Ee[De++]=(ie<<3|ee>>>2)&255,Ee[De++]=(ee<<6|ae<<1|de>>>4)&255,Ee[De++]=(de<<4|Se>>>1)&255,Ee[De++]=(Se<<7|ve<<2|Pe>>>3)&255),Ee},T=function(X){for(var ie,ee,ae,de,Se,ve="",Pe=X.length,Ie=0,Ee=parseInt(Pe/5)*5;Ie<Ee;)ie=X.charCodeAt(Ie++),ee=X.charCodeAt(Ie++),ae=X.charCodeAt(Ie++),de=X.charCodeAt(Ie++),Se=X.charCodeAt(Ie++),ve+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[(ee<<4|ae>>>4)&31]+v[(ae<<1|de>>>7)&31]+v[de>>>2&31]+v[(de<<3|Se>>>5)&31]+v[Se&31];var De=Pe-Ee;return De===1?(ie=X.charCodeAt(Ie),ve+=v[ie>>>3]+v[ie<<2&31]+"======"):De===2?(ie=X.charCodeAt(Ie++),ee=X.charCodeAt(Ie),ve+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[ee<<4&31]+"===="):De===3?(ie=X.charCodeAt(Ie++),ee=X.charCodeAt(Ie++),ae=X.charCodeAt(Ie),ve+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[(ee<<4|ae>>>4)&31]+v[ae<<1&31]+"==="):De===4&&(ie=X.charCodeAt(Ie++),ee=X.charCodeAt(Ie++),ae=X.charCodeAt(Ie++),de=X.charCodeAt(Ie),ve+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[(ee<<4|ae>>>4)&31]+v[(ae<<1|de>>>7)&31]+v[de>>>2&31]+v[de<<3&31]+"="),ve},C=function(X){var ie,ee,ae,de,Se,ve,Pe=!1,Ie="",Ee=0,De,be=0,B=X.length;if(X==="")return Ie;do{for(_[0]=_[5],_[1]=_[6],_[2]=_[7],De=be;Ee<B&&De<5;++Ee)ve=X.charCodeAt(Ee),ve<128?_[De++]=ve:ve<2048?(_[De++]=192|ve>>6,_[De++]=128|ve&63):ve<55296||ve>=57344?(_[De++]=224|ve>>12,_[De++]=128|ve>>6&63,_[De++]=128|ve&63):(ve=65536+((ve&1023)<<10|X.charCodeAt(++Ee)&1023),_[De++]=240|ve>>18,_[De++]=128|ve>>12&63,_[De++]=128|ve>>6&63,_[De++]=128|ve&63);be=De-5,Ee===B&&++Ee,Ee>B&&De<6&&(Pe=!0),ie=_[0],De>4?(ee=_[1],ae=_[2],de=_[3],Se=_[4],Ie+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[(ee<<4|ae>>>4)&31]+v[(ae<<1|de>>>7)&31]+v[de>>>2&31]+v[(de<<3|Se>>>5)&31]+v[Se&31]):De===1?Ie+=v[ie>>>3]+v[ie<<2&31]+"======":De===2?(ee=_[1],Ie+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[ee<<4&31]+"===="):De===3?(ee=_[1],ae=_[2],Ie+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[(ee<<4|ae>>>4)&31]+v[ae<<1&31]+"==="):(ee=_[1],ae=_[2],de=_[3],Ie+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[(ee<<4|ae>>>4)&31]+v[(ae<<1|de>>>7)&31]+v[de>>>2&31]+v[de<<3&31]+"=")}while(!Pe);return Ie},O=function(X){for(var ie,ee,ae,de,Se,ve="",Pe=X.length,Ie=0,Ee=parseInt(Pe/5)*5;Ie<Ee;)ie=X[Ie++],ee=X[Ie++],ae=X[Ie++],de=X[Ie++],Se=X[Ie++],ve+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[(ee<<4|ae>>>4)&31]+v[(ae<<1|de>>>7)&31]+v[de>>>2&31]+v[(de<<3|Se>>>5)&31]+v[Se&31];var De=Pe-Ee;return De===1?(ie=X[Ie],ve+=v[ie>>>3]+v[ie<<2&31]+"======"):De===2?(ie=X[Ie++],ee=X[Ie],ve+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[ee<<4&31]+"===="):De===3?(ie=X[Ie++],ee=X[Ie++],ae=X[Ie],ve+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[(ee<<4|ae>>>4)&31]+v[ae<<1&31]+"==="):De===4&&(ie=X[Ie++],ee=X[Ie++],ae=X[Ie++],de=X[Ie],ve+=v[ie>>>3]+v[(ie<<2|ee>>>6)&31]+v[ee>>>1&31]+v[(ee<<4|ae>>>4)&31]+v[(ae<<1|de>>>7)&31]+v[de>>>2&31]+v[de<<3&31]+"="),ve},D=function(X,ie){var ee=typeof X!="string";return ee&&X.constructor===ArrayBuffer&&(X=new Uint8Array(X)),ee?O(X):ie?T(X):C(X)},U=function(X,ie){if(!ie)return S(x(X));if(X==="")return"";if(!/^[A-Z2-7=]+$/.test(X))throw new Error("Invalid base32 characters");var ee,ae,de,Se,ve,Pe,Ie,Ee,De="",be=X.indexOf("=");be===-1&&(be=X.length);for(var B=0,F=be>>3<<3;B<F;)ee=w[X.charAt(B++)],ae=w[X.charAt(B++)],de=w[X.charAt(B++)],Se=w[X.charAt(B++)],ve=w[X.charAt(B++)],Pe=w[X.charAt(B++)],Ie=w[X.charAt(B++)],Ee=w[X.charAt(B++)],De+=String.fromCharCode((ee<<3|ae>>>2)&255)+String.fromCharCode((ae<<6|de<<1|Se>>>4)&255)+String.fromCharCode((Se<<4|ve>>>1)&255)+String.fromCharCode((ve<<7|Pe<<2|Ie>>>3)&255)+String.fromCharCode((Ie<<5|Ee)&255);var M=be-F;return M===2?(ee=w[X.charAt(B++)],ae=w[X.charAt(B++)],De+=String.fromCharCode((ee<<3|ae>>>2)&255)):M===4?(ee=w[X.charAt(B++)],ae=w[X.charAt(B++)],de=w[X.charAt(B++)],Se=w[X.charAt(B++)],De+=String.fromCharCode((ee<<3|ae>>>2)&255)+String.fromCharCode((ae<<6|de<<1|Se>>>4)&255)):M===5?(ee=w[X.charAt(B++)],ae=w[X.charAt(B++)],de=w[X.charAt(B++)],Se=w[X.charAt(B++)],ve=w[X.charAt(B++)],De+=String.fromCharCode((ee<<3|ae>>>2)&255)+String.fromCharCode((ae<<6|de<<1|Se>>>4)&255)+String.fromCharCode((Se<<4|ve>>>1)&255)):M===7&&(ee=w[X.charAt(B++)],ae=w[X.charAt(B++)],de=w[X.charAt(B++)],Se=w[X.charAt(B++)],ve=w[X.charAt(B++)],Pe=w[X.charAt(B++)],Ie=w[X.charAt(B++)],De+=String.fromCharCode((ee<<3|ae>>>2)&255)+String.fromCharCode((ae<<6|de<<1|Se>>>4)&255)+String.fromCharCode((Se<<4|ve>>>1)&255)+String.fromCharCode((ve<<7|Pe<<2|Ie>>>3)&255)),De},te={encode:D,decode:U};U.asBytes=x,b?y.exports=te:u.base32=te})()})(base32$1);var base32Exports=base32$1.exports;const base32=getDefaultExportFromCjs$1(base32Exports),Us=class Us{static parseAndVerifyRoot(u,h){if(!u.startsWith(this.ROOT_PREFIX))throw new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const b=Us.parseRootValues(u),v=base32.decode.asBytes(h),w=u.split(" sig")[0],_=utf8ToBytes$1(w),E=fromString(b.signature,"base64url").slice(0,64);if(!verifySignature(E,keccak256(_),new Uint8Array(v)))throw new Error("Unable to verify ENRTree root signature");return b.eRoot}static parseRootValues(u){const h=u.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(h))throw new Error("Could not parse ENRTree root entry");h.shift();const[b,v,w,_]=h;if(!b)throw new Error("Could not parse 'e' value from ENRTree root entry");if(!v)throw new Error("Could not parse 'l' value from ENRTree root entry");if(!w)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!_)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:b,lRoot:v,seq:Number(w),signature:_}}static parseTree(u){if(!u.startsWith(this.TREE_PREFIX))throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const h=u.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(h))throw new Error("Could not parse ENRTree tree entry");h.shift();const[b,v]=h;if(!b)throw new Error("Could not parse public key from ENRTree tree entry");if(!v)throw new Error("Could not parse domain from ENRTree tree entry");return{publicKey:b,domain:v}}static parseBranch(u){if(!u.startsWith(this.BRANCH_PREFIX))throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return u.split(this.BRANCH_PREFIX)[1].split(",")}};Z(Us,"RECORD_PREFIX",ENR.RECORD_PREFIX),Z(Us,"TREE_PREFIX","enrtree:"),Z(Us,"BRANCH_PREFIX","enrtree-branch:"),Z(Us,"ROOT_PREFIX","enrtree-root:");let ENRTree=Us;const log$6=new Logger$1("discovery:fetch_nodes");async function*fetchNodes(y,u=10,h=3){const b=new Set;let v=0,w=0;for(;v<u&&w<h;){v++;const _=await y();if(!_||!_.nodeId){w++;continue}b.has(_.nodeId)||(b.add(_.nodeId),_.waku2&&(yield _),log$6.info(`got new peer candidate from DNS address=${_.nodeId}@${_.ip}`))}}const log$5=new Logger$1("discovery:dns");class DnsNodeDiscovery{constructor(u){Z(this,"dns");Z(this,"_DNSTreeCache");this._DNSTreeCache={},this.dns=u}static async dnsOverHttp(u){return u||(u=await DnsOverHttps.create()),new DnsNodeDiscovery(u)}async*getNextPeer(u){for(const h of shuffle(u)){const{publicKey:b,domain:v}=ENRTree.parseTree(h),w={domain:v,publicKey:b,visits:{}};for await(const _ of fetchNodes(()=>this._search(v,w)))yield _}}async _search(u,h){try{const b=await this._getTXTRecord(u,h);h.visits[u]=!0;let v,w;const _=getEntryType(b);try{switch(_){case ENRTree.ROOT_PREFIX:return v=ENRTree.parseAndVerifyRoot(b,h.publicKey),await this._search(v,h);case ENRTree.BRANCH_PREFIX:return w=ENRTree.parseBranch(b),v=selectRandomPath(w,h),await this._search(v,h);case ENRTree.RECORD_PREFIX:return EnrDecoder.fromString(b);default:return null}}catch(E){return log$5.error(`Failed to search DNS tree ${_} at subdomain ${u}: ${E}`),null}}catch(b){return log$5.error(`Failed to retrieve TXT record at subdomain ${u}: ${b}`),null}}async _getTXTRecord(u,h){if(this._DNSTreeCache[u])return this._DNSTreeCache[u];const b=u!==h.domain?`${u}.${h.domain}`:h.domain,v=await this.dns.resolveTXT(b);if(!v.length)throw new Error("Received empty result array while fetching TXT record");if(!v[0].length)throw new Error("Received empty TXT record");const w=v.join("");return this._DNSTreeCache[u]=w,w}}function getEntryType(y){return y.startsWith(ENRTree.ROOT_PREFIX)?ENRTree.ROOT_PREFIX:y.startsWith(ENRTree.BRANCH_PREFIX)?ENRTree.BRANCH_PREFIX:y.startsWith(ENRTree.RECORD_PREFIX)?ENRTree.RECORD_PREFIX:""}function selectRandomPath(y,u){const h={};for(const[v,w]of y.entries())u.visits[w]&&(h[v]=!0);if(Object.keys(h).length===y.length)throw new Error("Unresolvable circular path detected");let b;do b=Math.floor(Math.random()*y.length);while(h[b]);return y[b]}const log$4=new Logger$1("peer-discovery-dns");class PeerDiscoveryDns extends TypedEventEmitter{constructor(h,b){super();Z(this,"nextPeer");Z(this,"_started");Z(this,"_components");Z(this,"_options");this._started=!1,this._components=h,this._options=b;const{enrUrls:v}=b;log$4.info("Use following EIP-1459 ENR Tree URLs: ",v)}async start(){log$4.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:h}=this._options;Array.isArray(h)||(h=[h]);const b=await DnsNodeDiscovery.dnsOverHttp();this.nextPeer=b.getNextPeer.bind(b,h)}for await(const h of this.nextPeer()){if(!this._started)return;const{peerInfo:b,shardInfo:v}=h;if(!b)continue;const w={[DEFAULT_BOOTSTRAP_TAG_NAME]:{value:this._options.tagValue??DEFAULT_BOOTSTRAP_TAG_VALUE,ttl:this._options.tagTTL??DEFAULT_BOOTSTRAP_TAG_TTL}};let _=!1;await this._components.peerStore.has(b.id)?(await this._components.peerStore.get(b.id)).tags.has(DEFAULT_BOOTSTRAP_TAG_NAME)||(_=!0,await this._components.peerStore.merge(b.id,{tags:w})):(_=!0,await this._components.peerStore.save(b.id,{tags:w,...v&&{metadata:{shardInfo:encodeRelayShard(v)}}})),_&&this.dispatchEvent(new CustomEvent("peer",{detail:b}))}}stop(){this._started=!1}get[peerDiscoverySymbol](){return!0}get[Symbol.toStringTag](){return DNS_DISCOVERY_TAG}}function wakuDnsDiscovery(y){return u=>new PeerDiscoveryDns(u,{enrUrls:y})}const DEFAULT_PEER_EXCHANGE_REQUEST_NODES=60,DEFAULT_PEER_EXCHANGE_TAG_NAME=Tags.PEER_EXCHANGE,DEFAULT_PEER_EXCHANGE_TAG_VALUE=50,DEFAULT_PEER_EXCHANGE_TAG_TTL=3e4,PeerExchangeCodec="/vac/waku/peer-exchange/2.0.0-alpha1";class PeerExchangeRPC{constructor(u){Z(this,"proto");this.proto=u}static createRequest(u){const{numPeers:h}=u;return new PeerExchangeRPC({query:{numPeers:h},response:void 0})}encode(){return PeerExchangeRPC$1.encode(this.proto)}static decode(u){const h=PeerExchangeRPC$1.decode(u);return new PeerExchangeRPC(h)}get query(){return this.proto.query}get response(){return this.proto.response}}const log$3=new Logger$1("peer-exchange");class PeerExchange{constructor(u){Z(this,"components");Z(this,"streamManager");this.components=u,this.streamManager=new StreamManager(PeerExchangeCodec,u)}async query(u){var S;const{numPeers:h,peerId:b}=u,v=PeerExchangeRPC.createRequest({numPeers:BigInt(h)});if(!await this.components.peerStore.has(b))return{peerInfos:null,error:ProtocolError.NO_PEER_AVAILABLE};const _=await this.streamManager.getStream(b);if(!_)return log$3.error(`Failed to get a stream for remote peer:${(S=b==null?void 0:b.toString)==null?void 0:S.call(b)}`),{peerInfos:null,error:ProtocolError.NO_STREAM_AVAILABLE};const E=await pipe$1([v.encode()],encode$2,_,decode$1,async x=>await all$2(x));try{const x=new Uint8ArrayList;E.forEach(O=>{x.append(O)});const{response:T}=PeerExchangeRPC.decode(x);return T?{peerInfos:await Promise.all(T.peerInfos.map(O=>O.enr).filter(isDefined).map(async O=>({ENR:await EnrDecoder.fromRLP(O)}))),error:null}:(log$3.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:ProtocolError.EMPTY_PAYLOAD})}catch(x){return log$3.error("Failed to decode push reply",x),{peerInfos:null,error:ProtocolError.DECODE_FAILED}}}}const log$2=new Logger$1("peer-exchange-discovery");class PeerExchangeDiscovery extends TypedEventEmitter{constructor(h,b={}){super();Z(this,"components");Z(this,"peerExchange");Z(this,"options");Z(this,"isStarted",!1);Z(this,"queryingPeers",new Set);Z(this,"peerExpirationRecords",new Map);Z(this,"continuousDiscoveryInterval",null);this.components=h,this.peerExchange=new PeerExchange(h),this.options={...b,TTL:b.TTL??DEFAULT_PEER_EXCHANGE_TAG_TTL},this.handleDiscoveredPeer=this.handleDiscoveredPeer.bind(this)}start(){this.isStarted||(log$2.info("Starting peer exchange node discovery, discovering peers"),this.isStarted=!0,this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),this.continuousDiscoveryInterval=setInterval(()=>{this.handlePeriodicDiscovery()},this.options.TTL))}stop(){this.isStarted&&(log$2.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.peerExpirationRecords.clear(),this.continuousDiscoveryInterval&&clearInterval(this.continuousDiscoveryInterval),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[peerDiscoverySymbol](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}async handleDiscoveredPeer(h){this.runQuery(h.detail.peerId,h.detail.protocols)}async handlePeriodicDiscovery(){const h=this.components.connectionManager.getConnections();await Promise.all(h.map(async b=>{try{const v=b.remotePeer.toString();if(!(this.peerExpirationRecords.has(v)?this.peerExpirationRecords.get(v)<=Date.now():!0))return null;const _=await this.components.peerStore.get(b.remotePeer);return this.runQuery(b.remotePeer,_.protocols)}catch(v){return log$2.warn("Error getting peer info",v),null}}))}async runQuery(h,b){if(!b.includes(PeerExchangeCodec)||this.queryingPeers.has(h.toString())){log$2.info(`Skipping peer ${h} as it is already querying or does not support peer exchange`);return}try{this.queryingPeers.add(h.toString()),await this.query(h)}catch(v){log$2.error("Error querying peer",v)}this.peerExpirationRecords.set(h.toString(),Date.now()+this.options.TTL),this.queryingPeers.delete(h.toString())}async query(h){const b=h.toString();log$2.info(`Querying peer exchange for ${b}`);const{error:v,peerInfos:w}=await this.peerExchange.query({numPeers:DEFAULT_PEER_EXCHANGE_REQUEST_NODES,peerId:h});if(v){log$2.error(`Peer exchange query to ${b} failed`,v);return}for(const{ENR:_}of w){if(!_){log$2.warn(`No ENR in peerInfo object from ${b}, skipping`);continue}const{peerInfo:E,shardInfo:S}=_;if(!E){log$2.warn(`No peerInfo in ENR from ${b}, skipping`);continue}const T=!await this.hasShardInfo(E.id)&&S?{metadata:{shardInfo:encodeRelayShard(S)}}:void 0;await this.components.peerStore.merge(E.id,{tags:{[DEFAULT_PEER_EXCHANGE_TAG_NAME]:{value:DEFAULT_PEER_EXCHANGE_TAG_VALUE}},...T,...E.multiaddrs&&{multiaddrs:E.multiaddrs}}),log$2.info(`Discovered peer: ${E.id.toString()}`),this.dispatchEvent(new CustomEvent("peer",{detail:{id:E.id,multiaddrs:E.multiaddrs}}))}}async hasShardInfo(h){try{const b=await this.components.peerStore.get(h);return b?b.metadata.has("shardInfo"):!1}catch(b){log$2.warn(`Error getting shard info for ${h.toString()}`,b)}return!1}}function wakuPeerExchangeDiscovery(y={}){return u=>new PeerExchangeDiscovery(u,y)}const DEFAULT_PEER_CACHE_TAG_NAME=Tags.PEER_CACHE,DEFAULT_PEER_CACHE_TAG_VALUE=50,isValidStoredPeer=y=>!!y&&typeof y=="object"&&"id"in y&&typeof y.id=="string"&&"multiaddrs"in y&&Array.isArray(y.multiaddrs);class NoopCache{get(){return[]}set(u){}remove(){}}class LocalStorageCache{get(){try{const u=localStorage.getItem("waku:peers");return(u?JSON.parse(u):[]).filter(isValidStoredPeer)}catch{return[]}}set(u){try{localStorage.setItem("waku:peers",JSON.stringify(u))}catch{}}remove(){try{localStorage.removeItem("waku:peers")}catch{}}}const defaultCache=()=>{try{if(typeof localStorage<"u")return new LocalStorageCache}catch{}return new NoopCache},log$1=new Logger$1("peer-cache");class PeerCacheDiscovery extends TypedEventEmitter{constructor(h,b){super();Z(this,"components");Z(this,"isStarted",!1);Z(this,"cache");Z(this,"handleDiscoveredPeer",h=>{const{peerId:b,listenAddrs:v}=h.detail,w=v.map(x=>x.toString()),_=b.toString(),E=this.readPeerInfoFromCache(),S=E.findIndex(x=>x.id===_);S!==-1?E[S].multiaddrs=w:E.push({id:_,multiaddrs:w}),this.writePeerInfoToCache(E)});this.components=h,this.cache=(b==null?void 0:b.cache)??defaultCache()}get[Symbol.toStringTag](){return`@waku/${DEFAULT_PEER_CACHE_TAG_NAME}`}async start(){this.isStarted||(log$1.info("Starting Peer Cache Discovery"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),await this.discoverPeers(),this.isStarted=!0)}stop(){this.isStarted&&(log$1.info("Stopping Peer Cache Discovery"),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer),this.isStarted=!1)}async discoverPeers(){const h=this.readPeerInfoFromCache();for(const b of h){const v=peerIdFromString$1(b.id),w=b.multiaddrs.map(_=>multiaddr(_));await this.components.peerStore.has(v)||(await this.components.peerStore.save(v,{multiaddrs:w,tags:{[DEFAULT_PEER_CACHE_TAG_NAME]:{value:DEFAULT_PEER_CACHE_TAG_VALUE}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:v,multiaddrs:w}})))}}readPeerInfoFromCache(){try{return this.cache.get()}catch(h){return log$1.error("Error parsing peers from cache:",h),[]}}writePeerInfoToCache(h){try{this.cache.set(h)}catch(b){log$1.error("Error saving peers to cache:",b)}}}function wakuPeerCacheDiscovery(y={}){return u=>new PeerCacheDiscovery(u,y)}function getPeerDiscoveries(y,u){const h=[enrTree.SANDBOX,enrTree.TEST],b=[];return y!=null&&y.dns&&b.push(wakuDnsDiscovery(h)),(y!=null&&y.peerCache||u)&&b.push(wakuPeerCacheDiscovery({cache:u})),y!=null&&y.peerExchange&&b.push(wakuPeerExchangeDiscovery()),b}const log=new Logger$1("sdk:create"),DefaultUserAgent="js-waku",DefaultPingMaxInboundStreams=10;async function defaultLibp2p(y,u,h){!(u!=null&&u.hideWebSocketInfo)&&!isTestEnvironment()&&(console.info("%cIgnore WebSocket connection failures","background: gray; color: white; font-size: x-large"),console.info("%cWaku tries to discover peers and some of them are expected to fail","background: gray; color: white; font-size: x-large"));const b=(u==null?void 0:u.filterMultiaddrs)===!1||isTestEnvironment()?all$1:wss;return createLibp2p({transports:[webSockets({filter:b})],streamMuxers:[mplex()],connectionEncrypters:[noise()],...u,services:{identify:identify({agentVersion:h??DefaultUserAgent}),ping:ping({maxInboundStreams:(u==null?void 0:u.pingMaxInboundStreams)??DefaultPingMaxInboundStreams}),metadata:wakuMetadata(y),...u==null?void 0:u.services}})}async function createLibp2pAndUpdateOptions(y){var _;const h=(y.networkConfig??DefaultNetworkConfig).clusterId??DEFAULT_CLUSTER_ID;log.info("Creating Waku node with cluster id: ",h);const b=(y==null?void 0:y.libp2p)??{},v=b.peerDiscovery??[];y!=null&&y.defaultBootstrap?v.push(...getPeerDiscoveries({dns:!0,peerExchange:!0,peerCache:!0,...y.discovery},y.peerCache)):v.push(...getPeerDiscoveries(y.discovery,y.peerCache));const w=[...y.bootstrapPeers||[],...((_=y.store)==null?void 0:_.peers)||[]];return w.length&&v.push(bootstrap({list:w})),b.peerDiscovery=v,defaultLibp2p(h,b,y==null?void 0:y.userAgent)}async function createLightNode(y={}){const u=await createLibp2pAndUpdateOptions(y),h=new WakuNode(y,u,{store:!0,lightpush:!0,filter:!0});return(y==null?void 0:y.autoStart)!==!1&&await h.start(),h}var excHandler=0,NTI134217745={size:0,kind:17,base:null,node:null,finalizer:null},NTI134217749={size:0,kind:17,base:null,node:null,finalizer:null},NTI134217751={size:0,kind:17,base:null,node:null,finalizer:null},NTI134217743={size:0,kind:17,base:null,node:null,finalizer:null},NTI33555167={size:0,kind:17,base:null,node:null,finalizer:null},NTI33555175={size:0,kind:22,base:null,node:null,finalizer:null},NTI33554449={size:0,kind:28,base:null,node:null,finalizer:null},NTI33554450={size:0,kind:29,base:null,node:null,finalizer:null},NTI33555174={size:0,kind:22,base:null,node:null,finalizer:null},NTI33555171={size:0,kind:17,base:null,node:null,finalizer:null},NTI33555172={size:0,kind:17,base:null,node:null,finalizer:null},NTI134217741={size:0,kind:17,base:null,node:null,finalizer:null},NTI134217742={size:0,kind:17,base:null,node:null,finalizer:null},NNI134217742={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};NTI134217742.node=NNI134217742;var NNI134217741={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};NTI134217741.node=NNI134217741;var NNI33555172={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};NTI33555172.node=NNI33555172;NTI33555174.base=NTI33555171;NTI33555175.base=NTI33555171;var NNI33555171={kind:2,len:5,offset:0,typ:null,name:null,sons:[{kind:1,offset:"parent",len:0,typ:NTI33555174,name:"parent",sons:null},{kind:1,offset:"name",len:0,typ:NTI33554450,name:"name",sons:null},{kind:1,offset:"message",len:0,typ:NTI33554449,name:"msg",sons:null},{kind:1,offset:"trace",len:0,typ:NTI33554449,name:"trace",sons:null},{kind:1,offset:"up",len:0,typ:NTI33555175,name:"up",sons:null}]};NTI33555171.node=NNI33555171;var NNI33555167={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};NTI33555167.node=NNI33555167;NTI33555171.base=NTI33555167;NTI33555172.base=NTI33555171;NTI134217741.base=NTI33555172;NTI134217742.base=NTI134217741;var NNI134217743={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};NTI134217743.node=NNI134217743;NTI134217743.base=NTI134217741;var NNI134217751={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};NTI134217751.node=NNI134217751;NTI134217751.base=NTI33555172;var NNI134217749={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};NTI134217749.node=NNI134217749;NTI134217749.base=NTI33555172;var NNI134217745={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};NTI134217745.node=NNI134217745;NTI134217745.base=NTI33555172;function toJSStr(y){var u=null,h=newSeq__system_u2508(y.length),b=0,v=0;e:for(;;){if(!(b<y.length))break e;var w=y[b];if(w<128)h[v]=String.fromCharCode(w),b+=1;else{var _=newSeq__system_u2508(0);t:for(;;){var E=w.toString(16);if((E==null?0:E.length)==1?_.push("%0"):_.push("%"),_.push(E),b+=1,y.length<=b||y[b]<128)break t;w=y[b]}++excHandler;try{h[v]=decodeURIComponent(_.join("")),--excHandler}catch{--excHandler,h[v]=_.join("")}finally{}}v+=1}if(h.length<v)for(var S=h.length;S<v;++S)h.push(null);else h.length=v;return u=h.join(""),u}function raiseException(y,u){throw y.name=u,excHandler==0&&unhandledException(y),y}function modInt(y,u){return u==0&&raiseDivByZero(),u==-1&&y==2147483647&&raiseOverflow(),Math.trunc(y%u)}function absInt(y){var u,h=0;return y<0?u=y*-1:u=y,h=u,h}function divInt(y,u){return u==0&&raiseDivByZero(),u==-1&&y==2147483647&&raiseOverflow(),Math.trunc(y/u)}function mulInt(y,u){var h=y*u;return checkOverflowInt(h),h}function subInt(y,u){var h=y-u;return checkOverflowInt(h),h}function addInt(y,u){var h=y+u;return checkOverflowInt(h),h}function chckRange(y,u,h){var b=0;e:if(u<=y&&y<=h){b=y;break e}else raiseRangeError();return b}function setConstr(){for(var y={},u=0;u<arguments.length;++u){var h=arguments[u];if(typeof h=="object")for(var b=h[0];b<=h[1];++b)y[b]=!0;else y[h]=!0}return y}var ConstSet1=setConstr(17,16,4,18,27,19,23,22,21);function nimCopy(y,u,h){var b=null;switch(h.kind){case 21:case 22:case 23:case 5:isFatPointer__system_u2866(h)?b=[u[0],u[1]]:b=u;break;case 19:if(y==null)y={};else for(var v in y)delete y[v];for(var v in u)y[v]=u[v];b=y;break;case 18:case 17:h.base!=null?b=nimCopy(y,u,h.base):h.kind==17?b=y??{m_type:h}:b=y??{},nimCopyAux(b,u,h.node);break;case 4:case 16:if(ArrayBuffer.isView(u))y==null||y.length!=u.length?y=new u.constructor(u):y.set(u,0),b=y;else if(u===null)b=null;else{(y==null||y.length!=u.length)&&(y=new Array(u.length)),b=y;for(var w=0;w<u.length;++w)b[w]=nimCopy(b[w],u[w],h.base)}break;case 24:case 27:if(u===null)b=null;else{(y==null||y.length!=u.length)&&(y=new Array(u.length)),b=y;for(var w=0;w<u.length;++w)b[w]=nimCopy(b[w],u[w],h.base)}break;case 28:u!==null&&(b=u.slice(0));break;default:b=u;break}return b}function chckIndx(y,u,h){var b=0;e:if(u<=y&&y<=h){b=y;break e}else raiseIndexError(y,u,h);return b}function add__system_u1943(y,u,h){y[u]===null&&(y[u]=[]);var b=y[u].length;y[u].length+=h.length;for(var v=0;v<h.length;++v)y[u][b+v]=h.charCodeAt(v)}function newSeq__system_u2508(y){var u=[];u=new Array(y);for(var h=0;h<y;++h)u[h]=null;return u}function unhandledException(y){var u=[[]];y.message.length!=0?(u[0].push.apply(u[0],[69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]),u[0].push.apply(u[0],y.message)):u[0].push.apply(u[0],[69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]),u[0].push.apply(u[0],[32,91]),add__system_u1943(u,0,y.name),u[0].push.apply(u[0],[93,10]);var h=toJSStr(u[0]);throw typeof Error<"u"?new Error(h):h}function raiseDivByZero(){raiseException({message:[100,105,118,105,115,105,111,110,32,98,121,32,122,101,114,111],parent:null,m_type:NTI134217742,name:null,trace:[],up:null},"DivByZeroDefect")}function raiseOverflow(){raiseException({message:[111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119],parent:null,m_type:NTI134217743,name:null,trace:[],up:null},"OverflowDefect")}function checkOverflowInt(y){(y>2147483647||y<-2147483648)&&raiseOverflow()}function raiseRangeError(){raiseException({message:[118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101],parent:null,m_type:NTI134217751,name:null,trace:[],up:null},"RangeDefect")}function addChars__stdZprivateZdigitsutils_u202(y,u,h,b,v){var w,_=y[u].length;if(y[u].length<(w=chckRange(addInt(_,v),0,2147483647),w))for(var E=y[u].length;E<w;++E)y[u].push(0);else y[u].length=w;{var S=0,x=0;e:for(;;){if(!(x<v))break e;S=x,y[u][chckIndx(addInt(_,S),0,y[u].length-1)]=h.charCodeAt(chckIndx(addInt(b,S),0,h.length-1)),x=addInt(x,1)}}}function addChars__stdZprivateZdigitsutils_u198(y,u,h){addChars__stdZprivateZdigitsutils_u202(y,u,h,0,h==null?0:h.length)}function addInt__stdZprivateZdigitsutils_u223(y,u,h){addChars__stdZprivateZdigitsutils_u198(y,u,h+"")}function addInt__stdZprivateZdigitsutils_u241(y,u,h){addInt__stdZprivateZdigitsutils_u223(y,u,h)}function HEX24__systemZdollars_u8(y){var u=[[]];return addInt__stdZprivateZdigitsutils_u241(u,0,y),u[0]}function isFatPointer__system_u2866(y){var u=!1;e:{u=ConstSet1[y.base.kind]==null;break e}return u}function nimCopyAux(y,u,h){switch(h.kind){case 0:break;case 1:y[h.offset]=nimCopy(y[h.offset],u[h.offset],h.typ);break;case 2:for(var b=0;b<h.sons.length;b++)nimCopyAux(y,u,h.sons[b]);break;case 3:y[h.offset]=nimCopy(y[h.offset],u[h.offset],h.typ);for(var b=0;b<h.sons.length;++b)nimCopyAux(y,u,h.sons[b][1]);break}}function raiseIndexError(y,u,h){var b;h<u?b=[105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]:b=[105,110,100,101,120,32].concat(HEX24__systemZdollars_u8(y),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(u),[32,46,46,32],HEX24__systemZdollars_u8(h)),raiseException({message:nimCopy(null,b,NTI33554449),parent:null,m_type:NTI134217749,name:null,trace:[],up:null},"IndexDefect")}function imul__pureZhashes_u340(y,u){var h=0,b=65535,v=(y>>>16&b)>>>0,w=(y&b)>>>0,_=(u>>>16&b)>>>0,E=(u&b)>>>0;return h=(w*E>>>0)+((v*E>>>0)+(w*_>>>0)>>>0<<16>>>0)>>>0,h}function rotl32__pureZhashes_u361(y,u){var h=0;return h=(y<<u>>>0|y>>>subInt(32,u))>>>0,h}function murmurHash__pureZhashes_u373(y){var u=0;e:{var h=y.length,b=4,v=divInt(h,b),w=0,_=0;t:for(;;){if(!(_<mulInt(v,b)))break t;var E=0,S=b;r:for(;;){if(!(0<S))break r;S=subInt(S,1),E=(E<<8>>>0|Number(BigInt.asUintN(32,BigInt(y[chckIndx(addInt(_,S),0,y.length-1)]))))>>>0}_=addInt(_,b),E=imul__pureZhashes_u340(E,3432918353),E=rotl32__pureZhashes_u361(E,15),E=imul__pureZhashes_u340(E,461845907),w=(w^E)>>>0,w=rotl32__pureZhashes_u361(w,13),w=(w*5>>>0)+3864292196>>>0}var x=0,T=modInt(h,b);t:for(;;){if(!(0<T))break t;T=subInt(T,1),x=(x<<8>>>0|Number(BigInt.asUintN(32,BigInt(y[chckIndx(addInt(_,T),0,y.length-1)]))))>>>0}x=imul__pureZhashes_u340(x,3432918353),x=rotl32__pureZhashes_u361(x,15),x=imul__pureZhashes_u340(x,461845907),w=(w^x)>>>0,w=(w^Number(BigInt.asUintN(32,BigInt(h))))>>>0,w=(w^w>>>16)>>>0,w=imul__pureZhashes_u340(w,2246822507),w=(w^w>>>13)>>>0,w=imul__pureZhashes_u340(w,3266489909),w=(w^w>>>16)>>>0,u=Number(BigInt.asIntN(32,BigInt(w)));break e}return u}function hash__pureZhashes_u782(y){var u=0;return u=murmurHash__pureZhashes_u373(y.slice(0,y.length-1+1)),u}function hashN__nim95hash_u2(y,u,h){var b=0,v=modInt(absInt(hash__pureZhashes_u782(y)),h),w=modInt(absInt(hash__pureZhashes_u782(y.concat([32,98]))),h);return b=modInt(absInt(addInt(v,mulInt(u,w))),h),b}function sysFatal__stdZassertions_u45(y){raiseException({message:nimCopy(null,y,NTI33554449),m_type:NTI134217745,parent:null,name:null,trace:[],up:null},"AssertionDefect")}function raiseAssert__stdZassertions_u43(y){sysFatal__stdZassertions_u45(y)}function failedAssertImpl__stdZassertions_u85(y){raiseAssert__stdZassertions_u43(y)}hashN__nim95hash_u2([100,117,109,109,121],0,1)!=0&&failedAssertImpl__stdZassertions_u85([110,105,109,95,104,97,115,104,46,110,105,109,40,50,54,44,32,51,41,32,96,104,97,115,104,78,40,34,100,117,109,109,121,34,44,32,48,44,32,49,41,32,61,61,32,48,96,32]);var Command;(function(y){y.Send="send",y.Receive="receive",y.SendEphemeral="sendEphemeral"})(Command||(Command={}));var MessageChannelEvent;(function(y){y.OutMessageSent="sds:out:message-sent",y.InMessageDelivered="sds:in:message-delivered",y.InMessageReceived="sds:in:message-received",y.OutMessageAcknowledged="sds:out:message-acknowledged",y.OutMessagePossiblyAcknowledged="sds:out:message-possibly-acknowledged",y.InMessageMissing="sds:in:message-missing",y.OutSyncSent="sds:out:sync-sent",y.InSyncReceived="sds:in:sync-received",y.InMessageLost="sds:in:message-irretrievably-lost",y.ErrorTask="sds:error-task"})(MessageChannelEvent||(MessageChannelEvent={}));var lodash={exports:{}};/**
50
+ * @license
51
+ * Lodash <https://lodash.com/>
52
+ * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
53
+ * Released under MIT license <https://lodash.com/license>
54
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
55
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
56
+ */lodash.exports;(function(y,u){(function(){var h,b="4.17.21",v=200,w="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",_="Expected a function",E="Invalid `variable` option passed into `_.template`",S="__lodash_hash_undefined__",x=500,T="__lodash_placeholder__",C=1,O=2,D=4,U=1,te=2,X=1,ie=2,ee=4,ae=8,de=16,Se=32,ve=64,Pe=128,Ie=256,Ee=512,De=30,be="...",B=800,F=16,M=1,N=2,Q=3,j=1/0,ne=9007199254740991,J=17976931348623157e292,q=NaN,re=4294967295,H=re-1,he=re>>>1,Oe=[["ary",Pe],["bind",X],["bindKey",ie],["curry",ae],["curryRight",de],["flip",Ee],["partial",Se],["partialRight",ve],["rearg",Ie]],Ne="[object Arguments]",Ae="[object Array]",le="[object AsyncFunction]",me="[object Boolean]",Me="[object Date]",fe="[object DOMException]",ge="[object Error]",ce="[object Function]",_e="[object GeneratorFunction]",Re="[object Map]",Ue="[object Number]",qe="[object Null]",Ze="[object Object]",tt="[object Promise]",Fe="[object Proxy]",nt="[object RegExp]",it="[object Set]",at="[object String]",ct="[object Symbol]",ht="[object Undefined]",xt="[object WeakMap]",Ot="[object WeakSet]",dt="[object ArrayBuffer]",Rt="[object DataView]",Nt="[object Float32Array]",yt="[object Float64Array]",zt="[object Int8Array]",Vt="[object Int16Array]",vt="[object Int32Array]",Ut="[object Uint8Array]",Lt="[object Uint8ClampedArray]",wt="[object Uint16Array]",Wt="[object Uint32Array]",Gt=/\b__p \+= '';/g,At=/\b(__p \+=) '' \+/g,tr=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Xt=/&(?:amp|lt|gt|quot|#39);/g,bt=/[&<>"']/g,Bt=RegExp(Xt.source),Yt=RegExp(bt.source),Tt=/<%-([\s\S]+?)%>/g,qt=/<%([\s\S]+?)%>/g,Jt=/<%=([\s\S]+?)%>/g,we=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,se=/^\w*$/,ue=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,xe=/[\\^$.*+?()[\]{}|]/g,ke=RegExp(xe.source),Ke=/^\s+/,We=/\s/,ut=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,_t=/\{\n\/\* \[wrapped with (.+)\] \*/,st=/,? & /,Et=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,gt=/[()=,{}\[\]\/\s]/,It=/\\(\\)?/g,Qt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,rr=/\w*$/,ar=/^[-+]0x[0-9a-f]+$/i,Gr=/^0b[01]+$/i,Hr=/^\[object .+?Constructor\]$/,jr=/^0o[0-7]+$/i,Xr=/^(?:0|[1-9]\d*)$/,Yr=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Br=/($^)/,Kr=/['\n\r\u2028\u2029\\]/g,kr="\\ud800-\\udfff",Mr="\\u0300-\\u036f",Jr="\\ufe20-\\ufe2f",Vr="\\u20d0-\\u20ff",Tn=Mr+Jr+Vr,In="\\u2700-\\u27bf",pn="a-z\\xdf-\\xf6\\xf8-\\xff",Fn="\\xac\\xb1\\xd7\\xf7",Un="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",qn="\\u2000-\\u206f",Qi=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Hn="A-Z\\xc0-\\xd6\\xd8-\\xde",cc="\\ufe0e\\ufe0f",uc=Fn+Un+qn+Qi,Ko="['’]",zu="["+kr+"]",fc="["+uc+"]",qs="["+Tn+"]",lc="\\d+",Wu="["+In+"]",dc="["+pn+"]",hc="[^"+kr+uc+lc+In+pn+Hn+"]",Vo="\\ud83c[\\udffb-\\udfff]",Gu="(?:"+qs+"|"+Vo+")",pc="[^"+kr+"]",Zo="(?:\\ud83c[\\udde6-\\uddff]){2}",zo="[\\ud800-\\udbff][\\udc00-\\udfff]",pi="["+Hn+"]",gc="\\u200d",mc="(?:"+dc+"|"+hc+")",Wo="(?:"+pi+"|"+hc+")",yc="(?:"+Ko+"(?:d|ll|m|re|s|t|ve))?",bc="(?:"+Ko+"(?:D|LL|M|RE|S|T|VE))?",vc=Gu+"?",wc="["+cc+"]?",ju="(?:"+gc+"(?:"+[pc,Zo,zo].join("|")+")"+wc+vc+")*",Xu="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Yu="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",es=wc+vc+ju,Ju="(?:"+[Wu,Zo,zo].join("|")+")"+es,Qu="(?:"+[pc+qs+"?",qs,Zo,zo,zu].join("|")+")",ef=RegExp(Ko,"g"),tf=RegExp(qs,"g"),Hs=RegExp(Vo+"(?="+Vo+")|"+Qu+es,"g"),Go=RegExp([pi+"?"+dc+"+"+yc+"(?="+[fc,pi,"$"].join("|")+")",Wo+"+"+bc+"(?="+[fc,pi+mc,"$"].join("|")+")",pi+"?"+mc+"+"+yc,pi+"+"+bc,Yu,Xu,lc,Ju].join("|"),"g"),jo=RegExp("["+gc+kr+Tn+cc+"]"),_c=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,rf=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],nf=-1,pr={};pr[Nt]=pr[yt]=pr[zt]=pr[Vt]=pr[vt]=pr[Ut]=pr[Lt]=pr[wt]=pr[Wt]=!0,pr[Ne]=pr[Ae]=pr[dt]=pr[me]=pr[Rt]=pr[Me]=pr[ge]=pr[ce]=pr[Re]=pr[Ue]=pr[Ze]=pr[nt]=pr[it]=pr[at]=pr[xt]=!1;var gr={};gr[Ne]=gr[Ae]=gr[dt]=gr[Rt]=gr[me]=gr[Me]=gr[Nt]=gr[yt]=gr[zt]=gr[Vt]=gr[vt]=gr[Re]=gr[Ue]=gr[Ze]=gr[nt]=gr[it]=gr[at]=gr[ct]=gr[Ut]=gr[Lt]=gr[wt]=gr[Wt]=!0,gr[ge]=gr[ce]=gr[xt]=!1;var Xo={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},Yo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},sf={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},of={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},af=parseFloat,cf=parseInt,Jo=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,ts=typeof self=="object"&&self&&self.Object===Object&&self,xr=Jo||ts||Function("return this")(),Ks=u&&!u.nodeType&&u,Qn=Ks&&!0&&y&&!y.nodeType&&y,Qo=Qn&&Qn.exports===Ks,gi=Qo&&Jo.process,sn=function(){try{var He=Qn&&Qn.require&&Qn.require("util").types;return He||gi&&gi.binding&&gi.binding("util")}catch{}}(),Ec=sn&&sn.isArrayBuffer,Sc=sn&&sn.isDate,$c=sn&&sn.isMap,ea=sn&&sn.isRegExp,ta=sn&&sn.isSet,xc=sn&&sn.isTypedArray;function Qr(He,Ye,Ge){switch(Ge.length){case 0:return He.call(Ye);case 1:return He.call(Ye,Ge[0]);case 2:return He.call(Ye,Ge[0],Ge[1]);case 3:return He.call(Ye,Ge[0],Ge[1],Ge[2])}return He.apply(Ye,Ge)}function Oi(He,Ye,Ge,lt){for(var Mt=-1,nr=He==null?0:He.length;++Mt<nr;){var Ar=He[Mt];Ye(lt,Ar,Ge(Ar),He)}return lt}function on(He,Ye){for(var Ge=-1,lt=He==null?0:He.length;++Ge<lt&&Ye(He[Ge],Ge,He)!==!1;);return He}function uf(He,Ye){for(var Ge=He==null?0:He.length;Ge--&&Ye(He[Ge],Ge,He)!==!1;);return He}function ra(He,Ye){for(var Ge=-1,lt=He==null?0:He.length;++Ge<lt;)if(!Ye(He[Ge],Ge,He))return!1;return!0}function Kn(He,Ye){for(var Ge=-1,lt=He==null?0:He.length,Mt=0,nr=[];++Ge<lt;){var Ar=He[Ge];Ye(Ar,Ge,He)&&(nr[Mt++]=Ar)}return nr}function rs(He,Ye){var Ge=He==null?0:He.length;return!!Ge&&mi(He,Ye,0)>-1}function na(He,Ye,Ge){for(var lt=-1,Mt=He==null?0:He.length;++lt<Mt;)if(Ge(Ye,He[lt]))return!0;return!1}function wr(He,Ye){for(var Ge=-1,lt=He==null?0:He.length,Mt=Array(lt);++Ge<lt;)Mt[Ge]=Ye(He[Ge],Ge,He);return Mt}function ei(He,Ye){for(var Ge=-1,lt=Ye.length,Mt=He.length;++Ge<lt;)He[Mt+Ge]=Ye[Ge];return He}function ia(He,Ye,Ge,lt){var Mt=-1,nr=He==null?0:He.length;for(lt&&nr&&(Ge=He[++Mt]);++Mt<nr;)Ge=Ye(Ge,He[Mt],Mt,He);return Ge}function ff(He,Ye,Ge,lt){var Mt=He==null?0:He.length;for(lt&&Mt&&(Ge=He[--Mt]);Mt--;)Ge=Ye(Ge,He[Mt],Mt,He);return Ge}function Vs(He,Ye){for(var Ge=-1,lt=He==null?0:He.length;++Ge<lt;)if(Ye(He[Ge],Ge,He))return!0;return!1}var Ac=sa("length");function lf(He){return He.split("")}function df(He){return He.match(Et)||[]}function Tc(He,Ye,Ge){var lt;return Ge(He,function(Mt,nr,Ar){if(Ye(Mt,nr,Ar))return lt=nr,!1}),lt}function Zs(He,Ye,Ge,lt){for(var Mt=He.length,nr=Ge+(lt?1:-1);lt?nr--:++nr<Mt;)if(Ye(He[nr],nr,He))return nr;return-1}function mi(He,Ye,Ge){return Ye===Ye?vf(He,Ye,Ge):Zs(He,Cc,Ge)}function Ic(He,Ye,Ge,lt){for(var Mt=Ge-1,nr=He.length;++Mt<nr;)if(lt(He[Mt],Ye))return Mt;return-1}function Cc(He){return He!==He}function Pc(He,Ye){var Ge=He==null?0:He.length;return Ge?oa(He,Ye)/Ge:q}function sa(He){return function(Ye){return Ye==null?h:Ye[He]}}function ns(He){return function(Ye){return He==null?h:He[Ye]}}function Rc(He,Ye,Ge,lt,Mt){return Mt(He,function(nr,Ar,yr){Ge=lt?(lt=!1,nr):Ye(Ge,nr,Ar,yr)}),Ge}function hf(He,Ye){var Ge=He.length;for(He.sort(Ye);Ge--;)He[Ge]=He[Ge].value;return He}function oa(He,Ye){for(var Ge,lt=-1,Mt=He.length;++lt<Mt;){var nr=Ye(He[lt]);nr!==h&&(Ge=Ge===h?nr:Ge+nr)}return Ge}function aa(He,Ye){for(var Ge=-1,lt=Array(He);++Ge<He;)lt[Ge]=Ye(Ge);return lt}function Mc(He,Ye){return wr(Ye,function(Ge){return[Ge,He[Ge]]})}function Oc(He){return He&&He.slice(0,Fc(He)+1).replace(Ke,"")}function en(He){return function(Ye){return He(Ye)}}function ca(He,Ye){return wr(Ye,function(Ge){return He[Ge]})}function yi(He,Ye){return He.has(Ye)}function Dc(He,Ye){for(var Ge=-1,lt=He.length;++Ge<lt&&mi(Ye,He[Ge],0)>-1;);return Ge}function Bc(He,Ye){for(var Ge=He.length;Ge--&&mi(Ye,He[Ge],0)>-1;);return Ge}function zs(He,Ye){for(var Ge=He.length,lt=0;Ge--;)He[Ge]===Ye&&++lt;return lt}var pf=ns(Xo),kc=ns(Yo);function Nc(He){return"\\"+of[He]}function gf(He,Ye){return He==null?h:He[Ye]}function bi(He){return jo.test(He)}function mf(He){return _c.test(He)}function yf(He){for(var Ye,Ge=[];!(Ye=He.next()).done;)Ge.push(Ye.value);return Ge}function ua(He){var Ye=-1,Ge=Array(He.size);return He.forEach(function(lt,Mt){Ge[++Ye]=[Mt,lt]}),Ge}function Lc(He,Ye){return function(Ge){return He(Ye(Ge))}}function ti(He,Ye){for(var Ge=-1,lt=He.length,Mt=0,nr=[];++Ge<lt;){var Ar=He[Ge];(Ar===Ye||Ar===T)&&(He[Ge]=T,nr[Mt++]=Ge)}return nr}function Ws(He){var Ye=-1,Ge=Array(He.size);return He.forEach(function(lt){Ge[++Ye]=lt}),Ge}function bf(He){var Ye=-1,Ge=Array(He.size);return He.forEach(function(lt){Ge[++Ye]=[lt,lt]}),Ge}function vf(He,Ye,Ge){for(var lt=Ge-1,Mt=He.length;++lt<Mt;)if(He[lt]===Ye)return lt;return-1}function wf(He,Ye,Ge){for(var lt=Ge+1;lt--;)if(He[lt]===Ye)return lt;return lt}function Di(He){return bi(He)?Ef(He):Ac(He)}function gn(He){return bi(He)?Sf(He):lf(He)}function Fc(He){for(var Ye=He.length;Ye--&&We.test(He.charAt(Ye)););return Ye}var _f=ns(sf);function Ef(He){for(var Ye=Hs.lastIndex=0;Hs.test(He);)++Ye;return Ye}function Sf(He){return He.match(Hs)||[]}function $f(He){return He.match(Go)||[]}var xf=function He(Ye){Ye=Ye==null?xr:Zr.defaults(xr.Object(),Ye,Zr.pick(xr,rf));var Ge=Ye.Array,lt=Ye.Date,Mt=Ye.Error,nr=Ye.Function,Ar=Ye.Math,yr=Ye.Object,fa=Ye.RegExp,la=Ye.String,an=Ye.TypeError,Gs=Ge.prototype,Af=nr.prototype,Bi=yr.prototype,js=Ye["__core-js_shared__"],is=Af.toString,cr=Bi.hasOwnProperty,Tf=0,Uc=function(){var $=/[^.]+$/.exec(js&&js.keys&&js.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),Xs=Bi.toString,If=is.call(yr),Cf=xr._,Pf=fa("^"+is.call(cr).replace(xe,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ys=Qo?Ye.Buffer:h,ri=Ye.Symbol,Js=Ye.Uint8Array,qc=Ys?Ys.allocUnsafe:h,ki=Lc(yr.getPrototypeOf,yr),Hc=yr.create,Kc=Bi.propertyIsEnumerable,ss=Gs.splice,Vc=ri?ri.isConcatSpreadable:h,os=ri?ri.iterator:h,vi=ri?ri.toStringTag:h,Qs=function(){try{var $=jn(yr,"defineProperty");return $({},"",{}),$}catch{}}(),Zc=Ye.clearTimeout!==xr.clearTimeout&&Ye.clearTimeout,zc=lt&&lt.now!==xr.Date.now&&lt.now,wi=Ye.setTimeout!==xr.setTimeout&&Ye.setTimeout,as=Ar.ceil,eo=Ar.floor,da=yr.getOwnPropertySymbols,Rf=Ys?Ys.isBuffer:h,Wc=Ye.isFinite,Mf=Gs.join,Of=Lc(yr.keys,yr),Ir=Ar.max,Nr=Ar.min,Df=lt.now,Bf=Ye.parseInt,Vn=Ar.random,kf=Gs.reverse,to=jn(Ye,"DataView"),cs=jn(Ye,"Map"),ha=jn(Ye,"Promise"),ni=jn(Ye,"Set"),_i=jn(Ye,"WeakMap"),us=jn(yr,"create"),ro=_i&&new _i,Ni={},Nf=ks(to),Lf=ks(cs),Ff=ks(ha),Uf=ks(ni),qf=ks(_i),no=ri?ri.prototype:h,ls=no?no.valueOf:h,Gc=no?no.toString:h;function $e($){if(Tr($)&&!kt($)&&!($ instanceof Zt)){if($ instanceof cn)return $;if(cr.call($,"__wrapped__"))return ud($)}return new cn($)}var Li=function(){function $(){}return function(I){if(!$r(I))return{};if(Hc)return Hc(I);$.prototype=I;var k=new $;return $.prototype=h,k}}();function io(){}function cn($,I){this.__wrapped__=$,this.__actions__=[],this.__chain__=!!I,this.__index__=0,this.__values__=h}$e.templateSettings={escape:Tt,evaluate:qt,interpolate:Jt,variable:"",imports:{_:$e}},$e.prototype=io.prototype,$e.prototype.constructor=$e,cn.prototype=Li(io.prototype),cn.prototype.constructor=cn;function Zt($){this.__wrapped__=$,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=re,this.__views__=[]}function Hf(){var $=new Zt(this.__wrapped__);return $.__actions__=Je(this.__actions__),$.__dir__=this.__dir__,$.__filtered__=this.__filtered__,$.__iteratees__=Je(this.__iteratees__),$.__takeCount__=this.__takeCount__,$.__views__=Je(this.__views__),$}function Kf(){if(this.__filtered__){var $=new Zt(this);$.__dir__=-1,$.__filtered__=!0}else $=this.clone(),$.__dir__*=-1;return $}function Vf(){var $=this.__wrapped__.value(),I=this.__dir__,k=kt($),oe=I<0,ye=k?$.length:0,Te=La(0,ye,this.__views__),Be=Te.start,Le=Te.end,Ve=Le-Be,Qe=oe?Le:Be-1,et=this.__iteratees__,rt=et.length,ot=0,mt=Nr(Ve,this.__takeCount__);if(!k||!oe&&ye==Ve&&mt==Ve)return Ca($,this.__actions__);var Ct=[];e:for(;Ve--&&ot<mt;){Qe+=I;for(var Kt=-1,Pt=$[Qe];++Kt<rt;){var jt=et[Kt],er=jt.iteratee,$n=jt.type,rn=er(Pt);if($n==N)Pt=rn;else if(!rn){if($n==M)continue e;break e}}Ct[ot++]=Pt}return Ct}Zt.prototype=Li(io.prototype),Zt.prototype.constructor=Zt;function Cn($){var I=-1,k=$==null?0:$.length;for(this.clear();++I<k;){var oe=$[I];this.set(oe[0],oe[1])}}function Zf(){this.__data__=us?us(null):{},this.size=0}function jc($){var I=this.has($)&&delete this.__data__[$];return this.size-=I?1:0,I}function zf($){var I=this.__data__;if(us){var k=I[$];return k===S?h:k}return cr.call(I,$)?I[$]:h}function Xc($){var I=this.__data__;return us?I[$]!==h:cr.call(I,$)}function Wf($,I){var k=this.__data__;return this.size+=this.has($)?0:1,k[$]=us&&I===h?S:I,this}Cn.prototype.clear=Zf,Cn.prototype.delete=jc,Cn.prototype.get=zf,Cn.prototype.has=Xc,Cn.prototype.set=Wf;function Zn($){var I=-1,k=$==null?0:$.length;for(this.clear();++I<k;){var oe=$[I];this.set(oe[0],oe[1])}}function Yc(){this.__data__=[],this.size=0}function Jc($){var I=this.__data__,k=so(I,$);if(k<0)return!1;var oe=I.length-1;return k==oe?I.pop():ss.call(I,k,1),--this.size,!0}function Gf($){var I=this.__data__,k=so(I,$);return k<0?h:I[k][1]}function jf($){return so(this.__data__,$)>-1}function Xf($,I){var k=this.__data__,oe=so(k,$);return oe<0?(++this.size,k.push([$,I])):k[oe][1]=I,this}Zn.prototype.clear=Yc,Zn.prototype.delete=Jc,Zn.prototype.get=Gf,Zn.prototype.has=jf,Zn.prototype.set=Xf;function Pn($){var I=-1,k=$==null?0:$.length;for(this.clear();++I<k;){var oe=$[I];this.set(oe[0],oe[1])}}function Yf(){this.size=0,this.__data__={hash:new Cn,map:new(cs||Zn),string:new Cn}}function Jf($){var I=Wi(this,$).delete($);return this.size-=I?1:0,I}function Qf($){return Wi(this,$).get($)}function pa($){return Wi(this,$).has($)}function el($,I){var k=Wi(this,$),oe=k.size;return k.set($,I),this.size+=k.size==oe?0:1,this}Pn.prototype.clear=Yf,Pn.prototype.delete=Jf,Pn.prototype.get=Qf,Pn.prototype.has=pa,Pn.prototype.set=el;function Ei($){var I=-1,k=$==null?0:$.length;for(this.__data__=new Pn;++I<k;)this.add($[I])}function Qc($){return this.__data__.set($,S),this}function tl($){return this.__data__.has($)}Ei.prototype.add=Ei.prototype.push=Qc,Ei.prototype.has=tl;function mn($){var I=this.__data__=new Zn($);this.size=I.size}function rl(){this.__data__=new Zn,this.size=0}function ii($){var I=this.__data__,k=I.delete($);return this.size=I.size,k}function nl($){return this.__data__.get($)}function il($){return this.__data__.has($)}function ol($,I){var k=this.__data__;if(k instanceof Zn){var oe=k.__data__;if(!cs||oe.length<v-1)return oe.push([$,I]),this.size=++k.size,this;k=this.__data__=new Pn(oe)}return k.set($,I),this.size=k.size,this}mn.prototype.clear=rl,mn.prototype.delete=ii,mn.prototype.get=nl,mn.prototype.has=il,mn.prototype.set=ol;function eu($,I){var k=kt($),oe=!k&&Ns($),ye=!k&&!oe&&Gi($),Te=!k&&!oe&&!ye&&Ro($),Be=k||oe||ye||Te,Le=Be?aa($.length,la):[],Ve=Le.length;for(var Qe in $)(I||cr.call($,Qe))&&!(Be&&(Qe=="length"||ye&&(Qe=="offset"||Qe=="parent")||Te&&(Qe=="buffer"||Qe=="byteLength"||Qe=="byteOffset")||En(Qe,Ve)))&&Le.push(Qe);return Le}function tu($){var I=$.length;return I?$[Es(0,I-1)]:h}function al($,I){return $u(Je($),$i(I,0,$.length))}function cl($){return $u(Je($))}function ga($,I,k){(k!==h&&!Xn($[I],k)||k===h&&!(I in $))&&Rn($,I,k)}function ds($,I,k){var oe=$[I];(!(cr.call($,I)&&Xn(oe,k))||k===h&&!(I in $))&&Rn($,I,k)}function so($,I){for(var k=$.length;k--;)if(Xn($[k][0],I))return k;return-1}function ru($,I,k,oe){return si($,function(ye,Te,Be){I(oe,ye,k(ye),Be)}),oe}function Si($,I){return $&&Xe(I,qr(I),$)}function nu($,I){return $&&Xe(I,ln(I),$)}function Rn($,I,k){I=="__proto__"&&Qs?Qs($,I,{configurable:!0,enumerable:!0,value:k,writable:!0}):$[I]=k}function oo($,I){for(var k=-1,oe=I.length,ye=Ge(oe),Te=$==null;++k<oe;)ye[k]=Te?h:Rl($,I[k]);return ye}function $i($,I,k){return $===$&&(k!==h&&($=$<=k?$:k),I!==h&&($=$>=I?$:I)),$}function un($,I,k,oe,ye,Te){var Be,Le=I&C,Ve=I&O,Qe=I&D;if(k&&(Be=ye?k($,oe,ye,Te):k($)),Be!==h)return Be;if(!$r($))return $;var et=kt($);if(et){if(Be=Ua($),!Le)return Je($,Be)}else{var rt=Dr($),ot=rt==ce||rt==_e;if(Gi($))return bu($,Le);if(rt==Ze||rt==Ne||ot&&!ye){if(Be=Ve||ot?{}:xo($),!Le)return Ve?lr($,nu(Be,$)):pt($,Si(Be,$))}else{if(!gr[rt])return ye?$:{};Be=qa($,rt,Le)}}Te||(Te=new mn);var mt=Te.get($);if(mt)return mt;Te.set($,Be),Cd($)?$.forEach(function(Pt){Be.add(un(Pt,I,k,Pt,$,Te))}):Td($)&&$.forEach(function(Pt,jt){Be.set(jt,un(Pt,I,k,jt,$,Te))});var Ct=Qe?Ve?Cs:Is:Ve?ln:qr,Kt=et?h:Ct($);return on(Kt||$,function(Pt,jt){Kt&&(jt=Pt,Pt=$[jt]),ds(Be,jt,un(Pt,I,k,jt,$,Te))}),Be}function ul($){var I=qr($);return function(k){return iu(k,$,I)}}function iu($,I,k){var oe=k.length;if($==null)return!oe;for($=yr($);oe--;){var ye=k[oe],Te=I[ye],Be=$[ye];if(Be===h&&!(ye in $)||!Te(Be))return!1}return!0}function su($,I,k){if(typeof $!="function")throw new an(_);return Ja(function(){$.apply(h,k)},I)}function hs($,I,k,oe){var ye=-1,Te=rs,Be=!0,Le=$.length,Ve=[],Qe=I.length;if(!Le)return Ve;k&&(I=wr(I,en(k))),oe?(Te=na,Be=!1):I.length>=v&&(Te=yi,Be=!1,I=new Ei(I));e:for(;++ye<Le;){var et=$[ye],rt=k==null?et:k(et);if(et=oe||et!==0?et:0,Be&&rt===rt){for(var ot=Qe;ot--;)if(I[ot]===rt)continue e;Ve.push(et)}else Te(I,rt,oe)||Ve.push(et)}return Ve}var si=vu(yn),ao=vu(uo,!0);function fl($,I){var k=!0;return si($,function(oe,ye,Te){return k=!!I(oe,ye,Te),k}),k}function zn($,I,k){for(var oe=-1,ye=$.length;++oe<ye;){var Te=$[oe],Be=I(Te);if(Be!=null&&(Le===h?Be===Be&&!Sn(Be):k(Be,Le)))var Le=Be,Ve=Te}return Ve}function Fi($,I,k,oe){var ye=$.length;for(k=Ht(k),k<0&&(k=-k>ye?0:ye+k),oe=oe===h||oe>ye?ye:Ht(oe),oe<0&&(oe+=ye),oe=k>oe?0:Rd(oe);k<oe;)$[k++]=I;return $}function ou($,I){var k=[];return si($,function(oe,ye,Te){I(oe,ye,Te)&&k.push(oe)}),k}function Cr($,I,k,oe,ye){var Te=-1,Be=$.length;for(k||(k=Ka),ye||(ye=[]);++Te<Be;){var Le=$[Te];I>0&&k(Le)?I>1?Cr(Le,I-1,k,oe,ye):ei(ye,Le):oe||(ye[ye.length]=Le)}return ye}var co=Hi(),au=Hi(!0);function yn($,I){return $&&co($,I,qr)}function uo($,I){return $&&au($,I,qr)}function ps($,I){return Kn(I,function(k){return Ii($[k])})}function oi($,I){I=ci(I,$);for(var k=0,oe=I.length;$!=null&&k<oe;)$=$[di(I[k++])];return k&&k==oe?$:h}function Mn($,I,k){var oe=I($);return kt($)?oe:ei(oe,k($))}function Wr($){return $==null?$===h?ht:qe:vi&&vi in yr($)?Na($):Xa($)}function ma($,I){return $>I}function ll($,I){return $!=null&&cr.call($,I)}function dl($,I){return $!=null&&I in yr($)}function pl($,I,k){return $>=Nr(I,k)&&$<Ir(I,k)}function ya($,I,k){for(var oe=k?na:rs,ye=$[0].length,Te=$.length,Be=Te,Le=Ge(Te),Ve=1/0,Qe=[];Be--;){var et=$[Be];Be&&I&&(et=wr(et,en(I))),Ve=Nr(et.length,Ve),Le[Be]=!k&&(I||ye>=120&&et.length>=120)?new Ei(Be&&et):h}et=$[0];var rt=-1,ot=Le[0];e:for(;++rt<ye&&Qe.length<Ve;){var mt=et[rt],Ct=I?I(mt):mt;if(mt=k||mt!==0?mt:0,!(ot?yi(ot,Ct):oe(Qe,Ct,k))){for(Be=Te;--Be;){var Kt=Le[Be];if(!(Kt?yi(Kt,Ct):oe($[Be],Ct,k)))continue e}ot&&ot.push(Ct),Qe.push(mt)}}return Qe}function cu($,I,k,oe){return yn($,function(ye,Te,Be){I(oe,k(ye),Te,Be)}),oe}function gs($,I,k){I=ci(I,$),$=Co($,I);var oe=$==null?$:$[di(Dn(I))];return oe==null?h:Qr(oe,$,k)}function ba($){return Tr($)&&Wr($)==Ne}function gl($){return Tr($)&&Wr($)==dt}function ml($){return Tr($)&&Wr($)==Me}function ys($,I,k,oe,ye){return $===I?!0:$==null||I==null||!Tr($)&&!Tr(I)?$!==$&&I!==I:br($,I,k,oe,ys,ye)}function br($,I,k,oe,ye,Te){var Be=kt($),Le=kt(I),Ve=Be?Ae:Dr($),Qe=Le?Ae:Dr(I);Ve=Ve==Ne?Ze:Ve,Qe=Qe==Ne?Ze:Qe;var et=Ve==Ze,rt=Qe==Ze,ot=Ve==Qe;if(ot&&Gi($)){if(!Gi(I))return!1;Be=!0,et=!1}if(ot&&!et)return Te||(Te=new mn),Be||Ro($)?Eo($,I,k,oe,ye,Te):Ba($,I,Ve,k,oe,ye,Te);if(!(k&U)){var mt=et&&cr.call($,"__wrapped__"),Ct=rt&&cr.call(I,"__wrapped__");if(mt||Ct){var Kt=mt?$.value():$,Pt=Ct?I.value():I;return Te||(Te=new mn),ye(Kt,Pt,k,oe,Te)}}return ot?(Te||(Te=new mn),ka($,I,k,oe,ye,Te)):!1}function bs($){return Tr($)&&Dr($)==Re}function va($,I,k,oe){var ye=k.length,Te=ye,Be=!oe;if($==null)return!Te;for($=yr($);ye--;){var Le=k[ye];if(Be&&Le[2]?Le[1]!==$[Le[0]]:!(Le[0]in $))return!1}for(;++ye<Te;){Le=k[ye];var Ve=Le[0],Qe=$[Ve],et=Le[1];if(Be&&Le[2]){if(Qe===h&&!(Ve in $))return!1}else{var rt=new mn;if(oe)var ot=oe(Qe,et,Ve,$,I,rt);if(!(ot===h?ys(et,Qe,U|te,oe,rt):ot))return!1}}return!0}function wa($){if(!$r($)||Za($))return!1;var I=Ii($)?Pf:Hr;return I.test(ks($))}function Ur($){return Tr($)&&Wr($)==nt}function Or($){return Tr($)&&Dr($)==it}function fo($){return Tr($)&&Pu($.length)&&!!pr[Wr($)]}function vs($){return typeof $=="function"?$:$==null?dn:typeof $=="object"?kt($)?lu($[0],$[1]):fu($):Hd($)}function ws($){if(!Ti($))return Of($);var I=[];for(var k in yr($))cr.call($,k)&&k!="constructor"&&I.push(k);return I}function lo($){if(!$r($))return ja($);var I=Ti($),k=[];for(var oe in $)oe=="constructor"&&(I||!cr.call($,oe))||k.push(oe);return k}function _a($,I){return $<I}function uu($,I){var k=-1,oe=fn($)?Ge($.length):[];return si($,function(ye,Te,Be){oe[++k]=I(ye,Te,Be)}),oe}function fu($){var I=Rs($);return I.length==1&&I[0][2]?To(I[0][0],I[0][1]):function(k){return k===$||va(k,$,I)}}function lu($,I){return Os($)&&Ao(I)?To(di($),I):function(k){var oe=Rl(k,$);return oe===h&&oe===I?Ml(k,$):ys(I,oe,U|te)}}function ho($,I,k,oe,ye){$!==I&&co(I,function(Te,Be){if(ye||(ye=new mn),$r(Te))xi($,I,Be,k,ho,oe,ye);else{var Le=oe?oe(Bs($,Be),Te,Be+"",$,I,ye):h;Le===h&&(Le=Te),ga($,Be,Le)}},ln)}function xi($,I,k,oe,ye,Te,Be){var Le=Bs($,k),Ve=Bs(I,k),Qe=Be.get(Ve);if(Qe){ga($,k,Qe);return}var et=Te?Te(Le,Ve,k+"",$,I,Be):h,rt=et===h;if(rt){var ot=kt(Ve),mt=!ot&&Gi(Ve),Ct=!ot&&!mt&&Ro(Ve);et=Ve,ot||mt||Ct?kt(Le)?et=Le:Pr(Le)?et=Je(Le):mt?(rt=!1,et=bu(Ve,!0)):Ct?(rt=!1,et=L(Ve,!0)):et=[]:Qa(Ve)||Ns(Ve)?(et=Le,Ns(Le)?et=Md(Le):(!$r(Le)||Ii(Le))&&(et=xo(Ve))):rt=!1}rt&&(Be.set(Ve,et),ye(et,Ve,oe,Te,Be),Be.delete(Ve)),ga($,k,et)}function du($,I){var k=$.length;if(k)return I+=I<0?k:0,En(I,k)?$[I]:h}function Ea($,I,k){I.length?I=wr(I,function(Te){return kt(Te)?function(Be){return oi(Be,Te.length===1?Te[0]:Te)}:Te}):I=[dn];var oe=-1;I=wr(I,en(St()));var ye=uu($,function(Te,Be,Le){var Ve=wr(I,function(Qe){return Qe(Te)});return{criteria:Ve,index:++oe,value:Te}});return hf(ye,function(Te,Be){return pe(Te,Be,k)})}function yl($,I){return hu($,I,function(k,oe){return Ml($,oe)})}function hu($,I,k){for(var oe=-1,ye=I.length,Te={};++oe<ye;){var Be=I[oe],Le=oi($,Be);k(Le,Be)&&Ui(Te,ci(Be,$),Le)}return Te}function pu($){return function(I){return oi(I,$)}}function po($,I,k,oe){var ye=oe?Ic:mi,Te=-1,Be=I.length,Le=$;for($===I&&(I=Je(I)),k&&(Le=wr($,en(k)));++Te<Be;)for(var Ve=0,Qe=I[Te],et=k?k(Qe):Qe;(Ve=ye(Le,et,Ve,oe))>-1;)Le!==$&&ss.call(Le,Ve,1),ss.call($,Ve,1);return $}function _s($,I){for(var k=$?I.length:0,oe=k-1;k--;){var ye=I[k];if(k==oe||ye!==Te){var Te=ye;En(ye)?ss.call($,ye,1):Ta($,ye)}}return $}function Es($,I){return $+eo(Vn()*(I-$+1))}function On($,I,k,oe){for(var ye=-1,Te=Ir(as((I-$)/(k||1)),0),Be=Ge(Te);Te--;)Be[oe?Te:++ye]=$,$+=k;return Be}function Sa($,I){var k="";if(!$||I<1||I>ne)return k;do I%2&&(k+=$),I=eo(I/2),I&&($+=$);while(I);return k}function Dt($,I){return $l(Io($,I,dn),$+"")}function bl($){return tu(Mo($))}function vl($,I){var k=Mo($);return $u(k,$i(I,0,k.length))}function Ui($,I,k,oe){if(!$r($))return $;I=ci(I,$);for(var ye=-1,Te=I.length,Be=Te-1,Le=$;Le!=null&&++ye<Te;){var Ve=di(I[ye]),Qe=k;if(Ve==="__proto__"||Ve==="constructor"||Ve==="prototype")return $;if(ye!=Be){var et=Le[Ve];Qe=oe?oe(et,Ve,Le):h,Qe===h&&(Qe=$r(et)?et:En(I[ye+1])?[]:{})}ds(Le,Ve,Qe),Le=Le[Ve]}return $}var gu=ro?function($,I){return ro.set($,I),$}:dn,mu=Qs?function($,I){return Qs($,"toString",{configurable:!0,enumerable:!1,value:Dl(I),writable:!0})}:dn;function wl($){return $u(Mo($))}function tn($,I,k){var oe=-1,ye=$.length;I<0&&(I=-I>ye?0:ye+I),k=k>ye?ye:k,k<0&&(k+=ye),ye=I>k?0:k-I>>>0,I>>>=0;for(var Te=Ge(ye);++oe<ye;)Te[oe]=$[oe+I];return Te}function _l($,I){var k;return si($,function(oe,ye,Te){return k=I(oe,ye,Te),!k}),!!k}function qi($,I,k){var oe=0,ye=$==null?oe:$.length;if(typeof I=="number"&&I===I&&ye<=he){for(;oe<ye;){var Te=oe+ye>>>1,Be=$[Te];Be!==null&&!Sn(Be)&&(k?Be<=I:Be<I)?oe=Te+1:ye=Te}return ye}return $a($,I,dn,k)}function $a($,I,k,oe){var ye=0,Te=$==null?0:$.length;if(Te===0)return 0;I=k(I);for(var Be=I!==I,Le=I===null,Ve=Sn(I),Qe=I===h;ye<Te;){var et=eo((ye+Te)/2),rt=k($[et]),ot=rt!==h,mt=rt===null,Ct=rt===rt,Kt=Sn(rt);if(Be)var Pt=oe||Ct;else Qe?Pt=Ct&&(oe||ot):Le?Pt=Ct&&ot&&(oe||!mt):Ve?Pt=Ct&&ot&&!mt&&(oe||!Kt):mt||Kt?Pt=!1:Pt=oe?rt<=I:rt<I;Pt?ye=et+1:Te=et}return Nr(Te,H)}function xa($,I){for(var k=-1,oe=$.length,ye=0,Te=[];++k<oe;){var Be=$[k],Le=I?I(Be):Be;if(!k||!Xn(Le,Ve)){var Ve=Le;Te[ye++]=Be===0?0:Be}}return Te}function Aa($){return typeof $=="number"?$:Sn($)?q:+$}function Lr($){if(typeof $=="string")return $;if(kt($))return wr($,Lr)+"";if(Sn($))return Gc?Gc.call($):"";var I=$+"";return I=="0"&&1/$==-j?"-0":I}function ai($,I,k){var oe=-1,ye=rs,Te=$.length,Be=!0,Le=[],Ve=Le;if(k)Be=!1,ye=na;else if(Te>=v){var Qe=I?null:Oa($);if(Qe)return Ws(Qe);Be=!1,ye=yi,Ve=new Ei}else Ve=I?[]:Le;e:for(;++oe<Te;){var et=$[oe],rt=I?I(et):et;if(et=k||et!==0?et:0,Be&&rt===rt){for(var ot=Ve.length;ot--;)if(Ve[ot]===rt)continue e;I&&Ve.push(rt),Le.push(et)}else ye(Ve,rt,k)||(Ve!==Le&&Ve.push(rt),Le.push(et))}return Le}function Ta($,I){return I=ci(I,$),$=Co($,I),$==null||delete $[di(Dn(I))]}function Ia($,I,k,oe){return Ui($,I,k(oi($,I)),oe)}function Ss($,I,k,oe){for(var ye=$.length,Te=oe?ye:-1;(oe?Te--:++Te<ye)&&I($[Te],Te,$););return k?tn($,oe?0:Te,oe?Te+1:ye):tn($,oe?Te+1:0,oe?ye:Te)}function Ca($,I){var k=$;return k instanceof Zt&&(k=k.value()),ia(I,function(oe,ye){return ye.func.apply(ye.thisArg,ei([oe],ye.args))},k)}function go($,I,k){var oe=$.length;if(oe<2)return oe?ai($[0]):[];for(var ye=-1,Te=Ge(oe);++ye<oe;)for(var Be=$[ye],Le=-1;++Le<oe;)Le!=ye&&(Te[ye]=hs(Te[ye]||Be,$[Le],I,k));return ai(Cr(Te,1),I,k)}function yu($,I,k){for(var oe=-1,ye=$.length,Te=I.length,Be={};++oe<ye;){var Le=oe<Te?I[oe]:h;k(Be,$[oe],Le)}return Be}function Pa($){return Pr($)?$:[]}function Ra($){return typeof $=="function"?$:dn}function ci($,I){return kt($)?$:Os($,I)?[$]:cd(dr($))}var El=Dt;function Wn($,I,k){var oe=$.length;return k=k===h?oe:k,!I&&k>=oe?$:tn($,I,k)}var mo=Zc||function($){return xr.clearTimeout($)};function bu($,I){if(I)return $.slice();var k=$.length,oe=qc?qc(k):new $.constructor(k);return $.copy(oe),oe}function $s($){var I=new $.constructor($.byteLength);return new Js(I).set(new Js($)),I}function Sl($,I){var k=I?$s($.buffer):$.buffer;return new $.constructor(k,$.byteOffset,$.byteLength)}function A($){var I=new $.constructor($.source,rr.exec($));return I.lastIndex=$.lastIndex,I}function P($){return ls?yr(ls.call($)):{}}function L($,I){var k=I?$s($.buffer):$.buffer;return new $.constructor(k,$.byteOffset,$.length)}function Y($,I){if($!==I){var k=$!==h,oe=$===null,ye=$===$,Te=Sn($),Be=I!==h,Le=I===null,Ve=I===I,Qe=Sn(I);if(!Le&&!Qe&&!Te&&$>I||Te&&Be&&Ve&&!Le&&!Qe||oe&&Be&&Ve||!k&&Ve||!ye)return 1;if(!oe&&!Te&&!Qe&&$<I||Qe&&k&&ye&&!oe&&!Te||Le&&k&&ye||!Be&&ye||!Ve)return-1}return 0}function pe($,I,k){for(var oe=-1,ye=$.criteria,Te=I.criteria,Be=ye.length,Le=k.length;++oe<Be;){var Ve=Y(ye[oe],Te[oe]);if(Ve){if(oe>=Le)return Ve;var Qe=k[oe];return Ve*(Qe=="desc"?-1:1)}}return $.index-I.index}function Ce($,I,k,oe){for(var ye=-1,Te=$.length,Be=k.length,Le=-1,Ve=I.length,Qe=Ir(Te-Be,0),et=Ge(Ve+Qe),rt=!oe;++Le<Ve;)et[Le]=I[Le];for(;++ye<Be;)(rt||ye<Te)&&(et[k[ye]]=$[ye]);for(;Qe--;)et[Le++]=$[ye++];return et}function ze($,I,k,oe){for(var ye=-1,Te=$.length,Be=-1,Le=k.length,Ve=-1,Qe=I.length,et=Ir(Te-Le,0),rt=Ge(et+Qe),ot=!oe;++ye<et;)rt[ye]=$[ye];for(var mt=ye;++Ve<Qe;)rt[mt+Ve]=I[Ve];for(;++Be<Le;)(ot||ye<Te)&&(rt[mt+k[Be]]=$[ye++]);return rt}function Je($,I){var k=-1,oe=$.length;for(I||(I=Ge(oe));++k<oe;)I[k]=$[k];return I}function Xe($,I,k,oe){var ye=!k;k||(k={});for(var Te=-1,Be=I.length;++Te<Be;){var Le=I[Te],Ve=oe?oe(k[Le],$[Le],Le,k,$):h;Ve===h&&(Ve=$[Le]),ye?Rn(k,Le,Ve):ds(k,Le,Ve)}return k}function pt($,I){return Xe($,Ms($),I)}function lr($,I){return Xe($,So($),I)}function Sr($,I){return function(k,oe){var ye=kt(k)?Oi:ru,Te=I?I():{};return ye(k,$,St(oe,2),Te)}}function vn($){return Dt(function(I,k){var oe=-1,ye=k.length,Te=ye>1?k[ye-1]:h,Be=ye>2?k[2]:h;for(Te=$.length>3&&typeof Te=="function"?(ye--,Te):h,Be&&Fr(k[0],k[1],Be)&&(Te=ye<3?h:Te,ye=1),I=yr(I);++oe<ye;){var Le=k[oe];Le&&$(I,Le,oe,Te)}return I})}function vu($,I){return function(k,oe){if(k==null)return k;if(!fn(k))return $(k,oe);for(var ye=k.length,Te=I?ye:-1,Be=yr(k);(I?Te--:++Te<ye)&&oe(Be[Te],Te,Be)!==!1;);return k}}function Hi($){return function(I,k,oe){for(var ye=-1,Te=yr(I),Be=oe(I),Le=Be.length;Le--;){var Ve=Be[$?Le:++ye];if(k(Te[Ve],Ve,Te)===!1)break}return I}}function xs($,I,k){var oe=I&X,ye=Gn($);function Te(){var Be=this&&this!==xr&&this instanceof Te?ye:$;return Be.apply(oe?k:this,arguments)}return Te}function wu($){return function(I){I=dr(I);var k=bi(I)?gn(I):h,oe=k?k[0]:I.charAt(0),ye=k?Wn(k,1).join(""):I.slice(1);return oe[$]()+ye}}function Ki($){return function(I){return ia(Ud(Fd(I).replace(ef,"")),$,"")}}function Gn($){return function(){var I=arguments;switch(I.length){case 0:return new $;case 1:return new $(I[0]);case 2:return new $(I[0],I[1]);case 3:return new $(I[0],I[1],I[2]);case 4:return new $(I[0],I[1],I[2],I[3]);case 5:return new $(I[0],I[1],I[2],I[3],I[4]);case 6:return new $(I[0],I[1],I[2],I[3],I[4],I[5]);case 7:return new $(I[0],I[1],I[2],I[3],I[4],I[5],I[6])}var k=Li($.prototype),oe=$.apply(k,I);return $r(oe)?oe:k}}function As($,I,k){var oe=Gn($);function ye(){for(var Te=arguments.length,Be=Ge(Te),Le=Te,Ve=li(ye);Le--;)Be[Le]=arguments[Le];var Qe=Te<3&&Be[0]!==Ve&&Be[Te-1]!==Ve?[]:ti(Be,Ve);if(Te-=Qe.length,Te<k)return Zi($,I,ui,ye.placeholder,h,Be,Qe,h,h,k-Te);var et=this&&this!==xr&&this instanceof ye?oe:$;return Qr(et,this,Be)}return ye}function _u($){return function(I,k,oe){var ye=yr(I);if(!fn(I)){var Te=St(k,3);I=qr(I),k=function(Le){return Te(ye[Le],Le,ye)}}var Be=$(I,k,oe);return Be>-1?ye[Te?I[Be]:Be]:h}}function Eu($){return _n(function(I){var k=I.length,oe=k,ye=cn.prototype.thru;for($&&I.reverse();oe--;){var Te=I[oe];if(typeof Te!="function")throw new an(_);if(ye&&!Be&&zi(Te)=="wrapper")var Be=new cn([],!0)}for(oe=Be?oe:k;++oe<k;){Te=I[oe];var Le=zi(Te),Ve=Le=="wrapper"?Ps(Te):h;Ve&&Ds(Ve[0])&&Ve[1]==(Pe|ae|Se|Ie)&&!Ve[4].length&&Ve[9]==1?Be=Be[zi(Ve[0])].apply(Be,Ve[3]):Be=Te.length==1&&Ds(Te)?Be[Le]():Be.thru(Te)}return function(){var Qe=arguments,et=Qe[0];if(Be&&Qe.length==1&&kt(et))return Be.plant(et).value();for(var rt=0,ot=k?I[rt].apply(this,Qe):et;++rt<k;)ot=I[rt].call(this,ot);return ot}})}function ui($,I,k,oe,ye,Te,Be,Le,Ve,Qe){var et=I&Pe,rt=I&X,ot=I&ie,mt=I&(ae|de),Ct=I&Ee,Kt=ot?h:Gn($);function Pt(){for(var jt=arguments.length,er=Ge(jt),$n=jt;$n--;)er[$n]=arguments[$n];if(mt)var rn=li(Pt),xn=zs(er,rn);if(oe&&(er=Ce(er,oe,ye,mt)),Te&&(er=ze(er,Te,Be,mt)),jt-=xn,mt&&jt<Qe){var Rr=ti(er,rn);return Zi($,I,ui,Pt.placeholder,k,er,Rr,Le,Ve,Qe-jt)}var Yn=rt?k:this,Pi=ot?Yn[$]:$;return jt=er.length,Le?er=Ya(er,Le):Ct&&jt>1&&er.reverse(),et&&Ve<jt&&(er.length=Ve),this&&this!==xr&&this instanceof Pt&&(Pi=Kt||Gn(Pi)),Pi.apply(Yn,er)}return Pt}function Vi($,I){return function(k,oe){return cu(k,$,I(oe),{})}}function yo($,I){return function(k,oe){var ye;if(k===h&&oe===h)return I;if(k!==h&&(ye=k),oe!==h){if(ye===h)return oe;typeof k=="string"||typeof oe=="string"?(k=Lr(k),oe=Lr(oe)):(k=Aa(k),oe=Aa(oe)),ye=$(k,oe)}return ye}}function Ma($){return _n(function(I){return I=wr(I,en(St())),Dt(function(k){var oe=this;return $(I,function(ye){return Qr(ye,oe,k)})})})}function fi($,I){I=I===h?" ":Lr(I);var k=I.length;if(k<2)return k?Sa(I,$):I;var oe=Sa(I,as($/Di(I)));return bi(I)?Wn(gn(oe),0,$).join(""):oe.slice(0,$)}function Ts($,I,k,oe){var ye=I&X,Te=Gn($);function Be(){for(var Le=-1,Ve=arguments.length,Qe=-1,et=oe.length,rt=Ge(et+Ve),ot=this&&this!==xr&&this instanceof Be?Te:$;++Qe<et;)rt[Qe]=oe[Qe];for(;Ve--;)rt[Qe++]=arguments[++Le];return Qr(ot,ye?k:this,rt)}return Be}function Su($){return function(I,k,oe){return oe&&typeof oe!="number"&&Fr(I,k,oe)&&(k=oe=h),I=Ci(I),k===h?(k=I,I=0):k=Ci(k),oe=oe===h?I<k?1:-1:Ci(oe),On(I,k,oe,$)}}function bo($){return function(I,k){return typeof I=="string"&&typeof k=="string"||(I=Bn(I),k=Bn(k)),$(I,k)}}function Zi($,I,k,oe,ye,Te,Be,Le,Ve,Qe){var et=I&ae,rt=et?Be:h,ot=et?h:Be,mt=et?Te:h,Ct=et?h:Te;I|=et?Se:ve,I&=~(et?ve:Se),I&ee||(I&=~(X|ie));var Kt=[$,I,ye,mt,rt,Ct,ot,Le,Ve,Qe],Pt=k.apply(h,Kt);return Ds($)&&Po(Pt,Kt),Pt.placeholder=oe,od(Pt,$,I)}function Ai($){var I=Ar[$];return function(k,oe){if(k=Bn(k),oe=oe==null?0:Nr(Ht(oe),292),oe&&Wc(k)){var ye=(dr(k)+"e").split("e"),Te=I(ye[0]+"e"+(+ye[1]+oe));return ye=(dr(Te)+"e").split("e"),+(ye[0]+"e"+(+ye[1]-oe))}return I(k)}}var Oa=ni&&1/Ws(new ni([,-0]))[1]==j?function($){return new ni($)}:Nl;function vo($){return function(I){var k=Dr(I);return k==Re?ua(I):k==it?bf(I):Mc(I,$(I))}}function wn($,I,k,oe,ye,Te,Be,Le){var Ve=I&ie;if(!Ve&&typeof $!="function")throw new an(_);var Qe=oe?oe.length:0;if(Qe||(I&=~(Se|ve),oe=ye=h),Be=Be===h?Be:Ir(Ht(Be),0),Le=Le===h?Le:Ht(Le),Qe-=ye?ye.length:0,I&ve){var et=oe,rt=ye;oe=ye=h}var ot=Ve?h:Ps($),mt=[$,I,k,oe,ye,et,rt,Te,Be,Le];if(ot&&Ga(mt,ot),$=mt[0],I=mt[1],k=mt[2],oe=mt[3],ye=mt[4],Le=mt[9]=mt[9]===h?Ve?0:$.length:Ir(mt[9]-Qe,0),!Le&&I&(ae|de)&&(I&=~(ae|de)),!I||I==X)var Ct=xs($,I,k);else I==ae||I==de?Ct=As($,I,Le):(I==Se||I==(X|Se))&&!ye.length?Ct=Ts($,I,k,oe):Ct=ui.apply(h,mt);var Kt=ot?gu:Po;return od(Kt(Ct,mt),$,I)}function wo($,I,k,oe){return $===h||Xn($,Bi[k])&&!cr.call(oe,k)?I:$}function _o($,I,k,oe,ye,Te){return $r($)&&$r(I)&&(Te.set(I,$),ho($,I,h,_o,Te),Te.delete(I)),$}function Da($){return Qa($)?h:$}function Eo($,I,k,oe,ye,Te){var Be=k&U,Le=$.length,Ve=I.length;if(Le!=Ve&&!(Be&&Ve>Le))return!1;var Qe=Te.get($),et=Te.get(I);if(Qe&&et)return Qe==I&&et==$;var rt=-1,ot=!0,mt=k&te?new Ei:h;for(Te.set($,I),Te.set(I,$);++rt<Le;){var Ct=$[rt],Kt=I[rt];if(oe)var Pt=Be?oe(Kt,Ct,rt,I,$,Te):oe(Ct,Kt,rt,$,I,Te);if(Pt!==h){if(Pt)continue;ot=!1;break}if(mt){if(!Vs(I,function(jt,er){if(!yi(mt,er)&&(Ct===jt||ye(Ct,jt,k,oe,Te)))return mt.push(er)})){ot=!1;break}}else if(!(Ct===Kt||ye(Ct,Kt,k,oe,Te))){ot=!1;break}}return Te.delete($),Te.delete(I),ot}function Ba($,I,k,oe,ye,Te,Be){switch(k){case Rt:if($.byteLength!=I.byteLength||$.byteOffset!=I.byteOffset)return!1;$=$.buffer,I=I.buffer;case dt:return!($.byteLength!=I.byteLength||!Te(new Js($),new Js(I)));case me:case Me:case Ue:return Xn(+$,+I);case ge:return $.name==I.name&&$.message==I.message;case nt:case at:return $==I+"";case Re:var Le=ua;case it:var Ve=oe&U;if(Le||(Le=Ws),$.size!=I.size&&!Ve)return!1;var Qe=Be.get($);if(Qe)return Qe==I;oe|=te,Be.set($,I);var et=Eo(Le($),Le(I),oe,ye,Te,Be);return Be.delete($),et;case ct:if(ls)return ls.call($)==ls.call(I)}return!1}function ka($,I,k,oe,ye,Te){var Be=k&U,Le=Is($),Ve=Le.length,Qe=Is(I),et=Qe.length;if(Ve!=et&&!Be)return!1;for(var rt=Ve;rt--;){var ot=Le[rt];if(!(Be?ot in I:cr.call(I,ot)))return!1}var mt=Te.get($),Ct=Te.get(I);if(mt&&Ct)return mt==I&&Ct==$;var Kt=!0;Te.set($,I),Te.set(I,$);for(var Pt=Be;++rt<Ve;){ot=Le[rt];var jt=$[ot],er=I[ot];if(oe)var $n=Be?oe(er,jt,ot,I,$,Te):oe(jt,er,ot,$,I,Te);if(!($n===h?jt===er||ye(jt,er,k,oe,Te):$n)){Kt=!1;break}Pt||(Pt=ot=="constructor")}if(Kt&&!Pt){var rn=$.constructor,xn=I.constructor;rn!=xn&&"constructor"in $&&"constructor"in I&&!(typeof rn=="function"&&rn instanceof rn&&typeof xn=="function"&&xn instanceof xn)&&(Kt=!1)}return Te.delete($),Te.delete(I),Kt}function _n($){return $l(Io($,h,dd),$+"")}function Is($){return Mn($,qr,Ms)}function Cs($){return Mn($,ln,So)}var Ps=ro?function($){return ro.get($)}:Nl;function zi($){for(var I=$.name+"",k=Ni[I],oe=cr.call(Ni,I)?k.length:0;oe--;){var ye=k[oe],Te=ye.func;if(Te==null||Te==$)return ye.name}return I}function li($){var I=cr.call($e,"placeholder")?$e:$;return I.placeholder}function St(){var $=$e.iteratee||Bl;return $=$===Bl?vs:$,arguments.length?$(arguments[0],arguments[1]):$}function Wi($,I){var k=$.__data__;return Va(I)?k[typeof I=="string"?"string":"hash"]:k.map}function Rs($){for(var I=qr($),k=I.length;k--;){var oe=I[k],ye=$[oe];I[k]=[oe,ye,Ao(ye)]}return I}function jn($,I){var k=gf($,I);return wa(k)?k:h}function Na($){var I=cr.call($,vi),k=$[vi];try{$[vi]=h;var oe=!0}catch{}var ye=Xs.call($);return oe&&(I?$[vi]=k:delete $[vi]),ye}var Ms=da?function($){return $==null?[]:($=yr($),Kn(da($),function(I){return Kc.call($,I)}))}:Ll,So=da?function($){for(var I=[];$;)ei(I,Ms($)),$=ki($);return I}:Ll,Dr=Wr;(to&&Dr(new to(new ArrayBuffer(1)))!=Rt||cs&&Dr(new cs)!=Re||ha&&Dr(ha.resolve())!=tt||ni&&Dr(new ni)!=it||_i&&Dr(new _i)!=xt)&&(Dr=function($){var I=Wr($),k=I==Ze?$.constructor:h,oe=k?ks(k):"";if(oe)switch(oe){case Nf:return Rt;case Lf:return Re;case Ff:return tt;case Uf:return it;case qf:return xt}return I});function La($,I,k){for(var oe=-1,ye=k.length;++oe<ye;){var Te=k[oe],Be=Te.size;switch(Te.type){case"drop":$+=Be;break;case"dropRight":I-=Be;break;case"take":I=Nr(I,$+Be);break;case"takeRight":$=Ir($,I-Be);break}}return{start:$,end:I}}function Fa($){var I=$.match(_t);return I?I[1].split(st):[]}function $o($,I,k){I=ci(I,$);for(var oe=-1,ye=I.length,Te=!1;++oe<ye;){var Be=di(I[oe]);if(!(Te=$!=null&&k($,Be)))break;$=$[Be]}return Te||++oe!=ye?Te:(ye=$==null?0:$.length,!!ye&&Pu(ye)&&En(Be,ye)&&(kt($)||Ns($)))}function Ua($){var I=$.length,k=new $.constructor(I);return I&&typeof $[0]=="string"&&cr.call($,"index")&&(k.index=$.index,k.input=$.input),k}function xo($){return typeof $.constructor=="function"&&!Ti($)?Li(ki($)):{}}function qa($,I,k){var oe=$.constructor;switch(I){case dt:return $s($);case me:case Me:return new oe(+$);case Rt:return Sl($,k);case Nt:case yt:case zt:case Vt:case vt:case Ut:case Lt:case wt:case Wt:return L($,k);case Re:return new oe;case Ue:case at:return new oe($);case nt:return A($);case it:return new oe;case ct:return P($)}}function Ha($,I){var k=I.length;if(!k)return $;var oe=k-1;return I[oe]=(k>1?"& ":"")+I[oe],I=I.join(k>2?", ":" "),$.replace(ut,`{
57
+ /* [wrapped with `+I+`] */
58
+ `)}function Ka($){return kt($)||Ns($)||!!(Vc&&$&&$[Vc])}function En($,I){var k=typeof $;return I=I??ne,!!I&&(k=="number"||k!="symbol"&&Xr.test($))&&$>-1&&$%1==0&&$<I}function Fr($,I,k){if(!$r(k))return!1;var oe=typeof I;return(oe=="number"?fn(k)&&En(I,k.length):oe=="string"&&I in k)?Xn(k[I],$):!1}function Os($,I){if(kt($))return!1;var k=typeof $;return k=="number"||k=="symbol"||k=="boolean"||$==null||Sn($)?!0:se.test($)||!we.test($)||I!=null&&$ in yr(I)}function Va($){var I=typeof $;return I=="string"||I=="number"||I=="symbol"||I=="boolean"?$!=="__proto__":$===null}function Ds($){var I=zi($),k=$e[I];if(typeof k!="function"||!(I in Zt.prototype))return!1;if($===k)return!0;var oe=Ps(k);return!!oe&&$===oe[0]}function Za($){return!!Uc&&Uc in $}var za=js?Ii:Fl;function Ti($){var I=$&&$.constructor,k=typeof I=="function"&&I.prototype||Bi;return $===k}function Ao($){return $===$&&!$r($)}function To($,I){return function(k){return k==null?!1:k[$]===I&&(I!==h||$ in yr(k))}}function Wa($){var I=Iu($,function(oe){return k.size===x&&k.clear(),oe}),k=I.cache;return I}function Ga($,I){var k=$[1],oe=I[1],ye=k|oe,Te=ye<(X|ie|Pe),Be=oe==Pe&&k==ae||oe==Pe&&k==Ie&&$[7].length<=I[8]||oe==(Pe|Ie)&&I[7].length<=I[8]&&k==ae;if(!(Te||Be))return $;oe&X&&($[2]=I[2],ye|=k&X?0:ee);var Le=I[3];if(Le){var Ve=$[3];$[3]=Ve?Ce(Ve,Le,I[4]):Le,$[4]=Ve?ti($[3],T):I[4]}return Le=I[5],Le&&(Ve=$[5],$[5]=Ve?ze(Ve,Le,I[6]):Le,$[6]=Ve?ti($[5],T):I[6]),Le=I[7],Le&&($[7]=Le),oe&Pe&&($[8]=$[8]==null?I[8]:Nr($[8],I[8])),$[9]==null&&($[9]=I[9]),$[0]=I[0],$[1]=ye,$}function ja($){var I=[];if($!=null)for(var k in yr($))I.push(k);return I}function Xa($){return Xs.call($)}function Io($,I,k){return I=Ir(I===h?$.length-1:I,0),function(){for(var oe=arguments,ye=-1,Te=Ir(oe.length-I,0),Be=Ge(Te);++ye<Te;)Be[ye]=oe[I+ye];ye=-1;for(var Le=Ge(I+1);++ye<I;)Le[ye]=oe[ye];return Le[I]=k(Be),Qr($,this,Le)}}function Co($,I){return I.length<2?$:oi($,tn(I,0,-1))}function Ya($,I){for(var k=$.length,oe=Nr(I.length,k),ye=Je($);oe--;){var Te=I[oe];$[oe]=En(Te,k)?ye[Te]:h}return $}function Bs($,I){if(!(I==="constructor"&&typeof $[I]=="function")&&I!="__proto__")return $[I]}var Po=ad(gu),Ja=wi||function($,I){return xr.setTimeout($,I)},$l=ad(mu);function od($,I,k){var oe=I+"";return $l($,Ha(oe,Vh(Fa(oe),k)))}function ad($){var I=0,k=0;return function(){var oe=Df(),ye=F-(oe-k);if(k=oe,ye>0){if(++I>=B)return arguments[0]}else I=0;return $.apply(h,arguments)}}function $u($,I){var k=-1,oe=$.length,ye=oe-1;for(I=I===h?oe:I;++k<I;){var Te=Es(k,ye),Be=$[Te];$[Te]=$[k],$[k]=Be}return $.length=I,$}var cd=Wa(function($){var I=[];return $.charCodeAt(0)===46&&I.push(""),$.replace(ue,function(k,oe,ye,Te){I.push(ye?Te.replace(It,"$1"):oe||k)}),I});function di($){if(typeof $=="string"||Sn($))return $;var I=$+"";return I=="0"&&1/$==-j?"-0":I}function ks($){if($!=null){try{return is.call($)}catch{}try{return $+""}catch{}}return""}function Vh($,I){return on(Oe,function(k){var oe="_."+k[0];I&k[1]&&!rs($,oe)&&$.push(oe)}),$.sort()}function ud($){if($ instanceof Zt)return $.clone();var I=new cn($.__wrapped__,$.__chain__);return I.__actions__=Je($.__actions__),I.__index__=$.__index__,I.__values__=$.__values__,I}function Zh($,I,k){(k?Fr($,I,k):I===h)?I=1:I=Ir(Ht(I),0);var oe=$==null?0:$.length;if(!oe||I<1)return[];for(var ye=0,Te=0,Be=Ge(as(oe/I));ye<oe;)Be[Te++]=tn($,ye,ye+=I);return Be}function zh($){for(var I=-1,k=$==null?0:$.length,oe=0,ye=[];++I<k;){var Te=$[I];Te&&(ye[oe++]=Te)}return ye}function Wh(){var $=arguments.length;if(!$)return[];for(var I=Ge($-1),k=arguments[0],oe=$;oe--;)I[oe-1]=arguments[oe];return ei(kt(k)?Je(k):[k],Cr(I,1))}var Gh=Dt(function($,I){return Pr($)?hs($,Cr(I,1,Pr,!0)):[]}),jh=Dt(function($,I){var k=Dn(I);return Pr(k)&&(k=h),Pr($)?hs($,Cr(I,1,Pr,!0),St(k,2)):[]}),Xh=Dt(function($,I){var k=Dn(I);return Pr(k)&&(k=h),Pr($)?hs($,Cr(I,1,Pr,!0),h,k):[]});function Yh($,I,k){var oe=$==null?0:$.length;return oe?(I=k||I===h?1:Ht(I),tn($,I<0?0:I,oe)):[]}function Jh($,I,k){var oe=$==null?0:$.length;return oe?(I=k||I===h?1:Ht(I),I=oe-I,tn($,0,I<0?0:I)):[]}function Qh($,I){return $&&$.length?Ss($,St(I,3),!0,!0):[]}function ep($,I){return $&&$.length?Ss($,St(I,3),!0):[]}function tp($,I,k,oe){var ye=$==null?0:$.length;return ye?(k&&typeof k!="number"&&Fr($,I,k)&&(k=0,oe=ye),Fi($,I,k,oe)):[]}function fd($,I,k){var oe=$==null?0:$.length;if(!oe)return-1;var ye=k==null?0:Ht(k);return ye<0&&(ye=Ir(oe+ye,0)),Zs($,St(I,3),ye)}function ld($,I,k){var oe=$==null?0:$.length;if(!oe)return-1;var ye=oe-1;return k!==h&&(ye=Ht(k),ye=k<0?Ir(oe+ye,0):Nr(ye,oe-1)),Zs($,St(I,3),ye,!0)}function dd($){var I=$==null?0:$.length;return I?Cr($,1):[]}function rp($){var I=$==null?0:$.length;return I?Cr($,j):[]}function np($,I){var k=$==null?0:$.length;return k?(I=I===h?1:Ht(I),Cr($,I)):[]}function ip($){for(var I=-1,k=$==null?0:$.length,oe={};++I<k;){var ye=$[I];oe[ye[0]]=ye[1]}return oe}function hd($){return $&&$.length?$[0]:h}function sp($,I,k){var oe=$==null?0:$.length;if(!oe)return-1;var ye=k==null?0:Ht(k);return ye<0&&(ye=Ir(oe+ye,0)),mi($,I,ye)}function op($){var I=$==null?0:$.length;return I?tn($,0,-1):[]}var ap=Dt(function($){var I=wr($,Pa);return I.length&&I[0]===$[0]?ya(I):[]}),cp=Dt(function($){var I=Dn($),k=wr($,Pa);return I===Dn(k)?I=h:k.pop(),k.length&&k[0]===$[0]?ya(k,St(I,2)):[]}),up=Dt(function($){var I=Dn($),k=wr($,Pa);return I=typeof I=="function"?I:h,I&&k.pop(),k.length&&k[0]===$[0]?ya(k,h,I):[]});function fp($,I){return $==null?"":Mf.call($,I)}function Dn($){var I=$==null?0:$.length;return I?$[I-1]:h}function lp($,I,k){var oe=$==null?0:$.length;if(!oe)return-1;var ye=oe;return k!==h&&(ye=Ht(k),ye=ye<0?Ir(oe+ye,0):Nr(ye,oe-1)),I===I?wf($,I,ye):Zs($,Cc,ye,!0)}function dp($,I){return $&&$.length?du($,Ht(I)):h}var hp=Dt(pd);function pd($,I){return $&&$.length&&I&&I.length?po($,I):$}function pp($,I,k){return $&&$.length&&I&&I.length?po($,I,St(k,2)):$}function gp($,I,k){return $&&$.length&&I&&I.length?po($,I,h,k):$}var mp=_n(function($,I){var k=$==null?0:$.length,oe=oo($,I);return _s($,wr(I,function(ye){return En(ye,k)?+ye:ye}).sort(Y)),oe});function yp($,I){var k=[];if(!($&&$.length))return k;var oe=-1,ye=[],Te=$.length;for(I=St(I,3);++oe<Te;){var Be=$[oe];I(Be,oe,$)&&(k.push(Be),ye.push(oe))}return _s($,ye),k}function xl($){return $==null?$:kf.call($)}function bp($,I,k){var oe=$==null?0:$.length;return oe?(k&&typeof k!="number"&&Fr($,I,k)?(I=0,k=oe):(I=I==null?0:Ht(I),k=k===h?oe:Ht(k)),tn($,I,k)):[]}function vp($,I){return qi($,I)}function wp($,I,k){return $a($,I,St(k,2))}function _p($,I){var k=$==null?0:$.length;if(k){var oe=qi($,I);if(oe<k&&Xn($[oe],I))return oe}return-1}function Ep($,I){return qi($,I,!0)}function Sp($,I,k){return $a($,I,St(k,2),!0)}function $p($,I){var k=$==null?0:$.length;if(k){var oe=qi($,I,!0)-1;if(Xn($[oe],I))return oe}return-1}function xp($){return $&&$.length?xa($):[]}function Ap($,I){return $&&$.length?xa($,St(I,2)):[]}function Tp($){var I=$==null?0:$.length;return I?tn($,1,I):[]}function Ip($,I,k){return $&&$.length?(I=k||I===h?1:Ht(I),tn($,0,I<0?0:I)):[]}function Cp($,I,k){var oe=$==null?0:$.length;return oe?(I=k||I===h?1:Ht(I),I=oe-I,tn($,I<0?0:I,oe)):[]}function Pp($,I){return $&&$.length?Ss($,St(I,3),!1,!0):[]}function Rp($,I){return $&&$.length?Ss($,St(I,3)):[]}var Mp=Dt(function($){return ai(Cr($,1,Pr,!0))}),Dp=Dt(function($){var I=Dn($);return Pr(I)&&(I=h),ai(Cr($,1,Pr,!0),St(I,2))}),Bp=Dt(function($){var I=Dn($);return I=typeof I=="function"?I:h,ai(Cr($,1,Pr,!0),h,I)});function kp($){return $&&$.length?ai($):[]}function Np($,I){return $&&$.length?ai($,St(I,2)):[]}function Lp($,I){return I=typeof I=="function"?I:h,$&&$.length?ai($,h,I):[]}function Al($){if(!($&&$.length))return[];var I=0;return $=Kn($,function(k){if(Pr(k))return I=Ir(k.length,I),!0}),aa(I,function(k){return wr($,sa(k))})}function gd($,I){if(!($&&$.length))return[];var k=Al($);return I==null?k:wr(k,function(oe){return Qr(I,h,oe)})}var Up=Dt(function($,I){return Pr($)?hs($,I):[]}),qp=Dt(function($){return go(Kn($,Pr))}),Hp=Dt(function($){var I=Dn($);return Pr(I)&&(I=h),go(Kn($,Pr),St(I,2))}),Kp=Dt(function($){var I=Dn($);return I=typeof I=="function"?I:h,go(Kn($,Pr),h,I)}),Vp=Dt(Al);function Zp($,I){return yu($||[],I||[],ds)}function zp($,I){return yu($||[],I||[],Ui)}var Wp=Dt(function($){var I=$.length,k=I>1?$[I-1]:h;return k=typeof k=="function"?($.pop(),k):h,gd($,k)});function md($){var I=$e($);return I.__chain__=!0,I}function Gp($,I){return I($),$}function xu($,I){return I($)}var jp=_n(function($){var I=$.length,k=I?$[0]:0,oe=this.__wrapped__,ye=function(Te){return oo(Te,$)};return I>1||this.__actions__.length||!(oe instanceof Zt)||!En(k)?this.thru(ye):(oe=oe.slice(k,+k+(I?1:0)),oe.__actions__.push({func:xu,args:[ye],thisArg:h}),new cn(oe,this.__chain__).thru(function(Te){return I&&!Te.length&&Te.push(h),Te}))});function Xp(){return md(this)}function Yp(){return new cn(this.value(),this.__chain__)}function Jp(){this.__values__===h&&(this.__values__=Pd(this.value()));var $=this.__index__>=this.__values__.length,I=$?h:this.__values__[this.__index__++];return{done:$,value:I}}function Qp(){return this}function e0($){for(var I,k=this;k instanceof io;){var oe=ud(k);oe.__index__=0,oe.__values__=h,I?ye.__wrapped__=oe:I=oe;var ye=oe;k=k.__wrapped__}return ye.__wrapped__=$,I}function t0(){var $=this.__wrapped__;if($ instanceof Zt){var I=$;return this.__actions__.length&&(I=new Zt(this)),I=I.reverse(),I.__actions__.push({func:xu,args:[xl],thisArg:h}),new cn(I,this.__chain__)}return this.thru(xl)}function r0(){return Ca(this.__wrapped__,this.__actions__)}var n0=Sr(function($,I,k){cr.call($,k)?++$[k]:Rn($,k,1)});function i0($,I,k){var oe=kt($)?ra:fl;return k&&Fr($,I,k)&&(I=h),oe($,St(I,3))}function s0($,I){var k=kt($)?Kn:ou;return k($,St(I,3))}var o0=_u(fd),a0=_u(ld);function c0($,I){return Cr(Au($,I),1)}function u0($,I){return Cr(Au($,I),j)}function f0($,I,k){return k=k===h?1:Ht(k),Cr(Au($,I),k)}function yd($,I){var k=kt($)?on:si;return k($,St(I,3))}function bd($,I){var k=kt($)?uf:ao;return k($,St(I,3))}var l0=Sr(function($,I,k){cr.call($,k)?$[k].push(I):Rn($,k,[I])});function d0($,I,k,oe){$=fn($)?$:Mo($),k=k&&!oe?Ht(k):0;var ye=$.length;return k<0&&(k=Ir(ye+k,0)),Ru($)?k<=ye&&$.indexOf(I,k)>-1:!!ye&&mi($,I,k)>-1}var h0=Dt(function($,I,k){var oe=-1,ye=typeof I=="function",Te=fn($)?Ge($.length):[];return si($,function(Be){Te[++oe]=ye?Qr(I,Be,k):gs(Be,I,k)}),Te}),p0=Sr(function($,I,k){Rn($,k,I)});function Au($,I){var k=kt($)?wr:uu;return k($,St(I,3))}function g0($,I,k,oe){return $==null?[]:(kt(I)||(I=I==null?[]:[I]),k=oe?h:k,kt(k)||(k=k==null?[]:[k]),Ea($,I,k))}var m0=Sr(function($,I,k){$[k?0:1].push(I)},function(){return[[],[]]});function y0($,I,k){var oe=kt($)?ia:Rc,ye=arguments.length<3;return oe($,St(I,4),k,ye,si)}function b0($,I,k){var oe=kt($)?ff:Rc,ye=arguments.length<3;return oe($,St(I,4),k,ye,ao)}function v0($,I){var k=kt($)?Kn:ou;return k($,Cu(St(I,3)))}function w0($){var I=kt($)?tu:bl;return I($)}function _0($,I,k){(k?Fr($,I,k):I===h)?I=1:I=Ht(I);var oe=kt($)?al:vl;return oe($,I)}function E0($){var I=kt($)?cl:wl;return I($)}function S0($){if($==null)return 0;if(fn($))return Ru($)?Di($):$.length;var I=Dr($);return I==Re||I==it?$.size:ws($).length}function $0($,I,k){var oe=kt($)?Vs:_l;return k&&Fr($,I,k)&&(I=h),oe($,St(I,3))}var x0=Dt(function($,I){if($==null)return[];var k=I.length;return k>1&&Fr($,I[0],I[1])?I=[]:k>2&&Fr(I[0],I[1],I[2])&&(I=[I[0]]),Ea($,Cr(I,1),[])}),Tu=zc||function(){return xr.Date.now()};function A0($,I){if(typeof I!="function")throw new an(_);return $=Ht($),function(){if(--$<1)return I.apply(this,arguments)}}function vd($,I,k){return I=k?h:I,I=$&&I==null?$.length:I,wn($,Pe,h,h,h,h,I)}function wd($,I){var k;if(typeof I!="function")throw new an(_);return $=Ht($),function(){return--$>0&&(k=I.apply(this,arguments)),$<=1&&(I=h),k}}var Tl=Dt(function($,I,k){var oe=X;if(k.length){var ye=ti(k,li(Tl));oe|=Se}return wn($,oe,I,k,ye)}),_d=Dt(function($,I,k){var oe=X|ie;if(k.length){var ye=ti(k,li(_d));oe|=Se}return wn(I,oe,$,k,ye)});function Ed($,I,k){I=k?h:I;var oe=wn($,ae,h,h,h,h,h,I);return oe.placeholder=Ed.placeholder,oe}function Sd($,I,k){I=k?h:I;var oe=wn($,de,h,h,h,h,h,I);return oe.placeholder=Sd.placeholder,oe}function $d($,I,k){var oe,ye,Te,Be,Le,Ve,Qe=0,et=!1,rt=!1,ot=!0;if(typeof $!="function")throw new an(_);I=Bn(I)||0,$r(k)&&(et=!!k.leading,rt="maxWait"in k,Te=rt?Ir(Bn(k.maxWait)||0,I):Te,ot="trailing"in k?!!k.trailing:ot);function mt(Rr){var Yn=oe,Pi=ye;return oe=ye=h,Qe=Rr,Be=$.apply(Pi,Yn),Be}function Ct(Rr){return Qe=Rr,Le=Ja(jt,I),et?mt(Rr):Be}function Kt(Rr){var Yn=Rr-Ve,Pi=Rr-Qe,Kd=I-Yn;return rt?Nr(Kd,Te-Pi):Kd}function Pt(Rr){var Yn=Rr-Ve,Pi=Rr-Qe;return Ve===h||Yn>=I||Yn<0||rt&&Pi>=Te}function jt(){var Rr=Tu();if(Pt(Rr))return er(Rr);Le=Ja(jt,Kt(Rr))}function er(Rr){return Le=h,ot&&oe?mt(Rr):(oe=ye=h,Be)}function $n(){Le!==h&&mo(Le),Qe=0,oe=Ve=ye=Le=h}function rn(){return Le===h?Be:er(Tu())}function xn(){var Rr=Tu(),Yn=Pt(Rr);if(oe=arguments,ye=this,Ve=Rr,Yn){if(Le===h)return Ct(Ve);if(rt)return mo(Le),Le=Ja(jt,I),mt(Ve)}return Le===h&&(Le=Ja(jt,I)),Be}return xn.cancel=$n,xn.flush=rn,xn}var T0=Dt(function($,I){return su($,1,I)}),I0=Dt(function($,I,k){return su($,Bn(I)||0,k)});function C0($){return wn($,Ee)}function Iu($,I){if(typeof $!="function"||I!=null&&typeof I!="function")throw new an(_);var k=function(){var oe=arguments,ye=I?I.apply(this,oe):oe[0],Te=k.cache;if(Te.has(ye))return Te.get(ye);var Be=$.apply(this,oe);return k.cache=Te.set(ye,Be)||Te,Be};return k.cache=new(Iu.Cache||Pn),k}Iu.Cache=Pn;function Cu($){if(typeof $!="function")throw new an(_);return function(){var I=arguments;switch(I.length){case 0:return!$.call(this);case 1:return!$.call(this,I[0]);case 2:return!$.call(this,I[0],I[1]);case 3:return!$.call(this,I[0],I[1],I[2])}return!$.apply(this,I)}}function P0($){return wd(2,$)}var R0=El(function($,I){I=I.length==1&&kt(I[0])?wr(I[0],en(St())):wr(Cr(I,1),en(St()));var k=I.length;return Dt(function(oe){for(var ye=-1,Te=Nr(oe.length,k);++ye<Te;)oe[ye]=I[ye].call(this,oe[ye]);return Qr($,this,oe)})}),Il=Dt(function($,I){var k=ti(I,li(Il));return wn($,Se,h,I,k)}),xd=Dt(function($,I){var k=ti(I,li(xd));return wn($,ve,h,I,k)}),M0=_n(function($,I){return wn($,Ie,h,h,h,I)});function O0($,I){if(typeof $!="function")throw new an(_);return I=I===h?I:Ht(I),Dt($,I)}function D0($,I){if(typeof $!="function")throw new an(_);return I=I==null?0:Ir(Ht(I),0),Dt(function(k){var oe=k[I],ye=Wn(k,0,I);return oe&&ei(ye,oe),Qr($,this,ye)})}function B0($,I,k){var oe=!0,ye=!0;if(typeof $!="function")throw new an(_);return $r(k)&&(oe="leading"in k?!!k.leading:oe,ye="trailing"in k?!!k.trailing:ye),$d($,I,{leading:oe,maxWait:I,trailing:ye})}function k0($){return vd($,1)}function N0($,I){return Il(Ra(I),$)}function L0(){if(!arguments.length)return[];var $=arguments[0];return kt($)?$:[$]}function F0($){return un($,D)}function U0($,I){return I=typeof I=="function"?I:h,un($,D,I)}function q0($){return un($,C|D)}function H0($,I){return I=typeof I=="function"?I:h,un($,C|D,I)}function K0($,I){return I==null||iu($,I,qr(I))}function Xn($,I){return $===I||$!==$&&I!==I}var V0=bo(ma),Z0=bo(function($,I){return $>=I}),Ns=ba(function(){return arguments}())?ba:function($){return Tr($)&&cr.call($,"callee")&&!Kc.call($,"callee")},kt=Ge.isArray,z0=Ec?en(Ec):gl;function fn($){return $!=null&&Pu($.length)&&!Ii($)}function Pr($){return Tr($)&&fn($)}function W0($){return $===!0||$===!1||Tr($)&&Wr($)==me}var Gi=Rf||Fl,G0=Sc?en(Sc):ml;function j0($){return Tr($)&&$.nodeType===1&&!Qa($)}function X0($){if($==null)return!0;if(fn($)&&(kt($)||typeof $=="string"||typeof $.splice=="function"||Gi($)||Ro($)||Ns($)))return!$.length;var I=Dr($);if(I==Re||I==it)return!$.size;if(Ti($))return!ws($).length;for(var k in $)if(cr.call($,k))return!1;return!0}function Y0($,I){return ys($,I)}function J0($,I,k){k=typeof k=="function"?k:h;var oe=k?k($,I):h;return oe===h?ys($,I,h,k):!!oe}function Cl($){if(!Tr($))return!1;var I=Wr($);return I==ge||I==fe||typeof $.message=="string"&&typeof $.name=="string"&&!Qa($)}function Q0($){return typeof $=="number"&&Wc($)}function Ii($){if(!$r($))return!1;var I=Wr($);return I==ce||I==_e||I==le||I==Fe}function Ad($){return typeof $=="number"&&$==Ht($)}function Pu($){return typeof $=="number"&&$>-1&&$%1==0&&$<=ne}function $r($){var I=typeof $;return $!=null&&(I=="object"||I=="function")}function Tr($){return $!=null&&typeof $=="object"}var Td=$c?en($c):bs;function eg($,I){return $===I||va($,I,Rs(I))}function tg($,I,k){return k=typeof k=="function"?k:h,va($,I,Rs(I),k)}function rg($){return Id($)&&$!=+$}function ng($){if(za($))throw new Mt(w);return wa($)}function ig($){return $===null}function sg($){return $==null}function Id($){return typeof $=="number"||Tr($)&&Wr($)==Ue}function Qa($){if(!Tr($)||Wr($)!=Ze)return!1;var I=ki($);if(I===null)return!0;var k=cr.call(I,"constructor")&&I.constructor;return typeof k=="function"&&k instanceof k&&is.call(k)==If}var Pl=ea?en(ea):Ur;function og($){return Ad($)&&$>=-ne&&$<=ne}var Cd=ta?en(ta):Or;function Ru($){return typeof $=="string"||!kt($)&&Tr($)&&Wr($)==at}function Sn($){return typeof $=="symbol"||Tr($)&&Wr($)==ct}var Ro=xc?en(xc):fo;function ag($){return $===h}function cg($){return Tr($)&&Dr($)==xt}function ug($){return Tr($)&&Wr($)==Ot}var fg=bo(_a),lg=bo(function($,I){return $<=I});function Pd($){if(!$)return[];if(fn($))return Ru($)?gn($):Je($);if(os&&$[os])return yf($[os]());var I=Dr($),k=I==Re?ua:I==it?Ws:Mo;return k($)}function Ci($){if(!$)return $===0?$:0;if($=Bn($),$===j||$===-j){var I=$<0?-1:1;return I*J}return $===$?$:0}function Ht($){var I=Ci($),k=I%1;return I===I?k?I-k:I:0}function Rd($){return $?$i(Ht($),0,re):0}function Bn($){if(typeof $=="number")return $;if(Sn($))return q;if($r($)){var I=typeof $.valueOf=="function"?$.valueOf():$;$=$r(I)?I+"":I}if(typeof $!="string")return $===0?$:+$;$=Oc($);var k=Gr.test($);return k||jr.test($)?cf($.slice(2),k?2:8):ar.test($)?q:+$}function Md($){return Xe($,ln($))}function dg($){return $?$i(Ht($),-ne,ne):$===0?$:0}function dr($){return $==null?"":Lr($)}var hg=vn(function($,I){if(Ti(I)||fn(I)){Xe(I,qr(I),$);return}for(var k in I)cr.call(I,k)&&ds($,k,I[k])}),Od=vn(function($,I){Xe(I,ln(I),$)}),Mu=vn(function($,I,k,oe){Xe(I,ln(I),$,oe)}),pg=vn(function($,I,k,oe){Xe(I,qr(I),$,oe)}),gg=_n(oo);function mg($,I){var k=Li($);return I==null?k:Si(k,I)}var yg=Dt(function($,I){$=yr($);var k=-1,oe=I.length,ye=oe>2?I[2]:h;for(ye&&Fr(I[0],I[1],ye)&&(oe=1);++k<oe;)for(var Te=I[k],Be=ln(Te),Le=-1,Ve=Be.length;++Le<Ve;){var Qe=Be[Le],et=$[Qe];(et===h||Xn(et,Bi[Qe])&&!cr.call($,Qe))&&($[Qe]=Te[Qe])}return $}),bg=Dt(function($){return $.push(h,_o),Qr(Dd,h,$)});function vg($,I){return Tc($,St(I,3),yn)}function wg($,I){return Tc($,St(I,3),uo)}function _g($,I){return $==null?$:co($,St(I,3),ln)}function Eg($,I){return $==null?$:au($,St(I,3),ln)}function Sg($,I){return $&&yn($,St(I,3))}function $g($,I){return $&&uo($,St(I,3))}function xg($){return $==null?[]:ps($,qr($))}function Ag($){return $==null?[]:ps($,ln($))}function Rl($,I,k){var oe=$==null?h:oi($,I);return oe===h?k:oe}function Tg($,I){return $!=null&&$o($,I,ll)}function Ml($,I){return $!=null&&$o($,I,dl)}var Ig=Vi(function($,I,k){I!=null&&typeof I.toString!="function"&&(I=Xs.call(I)),$[I]=k},Dl(dn)),Cg=Vi(function($,I,k){I!=null&&typeof I.toString!="function"&&(I=Xs.call(I)),cr.call($,I)?$[I].push(k):$[I]=[k]},St),Pg=Dt(gs);function qr($){return fn($)?eu($):ws($)}function ln($){return fn($)?eu($,!0):lo($)}function Rg($,I){var k={};return I=St(I,3),yn($,function(oe,ye,Te){Rn(k,I(oe,ye,Te),oe)}),k}function Mg($,I){var k={};return I=St(I,3),yn($,function(oe,ye,Te){Rn(k,ye,I(oe,ye,Te))}),k}var Og=vn(function($,I,k){ho($,I,k)}),Dd=vn(function($,I,k,oe){ho($,I,k,oe)}),Dg=_n(function($,I){var k={};if($==null)return k;var oe=!1;I=wr(I,function(Te){return Te=ci(Te,$),oe||(oe=Te.length>1),Te}),Xe($,Cs($),k),oe&&(k=un(k,C|O|D,Da));for(var ye=I.length;ye--;)Ta(k,I[ye]);return k});function Bg($,I){return Bd($,Cu(St(I)))}var kg=_n(function($,I){return $==null?{}:yl($,I)});function Bd($,I){if($==null)return{};var k=wr(Cs($),function(oe){return[oe]});return I=St(I),hu($,k,function(oe,ye){return I(oe,ye[0])})}function Ng($,I,k){I=ci(I,$);var oe=-1,ye=I.length;for(ye||(ye=1,$=h);++oe<ye;){var Te=$==null?h:$[di(I[oe])];Te===h&&(oe=ye,Te=k),$=Ii(Te)?Te.call($):Te}return $}function Lg($,I,k){return $==null?$:Ui($,I,k)}function Fg($,I,k,oe){return oe=typeof oe=="function"?oe:h,$==null?$:Ui($,I,k,oe)}var kd=vo(qr),Nd=vo(ln);function Ug($,I,k){var oe=kt($),ye=oe||Gi($)||Ro($);if(I=St(I,4),k==null){var Te=$&&$.constructor;ye?k=oe?new Te:[]:$r($)?k=Ii(Te)?Li(ki($)):{}:k={}}return(ye?on:yn)($,function(Be,Le,Ve){return I(k,Be,Le,Ve)}),k}function qg($,I){return $==null?!0:Ta($,I)}function Hg($,I,k){return $==null?$:Ia($,I,Ra(k))}function Kg($,I,k,oe){return oe=typeof oe=="function"?oe:h,$==null?$:Ia($,I,Ra(k),oe)}function Mo($){return $==null?[]:ca($,qr($))}function Vg($){return $==null?[]:ca($,ln($))}function Zg($,I,k){return k===h&&(k=I,I=h),k!==h&&(k=Bn(k),k=k===k?k:0),I!==h&&(I=Bn(I),I=I===I?I:0),$i(Bn($),I,k)}function zg($,I,k){return I=Ci(I),k===h?(k=I,I=0):k=Ci(k),$=Bn($),pl($,I,k)}function Wg($,I,k){if(k&&typeof k!="boolean"&&Fr($,I,k)&&(I=k=h),k===h&&(typeof I=="boolean"?(k=I,I=h):typeof $=="boolean"&&(k=$,$=h)),$===h&&I===h?($=0,I=1):($=Ci($),I===h?(I=$,$=0):I=Ci(I)),$>I){var oe=$;$=I,I=oe}if(k||$%1||I%1){var ye=Vn();return Nr($+ye*(I-$+af("1e-"+((ye+"").length-1))),I)}return Es($,I)}var Gg=Ki(function($,I,k){return I=I.toLowerCase(),$+(k?Ld(I):I)});function Ld($){return Ol(dr($).toLowerCase())}function Fd($){return $=dr($),$&&$.replace(Yr,pf).replace(tf,"")}function jg($,I,k){$=dr($),I=Lr(I);var oe=$.length;k=k===h?oe:$i(Ht(k),0,oe);var ye=k;return k-=I.length,k>=0&&$.slice(k,ye)==I}function Xg($){return $=dr($),$&&Yt.test($)?$.replace(bt,kc):$}function Yg($){return $=dr($),$&&ke.test($)?$.replace(xe,"\\$&"):$}var Jg=Ki(function($,I,k){return $+(k?"-":"")+I.toLowerCase()}),Qg=Ki(function($,I,k){return $+(k?" ":"")+I.toLowerCase()}),e1=wu("toLowerCase");function t1($,I,k){$=dr($),I=Ht(I);var oe=I?Di($):0;if(!I||oe>=I)return $;var ye=(I-oe)/2;return fi(eo(ye),k)+$+fi(as(ye),k)}function r1($,I,k){$=dr($),I=Ht(I);var oe=I?Di($):0;return I&&oe<I?$+fi(I-oe,k):$}function n1($,I,k){$=dr($),I=Ht(I);var oe=I?Di($):0;return I&&oe<I?fi(I-oe,k)+$:$}function i1($,I,k){return k||I==null?I=0:I&&(I=+I),Bf(dr($).replace(Ke,""),I||0)}function s1($,I,k){return(k?Fr($,I,k):I===h)?I=1:I=Ht(I),Sa(dr($),I)}function o1(){var $=arguments,I=dr($[0]);return $.length<3?I:I.replace($[1],$[2])}var a1=Ki(function($,I,k){return $+(k?"_":"")+I.toLowerCase()});function c1($,I,k){return k&&typeof k!="number"&&Fr($,I,k)&&(I=k=h),k=k===h?re:k>>>0,k?($=dr($),$&&(typeof I=="string"||I!=null&&!Pl(I))&&(I=Lr(I),!I&&bi($))?Wn(gn($),0,k):$.split(I,k)):[]}var u1=Ki(function($,I,k){return $+(k?" ":"")+Ol(I)});function f1($,I,k){return $=dr($),k=k==null?0:$i(Ht(k),0,$.length),I=Lr(I),$.slice(k,k+I.length)==I}function l1($,I,k){var oe=$e.templateSettings;k&&Fr($,I,k)&&(I=h),$=dr($),I=Mu({},I,oe,wo);var ye=Mu({},I.imports,oe.imports,wo),Te=qr(ye),Be=ca(ye,Te),Le,Ve,Qe=0,et=I.interpolate||Br,rt="__p += '",ot=fa((I.escape||Br).source+"|"+et.source+"|"+(et===Jt?Qt:Br).source+"|"+(I.evaluate||Br).source+"|$","g"),mt="//# sourceURL="+(cr.call(I,"sourceURL")?(I.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++nf+"]")+`
59
+ `;$.replace(ot,function(Pt,jt,er,$n,rn,xn){return er||(er=$n),rt+=$.slice(Qe,xn).replace(Kr,Nc),jt&&(Le=!0,rt+=`' +
60
+ __e(`+jt+`) +
61
+ '`),rn&&(Ve=!0,rt+=`';
62
+ `+rn+`;
63
+ __p += '`),er&&(rt+=`' +
64
+ ((__t = (`+er+`)) == null ? '' : __t) +
65
+ '`),Qe=xn+Pt.length,Pt}),rt+=`';
66
+ `;var Ct=cr.call(I,"variable")&&I.variable;if(!Ct)rt=`with (obj) {
67
+ `+rt+`
68
+ }
69
+ `;else if(gt.test(Ct))throw new Mt(E);rt=(Ve?rt.replace(Gt,""):rt).replace(At,"$1").replace(tr,"$1;"),rt="function("+(Ct||"obj")+`) {
70
+ `+(Ct?"":`obj || (obj = {});
71
+ `)+"var __t, __p = ''"+(Le?", __e = _.escape":"")+(Ve?`, __j = Array.prototype.join;
72
+ function print() { __p += __j.call(arguments, '') }
73
+ `:`;
74
+ `)+rt+`return __p
75
+ }`;var Kt=qd(function(){return nr(Te,mt+"return "+rt).apply(h,Be)});if(Kt.source=rt,Cl(Kt))throw Kt;return Kt}function d1($){return dr($).toLowerCase()}function h1($){return dr($).toUpperCase()}function p1($,I,k){if($=dr($),$&&(k||I===h))return Oc($);if(!$||!(I=Lr(I)))return $;var oe=gn($),ye=gn(I),Te=Dc(oe,ye),Be=Bc(oe,ye)+1;return Wn(oe,Te,Be).join("")}function g1($,I,k){if($=dr($),$&&(k||I===h))return $.slice(0,Fc($)+1);if(!$||!(I=Lr(I)))return $;var oe=gn($),ye=Bc(oe,gn(I))+1;return Wn(oe,0,ye).join("")}function m1($,I,k){if($=dr($),$&&(k||I===h))return $.replace(Ke,"");if(!$||!(I=Lr(I)))return $;var oe=gn($),ye=Dc(oe,gn(I));return Wn(oe,ye).join("")}function y1($,I){var k=De,oe=be;if($r(I)){var ye="separator"in I?I.separator:ye;k="length"in I?Ht(I.length):k,oe="omission"in I?Lr(I.omission):oe}$=dr($);var Te=$.length;if(bi($)){var Be=gn($);Te=Be.length}if(k>=Te)return $;var Le=k-Di(oe);if(Le<1)return oe;var Ve=Be?Wn(Be,0,Le).join(""):$.slice(0,Le);if(ye===h)return Ve+oe;if(Be&&(Le+=Ve.length-Le),Pl(ye)){if($.slice(Le).search(ye)){var Qe,et=Ve;for(ye.global||(ye=fa(ye.source,dr(rr.exec(ye))+"g")),ye.lastIndex=0;Qe=ye.exec(et);)var rt=Qe.index;Ve=Ve.slice(0,rt===h?Le:rt)}}else if($.indexOf(Lr(ye),Le)!=Le){var ot=Ve.lastIndexOf(ye);ot>-1&&(Ve=Ve.slice(0,ot))}return Ve+oe}function b1($){return $=dr($),$&&Bt.test($)?$.replace(Xt,_f):$}var v1=Ki(function($,I,k){return $+(k?" ":"")+I.toUpperCase()}),Ol=wu("toUpperCase");function Ud($,I,k){return $=dr($),I=k?h:I,I===h?mf($)?$f($):df($):$.match(I)||[]}var qd=Dt(function($,I){try{return Qr($,h,I)}catch(k){return Cl(k)?k:new Mt(k)}}),w1=_n(function($,I){return on(I,function(k){k=di(k),Rn($,k,Tl($[k],$))}),$});function E1($){var I=$==null?0:$.length,k=St();return $=I?wr($,function(oe){if(typeof oe[1]!="function")throw new an(_);return[k(oe[0]),oe[1]]}):[],Dt(function(oe){for(var ye=-1;++ye<I;){var Te=$[ye];if(Qr(Te[0],this,oe))return Qr(Te[1],this,oe)}})}function S1($){return ul(un($,C))}function Dl($){return function(){return $}}function $1($,I){return $==null||$!==$?I:$}var x1=Eu(),A1=Eu(!0);function dn($){return $}function Bl($){return vs(typeof $=="function"?$:un($,C))}function T1($){return fu(un($,C))}function I1($,I){return lu($,un(I,C))}var C1=Dt(function($,I){return function(k){return gs(k,$,I)}}),P1=Dt(function($,I){return function(k){return gs($,k,I)}});function kl($,I,k){var oe=qr(I),ye=ps(I,oe);k==null&&!($r(I)&&(ye.length||!oe.length))&&(k=I,I=$,$=this,ye=ps(I,qr(I)));var Te=!($r(k)&&"chain"in k)||!!k.chain,Be=Ii($);return on(ye,function(Le){var Ve=I[Le];$[Le]=Ve,Be&&($.prototype[Le]=function(){var Qe=this.__chain__;if(Te||Qe){var et=$(this.__wrapped__),rt=et.__actions__=Je(this.__actions__);return rt.push({func:Ve,args:arguments,thisArg:$}),et.__chain__=Qe,et}return Ve.apply($,ei([this.value()],arguments))})}),$}function R1(){return xr._===this&&(xr._=Cf),this}function Nl(){}function M1($){return $=Ht($),Dt(function(I){return du(I,$)})}var O1=Ma(wr),D1=Ma(ra),B1=Ma(Vs);function Hd($){return Os($)?sa(di($)):pu($)}function k1($){return function(I){return $==null?h:oi($,I)}}var L1=Su(),F1=Su(!0);function Ll(){return[]}function Fl(){return!1}function U1(){return{}}function q1(){return""}function H1(){return!0}function K1($,I){if($=Ht($),$<1||$>ne)return[];var k=re,oe=Nr($,re);I=St(I),$-=re;for(var ye=aa(oe,I);++k<$;)I(k);return ye}function V1($){return kt($)?wr($,di):Sn($)?[$]:Je(cd(dr($)))}function Z1($){var I=++Tf;return dr($)+I}var z1=yo(function($,I){return $+I},0),W1=Ai("ceil"),G1=yo(function($,I){return $/I},1),j1=Ai("floor");function X1($){return $&&$.length?zn($,dn,ma):h}function Y1($,I){return $&&$.length?zn($,St(I,2),ma):h}function J1($){return Pc($,dn)}function Q1($,I){return Pc($,St(I,2))}function em($){return $&&$.length?zn($,dn,_a):h}function tm($,I){return $&&$.length?zn($,St(I,2),_a):h}var rm=yo(function($,I){return $*I},1),nm=Ai("round"),im=yo(function($,I){return $-I},0);function sm($){return $&&$.length?oa($,dn):0}function om($,I){return $&&$.length?oa($,St(I,2)):0}return $e.after=A0,$e.ary=vd,$e.assign=hg,$e.assignIn=Od,$e.assignInWith=Mu,$e.assignWith=pg,$e.at=gg,$e.before=wd,$e.bind=Tl,$e.bindAll=w1,$e.bindKey=_d,$e.castArray=L0,$e.chain=md,$e.chunk=Zh,$e.compact=zh,$e.concat=Wh,$e.cond=E1,$e.conforms=S1,$e.constant=Dl,$e.countBy=n0,$e.create=mg,$e.curry=Ed,$e.curryRight=Sd,$e.debounce=$d,$e.defaults=yg,$e.defaultsDeep=bg,$e.defer=T0,$e.delay=I0,$e.difference=Gh,$e.differenceBy=jh,$e.differenceWith=Xh,$e.drop=Yh,$e.dropRight=Jh,$e.dropRightWhile=Qh,$e.dropWhile=ep,$e.fill=tp,$e.filter=s0,$e.flatMap=c0,$e.flatMapDeep=u0,$e.flatMapDepth=f0,$e.flatten=dd,$e.flattenDeep=rp,$e.flattenDepth=np,$e.flip=C0,$e.flow=x1,$e.flowRight=A1,$e.fromPairs=ip,$e.functions=xg,$e.functionsIn=Ag,$e.groupBy=l0,$e.initial=op,$e.intersection=ap,$e.intersectionBy=cp,$e.intersectionWith=up,$e.invert=Ig,$e.invertBy=Cg,$e.invokeMap=h0,$e.iteratee=Bl,$e.keyBy=p0,$e.keys=qr,$e.keysIn=ln,$e.map=Au,$e.mapKeys=Rg,$e.mapValues=Mg,$e.matches=T1,$e.matchesProperty=I1,$e.memoize=Iu,$e.merge=Og,$e.mergeWith=Dd,$e.method=C1,$e.methodOf=P1,$e.mixin=kl,$e.negate=Cu,$e.nthArg=M1,$e.omit=Dg,$e.omitBy=Bg,$e.once=P0,$e.orderBy=g0,$e.over=O1,$e.overArgs=R0,$e.overEvery=D1,$e.overSome=B1,$e.partial=Il,$e.partialRight=xd,$e.partition=m0,$e.pick=kg,$e.pickBy=Bd,$e.property=Hd,$e.propertyOf=k1,$e.pull=hp,$e.pullAll=pd,$e.pullAllBy=pp,$e.pullAllWith=gp,$e.pullAt=mp,$e.range=L1,$e.rangeRight=F1,$e.rearg=M0,$e.reject=v0,$e.remove=yp,$e.rest=O0,$e.reverse=xl,$e.sampleSize=_0,$e.set=Lg,$e.setWith=Fg,$e.shuffle=E0,$e.slice=bp,$e.sortBy=x0,$e.sortedUniq=xp,$e.sortedUniqBy=Ap,$e.split=c1,$e.spread=D0,$e.tail=Tp,$e.take=Ip,$e.takeRight=Cp,$e.takeRightWhile=Pp,$e.takeWhile=Rp,$e.tap=Gp,$e.throttle=B0,$e.thru=xu,$e.toArray=Pd,$e.toPairs=kd,$e.toPairsIn=Nd,$e.toPath=V1,$e.toPlainObject=Md,$e.transform=Ug,$e.unary=k0,$e.union=Mp,$e.unionBy=Dp,$e.unionWith=Bp,$e.uniq=kp,$e.uniqBy=Np,$e.uniqWith=Lp,$e.unset=qg,$e.unzip=Al,$e.unzipWith=gd,$e.update=Hg,$e.updateWith=Kg,$e.values=Mo,$e.valuesIn=Vg,$e.without=Up,$e.words=Ud,$e.wrap=N0,$e.xor=qp,$e.xorBy=Hp,$e.xorWith=Kp,$e.zip=Vp,$e.zipObject=Zp,$e.zipObjectDeep=zp,$e.zipWith=Wp,$e.entries=kd,$e.entriesIn=Nd,$e.extend=Od,$e.extendWith=Mu,kl($e,$e),$e.add=z1,$e.attempt=qd,$e.camelCase=Gg,$e.capitalize=Ld,$e.ceil=W1,$e.clamp=Zg,$e.clone=F0,$e.cloneDeep=q0,$e.cloneDeepWith=H0,$e.cloneWith=U0,$e.conformsTo=K0,$e.deburr=Fd,$e.defaultTo=$1,$e.divide=G1,$e.endsWith=jg,$e.eq=Xn,$e.escape=Xg,$e.escapeRegExp=Yg,$e.every=i0,$e.find=o0,$e.findIndex=fd,$e.findKey=vg,$e.findLast=a0,$e.findLastIndex=ld,$e.findLastKey=wg,$e.floor=j1,$e.forEach=yd,$e.forEachRight=bd,$e.forIn=_g,$e.forInRight=Eg,$e.forOwn=Sg,$e.forOwnRight=$g,$e.get=Rl,$e.gt=V0,$e.gte=Z0,$e.has=Tg,$e.hasIn=Ml,$e.head=hd,$e.identity=dn,$e.includes=d0,$e.indexOf=sp,$e.inRange=zg,$e.invoke=Pg,$e.isArguments=Ns,$e.isArray=kt,$e.isArrayBuffer=z0,$e.isArrayLike=fn,$e.isArrayLikeObject=Pr,$e.isBoolean=W0,$e.isBuffer=Gi,$e.isDate=G0,$e.isElement=j0,$e.isEmpty=X0,$e.isEqual=Y0,$e.isEqualWith=J0,$e.isError=Cl,$e.isFinite=Q0,$e.isFunction=Ii,$e.isInteger=Ad,$e.isLength=Pu,$e.isMap=Td,$e.isMatch=eg,$e.isMatchWith=tg,$e.isNaN=rg,$e.isNative=ng,$e.isNil=sg,$e.isNull=ig,$e.isNumber=Id,$e.isObject=$r,$e.isObjectLike=Tr,$e.isPlainObject=Qa,$e.isRegExp=Pl,$e.isSafeInteger=og,$e.isSet=Cd,$e.isString=Ru,$e.isSymbol=Sn,$e.isTypedArray=Ro,$e.isUndefined=ag,$e.isWeakMap=cg,$e.isWeakSet=ug,$e.join=fp,$e.kebabCase=Jg,$e.last=Dn,$e.lastIndexOf=lp,$e.lowerCase=Qg,$e.lowerFirst=e1,$e.lt=fg,$e.lte=lg,$e.max=X1,$e.maxBy=Y1,$e.mean=J1,$e.meanBy=Q1,$e.min=em,$e.minBy=tm,$e.stubArray=Ll,$e.stubFalse=Fl,$e.stubObject=U1,$e.stubString=q1,$e.stubTrue=H1,$e.multiply=rm,$e.nth=dp,$e.noConflict=R1,$e.noop=Nl,$e.now=Tu,$e.pad=t1,$e.padEnd=r1,$e.padStart=n1,$e.parseInt=i1,$e.random=Wg,$e.reduce=y0,$e.reduceRight=b0,$e.repeat=s1,$e.replace=o1,$e.result=Ng,$e.round=nm,$e.runInContext=He,$e.sample=w0,$e.size=S0,$e.snakeCase=a1,$e.some=$0,$e.sortedIndex=vp,$e.sortedIndexBy=wp,$e.sortedIndexOf=_p,$e.sortedLastIndex=Ep,$e.sortedLastIndexBy=Sp,$e.sortedLastIndexOf=$p,$e.startCase=u1,$e.startsWith=f1,$e.subtract=im,$e.sum=sm,$e.sumBy=om,$e.template=l1,$e.times=K1,$e.toFinite=Ci,$e.toInteger=Ht,$e.toLength=Rd,$e.toLower=d1,$e.toNumber=Bn,$e.toSafeInteger=dg,$e.toString=dr,$e.toUpper=h1,$e.trim=p1,$e.trimEnd=g1,$e.trimStart=m1,$e.truncate=y1,$e.unescape=b1,$e.uniqueId=Z1,$e.upperCase=v1,$e.upperFirst=Ol,$e.each=yd,$e.eachRight=bd,$e.first=hd,kl($e,function(){var $={};return yn($e,function(I,k){cr.call($e.prototype,k)||($[k]=I)}),$}(),{chain:!1}),$e.VERSION=b,on(["bind","bindKey","curry","curryRight","partial","partialRight"],function($){$e[$].placeholder=$e}),on(["drop","take"],function($,I){Zt.prototype[$]=function(k){k=k===h?1:Ir(Ht(k),0);var oe=this.__filtered__&&!I?new Zt(this):this.clone();return oe.__filtered__?oe.__takeCount__=Nr(k,oe.__takeCount__):oe.__views__.push({size:Nr(k,re),type:$+(oe.__dir__<0?"Right":"")}),oe},Zt.prototype[$+"Right"]=function(k){return this.reverse()[$](k).reverse()}}),on(["filter","map","takeWhile"],function($,I){var k=I+1,oe=k==M||k==Q;Zt.prototype[$]=function(ye){var Te=this.clone();return Te.__iteratees__.push({iteratee:St(ye,3),type:k}),Te.__filtered__=Te.__filtered__||oe,Te}}),on(["head","last"],function($,I){var k="take"+(I?"Right":"");Zt.prototype[$]=function(){return this[k](1).value()[0]}}),on(["initial","tail"],function($,I){var k="drop"+(I?"":"Right");Zt.prototype[$]=function(){return this.__filtered__?new Zt(this):this[k](1)}}),Zt.prototype.compact=function(){return this.filter(dn)},Zt.prototype.find=function($){return this.filter($).head()},Zt.prototype.findLast=function($){return this.reverse().find($)},Zt.prototype.invokeMap=Dt(function($,I){return typeof $=="function"?new Zt(this):this.map(function(k){return gs(k,$,I)})}),Zt.prototype.reject=function($){return this.filter(Cu(St($)))},Zt.prototype.slice=function($,I){$=Ht($);var k=this;return k.__filtered__&&($>0||I<0)?new Zt(k):($<0?k=k.takeRight(-$):$&&(k=k.drop($)),I!==h&&(I=Ht(I),k=I<0?k.dropRight(-I):k.take(I-$)),k)},Zt.prototype.takeRightWhile=function($){return this.reverse().takeWhile($).reverse()},Zt.prototype.toArray=function(){return this.take(re)},yn(Zt.prototype,function($,I){var k=/^(?:filter|find|map|reject)|While$/.test(I),oe=/^(?:head|last)$/.test(I),ye=$e[oe?"take"+(I=="last"?"Right":""):I],Te=oe||/^find/.test(I);ye&&($e.prototype[I]=function(){var Be=this.__wrapped__,Le=oe?[1]:arguments,Ve=Be instanceof Zt,Qe=Le[0],et=Ve||kt(Be),rt=function(jt){var er=ye.apply($e,ei([jt],Le));return oe&&ot?er[0]:er};et&&k&&typeof Qe=="function"&&Qe.length!=1&&(Ve=et=!1);var ot=this.__chain__,mt=!!this.__actions__.length,Ct=Te&&!ot,Kt=Ve&&!mt;if(!Te&&et){Be=Kt?Be:new Zt(this);var Pt=$.apply(Be,Le);return Pt.__actions__.push({func:xu,args:[rt],thisArg:h}),new cn(Pt,ot)}return Ct&&Kt?$.apply(this,Le):(Pt=this.thru(rt),Ct?oe?Pt.value()[0]:Pt.value():Pt)})}),on(["pop","push","shift","sort","splice","unshift"],function($){var I=Gs[$],k=/^(?:push|sort|unshift)$/.test($)?"tap":"thru",oe=/^(?:pop|shift)$/.test($);$e.prototype[$]=function(){var ye=arguments;if(oe&&!this.__chain__){var Te=this.value();return I.apply(kt(Te)?Te:[],ye)}return this[k](function(Be){return I.apply(kt(Be)?Be:[],ye)})}}),yn(Zt.prototype,function($,I){var k=$e[I];if(k){var oe=k.name+"";cr.call(Ni,oe)||(Ni[oe]=[]),Ni[oe].push({name:I,func:k})}}),Ni[ui(h,ie).name]=[{name:"wrapper",func:h}],Zt.prototype.clone=Hf,Zt.prototype.reverse=Kf,Zt.prototype.value=Vf,$e.prototype.at=jp,$e.prototype.chain=Xp,$e.prototype.commit=Yp,$e.prototype.next=Jp,$e.prototype.plant=e0,$e.prototype.reverse=t0,$e.prototype.toJSON=$e.prototype.valueOf=$e.prototype.value=r0,$e.prototype.first=$e.prototype.head,os&&($e.prototype[os]=Qp),$e},Zr=xf();Qn?((Qn.exports=Zr)._=Zr,Ks._=Zr):xr._=Zr}).call(commonjsGlobal)})(lodash,lodash.exports);lodash.exports;new Logger$1("sds:message");new Logger$1("sds:message-channel");new Logger$1("sdk:query-on-connect");var QueryOnConnectEvent;(function(y){y.MessagesRetrieved="messages:retrieved"})(QueryOnConnectEvent||(QueryOnConnectEvent={}));new Logger$1("sdk:missing-message-retriever");new Logger$1("sdk:reliable-channel");LightPushError.ENCODE_FAILED,LightPushError.EMPTY_PAYLOAD,LightPushError.SIZE_TOO_BIG,LightPushError.RLN_PROOF_GENERATION;const EVENTS={LOADING_INIT:"loadingInit",LOADING_PREVIOUS_MESSAGES:"loadingPreviousMessages",MESSAGE_RECEIVED:"messageReceived",MESSAGE_REQUEST_INITIATED:"messageRequestInitiated",MESSAGE_REQUEST_UPLOADED:"messageRequestUploaded",MESSAGE_REQUEST_ERROR:"messageRequestError",CRITICAL_ERROR:"criticalError"},WAKU_CLUSTER_ID=1;function assertPath(y){if(typeof y!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(y))}function normalizeStringPosix(y,u){for(var h="",b=0,v=-1,w=0,_,E=0;E<=y.length;++E){if(E<y.length)_=y.charCodeAt(E);else{if(_===47)break;_=47}if(_===47){if(!(v===E-1||w===1))if(v!==E-1&&w===2){if(h.length<2||b!==2||h.charCodeAt(h.length-1)!==46||h.charCodeAt(h.length-2)!==46){if(h.length>2){var S=h.lastIndexOf("/");if(S!==h.length-1){S===-1?(h="",b=0):(h=h.slice(0,S),b=h.length-1-h.lastIndexOf("/")),v=E,w=0;continue}}else if(h.length===2||h.length===1){h="",b=0,v=E,w=0;continue}}u&&(h.length>0?h+="/..":h="..",b=2)}else h.length>0?h+="/"+y.slice(v+1,E):h=y.slice(v+1,E),b=E-v-1;v=E,w=0}else _===46&&w!==-1?++w:w=-1}return h}function _format(y,u){var h=u.dir||u.root,b=u.base||(u.name||"")+(u.ext||"");return h?h===u.root?h+b:h+y+b:b}var posix={resolve:function y(){for(var u="",h=!1,b,v=arguments.length-1;v>=-1&&!h;v--){var w;v>=0?w=arguments[v]:(b===void 0&&(b=process$1.cwd()),w=b),assertPath(w),w.length!==0&&(u=w+"/"+u,h=w.charCodeAt(0)===47)}return u=normalizeStringPosix(u,!h),h?u.length>0?"/"+u:"/":u.length>0?u:"."},normalize:function y(u){if(assertPath(u),u.length===0)return".";var h=u.charCodeAt(0)===47,b=u.charCodeAt(u.length-1)===47;return u=normalizeStringPosix(u,!h),u.length===0&&!h&&(u="."),u.length>0&&b&&(u+="/"),h?"/"+u:u},isAbsolute:function y(u){return assertPath(u),u.length>0&&u.charCodeAt(0)===47},join:function y(){if(arguments.length===0)return".";for(var u,h=0;h<arguments.length;++h){var b=arguments[h];assertPath(b),b.length>0&&(u===void 0?u=b:u+="/"+b)}return u===void 0?".":posix.normalize(u)},relative:function y(u,h){if(assertPath(u),assertPath(h),u===h||(u=posix.resolve(u),h=posix.resolve(h),u===h))return"";for(var b=1;b<u.length&&u.charCodeAt(b)===47;++b);for(var v=u.length,w=v-b,_=1;_<h.length&&h.charCodeAt(_)===47;++_);for(var E=h.length,S=E-_,x=w<S?w:S,T=-1,C=0;C<=x;++C){if(C===x){if(S>x){if(h.charCodeAt(_+C)===47)return h.slice(_+C+1);if(C===0)return h.slice(_+C)}else w>x&&(u.charCodeAt(b+C)===47?T=C:C===0&&(T=0));break}var O=u.charCodeAt(b+C),D=h.charCodeAt(_+C);if(O!==D)break;O===47&&(T=C)}var U="";for(C=b+T+1;C<=v;++C)(C===v||u.charCodeAt(C)===47)&&(U.length===0?U+="..":U+="/..");return U.length>0?U+h.slice(_+T):(_+=T,h.charCodeAt(_)===47&&++_,h.slice(_))},_makeLong:function y(u){return u},dirname:function y(u){if(assertPath(u),u.length===0)return".";for(var h=u.charCodeAt(0),b=h===47,v=-1,w=!0,_=u.length-1;_>=1;--_)if(h=u.charCodeAt(_),h===47){if(!w){v=_;break}}else w=!1;return v===-1?b?"/":".":b&&v===1?"//":u.slice(0,v)},basename:function y(u,h){if(h!==void 0&&typeof h!="string")throw new TypeError('"ext" argument must be a string');assertPath(u);var b=0,v=-1,w=!0,_;if(h!==void 0&&h.length>0&&h.length<=u.length){if(h.length===u.length&&h===u)return"";var E=h.length-1,S=-1;for(_=u.length-1;_>=0;--_){var x=u.charCodeAt(_);if(x===47){if(!w){b=_+1;break}}else S===-1&&(w=!1,S=_+1),E>=0&&(x===h.charCodeAt(E)?--E===-1&&(v=_):(E=-1,v=S))}return b===v?v=S:v===-1&&(v=u.length),u.slice(b,v)}else{for(_=u.length-1;_>=0;--_)if(u.charCodeAt(_)===47){if(!w){b=_+1;break}}else v===-1&&(w=!1,v=_+1);return v===-1?"":u.slice(b,v)}},extname:function y(u){assertPath(u);for(var h=-1,b=0,v=-1,w=!0,_=0,E=u.length-1;E>=0;--E){var S=u.charCodeAt(E);if(S===47){if(!w){b=E+1;break}continue}v===-1&&(w=!1,v=E+1),S===46?h===-1?h=E:_!==1&&(_=1):h!==-1&&(_=-1)}return h===-1||v===-1||_===0||_===1&&h===v-1&&h===b+1?"":u.slice(h,v)},format:function y(u){if(u===null||typeof u!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof u);return _format("/",u)},parse:function y(u){assertPath(u);var h={root:"",dir:"",base:"",ext:"",name:""};if(u.length===0)return h;var b=u.charCodeAt(0),v=b===47,w;v?(h.root="/",w=1):w=0;for(var _=-1,E=0,S=-1,x=!0,T=u.length-1,C=0;T>=w;--T){if(b=u.charCodeAt(T),b===47){if(!x){E=T+1;break}continue}S===-1&&(x=!1,S=T+1),b===46?_===-1?_=T:C!==1&&(C=1):_!==-1&&(C=-1)}return _===-1||S===-1||C===0||C===1&&_===S-1&&_===E+1?S!==-1&&(E===0&&v?h.base=h.name=u.slice(1,S):h.base=h.name=u.slice(E,S)):(E===0&&v?(h.name=u.slice(1,_),h.base=u.slice(1,S)):(h.name=u.slice(E,_),h.base=u.slice(E,S)),h.ext=u.slice(_,S)),E>0?h.dir=u.slice(0,E-1):v&&(h.dir="/"),h},sep:"/",delimiter:":",win32:null,posix:null};posix.posix=posix;var pathBrowserify=posix;const path$1=getDefaultExportFromCjs$1(pathBrowserify);var src={exports:{}},indexLight={exports:{}},indexMinimal={},minimal={},aspromise=asPromise$1;function asPromise$1(y,u){for(var h=new Array(arguments.length-1),b=0,v=2,w=!0;v<arguments.length;)h[b++]=arguments[v++];return new Promise(function(E,S){h[b]=function(T){if(w)if(w=!1,T)S(T);else{for(var C=new Array(arguments.length-1),O=0;O<C.length;)C[O++]=arguments[O];E.apply(null,C)}};try{y.apply(u||null,h)}catch(x){w&&(w=!1,S(x))}})}var base64$1={};(function(y){var u=y;u.length=function(E){var S=E.length;if(!S)return 0;for(var x=0;--S%4>1&&E.charAt(S)==="=";)++x;return Math.ceil(E.length*3)/4-x};for(var h=new Array(64),b=new Array(123),v=0;v<64;)b[h[v]=v<26?v+65:v<52?v+71:v<62?v-4:v-59|43]=v++;u.encode=function(E,S,x){for(var T=null,C=[],O=0,D=0,U;S<x;){var te=E[S++];switch(D){case 0:C[O++]=h[te>>2],U=(te&3)<<4,D=1;break;case 1:C[O++]=h[U|te>>4],U=(te&15)<<2,D=2;break;case 2:C[O++]=h[U|te>>6],C[O++]=h[te&63],D=0;break}O>8191&&((T||(T=[])).push(String.fromCharCode.apply(String,C)),O=0)}return D&&(C[O++]=h[U],C[O++]=61,D===1&&(C[O++]=61)),T?(O&&T.push(String.fromCharCode.apply(String,C.slice(0,O))),T.join("")):String.fromCharCode.apply(String,C.slice(0,O))};var w="invalid encoding";u.decode=function(E,S,x){for(var T=x,C=0,O,D=0;D<E.length;){var U=E.charCodeAt(D++);if(U===61&&C>1)break;if((U=b[U])===void 0)throw Error(w);switch(C){case 0:O=U,C=1;break;case 1:S[x++]=O<<2|(U&48)>>4,O=U,C=2;break;case 2:S[x++]=(O&15)<<4|(U&60)>>2,O=U,C=3;break;case 3:S[x++]=(O&3)<<6|U,C=0;break}}if(C===1)throw Error(w);return x-T},u.test=function(E){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(E)}})(base64$1);var eventemitter=EventEmitter;function EventEmitter(){this._listeners={}}EventEmitter.prototype.on=function y(u,h,b){return(this._listeners[u]||(this._listeners[u]=[])).push({fn:h,ctx:b||this}),this};EventEmitter.prototype.off=function y(u,h){if(u===void 0)this._listeners={};else if(h===void 0)this._listeners[u]=[];else for(var b=this._listeners[u],v=0;v<b.length;)b[v].fn===h?b.splice(v,1):++v;return this};EventEmitter.prototype.emit=function y(u){var h=this._listeners[u];if(h){for(var b=[],v=1;v<arguments.length;)b.push(arguments[v++]);for(v=0;v<h.length;)h[v].fn.apply(h[v++].ctx,b)}return this};var float=factory(factory);function factory(y){return typeof Float32Array<"u"?function(){var u=new Float32Array([-0]),h=new Uint8Array(u.buffer),b=h[3]===128;function v(S,x,T){u[0]=S,x[T]=h[0],x[T+1]=h[1],x[T+2]=h[2],x[T+3]=h[3]}function w(S,x,T){u[0]=S,x[T]=h[3],x[T+1]=h[2],x[T+2]=h[1],x[T+3]=h[0]}y.writeFloatLE=b?v:w,y.writeFloatBE=b?w:v;function _(S,x){return h[0]=S[x],h[1]=S[x+1],h[2]=S[x+2],h[3]=S[x+3],u[0]}function E(S,x){return h[3]=S[x],h[2]=S[x+1],h[1]=S[x+2],h[0]=S[x+3],u[0]}y.readFloatLE=b?_:E,y.readFloatBE=b?E:_}():function(){function u(b,v,w,_){var E=v<0?1:0;if(E&&(v=-v),v===0)b(1/v>0?0:2147483648,w,_);else if(isNaN(v))b(2143289344,w,_);else if(v>34028234663852886e22)b((E<<31|2139095040)>>>0,w,_);else if(v<11754943508222875e-54)b((E<<31|Math.round(v/1401298464324817e-60))>>>0,w,_);else{var S=Math.floor(Math.log(v)/Math.LN2),x=Math.round(v*Math.pow(2,-S)*8388608)&8388607;b((E<<31|S+127<<23|x)>>>0,w,_)}}y.writeFloatLE=u.bind(null,writeUintLE),y.writeFloatBE=u.bind(null,writeUintBE);function h(b,v,w){var _=b(v,w),E=(_>>31)*2+1,S=_>>>23&255,x=_&8388607;return S===255?x?NaN:E*(1/0):S===0?E*1401298464324817e-60*x:E*Math.pow(2,S-150)*(x+8388608)}y.readFloatLE=h.bind(null,readUintLE),y.readFloatBE=h.bind(null,readUintBE)}(),typeof Float64Array<"u"?function(){var u=new Float64Array([-0]),h=new Uint8Array(u.buffer),b=h[7]===128;function v(S,x,T){u[0]=S,x[T]=h[0],x[T+1]=h[1],x[T+2]=h[2],x[T+3]=h[3],x[T+4]=h[4],x[T+5]=h[5],x[T+6]=h[6],x[T+7]=h[7]}function w(S,x,T){u[0]=S,x[T]=h[7],x[T+1]=h[6],x[T+2]=h[5],x[T+3]=h[4],x[T+4]=h[3],x[T+5]=h[2],x[T+6]=h[1],x[T+7]=h[0]}y.writeDoubleLE=b?v:w,y.writeDoubleBE=b?w:v;function _(S,x){return h[0]=S[x],h[1]=S[x+1],h[2]=S[x+2],h[3]=S[x+3],h[4]=S[x+4],h[5]=S[x+5],h[6]=S[x+6],h[7]=S[x+7],u[0]}function E(S,x){return h[7]=S[x],h[6]=S[x+1],h[5]=S[x+2],h[4]=S[x+3],h[3]=S[x+4],h[2]=S[x+5],h[1]=S[x+6],h[0]=S[x+7],u[0]}y.readDoubleLE=b?_:E,y.readDoubleBE=b?E:_}():function(){function u(b,v,w,_,E,S){var x=_<0?1:0;if(x&&(_=-_),_===0)b(0,E,S+v),b(1/_>0?0:2147483648,E,S+w);else if(isNaN(_))b(0,E,S+v),b(2146959360,E,S+w);else if(_>17976931348623157e292)b(0,E,S+v),b((x<<31|2146435072)>>>0,E,S+w);else{var T;if(_<22250738585072014e-324)T=_/5e-324,b(T>>>0,E,S+v),b((x<<31|T/4294967296)>>>0,E,S+w);else{var C=Math.floor(Math.log(_)/Math.LN2);C===1024&&(C=1023),T=_*Math.pow(2,-C),b(T*4503599627370496>>>0,E,S+v),b((x<<31|C+1023<<20|T*1048576&1048575)>>>0,E,S+w)}}}y.writeDoubleLE=u.bind(null,writeUintLE,0,4),y.writeDoubleBE=u.bind(null,writeUintBE,4,0);function h(b,v,w,_,E){var S=b(_,E+v),x=b(_,E+w),T=(x>>31)*2+1,C=x>>>20&2047,O=4294967296*(x&1048575)+S;return C===2047?O?NaN:T*(1/0):C===0?T*5e-324*O:T*Math.pow(2,C-1075)*(O+4503599627370496)}y.readDoubleLE=h.bind(null,readUintLE,0,4),y.readDoubleBE=h.bind(null,readUintBE,4,0)}(),y}function writeUintLE(y,u,h){u[h]=y&255,u[h+1]=y>>>8&255,u[h+2]=y>>>16&255,u[h+3]=y>>>24}function writeUintBE(y,u,h){u[h]=y>>>24,u[h+1]=y>>>16&255,u[h+2]=y>>>8&255,u[h+3]=y&255}function readUintLE(y,u){return(y[u]|y[u+1]<<8|y[u+2]<<16|y[u+3]<<24)>>>0}function readUintBE(y,u){return(y[u]<<24|y[u+1]<<16|y[u+2]<<8|y[u+3])>>>0}var inquire_1=inquire$1;function inquire$1(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(y){}return null}var utf8$2={};(function(y){var u=y;u.length=function(b){for(var v=0,w=0,_=0;_<b.length;++_)w=b.charCodeAt(_),w<128?v+=1:w<2048?v+=2:(w&64512)===55296&&(b.charCodeAt(_+1)&64512)===56320?(++_,v+=4):v+=3;return v},u.read=function(b,v,w){var _=w-v;if(_<1)return"";for(var E=null,S=[],x=0,T;v<w;)T=b[v++],T<128?S[x++]=T:T>191&&T<224?S[x++]=(T&31)<<6|b[v++]&63:T>239&&T<365?(T=((T&7)<<18|(b[v++]&63)<<12|(b[v++]&63)<<6|b[v++]&63)-65536,S[x++]=55296+(T>>10),S[x++]=56320+(T&1023)):S[x++]=(T&15)<<12|(b[v++]&63)<<6|b[v++]&63,x>8191&&((E||(E=[])).push(String.fromCharCode.apply(String,S)),x=0);return E?(x&&E.push(String.fromCharCode.apply(String,S.slice(0,x))),E.join("")):String.fromCharCode.apply(String,S.slice(0,x))},u.write=function(b,v,w){for(var _=w,E,S,x=0;x<b.length;++x)E=b.charCodeAt(x),E<128?v[w++]=E:E<2048?(v[w++]=E>>6|192,v[w++]=E&63|128):(E&64512)===55296&&((S=b.charCodeAt(x+1))&64512)===56320?(E=65536+((E&1023)<<10)+(S&1023),++x,v[w++]=E>>18|240,v[w++]=E>>12&63|128,v[w++]=E>>6&63|128,v[w++]=E&63|128):(v[w++]=E>>12|224,v[w++]=E>>6&63|128,v[w++]=E&63|128);return w-_}})(utf8$2);var pool_1=pool;function pool(y,u,h){var b=h||8192,v=b>>>1,w=null,_=b;return function(S){if(S<1||S>v)return y(S);_+S>b&&(w=y(b),_=0);var x=u.call(w,_,_+=S);return _&7&&(_=(_|7)+1),x}}var longbits,hasRequiredLongbits;function requireLongbits(){if(hasRequiredLongbits)return longbits;hasRequiredLongbits=1,longbits=u;var y=requireMinimal();function u(w,_){this.lo=w>>>0,this.hi=_>>>0}var h=u.zero=new u(0,0);h.toNumber=function(){return 0},h.zzEncode=h.zzDecode=function(){return this},h.length=function(){return 1};var b=u.zeroHash="\0\0\0\0\0\0\0\0";u.fromNumber=function(_){if(_===0)return h;var E=_<0;E&&(_=-_);var S=_>>>0,x=(_-S)/4294967296>>>0;return E&&(x=~x>>>0,S=~S>>>0,++S>4294967295&&(S=0,++x>4294967295&&(x=0))),new u(S,x)},u.from=function(_){if(typeof _=="number")return u.fromNumber(_);if(y.isString(_))if(y.Long)_=y.Long.fromString(_);else return u.fromNumber(parseInt(_,10));return _.low||_.high?new u(_.low>>>0,_.high>>>0):h},u.prototype.toNumber=function(_){if(!_&&this.hi>>>31){var E=~this.lo+1>>>0,S=~this.hi>>>0;return E||(S=S+1>>>0),-(E+S*4294967296)}return this.lo+this.hi*4294967296},u.prototype.toLong=function(_){return y.Long?new y.Long(this.lo|0,this.hi|0,!!_):{low:this.lo|0,high:this.hi|0,unsigned:!!_}};var v=String.prototype.charCodeAt;return u.fromHash=function(_){return _===b?h:new u((v.call(_,0)|v.call(_,1)<<8|v.call(_,2)<<16|v.call(_,3)<<24)>>>0,(v.call(_,4)|v.call(_,5)<<8|v.call(_,6)<<16|v.call(_,7)<<24)>>>0)},u.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},u.prototype.zzEncode=function(){var _=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^_)>>>0,this.lo=(this.lo<<1^_)>>>0,this},u.prototype.zzDecode=function(){var _=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^_)>>>0,this.hi=(this.hi>>>1^_)>>>0,this},u.prototype.length=function(){var _=this.lo,E=(this.lo>>>28|this.hi<<4)>>>0,S=this.hi>>>24;return S===0?E===0?_<16384?_<128?1:2:_<2097152?3:4:E<16384?E<128?5:6:E<2097152?7:8:S<128?9:10},longbits}var hasRequiredMinimal;function requireMinimal(){return hasRequiredMinimal||(hasRequiredMinimal=1,function(y){var u=y;u.asPromise=aspromise,u.base64=base64$1,u.EventEmitter=eventemitter,u.float=float,u.inquire=inquire_1,u.utf8=utf8$2,u.pool=pool_1,u.LongBits=requireLongbits(),u.isNode=!!(typeof commonjsGlobal<"u"&&commonjsGlobal&&commonjsGlobal.process&&commonjsGlobal.process.versions&&commonjsGlobal.process.versions.node),u.global=u.isNode&&commonjsGlobal||typeof window<"u"&&window||typeof self<"u"&&self||commonjsGlobal,u.emptyArray=Object.freeze?Object.freeze([]):[],u.emptyObject=Object.freeze?Object.freeze({}):{},u.isInteger=Number.isInteger||function(w){return typeof w=="number"&&isFinite(w)&&Math.floor(w)===w},u.isString=function(w){return typeof w=="string"||w instanceof String},u.isObject=function(w){return w&&typeof w=="object"},u.isset=u.isSet=function(w,_){var E=w[_];return E!=null&&w.hasOwnProperty(_)?typeof E!="object"||(Array.isArray(E)?E.length:Object.keys(E).length)>0:!1},u.Buffer=function(){try{var v=u.inquire("buffer").Buffer;return v.prototype.utf8Write?v:null}catch{return null}}(),u._Buffer_from=null,u._Buffer_allocUnsafe=null,u.newBuffer=function(w){return typeof w=="number"?u.Buffer?u._Buffer_allocUnsafe(w):new u.Array(w):u.Buffer?u._Buffer_from(w):typeof Uint8Array>"u"?w:new Uint8Array(w)},u.Array=typeof Uint8Array<"u"?Uint8Array:Array,u.Long=u.global.dcodeIO&&u.global.dcodeIO.Long||u.global.Long||u.inquire("long"),u.key2Re=/^true|false|0|1$/,u.key32Re=/^-?(?:0|[1-9][0-9]*)$/,u.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,u.longToHash=function(w){return w?u.LongBits.from(w).toHash():u.LongBits.zeroHash},u.longFromHash=function(w,_){var E=u.LongBits.fromHash(w);return u.Long?u.Long.fromBits(E.lo,E.hi,_):E.toNumber(!!_)};function h(v,w,_){for(var E=Object.keys(w),S=0;S<E.length;++S)(v[E[S]]===void 0||!_)&&(v[E[S]]=w[E[S]]);return v}u.merge=h,u.lcFirst=function(w){return w.charAt(0).toLowerCase()+w.substring(1)};function b(v){function w(_,E){if(!(this instanceof w))return new w(_,E);Object.defineProperty(this,"message",{get:function(){return _}}),Error.captureStackTrace?Error.captureStackTrace(this,w):Object.defineProperty(this,"stack",{value:new Error().stack||""}),E&&h(this,E)}return w.prototype=Object.create(Error.prototype,{constructor:{value:w,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return v},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),w}u.newError=b,u.ProtocolError=b("ProtocolError"),u.oneOfGetter=function(w){for(var _={},E=0;E<w.length;++E)_[w[E]]=1;return function(){for(var S=Object.keys(this),x=S.length-1;x>-1;--x)if(_[S[x]]===1&&this[S[x]]!==void 0&&this[S[x]]!==null)return S[x]}},u.oneOfSetter=function(w){return function(_){for(var E=0;E<w.length;++E)w[E]!==_&&delete this[w[E]]}},u.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},u._configure=function(){var v=u.Buffer;if(!v){u._Buffer_from=u._Buffer_allocUnsafe=null;return}u._Buffer_from=v.from!==Uint8Array.from&&v.from||function(_,E){return new v(_,E)},u._Buffer_allocUnsafe=v.allocUnsafe||function(_){return new v(_)}}}(minimal)),minimal}var writer=Writer$1,util$7=requireMinimal(),BufferWriter$1,LongBits$1=util$7.LongBits,base64=util$7.base64,utf8$1=util$7.utf8;function Op(y,u,h){this.fn=y,this.len=u,this.next=void 0,this.val=h}function noop(){}function State(y){this.head=y.head,this.tail=y.tail,this.len=y.len,this.next=y.states}function Writer$1(){this.len=0,this.head=new Op(noop,0,0),this.tail=this.head,this.states=null}var create$1=function y(){return util$7.Buffer?function(){return(Writer$1.create=function(){return new BufferWriter$1})()}:function(){return new Writer$1}};Writer$1.create=create$1();Writer$1.alloc=function y(u){return new util$7.Array(u)};util$7.Array!==Array&&(Writer$1.alloc=util$7.pool(Writer$1.alloc,util$7.Array.prototype.subarray));Writer$1.prototype._push=function y(u,h,b){return this.tail=this.tail.next=new Op(u,h,b),this.len+=h,this};function writeByte(y,u,h){u[h]=y&255}function writeVarint32(y,u,h){for(;y>127;)u[h++]=y&127|128,y>>>=7;u[h]=y}function VarintOp(y,u){this.len=y,this.next=void 0,this.val=u}VarintOp.prototype=Object.create(Op.prototype);VarintOp.prototype.fn=writeVarint32;Writer$1.prototype.uint32=function y(u){return this.len+=(this.tail=this.tail.next=new VarintOp((u=u>>>0)<128?1:u<16384?2:u<2097152?3:u<268435456?4:5,u)).len,this};Writer$1.prototype.int32=function y(u){return u<0?this._push(writeVarint64,10,LongBits$1.fromNumber(u)):this.uint32(u)};Writer$1.prototype.sint32=function y(u){return this.uint32((u<<1^u>>31)>>>0)};function writeVarint64(y,u,h){for(;y.hi;)u[h++]=y.lo&127|128,y.lo=(y.lo>>>7|y.hi<<25)>>>0,y.hi>>>=7;for(;y.lo>127;)u[h++]=y.lo&127|128,y.lo=y.lo>>>7;u[h++]=y.lo}Writer$1.prototype.uint64=function y(u){var h=LongBits$1.from(u);return this._push(writeVarint64,h.length(),h)};Writer$1.prototype.int64=Writer$1.prototype.uint64;Writer$1.prototype.sint64=function y(u){var h=LongBits$1.from(u).zzEncode();return this._push(writeVarint64,h.length(),h)};Writer$1.prototype.bool=function y(u){return this._push(writeByte,1,u?1:0)};function writeFixed32(y,u,h){u[h]=y&255,u[h+1]=y>>>8&255,u[h+2]=y>>>16&255,u[h+3]=y>>>24}Writer$1.prototype.fixed32=function y(u){return this._push(writeFixed32,4,u>>>0)};Writer$1.prototype.sfixed32=Writer$1.prototype.fixed32;Writer$1.prototype.fixed64=function y(u){var h=LongBits$1.from(u);return this._push(writeFixed32,4,h.lo)._push(writeFixed32,4,h.hi)};Writer$1.prototype.sfixed64=Writer$1.prototype.fixed64;Writer$1.prototype.float=function y(u){return this._push(util$7.float.writeFloatLE,4,u)};Writer$1.prototype.double=function y(u){return this._push(util$7.float.writeDoubleLE,8,u)};var writeBytes=util$7.Array.prototype.set?function y(u,h,b){h.set(u,b)}:function y(u,h,b){for(var v=0;v<u.length;++v)h[b+v]=u[v]};Writer$1.prototype.bytes=function y(u){var h=u.length>>>0;if(!h)return this._push(writeByte,1,0);if(util$7.isString(u)){var b=Writer$1.alloc(h=base64.length(u));base64.decode(u,b,0),u=b}return this.uint32(h)._push(writeBytes,h,u)};Writer$1.prototype.string=function y(u){var h=utf8$1.length(u);return h?this.uint32(h)._push(utf8$1.write,h,u):this._push(writeByte,1,0)};Writer$1.prototype.fork=function y(){return this.states=new State(this),this.head=this.tail=new Op(noop,0,0),this.len=0,this};Writer$1.prototype.reset=function y(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op(noop,0,0),this.len=0),this};Writer$1.prototype.ldelim=function y(){var u=this.head,h=this.tail,b=this.len;return this.reset().uint32(b),b&&(this.tail.next=u.next,this.tail=h,this.len+=b),this};Writer$1.prototype.finish=function y(){for(var u=this.head.next,h=this.constructor.alloc(this.len),b=0;u;)u.fn(u.val,h,b),b+=u.len,u=u.next;return h};Writer$1._configure=function(y){BufferWriter$1=y,Writer$1.create=create$1(),BufferWriter$1._configure()};var writer_buffer=BufferWriter,Writer=writer;(BufferWriter.prototype=Object.create(Writer.prototype)).constructor=BufferWriter;var util$6=requireMinimal();function BufferWriter(){Writer.call(this)}BufferWriter._configure=function(){BufferWriter.alloc=util$6._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=util$6.Buffer&&util$6.Buffer.prototype instanceof Uint8Array&&util$6.Buffer.prototype.set.name==="set"?function(u,h,b){h.set(u,b)}:function(u,h,b){if(u.copy)u.copy(h,b,0,u.length);else for(var v=0;v<u.length;)h[b++]=u[v++]}};BufferWriter.prototype.bytes=function y(u){util$6.isString(u)&&(u=util$6._Buffer_from(u,"base64"));var h=u.length>>>0;return this.uint32(h),h&&this._push(BufferWriter.writeBytesBuffer,h,u),this};function writeStringBuffer(y,u,h){y.length<40?util$6.utf8.write(y,u,h):u.utf8Write?u.utf8Write(y,h):u.write(y,h)}BufferWriter.prototype.string=function y(u){var h=util$6.Buffer.byteLength(u);return this.uint32(h),h&&this._push(writeStringBuffer,h,u),this};BufferWriter._configure();var reader=Reader$1,util$5=requireMinimal(),BufferReader$1,LongBits=util$5.LongBits,utf8=util$5.utf8;function indexOutOfRange(y,u){return RangeError("index out of range: "+y.pos+" + "+(u||1)+" > "+y.len)}function Reader$1(y){this.buf=y,this.pos=0,this.len=y.length}var create_array=typeof Uint8Array<"u"?function y(u){if(u instanceof Uint8Array||Array.isArray(u))return new Reader$1(u);throw Error("illegal buffer")}:function y(u){if(Array.isArray(u))return new Reader$1(u);throw Error("illegal buffer")},create=function y(){return util$5.Buffer?function(h){return(Reader$1.create=function(v){return util$5.Buffer.isBuffer(v)?new BufferReader$1(v):create_array(v)})(h)}:create_array};Reader$1.create=create();Reader$1.prototype._slice=util$5.Array.prototype.subarray||util$5.Array.prototype.slice;Reader$1.prototype.uint32=function y(){var u=4294967295;return function(){if(u=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(u=(u|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(u=(u|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(u=(u|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(u=(u|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return u;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return u}}();Reader$1.prototype.int32=function y(){return this.uint32()|0};Reader$1.prototype.sint32=function y(){var u=this.uint32();return u>>>1^-(u&1)|0};function readLongVarint(){var y=new LongBits(0,0),u=0;if(this.len-this.pos>4){for(;u<4;++u)if(y.lo=(y.lo|(this.buf[this.pos]&127)<<u*7)>>>0,this.buf[this.pos++]<128)return y;if(y.lo=(y.lo|(this.buf[this.pos]&127)<<28)>>>0,y.hi=(y.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return y;u=0}else{for(;u<3;++u){if(this.pos>=this.len)throw indexOutOfRange(this);if(y.lo=(y.lo|(this.buf[this.pos]&127)<<u*7)>>>0,this.buf[this.pos++]<128)return y}return y.lo=(y.lo|(this.buf[this.pos++]&127)<<u*7)>>>0,y}if(this.len-this.pos>4){for(;u<5;++u)if(y.hi=(y.hi|(this.buf[this.pos]&127)<<u*7+3)>>>0,this.buf[this.pos++]<128)return y}else for(;u<5;++u){if(this.pos>=this.len)throw indexOutOfRange(this);if(y.hi=(y.hi|(this.buf[this.pos]&127)<<u*7+3)>>>0,this.buf[this.pos++]<128)return y}throw Error("invalid varint encoding")}Reader$1.prototype.bool=function y(){return this.uint32()!==0};function readFixed32_end(y,u){return(y[u-4]|y[u-3]<<8|y[u-2]<<16|y[u-1]<<24)>>>0}Reader$1.prototype.fixed32=function y(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)};Reader$1.prototype.sfixed32=function y(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)|0};function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.prototype.float=function y(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var u=util$5.float.readFloatLE(this.buf,this.pos);return this.pos+=4,u};Reader$1.prototype.double=function y(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var u=util$5.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,u};Reader$1.prototype.bytes=function y(){var u=this.uint32(),h=this.pos,b=this.pos+u;if(b>this.len)throw indexOutOfRange(this,u);if(this.pos+=u,Array.isArray(this.buf))return this.buf.slice(h,b);if(h===b){var v=util$5.Buffer;return v?v.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,h,b)};Reader$1.prototype.string=function y(){var u=this.bytes();return utf8.read(u,0,u.length)};Reader$1.prototype.skip=function y(u){if(typeof u=="number"){if(this.pos+u>this.len)throw indexOutOfRange(this,u);this.pos+=u}else do if(this.pos>=this.len)throw indexOutOfRange(this);while(this.buf[this.pos++]&128);return this};Reader$1.prototype.skipType=function(y){switch(y){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(y=this.uint32()&7)!==4;)this.skipType(y);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+y+" at offset "+this.pos)}return this};Reader$1._configure=function(y){BufferReader$1=y,Reader$1.create=create(),BufferReader$1._configure();var u=util$5.Long?"toLong":"toNumber";util$5.merge(Reader$1.prototype,{int64:function(){return readLongVarint.call(this)[u](!1)},uint64:function(){return readLongVarint.call(this)[u](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[u](!1)},fixed64:function(){return readFixed64.call(this)[u](!0)},sfixed64:function(){return readFixed64.call(this)[u](!1)}})};var reader_buffer=BufferReader,Reader=reader;(BufferReader.prototype=Object.create(Reader.prototype)).constructor=BufferReader;var util$4=requireMinimal();function BufferReader(y){Reader.call(this,y)}BufferReader._configure=function(){util$4.Buffer&&(BufferReader.prototype._slice=util$4.Buffer.prototype.slice)};BufferReader.prototype.string=function y(){var u=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+u,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+u,this.len))};BufferReader._configure();var rpc={},service$1=Service$1,util$3=requireMinimal();(Service$1.prototype=Object.create(util$3.EventEmitter.prototype)).constructor=Service$1;function Service$1(y,u,h){if(typeof y!="function")throw TypeError("rpcImpl must be a function");util$3.EventEmitter.call(this),this.rpcImpl=y,this.requestDelimited=!!u,this.responseDelimited=!!h}Service$1.prototype.rpcCall=function y(u,h,b,v,w){if(!v)throw TypeError("request must be specified");var _=this;if(!w)return util$3.asPromise(y,_,u,h,b,v);if(!_.rpcImpl){setTimeout(function(){w(Error("already ended"))},0);return}try{return _.rpcImpl(u,h[_.requestDelimited?"encodeDelimited":"encode"](v).finish(),function(S,x){if(S)return _.emit("error",S,u),w(S);if(x===null){_.end(!0);return}if(!(x instanceof b))try{x=b[_.responseDelimited?"decodeDelimited":"decode"](x)}catch(T){return _.emit("error",T,u),w(T)}return _.emit("data",x,u),w(null,x)})}catch(E){_.emit("error",E,u),setTimeout(function(){w(E)},0);return}};Service$1.prototype.end=function y(u){return this.rpcImpl&&(u||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this};(function(y){var u=y;u.Service=service$1})(rpc);var roots={};(function(y){var u=y;u.build="minimal",u.Writer=writer,u.BufferWriter=writer_buffer,u.Reader=reader,u.BufferReader=reader_buffer,u.util=requireMinimal(),u.rpc=rpc,u.roots=roots,u.configure=h;function h(){u.util._configure(),u.Writer._configure(u.BufferWriter),u.Reader._configure(u.BufferReader)}h()})(indexMinimal);var types$1={},util$2={exports:{}},codegen_1=codegen;function codegen(y,u){typeof y=="string"&&(u=y,y=void 0);var h=[];function b(w){if(typeof w!="string"){var _=v();if(codegen.verbose&&console.log("codegen: "+_),_="return "+_,w){for(var E=Object.keys(w),S=new Array(E.length+1),x=new Array(E.length),T=0;T<E.length;)S[T]=E[T],x[T]=w[E[T++]];return S[T]=_,Function.apply(null,S).apply(null,x)}return Function(_)()}for(var C=new Array(arguments.length-1),O=0;O<C.length;)C[O]=arguments[++O];if(O=0,w=w.replace(/%([%dfijs])/g,function(U,te){var X=C[O++];switch(te){case"d":case"f":return String(Number(X));case"i":return String(Math.floor(X));case"j":return JSON.stringify(X);case"s":return String(X)}return"%"}),O!==C.length)throw Error("parameter count mismatch");return h.push(w),b}function v(w){return"function "+(w||u||"")+"("+(y&&y.join(",")||"")+`){
76
+ `+h.join(`
77
+ `)+`
78
+ }`}return b.toString=v,b}codegen.verbose=!1;var fetch_1=fetch$1,asPromise=aspromise,inquire=inquire_1,fs=inquire("fs");function fetch$1(y,u,h){return typeof u=="function"?(h=u,u={}):u||(u={}),h?!u.xhr&&fs&&fs.readFile?fs.readFile(y,function(v,w){return v&&typeof XMLHttpRequest<"u"?fetch$1.xhr(y,u,h):v?h(v):h(null,u.binary?w:w.toString("utf8"))}):fetch$1.xhr(y,u,h):asPromise(fetch$1,this,y,u)}fetch$1.xhr=function y(u,h,b){var v=new XMLHttpRequest;v.onreadystatechange=function(){if(v.readyState===4){if(v.status!==0&&v.status!==200)return b(Error("status "+v.status));if(h.binary){var _=v.response;if(!_){_=[];for(var E=0;E<v.responseText.length;++E)_.push(v.responseText.charCodeAt(E)&255)}return b(null,typeof Uint8Array<"u"?new Uint8Array(_):_)}return b(null,v.responseText)}},h.binary&&("overrideMimeType"in v&&v.overrideMimeType("text/plain; charset=x-user-defined"),v.responseType="arraybuffer"),v.open("GET",u),v.send()};var path={};(function(y){var u=y,h=u.isAbsolute=function(w){return/^(?:\/|\w+:)/.test(w)},b=u.normalize=function(w){w=w.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var _=w.split("/"),E=h(w),S="";E&&(S=_.shift()+"/");for(var x=0;x<_.length;)_[x]===".."?x>0&&_[x-1]!==".."?_.splice(--x,2):E?_.splice(x,1):++x:_[x]==="."?_.splice(x,1):++x;return S+_.join("/")};u.resolve=function(w,_,E){return E||(_=b(_)),h(_)?_:(E||(w=b(w)),(w=w.replace(/(?:\/|^)[^/]+$/,"")).length?b(w+"/"+_):_)}})(path);var namespace,hasRequiredNamespace;function requireNamespace(){if(hasRequiredNamespace)return namespace;hasRequiredNamespace=1,namespace=S;var y=requireObject();((S.prototype=Object.create(y.prototype)).constructor=S).className="Namespace";var u=requireField(),h=requireUtil(),b=requireOneof(),v,w,_;S.fromJSON=function(C,O){return new S(C,O.options).addJSON(O.nested)};function E(T,C){if(T&&T.length){for(var O={},D=0;D<T.length;++D)O[T[D].name]=T[D].toJSON(C);return O}}S.arrayToJSON=E,S.isReservedId=function(C,O){if(C){for(var D=0;D<C.length;++D)if(typeof C[D]!="string"&&C[D][0]<=O&&C[D][1]>O)return!0}return!1},S.isReservedName=function(C,O){if(C){for(var D=0;D<C.length;++D)if(C[D]===O)return!0}return!1};function S(T,C){y.call(this,T,C),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function x(T){T._nestedArray=null,T._lookupCache={};for(var C=T;C=C.parent;)C._lookupCache={};return T}return Object.defineProperty(S.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=h.toArray(this.nested))}}),S.prototype.toJSON=function(C){return h.toObject(["options",this.options,"nested",E(this.nestedArray,C)])},S.prototype.addJSON=function(C){var O=this;if(C)for(var D=Object.keys(C),U=0,te;U<D.length;++U)te=C[D[U]],O.add((te.fields!==void 0?v.fromJSON:te.values!==void 0?_.fromJSON:te.methods!==void 0?w.fromJSON:te.id!==void 0?u.fromJSON:S.fromJSON)(D[U],te));return this},S.prototype.get=function(C){return this.nested&&this.nested[C]||null},S.prototype.getEnum=function(C){if(this.nested&&this.nested[C]instanceof _)return this.nested[C].values;throw Error("no such enum: "+C)},S.prototype.add=function(C){if(!(C instanceof u&&C.extend!==void 0||C instanceof v||C instanceof b||C instanceof _||C instanceof w||C instanceof S))throw TypeError("object must be a valid nested object");if(!this.nested)this.nested={};else{var O=this.get(C.name);if(O)if(O instanceof S&&C instanceof S&&!(O instanceof v||O instanceof w)){for(var D=O.nestedArray,U=0;U<D.length;++U)C.add(D[U]);this.remove(O),this.nested||(this.nested={}),C.setOptions(O.options,!0)}else throw Error("duplicate name '"+C.name+"' in "+this)}this.nested[C.name]=C,this instanceof v||this instanceof w||this instanceof _||this instanceof u||C._edition||(C._edition=C._defaultEdition),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;for(var te=this;te=te.parent;)te._needsRecursiveFeatureResolution=!0,te._needsRecursiveResolve=!0;return C.onAdd(this),x(this)},S.prototype.remove=function(C){if(!(C instanceof y))throw TypeError("object must be a ReflectionObject");if(C.parent!==this)throw Error(C+" is not a member of "+this);return delete this.nested[C.name],Object.keys(this.nested).length||(this.nested=void 0),C.onRemove(this),x(this)},S.prototype.define=function(C,O){if(h.isString(C))C=C.split(".");else if(!Array.isArray(C))throw TypeError("illegal path");if(C&&C.length&&C[0]==="")throw Error("path must be relative");for(var D=this;C.length>0;){var U=C.shift();if(D.nested&&D.nested[U]){if(D=D.nested[U],!(D instanceof S))throw Error("path conflicts with non-namespace objects")}else D.add(D=new S(U))}return O&&D.addJSON(O),D},S.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var C=this.nestedArray,O=0;for(this.resolve();O<C.length;)C[O]instanceof S?C[O++].resolveAll():C[O++].resolve();return this._needsRecursiveResolve=!1,this},S.prototype._resolveFeaturesRecursive=function(C){return this._needsRecursiveFeatureResolution?(this._needsRecursiveFeatureResolution=!1,C=this._edition||C,y.prototype._resolveFeaturesRecursive.call(this,C),this.nestedArray.forEach(O=>{O._resolveFeaturesRecursive(C)}),this):this},S.prototype.lookup=function(C,O,D){if(typeof O=="boolean"?(D=O,O=void 0):O&&!Array.isArray(O)&&(O=[O]),h.isString(C)&&C.length){if(C===".")return this.root;C=C.split(".")}else if(!C.length)return this;var U=C.join(".");if(C[0]==="")return this.root.lookup(C.slice(1),O);var te=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+U];if(te&&(!O||O.indexOf(te.constructor)>-1)||(te=this._lookupImpl(C,U),te&&(!O||O.indexOf(te.constructor)>-1)))return te;if(D)return null;for(var X=this;X.parent;){if(te=X.parent._lookupImpl(C,U),te&&(!O||O.indexOf(te.constructor)>-1))return te;X=X.parent}return null},S.prototype._lookupImpl=function(C,O){if(Object.prototype.hasOwnProperty.call(this._lookupCache,O))return this._lookupCache[O];var D=this.get(C[0]),U=null;if(D)C.length===1?U=D:D instanceof S&&(C=C.slice(1),U=D._lookupImpl(C,C.join(".")));else for(var te=0;te<this.nestedArray.length;++te)this._nestedArray[te]instanceof S&&(D=this._nestedArray[te]._lookupImpl(C,O))&&(U=D);return this._lookupCache[O]=U,U},S.prototype.lookupType=function(C){var O=this.lookup(C,[v]);if(!O)throw Error("no such type: "+C);return O},S.prototype.lookupEnum=function(C){var O=this.lookup(C,[_]);if(!O)throw Error("no such Enum '"+C+"' in "+this);return O},S.prototype.lookupTypeOrEnum=function(C){var O=this.lookup(C,[v,_]);if(!O)throw Error("no such Type or Enum '"+C+"' in "+this);return O},S.prototype.lookupService=function(C){var O=this.lookup(C,[w]);if(!O)throw Error("no such Service '"+C+"' in "+this);return O},S._configure=function(T,C,O){v=T,w=C,_=O},namespace}var mapfield,hasRequiredMapfield;function requireMapfield(){if(hasRequiredMapfield)return mapfield;hasRequiredMapfield=1,mapfield=b;var y=requireField();((b.prototype=Object.create(y.prototype)).constructor=b).className="MapField";var u=requireTypes(),h=requireUtil();function b(v,w,_,E,S,x){if(y.call(this,v,w,E,void 0,void 0,S,x),!h.isString(_))throw TypeError("keyType must be a string");this.keyType=_,this.resolvedKeyType=null,this.map=!0}return b.fromJSON=function(w,_){return new b(w,_.id,_.keyType,_.type,_.options,_.comment)},b.prototype.toJSON=function(w){var _=w?!!w.keepComments:!1;return h.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",_?this.comment:void 0])},b.prototype.resolve=function(){if(this.resolved)return this;if(u.mapKey[this.keyType]===void 0)throw Error("invalid key type: "+this.keyType);return y.prototype.resolve.call(this)},b.d=function(w,_,E){return typeof E=="function"?E=h.decorateType(E).name:E&&typeof E=="object"&&(E=h.decorateEnum(E).name),function(x,T){h.decorateType(x.constructor).add(new b(T,w,_,E))}},mapfield}var method,hasRequiredMethod;function requireMethod(){if(hasRequiredMethod)return method;hasRequiredMethod=1,method=h;var y=requireObject();((h.prototype=Object.create(y.prototype)).constructor=h).className="Method";var u=requireUtil();function h(b,v,w,_,E,S,x,T,C){if(u.isObject(E)?(x=E,E=S=void 0):u.isObject(S)&&(x=S,S=void 0),!(v===void 0||u.isString(v)))throw TypeError("type must be a string");if(!u.isString(w))throw TypeError("requestType must be a string");if(!u.isString(_))throw TypeError("responseType must be a string");y.call(this,b,x),this.type=v||"rpc",this.requestType=w,this.requestStream=E?!0:void 0,this.responseType=_,this.responseStream=S?!0:void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=T,this.parsedOptions=C}return h.fromJSON=function(v,w){return new h(v,w.type,w.requestType,w.responseType,w.requestStream,w.responseStream,w.options,w.comment,w.parsedOptions)},h.prototype.toJSON=function(v){var w=v?!!v.keepComments:!1;return u.toObject(["type",this.type!=="rpc"&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",w?this.comment:void 0,"parsedOptions",this.parsedOptions])},h.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),y.prototype.resolve.call(this))},method}var service,hasRequiredService;function requireService(){if(hasRequiredService)return service;hasRequiredService=1,service=v;var y=requireNamespace();((v.prototype=Object.create(y.prototype)).constructor=v).className="Service";var u=requireMethod(),h=requireUtil(),b=rpc;function v(_,E){y.call(this,_,E),this.methods={},this._methodsArray=null}v.fromJSON=function(E,S){var x=new v(E,S.options);if(S.methods)for(var T=Object.keys(S.methods),C=0;C<T.length;++C)x.add(u.fromJSON(T[C],S.methods[T[C]]));return S.nested&&x.addJSON(S.nested),S.edition&&(x._edition=S.edition),x.comment=S.comment,x._defaultEdition="proto3",x},v.prototype.toJSON=function(E){var S=y.prototype.toJSON.call(this,E),x=E?!!E.keepComments:!1;return h.toObject(["edition",this._editionToJSON(),"options",S&&S.options||void 0,"methods",y.arrayToJSON(this.methodsArray,E)||{},"nested",S&&S.nested||void 0,"comment",x?this.comment:void 0])},Object.defineProperty(v.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=h.toArray(this.methods))}});function w(_){return _._methodsArray=null,_}return v.prototype.get=function(E){return this.methods[E]||y.prototype.get.call(this,E)},v.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;y.prototype.resolve.call(this);for(var E=this.methodsArray,S=0;S<E.length;++S)E[S].resolve();return this},v.prototype._resolveFeaturesRecursive=function(E){return this._needsRecursiveFeatureResolution?(E=this._edition||E,y.prototype._resolveFeaturesRecursive.call(this,E),this.methodsArray.forEach(S=>{S._resolveFeaturesRecursive(E)}),this):this},v.prototype.add=function(E){if(this.get(E.name))throw Error("duplicate name '"+E.name+"' in "+this);return E instanceof u?(this.methods[E.name]=E,E.parent=this,w(this)):y.prototype.add.call(this,E)},v.prototype.remove=function(E){if(E instanceof u){if(this.methods[E.name]!==E)throw Error(E+" is not a member of "+this);return delete this.methods[E.name],E.parent=null,w(this)}return y.prototype.remove.call(this,E)},v.prototype.create=function(E,S,x){for(var T=new b.Service(E,S,x),C=0,O;C<this.methodsArray.length;++C){var D=h.lcFirst((O=this._methodsArray[C]).resolve().name).replace(/[^$\w_]/g,"");T[D]=h.codegen(["r","c"],h.isReserved(D)?D+"_":D)("return this.rpcCall(m,q,s,r,c)")({m:O,q:O.resolvedRequestType.ctor,s:O.resolvedResponseType.ctor})}return T},service}var message=Message,util$1=requireMinimal();function Message(y){if(y)for(var u=Object.keys(y),h=0;h<u.length;++h)this[u[h]]=y[u[h]]}Message.create=function y(u){return this.$type.create(u)};Message.encode=function y(u,h){return this.$type.encode(u,h)};Message.encodeDelimited=function y(u,h){return this.$type.encodeDelimited(u,h)};Message.decode=function y(u){return this.$type.decode(u)};Message.decodeDelimited=function y(u){return this.$type.decodeDelimited(u)};Message.verify=function y(u){return this.$type.verify(u)};Message.fromObject=function y(u){return this.$type.fromObject(u)};Message.toObject=function y(u,h){return this.$type.toObject(u,h)};Message.prototype.toJSON=function y(){return this.$type.toObject(this,util$1.toJSONOptions)};var decoder_1,hasRequiredDecoder;function requireDecoder(){if(hasRequiredDecoder)return decoder_1;hasRequiredDecoder=1,decoder_1=v;var y=require_enum(),u=requireTypes(),h=requireUtil();function b(w){return"missing required '"+w.name+"'"}function v(w){for(var _=h.codegen(["r","l","e"],w.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(w.fieldsArray.filter(function(O){return O.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),E=0;E<w.fieldsArray.length;++E){var S=w._fieldsArray[E].resolve(),x=S.resolvedType instanceof y?"int32":S.type,T="m"+h.safeProp(S.name);_("case %i: {",S.id),S.map?(_("if(%s===util.emptyObject)",T)("%s={}",T)("var c2 = r.uint32()+r.pos"),u.defaults[S.keyType]!==void 0?_("k=%j",u.defaults[S.keyType]):_("k=null"),u.defaults[x]!==void 0?_("value=%j",u.defaults[x]):_("value=null"),_("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",S.keyType)("case 2:"),u.basic[x]===void 0?_("value=types[%i].decode(r,r.uint32())",E):_("value=r.%s()",x),_("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),u.long[S.keyType]!==void 0?_('%s[typeof k==="object"?util.longToHash(k):k]=value',T):_("%s[k]=value",T)):S.repeated?(_("if(!(%s&&%s.length))",T,T)("%s=[]",T),u.packed[x]!==void 0&&_("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",T,x)("}else"),u.basic[x]===void 0?_(S.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",T,E):_("%s.push(r.%s())",T,x)):u.basic[x]===void 0?_(S.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",T,E):_("%s=r.%s()",T,x),_("break")("}")}for(_("default:")("r.skipType(t&7)")("break")("}")("}"),E=0;E<w._fieldsArray.length;++E){var C=w._fieldsArray[E];C.required&&_("if(!m.hasOwnProperty(%j))",C.name)("throw util.ProtocolError(%j,{instance:m})",b(C))}return _("return m")}return decoder_1}var verifier_1,hasRequiredVerifier;function requireVerifier(){if(hasRequiredVerifier)return verifier_1;hasRequiredVerifier=1,verifier_1=w;var y=require_enum(),u=requireUtil();function h(_,E){return _.name+": "+E+(_.repeated&&E!=="array"?"[]":_.map&&E!=="object"?"{k:"+_.keyType+"}":"")+" expected"}function b(_,E,S,x){if(E.resolvedType)if(E.resolvedType instanceof y){_("switch(%s){",x)("default:")("return%j",h(E,"enum value"));for(var T=Object.keys(E.resolvedType.values),C=0;C<T.length;++C)_("case %i:",E.resolvedType.values[T[C]]);_("break")("}")}else _("{")("var e=types[%i].verify(%s);",S,x)("if(e)")("return%j+e",E.name+".")("}");else switch(E.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":_("if(!util.isInteger(%s))",x)("return%j",h(E,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":_("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",x,x,x,x)("return%j",h(E,"integer|Long"));break;case"float":case"double":_('if(typeof %s!=="number")',x)("return%j",h(E,"number"));break;case"bool":_('if(typeof %s!=="boolean")',x)("return%j",h(E,"boolean"));break;case"string":_("if(!util.isString(%s))",x)("return%j",h(E,"string"));break;case"bytes":_('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',x,x,x)("return%j",h(E,"buffer"));break}return _}function v(_,E,S){switch(E.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":_("if(!util.key32Re.test(%s))",S)("return%j",h(E,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":_("if(!util.key64Re.test(%s))",S)("return%j",h(E,"integer|Long key"));break;case"bool":_("if(!util.key2Re.test(%s))",S)("return%j",h(E,"boolean key"));break}return _}function w(_){var E=u.codegen(["m"],_.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),S=_.oneofsArray,x={};S.length&&E("var p={}");for(var T=0;T<_.fieldsArray.length;++T){var C=_._fieldsArray[T].resolve(),O="m"+u.safeProp(C.name);if(C.optional&&E("if(%s!=null&&m.hasOwnProperty(%j)){",O,C.name),C.map)E("if(!util.isObject(%s))",O)("return%j",h(C,"object"))("var k=Object.keys(%s)",O)("for(var i=0;i<k.length;++i){"),v(E,C,"k[i]"),b(E,C,T,O+"[k[i]]")("}");else if(C.repeated)E("if(!Array.isArray(%s))",O)("return%j",h(C,"array"))("for(var i=0;i<%s.length;++i){",O),b(E,C,T,O+"[i]")("}");else{if(C.partOf){var D=u.safeProp(C.partOf.name);x[C.partOf.name]===1&&E("if(p%s===1)",D)("return%j",C.partOf.name+": multiple values"),x[C.partOf.name]=1,E("p%s=1",D)}b(E,C,T,O)}C.optional&&E("}")}return E("return null")}return verifier_1}var converter={},hasRequiredConverter;function requireConverter(){return hasRequiredConverter||(hasRequiredConverter=1,function(y){var u=y,h=require_enum(),b=requireUtil();function v(_,E,S,x){var T=!1;if(E.resolvedType)if(E.resolvedType instanceof h){_("switch(d%s){",x);for(var C=E.resolvedType.values,O=Object.keys(C),D=0;D<O.length;++D)C[O[D]]===E.typeDefault&&!T&&(_("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',x,x,x),E.repeated||_("break"),T=!0),_("case%j:",O[D])("case %i:",C[O[D]])("m%s=%j",x,C[O[D]])("break");_("}")}else _('if(typeof d%s!=="object")',x)("throw TypeError(%j)",E.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",x,S,x);else{var U=!1;switch(E.type){case"double":case"float":_("m%s=Number(d%s)",x,x);break;case"uint32":case"fixed32":_("m%s=d%s>>>0",x,x);break;case"int32":case"sint32":case"sfixed32":_("m%s=d%s|0",x,x);break;case"uint64":U=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":_("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",x,x,U)('else if(typeof d%s==="string")',x)("m%s=parseInt(d%s,10)",x,x)('else if(typeof d%s==="number")',x)("m%s=d%s",x,x)('else if(typeof d%s==="object")',x)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",x,x,x,U?"true":"");break;case"bytes":_('if(typeof d%s==="string")',x)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",x,x,x)("else if(d%s.length >= 0)",x)("m%s=d%s",x,x);break;case"string":_("m%s=String(d%s)",x,x);break;case"bool":_("m%s=Boolean(d%s)",x,x);break}}return _}u.fromObject=function(E){var S=E.fieldsArray,x=b.codegen(["d"],E.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!S.length)return x("return new this.ctor");x("var m=new this.ctor");for(var T=0;T<S.length;++T){var C=S[T].resolve(),O=b.safeProp(C.name);C.map?(x("if(d%s){",O)('if(typeof d%s!=="object")',O)("throw TypeError(%j)",C.fullName+": object expected")("m%s={}",O)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",O),v(x,C,T,O+"[ks[i]]")("}")("}")):C.repeated?(x("if(d%s){",O)("if(!Array.isArray(d%s))",O)("throw TypeError(%j)",C.fullName+": array expected")("m%s=[]",O)("for(var i=0;i<d%s.length;++i){",O),v(x,C,T,O+"[i]")("}")("}")):(C.resolvedType instanceof h||x("if(d%s!=null){",O),v(x,C,T,O),C.resolvedType instanceof h||x("}"))}return x("return m")};function w(_,E,S,x){if(E.resolvedType)E.resolvedType instanceof h?_("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",x,S,x,x,S,x,x):_("d%s=types[%i].toObject(m%s,o)",x,S,x);else{var T=!1;switch(E.type){case"double":case"float":_("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",x,x,x,x);break;case"uint64":T=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":_('if(typeof m%s==="number")',x)("d%s=o.longs===String?String(m%s):m%s",x,x,x)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",x,x,x,x,T?"true":"",x);break;case"bytes":_("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",x,x,x,x,x);break;default:_("d%s=m%s",x,x);break}}return _}u.toObject=function(E){var S=E.fieldsArray.slice().sort(b.compareFieldsById);if(!S.length)return b.codegen()("return {}");for(var x=b.codegen(["m","o"],E.name+"$toObject")("if(!o)")("o={}")("var d={}"),T=[],C=[],O=[],D=0;D<S.length;++D)S[D].partOf||(S[D].resolve().repeated?T:S[D].map?C:O).push(S[D]);if(T.length){for(x("if(o.arrays||o.defaults){"),D=0;D<T.length;++D)x("d%s=[]",b.safeProp(T[D].name));x("}")}if(C.length){for(x("if(o.objects||o.defaults){"),D=0;D<C.length;++D)x("d%s={}",b.safeProp(C[D].name));x("}")}if(O.length){for(x("if(o.defaults){"),D=0;D<O.length;++D){var U=O[D],te=b.safeProp(U.name);if(U.resolvedType instanceof h)x("d%s=o.enums===String?%j:%j",te,U.resolvedType.valuesById[U.typeDefault],U.typeDefault);else if(U.long)x("if(util.Long){")("var n=new util.Long(%i,%i,%j)",U.typeDefault.low,U.typeDefault.high,U.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",te)("}else")("d%s=o.longs===String?%j:%i",te,U.typeDefault.toString(),U.typeDefault.toNumber());else if(U.bytes){var X="["+Array.prototype.slice.call(U.typeDefault).join(",")+"]";x("if(o.bytes===String)d%s=%j",te,String.fromCharCode.apply(String,U.typeDefault))("else{")("d%s=%s",te,X)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",te,te)("}")}else x("d%s=%j",te,U.typeDefault)}x("}")}var ie=!1;for(D=0;D<S.length;++D){var U=S[D],ee=E._fieldsArray.indexOf(U),te=b.safeProp(U.name);U.map?(ie||(ie=!0,x("var ks2")),x("if(m%s&&(ks2=Object.keys(m%s)).length){",te,te)("d%s={}",te)("for(var j=0;j<ks2.length;++j){"),w(x,U,ee,te+"[ks2[j]]")("}")):U.repeated?(x("if(m%s&&m%s.length){",te,te)("d%s=[]",te)("for(var j=0;j<m%s.length;++j){",te),w(x,U,ee,te+"[j]")("}")):(x("if(m%s!=null&&m.hasOwnProperty(%j)){",te,U.name),w(x,U,ee,te),U.partOf&&x("if(o.oneofs)")("d%s=%j",b.safeProp(U.partOf.name),U.name)),x("}")}return x("return d")}}(converter)),converter}var wrappers={};(function(y){var u=y,h=message;u[".google.protobuf.Any"]={fromObject:function(b){if(b&&b["@type"]){var v=b["@type"].substring(b["@type"].lastIndexOf("/")+1),w=this.lookup(v);if(w){var _=b["@type"].charAt(0)==="."?b["@type"].slice(1):b["@type"];return _.indexOf("/")===-1&&(_="/"+_),this.create({type_url:_,value:w.encode(w.fromObject(b)).finish()})}}return this.fromObject(b)},toObject:function(b,v){var w="type.googleapis.com/",_="",E="";if(v&&v.json&&b.type_url&&b.value){E=b.type_url.substring(b.type_url.lastIndexOf("/")+1),_=b.type_url.substring(0,b.type_url.lastIndexOf("/")+1);var S=this.lookup(E);S&&(b=S.decode(b.value))}if(!(b instanceof this.ctor)&&b instanceof h){var x=b.$type.toObject(b,v),T=b.$type.fullName[0]==="."?b.$type.fullName.slice(1):b.$type.fullName;return _===""&&(_=w),E=_+T,x["@type"]=E,x}return this.toObject(b,v)}}})(wrappers);var type,hasRequiredType;function requireType(){if(hasRequiredType)return type;hasRequiredType=1,type=te;var y=requireNamespace();((te.prototype=Object.create(y.prototype)).constructor=te).className="Type";var u=require_enum(),h=requireOneof(),b=requireField(),v=requireMapfield(),w=requireService(),_=message,E=reader,S=writer,x=requireUtil(),T=requireEncoder(),C=requireDecoder(),O=requireVerifier(),D=requireConverter(),U=wrappers;function te(ie,ee){y.call(this,ie,ee),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}Object.defineProperties(te.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var ie=Object.keys(this.fields),ee=0;ee<ie.length;++ee){var ae=this.fields[ie[ee]],de=ae.id;if(this._fieldsById[de])throw Error("duplicate id "+de+" in "+this);this._fieldsById[de]=ae}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=x.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=x.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=te.generateConstructor(this)())},set:function(ie){var ee=ie.prototype;ee instanceof _||((ie.prototype=new _).constructor=ie,x.merge(ie.prototype,ee)),ie.$type=ie.prototype.$type=this,x.merge(ie,_,!0),this._ctor=ie;for(var ae=0;ae<this.fieldsArray.length;++ae)this._fieldsArray[ae].resolve();var de={};for(ae=0;ae<this.oneofsArray.length;++ae)de[this._oneofsArray[ae].resolve().name]={get:x.oneOfGetter(this._oneofsArray[ae].oneof),set:x.oneOfSetter(this._oneofsArray[ae].oneof)};ae&&Object.defineProperties(ie.prototype,de)}}}),te.generateConstructor=function(ee){for(var ae=x.codegen(["p"],ee.name),de=0,Se;de<ee.fieldsArray.length;++de)(Se=ee._fieldsArray[de]).map?ae("this%s={}",x.safeProp(Se.name)):Se.repeated&&ae("this%s=[]",x.safeProp(Se.name));return ae("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")};function X(ie){return ie._fieldsById=ie._fieldsArray=ie._oneofsArray=null,delete ie.encode,delete ie.decode,delete ie.verify,ie}return te.fromJSON=function(ee,ae){var de=new te(ee,ae.options);de.extensions=ae.extensions,de.reserved=ae.reserved;for(var Se=Object.keys(ae.fields),ve=0;ve<Se.length;++ve)de.add((typeof ae.fields[Se[ve]].keyType<"u"?v.fromJSON:b.fromJSON)(Se[ve],ae.fields[Se[ve]]));if(ae.oneofs)for(Se=Object.keys(ae.oneofs),ve=0;ve<Se.length;++ve)de.add(h.fromJSON(Se[ve],ae.oneofs[Se[ve]]));if(ae.nested)for(Se=Object.keys(ae.nested),ve=0;ve<Se.length;++ve){var Pe=ae.nested[Se[ve]];de.add((Pe.id!==void 0?b.fromJSON:Pe.fields!==void 0?te.fromJSON:Pe.values!==void 0?u.fromJSON:Pe.methods!==void 0?w.fromJSON:y.fromJSON)(Se[ve],Pe))}return ae.extensions&&ae.extensions.length&&(de.extensions=ae.extensions),ae.reserved&&ae.reserved.length&&(de.reserved=ae.reserved),ae.group&&(de.group=!0),ae.comment&&(de.comment=ae.comment),ae.edition&&(de._edition=ae.edition),de._defaultEdition="proto3",de},te.prototype.toJSON=function(ee){var ae=y.prototype.toJSON.call(this,ee),de=ee?!!ee.keepComments:!1;return x.toObject(["edition",this._editionToJSON(),"options",ae&&ae.options||void 0,"oneofs",y.arrayToJSON(this.oneofsArray,ee),"fields",y.arrayToJSON(this.fieldsArray.filter(function(Se){return!Se.declaringField}),ee)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",ae&&ae.nested||void 0,"comment",de?this.comment:void 0])},te.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;y.prototype.resolveAll.call(this);var ee=this.oneofsArray;for(de=0;de<ee.length;)ee[de++].resolve();for(var ae=this.fieldsArray,de=0;de<ae.length;)ae[de++].resolve();return this},te.prototype._resolveFeaturesRecursive=function(ee){return this._needsRecursiveFeatureResolution?(ee=this._edition||ee,y.prototype._resolveFeaturesRecursive.call(this,ee),this.oneofsArray.forEach(ae=>{ae._resolveFeatures(ee)}),this.fieldsArray.forEach(ae=>{ae._resolveFeatures(ee)}),this):this},te.prototype.get=function(ee){return this.fields[ee]||this.oneofs&&this.oneofs[ee]||this.nested&&this.nested[ee]||null},te.prototype.add=function(ee){if(this.get(ee.name))throw Error("duplicate name '"+ee.name+"' in "+this);if(ee instanceof b&&ee.extend===void 0){if(this._fieldsById?this._fieldsById[ee.id]:this.fieldsById[ee.id])throw Error("duplicate id "+ee.id+" in "+this);if(this.isReservedId(ee.id))throw Error("id "+ee.id+" is reserved in "+this);if(this.isReservedName(ee.name))throw Error("name '"+ee.name+"' is reserved in "+this);return ee.parent&&ee.parent.remove(ee),this.fields[ee.name]=ee,ee.message=this,ee.onAdd(this),X(this)}return ee instanceof h?(this.oneofs||(this.oneofs={}),this.oneofs[ee.name]=ee,ee.onAdd(this),X(this)):y.prototype.add.call(this,ee)},te.prototype.remove=function(ee){if(ee instanceof b&&ee.extend===void 0){if(!this.fields||this.fields[ee.name]!==ee)throw Error(ee+" is not a member of "+this);return delete this.fields[ee.name],ee.parent=null,ee.onRemove(this),X(this)}if(ee instanceof h){if(!this.oneofs||this.oneofs[ee.name]!==ee)throw Error(ee+" is not a member of "+this);return delete this.oneofs[ee.name],ee.parent=null,ee.onRemove(this),X(this)}return y.prototype.remove.call(this,ee)},te.prototype.isReservedId=function(ee){return y.isReservedId(this.reserved,ee)},te.prototype.isReservedName=function(ee){return y.isReservedName(this.reserved,ee)},te.prototype.create=function(ee){return new this.ctor(ee)},te.prototype.setup=function(){for(var ee=this.fullName,ae=[],de=0;de<this.fieldsArray.length;++de)ae.push(this._fieldsArray[de].resolve().resolvedType);this.encode=T(this)({Writer:S,types:ae,util:x}),this.decode=C(this)({Reader:E,types:ae,util:x}),this.verify=O(this)({types:ae,util:x}),this.fromObject=D.fromObject(this)({types:ae,util:x}),this.toObject=D.toObject(this)({types:ae,util:x});var Se=U[ee];if(Se){var ve=Object.create(this);ve.fromObject=this.fromObject,this.fromObject=Se.fromObject.bind(ve),ve.toObject=this.toObject,this.toObject=Se.toObject.bind(ve)}return this},te.prototype.encode=function(ee,ae){return this.setup().encode(ee,ae)},te.prototype.encodeDelimited=function(ee,ae){return this.encode(ee,ae&&ae.len?ae.fork():ae).ldelim()},te.prototype.decode=function(ee,ae){return this.setup().decode(ee,ae)},te.prototype.decodeDelimited=function(ee){return ee instanceof E||(ee=E.create(ee)),this.decode(ee,ee.uint32())},te.prototype.verify=function(ee){return this.setup().verify(ee)},te.prototype.fromObject=function(ee){return this.setup().fromObject(ee)},te.prototype.toObject=function(ee,ae){return this.setup().toObject(ee,ae)},te.d=function(ee){return function(de){x.decorateType(de,ee)}},type}var root,hasRequiredRoot;function requireRoot(){if(hasRequiredRoot)return root;hasRequiredRoot=1,root=S;var y=requireNamespace();((S.prototype=Object.create(y.prototype)).constructor=S).className="Root";var u=requireField(),h=require_enum(),b=requireOneof(),v=requireUtil(),w,_,E;function S(O){y.call(this,"",O),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}S.fromJSON=function(D,U){return U||(U=new S),D.options&&U.setOptions(D.options),U.addJSON(D.nested).resolveAll()},S.prototype.resolvePath=v.path.resolve,S.prototype.fetch=v.fetch;function x(){}S.prototype.load=function O(D,U,te){typeof U=="function"&&(te=U,U=void 0);var X=this;if(!te)return v.asPromise(O,X,D,U);var ie=te===x;function ee(Ee,De){if(te){if(ie)throw Ee;De&&De.resolveAll();var be=te;te=null,be(Ee,De)}}function ae(Ee){var De=Ee.lastIndexOf("google/protobuf/");if(De>-1){var be=Ee.substring(De);if(be in E)return be}return null}function de(Ee,De){try{if(v.isString(De)&&De.charAt(0)==="{"&&(De=JSON.parse(De)),!v.isString(De))X.setOptions(De.options).addJSON(De.nested);else{_.filename=Ee;var be=_(De,X,U),B,F=0;if(be.imports)for(;F<be.imports.length;++F)(B=ae(be.imports[F])||X.resolvePath(Ee,be.imports[F]))&&Se(B);if(be.weakImports)for(F=0;F<be.weakImports.length;++F)(B=ae(be.weakImports[F])||X.resolvePath(Ee,be.weakImports[F]))&&Se(B,!0)}}catch(M){ee(M)}!ie&&!ve&&ee(null,X)}function Se(Ee,De){if(Ee=ae(Ee)||Ee,!(X.files.indexOf(Ee)>-1)){if(X.files.push(Ee),Ee in E){ie?de(Ee,E[Ee]):(++ve,setTimeout(function(){--ve,de(Ee,E[Ee])}));return}if(ie){var be;try{be=v.fs.readFileSync(Ee).toString("utf8")}catch(B){De||ee(B);return}de(Ee,be)}else++ve,X.fetch(Ee,function(B,F){if(--ve,!!te){if(B){De?ve||ee(null,X):ee(B);return}de(Ee,F)}})}}var ve=0;v.isString(D)&&(D=[D]);for(var Pe=0,Ie;Pe<D.length;++Pe)(Ie=X.resolvePath("",D[Pe]))&&Se(Ie);return ie?(X.resolveAll(),X):(ve||ee(null,X),X)},S.prototype.loadSync=function(D,U){if(!v.isNode)throw Error("not supported");return this.load(D,U,x)},S.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(D){return"'extend "+D.extend+"' in "+D.parent.fullName}).join(", "));return y.prototype.resolveAll.call(this)};var T=/^[A-Z]/;function C(O,D){var U=D.parent.lookup(D.extend);if(U){var te=new u(D.fullName,D.id,D.type,D.rule,void 0,D.options);return U.get(te.name)||(te.declaringField=D,D.extensionField=te,U.add(te)),!0}return!1}return S.prototype._handleAdd=function(D){if(D instanceof u)D.extend!==void 0&&!D.extensionField&&(C(this,D)||this.deferred.push(D));else if(D instanceof h)T.test(D.name)&&(D.parent[D.name]=D.values);else if(!(D instanceof b)){if(D instanceof w)for(var U=0;U<this.deferred.length;)C(this,this.deferred[U])?this.deferred.splice(U,1):++U;for(var te=0;te<D.nestedArray.length;++te)this._handleAdd(D._nestedArray[te]);T.test(D.name)&&(D.parent[D.name]=D)}(D instanceof w||D instanceof h||D instanceof u)&&(this._fullyQualifiedObjects[D.fullName]=D)},S.prototype._handleRemove=function(D){if(D instanceof u){if(D.extend!==void 0)if(D.extensionField)D.extensionField.parent.remove(D.extensionField),D.extensionField=null;else{var U=this.deferred.indexOf(D);U>-1&&this.deferred.splice(U,1)}}else if(D instanceof h)T.test(D.name)&&delete D.parent[D.name];else if(D instanceof y){for(var te=0;te<D.nestedArray.length;++te)this._handleRemove(D._nestedArray[te]);T.test(D.name)&&delete D.parent[D.name]}delete this._fullyQualifiedObjects[D.fullName]},S._configure=function(O,D,U){w=O,_=D,E=U},root}var hasRequiredUtil;function requireUtil(){if(hasRequiredUtil)return util$2.exports;hasRequiredUtil=1;var y=util$2.exports=requireMinimal(),u=roots,h,b;y.codegen=codegen_1,y.fetch=fetch_1,y.path=path,y.fs=y.inquire("fs"),y.toArray=function(x){if(x){for(var T=Object.keys(x),C=new Array(T.length),O=0;O<T.length;)C[O]=x[T[O++]];return C}return[]},y.toObject=function(x){for(var T={},C=0;C<x.length;){var O=x[C++],D=x[C++];D!==void 0&&(T[O]=D)}return T};var v=/\\/g,w=/"/g;y.isReserved=function(x){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(x)},y.safeProp=function(x){return!/^[$\w_]+$/.test(x)||y.isReserved(x)?'["'+x.replace(v,"\\\\").replace(w,'\\"')+'"]':"."+x},y.ucFirst=function(x){return x.charAt(0).toUpperCase()+x.substring(1)};var _=/_([a-z])/g;y.camelCase=function(x){return x.substring(0,1)+x.substring(1).replace(_,function(T,C){return C.toUpperCase()})},y.compareFieldsById=function(x,T){return x.id-T.id},y.decorateType=function(x,T){if(x.$type)return T&&x.$type.name!==T&&(y.decorateRoot.remove(x.$type),x.$type.name=T,y.decorateRoot.add(x.$type)),x.$type;h||(h=requireType());var C=new h(T||x.name);return y.decorateRoot.add(C),C.ctor=x,Object.defineProperty(x,"$type",{value:C,enumerable:!1}),Object.defineProperty(x.prototype,"$type",{value:C,enumerable:!1}),C};var E=0;return y.decorateEnum=function(x){if(x.$type)return x.$type;b||(b=require_enum());var T=new b("Enum"+E++,x);return y.decorateRoot.add(T),Object.defineProperty(x,"$type",{value:T,enumerable:!1}),T},y.setProperty=function(x,T,C,O){function D(U,te,X){var ie=te.shift();if(ie==="__proto__"||ie==="prototype")return U;if(te.length>0)U[ie]=D(U[ie]||{},te,X);else{var ee=U[ie];if(ee&&O)return U;ee&&(X=[].concat(ee).concat(X)),U[ie]=X}return U}if(typeof x!="object")throw TypeError("dst must be an object");if(!T)throw TypeError("path must be specified");return T=T.split("."),D(x,T,C)},Object.defineProperty(y,"decorateRoot",{get:function(){return u.decorated||(u.decorated=new(requireRoot()))}}),util$2.exports}var hasRequiredTypes;function requireTypes(){return hasRequiredTypes||(hasRequiredTypes=1,function(y){var u=y,h=requireUtil(),b=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function v(w,_){var E=0,S={};for(_|=0;E<w.length;)S[b[E+_]]=w[E++];return S}u.basic=v([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),u.defaults=v([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",h.emptyArray,null]),u.long=v([0,0,0,1,1],7),u.mapKey=v([0,0,0,5,5,0,0,0,1,1,0,2],2),u.packed=v([1,5,0,0,0,5,5,0,0,0,1,1,0])}(types$1)),types$1}var field,hasRequiredField;function requireField(){if(hasRequiredField)return field;hasRequiredField=1,field=_;var y=requireObject();((_.prototype=Object.create(y.prototype)).constructor=_).className="Field";var u=require_enum(),h=requireTypes(),b=requireUtil(),v,w=/^required|optional|repeated$/;_.fromJSON=function(S,x){var T=new _(S,x.id,x.type,x.rule,x.extend,x.options,x.comment);return x.edition&&(T._edition=x.edition),T._defaultEdition="proto3",T};function _(E,S,x,T,C,O,D){if(b.isObject(T)?(D=C,O=T,T=C=void 0):b.isObject(C)&&(D=O,O=C,C=void 0),y.call(this,E,O),!b.isInteger(S)||S<0)throw TypeError("id must be a non-negative integer");if(!b.isString(x))throw TypeError("type must be a string");if(T!==void 0&&!w.test(T=T.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(C!==void 0&&!b.isString(C))throw TypeError("extend must be a string");T==="proto3_optional"&&(T="optional"),this.rule=T&&T!=="optional"?T:void 0,this.type=x,this.id=S,this.extend=C||void 0,this.repeated=T==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=b.Long?h.long[x]!==void 0:!1,this.bytes=x==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=D}return Object.defineProperty(_.prototype,"required",{get:function(){return this._features.field_presence==="LEGACY_REQUIRED"}}),Object.defineProperty(_.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(_.prototype,"delimited",{get:function(){return this.resolvedType instanceof v&&this._features.message_encoding==="DELIMITED"}}),Object.defineProperty(_.prototype,"packed",{get:function(){return this._features.repeated_field_encoding==="PACKED"}}),Object.defineProperty(_.prototype,"hasPresence",{get:function(){return this.repeated||this.map?!1:this.partOf||this.declaringField||this.extensionField||this._features.field_presence!=="IMPLICIT"}}),_.prototype.setOption=function(S,x,T){return y.prototype.setOption.call(this,S,x,T)},_.prototype.toJSON=function(S){var x=S?!!S.keepComments:!1;return b.toObject(["edition",this._editionToJSON(),"rule",this.rule!=="optional"&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",x?this.comment:void 0])},_.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=h.defaults[this.type])===void 0?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof v?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&this.options.default!=null&&(this.typeDefault=this.options.default,this.resolvedType instanceof u&&typeof this.typeDefault=="string"&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(this.options.packed!==void 0&&this.resolvedType&&!(this.resolvedType instanceof u)&&delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=b.Long.fromNumber(this.typeDefault,this.type.charAt(0)==="u"),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&typeof this.typeDefault=="string"){var S;b.base64.test(this.typeDefault)?b.base64.decode(this.typeDefault,S=b.newBuffer(b.base64.length(this.typeDefault)),0):b.utf8.write(this.typeDefault,S=b.newBuffer(b.utf8.length(this.typeDefault)),0),this.typeDefault=S}return this.map?this.defaultValue=b.emptyObject:this.repeated?this.defaultValue=b.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof v&&(this.parent.ctor.prototype[this.name]=this.defaultValue),y.prototype.resolve.call(this)},_.prototype._inferLegacyProtoFeatures=function(S){if(S!=="proto2"&&S!=="proto3")return{};var x={};if(this.rule==="required"&&(x.field_presence="LEGACY_REQUIRED"),this.parent&&h.defaults[this.type]===void 0){var T=this.parent.get(this.type.split(".").pop());T&&T instanceof v&&T.group&&(x.message_encoding="DELIMITED")}return this.getOption("packed")===!0?x.repeated_field_encoding="PACKED":this.getOption("packed")===!1&&(x.repeated_field_encoding="EXPANDED"),x},_.prototype._resolveFeatures=function(S){return y.prototype._resolveFeatures.call(this,this._edition||S)},_.d=function(S,x,T,C){return typeof x=="function"?x=b.decorateType(x).name:x&&typeof x=="object"&&(x=b.decorateEnum(x).name),function(D,U){b.decorateType(D.constructor).add(new _(U,S,x,T,{default:C}))}},_._configure=function(S){v=S},field}var oneof,hasRequiredOneof;function requireOneof(){if(hasRequiredOneof)return oneof;hasRequiredOneof=1,oneof=b;var y=requireObject();((b.prototype=Object.create(y.prototype)).constructor=b).className="OneOf";var u=requireField(),h=requireUtil();function b(w,_,E,S){if(Array.isArray(_)||(E=_,_=void 0),y.call(this,w,E),!(_===void 0||Array.isArray(_)))throw TypeError("fieldNames must be an Array");this.oneof=_||[],this.fieldsArray=[],this.comment=S}b.fromJSON=function(_,E){return new b(_,E.oneof,E.options,E.comment)},b.prototype.toJSON=function(_){var E=_?!!_.keepComments:!1;return h.toObject(["options",this.options,"oneof",this.oneof,"comment",E?this.comment:void 0])};function v(w){if(w.parent)for(var _=0;_<w.fieldsArray.length;++_)w.fieldsArray[_].parent||w.parent.add(w.fieldsArray[_])}return b.prototype.add=function(_){if(!(_ instanceof u))throw TypeError("field must be a Field");return _.parent&&_.parent!==this.parent&&_.parent.remove(_),this.oneof.push(_.name),this.fieldsArray.push(_),_.partOf=this,v(this),this},b.prototype.remove=function(_){if(!(_ instanceof u))throw TypeError("field must be a Field");var E=this.fieldsArray.indexOf(_);if(E<0)throw Error(_+" is not a member of "+this);return this.fieldsArray.splice(E,1),E=this.oneof.indexOf(_.name),E>-1&&this.oneof.splice(E,1),_.partOf=null,this},b.prototype.onAdd=function(_){y.prototype.onAdd.call(this,_);for(var E=this,S=0;S<this.oneof.length;++S){var x=_.get(this.oneof[S]);x&&!x.partOf&&(x.partOf=E,E.fieldsArray.push(x))}v(this)},b.prototype.onRemove=function(_){for(var E=0,S;E<this.fieldsArray.length;++E)(S=this.fieldsArray[E]).parent&&S.parent.remove(S);y.prototype.onRemove.call(this,_)},Object.defineProperty(b.prototype,"isProto3Optional",{get:function(){if(this.fieldsArray==null||this.fieldsArray.length!==1)return!1;var w=this.fieldsArray[0];return w.options!=null&&w.options.proto3_optional===!0}}),b.d=function(){for(var _=new Array(arguments.length),E=0;E<arguments.length;)_[E]=arguments[E++];return function(x,T){h.decorateType(x.constructor).add(new b(T,_)),Object.defineProperty(x,T,{get:h.oneOfGetter(_),set:h.oneOfSetter(_)})}},oneof}var object,hasRequiredObject;function requireObject(){if(hasRequiredObject)return object;hasRequiredObject=1,object=_,_.className="ReflectionObject";const y=requireOneof();var u=requireUtil(),h,b={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},v={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},w={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function _(E,S){if(!u.isString(E))throw TypeError("name must be a string");if(S&&!u.isObject(S))throw TypeError("options must be an object");this.options=S,this.parsedOptions=null,this.name=E,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}return Object.defineProperties(_.prototype,{root:{get:function(){for(var E=this;E.parent!==null;)E=E.parent;return E}},fullName:{get:function(){for(var E=[this.name],S=this.parent;S;)E.unshift(S.name),S=S.parent;return E.join(".")}}}),_.prototype.toJSON=function(){throw Error()},_.prototype.onAdd=function(S){this.parent&&this.parent!==S&&this.parent.remove(this),this.parent=S,this.resolved=!1;var x=S.root;x instanceof h&&x._handleAdd(this)},_.prototype.onRemove=function(S){var x=S.root;x instanceof h&&x._handleRemove(this),this.parent=null,this.resolved=!1},_.prototype.resolve=function(){return this.resolved?this:(this.root instanceof h&&(this.resolved=!0),this)},_.prototype._resolveFeaturesRecursive=function(S){return this._resolveFeatures(this._edition||S)},_.prototype._resolveFeatures=function(S){if(!this._featuresResolved){var x={};if(!S)throw new Error("Unknown edition for "+this.fullName);var T=Object.assign(this.options?Object.assign({},this.options.features):{},this._inferLegacyProtoFeatures(S));if(this._edition){if(S==="proto2")x=Object.assign({},v);else if(S==="proto3")x=Object.assign({},w);else if(S==="2023")x=Object.assign({},b);else throw new Error("Unknown edition: "+S);this._features=Object.assign(x,T||{}),this._featuresResolved=!0;return}if(this.partOf instanceof y){var C=Object.assign({},this.partOf._features);this._features=Object.assign(C,T||{})}else if(!this.declaringField)if(this.parent){var O=Object.assign({},this.parent._features);this._features=Object.assign(O,T||{})}else throw new Error("Unable to find a parent for "+this.fullName);this.extensionField&&(this.extensionField._features=this._features),this._featuresResolved=!0}},_.prototype._inferLegacyProtoFeatures=function(){return{}},_.prototype.getOption=function(S){if(this.options)return this.options[S]},_.prototype.setOption=function(S,x,T){return this.options||(this.options={}),/^features\./.test(S)?u.setProperty(this.options,S,x,T):(!T||this.options[S]===void 0)&&(this.getOption(S)!==x&&(this.resolved=!1),this.options[S]=x),this},_.prototype.setParsedOption=function(S,x,T){this.parsedOptions||(this.parsedOptions=[]);var C=this.parsedOptions;if(T){var O=C.find(function(te){return Object.prototype.hasOwnProperty.call(te,S)});if(O){var D=O[S];u.setProperty(D,T,x)}else O={},O[S]=u.setProperty({},T,x),C.push(O)}else{var U={};U[S]=x,C.push(U)}return this},_.prototype.setOptions=function(S,x){if(S)for(var T=Object.keys(S),C=0;C<T.length;++C)this.setOption(T[C],S[T[C]],x);return this},_.prototype.toString=function(){var S=this.constructor.className,x=this.fullName;return x.length?S+" "+x:S},_.prototype._editionToJSON=function(){if(!(!this._edition||this._edition==="proto3"))return this._edition},_._configure=function(E){h=E},object}var _enum,hasRequired_enum;function require_enum(){if(hasRequired_enum)return _enum;hasRequired_enum=1,_enum=b;var y=requireObject();((b.prototype=Object.create(y.prototype)).constructor=b).className="Enum";var u=requireNamespace(),h=requireUtil();function b(v,w,_,E,S,x){if(y.call(this,v,_),w&&typeof w!="object")throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=E,this.comments=S||{},this.valuesOptions=x,this._valuesFeatures={},this.reserved=void 0,w)for(var T=Object.keys(w),C=0;C<T.length;++C)typeof w[T[C]]=="number"&&(this.valuesById[this.values[T[C]]=w[T[C]]]=T[C])}return b.prototype._resolveFeatures=function(w){return w=this._edition||w,y.prototype._resolveFeatures.call(this,w),Object.keys(this.values).forEach(_=>{var E=Object.assign({},this._features);this._valuesFeatures[_]=Object.assign(E,this.valuesOptions&&this.valuesOptions[_]&&this.valuesOptions[_].features)}),this},b.fromJSON=function(w,_){var E=new b(w,_.values,_.options,_.comment,_.comments);return E.reserved=_.reserved,_.edition&&(E._edition=_.edition),E._defaultEdition="proto3",E},b.prototype.toJSON=function(w){var _=w?!!w.keepComments:!1;return h.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",_?this.comment:void 0,"comments",_?this.comments:void 0])},b.prototype.add=function(w,_,E,S){if(!h.isString(w))throw TypeError("name must be a string");if(!h.isInteger(_))throw TypeError("id must be an integer");if(this.values[w]!==void 0)throw Error("duplicate name '"+w+"' in "+this);if(this.isReservedId(_))throw Error("id "+_+" is reserved in "+this);if(this.isReservedName(w))throw Error("name '"+w+"' is reserved in "+this);if(this.valuesById[_]!==void 0){if(!(this.options&&this.options.allow_alias))throw Error("duplicate id "+_+" in "+this);this.values[w]=_}else this.valuesById[this.values[w]=_]=w;return S&&(this.valuesOptions===void 0&&(this.valuesOptions={}),this.valuesOptions[w]=S||null),this.comments[w]=E||null,this},b.prototype.remove=function(w){if(!h.isString(w))throw TypeError("name must be a string");var _=this.values[w];if(_==null)throw Error("name '"+w+"' does not exist in "+this);return delete this.valuesById[_],delete this.values[w],delete this.comments[w],this.valuesOptions&&delete this.valuesOptions[w],this},b.prototype.isReservedId=function(w){return u.isReservedId(this.reserved,w)},b.prototype.isReservedName=function(w){return u.isReservedName(this.reserved,w)},_enum}var encoder_1,hasRequiredEncoder;function requireEncoder(){if(hasRequiredEncoder)return encoder_1;hasRequiredEncoder=1,encoder_1=v;var y=require_enum(),u=requireTypes(),h=requireUtil();function b(w,_,E,S){return _.delimited?w("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",E,S,(_.id<<3|3)>>>0,(_.id<<3|4)>>>0):w("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",E,S,(_.id<<3|2)>>>0)}function v(w){for(var _=h.codegen(["m","w"],w.name+"$encode")("if(!w)")("w=Writer.create()"),E,S,x=w.fieldsArray.slice().sort(h.compareFieldsById),E=0;E<x.length;++E){var T=x[E].resolve(),C=w._fieldsArray.indexOf(T),O=T.resolvedType instanceof y?"int32":T.type,D=u.basic[O];S="m"+h.safeProp(T.name),T.map?(_("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",S,T.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",S)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(T.id<<3|2)>>>0,8|u.mapKey[T.keyType],T.keyType),D===void 0?_("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",C,S):_(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|D,O,S),_("}")("}")):T.repeated?(_("if(%s!=null&&%s.length){",S,S),T.packed&&u.packed[O]!==void 0?_("w.uint32(%i).fork()",(T.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",S)("w.%s(%s[i])",O,S)("w.ldelim()"):(_("for(var i=0;i<%s.length;++i)",S),D===void 0?b(_,T,C,S+"[i]"):_("w.uint32(%i).%s(%s[i])",(T.id<<3|D)>>>0,O,S)),_("}")):(T.optional&&_("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",S,T.name),D===void 0?b(_,T,C,S):_("w.uint32(%i).%s(%s)",(T.id<<3|D)>>>0,O,S))}return _("return w")}return encoder_1}var protobuf$2=indexLight.exports=indexMinimal;protobuf$2.build="light";function load$1(y,u,h){return typeof u=="function"?(h=u,u=new protobuf$2.Root):u||(u=new protobuf$2.Root),u.load(y,h)}protobuf$2.load=load$1;function loadSync(y,u){return u||(u=new protobuf$2.Root),u.loadSync(y)}protobuf$2.loadSync=loadSync;protobuf$2.encoder=requireEncoder();protobuf$2.decoder=requireDecoder();protobuf$2.verifier=requireVerifier();protobuf$2.converter=requireConverter();protobuf$2.ReflectionObject=requireObject();protobuf$2.Namespace=requireNamespace();protobuf$2.Root=requireRoot();protobuf$2.Enum=require_enum();protobuf$2.Type=requireType();protobuf$2.Field=requireField();protobuf$2.OneOf=requireOneof();protobuf$2.MapField=requireMapfield();protobuf$2.Service=requireService();protobuf$2.Method=requireMethod();protobuf$2.Message=message;protobuf$2.wrappers=wrappers;protobuf$2.types=requireTypes();protobuf$2.util=requireUtil();protobuf$2.ReflectionObject._configure(protobuf$2.Root);protobuf$2.Namespace._configure(protobuf$2.Type,protobuf$2.Service,protobuf$2.Enum);protobuf$2.Root._configure(protobuf$2.Type);protobuf$2.Field._configure(protobuf$2.Type);var indexLightExports=indexLight.exports,tokenize_1=tokenize$1,delimRe=/[\s{}=;:[\],'"()<>]/g,stringDoubleRe=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,stringSingleRe=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,setCommentRe=/^ *[*/]+ */,setCommentAltRe=/^\s*\*?\/*/,setCommentSplitRe=/\n/g,whitespaceRe=/\s/,unescapeRe=/\\(.?)/g,unescapeMap={0:"\0",r:"\r",n:`
79
+ `,t:" "};function unescape(y){return y.replace(unescapeRe,function(u,h){switch(h){case"\\":case"":return h;default:return unescapeMap[h]||""}})}tokenize$1.unescape=unescape;function tokenize$1(y,u){y=y.toString();var h=0,b=y.length,v=1,w=0,_={},E=[],S=null;function x(de){return Error("illegal "+de+" (line "+v+")")}function T(){var de=S==="'"?stringSingleRe:stringDoubleRe;de.lastIndex=h-1;var Se=de.exec(y);if(!Se)throw x("string");return h=de.lastIndex,X(S),S=null,unescape(Se[1])}function C(de){return y.charAt(de)}function O(de,Se,ve){var Pe={type:y.charAt(de++),lineEmpty:!1,leading:ve},Ie;u?Ie=2:Ie=3;var Ee=de-Ie,De;do if(--Ee<0||(De=y.charAt(Ee))===`
80
+ `){Pe.lineEmpty=!0;break}while(De===" "||De===" ");for(var be=y.substring(de,Se).split(setCommentSplitRe),B=0;B<be.length;++B)be[B]=be[B].replace(u?setCommentAltRe:setCommentRe,"").trim();Pe.text=be.join(`
81
+ `).trim(),_[v]=Pe,w=v}function D(de){var Se=U(de),ve=y.substring(de,Se),Pe=/^\s*\/\//.test(ve);return Pe}function U(de){for(var Se=de;Se<b&&C(Se)!==`
82
+ `;)Se++;return Se}function te(){if(E.length>0)return E.shift();if(S)return T();var de,Se,ve,Pe,Ie,Ee=h===0;do{if(h===b)return null;for(de=!1;whitespaceRe.test(ve=C(h));)if(ve===`
83
+ `&&(Ee=!0,++v),++h===b)return null;if(C(h)==="/"){if(++h===b)throw x("comment");if(C(h)==="/")if(u){if(Pe=h,Ie=!1,D(h-1)){Ie=!0;do if(h=U(h),h===b||(h++,!Ee))break;while(D(h))}else h=Math.min(b,U(h)+1);Ie&&(O(Pe,h,Ee),Ee=!0),v++,de=!0}else{for(Ie=C(Pe=h+1)==="/";C(++h)!==`
84
+ `;)if(h===b)return null;++h,Ie&&(O(Pe,h-1,Ee),Ee=!0),++v,de=!0}else if((ve=C(h))==="*"){Pe=h+1,Ie=u||C(Pe)==="*";do{if(ve===`
85
+ `&&++v,++h===b)throw x("comment");Se=ve,ve=C(h)}while(Se!=="*"||ve!=="/");++h,Ie&&(O(Pe,h-2,Ee),Ee=!0),de=!0}else return"/"}}while(de);var De=h;delimRe.lastIndex=0;var be=delimRe.test(C(De++));if(!be)for(;De<b&&!delimRe.test(C(De));)++De;var B=y.substring(h,h=De);return(B==='"'||B==="'")&&(S=B),B}function X(de){E.push(de)}function ie(){if(!E.length){var de=te();if(de===null)return null;X(de)}return E[0]}function ee(de,Se){var ve=ie(),Pe=ve===de;if(Pe)return te(),!0;if(!Se)throw x("token '"+ve+"', '"+de+"' expected");return!1}function ae(de){var Se=null,ve;return de===void 0?(ve=_[v-1],delete _[v-1],ve&&(u||ve.type==="*"||ve.lineEmpty)&&(Se=ve.leading?ve.text:null)):(w<de&&ie(),ve=_[de],delete _[de],ve&&!ve.lineEmpty&&(u||ve.type==="/")&&(Se=ve.leading?null:ve.text)),Se}return Object.defineProperty({next:te,peek:ie,push:X,skip:ee,cmnt:ae},"line",{get:function(){return v}})}var parse_1=parse;parse.filename=null;parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),ReflectionObject=requireObject(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function parse(y,u,h){u instanceof Root||(h=u,u=new Root),h||(h=parse.defaults);var b=h.preferTrailingComment||!1,v=tokenize(y,h.alternateCommentMode||!1),w=v.next,_=v.push,E=v.peek,S=v.skip,x=v.cmnt,T=!0,C,O,D,U="proto2",te=u,X=[],ie={},ee=h.keepCase?function(ce){return ce}:util.camelCase;function ae(){X.forEach(ce=>{ce._edition=U,Object.keys(ie).forEach(_e=>{ce.getOption(_e)===void 0&&ce.setOption(_e,ie[_e],!0)})})}function de(ce,_e,Re){var Ue=parse.filename;return Re||(parse.filename=null),Error("illegal "+(_e||"token")+" '"+ce+"' ("+(Ue?Ue+", ":"")+"line "+v.line+")")}function Se(){var ce=[],_e;do{if((_e=w())!=='"'&&_e!=="'")throw de(_e);ce.push(w()),S(_e),_e=E()}while(_e==='"'||_e==="'");return ce.join("")}function ve(ce){var _e=w();switch(_e){case"'":case'"':return _(_e),Se();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Ie(_e,!0)}catch{if(typeRefRe.test(_e))return _e;throw de(_e,"value")}}function Pe(ce,_e){var Re,Ue;do if(_e&&((Re=E())==='"'||Re==="'")){var qe=Se();if(ce.push(qe),U>=2023)throw de(qe,"id")}else try{ce.push([Ue=Ee(w()),S("to",!0)?Ee(w()):Ue])}catch(tt){if(_e&&typeRefRe.test(Re)&&U>=2023)ce.push(Re);else throw tt}while(S(",",!0));var Ze={options:void 0};Ze.setOption=function(tt,Fe){this.options===void 0&&(this.options={}),this.options[tt]=Fe},N(Ze,function(Fe){if(Fe==="option")he(Ze,Fe),S(";");else throw de(Fe)},function(){le(Ze)})}function Ie(ce,_e){var Re=1;switch(ce.charAt(0)==="-"&&(Re=-1,ce=ce.substring(1)),ce){case"inf":case"INF":case"Inf":return Re*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(ce))return Re*parseInt(ce,10);if(base16Re.test(ce))return Re*parseInt(ce,16);if(base8Re.test(ce))return Re*parseInt(ce,8);if(numberRe.test(ce))return Re*parseFloat(ce);throw de(ce,"number",_e)}function Ee(ce,_e){switch(ce){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!_e&&ce.charAt(0)==="-")throw de(ce,"id");if(base10NegRe.test(ce))return parseInt(ce,10);if(base16NegRe.test(ce))return parseInt(ce,16);if(base8NegRe.test(ce))return parseInt(ce,8);throw de(ce,"id")}function De(){if(C!==void 0)throw de("package");if(C=w(),!typeRefRe.test(C))throw de(C,"name");te=te.define(C),S(";")}function be(){var ce=E(),_e;switch(ce){case"weak":_e=D||(D=[]),w();break;case"public":w();default:_e=O||(O=[]);break}ce=Se(),S(";"),_e.push(ce)}function B(){if(S("="),U=Se(),U<2023)throw de(U,"syntax");S(";")}function F(){if(S("="),U=Se(),!["2023"].includes(U))throw de(U,"edition");S(";")}function M(ce,_e){switch(_e){case"option":return he(ce,_e),S(";"),!0;case"message":return Q(ce,_e),!0;case"enum":return re(ce,_e),!0;case"service":return me(ce,_e),!0;case"extend":return fe(ce,_e),!0}return!1}function N(ce,_e,Re){var Ue=v.line;if(ce&&(typeof ce.comment!="string"&&(ce.comment=x()),ce.filename=parse.filename),S("{",!0)){for(var qe;(qe=w())!=="}";)_e(qe);S(";",!0)}else Re&&Re(),S(";"),ce&&(typeof ce.comment!="string"||b)&&(ce.comment=x(Ue)||ce.comment)}function Q(ce,_e){if(!nameRe.test(_e=w()))throw de(_e,"type name");var Re=new Type(_e);N(Re,function(qe){if(!M(Re,qe))switch(qe){case"map":J(Re);break;case"required":if(U!=="proto2")throw de(qe);case"repeated":j(Re,qe);break;case"optional":if(U==="proto3")j(Re,"proto3_optional");else{if(U!=="proto2")throw de(qe);j(Re,"optional")}break;case"oneof":q(Re,qe);break;case"extensions":Pe(Re.extensions||(Re.extensions=[]));break;case"reserved":Pe(Re.reserved||(Re.reserved=[]),!0);break;default:if(U==="proto2"||!typeRefRe.test(qe))throw de(qe);_(qe),j(Re,"optional");break}}),ce.add(Re),ce===te&&X.push(Re)}function j(ce,_e,Re){var Ue=w();if(Ue==="group"){ne(ce,_e);return}for(;Ue.endsWith(".")||E().startsWith(".");)Ue+=w();if(!typeRefRe.test(Ue))throw de(Ue,"type");var qe=w();if(!nameRe.test(qe))throw de(qe,"name");qe=ee(qe),S("=");var Ze=new Field(qe,Ee(w()),Ue,_e,Re);if(N(Ze,function(nt){if(nt==="option")he(Ze,nt),S(";");else throw de(nt)},function(){le(Ze)}),_e==="proto3_optional"){var tt=new OneOf("_"+qe);Ze.setOption("proto3_optional",!0),tt.add(Ze),ce.add(tt)}else ce.add(Ze);ce===te&&X.push(Ze)}function ne(ce,_e){if(U>=2023)throw de("group");var Re=w();if(!nameRe.test(Re))throw de(Re,"name");var Ue=util.lcFirst(Re);Re===Ue&&(Re=util.ucFirst(Re)),S("=");var qe=Ee(w()),Ze=new Type(Re);Ze.group=!0;var tt=new Field(Ue,qe,Re,_e);tt.filename=parse.filename,N(Ze,function(nt){switch(nt){case"option":he(Ze,nt),S(";");break;case"required":case"repeated":j(Ze,nt);break;case"optional":U==="proto3"?j(Ze,"proto3_optional"):j(Ze,"optional");break;case"message":Q(Ze,nt);break;case"enum":re(Ze,nt);break;case"reserved":Pe(Ze.reserved||(Ze.reserved=[]),!0);break;default:throw de(nt)}}),ce.add(Ze).add(tt)}function J(ce){S("<");var _e=w();if(types.mapKey[_e]===void 0)throw de(_e,"type");S(",");var Re=w();if(!typeRefRe.test(Re))throw de(Re,"type");S(">");var Ue=w();if(!nameRe.test(Ue))throw de(Ue,"name");S("=");var qe=new MapField(ee(Ue),Ee(w()),_e,Re);N(qe,function(tt){if(tt==="option")he(qe,tt),S(";");else throw de(tt)},function(){le(qe)}),ce.add(qe)}function q(ce,_e){if(!nameRe.test(_e=w()))throw de(_e,"name");var Re=new OneOf(ee(_e));N(Re,function(qe){qe==="option"?(he(Re,qe),S(";")):(_(qe),j(Re,"optional"))}),ce.add(Re)}function re(ce,_e){if(!nameRe.test(_e=w()))throw de(_e,"name");var Re=new Enum(_e);N(Re,function(qe){switch(qe){case"option":he(Re,qe),S(";");break;case"reserved":Pe(Re.reserved||(Re.reserved=[]),!0),Re.reserved===void 0&&(Re.reserved=[]);break;default:H(Re,qe)}}),ce.add(Re),ce===te&&X.push(Re)}function H(ce,_e){if(!nameRe.test(_e))throw de(_e,"name");S("=");var Re=Ee(w(),!0),Ue={options:void 0};Ue.getOption=function(qe){return this.options[qe]},Ue.setOption=function(qe,Ze){ReflectionObject.prototype.setOption.call(Ue,qe,Ze)},Ue.setParsedOption=function(){},N(Ue,function(Ze){if(Ze==="option")he(Ue,Ze),S(";");else throw de(Ze)},function(){le(Ue)}),ce.add(_e,Re,Ue.comment,Ue.parsedOptions||Ue.options)}function he(ce,_e){var Re,Ue,qe=!0;for(_e==="option"&&(_e=w());_e!=="=";){if(_e==="("){var Ze=w();S(")"),_e="("+Ze+")"}if(qe){if(qe=!1,_e.includes(".")&&!_e.includes("(")){var tt=_e.split(".");Re=tt[0]+".",_e=tt[1];continue}Re=_e}else Ue=Ue?Ue+=_e:_e;_e=w()}var Fe=Ue?Re.concat(Ue):Re,nt=Oe(ce,Fe);Ue=Ue&&Ue[0]==="."?Ue.slice(1):Ue,Re=Re&&Re[Re.length-1]==="."?Re.slice(0,-1):Re,Ae(ce,Re,nt,Ue)}function Oe(ce,_e){if(S("{",!0)){for(var Re={};!S("}",!0);){if(!nameRe.test(ge=w()))throw de(ge,"name");if(ge===null)throw de(ge,"end of input");var Ue,qe=ge;if(S(":",!0),E()==="{")Ue=Oe(ce,_e+"."+ge);else if(E()==="["){Ue=[];var Ze;if(S("[",!0)){do Ze=ve(),Ue.push(Ze);while(S(",",!0));S("]"),typeof Ze<"u"&&Ne(ce,_e+"."+ge,Ze)}}else Ue=ve(),Ne(ce,_e+"."+ge,Ue);var tt=Re[qe];tt&&(Ue=[].concat(tt).concat(Ue)),Re[qe]=Ue,S(",",!0),S(";",!0)}return Re}var Fe=ve();return Ne(ce,_e,Fe),Fe}function Ne(ce,_e,Re){if(te===ce&&/^features\./.test(_e)){ie[_e]=Re;return}ce.setOption&&ce.setOption(_e,Re)}function Ae(ce,_e,Re,Ue){ce.setParsedOption&&ce.setParsedOption(_e,Re,Ue)}function le(ce){if(S("[",!0)){do he(ce,"option");while(S(",",!0));S("]")}return ce}function me(ce,_e){if(!nameRe.test(_e=w()))throw de(_e,"service name");var Re=new Service(_e);N(Re,function(qe){if(!M(Re,qe))if(qe==="rpc")Me(Re,qe);else throw de(qe)}),ce.add(Re),ce===te&&X.push(Re)}function Me(ce,_e){var Re=x(),Ue=_e;if(!nameRe.test(_e=w()))throw de(_e,"name");var qe=_e,Ze,tt,Fe,nt;if(S("("),S("stream",!0)&&(tt=!0),!typeRefRe.test(_e=w())||(Ze=_e,S(")"),S("returns"),S("("),S("stream",!0)&&(nt=!0),!typeRefRe.test(_e=w())))throw de(_e);Fe=_e,S(")");var it=new Method(qe,Ue,Ze,Fe,tt,nt);it.comment=Re,N(it,function(ct){if(ct==="option")he(it,ct),S(";");else throw de(ct)}),ce.add(it)}function fe(ce,_e){if(!typeRefRe.test(_e=w()))throw de(_e,"reference");var Re=_e;N(null,function(qe){switch(qe){case"required":case"repeated":j(ce,qe,Re);break;case"optional":U==="proto3"?j(ce,"proto3_optional",Re):j(ce,"optional",Re);break;default:if(U==="proto2"||!typeRefRe.test(qe))throw de(qe);_(qe),j(ce,"optional",Re);break}})}for(var ge;(ge=w())!==null;)switch(ge){case"package":if(!T)throw de(ge);De();break;case"import":if(!T)throw de(ge);be();break;case"syntax":if(!T)throw de(ge);B();break;case"edition":if(!T)throw de(ge);F();break;case"option":he(te,ge),S(";",!0);break;default:if(M(te,ge)){T=!1;continue}throw de(ge)}return ae(),parse.filename=null,{package:C,imports:O,weakImports:D,root:u}}var common_1=common,commonRe=/\/|\./;function common(y,u){commonRe.test(y)||(y="google/protobuf/"+y+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),common[y]=u}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});common("timestamp",{Timestamp:timeType});common("empty",{Empty:{fields:{}}});common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});common.get=function y(u){return common[u]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full";protobuf$1.tokenize=tokenize_1;protobuf$1.parse=parse_1;protobuf$1.common=common_1;protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs$1(protobufjs),{load}=protobuf;let protoRoot=null,messagePayloadType=null;async function initializeProtobuf(){protoRoot||(protoRoot=await load(path$1.join(__dirname,"../waku/message.proto")),protoRoot.resolveAll(),messagePayloadType=protoRoot.lookupType("MessagePayload"))}async function decodeMessagePayload(y){if(await initializeProtobuf(),!messagePayloadType)throw new Error("MessagePayload type not initialized");const u={0:"text",1:"thread",2:"reaction"};try{const h=messagePayloadType.decode(y),b=messagePayloadType.toObject(h),v={...b.message,type:u[b.message.type]??"text"},w=b.messageStateRefs||[];return{message:v,messageStateRefs:w}}catch(h){throw new Error(`Failed to decode message payload: ${h}`)}}class Waku{constructor(u,h,b){this.logger=Logger$2.getInstance(),this.wakuNode=null,this.handleWakuMessage=async({payload:v})=>{try{if(!v)return this.logger.warn("Received Waku message without payload");const{message:w}=await decodeMessagePayload(v);if(!(w!=null&&w.id))return this.logger.warn("Received invalid message structure via Waku");this.onMessage(w)}catch(w){this.logger.error("Failed to decode Waku message:",w)}},this.chatTopic=u,this.onMessage=h,this.wakuNode=b||null,this.initPromise=this.init()}async init(){if(this.wakuNode=this.wakuNode??await this.createWakuLightNode(),!await this.subscribeToTopic())throw new Error("Failed to subscribe to Waku topic");this.logger.info(`Subscribed to Waku topic: ${this.chatTopic}`)}async createWakuLightNode(){const u=await createLightNode({defaultBootstrap:!0,networkConfig:{clusterId:WAKU_CLUSTER_ID}});return await u.start(),await u.waitForPeers([Protocols.LightPush,Protocols.Filter],3e4),this.logger.info(`Waku node ready: ${u.libp2p.peerId.toString()}`),u}createWakuDecoder(u){if(!(u!=null&&u.trim()))throw new Error("Topic name must be a non-empty string");const h=cryptoBrowserifyExports.createHash("sha256").update(u).digest("hex"),b=Number(BigInt("0x"+h)%8n);return createDecoder(`solarpunk-msrs/1/${u}/proto`,{clusterId:WAKU_CLUSTER_ID,shardId:b,pubsubTopic:`/waku/2/rs/${WAKU_CLUSTER_ID}/${b}`})}async subscribeToTopic(){var u;if(!((u=this.wakuNode)!=null&&u.isStarted()))throw new Error("Waku node is not running");return this.wakuNode.filter.subscribe(this.createWakuDecoder(this.chatTopic),this.handleWakuMessage)}async isReady(){var u;try{return await this.initPromise,((u=this.wakuNode)==null?void 0:u.isStarted())??!1}catch{return!1}}async stop(){try{await this.initPromise,this.wakuNode&&(await this.wakuNode.stop(),this.wakuNode=null,this.logger.info("Waku node stopped successfully"))}catch(u){throw this.logger.error("Error stopping Waku node:",u),u}}}class SwarmHistory{constructor(u,h){this.utils=u,this.emitter=h,this.logger=Logger$2.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.processedRefs=new Set,this.refRetryCount=new Map,this.bannedRefs=new Set,this.latestStatefulMessage=null,this.MAX_RETRIES=3,this.RETRY_DELAY=1e3}async init(){try{const{data:u,index:h}=await this.utils.fetchLatestChatMessage();this.latestStatefulMessage=u;try{await this.initMessageState(u)}catch(b){this.errorHandler.handleError(b,"SwarmHistory.initMessageState")}return h}catch(u){return this.errorHandler.handleError(u,"SwarmHistory.init"),beeJs.FeedIndex.fromBigInt(0n)}}async initMessageState(u){try{if(!validateGsocMessage(u)){this.logger.warn("Invalid GSOC message during message state initialization");return}if(!u.messageStateRefs||u.messageStateRefs.length===0){this.logger.debug("No message state refs to initialize");return}const h=this.findLatestRef(u.messageStateRefs);if(!h){this.logger.warn("No valid latest reference found");return}this.logger.debug("Initializing message state with latest ref:",h.reference),await this.processMessageRefWithRetry(h.reference)}catch(h){if(this.utils.isNotFoundError(h)){this.logger.debug("No latest GSOC message found for message state initialization");return}this.errorHandler.handleError(h,"SwarmHistory.init")}}async fetchPreviousMessageState(){let u=this.latestStatefulMessage;if(!u){const{data:b}=await this.utils.fetchLatestChatMessage();u=b,this.latestStatefulMessage=b}if(!u.messageStateRefs||u.messageStateRefs.length===0){this.logger.debug("No message state refs to fetch");return}const h=[...u.messageStateRefs].sort((b,v)=>b.timestamp-v.timestamp);for(const b of h)!this.processedRefs.has(b.reference)&&!this.bannedRefs.has(b.reference)&&(this.logger.debug("Fetching previous message ref:",b.reference),await this.processMessageRefWithRetry(b.reference))}findLatestRef(u){return u.length===0?null:u.reduce((h,b)=>b.timestamp>h.timestamp?b:h)}async processMessageRefWithRetry(u){if(!(this.processedRefs.has(u)||this.bannedRefs.has(u)))try{await this.processMessageRef(u)}catch(h){await this.handleRefError(u,h)}}async processMessageRef(u){const h=await this.utils.downloadObjectFromBee(u);if(!validateMessageState(h))throw new Error(`Invalid message state for ref: ${u}`);this.processedRefs.add(u),this.refRetryCount.delete(u);for(const v of h)this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)}async handleRefError(u,h){const b=this.refRetryCount.get(u)||0,v=b+1;if(this.logger.warn(`Error processing ref ${u} (attempt ${v}/${this.MAX_RETRIES}):`,h),v>=this.MAX_RETRIES)this.bannedRefs.add(u),this.refRetryCount.delete(u),this.logger.error(`Ref ${u} has been banned after ${this.MAX_RETRIES} failed attempts`),this.errorHandler.handleError(h,"SwarmHistory.processMessageRef");else{this.refRetryCount.set(u,v);const w=this.RETRY_DELAY*Math.pow(2,b);this.logger.debug(`Retrying ref ${u} after ${w}ms delay`),await sleep(w),await this.processMessageRefWithRetry(u)}}hasPreviousMessages(){return!!this.latestStatefulMessage&&!!this.latestStatefulMessage.messageStateRefs&&this.latestStatefulMessage.messageStateRefs.length>1}cleanup(){this.processedRefs.clear(),this.refRetryCount.clear(),this.bannedRefs.clear(),this.latestStatefulMessage=null}}class SwarmChatUtils{constructor(u,h){this.userDetails=u,this.swarmSettings=h,this.depth=26,this.errorHandler=ErrorHandler.getInstance(),this.UPLOAD_GSOC_TIMEOUT=2e3}generateUserOwnedFeedId(u,h){return`${u}_EthercastChat_${h}`}isNotFoundError(u){return u.stack.includes("404")||u.message.includes("Not Found")||u.message.includes("404")||u.code===404}async writeOwnFeedDataByIndex(u,h){const{enveloped:b,stamp:v}=this.swarmSettings;if(!b)await this.writeOwnFeedDataByIndexOwned(u,h);else if(v)await this.writeOwnFeedDataByIndexEnvelope(u,h);else throw new Error("Enveloped mode is enabled, but stamp is not provided")}async writeOwnFeedDataByIndexOwned(u,h){const{bee:b,stamp:v,chatTopic:w}=this.swarmSettings,{privateKey:_,ownAddress:E}=this.userDetails,S=this.generateUserOwnedFeedId(w,E),x=beeJs.Topic.fromString(S);await b.makeFeedWriter(x,new beeJs.PrivateKey(_)).uploadPayload(v,JSON.stringify(h),{index:u})}async writeOwnFeedDataByIndexEnvelope(u,h){const{bee:b,stamp:v,chatTopic:w}=this.swarmSettings,{privateKey:_,ownAddress:E}=this.userDetails,S=new beeJs.PrivateKey(_),x=beeJs.Stamper.fromBlank(_,v,this.depth),T=this.generateUserOwnedFeedId(w,E),C=beeJs.Topic.fromString(T),O=makeFeedIdentifier(C,u),D=makeContentAddressedChunk(h),U=makeSingleOwnerChunk(D,O,S),te={hash:()=>U.address.toUint8Array()},X=x.stamp(te),{upload:ie}=b.makeSOCWriter(S),ee=beeJs.Bytes.fromUtf8(h);return(await ie(X,O,ee.toUint8Array())).reference.toHex()}orderMessages(u){return u.sort((h,b)=>h.timestamp-b.timestamp)}async downloadObjectFromBee(u){try{const{bee:h}=this.swarmSettings,b=await h.downloadData(u);return b?b.toJSON():null}catch(h){return this.errorHandler.handleError(h,"Utils.downloadObjectFromBee"),null}}async uploadObjectToBee(u){const{enveloped:h,stamp:b}=this.swarmSettings;if(h){if(b)return this.uploadObjectToBeeEnvelope(u);throw new Error("Enveloped mode is enabled, but stamp is not provided")}else return this.uploadObjectToBeeOwn(u)}async uploadObjectToBeeOwn(u){try{const{bee:h,stamp:b}=this.swarmSettings;return(await h.uploadData(b,JSON.stringify(u),{redundancyLevel:4})).reference.toString()}catch(h){return this.errorHandler.handleError(h,"Utils.uploadObjectToBee"),null}}async uploadObjectToBeeEnvelope(u){try{const{bee:h,stamp:b}=this.swarmSettings,{privateKey:v}=this.userDetails,w=beeJs.Stamper.fromBlank(v,b,this.depth),_=beeJs.Bytes.fromUtf8(JSON.stringify(u)),E=new MerkleTree(async x=>{await h.uploadChunk(w.stamp(x),x.build())});await E.append(_.toUint8Array());const S=await E.finalize();return Binary.uint8ArrayToHex(S.hash())}catch(h){return this.errorHandler.handleError(h,"Utils.uploadObjectToBee"),null}}async getOwnLatestFeedIndex(){try{const{bee:u,chatTopic:h}=this.swarmSettings,{ownAddress:b}=this.userDetails,v=this.generateUserOwnedFeedId(h,b),w=beeJs.Topic.fromString(v),E=await u.makeFeedReader(w,b).downloadPayload(),S=Number(E.feedIndex.toBigInt()),x=S+1;return{latestIndex:S,nextIndex:x}}catch(u){if(this.isNotFoundError(u))return{latestIndex:-1,nextIndex:0};throw u}}async fetchLatestChatMessage(){const{bee:u,chatTopic:h,chatAddress:b}=this.swarmSettings,w=await u.makeFeedReader(beeJs.Topic.fromString(h),remove0x(b)).downloadPayload();return{data:w.payload.toJSON(),index:w.feedIndex}}async fetchChatMessage(u){const{bee:h,chatTopic:b,chatAddress:v}=this.swarmSettings;return(await h.makeFeedReader(beeJs.Topic.fromString(b),remove0x(v)).downloadPayload({index:u})).payload.toJSON()}async sendMessageToGsoc(u){const{enveloped:h,stamp:b}=this.swarmSettings;if(!h)await this.sendMessageToGsocOwn(u);else if(b)await this.sendMessageToGsocEnvelope(u);else throw new Error("Enveloped mode is enabled, but stamp is not provided")}async rawSocDownload(u,h){const{beeUrl:b}=this.swarmSettings,v=await fetch(`${b}/soc/${u}/${h}`,{headers:{"swarm-chunk-retrieval-timeout":"2000ms"}});if(!v.ok){const w=new Error(`Failed to fetch: ${u}/${h} [${v.status}]`);throw w.status=v.status,w}return v.text()}async sendMessageToGsocOwn(u){const{bee:h,stamp:b,gsocTopic:v,gsocResourceId:w}=this.swarmSettings,_=new beeJs.PrivateKey(w),E=beeJs.Identifier.fromString(v),S=beeJs.Bytes.fromUtf8(u),{upload:x}=h.makeSOCWriter(_,{timeout:this.UPLOAD_GSOC_TIMEOUT});await x(b,E,S.toUint8Array())}async sendMessageToGsocEnvelope(u){const{bee:h,stamp:b,gsocTopic:v,gsocResourceId:w}=this.swarmSettings,{privateKey:_}=this.userDetails,E=beeJs.Stamper.fromBlank(_,b,this.depth),S=new beeJs.PrivateKey(w),x=beeJs.Identifier.fromString(v),T=beeJs.Bytes.fromUtf8(u),C=makeContentAddressedChunk(T.toUint8Array()),O=makeSingleOwnerChunk(C,x,S),D={hash:()=>O.address.toUint8Array()},U=E.stamp(D),{upload:te}=h.makeSOCWriter(S,{timeout:this.UPLOAD_GSOC_TIMEOUT});await te(U,x,T.toUint8Array())}}class SwarmChat{constructor(u){this.waku=null,this.isExternalWakuNode=!1,this.logger=Logger$2.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const h=new beeJs.PrivateKey(remove0x(u.user.privateKey));this.userDetails={privateKey:u.user.privateKey,ownAddress:h.publicKey().address().toString(),nickname:u.user.nickname,ownIndex:-1},this.swarmSettings={bee:new beeJs.Bee(u.infra.beeUrl),beeUrl:u.infra.beeUrl,stamp:u.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:u.infra.enveloped,gsocTopic:u.infra.gsocTopic,gsocResourceId:u.infra.gsocResourceId,chatTopic:u.infra.chatTopic,chatAddress:u.infra.chatAddress,waku:u.infra.waku},this.emitter=new EventEmitter$3,this.utils=new SwarmChatUtils(this.userDetails,this.swarmSettings),this.history=new SwarmHistory(this.utils,this.emitter)}async start(){await this.init(),await this.startMessageFetchProcess()}async startMessageFetchProcess(){const{waku:u}=this.swarmSettings;u!=null&&u.enabled?await this.startWakuMessageFetch(u.node):await this.startPollingMessageFetch()}stop(){this.emitter.cleanAll(),this.stopPollingMessageFetch(),this.history.cleanup(),this.waku&&!this.isExternalWakuNode&&this.waku.stop(),this.waku=null}async startWakuMessageFetch(u){this.logger.info("Waku is enabled"),u&&(this.isExternalWakuNode=!0,this.logger.info("Using external Waku node instance"));const h=this.swarmSettings.chatTopic;if(this.waku=new Waku(h,v=>{this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)},u),!await this.waku.isReady())throw new Error("Waku node is not reachable")}getEmitter(){return this.emitter}orderMessages(u){return this.utils.orderMessages(u)}async sendMessage(u,h,b,v,w){const _=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,E={id:v||v4$1(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(u),timestamp:Date.now(),index:_,type:h,targetMessageId:b,message:u,additionalProps:w},S=validateMessageWithAdditionalProperties(E);if(!S.isValid){const x=`Invalid message: ${S.errors.join(", ")}`;throw this.logger.error(x),new Error(x)}try{this.emitter.emit(EVENTS.MESSAGE_REQUEST_INITIATED,E),await this.utils.writeOwnFeedDataByIndex(_,JSON.stringify(E)),this.userDetails.ownIndex=_,this.emitter.emit(EVENTS.MESSAGE_REQUEST_UPLOADED,E),await this.broadcastUserMessage(E)}catch(x){this.emitter.emit(EVENTS.MESSAGE_REQUEST_ERROR,E),this.errorHandler.handleError(x,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(u){this.sendMessage(u.message,u.type,u.targetMessageId,u.id,u.additionalProps)}async retryBroadcastUserMessage(u){await this.broadcastUserMessage(u)}async init(){try{this.emitter.emit(EVENTS.LOADING_INIT,!0);const[u,h]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(u.status==="rejected")throw u.reason;h.status==="fulfilled"&&(this.gsocIndex=h.value),this.emitter.emit(EVENTS.LOADING_INIT,!1)}catch(u){this.errorHandler.handleError(u,"Chat.initSelfState"),this.emitter.emit(EVENTS.CRITICAL_ERROR,u)}}async initOwnIndex(){const{latestIndex:b}=await retryAwaitableAsync(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=b}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const u=beeJs.Topic.fromString(this.swarmSettings.chatTopic),h=makeFeedIdentifier(u,this.gsocIndex),b=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,h.toString()),v=JSON.parse(b);if(!validateGsocMessage(v)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v.message),this.gsocIndex=this.gsocIndex.next()}catch(u){if(this.utils.isNotFoundError(u))return;this.errorHandler.handleError(u,"Chat.fetchLatestMessage")}}async broadcastUserMessage(u){try{return retryAwaitableAsync(()=>this.utils.sendMessageToGsoc(JSON.stringify(u)))}catch(h){this.errorHandler.handleError(h,"Chat.broadcastUserMessage")}}getSignature(u){const{ownAddress:h,privateKey:b,nickname:v}=this.userDetails,w=new beeJs.EthAddress(h).toString(),_=new beeJs.PrivateKey(b);if(_.publicKey().address().toString()!==w)throw new Error("The provided address does not match the address derived from the private key");const S=Date.now();return _.sign(JSON.stringify({username:v,address:w,message:u,timestamp:S})).toHex()}async startPollingMessageFetch(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const u=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(u,200)};u()}stopPollingMessageFetch(){this.stopFetch=!0}}exports.EVENTS=EVENTS;exports.MessageType=MessageType;exports.SwarmChat=SwarmChat;