UNPKG

@liascript/exporter

Version:
1 lines โ€ข 697 kB
var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{};function t(e,t,r,n){Object.defineProperty(e,t,{get:r,set:n,enumerable:!0,configurable:!0})}var r=e.parcelRequire55a5;r.register("62kvE",(function(n,i){t(n.exports,"selfId",(function(){return bC})),t(n.exports,"joinRoom",(function(){return ek}));var s,o,a,l,u,c,d,h,f,p,g,m,v,y,b,w,E,S,A,I,_,C=r("e963W"),k=r("lvOWe"),x=r("ezKE5"),T=r("dpALB"),P=r("1VQD5"),R=r("cJcuy"),L=r("2Xs1f"),D=r("dM3DM"),M=r("aQXMn");let N,O,U,F;var B,$,q,z,j,K,V,H,W,G,X=r("jhEmn");function Z(e=0){return new Uint8Array(e)}function Y(e=0){return new Uint8Array(e)}const Q=268435456,J=34359738368,ee=4398046511104,te=Math.pow(2,49),re=128,ne=127;function ie(e){if(e<128)return 1;if(e<16384)return 2;if(e<2097152)return 3;if(e<Q)return 4;if(e<J)return 5;if(e<ee)return 6;if(e<te)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function se(e,t,r=0){switch(ie(e)){case 8:t[r++]=255&e|re,e/=128;case 7:t[r++]=255&e|re,e/=128;case 6:t[r++]=255&e|re,e/=128;case 5:t[r++]=255&e|re,e/=128;case 4:t[r++]=255&e|re,e>>>=7;case 3:t[r++]=255&e|re,e>>>=7;case 2:t[r++]=255&e|re,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw Error("unreachable")}return t}function oe(e,t){let r=e[t],n=0;if(n+=r&ne,r<re)return n;if(r=e[t+1],n+=(r&ne)<<7,r<re)return n;if(r=e[t+2],n+=(r&ne)<<14,r<re)return n;if(r=e[t+3],n+=(r&ne)<<21,r<re)return n;if(r=e[t+4],n+=(r&ne)*Q,r<re)return n;if(r=e[t+5],n+=(r&ne)*J,r<re)return n;if(r=e[t+6],n+=(r&ne)*ee,r<re)return n;if(r=e[t+7],n+=(r&ne)*te,r<re)return n;throw new RangeError("Could not decode varint")}function ae(e,t,r=0){return null==t&&(t=Y(ie(e))),t instanceof Uint8Array?se(e,t,r):function(e,t,r=0){switch(ie(e)){case 8:t.set(r++,255&e|re),e/=128;case 7:t.set(r++,255&e|re),e/=128;case 6:t.set(r++,255&e|re),e/=128;case 5:t.set(r++,255&e|re),e/=128;case 4:t.set(r++,255&e|re),e>>>=7;case 3:t.set(r++,255&e|re),e>>>=7;case 2:t.set(r++,255&e|re),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw Error("unreachable")}return t}(e,t,r)}function le(e,t=0){return e instanceof Uint8Array?oe(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&ne,r<re)return n;if(r=e.get(t+1),n+=(r&ne)<<7,r<re)return n;if(r=e.get(t+2),n+=(r&ne)<<14,r<re)return n;if(r=e.get(t+3),n+=(r&ne)<<21,r<re)return n;if(r=e.get(t+4),n+=(r&ne)*Q,r<re)return n;if(r=e.get(t+5),n+=(r&ne)*J,r<re)return n;if(r=e.get(t+6),n+=(r&ne)*ee,r<re)return n;if(r=e.get(t+7),n+=(r&ne)*te,r<re)return n;throw new RangeError("Could not decode varint")}(e,t)}const ue=new Float32Array([-0]),ce=new Uint8Array(ue.buffer);function de(e,t,r){ue[0]=e,t[r]=ce[0],t[r+1]=ce[1],t[r+2]=ce[2],t[r+3]=ce[3]}const he=new Float64Array([-0]),fe=new Uint8Array(he.buffer);function pe(e,t,r){he[0]=e,t[r]=fe[0],t[r+1]=fe[1],t[r+2]=fe[2],t[r+3]=fe[3],t[r+4]=fe[4],t[r+5]=fe[5],t[r+6]=fe[6],t[r+7]=fe[7]}const ge=BigInt(Number.MAX_SAFE_INTEGER),me=BigInt(Number.MIN_SAFE_INTEGER);class ve{toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return ye;if(e<ge&&e>me)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>be&&(n=0n,++r>be&&(r=0n))),new ve(Number(n),Number(r))}static fromNumber(e){if(0===e)return ye;const t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new ve(r,n)}static from(e){return"number"==typeof e?ve.fromNumber(e):"bigint"==typeof e?ve.fromBigInt(e):"string"==typeof e?ve.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new ve(e.low>>>0,e.high>>>0):ye}constructor(e,t){(0,L.default)(this,"lo",void 0),(0,L.default)(this,"hi",void 0),this.lo=0|e,this.hi=0|t}}const ye=new ve(0,0);ye.toBigInt=()=>0n,ye.zzEncode=ye.zzDecode=function(){return this},ye.length=()=>1;const be=4294967296n;function we(e,t,r){const n=r;let i,s;for(let n=0;n<e.length;++n)i=e.charCodeAt(n),i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=e.charCodeAt(n+1)))?(i=65536+((1023&i)<<10)+(1023&s),++n,t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128);return r-n}function Ee(e,t){return RangeError(`index out of range: ${e.pos} + ${null!=t?t:1} > ${e.len}`)}function Se(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Ae{uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ee(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw Ee(this,4);return Se(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ee(this,4);return 0|Se(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Ee(this,4);const e=(t=this.buf,r=this.pos,ce[0]=t[r],ce[1]=t[r+1],ce[2]=t[r+2],ce[3]=t[r+3],ue[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ee(this,4);const e=(t=this.buf,r=this.pos,fe[0]=t[r],fe[1]=t[r+1],fe[2]=t[r+2],fe[3]=t[r+3],fe[4]=t[r+4],fe[5]=t[r+5],fe[6]=t[r+6],fe[7]=t[r+7],he[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw Ee(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const i=[];let s,o=0;for(;t<r;)s=e[t++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((null!=n?n:n=[]).push(String.fromCharCode.apply(String,i)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,i.slice(0,o))),n.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Ee(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Ee(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new ve(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Ee(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ee(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ee(this,8);const e=Se(this.buf,this.pos+=4),t=Se(this.buf,this.pos+=4);return new ve(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=oe(this.buf,this.pos);return this.pos+=ie(e),e}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()}constructor(e){(0,L.default)(this,"buf",void 0),(0,L.default)(this,"pos",void 0),(0,L.default)(this,"len",void 0),(0,L.default)(this,"_slice",Uint8Array.prototype.subarray),this.buf=e,this.pos=0,this.len=e.length}}function Ie(e,t,r){const n=function(e){return new Ae(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function _e(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unknown type, must be binary type")}var Ce=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(255!==r[o])throw new TypeError(s+" is ambiguous");r[o]=i}var a=e.length,l=e.charAt(0),u=Math.log(a)/Math.log(256),c=Math.log(256)/Math.log(a);function d(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,i=0;e[t]===l;)n++,t++;for(var s=(e.length-t)*u+1>>>0,o=new Uint8Array(s);e[t];){var c=r[e.charCodeAt(t)];if(255===c)return;for(var d=0,h=s-1;(0!==c||d<i)&&-1!==h;h--,d++)c+=a*o[h]>>>0,o[h]=c%256>>>0,c=c/256>>>0;if(0!==c)throw Error("Non-zero carry");i=d,t++}if(" "!==e[t]){for(var f=s-i;f!==s&&0===o[f];)f++;for(var p=new Uint8Array(n+(s-f)),g=n;f!==s;)p[g++]=o[f++];return p}}}return{encode(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,s=t.length;i!==s&&0===t[i];)i++,r++;for(var o=(s-i)*c+1>>>0,u=new Uint8Array(o);i!==s;){for(var d=t[i],h=0,f=o-1;(0!==d||h<n)&&-1!==f;f--,h++)d+=256*u[f]>>>0,u[f]=d%a>>>0,d=d/a>>>0;if(0!==d)throw Error("Non-zero carry");n=h,i++}for(var p=o-n;p!==o&&0===u[p];)p++;for(var g=l.repeat(r);p<o;++p)g+=e.charAt(u[p]);return g},decodeUnsafe:d,decode(e){var r=d(e);if(r)return r;throw Error(`Non-${t} character`)}}};let ke=class{encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}constructor(e,t,r){(0,L.default)(this,"name",void 0),(0,L.default)(this,"prefix",void 0),(0,L.default)(this,"baseEncode",void 0),this.name=e,this.prefix=t,this.baseEncode=r}},xe=class{decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Pe(this,e)}constructor(e,t,r){(0,L.default)(this,"name",void 0),(0,L.default)(this,"prefix",void 0),(0,L.default)(this,"baseDecode",void 0),(0,L.default)(this,"prefixCodePoint",void 0),this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}};class Te{or(e){return Pe(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}constructor(e){(0,L.default)(this,"decoders",void 0),this.decoders=e}}function Pe(e,t){var r,n;return new Te((0,D.default)({},null!==(r=e.decoders)&&void 0!==r?r:{[e.prefix]:e},null!==(n=t.decoders)&&void 0!==n?n:{[t.prefix]:t}))}class Re{encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}constructor(e,t,r,n){(0,L.default)(this,"name",void 0),(0,L.default)(this,"prefix",void 0),(0,L.default)(this,"baseEncode",void 0),(0,L.default)(this,"baseDecode",void 0),(0,L.default)(this,"encoder",void 0),(0,L.default)(this,"decoder",void 0),this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new ke(e,t,r),this.decoder=new xe(e,t,n)}}function Le({name:e,prefix:t,encode:r,decode:n}){return new Re(e,t,r,n)}function De({name:e,prefix:t,alphabet:r}){const{encode:n,decode:i}=Ce(r,e);return Le({prefix:t,name:e,encode:n,decode:e=>_e(i(e))})}function Me({name:e,prefix:t,bitsPerChar:r,alphabet:n}){const i=function(e){const t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(n);return Le({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],i=(1<<r)-1;let s="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>r;)o-=r,s+=t[i&a>>o];if(0!==o&&(s+=t[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s}(e,n,r),decode:t=>function(e,t,r,n){let i=e.length;for(;"="===e[i-1];)--i;const s=new Uint8Array(i*r/8|0);let o=0,a=0,l=0;for(let u=0;u<i;++u){const i=t[e[u]];if(void 0===i)throw new SyntaxError(`Non-${n} character`);a=a<<r|i,o+=r,o>=8&&(o-=8,s[l++]=255&a>>o)}if(o>=r||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return s}(t,i,r,e)})}const Ne=De({prefix:"9",name:"base10",alphabet:"0123456789"});var Oe=Object.freeze({__proto__:null,base10:Ne});const Ue=Me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Fe=Me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Be=Object.freeze({__proto__:null,base16:Ue,base16upper:Fe});const $e=Me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var qe=Object.freeze({__proto__:null,base2:$e});const ze=Array.from("๐Ÿš€๐Ÿชโ˜„๐Ÿ›ฐ๐ŸŒŒ๐ŸŒ‘๐ŸŒ’๐ŸŒ“๐ŸŒ”๐ŸŒ•๐ŸŒ–๐ŸŒ—๐ŸŒ˜๐ŸŒ๐ŸŒ๐ŸŒŽ๐Ÿ‰โ˜€๐Ÿ’ป๐Ÿ–ฅ๐Ÿ’พ๐Ÿ’ฟ๐Ÿ˜‚โค๐Ÿ˜๐Ÿคฃ๐Ÿ˜Š๐Ÿ™๐Ÿ’•๐Ÿ˜ญ๐Ÿ˜˜๐Ÿ‘๐Ÿ˜…๐Ÿ‘๐Ÿ˜๐Ÿ”ฅ๐Ÿฅฐ๐Ÿ’”๐Ÿ’–๐Ÿ’™๐Ÿ˜ข๐Ÿค”๐Ÿ˜†๐Ÿ™„๐Ÿ’ช๐Ÿ˜‰โ˜บ๐Ÿ‘Œ๐Ÿค—๐Ÿ’œ๐Ÿ˜”๐Ÿ˜Ž๐Ÿ˜‡๐ŸŒน๐Ÿคฆ๐ŸŽ‰๐Ÿ’žโœŒโœจ๐Ÿคท๐Ÿ˜ฑ๐Ÿ˜Œ๐ŸŒธ๐Ÿ™Œ๐Ÿ˜‹๐Ÿ’—๐Ÿ’š๐Ÿ˜๐Ÿ’›๐Ÿ™‚๐Ÿ’“๐Ÿคฉ๐Ÿ˜„๐Ÿ˜€๐Ÿ–ค๐Ÿ˜ƒ๐Ÿ’ฏ๐Ÿ™ˆ๐Ÿ‘‡๐ŸŽถ๐Ÿ˜’๐Ÿคญโฃ๐Ÿ˜œ๐Ÿ’‹๐Ÿ‘€๐Ÿ˜ช๐Ÿ˜‘๐Ÿ’ฅ๐Ÿ™‹๐Ÿ˜ž๐Ÿ˜ฉ๐Ÿ˜ก๐Ÿคช๐Ÿ‘Š๐Ÿฅณ๐Ÿ˜ฅ๐Ÿคค๐Ÿ‘‰๐Ÿ’ƒ๐Ÿ˜ณโœ‹๐Ÿ˜š๐Ÿ˜๐Ÿ˜ด๐ŸŒŸ๐Ÿ˜ฌ๐Ÿ™ƒ๐Ÿ€๐ŸŒท๐Ÿ˜ป๐Ÿ˜“โญโœ…๐Ÿฅบ๐ŸŒˆ๐Ÿ˜ˆ๐Ÿค˜๐Ÿ’ฆโœ”๐Ÿ˜ฃ๐Ÿƒ๐Ÿ’โ˜น๐ŸŽŠ๐Ÿ’˜๐Ÿ˜ โ˜๐Ÿ˜•๐ŸŒบ๐ŸŽ‚๐ŸŒป๐Ÿ˜๐Ÿ–•๐Ÿ’๐Ÿ™Š๐Ÿ˜น๐Ÿ—ฃ๐Ÿ’ซ๐Ÿ’€๐Ÿ‘‘๐ŸŽต๐Ÿคž๐Ÿ˜›๐Ÿ”ด๐Ÿ˜ค๐ŸŒผ๐Ÿ˜ซโšฝ๐Ÿค™โ˜•๐Ÿ†๐Ÿคซ๐Ÿ‘ˆ๐Ÿ˜ฎ๐Ÿ™†๐Ÿป๐Ÿƒ๐Ÿถ๐Ÿ’๐Ÿ˜ฒ๐ŸŒฟ๐Ÿงก๐ŸŽโšก๐ŸŒž๐ŸŽˆโŒโœŠ๐Ÿ‘‹๐Ÿ˜ฐ๐Ÿคจ๐Ÿ˜ถ๐Ÿค๐Ÿšถ๐Ÿ’ฐ๐Ÿ“๐Ÿ’ข๐ŸคŸ๐Ÿ™๐Ÿšจ๐Ÿ’จ๐Ÿคฌโœˆ๐ŸŽ€๐Ÿบ๐Ÿค“๐Ÿ˜™๐Ÿ’Ÿ๐ŸŒฑ๐Ÿ˜–๐Ÿ‘ถ๐Ÿฅดโ–ถโžกโ“๐Ÿ’Ž๐Ÿ’ธโฌ‡๐Ÿ˜จ๐ŸŒš๐Ÿฆ‹๐Ÿ˜ท๐Ÿ•บโš ๐Ÿ™…๐Ÿ˜Ÿ๐Ÿ˜ต๐Ÿ‘Ž๐Ÿคฒ๐Ÿค ๐Ÿคง๐Ÿ“Œ๐Ÿ”ต๐Ÿ’…๐Ÿง๐Ÿพ๐Ÿ’๐Ÿ˜—๐Ÿค‘๐ŸŒŠ๐Ÿคฏ๐Ÿทโ˜Ž๐Ÿ’ง๐Ÿ˜ฏ๐Ÿ’†๐Ÿ‘†๐ŸŽค๐Ÿ™‡๐Ÿ‘โ„๐ŸŒด๐Ÿ’ฃ๐Ÿธ๐Ÿ’Œ๐Ÿ“๐Ÿฅ€๐Ÿคข๐Ÿ‘…๐Ÿ’ก๐Ÿ’ฉ๐Ÿ‘๐Ÿ“ธ๐Ÿ‘ป๐Ÿค๐Ÿคฎ๐ŸŽผ๐Ÿฅต๐Ÿšฉ๐ŸŽ๐ŸŠ๐Ÿ‘ผ๐Ÿ’๐Ÿ“ฃ๐Ÿฅ‚"),je=ze.reduce(((e,t,r)=>(e[r]=t,e)),[]),Ke=ze.reduce(((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw Error("Invalid character: "+t);return e[n]=r,e}),[]),Ve=Le({prefix:"๐Ÿš€",name:"base256emoji",encode:e=>e.reduce(((e,t)=>e+je[t]),""),decode(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw Error("Invalid character: "+r);const n=Ke[e];if(null==n)throw Error("Non-base256emoji character: "+r);t.push(n)}return new Uint8Array(t)}});var He=Object.freeze({__proto__:null,base256emoji:Ve});const We=Me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ge=Me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Xe=Me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ze=Me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ye=Me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qe=Me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Je=Me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),et=Me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tt=Me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var rt=Object.freeze({__proto__:null,base32:We,base32hex:Ye,base32hexpad:Je,base32hexpadupper:et,base32hexupper:Qe,base32pad:Xe,base32padupper:Ze,base32upper:Ge,base32z:tt});const nt=De({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),it=De({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var st=Object.freeze({__proto__:null,base36:nt,base36upper:it});const ot=De({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),at=De({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lt=Object.freeze({__proto__:null,base58btc:ot,base58flickr:at});const ut=Me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ct=Me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),dt=Me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ht=Me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ft=Object.freeze({__proto__:null,base64:ut,base64pad:ct,base64url:dt,base64urlpad:ht});const pt=Me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gt=Object.freeze({__proto__:null,base8:pt});const mt=Le({prefix:"\0",name:"identity",encode(e){var t;return t=e,(new TextDecoder).decode(t)},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)});var vt=Object.freeze({__proto__:null,identity:mt});new TextEncoder,new TextDecoder;var yt=128,bt=-128,wt=2147483648,Et=128,St=127,At=Math.pow(2,63),It={encode:function e(t,r,n){r=r||[];for(var i=n=n||0;t>=wt;)r[n++]=255&t|yt,t/=128;for(;t&bt;)r[n++]=255&t|yt,t>>>=7;return r[n]=0|t,e.bytes=n-i+1,r},decode:function e(t,r){var n,i=0,s=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],i+=s<28?(n&St)<<s:(n&St)*Math.pow(2,s),s+=7}while(n>=Et);return e.bytes=o-r,i},encodingLength:e=>e<128?1:e<16384?2:e<2097152?3:e<268435456?4:e<34359738368?5:e<4398046511104?6:e<562949953421312?7:e<72057594037927940?8:e<At?9:10};function _t(e,t=0){return[It.decode(e,t),It.decode.bytes]}function Ct(e,t,r=0){return It.encode(e,t,r),t}function kt(e){return It.encodingLength(e)}function xt(e,t){const r=t.byteLength,n=kt(e),i=n+kt(r),s=new Uint8Array(i+r);return Ct(e,s,0),Ct(r,s,n),s.set(t,i),new Pt(e,r,t,s)}function Tt(e){const t=_e(e),[r,n]=_t(t),[i,s]=_t(t.subarray(n)),o=t.subarray(n+s);if(o.byteLength!==i)throw Error("Incorrect length");return new Pt(r,i,o,t)}class Pt{constructor(e,t,r,n){(0,L.default)(this,"code",void 0),(0,L.default)(this,"size",void 0),(0,L.default)(this,"digest",void 0),(0,L.default)(this,"bytes",void 0),this.code=e,this.size=t,this.digest=r,this.bytes=n}}const Rt=_e,Lt={code:0,name:"identity",encode:Rt,digest:e=>xt(0,Rt(e))};class Dt{digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?xt(this.code,t):t.then((e=>xt(this.code,e)))}throw Error("Unknown type, must be binary type")}constructor(e,t,r){(0,L.default)(this,"name",void 0),(0,L.default)(this,"code",void 0),(0,L.default)(this,"encode",void 0),this.name=e,this.code=t,this.encode=r}}const Mt=function({name:e,code:t,encode:r}){return new Dt(e,t,r)}({name:"sha2-256",code:18,encode:async e=>new Uint8Array(await crypto.subtle.digest("SHA-256",e))});function Nt(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==ot.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const i=t.get(n);if(null==i){const i=r.encode(e).slice(1);return t.set(n,i),i}return i}(r,Ut(e),null!=t?t:ot.encoder):function(e,t,r){const{prefix:n}=r,i=t.get(n);if(null==i){const i=r.encode(e);return t.set(n,i),i}return i}(r,Ut(e),null!=t?t:We.encoder)}const Ot=new WeakMap;function Ut(e){const t=Ot.get(e);if(null==t){const t=new Map;return Ot.set(e,t),t}return t}let Ft=Symbol.toStringTag,Bt=Symbol.for("nodejs.util.inspect.custom");class $t{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:e,multihash:t}=this;if(e!==qt)throw Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==zt)throw Error("Cannot convert non sha2-256 multihash CID to CIDv0");return $t.createV0(t)}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:e,digest:t}=this.multihash,r=xt(e,t);return $t.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return $t.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&((e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0})(e.bytes,r.bytes)}}(e.multihash,r.multihash)}toString(e){return Nt(this,e)}toJSON(){return{"/":Nt(this)}}link(){return this}[Bt](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;const t=e;if(t instanceof $t)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:r,multihash:n,bytes:i}=t;return new $t(e,r,n,null!=i?i:jt(e,r,n.bytes))}if(!0===t[Kt]){const{version:e,multihash:r,code:n}=t,i=Tt(r);return $t.create(e,n,i)}return null}static create(e,t,r){if("number"!=typeof t)throw Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw Error("Invalid digest");switch(e){case 0:if(t!==qt)throw Error(`Version 0 CID must use dag-pb (code: ${qt}) block encoding`);return new $t(e,t,r,r.bytes);case 1:{const n=jt(e,t,r.bytes);return new $t(e,t,r,n)}default:throw Error("Invalid version")}}static createV0(e){return $t.create(0,qt,e)}static createV1(e,t){return $t.create(1,e,t)}static decode(e){const[t,r]=$t.decodeFirst(e);if(0!==r.length)throw Error("Incorrect length");return t}static decodeFirst(e){const t=$t.inspectBytes(e),r=t.size-t.multihashSize,n=_e(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw Error("Incorrect length");const i=n.subarray(t.multihashSize-t.digestSize),s=new Pt(t.multihashCode,t.digestSize,i,n);return[0===t.version?$t.createV0(s):$t.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=_t(e.subarray(t));return t+=n,r};let n=r(),i=qt;if(18===n?(n=0,t=0):i=r(),0!==n&&1!==n)throw new RangeError("Invalid CID version "+n);const s=t,o=r(),a=r(),l=t+a;return{version:n,codec:i,multihashCode:o,digestSize:a,multihashSize:l-s,size:l}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=null!=t?t:ot;return[ot.prefix,r.decode(`${ot.prefix}${e}`)]}case ot.prefix:{const r=null!=t?t:ot;return[ot.prefix,r.decode(e)]}case We.prefix:{const r=null!=t?t:We;return[We.prefix,r.decode(e)]}case nt.prefix:{const r=null!=t?t:nt;return[nt.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),i=$t.decode(n);if(0===i.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return Ut(i).set(r,e),i}constructor(e,t,r,n){(0,L.default)(this,"code",void 0),(0,L.default)(this,"version",void 0),(0,L.default)(this,"multihash",void 0),(0,L.default)(this,"bytes",void 0),(0,L.default)(this,"/",void 0),(0,L.default)(this,Ft,"CID"),this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}}const qt=112,zt=18;function jt(e,t,r){const n=kt(e),i=n+kt(t),s=new Uint8Array(i+r.byteLength);return Ct(e,s,0),Ct(t,s,n),s.set(r,i),s}const Kt=Symbol.for("@ipld/js-cid/CID"),Vt=(0,D.default)({},vt,qe,gt,Oe,Be,rt,st,lt,ft,He);function Ht(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const Wt=Ht("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Gt=Ht("ascii","a",(e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{const t=Y((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),Xt=(0,D.default)({utf8:Wt,"utf-8":Wt,hex:Vt.base16,latin1:Gt,ascii:Gt,binary:Gt},Vt);function Zt(e,t="utf8"){const r=Xt[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}class Yt{constructor(e,t,r){(0,L.default)(this,"fn",void 0),(0,L.default)(this,"len",void 0),(0,L.default)(this,"next",void 0),(0,L.default)(this,"val",void 0),this.fn=e,this.len=t,this.next=void 0,this.val=r}}function Qt(){}class Jt{constructor(e){(0,L.default)(this,"head",void 0),(0,L.default)(this,"tail",void 0),(0,L.default)(this,"len",void 0),(0,L.default)(this,"next",void 0),this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const er=function(){const e=8192;let t,r=e;return function(n){if(n<1||n>4096)return Y(n);r+n>e&&(t=Y(e),r=0);const i=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),i}}();class tr{_push(e,t,r){return this.tail=this.tail.next=new Yt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ir((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(sr,10,ve.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=ve.fromBigInt(e);return this._push(sr,t.length(),t)}uint64Number(e){return this._push(se,ie(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=ve.fromBigInt(e).zzEncode();return this._push(sr,t.length(),t)}sint64Number(e){const t=ve.fromNumber(e).zzEncode();return this._push(sr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(rr,1,e?1:0)}fixed32(e){return this._push(or,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=ve.fromBigInt(e);return this._push(or,4,t.lo)._push(or,4,t.hi)}fixed64Number(e){const t=ve.fromNumber(e);return this._push(or,4,t.lo)._push(or,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(de,4,e)}double(e){return this._push(pe,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(rr,1,0):this.uint32(t)._push(ar,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(we,t,e):this._push(rr,1,0)}fork(){return this.states=new Jt(this),this.head=this.tail=new Yt(Qt,0,0),this.len=0,this}reset(){return null!=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 Yt(Qt,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next;const t=(r=this.len,null!=globalThis.Buffer?Y(r):er(r));var r;let n=0;for(;null!=e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}constructor(){(0,L.default)(this,"len",void 0),(0,L.default)(this,"head",void 0),(0,L.default)(this,"tail",void 0),(0,L.default)(this,"states",void 0),this.len=0,this.head=new Yt(Qt,0,0),this.tail=this.head,this.states=null}}function rr(e,t,r){t[r]=255&e}function nr(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class ir extends Yt{constructor(e,t){super(nr,e,t),(0,L.default)(this,"next",void 0),this.next=void 0}}function sr(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function or(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function ar(e,t,r){t.set(e,r)}function lr(e,t,r){t.set(e,r)}function ur(e,t,r){e.length<40?we(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(Zt(e),r)}function cr(e,t){const r=new tr;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var dr,hr,fr,pr,gr,mr,vr,yr,br,wr,Er,Sr,Ar,Ir,_r,Cr,kr,xr,Tr,Pr,Rr,Lr,Dr,Mr,Nr,Or,Ur,Fr,Br,$r,qr,zr,jr,Kr,Vr;function Hr(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Wr(e){function t(t){if(null==e[t.toString()])throw Error("Invalid enum value");return e[t]}return Hr("enum",dr.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Gr(e,t){return Hr("message",dr.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(tr.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(lr,t,e),this},tr.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(ur,t,e),this}),(Vr=dr||(dr={}))[Vr.VARINT=0]="VARINT",Vr[Vr.BIT64=1]="BIT64",Vr[Vr.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",Vr[Vr.START_GROUP=3]="START_GROUP",Vr[Vr.END_GROUP=4]="END_GROUP",Vr[Vr.BIT32=5]="BIT32";class Xr extends Error{constructor(...e){super(...e),(0,L.default)(this,"code","ERR_MAX_LENGTH"),(0,L.default)(this,"name","MaxLengthError")}}class Zr extends Error{constructor(...e){super(...e),(0,L.default)(this,"code","ERR_MAX_SIZE"),(0,L.default)(this,"name","MaxSizeError")}}function Yr(e){return!!e}(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:Z(0),merkleRoot:Z(0),epoch:Z(0),shareX:Z(0),shareY:Z(0),nullifier:Z(0),rlnIdentifier:Z(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(hr||(hr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),hr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:Z(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:var s;n.rateLimitProof=hr.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(fr||(fr={})),(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==t&&(t=Gr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const i={subscribe:!1,topic:"",contentFilters:[]},s=null==r?t.len:t.pos+r;for(;t.pos<s;){const r=t.uint32();switch(r>>>3){case 1:i.subscribe=t.bool();break;case 2:i.topic=t.string();break;case 3:var o,a;if(null!=(null===(o=n.limits)||void 0===o?void 0:o.contentFilters)&&i.contentFilters.length===n.limits.contentFilters)throw new Xr('Decode error - map field "contentFilters" had too many elements');i.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:null===(a=n.limits)||void 0===a?void 0:a.contentFilters$}));break;default:t.skipType(7&r)}}return i}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(pr||(pr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),yr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();if(t>>>3==1){var s,o;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.messages)&&n.messages.length===r.limits.messages)throw new Xr('Decode error - map field "messages" had too many elements');n.messages.push(yr.codec().decode(e,e.uint32(),{limits:null===(o=r.limits)||void 0===o?void 0:o.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(gr||(gr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),pr.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),gr.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:var s;n.request=pr.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.request});break;case 3:var o;n.push=gr.codec().decode(e,e.uint32(),{limits:null===(o=r.limits)||void 0===o?void 0:o.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(mr||(mr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:Z(0),merkleRoot:Z(0),epoch:Z(0),shareX:Z(0),shareY:Z(0),nullifier:Z(0),rlnIdentifier:Z(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(vr||(vr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),vr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:Z(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:var s;n.rateLimitProof=vr.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(yr||(yr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==2?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(br||(br={})),(e=>{let t,r,n;(e=>{e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),(e=>{e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"})(r||(r={})),(e=>{e.codec=()=>Wr(r)})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=Gr(((t,n,i={})=>{if(!1!==i.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==i.lengthDelimited&&n.ldelim()}),((r,n,i={})=>{const s={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},o=null==n?r.len:r.pos+n;for(;r.pos<o;){const t=r.uint32();switch(t>>>3){case 1:s.requestId=r.string();break;case 2:s.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:s.pubsubTopic=r.string();break;case 11:var a;if(null!=(null===(a=i.limits)||void 0===a?void 0:a.contentTopics)&&s.contentTopics.length===i.limits.contentTopics)throw new Xr('Decode error - map field "contentTopics" had too many elements');s.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return s}))),n),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(wr||(wr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Er||(Er={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),Ir.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:var s;n.wakuMessage=Ir.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Sr||(Sr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:Z(0),merkleRoot:Z(0),epoch:Z(0),shareX:Z(0),shareY:Z(0),nullifier:Z(0),rlnIdentifier:Z(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Ar||(Ar={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Ar.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:Z(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:var s;n.rateLimitProof=Ar.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Ir||(Ir={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),Rr.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.pubsubTopic=e.string();break;case 2:var s;n.message=Rr.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(_r||(_r={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={isSuccess:!1},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.isSuccess=e.bool();break;case 2:r.info=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Cr||(Cr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),_r.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),Cr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:var s;n.request=_r.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.request});break;case 3:var o;n.response=Cr.codec().decode(e,e.uint32(),{limits:null===(o=r.limits)||void 0===o?void 0:o.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(kr||(kr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.pubsubTopic&&(t.uint32(162),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(170),Rr.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 20:n.pubsubTopic=e.string();break;case 21:var s;n.message=Rr.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(xr||(xr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Tr||(Tr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:Z(0),merkleRoot:Z(0),epoch:Z(0),shareX:Z(0),shareY:Z(0),nullifier:Z(0),rlnIdentifier:Z(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Pr||(Pr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Pr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:Z(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:var s;n.rateLimitProof=Pr.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Rr||(Rr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),Or.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.messageHash=e.bytes();break;case 2:var s;n.message=Or.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Lr||(Lr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:var s;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.contentTopics)&&n.contentTopics.length===r.limits.contentTopics)throw new Xr('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:var o;if(null!=(null===(o=r.limits)||void 0===o?void 0:o.messageHashes)&&n.messageHashes.length===r.limits.messageHashes)throw new Xr('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Dr||(Dr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),Lr.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",messages:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:var s,o;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.messages)&&n.messages.length===r.limits.messages)throw new Xr('Decode error - map field "messages" had too many elements');n.messages.push(Lr.codec().decode(e,e.uint32(),{limits:null===(o=r.limits)||void 0===o?void 0:o.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Mr||(Mr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:Z(0),merkleRoot:Z(0),epoch:Z(0),shareX:Z(0),shareY:Z(0),nullifier:Z(0),rlnIdentifier:Z(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Nr||(Nr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Nr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:Z(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:var s;n.rateLimitProof=Nr.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Or||(Or={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.enr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Ur||(Ur={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.numPeers=e.uint64():e.skipType(7&t)}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Fr||(Fr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),Ur.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();if(t>>>3==1){var s,o;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.peerInfos)&&n.peerInfos.length===r.limits.peerInfos)throw new Xr('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(Ur.codec().decode(e,e.uint32(),{limits:null===(o=r.limits)||void 0===o?void 0:o.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Br||(Br={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),Fr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),Br.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:var s;n.query=Fr.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.query});break;case 2:var o;n.response=Br.codec().decode(e,e.uint32(),{limits:null===(o=r.limits)||void 0===o?void 0:o.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})($r||($r={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:var s;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.shards)&&n.shards.length===r.limits.shards)throw new Xr('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(qr||(qr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:var s;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.shards)&&n.shards.length===r.limits.shards)throw new Xr('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(zr||(zr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageId&&""!==e.messageId&&(t.uint32(10),t.string(e.messageId)),null!=e.retrievalHint&&(t.uint32(18),t.bytes(e.retrievalHint)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={messageId:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.messageId=e.string();break;case 2:r.retrievalHint=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(jr||(jr={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.senderId&&""!==e.senderId&&(t.uint32(10),t.string(e.senderId)),null!=e.messageId&&""!==e.messageId&&(t.uint32(18),t.string(e.messageId)),null!=e.channelId&&""!==e.channelId&&(t.uint32(26),t.string(e.channelId)),null!=e.lamportTimestamp&&(t.uint32(80),t.int32(e.lamportTimestamp)),null!=e.causalHistory)for(const r of e.causalHistory)t.uint32(90),jr.codec().encode(r,t);null!=e.bloomFilter&&(t.uint32(98),t.bytes(e.bloomFilter)),null!=e.content&&(t.uint32(162),t.bytes(e.content)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={senderId:"",messageId:"",channelId:"",causalHistory:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.senderId=e.string();break;case 2:n.messageId=e.string();break;case 3:n.channelId=e.string();break;case 10:n.lamportTimestamp=e.int32();break;case 11:var s,o;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.causalHistory)&&n.causalHistory.length===r.limits.causalHistory)throw new Xr('Decode error - map field "causalHistory" had too many elements');n.causalHistory.push(jr.codec().decode(e,e.uint32(),{limits:null===(o=r.limits)||void 0===o?void 0:o.causalHistory$}));break;case 12:n.bloomFilter=e.bytes();break;case 20:n.content=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Kr||(Kr={}));const Qr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Jr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function en(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function tn(e,...t){if(!Jr(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function rn(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");en(e.outputLen),en(e.blockLen)}function nn(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function sn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function on(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function an(e,t){return e<<32-t|e>>>t}const ln="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,un=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function cn(e){if(tn(e),ln)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=un[e[r]];return t}const dn=48,hn=57,fn=65,pn=70,gn=97,mn=102;function vn(e){return e>=dn&&e<=hn?e-dn:e>=fn&&e<=pn?e-(fn-10):e>=gn&&e<=mn?e-(gn-10):void 0}function yn(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(ln)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,i=0;t<r;t++,i+=2){const r=vn(e.charCodeAt(i)),s=vn(e.charCodeAt(i+1));if(void 0===r||void 0===s){const t=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+i)}n[t]=16*r+s}return n}function bn(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),tn(e),e}function wn(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];tn(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.length}return r}class En{}function Sn(e){const t=t=>e().update(bn(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function An(e=32){if(Qr&&"function"==typeof Qr.getRandomValues)return Qr.getRandomValues(new Uint8Array(e));if(Qr&&"function"==typeof Qr.randomBytes)return Uint8Array.from(Qr.randomBytes(e));throw Error("crypto.getRandomValues must be defined")}function In(e,t,r){return e&t^e&r^t&r}class _n extends En{update(e){nn(this),tn(e=bn(e));const{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);if(o!==n)r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=on(e);for(;n<=i-s;s+=n)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){nn(this),function(e,t){tn(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:i}=this;let{pos:s}=this;t[s++]=128,sn(this.buffer.subarray(s)),this.padOffset>n-s&&(this.process(r,0),s=0);for(let e=s;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),l=n?4:0,u=n?0:4;e.setUint32(t+l,o,n),e.setUint32(t+u,a,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const o=on(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");const l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<l;e++)o.setUint32(4*e,u[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:i,destroyed:s,pos:o}=this;return e.destroyed=s,e.finished=i,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=on(this.buffer)}}const Cn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),kn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),xn=BigInt(2**32-1),Tn=BigInt(32);function Pn(e,t=!1){return t?{h:Number(e&xn),l:Number(e>>Tn&xn)}:{h:0|Number(e>>Tn&xn),l:0|Number(e&xn)}}const Rn=(e,t,r)=>e>>>r,Ln=(e,t,r)=>e<<32-r|t>>>r,Dn=(e,t,r)=>e>>>r|t<<32-r,Mn=(e,t,r)=>e<<32-r|t>>>r,Nn=(e,t,r)=>e<<64-r|t>>>r-32,On=(e,t,r)=>e>>>r-32|t<<64-r;function Un(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}}const Fn=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Bn=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,$n=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),qn=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,zn=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),jn=(e,t,r,n,i,s)=>t+r+n+i+s+(e/2**32|0)|0,Kn=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]),Vn=new Uint32Array(64);class Hn extends _n{get(){const{A:e,B:t,C:r,D:n,E:i,F:s,G:o,H:a}=this;return[e,t,r,n,i,s,o,a]}set(e,t,r,n,i,s,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)Vn[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Vn[e-15],r=Vn[e-2],n=an(t,7)^an(t,18)^t>>>3,i=an(r,17)^an(r,19)^r>>>10;Vn[e]=i+Vn[e-7]+n+Vn[e-16]|0}let{A:r,B:n,C:i,D:s,E:o,F:a,G:l,H:u}=this;for(let e=0;e<64;e++){const t=u+(an(o,6)^an(o,11)^an(o,25))+((c=o)&a^~c&l)+Kn[e]+Vn[e]|0,d=(an(r,2)^an(r,13)^an(r,22))+In(r,n,i)|0;u=l,l=a,a=o,o=s+t|0,s=i,i=n,n=r,r=t+d|0}var c;r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,n,i,s,o,a,l,u)}roundClean(){sn(Vn)}destroy(){this.set(0,0,0,0,0,0,0,0),sn(this.buffer)}constructor(e=32){super(64,e,8,!1),this.A=0|Cn[0],this.B=0|Cn[1],this.C=0|Cn[2],this.D=0|Cn[3],this.E=0|Cn[4],this.F=0|Cn[5],this.G=0|Cn[6],this.H=0|Cn[7]}}const Wn=function(e,t=!1){const r=e.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:r,l:o}=Pn(e[s],t);[n[s],i[s]]=[r,o]}return[n,i]}(["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((e=>BigInt(e)))),Gn=Wn[0],Xn=Wn[1],Zn=new Uint32Array(80),Yn=new Uint32Array(80);class Qn extends _n{get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:s,Dh:o,Dl:a,Eh:l,El:u,Fh:c,Fl:d,Gh:h,Gl:f,Hh:p,Hl:g}=this;return[e,t,r,n,i,s,o,a,l,u,c,d,h,f,p,g]}set(e,t,r,n,i,s,o,a,l,u,c,d,h,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|o,this.Dl=0|a,this.Eh=0|l,this.El=0|u,this.Fh=0|c,this.Fl=0|d,this.Gh=0|h,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)Zn[r]=e.getUint32(t),Yn[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Zn[e-15],r=0|Yn[e-15],n=Dn(t,r,1)^Dn(t,r,8)^Rn(t,0,7),i=Mn(t,r,1)^Mn(t,r,8)^Ln(t,r,7),s=0|Zn[e-2],o=0|Yn[e-2],a=Dn(s,o,19)^Nn(s,o,61)^Rn(s,0,6),l=Mn(s,o,19)^On(s,o,61)^Ln(s,o,6),u=$n(i,l,Yn[e-7],Yn[e-16]),c=qn(u,n,a,Zn[e-7],Zn[e-16]);Zn[e]=0|c,Yn[e]=0|u}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:o,Cl:a,Dh:l,Dl:u,Eh:c,El:d,Fh:h,Fl:f,Gh:p,Gl:g,Hh:m,Hl:v}=this;for(let e=0;e<80;e++){const t=Dn(c,d,14)^Dn(c,d,18)^Nn(c,d,41),y=Mn(c,d,14)^Mn(c,d,18)^On(c,d,41),b=c&h^~c&p,w=zn(v,y,d&f^~d&g,Xn[e],Yn[e]),E=jn(w,m,t,b,Gn[e],Zn[e]),S=0|w,A=Dn(r,n,28)^Nn(r,n,34)^Nn(r,n,39),I=Mn(r,n,28)^On(r,n,34)^On(r,n,39),_=r&i^r&o^i&o,C=n&s^n&a^s&a;m=0|p,v=0|g,p=0|h,g=0|f,h=0|c,f=0|d,({h:c,l:d}=Un(0|l,0|u,0|E,0|S)),l=0|o,u=0|a,o=0|i,a=0|s,i=0|r,s=0|n;const k=Fn(S,I,C);r=Bn(k,E,A,_),n=0|k}({h:r,l:n}=Un(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=Un(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=Un(0|this.Ch,0|this.Cl,0|o,0|a)),({h:l,l:u}=Un(0|this.Dh,0|this.Dl,0|l,0|u)),({h:c,l:d}=Un(0|this.Eh,0|this.El,0|c,0|d)),({h:h,l:f}=Un(0|this.Fh,0|this.Fl,0|h,0|f)),({h:p,l:g}=Un(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:v}=Un(0|this.Hh,0|this.Hl,0|m,0|v)),this.set(r,n,i,s,o,a,l,u,c,d,h,f,p,g,m,v)}roundClean(){sn(Zn,Yn)}destroy(){sn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}constructor(e=64){super(128,e,16,!1),this.Ah=0|kn[0],this.Al=0|kn[1],this.Bh=0|kn[2],this.Bl=0|kn[3],this.Ch=0|kn[4],this.Cl=0|kn[5],this.Dh=0|kn[6],this.Dl=0|kn[7],this.Eh=0|kn[8],this.El=0|kn[9],this.Fh=0|kn[10],this.Fl=0|kn[11],this.Gh=0|kn[12],this.Gl=0|kn[13],this.Hh=0|kn[14],this.Hl=0|kn[15]}}const Jn=Sn((()=>new Hn)),ei=Sn((()=>new Qn)),ti=Jn;function ri(e,t="utf8"){const r=Xt[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function ni(e){return"string"==typeof e?Zt(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}function ii(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}const si=e=>ri(e,"base16"),oi=e=>ri(e,"utf8"),ai=e=>Zt(e,"utf8");function li(e){const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const ui=(e,t)=>`/waku/2/rs/${e}/${t}`,ci=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function di(e){const t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid: "+e);let r=0;if(6==t.length){if(r=parseInt(t[1]),isNaN(r))throw Error("Invalid generation field in content topic: "+e);if(r>0)throw Error("Generation greater than 0 is not supported: "+e)}const n=t.splice(-4);if(0==n[0].length)throw Error("Application field cannot be empty: "+e);if(0==n[1].length)throw Error("Version field cannot be empty: "+e);if(0==n[2].length)throw Error("Topic name field cannot be empty: "+e);if(0==n[3].length)throw Error("Encoding field cannot be empty: "+e);return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}class hi{constructor(e,t,r){(0,L.default)(this,"networkConfig",void 0),(0,L.default)(this,"pubsubTopic",void 0),(0,L.default)(this,"shardId",void 0),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}}class fi extends hi{static fromContentTopic(e,t){di(e);const r=function(e,t){const{application:r,version:n}=di(e),i=ti(li([ai(r),ai(n)])),s=new DataView(i.buffer.slice(-8));return Number(s.getBigUint64(0,!1)%BigInt(t))}(e,t.numShardsInCluster),n=ui(t.clusterId,r);return new fi(t,n,r,e)}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!0}get isStaticSharding(){return!1}constructor(e,t,r,n){super(e,t,r),(0,L.default)(this,"networkConfig",void 0),(0,L.default)(this,"pubsubTopic",void 0),(0,L.default)(this,"shardId",void 0),(0,L.default)(this,"contentTopic",void 0),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r,this.contentTopic=n}}class pi extends hi{static fromShard(e,t){const r=ui(t.clusterId,e);return new pi(t,r,e)}static fromPubsubTopic(e,t){const{clusterId:r,shard:n}=ci(e);if(r!=t.clusterId)throw"Pubsub topic does not match network config's cluster id";return new pi(t,e,n)}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!1}get isStaticSharding(){return!0}constructor(e,t,r){super(e,t,r),(0,L.default)(this,"networkConfig",void 0),(0,L.default)(this,"pubsubTopic",void 0),(0,L.default)(this,"shardId",void 0),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}}function gi(e,t){if("clusterId"in(r=e)&&"numShardsInCluster"in r){if(t.contentTopic)return fi.fromContentTopic(t.contentTopic,e);throw Error("AutoSharding requires contentTopic")}if(void 0!==t.shardId)return pi.fromShard(t.shardId,e);if(t.pubsubTopic)return pi.fromPubsubTopic(t.pubsubTopic,e);var r;throw Error("StaticSharding requires shardId or pubsubTopic")}const mi=e=>{if((e=new Uint8Array(e)).length<3)throw Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,i=7-e%8;t.getUint8(r)&1<<i&&n.push(e)}else{const r=t.getUint8(2);for(let i=0,s=3;i<r;i++,s+=2){if(s+1>=e.length)throw Error("Unexpected end of data");n.push(t.getUint16(s))}}return{clusterId:r,shards:n}},vi=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,i=new ArrayBuffer(n),s=new DataView(i);if(s.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;s.setUint8(t,s.getUint8(t)|1<<r)}else{s.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)s.setUint16(t,r[e])}return new Uint8Array(i)},yi=Symbol.for("@libp2p/connection"),bi=Symbol.for("@libp2p/content-routing"),wi=Symbol.for("@libp2p/peer-discovery"),Ei=Symbol.for("@libp2p/peer-id");function Si(e){return!!(null==e?void 0:e[Ei])}const Ai=Symbol.for("@libp2p/peer-routing"),Ii="keep-alive",_i=Symbol.for("@libp2p/transport");var Ci;(e=>{e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Ci||(Ci={}));let ki=(B=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},(0,L.default)(B,"name","AbortError"),B);class xi extends Error{constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}(0,L.default)(xi,"name","UnexpectedPeerError");let Ti=($=class extends Error{constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},(0,L.default)($,"name","InvalidCryptoExchangeError"),$),Pi=(q=class extends Error{constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},(0,L.default)(q,"name","InvalidParametersError"),q);class Ri extends Error{constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}(0,L.default)(Ri,"name","InvalidPublicKeyError");class Li extends Error{constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}}(0,L.default)(Li,"name","ConnectionClosingError");class Di extends Error{constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}(0,L.default)(Di,"name","ConnectionClosedError");class Mi extends Error{constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}(0,L.default)(Mi,"name","ConnectionFailedError");class Ni extends Error{constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}(0,L.default)(Ni,"name","MuxerClosedError");class Oi extends Error{constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}(0,L.default)(Oi,"name","StreamResetError");class Ui extends Error{constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}(0,L.default)(Ui,"name","StreamStateError");let Fi=(z=class extends Error{constructor(e="Not found"){super(e),this.name="NotFoundError"}},(0,L.default)(z,"name","NotFoundError"),z);class Bi extends Error{constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}(0,L.default)(Bi,"name","InvalidPeerIdError");let $i=(j=class extends Error{constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},(0,L.default)(j,"name","InvalidMultiaddrError"),j);class qi extends Error{constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}(0,L.default)(qi,"name","InvalidCIDError");class zi extends Error{constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}(0,L.default)(zi,"name","InvalidMultihashError");class ji extends Error{constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}(0,L.default)(ji,"name","UnsupportedProtocolError");class Ki extends Error{constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}(0,L.default)(Ki,"name","InvalidMessageError");let Vi=(K=class extends Error{constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},(0,L.default)(K,"name","ProtocolError"),K),Hi=(V=class extends Error{constructor(e="Timed out"){super(e),this.name="TimeoutError"}},(0,L.default)(V,"name","TimeoutError"),V);class Wi extends Error{constructor(e="Not started"){super(e),this.name="NotStartedError"}}(0,L.default)(Wi,"name","NotStartedError");class Gi extends Error{constructor(e="Dial error"){super(e),this.name="DialError"}}(0,L.default)(Gi,"name","DialError");class Xi extends Error{constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}(0,L.default)(Xi,"name","LimitedConnectionError");class Zi extends Error{constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}(0,L.default)(Zi,"name","TooManyInboundProtocolStreamsError");class Yi extends Error{constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}(0,L.default)(Yi,"name","TooManyOutboundProtocolStreamsError");class Qi extends Error{constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}(0,L.default)(Qi,"name","UnsupportedKeyTypeError");var Ji=new WeakMap;class es extends EventTarget{listenerCount(e){const t=(0,C.default)(this,Ji).get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=(0,C.default)(this,Ji).get(e);var i;null==n&&(n=[],(0,C.default)(this,Ji).set(e,n)),n.push({callback:t,once:null!==(i=!0!==r&&!1!==r&&(null==r?void 0:r.once))&&void 0!==i&&i})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),null!=t?t:null,r);let n=(0,C.default)(this,Ji).get(e);null!=n&&(n=n.filter((({callback:e})=>e!==t)),(0,C.default)(this,Ji).set(e,n))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=(0,C.default)(this,Ji).get(e.type);return null==r||(r=r.filter((({once:e})=>!e)),(0,C.default)(this,Ji).set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}constructor(){super(),(0,k.default)(this,Ji,{writable:!0,value:new Map})}}function ts(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}const rs=Symbol.for("@libp2p/service-capabilities"),ns=Symbol.for("@libp2p/service-dependencies");var is="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{};function ss(e){return e&&e.__esModule&&{}.hasOwnProperty.call(e,"default")?e.default:e}var os,as,ls,us,cs,ds={exports:{}};var hs=(cs||(cs=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=e=>{try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=()=>{let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&void 0!==X&&"env"in X&&(e=void 0),e},t.useColors=()=>{if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=(()=>{try{return localStorage}catch(e){}})(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!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`."))}})(),t.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"],t.log=console.debug||console.log||(()=>{}),e.exports=(us||(us=1,ls=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,i=-1,s=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(i=n,s=r,n++):(r++,n++);else{if(-1===i)return!1;n=i+1,s++,r=s}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=e=>e instanceof Error?e.stack||e.message:e,t.disable=()=>{const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=e=>{t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=e=>{for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=function(){if(as)return os;as=1;var e=1e3,t=60*e,r=60*t,n=24*r,i=7*n;function s(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return os=(o,a)=>{a=a||{};var l=typeof o;if("string"===l&&o.length>0)return function(s){if(!((s+="").length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*n;case"hours":case"hour":case"hrs":case"hr":case"h":return a*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(o);if("number"===l&&isFinite(o))return a.long?function(i){var o=Math.abs(i);return o>=n?s(i,o,n,"day"):o>=r?s(i,o,r,"hour"):o>=t?s(i,o,t,"minute"):o>=e?s(i,o,e,"second"):i+" ms"}(o):function(i){var s=Math.abs(i);return s>=n?Math.round(i/n)+"d":s>=r?Math.round(i/r)+"h":s>=t?Math.round(i/t)+"m":s>=e?Math.round(i/e)+"s":i+"ms"}(o);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))},os}(),t.destroy=()=>{console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=e=>{let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}),ls)(t);const{formatters:r}=e.exports;r.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(ds,ds.exports)),ds.exports),fs=ss(hs);const ps="waku";let gs=class e{static createDebugNamespace(e,t){return t?`${ps}:${t}:${e}`:`${ps}:${e}`}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...t){(this[e]||this.log)(...t)}constructor(t){(0,L.default)(this,"_info",void 0),(0,L.default)(this,"_warn",void 0),(0,L.default)(this,"_error",void 0),this._info=fs(e.createDebugNamespace("info",t)),this._warn=fs(e.createDebugNamespace("warn",t)),this._error=fs(e.createDebugNamespace("error",t))}};function ms(e,t){const r=ai(e),n=ai(t.contentTopic),i=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),ii(t)}(t.timestamp),s=li([r,t.payload,n,t.meta,i].filter(Yr));return ti(s)}const vs=new gs("message:version-0"),ys=BigInt(1e6);class bs{get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get hash(){return void 0===this._hash&&(this._hash=ms(this.pubsubTopic,this.proto)),this._hash}get hashStr(){return void 0===this._hashStr&&(this._hashStr=si(this.hash)),this._hashStr}get timestamp(){try{if(this.proto.timestamp){const e=this.proto.timestamp/ys;return new Date(Number(e))}return}catch(e){return}}get meta(){return this.proto.meta}get version(){var e;return null!==(e=this.proto.version)&&void 0!==e?e:0}get rateLimitProof(){return this.proto.rateLimitProof}constructor(e,t){(0,L.default)(this,"pubsubTopic",void 0),(0,L.default)(this,"proto",void 0),(0,L.default)(this,"_hash",void 0),(0,L.default)(this,"_hashStr",void 0),this.pubsubTopic=e,this.proto=t}}let ws=class{get pubsubTopic(){return this.routingInfo.pubsubTopic}async toWire(e){return fr.encode(await this.toProtoObj(e))}async toProtoObj(e){var t;const r=null!==(t=e.timestamp)&&void 0!==t?t:new Date,n={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(r.valueOf())*ys,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const e=this.metaSetter(n);return(0,M.default)((0,D.default)({},n),{meta:e})}return n}constructor(e,t=!1,r,n){if((0,L.default)(this,"contentTopic",void 0),(0,L.default)(this,"ephemeral",void 0),(0,L.default)(this,"routingInfo",void 0),(0,L.default)(this,"metaSetter",void 0),this.contentTopic=e,this.ephemeral=t,this.routingInfo=r,this.metaSetter=n,!e||""===e)throw Error("Content topic must be specified")}};function Es({contentTopic:e,routingInfo:t,ephemeral:r,metaSetter:n}){return new ws(e,r,t,n)}let Ss=class{get pubsubTopic(){return this.routingInfo.pubsubTopic}fromWireToProtoObj(e){const t=fr.decode(e);var r,n,i,s,o;return Promise.resolve({payload:t.payload,contentTopic:t.contentTopic,version:null!==(r=t.version)&&void 0!==r?r:void 0,timestamp:null!==(n=t.timestamp)&&void 0!==n?n:void 0,meta:null!==(i=t.meta)&&void 0!==i?i:void 0,rateLimitProof:null!==(s=t.rateLimitProof)&&void 0!==s?s:void 0,ephemeral:null!==(o=t.ephemeral)&&void 0!==o&&o})}async fromProtoObj(e,t){return t.version?(vs.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new bs(e,t)}constructor(e,t){if((0,L.default)(this,"contentTopic",void 0),(0,L.default)(this,"routingInfo",void 0),this.contentTopic=e,this.routingInfo=t,!e||""===e)throw Error("Content topic must be specified")}};var As,Is,_s,Cs,ks,xs,Ts;(e=>{e[e.SUCCESS=200]="SUCCESS",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",e[e.INVALID_MESSAGE=420]="INVALID_MESSAGE",e[e.UNSUPPORTED_TOPIC=421]="UNSUPPORTED_TOPIC",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.INTERNAL_ERROR=500]="INTERNAL_ERROR",e[e.UNAVAILABLE=503]="UNAVAILABLE",e[e.NO_RLN_PROOF=504]="NO_RLN_PROOF",e[e.NO_PEERS=505]="NO_PEERS"})(As||(As={})),As.SUCCESS,As.BAD_REQUEST,As.PAYLOAD_TOO_LARGE,As.INVALID_MESSAGE,As.UNSUPPORTED_TOPIC,As.TOO_MANY_REQUESTS,As.INTERNAL_ERROR,As.UNAVAILABLE,As.NO_RLN_PROOF,As.NO_PEERS,(e=>{e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"})(Is||(Is={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.RLN_PROOF_GENERATION="Proof generation failed",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.BAD_REQUEST="Bad request format",e.PAYLOAD_TOO_LARGE="Message payload exceeds maximum size",e.INVALID_MESSAGE="Message validation failed",e.UNSUPPORTED_TOPIC="Unsupported pubsub topic",e.TOO_MANY_REQUESTS="Rate limit exceeded",e.INTERNAL_ERROR="Internal server error",e.UNAVAILABLE="Service temporarily unavailable",e.NO_RLN_PROOF="RLN proof generation failed",e.NO_PEERS="No relay peers available"})(_s||(_s={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.SUBSCRIPTION_FAILED="Subscription failed",e.UNSUBSCRIBE_FAILED="Unsubscribe failed",e.PING_FAILED="Ping failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics",e.SUBSCRIPTION_LIMIT_EXCEEDED="Subscription limit exceeded",e.INVALID_CONTENT_TOPIC="Invalid content topic",e.PUSH_MESSAGE_FAILED="Push message failed",e.EMPTY_MESSAGE="Empty message received",e.MISSING_PUBSUB_TOPIC="Pubsub topic missing from push message"})(Cs||(Cs={})),(e=>{e.GENERIC_FAIL="Generic error",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.STREAM_ABORTED="Stream aborted",e.RLN_PROOF_GENERATION="Proof generation failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics"})(ks||(ks={})),(e=>{e.Connection="waku:connection",e.Health="waku:health"})(xs||(xs={})),(e=>{e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.PEER_CACHE="peer-cache"})(Ts||(Ts={}));const Ps="locked",Rs={clusterId:1,numShardsInCluster:8};var Ls;function Ds(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t}function Ms(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=Y(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Ns(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e=>{e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"})(Ls||(Ls={}));const Os=Symbol.for("@achingbrain/uint8arraylist");function Us(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");let r=0;for(const n of e){const e=r+n.byteLength;if(t<e)return{buf:n,index:t-r};r=e}throw new RangeError("index is out of bounds")}function Fs(e){return!!(null==e?void 0:e[Os])}let Bs=Os,$s=Symbol.iterator;class qs{*[$s](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!Fs(r))throw Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!Fs(r))throw Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=Us(this.bufs,e);return t.buf[t.index]}set(e,t){const r=Us(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!Fs(e))throw Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<e.length;r++)this.set(t+r,e.get(r))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return Ms(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:Ms(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),i=new qs;return i.length=n,i.bufs=[...r],i}_subList(e,t){if(e=null!=e?e:0,t=null!=t?t:this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let i=0;i<this.bufs.length;i++){const s=this.bufs[i],o=n,a=o+s.byteLength;if(n=a,e>=a)continue;const l=e>=o&&e<a,u=t>o&&t<=a;if(l&&u){if(e===o&&t===a){r.push(s);break}const n=e-o;r.push(s.subarray(n,n+(t-e)));break}if(l){if(0===e){r.push(s);continue}r.push(s.subarray(e-o))}else{if(u){if(t===a){r.push(s);break}r.push(s.subarray(0,t-o));break}r.push(s)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(Fs(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(isNaN(t=Number(null!=t?t:0))&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const i=new Int32Array(256);for(let e=0;e<256;e++)i[e]=-1;for(let e=0;e<n;e++)i[r[e]]=e;const s=i,o=this.byteLength-r.byteLength,a=r.byteLength-1;let l;for(let e=t;e<=o;e+=l){l=0;for(let t=a;t>=0;t--){const n=this.get(e+t);if(r[t]!==n){l=Math.max(1,t-s[n]);break}}if(0===l)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=Y(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=Z(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=Z(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=Z(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=Y(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=Z(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=Z(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=Z(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=Z(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=Z(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof qs))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ns(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const r=new qs;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}constructor(...e){(0,L.default)(this,"bufs",void 0),(0,L.default)(this,"length",void 0),(0,L.default)(this,Bs,!0),this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}}function zs(e){return null!=e[Symbol.asyncIterator]}const js=e=>{const t=ie(e),r=Y(t);return ae(e,r),js.bytes=t,r};function Ks(e,t){var r;const n=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:js;function*i(e){const t=n(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return zs(e)?async function*(){for await(const t of e)yield*i(t)}():function*(){for(const t of e)yield*i(t)}()}js.bytes=0,Ks.single=(e,t)=>{var r;const n=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:js;return new qs(n(e.byteLength),e)};let Vs=class extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidMessageLengthError"),(0,L.default)(this,"code","ERR_INVALID_MSG_LENGTH")}},Hs=class extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidDataLengthError"),(0,L.default)(this,"code","ERR_MSG_DATA_TOO_LONG")}},Ws=class extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidDataLengthLengthError"),(0,L.default)(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},Gs=class extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","UnexpectedEOFError"),(0,L.default)(this,"code","ERR_UNEXPECTED_EOF")}};var Xs;(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Xs||(Xs={}));const Zs=e=>{const t=le(e);return Zs.bytes=ie(t),t};function Ys(e,t){const r=new qs;let n=Xs.LENGTH,i=-1;var s,o,a;const l=null!==(s=null==t?void 0:t.lengthDecoder)&&void 0!==s?s:Zs,u=null!==(o=null==t?void 0:t.maxLengthLength)&&void 0!==o?o:8,c=null!==(a=null==t?void 0:t.maxDataLength)&&void 0!==a?a:4194304;function*d(){for(;r.byteLength>0;){if(n===Xs.LENGTH)try{if(i=l(r),i<0)throw new Vs("Invalid message length");if(i>c)throw new Hs("Message length too long");const e=l.bytes;r.consume(e),null!=(null==t?void 0:t.onLength)&&t.onLength(i),n=Xs.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>u)throw new Ws("Message length length too long");break}throw e}if(n===Xs.DATA){if(r.byteLength<i)break;const e=r.sublist(0,i);r.consume(i),null!=(null==t?void 0:t.onData)&&t.onData(e),yield e,n=Xs.LENGTH}}}return zs(e)?async function*(){for await(const t of e)r.append(t),yield*d();if(r.byteLength>0)throw new Gs("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*d();if(r.byteLength>0)throw new Gs("Unexpected end of input")}()}function Qs(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}Zs.bytes=0,Ys.fromReader=(e,t)=>{let r=1;return Ys(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),(0,M.default)((0,D.default)({},null!=t?t:{}),{onLength(e){r=e}}))};class Js{push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}constructor(e){if((0,L.default)(this,"buffer",void 0),(0,L.default)(this,"mask",void 0),(0,L.default)(this,"top",void 0),(0,L.default)(this,"btm",void 0),(0,L.default)(this,"next",void 0),!(e>0)||e-1&e)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}}class eo{calculateSize(e){return null!=(null==e?void 0:e.byteLength)?e.byteLength:1}push(e){if(null!=(null==e?void 0:e.value)&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new Js(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=(null==e?void 0:e.value)&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}constructor(e={}){var t;(0,L.default)(this,"size",void 0),(0,L.default)(this,"hwm",void 0),(0,L.default)(this,"head",void 0),(0,L.default)(this,"tail",void 0),this.hwm=null!==(t=e.splitLimit)&&void 0!==t?t:16,this.head=new Js(this.hwm),this.tail=this.head,this.size=0}}let to=class extends Error{constructor(e,t){super(null!=e?e:"The operation was aborted"),(0,L.default)(this,"type",void 0),(0,L.default)(this,"code",void 0),this.type="aborted",this.code=null!=t?t:"ABORT_ERR"}};function ro(e={}){return function(e,t){let r,n,i,s=(t=null!=t?t:{}).onEnd,o=new eo,a=Qs();const l=e=>null!=n?n(e):(o.push(e),r),u=e=>{if(i)return r;if(!0!==(null==t?void 0:t.objectMode)&&null==(null==e?void 0:e.byteLength))throw Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:e})},c=e=>i?r:(i=!0,null!=e?(e=>(o=new eo,null!=n?n({error:e}):(o.push({error:e}),r)))(e):l({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?i?{done:!0}:await new Promise(((t,i)=>{n=s=>{n=null,o.push(s);try{t(e(o))}catch(e){i(e)}return r}})):e(o)}finally{o.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=Qs()}))}},return:()=>(o=new eo,c(),{done:!0}),throw:e=>(c(e),{done:!0}),push:u,end:c,get readableLength(){return o.size},async onEmpty(e){const t=null==e?void 0:e.signal;if(null==t||t.throwIfAborted(),o.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new to)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&(null==t||t.removeEventListener("abort",n))}}},null==s)return r;const d=r;return r={[Symbol.asyncIterator](){return this},next:()=>d.next(),throw:e=>(d.throw(e),null!=s&&(s(e),s=void 0),{done:!0}),return:()=>(d.return(),null!=s&&(s(),s=void 0),{done:!0}),push:u,end:e=>(d.end(e),null!=s&&(s(e),s=void 0),r),get readableLength(){return d.readableLength},onEmpty:e=>d.onEmpty(e)},r}((e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),e)}let no=class extends Error{constructor(e,t,r){super(null!=e?e:"The operation was aborted"),(0,L.default)(this,"type",void 0),(0,L.default)(this,"code",void 0),this.type="aborted",this.name=null!=r?r:"AbortError",this.code=null!=t?t:"ABORT_ERR"}};async function io(e,t,r){if(null==t)return e;if(t.aborted)return e.catch((()=>{})),Promise.reject(new no(null==r?void 0:r.errorMessage,null==r?void 0:r.errorCode,null==r?void 0:r.errorName));let n;const i=new no(null==r?void 0:r.errorMessage,null==r?void 0:r.errorCode,null==r?void 0:r.errorName);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(i)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}let so=Symbol.asyncIterator;class oo{[so](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Qs(),e}async throw(e){return this.ended=!0,this.error=e,null!=e&&(this.haveNext.promise.catch((()=>{})),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){const e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){var r;if(null!=e&&this.ended)throw null!==(r=this.error)&&void 0!==r?r:Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Qs(),await io(this.readNext.promise,null==t?void 0:t.signal,t)}constructor(){(0,L.default)(this,"readNext",void 0),(0,L.default)(this,"haveNext",void 0),(0,L.default)(this,"ended",void 0),(0,L.default)(this,"nextResult",void 0),(0,L.default)(this,"error",void 0),this.ended=!1,this.readNext=Qs(),this.haveNext=Qs()}}function ao(){return new oo}function lo(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(e){for(const t of e)yield*t}(t):async function*(e){const t=new AbortController,r=ao();(async function(e,t,r){try{await Promise.all(e.map((async e=>{for await(const n of e)await t.push(n,{signal:r}),r.throwIfAborted()}))),await t.end(void 0,{signal:r})}catch(e){await t.end(e,{signal:r}).catch((()=>{}))}})(e,r,t.signal).catch((()=>{}));try{yield*r}finally{t.abort()}}(e)}function uo(e,...t){if(null==e)throw Error("Empty pipeline");if(po(e)){const t=e;e=()=>t.source}else if(fo(e)||ho(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&po(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e<r.length-1;e++)po(r[e])&&(r[e]=go(r[e]));return co(...r)}const co=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},ho=e=>null!=(null==e?void 0:e[Symbol.asyncIterator]),fo=e=>null!=(null==e?void 0:e[Symbol.iterator]),po=e=>null!=e&&null!=e.sink&&null!=e.source,go=e=>t=>{const r=e.sink(t);if(null!=(null==r?void 0:r.then)){const t=ro({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const i=e.source;if(ho(i))n=async function*(){yield*i,t.end()};else{if(!fo(i))throw Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*i,t.end()}}return lo(t,n())}return e.source};function mo(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const vo="consumed";class yo{async getStream(e){try{const t=e.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);const n=this.getOpenStreamForCodec(e)||await this.createStream(e);if(!n)return;return this.log.info(`Using stream for peerId=${t} multicodec=${this.multicodec}`),this.lockStream(t,n),n}catch(e){return void this.log.error("Failed to getStream:",e)}}async createStream(e,t=0){const r=mo(this.libp2p.connectionManager.getConnections(e));if(!r)return void this.log.error(`Failed to get a connection to the peer peerId=${e.toString()} multicodec=${this.multicodec}`);let n,i;for(let s=0;s<t+1;s++)try{this.log.info(`Attempting to create a stream for peerId=${e.toString()} multicodec=${this.multicodec}`),i=await r.newStream(this.multicodec),this.log.info(`Created stream for peerId=${e.toString()} multicodec=${this.multicodec}`);break}catch(e){n=e}if(i)return i;this.log.error(`Failed to create a new stream for ${e.toString()} -- `+n)}async createStreamWithLock(e){const t=e.id.toString();if(this.ongoingCreation.has(t))this.log.info(`Skipping creation of a stream due to lock for peerId=${t} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(t),await this.createStream(e.id)}catch(e){this.log.error("Failed to createStreamWithLock:",e)}finally{this.ongoingCreation.delete(t)}}scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=mo(this.libp2p.connectionManager.getConnections(e));if(!t)return void this.log.info(`No open connection found for peerId=${e.toString()} multicodec=${this.multicodec}`);const r=t.streams.find((e=>e.protocol===this.multicodec));if(r)return["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void this.log.info(`Stream for peerId=${e.toString()} multicodec=${this.multicodec} is unusable`):(this.log.info(`Found open stream for peerId=${e.toString()} multicodec=${this.multicodec}`),r);this.log.info(`No open stream found for peerId=${e.toString()} multicodec=${this.multicodec}`)}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[vo]=!0}isStreamLocked(e){return!!e.metadata[vo]}constructor(e,t){(0,L.default)(this,"multicodec",void 0),(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,"ongoingCreation",new Set),(0,L.default)(this,"streamPool",new Map),(0,L.default)(this,"handlePeerUpdateStreamPool",(e=>{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))})),this.multicodec=e,this.libp2p=t,this.log=new gs("stream-manager:"+e),this.libp2p.events.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}}let bo;const wo=new Uint8Array(16);function Eo(){if(!bo&&(bo="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!bo))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return bo(wo)}const So=[];for(let e=0;e<256;++e)So.push((e+256).toString(16).slice(1));var Ao={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Io(e){if(Ao.randomUUID&&!e)return Ao.randomUUID();const t=(e=e||{}).random||(e.rng||Eo)();return t[6]=15&t[6]|64,t[8]=63&t[8]|128,function(e,t=0){return So[e[t+0]]+So[e[t+1]]+So[e[t+2]]+So[e[t+3]]+"-"+So[e[t+4]]+So[e[t+5]]+"-"+So[e[t+6]]+So[e[t+7]]+"-"+So[e[t+8]]+So[e[t+9]]+"-"+So[e[t+10]]+So[e[t+11]]+So[e[t+12]]+So[e[t+13]]+So[e[t+14]]+So[e[t+15]]}(t)}class _o{static decode(e){const t=Sr.decode(e);return new _o(t)}encode(){return Sr.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}constructor(e){(0,L.default)(this,"proto",void 0),this.proto=e}}class Co{static createSubscribeRequest(e,t){return new Co({requestId:Io(),filterSubscribeType:wr.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new Co({requestId:Io(),filterSubscribeType:wr.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new Co({requestId:Io(),filterSubscribeType:wr.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new Co({requestId:Io(),filterSubscribeType:wr.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=wr.decode(e);return new Co(t)}encode(){return wr.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}constructor(e){(0,L.default)(this,"proto",void 0),this.proto=e}}class ko{static decode(e){const t=Er.decode(e);return new ko(t)}encode(){return Er.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}constructor(e){(0,L.default)(this,"proto",void 0),this.proto=e}}const xo=new gs("filter-core"),To="/vac/waku/filter-subscribe/2.0.0-beta1",Po="/vac/waku/filter-push/2.0.0-beta1";class Ro{async start(){try{await this.libp2p.handle(Po,this.onRequest.bind(this),{maxInboundStreams:100})}catch(e){xo.error("Failed to register ",Po,e)}}async stop(){try{await this.libp2p.unhandle(Po)}catch(e){xo.error("Failed to unregister ",Po,e)}}async subscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return{success:null,failure:{error:Cs.NO_STREAM_AVAILABLE,peerId:t}};const i=Co.createSubscribeRequest(e,r);let s;try{if(s=await uo([i.encode()],Ks,n,Ys,(async e=>await Ds(e))),!(null==s?void 0:s.length))throw Error("Received no response from subscription request.")}catch(e){return xo.error("Failed to send subscribe request",e),{success:null,failure:{error:Cs.GENERIC_FAIL,peerId:t}}}const{statusCode:o,requestId:a,statusDesc:l}=ko.decode(s[0].slice());return o<200||o>=300?(xo.error(`Filter subscribe request ${a} failed with status code ${o}: ${l}`),{failure:{error:Cs.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async unsubscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return xo.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Cs.NO_STREAM_AVAILABLE,peerId:t}};const i=Co.createUnsubscribeRequest(e,r);try{await uo([i.encode()],Ks,n.sink)}catch(e){return xo.error("Failed to send unsubscribe request",e),{success:null,failure:{error:Cs.GENERIC_FAIL,peerId:t}}}return{success:t,failure:null}}async unsubscribeAll(e,t){const r=await this.streamManager.getStream(t);if(!r)return xo.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Cs.NO_STREAM_AVAILABLE,peerId:t}};const n=Co.createUnsubscribeAllRequest(e),i=await uo([n.encode()],Ks,r,Ys,(async e=>await Ds(e)));if(!i||!i.length)return{failure:{error:Cs.NO_RESPONSE,peerId:t},success:null};const{statusCode:s,requestId:o,statusDesc:a}=ko.decode(i[0].slice());return s<200||s>=300?(xo.error(`Filter unsubscribe all request ${o} failed with status code ${s}: ${a}`),{failure:{error:Cs.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async ping(e){const t=await this.streamManager.getStream(e);if(!t)return xo.error("Failed to get a stream for remote peer:"+e.toString()),{success:null,failure:{error:Cs.NO_STREAM_AVAILABLE,peerId:e}};const r=Co.createSubscriberPingRequest();let n;try{n=await uo([r.encode()],Ks,t,Ys,(async e=>await Ds(e)))}catch(t){return xo.error("Failed to send ping request",t),{success:null,failure:{error:Cs.GENERIC_FAIL,peerId:e}}}if(!n||!n.length)return{success:null,failure:{error:Cs.NO_RESPONSE,peerId:e}};const{statusCode:i,requestId:s,statusDesc:o}=ko.decode(n[0].slice());return i<200||i>=300?(xo.error(`Filter ping request ${s} failed with status code ${i}: ${o}`),{success:null,failure:{error:Cs.REMOTE_PEER_REJECTED,peerId:e}}):{success:e,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;xo.info("Received message from "+n.toString());try{uo(r,Ys,(async e=>{for await(const r of e){const e=_o.decode(r.slice()),{pubsubTopic:n,wakuMessage:i}=e;if(!i)return void xo.error("Received empty message");if(!n)return void xo.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,i,t.remotePeer.toString())}})).then((()=>{xo.info("Receiving pipe closed.")}),(async e=>{xo.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)}))}catch(e){xo.error("Error decoding message",e)}}constructor(e,t){(0,L.default)(this,"handleIncomingMessage",void 0),(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"streamManager",void 0),(0,L.default)(this,"multicodec",To),this.handleIncomingMessage=e,this.libp2p=t,this.streamManager=new yo(To,t.components)}}const Lo="/vac/waku/lightpush/2.0.0-beta1",Do="/vac/waku/lightpush/3.0.0",Mo=Lo,No=Do;class Oo{static createRequest(e,t){return new Oo({requestId:Io(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=kr.decode(e);return new Oo(t)}encode(){return kr.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}constructor(e){(0,L.default)(this,"proto",void 0),this.proto=e}}class Uo{static createRequest(e,t){return new Uo({requestId:Io(),pubsubTopic:t,message:e})}static createResponse(e,t,r,n){return new Uo({requestId:e,statusCode:t,statusDesc:r,relayPeerCount:n})}static decodeRequest(e){const t=xr.decode(e);return new Uo(t)}static decodeResponse(e){const t=Tr.decode(e);return new Uo(t)}encode(){return this.isRequest()?xr.encode(this.proto):Tr.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}constructor(e){(0,L.default)(this,"proto",void 0),this.proto=e}}const Fo=new gs("light-push:protocol-handler");class Bo{static async preparePushMessage(e,t,r){try{if(!t.payload||0===t.payload.length)return Fo.error("Failed to send waku light push: payload is empty"),{rpc:null,error:_s.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return Fo.error("Failed to send waku light push: message is bigger than 1MB"),{rpc:null,error:_s.SIZE_TOO_BIG};const n=await e.toProtoObj(t);return n?r===Do?(Fo.info("Creating v3 RPC message"),{rpc:Bo.createV3Rpc(n,e.pubsubTopic),error:null}):(Fo.info("Creating v2 RPC message"),{rpc:Bo.createV2Rpc(n,e.pubsubTopic),error:null}):(Fo.error("Failed to encode to protoMessage, aborting push"),{rpc:null,error:_s.ENCODE_FAILED})}catch(e){return Fo.error("Failed to prepare push message",e),{rpc:null,error:_s.GENERIC_FAIL}}}static handleResponse(e,t,r){return t===Do?Bo.handleV3Response(e,r):Bo.handleV2Response(e,r)}static handleV3Response(e,t){try{const r=Uo.decodeResponse(e),n=r.statusCode,i=r.statusDesc;if(n!==As.SUCCESS){const e=_s.REMOTE_PEER_REJECTED;return Fo.error(`Remote peer rejected with v3 status code ${n}: ${i}`),{success:null,failure:{error:e,peerId:t}}}return void 0!==r.relayPeerCount&&Fo.info(`Message relayed to ${r.relayPeerCount} peers`),{success:t,failure:null}}catch(e){return{success:null,failure:{error:_s.DECODE_FAILED,peerId:t}}}}static handleV2Response(e,t){let r;try{r=Oo.decode(e).response}catch(e){return{success:null,failure:{error:_s.DECODE_FAILED,peerId:t}}}var n;return r?(n=r.info)&&(n.includes("could not generate rln proof")||n.includes("could not get new message id to generate an rln proof")||n.includes("RLN validation failed"))?(Fo.error("Remote peer fault: RLN generation"),{success:null,failure:{error:_s.RLN_PROOF_GENERATION,peerId:t}}):r.isSuccess?{success:t,failure:null}:(Fo.error("Remote peer rejected the message: ",r.info),{success:null,failure:{error:_s.REMOTE_PEER_REJECTED,peerId:t}}):{success:null,failure:{error:_s.NO_RESPONSE,peerId:t}}}static createV2Rpc(e,t){const r=Oo.createRequest(e,t);return Object.assign(r,{version:"v2"})}static createV3Rpc(e,t){e.timestamp||(e.timestamp=BigInt(Date.now())*BigInt(1e6));const r=Uo.createRequest(e,t);return Object.assign(r,{version:"v3"})}}const $o=new gs("light-push");class qo{async send(e,t,r,n=!1){const i=await this.getProtocol(r,n);if($o.info(`Sending light push request to peer:${r.toString()}, protocol:${i}`),!i)return{success:null,failure:{error:_s.GENERIC_FAIL,peerId:r}};const{rpc:s,error:o}=await Bo.preparePushMessage(e,t,i);if(o)return{success:null,failure:{error:o,peerId:r}};const a=await this.getStream(r,i);if(!a)return $o.error("Failed to get a stream for remote peer:"+r.toString()),{success:null,failure:{error:_s.NO_STREAM_AVAILABLE,peerId:r}};let l;try{l=await uo([s.encode()],Ks,a,Ys,(async e=>await Ds(e)))}catch(e){return $o.error("Failed to send waku light push request",e),{success:null,failure:{error:_s.STREAM_ABORTED,peerId:r}}}const u=new qs;return l.forEach((e=>u.append(e))),0===u.length?{success:null,failure:{error:_s.NO_RESPONSE,peerId:r}}:Bo.handleResponse(u,i,r)}async getProtocol(e,t){try{const r=await this.libp2p.peerStore.get(e);if(t||!r.protocols.includes(Do)&&r.protocols.includes(Lo))return Lo;if(r.protocols.includes(Do))return Do;throw Error("No supported protocol found")}catch(e){return void $o.error("Failed to get protocol",e)}}async getStream(e,t){switch(t){case Lo:return this.streamManagerV2.getStream(e);case Do:return this.streamManager.getStream(e);default:return}}constructor(e){(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"streamManager",void 0),(0,L.default)(this,"streamManagerV2",void 0),(0,L.default)(this,"multicodec",[Do,Lo]),this.libp2p=e,this.streamManagerV2=new yo(Lo,e.components),this.streamManager=new yo(Do,e.components)}}const zo={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},jo=864e5,Ko=1e6;class Vo{static create(e){const t=new Vo((0,M.default)((0,D.default)({},e),{contentTopics:e.contentTopics||[],requestId:Io(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*Ko):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*Ko):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0})),r=e.messageHashes&&e.messageHashes.length>0,n=e.contentTopics&&e.contentTopics.length>0,i=e.timeStart||e.timeEnd;if(r){if(n||i)throw Error("Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)")}else if(e.pubsubTopic&&(!e.contentTopics||0===e.contentTopics.length)||!e.pubsubTopic&&e.contentTopics&&e.contentTopics.length>0)throw Error("Both pubsubTopic and contentTopics must be set together for content-filtered queries");return t}static decode(e){const t=Dr.decode(e);return new Vo(t)}encode(){return Dr.encode(this.proto)}constructor(e){(0,L.default)(this,"proto",void 0),this.proto=e}}class Ho{static decode(e){const t=Mr.decode(e);return new Ho(t)}encode(){return Mr.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}constructor(e){(0,L.default)(this,"proto",void 0),this.proto=e}}const Wo=new gs("store"),Go="/vac/waku/store-query/3.0.0";class Xo{get maxTimeLimit(){return jo}async*queryPerPage(e,t,r){if(e.timeStart&&e.timeEnd&&e.timeEnd.getTime()-e.timeStart.getTime()>jo)throw Error("Time range bigger than 24h");if(!(e.messageHashes&&e.messageHashes.length>0)&&e.contentTopics&&e.contentTopics.toString()!==Array.from(t.keys()).toString())throw Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){var i,s;const o=Vo.create((0,M.default)((0,D.default)({},e),{paginationCursor:n}));Wo.info("Sending store query request:",{hasMessageHashes:!!(null===(i=e.messageHashes)||void 0===i?void 0:i.length),messageHashCount:null===(s=e.messageHashes)||void 0===s?void 0:s.length,pubsubTopic:e.pubsubTopic,contentTopics:e.contentTopics});const a=await this.streamManager.getStream(r);if(!a){Wo.error("Failed to get a stream for remote peer:"+r.toString());break}const l=await uo([o.encode()],Ks,a,Ys,(async e=>await Ds(e))),u=new qs;l.forEach((e=>{u.append(e)}));const c=Ho.decode(u);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw Wo.error(e),Error(e)}if(!c.messages||!c.messages.length){Wo.warn("Stopping pagination due to empty messages in response");break}Wo.info(c.messages.length+" messages retrieved from store");const d=c.messages.map((e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const i=t.get(r);if(i)return i.fromProtoObj(e.pubsubTopic||"",(n=e.message,(0,D.default)({},zo,n)))}var n;return Promise.resolve(void 0)}));if(yield d,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}constructor(e){(0,L.default)(this,"streamManager",void 0),(0,L.default)(this,"multicodec",Go),this.streamManager=new yo(Go,e.components)}}const Zo=parseInt("11111",2),Yo=parseInt("10000000",2),Qo=parseInt("01111111",2),Jo={0:ra,1:ra,2(e,t){const r=ta(e,t),n=t.offset,i=t.offset+r,s=[];for(let t=n;t<i;t++)t===n&&0===e[t]||s.push(e[t]);return t.offset+=r,Uint8Array.from(s)},3(e,t){const r=ta(e,t),n=e[t.offset];t.offset++;const i=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return i},4(e,t){const r=ta(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=ta(e,t),n=t.offset+r,i=e[t.offset];t.offset++;let s=0,o=0;i<40?(s=0,o=i):i<80?(s=1,o=i-40):(s=2,o=i-80);let a=`${s}.${o}`,l=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,l.push(127&r),r<128){l.reverse();let e=0;for(let t=0;t<l.length;t++)e+=l[t]<<7*t;a+="."+e,l=[]}}return a},16:ra,22:ra,48:ra};function ea(e,t={offset:0}){const r=e[t.offset]&Zo;if(t.offset++,null!=Jo[r])return Jo[r](e,t);throw Error("No decoder for tag "+r)}function ta(e,t){let r=0;if((e[t.offset]&Yo)===Yo){const n=e[t.offset]&Qo;let i="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)i+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(i,16)}else r=e[t.offset],t.offset++;return r}function ra(e,t){ta(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=ea(e,t);if(null===n)break;r.push(n)}return r}function na(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new qs;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new qs(Uint8Array.from([t.byteLength|Yo]),t)}function ia(e){const t=new qs;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new qs(Uint8Array.from([2]),na(t),t)}function sa(e){const t=Uint8Array.from([0]),r=new qs(t,e);return new qs(Uint8Array.from([3]),na(r),r)}function oa(e,t=48){const r=new qs;for(const t of e)r.append(t);return new qs(Uint8Array.from([t]),na(r),r)}const aa=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),la=Uint8Array.from([6,5,43,129,4,0,34]),ua=Uint8Array.from([6,5,43,129,4,0,35]),ca={ext:!0,kty:"EC",crv:"P-256"},da={ext:!0,kty:"EC",crv:"P-384"},ha={ext:!0,kty:"EC",crv:"P-521"},fa=32,pa=48,ga=66;function ma(e){return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=ri(t.subarray(1,1+fa),"base64url"),n=ri(t.subarray(1+fa),"base64url"),new ya((0,M.default)((0,D.default)({},ca),{key_ops:["verify"],x:r,y:n}));if(97===t.byteLength)return r=ri(t.subarray(1,1+pa),"base64url"),n=ri(t.subarray(1+pa),"base64url"),new ya((0,M.default)((0,D.default)({},da),{key_ops:["verify"],x:r,y:n}));if(133===t.byteLength)return r=ri(t.subarray(1,1+ga),"base64url"),n=ri(t.subarray(1+ga),"base64url"),new ya((0,M.default)((0,D.default)({},ha),{key_ops:["verify"],x:r,y:n}));throw new Pi(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(ea(e))}function va(e){if("P-256"===e)return aa;if("P-384"===e)return la;if("P-521"===e)return ua;throw new Pi("Invalid curve "+e)}let ya=class{get raw(){var e,t,r;return null==this._raw&&(this._raw=(e=this.jwk,oa([ia(Uint8Array.from([1])),oa([va(e.crv)],160),oa([sa(new qs(Uint8Array.from([4]),Zt(null!==(t=e.x)&&void 0!==t?t:"","base64url"),Zt(null!==(r=e.y)&&void 0!==r?r:"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return Lt.digest(Lu(this))}toCID(){return $t.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ns(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){var i,s,o;const a=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:null!==(o=e.crv)&&void 0!==o?o:"P-256"},!1,["verify"]);null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();const l=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},a,t,r.subarray());return null==n||null===(s=n.signal)||void 0===s||s.throwIfAborted(),l}(this.jwk,t,e,r)}constructor(e){(0,L.default)(this,"type","ECDSA"),(0,L.default)(this,"jwk",void 0),(0,L.default)(this,"_raw",void 0),this.jwk=e}};const ba=BigInt(0),wa=BigInt(1);function Ea(e,t=""){if("boolean"!=typeof e)throw Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function Sa(e,t,r=""){const n=Jr(e),i=null==e?void 0:e.length,s=void 0!==t;if(!n||s&&i!==t)throw Error((r&&`"${r}" `)+"expected Uint8Array"+(s?" of length "+t:"")+", got "+(n?"length="+i:"type="+typeof e));return e}function Aa(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Ia(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return""===e?ba:BigInt("0x"+e)}function _a(e){return Ia(cn(e))}function Ca(e){return tn(e),Ia(cn(Uint8Array.from(e).reverse()))}function ka(e,t){return yn(e.toString(16).padStart(2*t,"0"))}function xa(e,t){return ka(e,t).reverse()}function Ta(e,t,r){let n;if("string"==typeof t)try{n=yn(t)}catch(t){throw Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Jr(t))throw Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const i=n.length;if("number"==typeof r&&i!==r)throw Error(e+" of length "+r+" expected, got "+i);return n}function Pa(e){return Uint8Array.from(e)}const Ra=e=>"bigint"==typeof e&&ba<=e;function La(e,t,r,n){if(!function(e,t,r){return Ra(e)&&Ra(t)&&Ra(r)&&t<=e&&e<r}(t,r,n))throw Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Da(e){let t;for(t=0;e>ba;e>>=wa,t+=1);return t}const Ma=e=>(wa<<BigInt(e))-wa;function Na(e,t,r={}){if(!e||"object"!=typeof e)throw Error("expected valid options object");function n(t,r,n){const i=e[t];if(n&&void 0===i)return;const s=typeof i;if(s!==r||null===i)throw Error(`param "${t}" is invalid: expected ${r}, got ${s}`)}Object.entries(t).forEach((([e,t])=>n(e,t,!1))),Object.entries(r).forEach((([e,t])=>n(e,t,!0)))}function Oa(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(void 0!==i)return i;const s=e(r,...n);return t.set(r,s),s}}const Ua=BigInt(0),Fa=BigInt(1),Ba=BigInt(2),$a=BigInt(3),qa=BigInt(4),za=BigInt(5),ja=BigInt(7),Ka=BigInt(8),Va=BigInt(9),Ha=BigInt(16);function Wa(e,t){const r=e%t;return r>=Ua?r:t+r}function Ga(e,t,r){let n=e;for(;t-- >Ua;)n*=n,n%=r;return n}function Xa(e,t){if(e===Ua)throw Error("invert: expected non-zero number");if(t<=Ua)throw Error("invert: expected positive modulus, got "+t);let r=Wa(e,t),n=t,i=Ua,s=Fa;for(;r!==Ua;){const e=n%r,t=i-s*(n/r);n=r,r=e,i=s,s=t}if(n!==Fa)throw Error("invert: does not exist");return Wa(i,t)}function Za(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function Ya(e,t){const r=(e.ORDER+Fa)/qa,n=e.pow(t,r);return Za(e,n,t),n}function Qa(e,t){const r=(e.ORDER-za)/Ka,n=e.mul(t,Ba),i=e.pow(n,r),s=e.mul(t,i),o=e.mul(e.mul(s,Ba),i),a=e.mul(s,e.sub(o,e.ONE));return Za(e,a,t),a}function Ja(e){if(e<$a)throw Error("sqrt is not defined for small field");let t=e-Fa,r=0;for(;t%Ba===Ua;)t/=Ba,r++;let n=Ba;const i=il(e);for(;1===rl(i,n);)if(n++>1e3)throw Error("Cannot find square root: probably non-prime P");if(1===r)return Ya;let s=i.pow(n,t);const o=(t+Fa)/Ba;return function(e,n){if(e.is0(n))return n;if(1!==rl(e,n))throw Error("Cannot find square root");let i=r,a=e.mul(e.ONE,s),l=e.pow(n,t),u=e.pow(n,o);for(;!e.eql(l,e.ONE);){if(e.is0(l))return e.ZERO;let t=1,r=e.sqr(l);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===i)throw Error("Cannot find square root");const n=Fa<<BigInt(i-t-1),s=e.pow(a,n);i=t,a=e.sqr(s),l=e.mul(l,a),u=e.mul(u,s)}return u}}const el=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function tl(e,t,r=!1){const n=Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce(((t,r,i)=>e.is0(r)?t:(n[i]=t,e.mul(t,r))),e.ONE),s=e.inv(i);return t.reduceRight(((t,r,i)=>e.is0(r)?t:(n[i]=e.mul(t,n[i]),e.mul(t,r))),s),n}function rl(e,t){const r=(e.ORDER-Fa)/Ba,n=e.pow(t,r),i=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!i&&!s&&!o)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function nl(e,t){void 0!==t&&en(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function il(e,t,r=!1,n={}){if(e<=Ua)throw Error("invalid field: expected ORDER > 0, got "+e);let i,s,o,a=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw Error("cannot specify opts in two arguments");const e=t;e.BITS&&(i=e.BITS),e.sqrt&&(s=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(i=t),n.sqrt&&(s=n.sqrt);const{nBitLength:l,nByteLength:u}=nl(e,i);if(u>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let c;const d=Object.freeze({ORDER:e,isLE:r,BITS:l,BYTES:u,MASK:Ma(l),ZERO:Ua,ONE:Fa,allowedLengths:o,create:t=>Wa(t,e),isValid(t){if("bigint"!=typeof t)throw Error("invalid field element: expected bigint, got "+typeof t);return Ua<=t&&t<e},is0:e=>e===Ua,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&Fa)===Fa,neg:t=>Wa(-t,e),eql:(e,t)=>e===t,sqr:t=>Wa(t*t,e),add:(t,r)=>Wa(t+r,e),sub:(t,r)=>Wa(t-r,e),mul:(t,r)=>Wa(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Ua)throw Error("invalid exponent, negatives unsupported");if(r===Ua)return e.ONE;if(r===Fa)return t;let n=e.ONE,i=t;for(;r>Ua;)r&Fa&&(n=e.mul(n,i)),i=e.sqr(i),r>>=Fa;return n}(d,e,t),div:(t,r)=>Wa(t*Xa(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Xa(t,e),sqrt:s||(t=>(c||(c=function(e){return e%qa===$a?Ya:e%Ka===za?Qa:e%Ha===Va?function(e){const t=il(e),r=Ja(e),n=r(t,t.neg(t.ONE)),i=r(t,n),s=r(t,t.neg(n)),o=(e+ja)/Ha;return(e,t)=>{let r=e.pow(t,o),a=e.mul(r,n);const l=e.mul(r,i),u=e.mul(r,s),c=e.eql(e.sqr(a),t),d=e.eql(e.sqr(l),t);r=e.cmov(r,a,c),a=e.cmov(u,l,d);const h=e.eql(e.sqr(a),t),f=e.cmov(r,a,h);return Za(e,f,t),f}}(e):Ja(e)}(e)),c(d,t))),toBytes:e=>r?xa(e,u):ka(e,u),fromBytes(t,n=!0){if(o){if(!o.includes(t.length)||t.length>u)throw Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(u);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==u)throw Error("Field.fromBytes: expected "+u+" bytes, got "+t.length);let i=r?Ca(t):_a(t);if(a&&(i=Wa(i,e)),!n&&!d.isValid(i))throw Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:e=>tl(d,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(d)}function sl(e){if("bigint"!=typeof e)throw Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function ol(e){const t=sl(e);return t+Math.ceil(t/2)}const al=BigInt(0),ll=BigInt(1);function ul(e,t){const r=t.negate();return e?r:t}function cl(e,t){const r=tl(e.Fp,t.map((e=>e.Z)));return t.map(((t,n)=>e.fromAffine(t.toAffine(r[n]))))}function dl(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function hl(e,t){dl(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Ma(e),maxNumber:r,shiftBy:BigInt(e)}}function fl(e,t,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(e&i),l=e>>o;a>n&&(a-=s,l+=ll);const u=t*n;return{nextN:l,offset:u+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:u}}const pl=new WeakMap,gl=new WeakMap;function ml(e){return gl.get(e)||1}function vl(e){if(e!==al)throw Error("invalid wNAF")}class yl{_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>al;)t&ll&&(r=r.add(n)),n=n.double(),t>>=ll;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=hl(t,this.bits),i=[];let s=e,o=s;for(let e=0;e<r;e++){o=s,i.push(o);for(let e=1;e<n;e++)o=o.add(s),i.push(o);s=o.double()}return i}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let n=this.ZERO,i=this.BASE;const s=hl(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:o,offset:a,isZero:l,isNeg:u,isNegF:c,offsetF:d}=fl(r,e,s);r=o,l?i=i.add(ul(c,t[d])):n=n.add(ul(u,t[a]))}return vl(r),{p:n,f:i}}wNAFUnsafe(e,t,r,n=this.ZERO){const i=hl(e,this.bits);for(let e=0;e<i.windows&&r!==al;e++){const{nextN:s,offset:o,isZero:a,isNeg:l}=fl(r,e,i);if(r=s,!a){const e=t[o];n=n.add(l?e.negate():e)}}return vl(r),n}getPrecomputes(e,t,r){let n=pl.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),pl.set(t,n))),n}cached(e,t,r){const n=ml(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const i=ml(e);return 1===i?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)}createCache(e,t){dl(t,this.bits),gl.set(e,t),pl.delete(e)}hasCache(e){return 1!==ml(e)}constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}}function bl(e,t,r,n){!function(e,t){if(!Array.isArray(e))throw Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw Error("invalid scalar at index "+r)}))}(n,t);const i=r.length,s=n.length;if(i!==s)throw Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Da(BigInt(i));let l=1;a>12?l=a-3:a>4?l=a-2:a>0&&(l=2);const u=Ma(l),c=Array(Number(u)+1).fill(o);let d=o;for(let e=Math.floor((t.BITS-1)/l)*l;e>=0;e-=l){c.fill(o);for(let t=0;t<s;t++){const i=n[t],s=Number(i>>BigInt(e)&u);c[s]=c[s].add(r[t])}let t=o;for(let e=c.length-1,r=o;e>0;e--)r=r.add(c[e]),t=t.add(r);if(d=d.add(t),0!==e)for(let e=0;e<l;e++)d=d.double()}return d}function wl(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=el.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});Na(e,t)}(t),t}return il(e,{isLE:r})}function El(e,t,r={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const r=t[e];if(!("bigint"==typeof r&&r>al))throw Error(`CURVE.${e} must be positive bigint`)}const i=wl(t.p,r.Fp,n),s=wl(t.n,r.Fn,n),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:i,Fn:s}}const Sl=BigInt(0),Al=BigInt(1),Il=BigInt(2),_l=BigInt(8);function Cl(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:i}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:il(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e),s=function(e,t={}){const r=El("edwards",e,t,t.FpFnLE),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:o}=s;Na(t,{},{uvRatio:"function"});const a=Il<<BigInt(8*i.BYTES)-Al,l=e=>n.create(e),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:Sl}}});if(!((e,t,r,n)=>{const i=e.sqr(r),s=e.sqr(n),o=e.add(e.mul(t.a,i),s),a=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(o,a)})(n,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");function c(e,t,r=!1){return La("coordinate "+e,t,r?Al:Sl,a),t}function d(e){if(!(e instanceof p))throw Error("ExtendedPoint expected")}const h=Oa(((e,t)=>{const{X:r,Y:i,Z:s}=e,o=e.is0();null==t&&(t=o?_l:n.inv(s));const a=l(r*t),u=l(i*t),c=n.mul(s,t);if(o)return{x:Sl,y:Al};if(c!==Al)throw Error("invZ was invalid");return{x:a,y:u}})),f=Oa((e=>{const{a:t,d:r}=s;if(e.is0())throw Error("bad point: ZERO");const{X:n,Y:i,Z:o,T:a}=e,u=l(n*n),c=l(i*i),d=l(o*o),h=l(d*d),f=l(u*t);if(l(d*l(f+c))!==l(h+l(r*l(u*c))))throw Error("bad point: equation left != right (1)");if(l(n*i)!==l(o*a))throw Error("bad point: equation left != right (2)");return!0}));class p{static CURVE(){return s}static fromAffine(e){if(e instanceof p)throw Error("extended point not allowed");const{x:t,y:r}=e||{};return c("x",t),c("y",r),new p(t,r,Al,l(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:i,d:o}=s;e=Pa(Sa(e,r,"point")),Ea(t,"zip215");const c=Pa(e),d=e[r-1];c[r-1]=-129&d;const h=Ca(c),f=t?a:n.ORDER;La("point.y",h,Sl,f);const g=l(h*h),m=l(g-Al),v=l(o*g-i);let{isValid:y,value:b}=u(m,v);if(!y)throw Error("bad point: invalid y coordinate");const w=(b&Al)===Al,E=!!(128&d);if(!t&&b===Sl&&E)throw Error("bad point: x=0 and x_0=1");return E!==w&&(b=l(-b)),p.fromAffine({x:b,y:h})}static fromHex(e,t=!1){return p.fromBytes(Ta("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(Il),this}assertValidity(){f(this)}equals(e){d(e);const{X:t,Y:r,Z:n}=this,{X:i,Y:s,Z:o}=e,a=l(t*o),u=l(i*n),c=l(r*o),h=l(s*n);return a===u&&c===h}is0(){return this.equals(p.ZERO)}negate(){return new p(l(-this.X),this.Y,this.Z,l(-this.T))}double(){const{a:e}=s,{X:t,Y:r,Z:n}=this,i=l(t*t),o=l(r*r),a=l(Il*l(n*n)),u=l(e*i),c=t+r,d=l(l(c*c)-i-o),h=u+o,f=h-a,g=u-o,m=l(d*f),v=l(h*g),y=l(d*g),b=l(f*h);return new p(m,v,b,y)}add(e){d(e);const{a:t,d:r}=s,{X:n,Y:i,Z:o,T:a}=this,{X:u,Y:c,Z:h,T:f}=e,g=l(n*u),m=l(i*c),v=l(a*r*f),y=l(o*h),b=l((n+i)*(u+c)-g-m),w=y-v,E=y+v,S=l(m-t*g),A=l(b*w),I=l(E*S),_=l(b*S),C=l(w*E);return new p(A,I,C,_)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:r}=g.cached(this,e,(e=>cl(p,e)));return cl(p,[t,r])[0]}multiplyUnsafe(e,t=p.ZERO){if(!i.isValid(e))throw Error("invalid scalar: expected 0 <= sc < curve.n");return e===Sl?p.ZERO:this.is0()||e===Al?this:g.unsafe(this,e,(e=>cl(p,e)),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return o===Al?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&Al?128:0,r}toHex(){return cn(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(e){return cl(p,e)}static msm(e,t){return bl(p,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}constructor(e,t,r,n){this.X=c("x",e),this.Y=c("y",t),this.Z=c("z",r,!0),this.T=c("t",n),Object.freeze(this)}}p.BASE=new p(s.Gx,s.Gy,Al,l(s.Gx*s.Gy)),p.ZERO=new p(Sl,Al,Al,Sl),p.Fp=n,p.Fn=i;const g=new yl(p,i.BITS);return p.BASE.precompute(8),p}(t,r);return function(e,t){const r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(e,function(e,t,r={}){if("function"!=typeof t)throw Error('"hash" function param is required');Na(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:i,Fp:s,Fn:o}=e,a=r.randomBytes||An,l=r.adjustScalarBytes||(e=>e),u=r.domain||((e,t,r)=>{if(Ea(r,"phflag"),t.length||r)throw Error("Contexts/pre-hash are not supported");return e});function c(e){return o.create(Ca(e))}function d(e){const{head:r,prefix:n,scalar:s}=function(e){const r=m.secretKey;e=Ta("private key",e,r);const n=Ta("hashed private key",t(e),2*r),i=l(n.slice(0,r));return{head:i,prefix:n.slice(r,2*r),scalar:c(i)}}(e),o=i.multiply(s),a=o.toBytes();return{head:r,prefix:n,scalar:s,point:o,pointBytes:a}}function h(e){return d(e).pointBytes}function f(e=Uint8Array.of(),...r){const i=wn(...r);return c(t(u(i,Ta("context",e),!!n)))}const p={zip215:!0},g=s.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function v(e=a(m.seed)){return Sa(e,m.seed,"seed")}const y={getExtendedPublicKey:d,randomSecretKey:v,isValidSecretKey:e=>Jr(e)&&e.length===o.BYTES,isValidPublicKey(t,r){try{return!!e.fromBytes(t,r)}catch(e){return!1}},toMontgomery(t){const{y:r}=e.fromBytes(t),n=m.publicKey,i=32===n;if(!i&&57!==n)throw Error("only defined for 25519 and 448");const o=i?s.div(Al+r,Al-r):s.div(r-Al,r+Al);return s.toBytes(o)},toMontgomerySecret(e){const r=m.secretKey;Sa(e,r);const n=t(e.subarray(0,r));return l(n).subarray(0,r)},randomPrivateKey:v,precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen(e){const t=y.randomSecretKey(e);return{secretKey:t,publicKey:h(t)}},getPublicKey:h,sign(e,t,r={}){e=Ta("message",e),n&&(e=n(e));const{prefix:s,scalar:a,pointBytes:l}=d(t),u=f(r.context,s,e),c=i.multiply(u).toBytes(),h=f(r.context,c,l,e),p=o.create(u+h*a);if(!o.isValid(p))throw Error("sign failed: invalid s");return Sa(wn(c,o.toBytes(p)),m.signature,"result")},verify(t,r,s,o=p){const{context:a,zip215:l}=o,u=m.signature;t=Ta("signature",t,u),r=Ta("message",r),s=Ta("publicKey",s,m.publicKey),void 0!==l&&Ea(l,"zip215"),n&&(r=n(r));const c=u/2,d=t.subarray(0,c),h=Ca(t.subarray(c,u));let g,v,y;try{g=e.fromBytes(s,l),v=e.fromBytes(d,l),y=i.multiplyUnsafe(h)}catch(e){return!1}if(!l&&g.isSmallOrder())return!1;const b=f(a,v.toBytes(),g.toBytes(),r);return v.add(g.multiplyUnsafe(b)).subtract(y).clearCofactor().is0()},utils:y,Point:e,lengths:m})}(s,n,i))}const kl=BigInt(0),xl=BigInt(1),Tl=BigInt(2);const Pl=BigInt(1),Rl=BigInt(2),Ll=BigInt(3),Dl=BigInt(5),Ml=BigInt(8),Nl=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ol={p:Nl,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ml,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ul(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=Nl,o=e*e%s*e%s,a=Ga(o,Rl,s)*o%s,l=Ga(a,Pl,s)*e%s,u=Ga(l,Dl,s)*l%s,c=Ga(u,t,s)*u%s,d=Ga(c,r,s)*c%s,h=Ga(d,n,s)*d%s,f=Ga(h,i,s)*h%s,p=Ga(f,i,s)*h%s,g=Ga(p,t,s)*u%s;return{pow_p_5_8:Ga(g,Rl,s)*e%s,b2:o}}function Fl(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Bl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function $l(e,t){const r=Nl,n=Wa(t*t*t,r),i=Wa(n*n*t,r);let s=Wa(e*n*Ul(e*i).pow_p_5_8,r);const o=Wa(t*s*s,r),a=s,l=Wa(s*Bl,r),u=o===e,c=o===Wa(-e,r),d=o===Wa(-e*Bl,r);return u&&(s=a),(c||d)&&(s=l),(Wa(s,r)&Fa)===Fa&&(s=Wa(-s,r)),{isValid:u||c,value:s}}const ql=il(Ol.p,{isLE:!0}),zl=Cl((0,M.default)((0,D.default)({},Ol),{Fp:ql,hash:ei,adjustScalarBytes:Fl,uvRatio:$l})),jl=(()=>{const e=ql.ORDER;return function(e){const t=(Na(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze((0,D.default)({},r)));var r;const{P:n,type:i,adjustScalarBytes:s,powPminus2:o,randomBytes:a}=t,l="x25519"===i;if(!l&&"x448"!==i)throw Error("invalid type");const u=a||An,c=l?255:448,d=l?32:56,h=l?BigInt(9):BigInt(5),f=l?BigInt(121665):BigInt(39081),p=l?Tl**BigInt(254):Tl**BigInt(447),g=l?BigInt(8)*Tl**BigInt(251)-xl:BigInt(4)*Tl**BigInt(445)-xl,m=p+g+xl,v=e=>Wa(e,n),y=b(h);function b(e){return xa(v(e),d)}function w(e,t){const r=function(e,t){La("u",e,kl,n),La("scalar",t,p,m);const r=t,i=e;let s=xl,a=kl,l=e,u=xl,d=kl;for(let e=BigInt(c-1);e>=kl;e--){const t=r>>e&xl;d^=t,({x_2:s,x_3:l}=S(d,s,l)),({x_2:a,x_3:u}=S(d,a,u)),d=t;const n=s+a,o=v(n*n),c=s-a,h=v(c*c),p=o-h,g=l+u,m=v((l-u)*n),y=v(g*c),b=m+y,w=m-y;l=v(b*b),u=v(i*v(w*w)),s=v(o*h),a=v(p*(o+v(f*p)))}({x_2:s,x_3:l}=S(d,s,l)),({x_2:a,x_3:u}=S(d,a,u));const h=o(a);return v(s*h)}(function(e){const t=Ta("u coordinate",e,d);return l&&(t[31]&=127),v(Ca(t))}(t),function(e){return Ca(s(Ta("scalar",e,d)))}(e));if(r===kl)throw Error("invalid private or public key received");return b(r)}function E(e){return w(e,y)}function S(e,t,r){const n=v(e*(t-r));return{x_2:t=v(t-n),x_3:r=v(r+n)}}const A={secretKey:d,publicKey:d,seed:d},I=(e=u(d))=>(tn(e,A.seed),e),_={randomSecretKey:I,randomPrivateKey:I};return{keygen(e){const t=I(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>w(e,t),getPublicKey:e=>E(e),scalarMult:w,scalarMultBase:E,utils:_,GuBytes:y.slice(),lengths:A}}({P:e,type:"x25519",powPminus2(t){const{pow_p_5_8:r,b2:n}=Ul(t);return Wa(Ga(r,Ll,e)*n,e)},adjustScalarBytes:Fl})})();let Kl=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Vl=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Hl={get(e=globalThis){const t=e.crypto;if(null==(null==t?void 0:t.subtle))throw new Vl("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 t}};let Wl;const Gl=(async()=>{try{return await Hl.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch(e){return!1}})();function Xl(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}let Zl=class{toMultihash(){return Lt.digest(Lu(this))}toCID(){return $t.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ns(this.raw,e.raw)}verify(e,t,r){var n;null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();const i=async function(e,t,r){return null==Wl&&(Wl=await Gl),Wl?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await Hl.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Hl.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return zl.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return Xl(i)?i.then((e=>{var t;return null==r||null===(t=r.signal)||void 0===t||t.throwIfAborted(),e})):i}constructor(e){(0,L.default)(this,"type","Ed25519"),(0,L.default)(this,"raw",void 0),this.raw=Jl(e,32)}};class Yl{equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ns(this.raw,e.raw)}sign(e,t){var r,n;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();const i=async function(e,t){return null==Wl&&(Wl=await Gl),Wl?async function(e,t){let r;r=64===e.length?e.subarray(0,32):e;const n={crv:"Ed25519",kty:"OKP",x:ri(e.subarray(32),"base64url"),d:ri(r,"base64url"),ext:!0,key_ops:["sign"]},i=await Hl.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Hl.get().subtle.sign({name:"Ed25519"},i,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(s,0,s.byteLength)}(e,t):function(e,t){const r=e.subarray(0,32);return zl.sign(t instanceof Uint8Array?t:t.subarray(),r)}(e,t)}(this.raw,e);return Xl(i)?i.then((e=>{var r;return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e})):(null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted(),i)}constructor(e,t){(0,L.default)(this,"type","Ed25519"),(0,L.default)(this,"raw",void 0),(0,L.default)(this,"publicKey",void 0),this.raw=Jl(e,64),this.publicKey=new Zl(t)}}function Ql(e){return e=Jl(e,32),new Zl(e)}function Jl(e,t){if((e=Uint8Array.from(null!=e?e:[])).length!==t)throw new Pi(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var eu,tu,ru,nu;function iu(e){if(isNaN(e)||e<=0)throw new Pi("random bytes length must be a Number bigger than 0");return An(e)}(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(eu||(eu={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(tu||(tu={})),(eu||(eu={})).codec=()=>Wr(tu),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eu.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=eu.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(ru||(ru={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eu.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=eu.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(nu||(nu={}));let su=class{get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Pi("JWK was missing components");return oa([ou,sa(oa([ia(Zt(e.n,"base64url")),ia(Zt(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return $t.createV1(114,this._multihash)}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ns(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){var i,s;const o=await Hl.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();const a=await Hl.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,r instanceof Uint8Array?r:r.subarray());return null==n||null===(s=n.signal)||void 0===s||s.throwIfAborted(),a}(this.jwk,t,e,r)}constructor(e,t){(0,L.default)(this,"type","RSA"),(0,L.default)(this,"jwk",void 0),(0,L.default)(this,"_raw",void 0),(0,L.default)(this,"_multihash",void 0),this.jwk=e,this._multihash=t}};const ou=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class au extends En{update(e){return nn(this),this.iHash.update(e),this}digestInto(e){nn(this),tn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:s,outputLen:o}=this;return e.finished=n,e.destroyed=i,e.blockLen=s,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}constructor(e,t){super(),this.finished=!1,this.destroyed=!1,rn(e);const r=bn(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),sn(i)}}const lu=(e,t,r)=>new au(e,t).update(r).digest();lu.create=(e,t)=>new au(e,t);const uu=(e,t)=>(e+(e>=0?t:-t)/gu)/t;function cu(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function du(e,t){const r={};for(let n of Object.keys(t))r[n]=void 0===e[n]?t[n]:e[n];return Ea(r.lowS,"lowS"),Ea(r.prehash,"prehash"),void 0!==r.format&&cu(r.format),r}const hu={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode(e,t){const{Err:r}=hu;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=Aa(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Aa(i.length/2|128):"";return Aa(e)+s+i+t},decode(e,t){const{Err:r}=hu;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++];let s=0;if(128&i){const e=127&i;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const o=t.subarray(n,n+e);if(o.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===o[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of o)s=s<<8|e;if(n+=e,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=i;const o=t.subarray(n,n+s);if(o.length!==s)throw new r("tlv.decode: wrong value length");return{v:o,l:t.subarray(n+s)}}},_int:{encode(e){const{Err:t}=hu;if(e<fu)throw new t("integer: negative integers are not allowed");let r=Aa(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=hu;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return _a(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=hu,i=Ta("signature",e),{v:s,l:o}=n.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:l}=n.decode(2,s),{v:u,l:c}=n.decode(2,l);if(c.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){const{_tlv:t,_int:r}=hu,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},fu=BigInt(0),pu=BigInt(1),gu=BigInt(2),mu=BigInt(3),vu=BigInt(4);function yu(e,t){const{BYTES:r}=e;let n;if("bigint"==typeof t)n=t;else{let i=Ta("private key",t);try{n=e.fromBytes(i)}catch(e){throw Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw Error("invalid private key: out of range [1..N-1]");return n}function bu(e){return Uint8Array.of(e?2:3)}function wu(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Eu(e,t,r={}){rn(t),Na(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||An,i=r.hmac||((e,...r)=>lu(t,e,wn(...r))),{Fp:s,Fn:o}=e,{ORDER:a,BITS:l}=o,{keygen:u,getPublicKey:c,getSharedSecret:d,utils:h,lengths:f}=function(e,t={}){const{Fn:r}=e,n=t.randomBytes||An,i=Object.assign(wu(e.Fp,r),{seed:ol(r.ORDER)});function s(e){try{return!!yu(r,e)}catch(e){return!1}}function o(e=n(i.seed)){return function(e,t,r=!1){const n=e.length,i=sl(t),s=ol(t);if(n<16||n<s||n>1024)throw Error("expected "+s+"-1024 bytes of input, got "+n);const o=Wa(r?Ca(e):_a(e),t-Fa)+Fa;return r?xa(o,i):ka(o,i)}(Sa(e,i.seed,"seed"),r.ORDER)}function a(t,n=!0){return e.BASE.multiply(yu(r,t)).toBytes(n)}function l(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:n,publicKey:s,publicKeyUncompressed:o}=i;if(r.allowedLengths||n===s)return;const a=Ta("key",t).length;return a===s||a===o}const u={isValidSecretKey:s,isValidPublicKey(t,r){const{publicKey:n,publicKeyUncompressed:s}=i;try{const i=t.length;return!(!0===r&&i!==n||!1===r&&i!==s||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:s,randomPrivateKey:o,normPrivateKeyToScalar:e=>yu(r,e),precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret(t,n,i=!0){if(!0===l(t))throw Error("first arg must be private key");if(!1===l(n))throw Error("second arg must be public key");const s=yu(r,t);return e.fromHex(n).multiply(s).toBytes(i)},keygen(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:u,lengths:i})}(e,r),p={prehash:!1,lowS:"boolean"==typeof r.lowS&&r.lowS,format:void 0,extraEntropy:!1},g="compact";function m(e){return e>a>>pu}function v(e,t){if(!o.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class y{static fromBytes(e,t=g){let r;if(function(e,t){cu(t);const r=f.signature;Sa(e,"compact"===t?r:"recovered"===t?r+1:void 0,t+" signature")}(e,t),"der"===t){const{r:t,s:r}=hu.toSig(Sa(e));return new y(t,r)}"recovered"===t&&(r=e[0],t="compact",e=e.subarray(1));const n=o.BYTES,i=e.subarray(0,n),s=e.subarray(n,2*n);return new y(o.fromBytes(i),o.fromBytes(s),r)}static fromHex(e,t){return this.fromBytes(yn(e),t)}addRecoveryBit(e){return new y(this.r,this.s,e)}recoverPublicKey(t){const r=s.ORDER,{r:n,s:i,recovery:l}=this;if(null==l||![0,1,2,3].includes(l))throw Error("recovery id invalid");if(a*gu<r&&l>1)throw Error("recovery id is ambiguous for h>1 curve");const u=2===l||3===l?n+a:n;if(!s.isValid(u))throw Error("recovery id 2 or 3 invalid");const c=s.toBytes(u),d=e.fromBytes(wn(bu(!(1&l)),c)),h=o.inv(u),f=w(Ta("msgHash",t)),p=o.create(-f*h),g=o.create(i*h),m=e.BASE.multiplyUnsafe(p).add(d.multiplyUnsafe(g));if(m.is0())throw Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=g){if(cu(e),"der"===e)return yn(hu.hexFromSig(this));const t=o.toBytes(this.r),r=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw Error("recovery bit must be present");return wn(Uint8Array.of(this.recovery),t,r)}return wn(t,r)}toHex(e){return cn(this.toBytes(e))}assertValidity(){}static fromCompact(e){return y.fromBytes(Ta("sig",e),"compact")}static fromDER(e){return y.fromBytes(Ta("sig",e),"der")}normalizeS(){return this.hasHighS()?new y(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return cn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return cn(this.toBytes("compact"))}constructor(e,t,r){this.r=v("r",e),this.s=v("s",t),null!=r&&(this.recovery=r),Object.freeze(this)}}const b=r.bits2int||function(e){if(e.length>8192)throw Error("input is too large");const t=_a(e),r=8*e.length-l;return r>0?t>>BigInt(r):t},w=r.bits2int_modN||function(e){return o.create(b(e))},E=Ma(l);function S(e){return La("num < 2^"+l,e,fu,E),o.toBytes(e)}function A(e,r){return Sa(e,void 0,"message"),r?Sa(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:u,getPublicKey:c,getSharedSecret:d,utils:h,lengths:f,Point:e,sign(r,s,a={}){r=Ta("message",r);const{seed:l,k2sig:u}=function(t,r,i){if(["recovered","canonical"].some((e=>e in i)))throw Error("sign() legacy options not supported");const{lowS:s,prehash:a,extraEntropy:l}=du(i,p);t=A(t,a);const u=w(t),c=yu(o,r),d=[S(c),S(u)];if(null!=l&&!1!==l){const e=!0===l?n(f.secretKey):l;d.push(Ta("extraEntropy",e))}const h=wn(...d),g=u;return{seed:h,k2sig(t){const r=b(t);if(!o.isValidNot0(r))return;const n=o.inv(r),i=e.BASE.multiply(r).toAffine(),a=o.create(i.x);if(a===fu)return;const l=o.create(n*o.create(g+a*c));if(l===fu)return;let u=(i.x===a?0:2)|Number(i.y&pu),d=l;return s&&m(l)&&(d=o.neg(l),u^=1),new y(a,d,u)}}}(r,s,a),c=function(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");const n=e=>new Uint8Array(e),i=e=>Uint8Array.of(e);let s=n(e),o=n(e),a=0;const l=()=>{s.fill(1),o.fill(0),a=0},u=(...e)=>r(o,s,...e),c=(e=n(0))=>{o=u(i(0),e),s=u(),0!==e.length&&(o=u(i(1),e),s=u())},d=()=>{if(a++>=1e3)throw Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){s=u();const t=s.slice();r.push(t),e+=s.length}return wn(...r)};return(e,t)=>{let r;for(l(),c(e);!(r=t(d()));)c();return l(),r}}(t.outputLen,o.BYTES,i);return c(l,u)},verify(t,r,n,i={}){const{lowS:s,prehash:a,format:l}=du(i,p);if(n=Ta("publicKey",n),r=A(Ta("message",r),a),"strict"in i)throw Error("options.strict was renamed to lowS");const u=void 0===l?function(e){let t;const r="string"==typeof e||Jr(e),n=!r&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!r&&!n)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)t=new y(e.r,e.s);else if(r){try{t=y.fromBytes(Ta("sig",e),"der")}catch(e){if(!(e instanceof hu.Err))throw e}if(!t)try{t=y.fromBytes(Ta("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):y.fromBytes(Ta("sig",t),l);if(!1===u)return!1;try{const t=e.fromBytes(n);if(s&&u.hasHighS())return!1;const{r:i,s:a}=u,l=w(r),c=o.inv(a),d=o.create(l*c),h=o.create(i*c),f=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));return!f.is0()&&o.create(f.x)===i}catch(e){return!1}},recoverPublicKey(e,t,r={}){const{prehash:n}=du(r,p);return t=A(t,n),y.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:y,hash:t})}function Su(e){const{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:i}=function(e){const{CURVE:t,curveOpts:r}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp;let n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map((e=>Math.ceil(e/2))))):void 0;return{CURVE:t,curveOpts:{Fp:r,Fn:il(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,nl(r.Fn.ORDER,r.Fn.BITS))})}(e,Eu(function(e,t={}){const r=El("weierstrass",e,t),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:o,n:a}=s;Na(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:l}=t;if(l&&(!n.is0(s.a)||"bigint"!=typeof l.beta||!Array.isArray(l.basises)))throw Error('invalid endo: expected "beta": bigint and "basises": array');const u=wu(n,i);function c(){if(!n.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}const d=t.toBytes||function(e,t,r){const{x:i,y:s}=t.toAffine(),o=n.toBytes(i);return Ea(r,"isCompressed"),r?(c(),wn(bu(!n.isOdd(s)),o)):wn(Uint8Array.of(4),o,n.toBytes(s))},h=t.fromBytes||function(e){Sa(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:r}=u,i=e.length,s=e[0],o=e.subarray(1);if(i!==t||2!==s&&3!==s){if(i===r&&4===s){const e=n.BYTES,t=n.fromBytes(o.subarray(0,e)),r=n.fromBytes(o.subarray(e,2*e));if(!p(t,r))throw Error("bad point: is not on curve");return{x:t,y:r}}throw Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${r}`)}{const t=n.fromBytes(o);if(!n.isValid(t))throw Error("bad point: is not on curve, wrong x");const r=f(t);let i;try{i=n.sqrt(r)}catch(e){const t=e instanceof Error?": "+e.message:"";throw Error("bad point: is not on curve, sqrt error"+t)}return c(),!(1&~s)!==n.isOdd(i)&&(i=n.neg(i)),{x:t,y:i}}};function f(e){const t=n.sqr(e),r=n.mul(t,e);return n.add(n.add(r,n.mul(e,s.a)),s.b)}function p(e,t){const r=n.sqr(t),i=f(e);return n.eql(r,i)}if(!p(s.Gx,s.Gy))throw Error("bad curve params: generator point");const g=n.mul(n.pow(s.a,mu),vu),m=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,m)))throw Error("bad curve params: a or b");function v(e,t,r=!1){if(!n.isValid(t)||r&&n.is0(t))throw Error("bad point coordinate "+e);return t}function y(e){if(!(e instanceof A))throw Error("ProjectivePoint expected")}function b(e){if(!l||!l.basises)throw Error("no endo");return function(e,t,r){const[[n,i],[s,o]]=t,a=uu(o*e,r),l=uu(-i*e,r);let u=e-a*n-l*s,c=-a*i-l*o;const d=u<fu,h=c<fu;d&&(u=-u),h&&(c=-c);const f=Ma(Math.ceil(Da(r)/2))+pu;if(u<fu||u>=f||c<fu||c>=f)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:u,k2neg:h,k2:c}}(e,l.basises,i.ORDER)}const w=Oa(((e,t)=>{const{X:r,Y:i,Z:s}=e;if(n.eql(s,n.ONE))return{x:r,y:i};const o=e.is0();null==t&&(t=o?n.ONE:n.inv(s));const a=n.mul(r,t),l=n.mul(i,t),u=n.mul(s,t);if(o)return{x:n.ZERO,y:n.ZERO};if(!n.eql(u,n.ONE))throw Error("invZ was invalid");return{x:a,y:l}})),E=Oa((e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw Error("bad point: ZERO")}const{x:r,y:i}=e.toAffine();if(!n.isValid(r)||!n.isValid(i))throw Error("bad point: x or y not field elements");if(!p(r,i))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));function S(e,t,r,i,s){return r=new A(n.mul(r.X,e),r.Y,r.Z),t=ul(i,t),r=ul(s,r),t.add(r)}class A{static CURVE(){return s}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw Error("invalid affine point");if(e instanceof A)throw Error("projective point not allowed");return n.is0(t)&&n.is0(r)?A.ZERO:new A(t,r,n.ONE)}static fromBytes(e){const t=A.fromAffine(h(Sa(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(Ta("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return _.createCache(this,e),t||this.multiply(mu),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){y(e);const{X:t,Y:r,Z:i}=this,{X:s,Y:o,Z:a}=e,l=n.eql(n.mul(t,a),n.mul(s,i)),u=n.eql(n.mul(r,a),n.mul(o,i));return l&&u}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,r=n.mul(t,mu),{X:i,Y:o,Z:a}=this;let l=n.ZERO,u=n.ZERO,c=n.ZERO,d=n.mul(i,i),h=n.mul(o,o),f=n.mul(a,a),p=n.mul(i,o);return p=n.add(p,p),c=n.mul(i,a),c=n.add(c,c),l=n.mul(e,c),u=n.mul(r,f),u=n.add(l,u),l=n.sub(h,u),u=n.add(h,u),u=n.mul(l,u),l=n.mul(p,l),c=n.mul(r,c),f=n.mul(e,f),p=n.sub(d,f),p=n.mul(e,p),p=n.add(p,c),c=n.add(d,d),d=n.add(c,d),d=n.add(d,f),d=n.mul(d,p),u=n.add(u,d),f=n.mul(o,a),f=n.add(f,f),d=n.mul(f,p),l=n.sub(l,d),c=n.mul(f,h),c=n.add(c,c),c=n.add(c,c),new A(l,u,c)}add(e){y(e);const{X:t,Y:r,Z:i}=this,{X:o,Y:a,Z:l}=e;let u=n.ZERO,c=n.ZERO,d=n.ZERO;const h=s.a,f=n.mul(s.b,mu);let p=n.mul(t,o),g=n.mul(r,a),m=n.mul(i,l),v=n.add(t,r),b=n.add(o,a);v=n.mul(v,b),b=n.add(p,g),v=n.sub(v,b),b=n.add(t,i);let w=n.add(o,l);return b=n.mul(b,w),w=n.add(p,m),b=n.sub(b,w),w=n.add(r,i),u=n.add(a,l),w=n.mul(w,u),u=n.add(g,m),w=n.sub(w,u),d=n.mul(h,b),u=n.mul(f,m),d=n.add(u,d),u=n.sub(g,d),d=n.add(g,d),c=n.mul(u,d),g=n.add(p,p),g=n.add(g,p),m=n.mul(h,m),b=n.mul(f,b),g=n.add(g,m),m=n.sub(p,m),m=n.mul(h,m),b=n.add(b,m),p=n.mul(g,b),c=n.add(c,p),p=n.mul(w,b),u=n.mul(v,u),u=n.sub(u,p),p=n.mul(v,g),d=n.mul(w,d),d=n.add(d,p),new A(u,c,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:r}=t;if(!i.isValidNot0(e))throw Error("invalid scalar: out of range");let n,s;const o=e=>_.cached(this,e,(e=>cl(A,e)));if(r){const{k1neg:t,k1:i,k2neg:a,k2:l}=b(e),{p:u,f:c}=o(i),{p:d,f:h}=o(l);s=c.add(h),n=S(r.beta,u,d,t,a)}else{const{p:t,f:r}=o(e);n=t,s=r}return cl(A,[n,s])[0]}multiplyUnsafe(e){const{endo:r}=t,n=this;if(!i.isValid(e))throw Error("invalid scalar: out of range");if(e===fu||n.is0())return A.ZERO;if(e===pu)return n;if(_.hasCache(this))return this.multiply(e);if(r){const{k1neg:t,k1:i,k2neg:s,k2:o}=b(e),{p1:a,p2:l}=function(e,t,r,n){let i=t,s=e.ZERO,o=e.ZERO;for(;r>al||n>al;)r&ll&&(s=s.add(i)),n&ll&&(o=o.add(i)),i=i.double(),r>>=ll,n>>=ll;return{p1:s,p2:o}}(A,n,i,o);return S(r.beta,a,l,t,s)}return _.unsafe(n,e)}multiplyAndAddUnsafe(e,t,r){const n=this.multiplyUnsafe(t).add(e.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(e){return w(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===pu||(e?e(A,this):_.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===pu?this:e?e(A,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Ea(e,"isCompressed"),this.assertValidity(),d(A,this,e)}toHex(e=!0){return cn(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return cl(A,e)}static msm(e,t){return bl(A,i,e,t)}static fromPrivateKey(e){return A.BASE.multiply(yu(i,e))}constructor(e,t,r){this.X=v("x",e),this.Y=v("y",t,!0),this.Z=v("z",r),Object.freeze(this)}}A.BASE=new A(s.Gx,s.Gy,n.ONE),A.ZERO=new A(n.ZERO,n.ONE,n.ZERO),A.Fp=n,A.Fn=i;const I=i.BITS,_=new yl(A,t.endo?Math.ceil(I/2):I);return A.BASE.precompute(8),A}(t,r),n,i))}const Au={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Iu={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},_u=BigInt(2),Cu=il(Au.p,{sqrt(e){const t=Au.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),l=BigInt(88),u=e*e*e%t,c=u*u*e%t,d=Ga(c,r,t)*c%t,h=Ga(d,r,t)*c%t,f=Ga(h,_u,t)*u%t,p=Ga(f,i,t)*f%t,g=Ga(p,s,t)*p%t,m=Ga(g,a,t)*g%t,v=Ga(m,l,t)*m%t,y=Ga(v,a,t)*g%t,b=Ga(y,r,t)*c%t,w=Ga(b,o,t)*p%t,E=Ga(w,n,t)*u%t,S=Ga(E,_u,t);if(!Cu.eql(Cu.sqr(S),e))throw Error("Cannot find square root");return S}}),ku=function(e,t){const r=t=>Su((0,M.default)((0,D.default)({},e),{hash:t}));return(0,M.default)((0,D.default)({},r(t)),{create:r})}((0,M.default)((0,D.default)({},Au),{Fp:Cu,lowS:!0,endo:Iu}),Jn);let xu=class{toMultihash(){return Lt.digest(Lu(this))}toCID(){return $t.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ns(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const i=Mt.digest(r instanceof Uint8Array?r:r.subarray());if(Xl(i))return i.then((({digest:r})=>{var i;return null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted(),ku.verify(t,r,e)})).catch((e=>{if("AbortError"===e.name)throw e;throw new Kl(e+"")}));try{var s;return null==n||null===(s=n.signal)||void 0===s||s.throwIfAborted(),ku.verify(t,i.digest,e)}catch(e){throw new Kl(e+"")}}(this._key,t,e,r)}constructor(e){(0,L.default)(this,"type","secp256k1"),(0,L.default)(this,"raw",void 0),(0,L.default)(this,"_key",void 0),this._key=function(e){try{return ku.ProjectivePoint.fromHex(e),e}catch(e){throw new Ri(e+"")}}(e),this.raw=function(e){return ku.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}};function Tu(e){return new xu(e)}async function Pu(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=zl.utils.randomPrivateKey(),t=zl.getPublicKey(e),r=function(e,t){const r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}(e,t);return{privateKey:r,publicKey:t}}();return new Yl(e,t)}()}function Ru(e,t){const{Type:r,Data:n}=ru.decode(e),i=null!=n?n:new Uint8Array;switch(r){case eu.RSA:return function(e,t){if(e.byteLength>=1062)throw new Ri("Key size is too large");return function(e,t,r){const n=function(e){const t=ea(e[1],{offset:0});return{kty:"RSA",n:ri(t[0],"base64url"),e:ri(t[1],"base64url")}}(e);return null==r&&(r=xt(18,ti(ru.encode({Type:eu.RSA,Data:t})))),new su(n,r)}(ea(e,{offset:0}),e,t)}(i,t);case eu.Ed25519:return Ql(i);case eu.secp256k1:return Tu(i);case eu.ECDSA:return ma(i);default:throw new Qi}}function Lu(e){return ru.encode({Type:eu[e.type],Data:e.raw})}const Du=Symbol.for("nodejs.util.inspect.custom");let Mu=(N=Symbol.toStringTag,O=Ei,U=Du,class{get[N](){return`PeerId(${this.toString()})`}toString(){return null==this.string&&(this.string=ot.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return $t.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){var t;if(null==e)return!1;if(e instanceof Uint8Array)return Ns(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=(null===(t=null==e?void 0:e.toMultihash())||void 0===t?void 0:t.bytes))return Ns(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[U](){return`PeerId(${this.toString()})`}constructor(e){(0,L.default)(this,"type",void 0),(0,L.default)(this,"multihash",void 0),(0,L.default)(this,"publicKey",void 0),(0,L.default)(this,"string",void 0),(0,L.default)(this,O,!0),this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}}),Nu=class extends Mu{constructor(e){super((0,M.default)((0,D.default)({},e),{type:"RSA"})),(0,L.default)(this,"type","RSA"),(0,L.default)(this,"publicKey",void 0),this.publicKey=e.publicKey}},Ou=class extends Mu{constructor(e){super((0,M.default)((0,D.default)({},e),{type:"Ed25519"})),(0,L.default)(this,"type","Ed25519"),(0,L.default)(this,"publicKey",void 0),this.publicKey=e.publicKey}},Uu=class extends Mu{constructor(e){super((0,M.default)((0,D.default)({},e),{type:"secp256k1"})),(0,L.default)(this,"type","secp256k1"),(0,L.default)(this,"publicKey",void 0),this.publicKey=e.publicKey}},Fu=Du,Bu=Ei;class $u{[Fu](){return`PeerId(${this.url})`}toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return $t.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=ri(e)),e.toString()===this.toString())}constructor(e){(0,L.default)(this,"type","url"),(0,L.default)(this,"multihash",void 0),(0,L.default)(this,"publicKey",void 0),(0,L.default)(this,"url",void 0),(0,L.default)(this,Bu,!0),this.url=e.toString(),this.multihash=Lt.digest(Zt(this.url))}}function qu(e){let t;if("1"!==e.charAt(0)&&"Q"!==e.charAt(0)){if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return Ku($t.parse(e));throw new Pi('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return t=Tt(ot.decode("z"+e)),ju(t)}function zu(e){if("Ed25519"===e.type)return new Ou({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Uu({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Nu({multihash:e.toCID().multihash,publicKey:e});throw new Qi}function ju(e){if(function(e){return e.code===Mt.code}(e))return new Nu({multihash:e});if(function(e){return e.code===Lt.code}(e))try{const t=function(e){const{Type:t,Data:r}=ru.decode(e.digest),n=null!=r?r:new Uint8Array;switch(t){case eu.Ed25519:return Ql(n);case eu.secp256k1:return Tu(n);case eu.ECDSA:return ma(n);default:throw new Qi}}(e);if("Ed25519"===t.type)return new Ou({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Uu({multihash:e,publicKey:t})}catch(t){const r=ri(e.digest);return new $u(new URL(r))}throw new zi("Supplied PeerID Multihash is invalid")}function Ku(e){if(null==(null==e?void 0:e.multihash)||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new qi("Supplied PeerID CID is invalid");if(2336===e.code){const t=ri(e.multihash.digest);return new $u(new URL(t))}return ju(e.multihash)}class Vu extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidMultiaddrError")}}(0,L.default)(Vu,"name","InvalidMultiaddrError");class Hu extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","ValidationError")}}(0,L.default)(Hu,"name","ValidationError");class Wu extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidParametersError")}}(0,L.default)(Wu,"name","InvalidParametersError");class Gu extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","UnknownProtocolError")}}(0,L.default)(Gu,"name","UnknownProtocolError");const Xu=new class{new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const t=e();if(this.index===this.input.length)return t}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(e){return this.readAtomically((()=>{const t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{let i=0,s=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,l=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(i*=e,i+=r,i>l)return;if(s+=1,void 0!==t&&s>t)return}return 0===s||!r&&a&&s>1?void 0:i}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,(()=>this.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const i=new Uint8Array(14),s=16-(r+2),[o]=e(i.subarray(0,s));return t.set(i.subarray(0,o),16-o),t}))}readIPAddr(){var e;return null!==(e=this.readIPv4Addr())&&void 0!==e?e:this.readIPv6Addr()}constructor(){(0,L.default)(this,"index",0),(0,L.default)(this,"input","")}};function Zu(e){if(!(e.length>15))return Xu.new(e).parseWith((()=>Xu.readIPv4Addr()))}function Yu(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Xu.new(e).parseWith((()=>Xu.readIPv6Addr()))}function Qu(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const r=Xu.new(e).parseWith((()=>Xu.readIPAddr()));return r?t&&4===r.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,r[0],r[1],r[2],r[3]]):r:void 0}function Ju(e){return!!Zu(e)}function ec(e){return!!Yu(e)}const tc=41,rc=42;function nc(e){return t=>ri(t,e)}function ic(e){return t=>Zt(t,e)}function sc(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function oc(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function ac(e){const t=e.subarray(0,e.length-2),r=e.subarray(e.length-2);return`${ri(t,"base32")}:${sc(r)}`}const lc=e=>{e=e.toString().trim();const t=new Uint8Array(4);return e.split(/\./g).forEach(((e,r)=>{const n=parseInt(e,10);if(isNaN(n)||n<0||n>255)throw new Vu("Invalid byte value in IP address");t[r]=n})),t},uc=Object.values(Vt).map((e=>e.decoder)),cc=(()=>{let e=uc[0].or(uc[1]);return uc.slice(2).forEach((t=>e=e.or(t))),e})(),dc=function(...e){return t=>{for(const r of e)r(t)}}((function(e){if(parseInt(e).toString()!==e)throw new Hu("Value must be an integer")}),(function(e){if(e<0)throw new Hu("Value must be a positive integer, or zero")}),(65535,e=>{if(e>65535)throw new Hu("Value must be smaller than or equal to 65535")}));const hc=-1,fc=new class{getProtocol(e){let t;if(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e),null==t)throw new Gu(`Protocol ${e} was unknown`);return t}addProtocol(e){var t;this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),null===(t=e.aliases)||void 0===t||t.forEach((t=>{this.protocolsByName.set(t,e)}))}removeProtocol(e){var t;const r=this.protocolsByCode.get(e);null!=r&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),null===(t=r.aliases)||void 0===t||t.forEach((e=>{this.protocolsByName.delete(e)})))}constructor(){(0,L.default)(this,"protocolsByCode",new Map),(0,L.default)(this,"protocolsByName",new Map)}},pc=[{code:4,name:"ip4",size:32,valueToBytes:lc,bytesToValue(e){if(4!==e.byteLength)throw new Vu("IPv4 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate(e){if(!Ju(e))throw new Hu(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:oc,bytesToValue:sc,validate:dc},{code:273,name:"udp",size:16,valueToBytes:oc,bytesToValue:sc,validate:dc},{code:33,name:"dccp",size:16,valueToBytes:oc,bytesToValue:sc,validate:dc},{code:tc,name:"ip6",size:128,valueToBytes(e){let t=0;const r=(e=e.toString().trim()).split(":",8);let n;for(n=0;n<r.length;n++){let e;Ju(r[n])&&(e=lc(r[n]),r[n]=ri(e.subarray(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,ri(e.subarray(2,4),"base16"))}if(""===r[0])for(;r.length<8;)r.unshift("0");else if(""===r[r.length-1])for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&""!==r[n];n++);const e=[n,1];for(n=9-r.length;n>0;n--)e.push("0");r.splice.apply(r,e)}const i=new Uint8Array(t+16);for(n=0;n<r.length;n++){""===r[n]&&(r[n]="0");const e=parseInt(r[n],16);if(isNaN(e)||e<0||e>65535)throw new Vu("Invalid byte value in IP address");i[t++]=e>>8&255,i[t++]=255&e}return i},bytesToValue(e){if(16!==e.byteLength)throw new Vu("IPv6 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r+=2){const n=e[r],i=e[r+1],s=`${n.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;t.push(s)}const r=t.join(":");try{const e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch(e){throw new Vu(`Invalid IPv6 address "${r}"`)}},stringToValue(e){try{const t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch(t){throw new Vu(`Invalid IPv6 address "${e}"`)}},validate(e){if(!ec(e))throw new Hu(`Invalid IPv6 address "${e}"`)}},{code:rc,name:"ip6zone",size:hc},{code:43,name:"ipcidr",size:8,bytesToValue:nc("base10"),valueToBytes:ic("base10")},{code:53,name:"dns",size:hc,resolvable:!0},{code:54,name:"dns4",size:hc,resolvable:!0},{code:55,name:"dns6",size:hc,resolvable:!0},{code:56,name:"dnsaddr",size:hc,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:oc,bytesToValue:sc,validate:dc},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:hc,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:hc,bytesToValue:nc("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?ic("base58btc")(e):$t.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ac,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=Zt(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const i=oc(n);return Ms([r,i],r.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:ac,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=We.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const i=oc(n);return Ms([r,i],r.length+i.length)}},{code:446,name:"garlic64",size:hc},{code:447,name:"garlic32",size:hc},{code:448,name:"tls"},{code:449,name:"sni",size:hc},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:hc,bytesToValue:function(e){return t=>e.encoder.encode(t)}(dt),valueToBytes:e=>cc.decode(e)},{code:480,name:"http"},{code:481,name:"http-path",size:hc,stringToValue:e=>"/"+decodeURIComponent(e),valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:hc}];function gc(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:le(t,r)}pc.forEach((e=>{fc.addProtocol(e)}));const mc=Symbol.for("nodejs.util.inspect.custom"),vc=Symbol.for("@multiformats/multiaddr"),yc=[53,54,55,56];class bc extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}var wc=new WeakMap,Ec=new WeakMap,Sc=new WeakMap;let Ac=vc,Ic=mc;class _c{get bytes(){return null==(0,C.default)(this,Sc)&&(0,x.default)(this,Sc,function(e){let t=0;const r=[];for(const s of e){if(null==s.bytes){var n;const e=fc.getProtocol(s.code),t=ie(s.code);let r,o=0,a=0;var i;null!=s.value&&(r=null!==(i=null===(n=e.valueToBytes)||void 0===n?void 0:n.call(e,s.value))&&void 0!==i?i:Zt(s.value),o=r.byteLength,e.size===hc&&(a=ie(o)));const l=new Uint8Array(t+a+o);let u=0;se(s.code,l,u),u+=t,null!=r&&(e.size===hc&&(se(o,l,u),u+=a),l.set(r,u)),s.bytes=l}r.push(s.bytes),t+=s.bytes.byteLength}return Ms(r,t)}((0,C.default)(this,wc))),(0,C.default)(this,Sc)}toString(){return null==(0,C.default)(this,Ec)&&(0,x.default)(this,Ec,"/"+(0,C.default)(this,wc).flatMap((e=>{var t;if(null==e.value)return e.name;const r=fc.getProtocol(e.code);if(null==r)throw new Vu("Unknown protocol code "+e.code);var n;return[e.name,null!==(n=null===(t=r.valueToString)||void 0===t?void 0:t.call(r,e.value))&&void 0!==n?n:e.value]})).join("/")),(0,C.default)(this,Ec)}toJSON(){return this.toString()}toOptions(){let e,t,r,n,i="";for(const{code:s,name:o,value:a}of(0,C.default)(this,wc))s===rc&&(i="%"+(null!=a?a:"")),yc.includes(s)&&(t="tcp",n=443,r=`${null!=a?a:""}${i}`,e=55===s?6:4),6!==s&&273!==s||(t="tcp"===o?"tcp":"udp",n=parseInt(null!=a?a:"")),4!==s&&s!==tc||(t="tcp",r=`${null!=a?a:""}${i}`,e=s===tc?6:4);if(null==e||null==t||null==r||null==n)throw Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}getComponents(){return[...(0,C.default)(this,wc)]}protos(){return(0,C.default)(this,wc).map((({code:e,value:t})=>{const r=fc.getProtocol(e);var n;return{code:e,size:null!==(n=r.size)&&void 0!==n?n:0,name:r.name,resolvable:!!r.resolvable,path:!!r.path}}))}protoCodes(){return(0,C.default)(this,wc).map((({code:e})=>e))}protoNames(){return(0,C.default)(this,wc).map((({name:e})=>e))}tuples(){return(0,C.default)(this,wc).map((({code:e,value:t})=>{var r;if(null==t)return[e];const n=fc.getProtocol(e),i=[e];var s;return null!=t&&i.push(null!==(s=null===(r=n.valueToBytes)||void 0===r?void 0:r.call(n,t))&&void 0!==s?s:Zt(t)),i}))}stringTuples(){return(0,C.default)(this,wc).map((({code:e,value:t})=>null==t?[e]:[e,t]))}encapsulate(e){const t=new _c(e);return new _c([...(0,C.default)(this,wc),...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Wu(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new _c(r.slice(0,n),{validate:!1})}decapsulateCode(e){let t;for(let r=(0,C.default)(this,wc).length-1;r>-1;r--)if((0,C.default)(this,wc)[r].code===e){t=r;break}return new _c((0,C.default)(this,wc).slice(0,t),{validate:!1})}getPeerId(){try{let e=[];(0,C.default)(this,wc).forEach((({code:t,value:r})=>{421===t&&e.push([t,r]),290===t&&(e=[])}));const t=e.pop();if(null!=(null==t?void 0:t[1])){const e=t[1];return"Q"===e[0]||"1"===e[0]?ri(ot.decode("z"+e),"base58btc"):ri($t.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(const t of(0,C.default)(this,wc)){var e;if(fc.getProtocol(t.code).path)return null!==(e=t.value)&&void 0!==e?e:null}return null}equals(e){return Ns(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=Lc.get(t.name);if(null==r)throw new bc("no available resolver for "+t.name);return(await r(this,e)).map((e=>Mc(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(2!==(0,C.default)(this,wc).length||4!==(0,C.default)(this,wc)[0].code&&(0,C.default)(this,wc)[0].code!==tc||6!==(0,C.default)(this,wc)[1].code&&273!==(0,C.default)(this,wc)[1].code)}[Ic](){return`Multiaddr(${this.toString()})`}constructor(e="/",t={}){(0,L.default)(this,Ac,!0),(0,k.default)(this,wc,{writable:!0,value:void 0}),(0,k.default)(this,Ec,{writable:!0,value:void 0}),(0,k.default)(this,Sc,{writable:!0,value:void 0}),(0,x.default)(this,wc,function(e){if(null==e&&(e="/"),Dc(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let r=0;for(;r<e.length;){const s=le(e,r),o=fc.getProtocol(s),a=ie(s),l=gc(o,e,r+a);let u=0;l>0&&o.size===hc&&(u=ie(l));const c=a+u+l,d={code:s,name:o.name,bytes:e.subarray(r,r+c)};if(l>0){var n;const t=r+a+u,s=e.subarray(t,t+l);var i;d.value=null!==(i=null===(n=o.bytesToValue)||void 0===n?void 0:n.call(o,s))&&void 0!==i?i:ri(s)}t.push(d),r+=c}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new Vu('String multiaddr must start with "/"');const t=[];let r="protocol",n="",i="";for(let a=1;a<e.length;a++){const l=e.charAt(a);"/"!==l&&("protocol"===r?i+=e.charAt(a):n+=e.charAt(a));const u=a===e.length-1;if("/"===l||u){const e=fc.getProtocol(i);if("protocol"===r){if(null==e.size||0===e.size){t.push({code:e.code,name:e.name}),n="",i="",r="protocol";continue}if(u)throw new Vu(`Component ${i} was missing value`);r="value"}else if("value"===r){const a={code:e.code,name:e.name};if(null!=e.size&&0!==e.size){var s,o;if(""===n)throw new Vu(`Component ${i} was missing value`);a.value=null!==(o=null===(s=e.stringToValue)||void 0===s?void 0:s.call(e,n))&&void 0!==o?o:n}t.push(a),n="",i="",r="protocol"}}}if(""!==i&&""!==n)throw new Vu("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new Vu("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e)),!1!==t.validate&&function(e){e.getComponents().forEach((e=>{var t;const r=fc.getProtocol(e.code);null!=e.value&&(null===(t=r.validate)||void 0===t||t.call(r,e.value))}))}(this)}}const Cc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function kc(e,t){16===t.length&&4===e.length&&function(e,t,r){let n=0;for(const t of e)if(!(n<0)){if(n>11)break;if(255!==t)return!1;n++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t,r,n){let i=0;for(const r of e)if(!(i<0)){if(i>11)break;if(r!==t[i])return!1;i++}return!0}(e,Cc)&&(e=e.slice(12));const r=e.length;if(r!=t.length)throw Error("Failed to mask ip");const n=new Uint8Array(r);for(let i=0;i<r;i++)n[i]=e[i]&t[i];return n}function xc(e,t){if(32!==t&&128!==t)throw Error("Invalid CIDR mask");if(e<0||e>t)throw Error("Invalid CIDR mask");const r=t/8,n=new Uint8Array(r);for(let t=0;t<r;t++)e>=8?(n[t]=255,e-=8):(n[t]=255-(255>>e),e=0);return n}class Tc{contains(e){return function(e,t){if("string"==typeof t&&(t=Qu(t)),null==t)throw Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let r=0;r<t.length;r++)if((e.network[r]&e.mask[r])!=(t[r]&e.mask[r]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){const e=function(e){let t=0;for(let[r,n]of e.entries()){if(255!==n){for(;128&n;)t++,n<<=1;if(128&n)return-1;for(let t=r+1;t<e.length;t++)if(0!=e[t])return-1;break}t+=8}return t}(this.mask),t=-1!==e?e+"":function(e){let t="0x";for(const r of e)t+=(r>>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let r=0;r<e.length;r++)r%2==0&&t.push(e[r].toString(16).padStart(2,"0")+e[r+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw Error("Invalid ip length")}}(this.network)+"/"+t}constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,r]=e.split("/");if(!t||!r)throw Error("Failed to parse given CIDR: "+e);let n=4,i=Zu(t);if(null==i&&(n=16,i=Yu(t),null==i))throw Error("Failed to parse given CIDR: "+e);const s=parseInt(r,10);if(Number.isNaN(s)||(s+"").length!==r.length||s<0||s>8*n)throw Error("Failed to parse given CIDR: "+e);const o=xc(s,8*n);return{network:kc(i,o),mask:o}}(e));else{const r=Qu(e);if(null==r)throw Error("Failed to parse network");const n=parseInt(t+="",10);if(Number.isNaN(n)||(n+"").length!==t.length||n<0||n>8*r.length){const e=Qu(t);if(null==e)throw Error("Failed to parse mask");this.mask=e}else this.mask=xc(n,8*r.length);this.network=kc(r,this.mask)}}}function Pc(e,t){var r;const n=fc.getProtocol(e);var i;return null!==(i=null===(r=n.bytesToValue)||void 0===r?void 0:r.call(n,t))&&void 0!==i?i:ri(t,"base16")}function Rc(e,t){var r;const n=fc.getProtocol(e);var i;return null!==(i=null===(r=n.valueToBytes)||void 0===r?void 0:r.call(n,t))&&void 0!==i?i:Zt(t,"base16")}const Lc=new Map;function Dc(e){return!!(null==e?void 0:e[vc])}function Mc(e){return new _c(e)}function Nc(e){const t=fc.getProtocol(e);var r;return{code:t.code,size:null!==(r=t.size)&&void 0!==r?r:0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}const Oc=e=>{if(!e)return-1;try{const t=e.metadata.get("ping");return t?Number(oi(t)):-1}catch(e){return-1}},Uc=new gs("connection-limiter");class Fc{start(){this.dialPeersFromStore(),this.options.enableAutoRecovery&&null===this.connectionMonitorInterval&&(this.connectionMonitorInterval=setInterval((()=>{this.maintainConnections()}),5e3)),this.events.addEventListener(xs.Connection,this.onWakuConnectionEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent)}stop(){this.events.removeEventListener(xs.Connection,this.onWakuConnectionEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent),this.connectionMonitorInterval&&(clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=null)}onWakuConnectionEvent(){this.options.enableAutoRecovery?this.networkMonitor.isBrowserConnected()&&this.dialPeersFromStore():Uc.info("Auto recovery is disabled, skipping")}async maintainConnections(){await this.maintainConnectionsCount(),await this.maintainBootstrapConnections(),await this.maintainTTLConnectedPeers()}async onDisconnectedEvent(){0===this.libp2p.getConnections().length&&(Uc.info("No connections, dialing peers from store"),await this.dialPeersFromStore())}async maintainConnectionsCount(){Uc.info("Maintaining connections count");const e=this.libp2p.getConnections();if(e.length<=this.options.maxConnections){Uc.info(`Node has less than max connections ${this.options.maxConnections}, trying to dial more peers`);const t=await this.getPrioritizedPeers();if(0===t.length)return Uc.info("No peers to dial, skipping"),void await this.triggerBootstrap();const r=t.slice(0,this.options.maxConnections-e.length).map((e=>this.dialer.dial(e.id)));await Promise.all(r)}else{Uc.info(`Node has more than max connections ${this.options.maxConnections}, dropping connections`);try{const t=e.filter((e=>!e.tags.includes(Ps))).slice(this.options.maxConnections);if(0===t.length)return void Uc.info("No connections to drop, skipping");const r=t.map((e=>this.libp2p.hangUp(e.remotePeer)));await Promise.all(r),Uc.info(`Dropped ${t.length} connections`)}catch(e){Uc.error("Unexpected error while maintaining connections",e)}}}async maintainBootstrapConnections(){Uc.info("Maintaining bootstrap connections");const e=await this.getBootstrapPeers();if(!(e.length<=this.options.maxBootstrapPeers))try{const t=e.slice(this.options.maxBootstrapPeers);Uc.info(`Dropping ${t.length} bootstrap connections because node has more than max bootstrap connections ${this.options.maxBootstrapPeers}`);const r=t.map((e=>this.libp2p.hangUp(e.id)));await Promise.all(r),Uc.info(`Dropped ${t.length} bootstrap connections`)}catch(e){Uc.error("Unexpected error while maintaining bootstrap connections",e)}}async maintainTTLConnectedPeers(){Uc.info("Maintaining TTL connected peers");const e=this.libp2p.getConnections().map((async e=>{try{await this.libp2p.peerStore.merge(e.remotePeer,{metadata:{ttl:ii(Date.now())}}),Uc.info("TTL updated for connected peer "+e.remotePeer.toString())}catch(e){Uc.error("Unexpected error while maintaining TTL connected peer",e)}}));await Promise.all(e)}async dialPeersFromStore(){Uc.info("Dialing peers from store");try{const e=await this.getPrioritizedPeers();if(0===e.length)return Uc.info("No peers to dial, skipping"),void await this.triggerBootstrap();const t=e.map((e=>this.dialer.dial(e.id)));Uc.info(`Dialing ${e.length} peers from store`),await Promise.all(t),Uc.info(`Dialed ${t.length} peers from store`)}catch(e){Uc.error("Unexpected error while dialing peer store peers",e)}}async getPrioritizedPeers(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections();Uc.info(`Found ${e.length} peers in store, and found ${t.length} connections`);const r=e.filter((e=>!t.some((t=>t.remotePeer.equals(e.id)))&&((e,t)=>{var r,n;const i=(null==e||null===(r=e.components)||void 0===r||null===(n=r.transportManager)||void 0===n?void 0:n.getTransports())||[];return 0!==i.length&&i.map((e=>e.dialFilter(t))).some((e=>e.length>0))})(this.libp2p,e.addresses.map((e=>e.multiaddr)))));return[...r.filter((e=>e.tags.has(Ts.BOOTSTRAP))),...r.filter((e=>e.tags.has(Ts.PEER_EXCHANGE))),...r.filter((e=>e.tags.has(Ts.PEER_CACHE))),...r.filter((e=>!e.tags.has(Ts.BOOTSTRAP)&&!e.tags.has(Ts.PEER_EXCHANGE)&&!e.tags.has(Ts.PEER_CACHE)))]}async getBootstrapPeers(){return(await Promise.all(this.libp2p.getConnections().map((e=>e.remotePeer)).map((e=>this.getPeer(e))))).filter((e=>e&&e.tags.has(Ts.BOOTSTRAP)))}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return Uc.error(`Failed to get peer ${e}, error: ${t}`),null}}async triggerBootstrap(){Uc.info("Triggering bootstrap discovery");const e=Object.values(this.libp2p.components.components).filter((e=>!!e)).filter((e=>["@waku/"+Ts.BOOTSTRAP,"@waku/"+Ts.PEER_CACHE].includes(null==e?void 0:e[Symbol.toStringTag])));if(0===e.length)return void Uc.warn("No bootstrap components found to trigger");Uc.info(`Found ${e.length} bootstrap components, starting them`);const t=e.map((async e=>{try{var t,r;await(null==e||null===(t=e.stop)||void 0===t?void 0:t.call(e)),await(null==e||null===(r=e.start)||void 0===r?void 0:r.call(e)),Uc.info("Successfully started bootstrap component")}catch(e){Uc.error("Failed to start bootstrap component",e)}}));await Promise.all(t)}constructor(e){(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"events",void 0),(0,L.default)(this,"networkMonitor",void 0),(0,L.default)(this,"dialer",void 0),(0,L.default)(this,"connectionMonitorInterval",null),(0,L.default)(this,"options",void 0),this.libp2p=e.libp2p,this.events=e.events,this.networkMonitor=e.networkMonitor,this.dialer=e.dialer,this.options=e.options,this.onWakuConnectionEvent=this.onWakuConnectionEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this)}}const Bc=new gs("dialer");class $c{start(){Bc.info("Starting dialer"),this.dialingInterval||(this.dialingInterval=setInterval((()=>{this.processQueue()}),500)),this.dialHistory.clear(),this.failedDials.clear()}stop(){Bc.info("Stopping dialer"),this.dialingInterval&&(clearInterval(this.dialingInterval),this.dialingInterval=null),this.dialHistory.clear(),this.failedDials.clear()}async dial(e){if(await this.shouldSkipPeer(e))return void Bc.info("Skipping peer: "+e);const t=0===this.dialingQueue.length,r=!this.isProcessing&&!this.isImmediateDialing;t&&r?(this.isImmediateDialing=!0,Bc.info("Dialed peer immediately"),await this.dialPeer(e),this.isImmediateDialing=!1,Bc.info("Released immediate dial lock")):(this.dialingQueue.push(e),Bc.info("Added peer to dialing queue, queue size: "+this.dialingQueue.length))}async processQueue(){if(0!==this.dialingQueue.length&&!this.isProcessing){this.isProcessing=!0;try{const e=this.dialingQueue.slice(0,this.options.maxDialingPeers);this.dialingQueue=this.dialingQueue.slice(e.length),Bc.info(`Processing dial queue: dialing ${e.length} peers, ${this.dialingQueue.length} remaining in queue`),await Promise.all(e.map((e=>this.dialPeer(e))))}finally{this.isProcessing=!1}}}async dialPeer(e){try{Bc.info("Dialing peer from queue: "+e),await this.libp2p.dial(e),this.dialHistory.set(e.toString(),Date.now()),this.failedDials.delete(e.toString()),Bc.info("Successfully dialed peer from queue: "+e)}catch(t){Bc.error("Error dialing peer "+e,t),this.failedDials.set(e.toString(),Date.now())}}async shouldSkipPeer(e){if(this.libp2p.getPeers().some((t=>t.equals(e))))return Bc.info(`Skipping peer ${e} - already connected`),!0;if(this.isRecentlyDialed(e))return Bc.info(`Skipping peer ${e} - already dialed in the last 10 seconds`),!0;if(this.isRecentlyFailed(e))return Bc.info(`Skipping peer ${e} - recently failed to dial`),!0;try{return await this.shardReader.hasShardInfo(e)?!await this.shardReader.isPeerOnCluster(e)&&(Bc.info(`Skipping peer ${e} - not on same cluster`),!0):(Bc.info(`Skipping peer ${e} - no shard info`),!1)}catch(t){return Bc.error("Error checking shard info for peer "+e,t),!0}}isRecentlyDialed(e){const t=this.dialHistory.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.dialCooldown)}isRecentlyFailed(e){const t=this.failedDials.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.failedDialCooldown)}constructor(e){(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"shardReader",void 0),(0,L.default)(this,"options",void 0),(0,L.default)(this,"dialingQueue",[]),(0,L.default)(this,"dialHistory",new Map),(0,L.default)(this,"failedDials",new Map),(0,L.default)(this,"dialingInterval",null),(0,L.default)(this,"isProcessing",!1),(0,L.default)(this,"isImmediateDialing",!1),this.libp2p=e.libp2p,this.shardReader=e.shardReader,this.options=e.options}}const qc=new gs("discovery-dialer");class zc{start(){this.libp2p.addEventListener("peer:discovery",this.onPeerDiscovery)}stop(){this.libp2p.removeEventListener("peer:discovery",this.onPeerDiscovery)}async onPeerDiscovery(e){const t=e.detail.id;qc.info("Discovered new peer: "+t);try{await this.updatePeerStore(t,e.detail.multiaddrs),await this.dialer.dial(t)}catch(e){qc.error("Error dialing peer "+t,e)}}async updatePeerStore(e,t){try{qc.info("Updating peer store for "+e);const r=await this.getPeer(e);if(!r)return qc.info(`Peer ${e} not found in store, saving`),void await this.libp2p.peerStore.save(e,{multiaddrs:t});if(t.every((e=>r.addresses.some((t=>t.multiaddr.equals(e))))))return void qc.info(`Peer ${e} has same addresses in peer store, skipping`);qc.info(`Merging peer ${e} addresses in peer store`),await this.libp2p.peerStore.merge(e,{multiaddrs:t})}catch(t){qc.error("Error updating peer store for "+e,t)}}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return void qc.error("Error getting peer info for "+e,t)}}constructor(e){(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"dialer",void 0),this.libp2p=e.libp2p,this.dialer=e.dialer,this.onPeerDiscovery=this.onPeerDiscovery.bind(this)}}const jc="/relay-ping/1/ping/null",Kc=new gs("keep-alive");class Vc{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 e of this.pingKeepAliveTimers.values())clearInterval(e);for(const e of this.relayKeepAliveTimers.values())for(const t of e)clearInterval(t);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}onPeerConnect(e){const t=e.detail;this.startPingForPeer(t)}onPeerDisconnect(e){const t=e.detail;this.stopPingForPeer(t)}startPingForPeer(e){this.stopPingForPeer(e),this.startLibp2pPing(e),this.startRelayPing(e)}stopPingForPeer(e){this.stopLibp2pPing(e),this.stopRelayPing(e)}startLibp2pPing(e){if(0===this.options.pingKeepAlive)return void Kc.warn(`Ping keep alive is disabled pingKeepAlive:${this.options.pingKeepAlive}, skipping start for libp2p ping`);const t=e.toString();if(this.pingKeepAliveTimers.has(t))return void Kc.warn(`Ping already started for peer: ${t}, skipping start for libp2p ping`);const r=setInterval((()=>{this.pingLibp2p(e)}),1e3*this.options.pingKeepAlive);this.pingKeepAliveTimers.set(t,r)}stopLibp2pPing(e){const t=e.toString();this.pingKeepAliveTimers.has(t)?(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)):Kc.warn(`Ping not started for peer: ${t}, skipping stop for ping`)}startRelayPing(e){if(!this.relay)return;if(0===this.options.relayKeepAlive)return void Kc.warn(`Relay keep alive is disabled relayKeepAlive:${this.options.relayKeepAlive}, skipping start for relay ping`);if(this.relayKeepAliveTimers.has(e.toString()))return void Kc.warn(`Relay ping already started for peer: ${e.toString()}, skipping start for relay ping`);const t=[];for(const r of this.relay.pubsubTopics){if(!this.relay.getMeshPeers(r).includes(e.toString())){Kc.warn(`Peer: ${e.toString()} is not in the mesh for topic: ${r}, skipping start for relay ping`);continue}const n=Es({routingInfo:gi(this.networkConfig,{contentTopic:jc,pubsubTopic:r}),contentTopic:jc,ephemeral:!0}),i=setInterval((()=>{this.pingRelay(n)}),1e3*this.options.relayKeepAlive);t.push(i)}this.relayKeepAliveTimers.set(e.toString(),t)}stopRelayPing(e){var t;if(!this.relay)return;const r=e.toString();this.relayKeepAliveTimers.has(r)?(null===(t=this.relayKeepAliveTimers.get(r))||void 0===t||t.map(clearInterval),this.relayKeepAliveTimers.delete(r)):Kc.warn(`Relay ping not started for peer: ${r}, skipping stop for relay ping`)}async pingRelay(e){try{Kc.info("Sending Waku Relay ping message"),await this.relay.send(e,{payload:new Uint8Array([1])})}catch(e){Kc.error("Failed to send relay ping",e)}}async pingLibp2p(e){try{Kc.info(`Pinging libp2p peer (${e.toString()})`);const t=await this.libp2p.services.ping.ping(e);Kc.info(`Ping succeeded (${e.toString()})`,t),await this.libp2p.peerStore.merge(e,{metadata:{ping:ai(t.toString())}}),Kc.info(`Ping updated for peer (${e.toString()})`)}catch(t){Kc.error(`Ping failed for peer (${e.toString()})`,t)}}constructor({options:e,relay:t,networkConfig:r,libp2p:n}){(0,L.default)(this,"relay",void 0),(0,L.default)(this,"networkConfig",void 0),(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"options",void 0),(0,L.default)(this,"pingKeepAliveTimers",new Map),(0,L.default)(this,"relayKeepAliveTimers",new Map),this.options=e,this.relay=t,this.networkConfig=r,this.libp2p=n,this.onPeerConnect=this.onPeerConnect.bind(this),this.onPeerDisconnect=this.onPeerDisconnect.bind(this)}}class Hc{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(e){}}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(e){}}isConnected(){return!!this.isBrowserConnected()&&this.isP2PConnected()}isP2PConnected(){return this.isNetworkConnected}isBrowserConnected(){try{var e;if((null===globalThis||void 0===globalThis?void 0:globalThis.navigator)&&!(null===globalThis||void 0===globalThis||null===(e=globalThis.navigator)||void 0===e?void 0:e.onLine))return!1}catch(e){}return!0}onConnectedEvent(){this.isNetworkConnected||(this.isNetworkConnected=!0,this.dispatchNetworkEvent())}onDisconnectedEvent(){this.isNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isNetworkConnected=!1,this.dispatchNetworkEvent())}dispatchNetworkEvent(){this.events.dispatchEvent(new CustomEvent(xs.Connection,{detail:this.isConnected()}))}constructor(e){(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"events",void 0),(0,L.default)(this,"isNetworkConnected",!1),this.libp2p=e.libp2p,this.events=e.events,this.onConnectedEvent=this.onConnectedEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this),this.dispatchNetworkEvent=this.dispatchNetworkEvent.bind(this)}}const Wc=new gs("shard-reader");class Gc{async isPeerOnCluster(e){const t=await this.getRelayShards(e);return!!t&&t.clusterId===this.clusterId}async hasShardInfo(e){return!!await this.getRelayShards(e)}async isPeerOnTopic(e,t){try{const{clusterId:r,shard:n}=ci(t);return r===this.clusterId&&await this.isPeerOnShard(e,n)}catch(r){return Wc.error(`Error comparing pubsub topic ${t} with shard info for ${e}`,r),!1}}async isPeerOnShard(e,t){const r=await this.getRelayShards(e);return Wc.info(`Checking if peer on same shard: this { clusterId: ${this.clusterId}, shardId: ${t} },${e} { clusterId: ${null==r?void 0:r.clusterId}, shards: ${null==r?void 0:r.shards} }`),!!r&&r.clusterId===this.clusterId&&r.shards.includes(t)}async getRelayShards(e){try{const t=(await this.libp2p.peerStore.get(e)).metadata.get("shardInfo");if(!t)return;return mi(t)}catch(t){return void Wc.error("Error getting shard info for "+e,t)}}constructor(e){(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"clusterId",void 0),this.libp2p=e.libp2p,this.clusterId=e.networkConfig.clusterId}}const Xc=new gs("connection-manager");class Zc{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(e,t){const r=Si(n=e)?n:Mc(n);var n;Xc.info(`Dialing peer ${r.toString()} with protocols ${t}`);const i=await this.libp2p.dialProtocol(r,t);return Xc.info(`Dialed peer ${r.toString()} with protocols ${t}`),i}async hangUp(e){const t=Si(r=e)?r:qu(Mc(r).getPeerId());var r;try{return Xc.info("Dropping connection with peer "+t.toString()),await this.libp2p.hangUp(t),Xc.info("Dropped connection with peer "+t.toString()),!0}catch(e){return Xc.error(`Error dropping connection with peer ${t.toString()} - ${e}`),!1}}async getConnectedPeers(e){const t=this.libp2p.getPeers();if(Xc.info("Getting connected peers for codec "+e),0===t.length)return Xc.info("No connected peers"),[];const r=(await Promise.all(t.map((async e=>{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}})))).filter((e=>!!e)).filter((t=>!e||t.protocols.includes(e))).sort(((e,t)=>Oc(e)-Oc(t)));return Xc.info(`Found ${r.length} connected peers for codec ${e}`),r}async hasShardInfo(e){return this.shardReader.hasShardInfo(e)}async isPeerOnTopic(e,t){return this.shardReader.isPeerOnTopic(e,t)}async isPeerOnShard(e,t){return this.shardReader.isPeerOnShard(e,t)}constructor(e){(0,L.default)(this,"keepAliveManager",void 0),(0,L.default)(this,"discoveryDialer",void 0),(0,L.default)(this,"dialer",void 0),(0,L.default)(this,"shardReader",void 0),(0,L.default)(this,"networkMonitor",void 0),(0,L.default)(this,"connectionLimiter",void 0),(0,L.default)(this,"options",void 0),(0,L.default)(this,"libp2p",void 0),this.libp2p=e.libp2p,this.options=(0,D.default)({maxBootstrapPeers:3,maxConnections:10,pingKeepAlive:300,relayKeepAlive:300,enableAutoRecovery:!0,maxDialingPeers:3,failedDialCooldown:60,dialCooldown:10},e.config),this.keepAliveManager=new Vc({relay:e.relay,libp2p:e.libp2p,networkConfig:e.networkConfig,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.shardReader=new Gc({libp2p:e.libp2p,networkConfig:e.networkConfig}),this.dialer=new $c({libp2p:e.libp2p,shardReader:this.shardReader,options:this.options}),this.discoveryDialer=new zc({libp2p:e.libp2p,dialer:this.dialer}),this.networkMonitor=new Hc({libp2p:e.libp2p,events:e.events}),this.connectionLimiter=new Fc({libp2p:e.libp2p,events:e.events,networkMonitor:this.networkMonitor,dialer:this.dialer,options:this.options})}}const Yc=new gs("metadata"),Qc="/vac/waku/metadata/1.0.0";class Jc{async query(e){const t=qr.encode({clusterId:this.clusterId,shards:[]});if(!await this.libp2pComponents.peerStore.get(e))return{shardInfo:null,error:ks.NO_PEER_AVAILABLE};const r=await this.streamManager.getStream(e);if(!r)return Yc.error("Failed to get a stream for remote peer:"+e.toString()),{shardInfo:null,error:ks.NO_STREAM_AVAILABLE};const n=await uo([t],Ks,r,Ys,(async e=>await Ds(e))),{error:i,shardInfo:s}=this.decodeMetadataResponse(n);return i?{shardInfo:null,error:i}:(await this.savePeerShardInfo(e,s),{shardInfo:s,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=zr.encode({clusterId:this.clusterId,shards:[]}),i=await uo([n],Ks,t,Ys,(async e=>await Ds(e))),{error:s,shardInfo:o}=this.decodeMetadataResponse(i);if(s)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){Yc.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new qs;e.forEach((e=>{t.append(e)}));const r=zr.decode(t);return r?{shardInfo:r,error:null}:(Yc.error("Error decoding metadata response"),{shardInfo:null,error:ks.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:vi(t)}}),this.handshakesConfirmed.set(e.toString(),t)}constructor(e,t){(0,L.default)(this,"clusterId",void 0),(0,L.default)(this,"streamManager",void 0),(0,L.default)(this,"libp2pComponents",void 0),(0,L.default)(this,"handshakesConfirmed",new Map),(0,L.default)(this,"multicodec",Qc),this.clusterId=e,this.streamManager=new yo(Qc,t),this.libp2pComponents=t,t.registrar.handle(Qc,(e=>{this.onRequest(e)}))}}function ed(e){return t=>new Jc(e,t)}const td=new gs("peer-manager");var rd;(e=>{e.FilterConnect="filter:connect",e.FilterDisconnect="filter:disconnect",e.StoreConnect="store:connect"})(rd||(rd={}));class nd{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(e){td.info(`Getting peers for protocol: ${e.protocol}, pubsubTopic: ${e.pubsubTopic}`);const t=await this.connectionManager.getConnectedPeers();td.info(`Found ${t.length} connected peers`);let r=[];for(const n of t){const t=this.hasPeerProtocol(n,e.protocol),i=await this.isPeerOnPubsub(n.id,e.pubsubTopic),s=this.isPeerAvailableForUse(n.id);t&&i&&s&&(r.push(n),td.info(`Peer ${n.id} qualifies for protocol ${e.protocol}`))}const n=r.filter((e=>this.isPeerLocked(e.id)));if(td.info(`Found ${n.length} locked peers out of ${r.length} qualifying peers`),n.length>=this.numPeersToUse){const e=n.slice(0,this.numPeersToUse).map((e=>e.id));return td.info(`Using ${e.length} locked peers: ${e.map((e=>e.toString()))}`),e}const i=r.filter((e=>!this.isPeerLocked(e.id)));td.info(`Found ${i.length} unlocked peers, need ${this.numPeersToUse-n.length} more`),r=[...n,...i].slice(0,this.numPeersToUse).map((e=>(this.lockPeer(e.id),e)));const s=r.map((e=>e.id));return td.info(`Selected ${s.length} peers: ${s.map((e=>e.toString()))}`),s}async renewPeer(e,t){td.info(`Renewing peer ${e} for protocol: ${t.protocol}, pubsubTopic: ${t.pubsubTopic}`);const r=(await this.connectionManager.getConnectedPeers()).find((t=>t.id.equals(e)));r?(td.info(`Found peer ${e} in connected peers, unlocking and getting new peers`),this.unlockPeer(r.id),await this.getPeers(t)):td.warn(`Cannot renew peer:${e}, no connection to the peer.`)}async isPeerOnPubsub(e,t){return!await this.connectionManager.hasShardInfo(e)||this.connectionManager.isPeerOnTopic(e,t)}async onConnected(e){const t=e.detail,r=t.protocols.includes(this.getProtocolCodecs(Is.Filter)),n=t.protocols.includes(this.getProtocolCodecs(Is.Store));r&&this.dispatchFilterPeerConnect(t.peerId),n&&this.dispatchStorePeerConnect(t.peerId)}async onDisconnected(e){const t=e.detail;try{const e=await this.libp2p.peerStore.get(t);this.hasPeerProtocol(e,Is.Filter)&&this.dispatchFilterPeerDisconnect(e.id)}catch(e){td.error("Failed to dispatch Filter disconnect event:"+e)}}hasPeerProtocol(e,t){return e.protocols.includes(this.getProtocolCodecs(t))}lockPeer(e){td.info("Locking peer "+e),this.lockedPeers.add(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>e.tags.push(Ps))),this.unlockedPeers.delete(e.toString())}isPeerLocked(e){return this.lockedPeers.has(e.toString())}unlockPeer(e){td.info("Unlocking peer "+e),this.lockedPeers.delete(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>{e.tags=e.tags.filter((e=>e!==Ps))})),this.unlockedPeers.set(e.toString(),Date.now())}isPeerAvailableForUse(e){const t=this.unlockedPeers.get(e.toString());if(!t)return!0;const r=new Date(t).getTime();return Date.now()-r>=1e4}dispatchFilterPeerConnect(e){this.events.dispatchEvent(new CustomEvent(rd.FilterConnect,{detail:e}))}dispatchStorePeerConnect(e){this.events.dispatchEvent(new CustomEvent(rd.StoreConnect,{detail:e}))}dispatchFilterPeerDisconnect(e){this.events.dispatchEvent(new CustomEvent(rd.FilterDisconnect,{detail:e}))}getProtocolCodecs(e){if(e===Is.Relay)throw Error("Relay protocol is not supported");return{[Is.Filter]:To,[Is.LightPush]:No,[Is.Store]:Go,"light-push-v2":Mo}[e]}constructor(e){var t;(0,L.default)(this,"events",new es),(0,L.default)(this,"numPeersToUse",void 0),(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"connectionManager",void 0),(0,L.default)(this,"lockedPeers",new Set),(0,L.default)(this,"unlockedPeers",new Map),this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=(null==e||null===(t=e.config)||void 0===t?void 0:t.numPeersToUse)||2,this.libp2p=e.libp2p,this.connectionManager=e.connectionManager}}class id{dispose(){null!==this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.entryTimestamps.clear()}add(e){return this.entryTimestamps.set(e,Date.now()),this}has(e){return this.entryTimestamps.has(e)}startCleanupInterval(e){this.cleanupIntervalId=setInterval((()=>{this.removeExpiredEntries()}),e)}removeExpiredEntries(){const e=Date.now();for(const[t,r]of this.entryTimestamps.entries())e-r>this.ttlMs&&this.entryTimestamps.delete(t)}constructor(e,t=5e3){(0,L.default)(this,"ttlMs",void 0),(0,L.default)(this,"cleanupIntervalId",null),(0,L.default)(this,"entryTimestamps",new Map),this.ttlMs=e,this.startCleanupInterval(t)}}const sd=new gs("sdk:filter-subscription");class od{get contentTopics(){const e=Array.from(this.callbacks.keys()).map((e=>e.contentTopic)),t=new Set(e).values();return Array.from(t)}start(){sd.info("Starting subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted||this.inProgress?sd.info("Subscription already started or in progress, skipping start"):(this.inProgress=!0,this.attemptSubscribe({useNewContentTopics:!1}),this.setupSubscriptionInterval(),this.setupKeepAliveInterval(),this.setupEventListeners(),this.isStarted=!0,this.inProgress=!1,sd.info("Subscription started for pubsubTopic: "+this.pubsubTopic))}stop(){sd.info("Stopping subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted&&!this.inProgress?(this.inProgress=!0,this.disposeEventListeners(),this.disposeIntervals(),this.disposePeers(),this.disposeHandlers(),this.receivedMessages.dispose(),this.inProgress=!1,this.isStarted=!1,sd.info("Subscription stopped for pubsubTopic: "+this.pubsubTopic)):sd.info("Subscription not started or stop in progress, skipping stop")}isEmpty(){return 0===this.callbacks.size}async add(e,t){const r=Array.isArray(e)?e:[e];for(const e of r)this.addSingle(e,t);return!(this.toSubscribeContentTopics.size>0)||await this.attemptSubscribe({useNewContentTopics:!0})}async remove(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.removeSingle(e);return!(this.toUnsubscribeContentTopics.size>0)||await this.attemptUnsubscribe({useNewContentTopics:!0})}invoke(e,t){this.isMessageReceived(e)?sd.info(`Skipping invoking callbacks for already received message: pubsubTopic:${this.pubsubTopic}, peerId:${t.toString()}, contentTopic:${e.contentTopic}`):(sd.info("Invoking message for contentTopic: "+e.contentTopic),this.messageEmitter.dispatchEvent(new CustomEvent(e.contentTopic,{detail:e})))}addSingle(e,t){sd.info("Adding subscription for contentTopic: "+e.contentTopic);const r=!this.contentTopics.includes(e.contentTopic);if(r&&this.toSubscribeContentTopics.add(e.contentTopic),this.callbacks.has(e)){sd.warn(`Replacing callback associated associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`);const t=this.callbacks.get(e);this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t)}const n=r=>{(async()=>{try{const n=await e.fromProtoObj(e.pubsubTopic,r.detail);t(n)}catch(e){sd.error("Error decoding message",e)}})()};this.callbacks.set(e,n),this.messageEmitter.addEventListener(e.contentTopic,n),sd.info(`Subscription added for contentTopic: ${e.contentTopic}, isNewContentTopic: ${r}`)}removeSingle(e){sd.info("Removing subscription for contentTopic: "+e.contentTopic);const t=this.callbacks.get(e);t||sd.warn(`No callback associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`),this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t);const r=!this.contentTopics.includes(e.contentTopic);r&&this.toUnsubscribeContentTopics.add(e.contentTopic),sd.info(`Subscription removed for contentTopic: ${e.contentTopic}, isCompletelyRemoved: ${r}`)}isMessageReceived(e){try{const t=function(e,t){const r=ms(e,t);return si(r)}(this.pubsubTopic,e);if(this.receivedMessages.has(t))return!0;this.receivedMessages.add(t)}catch(e){}return!1}setupSubscriptionInterval(){sd.info("Setting up subscription interval with period 1000ms"),this.subscribeIntervalId=setInterval((()=>{(async()=>{this.toSubscribeContentTopics.size>0&&(sd.info(`Subscription interval: ${this.toSubscribeContentTopics.size} topics to subscribe`),await this.attemptSubscribe({useNewContentTopics:!0})),this.toUnsubscribeContentTopics.size>0&&(sd.info(`Subscription interval: ${this.toUnsubscribeContentTopics.size} topics to unsubscribe`),await this.attemptUnsubscribe({useNewContentTopics:!0}))})()}),1e3)}setupKeepAliveInterval(){sd.info(`Setting up keep-alive interval with period ${this.config.keepAliveIntervalMs}ms`),this.keepAliveIntervalId=setInterval((()=>{(async()=>{sd.info(`Keep-alive interval running for ${this.peers.size} peers`);let e=await Promise.all(Array.from(this.peers.values()).map((async e=>{if((await this.protocol.ping(e)).success)return sd.info("Ping successful for peer: "+e.toString()),void this.peerFailures.set(e.toString(),0);let t=this.peerFailures.get(e.toString())||0;return t+=1,this.peerFailures.set(e.toString(),t),sd.warn(`Ping failed for peer: ${e.toString()}, failures: ${t}/${this.config.pingsBeforePeerRenewed}`),t<this.config.pingsBeforePeerRenewed?void 0:(sd.info(`Peer ${e.toString()} exceeded max failures (${this.config.pingsBeforePeerRenewed}), will be replaced`),e)})));e=e.filter((e=>!!e)),await Promise.all(e.map((e=>(this.peers.delete(null==e?void 0:e.toString()),this.peerFailures.delete(null==e?void 0:e.toString()),this.requestUnsubscribe(e,this.contentTopics))))),e.length>0&&(sd.info(`Replacing ${e.length} failed peers`),await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}))})()}),this.config.keepAliveIntervalMs)}setupEventListeners(){this.peerManager.events.addEventListener(rd.FilterConnect,this.onPeerConnected),this.peerManager.events.addEventListener(rd.FilterDisconnect,this.onPeerDisconnected)}disposeIntervals(){this.subscribeIntervalId&&clearInterval(this.subscribeIntervalId),this.keepAliveIntervalId&&clearInterval(this.keepAliveIntervalId)}disposeHandlers(){for(const[e,t]of this.callbacks.entries())this.messageEmitter.removeEventListener(e.contentTopic,t);this.callbacks.clear()}async disposePeers(){await this.attemptUnsubscribe({useNewContentTopics:!1}),this.peers.clear(),this.peerFailures=new Map}disposeEventListeners(){this.peerManager.events.removeEventListener(rd.FilterConnect,this.onPeerConnected),this.peerManager.events.removeEventListener(rd.FilterDisconnect,this.onPeerDisconnected)}async onPeerConnected(e){var t;const r=null===(t=e.detail)||void 0===t?void 0:t.toString();sd.info("Peer connected: "+r),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(r)?sd.info(`Peer ${r} already subscribed, skipping`):await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}):sd.info(`Peer ${r} doesn't support pubsubTopic:${this.pubsubTopic}`)}async onPeerDisconnected(e){var t;const r=null===(t=e.detail)||void 0===t?void 0:t.toString();sd.info("Peer disconnected: "+r),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(r)?(sd.info(`Active peer ${r} disconnected, removing from peers list`),this.peers.delete(r),this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})):sd.info(`Disconnected peer ${r} not in use, ignoring`):sd.info(`Peer ${r} doesn't support pubsubTopic:${this.pubsubTopic}`)}async attemptSubscribe(e){const{useNewContentTopics:t,useOnlyNewPeers:r=!1}=e,n=t?Array.from(this.toSubscribeContentTopics):this.contentTopics;if(sd.info(`Attempting to subscribe: useNewContentTopics=${t}, useOnlyNewPeers=${r}, contentTopics=${n.length}`),!n.length)return sd.warn("Requested content topics is an empty array, skipping"),!1;const i=new Set(this.peers.keys()),s=await this.peerManager.getPeers({protocol:Is.Filter,pubsubTopic:this.pubsubTopic});for(const e of s){if(this.peers.size>=this.config.numPeersToUse)break;this.peers.set(e.toString(),e)}const o=r?Array.from(this.peers.values()).filter((e=>!i.has(e.toString()))):Array.from(this.peers.values());if(sd.info(`Subscribing with ${o.length} peers for ${n.length} content topics`),r&&0===o.length)return sd.warn("Requested to use only new peers, but no peers found, skipping"),!1;const a=await Promise.all(o.map((e=>this.requestSubscribe(e,n)))),l=a.filter((e=>e)).length;return sd.info(`Subscribe attempts completed: ${l}/${a.length} successful`),t&&(this.toSubscribeContentTopics=new Set),a.some((e=>e))}async requestSubscribe(e,t){if(sd.info(`requestSubscribe: pubsubTopic:${this.pubsubTopic}\tcontentTopics:${t.join(",")}`),!t.length||!this.pubsubTopic)return sd.warn("requestSubscribe: no contentTopics or pubsubTopic provided, not sending subscribe request"),!1;const r=await this.protocol.subscribe(this.pubsubTopic,e,t);return r.failure?(sd.warn(`requestSubscribe: Failed to subscribe ${this.pubsubTopic} to ${e.toString()} with error:${r.failure.error} for contentTopics:${t}`),!1):(sd.info(`requestSubscribe: Subscribed ${this.pubsubTopic} to ${e.toString()} for contentTopics:${t}`),!0)}async attemptUnsubscribe(e){const{useNewContentTopics:t}=e,r=t?Array.from(this.toUnsubscribeContentTopics):this.contentTopics;if(sd.info(`Attempting to unsubscribe: useNewContentTopics=${t}, contentTopics=${r.length}`),!r.length)return sd.warn("Requested content topics is an empty array, skipping"),!1;const n=Array.from(this.peers.values()),i=await Promise.all(n.map((e=>this.requestUnsubscribe(e,t?r:void 0)))),s=i.filter((e=>e)).length;return sd.info(`Unsubscribe attempts completed: ${s}/${i.length} successful`),t&&(this.toUnsubscribeContentTopics=new Set),i.some((e=>e))}async requestUnsubscribe(e,t){var r;const n=t?await this.protocol.unsubscribe(this.pubsubTopic,e,t):await this.protocol.unsubscribeAll(this.pubsubTopic,e);return n.failure?(sd.warn(`requestUnsubscribe: Failed to unsubscribe for pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} with error:${null===(r=n.failure)||void 0===r?void 0:r.error} for contentTopics:${t}`),!1):(sd.info(`requestUnsubscribe: Unsubscribed pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} for contentTopics:${t}`),!0)}constructor(e){(0,L.default)(this,"pubsubTopic",void 0),(0,L.default)(this,"protocol",void 0),(0,L.default)(this,"peerManager",void 0),(0,L.default)(this,"config",void 0),(0,L.default)(this,"isStarted",!1),(0,L.default)(this,"inProgress",!1),(0,L.default)(this,"peers",new Map),(0,L.default)(this,"peerFailures",new Map),(0,L.default)(this,"receivedMessages",new id(6e4)),(0,L.default)(this,"callbacks",new Map),(0,L.default)(this,"messageEmitter",new es),(0,L.default)(this,"toSubscribeContentTopics",new Set),(0,L.default)(this,"toUnsubscribeContentTopics",new Set),(0,L.default)(this,"subscribeIntervalId",null),(0,L.default)(this,"keepAliveIntervalId",null),this.config=e.config,this.pubsubTopic=e.pubsubTopic,this.protocol=e.protocol,this.peerManager=e.peerManager,this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}}const ad=new gs("sdk:filter");class ld{get multicodec(){return this.protocol.multicodec}async start(){await this.protocol.start()}async stop(){await this.protocol.stop()}unsubscribeAll(){for(const e of this.subscriptions.values())e.stop();this.subscriptions.clear()}async subscribe(e,t){const r=Array.isArray(e)?e:[e];if(0===r.length)throw Error("Cannot subscribe with 0 decoders.");const n=r.map((e=>e.pubsubTopic)),i=n[0],s=r.map((e=>e.contentTopic));ad.info(`Subscribing to contentTopics: ${s}, pubsubTopic: ${i}`),this.throwIfTopicNotSame(n);let o=this.subscriptions.get(i);o||(o=new od({pubsubTopic:i,protocol:this.protocol,config:this.config,peerManager:this.peerManager}),o.start());const a=await o.add(r,t);return this.subscriptions.set(i,o),ad.info(`Subscription ${a?"successful":"failed"} for content topic: ${s}`),a}async unsubscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw Error("Cannot unsubscribe with 0 decoders.");const r=t.map((e=>e.pubsubTopic)),n=r[0],i=t.map((e=>e.contentTopic));ad.info(`Unsubscribing from contentTopics: ${i}, pubsubTopic: ${n}`),this.throwIfTopicNotSame(r);const s=this.subscriptions.get(n);if(!s)return ad.warn("No subscriptions associated with the decoder."),!1;const o=await s.remove(t);return s.isEmpty()&&(ad.warn("Subscription has no decoders anymore, terminating it."),s.stop(),this.subscriptions.delete(n)),ad.info(`Unsubscribing ${o?"successful":"failed"} for content topic: ${i}`),o}async onIncomingMessage(e,t,r){ad.info(`Received message for pubsubTopic:${e}, contentTopic:${t.contentTopic}, peerId:${r.toString()}`);const n=this.subscriptions.get(e);n?n.invoke(t,r):ad.error("No subscription locally registered for topic "+e)}throwIfTopicNotSame(e){const t=e[0];if(!e.every((e=>e===t)))throw Error("Cannot subscribe to more than one pubsub topic at the same time, got pubsubTopics:"+e)}constructor(e){(0,L.default)(this,"protocol",void 0),(0,L.default)(this,"peerManager",void 0),(0,L.default)(this,"config",void 0),(0,L.default)(this,"subscriptions",new Map),this.config=(0,D.default)({numPeersToUse:2,pingsBeforePeerRenewed:3,keepAliveIntervalMs:6e4},e.options),this.peerManager=e.peerManager,this.protocol=new Ro(this.onIncomingMessage.bind(this),e.libp2p)}}var ud,cd,dd=function(){if(cd)return ud;cd=1;var e=/^\s+|\s+$/g,t=/^[-+]0x[0-9a-f]+$/i,r=/^0b[01]+$/i,n=/^0o[0-7]+$/i,i=parseInt,s="object"==typeof is&&is&&is.Object===Object&&is,o="object"==typeof self&&self&&self.Object===Object&&self,a=s||o||Function("return this")(),l=Object.prototype.toString,u=Math.max,c=Math.min,d=()=>a.Date.now();function h(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function f(s){if("number"==typeof s)return s;if(function(e){return"symbol"==typeof e||(e=>!!e&&"object"==typeof e)(e)&&"[object Symbol]"==l.call(e)}(s))return NaN;if(h(s)){var o="function"==typeof s.valueOf?s.valueOf():s;s=h(o)?o+"":o}if("string"!=typeof s)return 0===s?s:+s;s=s.replace(e,"");var a=r.test(s);return a||n.test(s)?i(s.slice(2),a?2:8):t.test(s)?NaN:+s}return ud=function(e,t,r){var n,i,s,o,a,l,p=0,g=!1,m=!1,v=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function y(t){var r=n,s=i;return n=i=void 0,p=t,o=e.apply(s,r)}function b(e){var r=e-l;return void 0===l||r>=t||r<0||m&&e-p>=s}function w(){var e=d();if(b(e))return E(e);a=setTimeout(w,function(e){var r=t-(e-l);return m?c(r,s-(e-p)):r}(e))}function E(e){return a=void 0,v&&n?y(e):(n=i=void 0,o)}function S(){var e=d(),r=b(e);if(n=arguments,i=this,l=e,r){if(void 0===a)return function(e){return p=e,a=setTimeout(w,t),g?y(e):o}(l);if(m)return a=setTimeout(w,t),y(l)}return void 0===a&&(a=setTimeout(w,t)),o}return t=f(t)||0,h(r)&&(g=!!r.leading,s=(m="maxWait"in r)?u(f(r.maxWait)||0,t):s,v="trailing"in r?!!r.trailing:v),S.cancel=function(){void 0!==a&&clearTimeout(a),p=0,n=l=i=a=void 0},S.flush=function(){return void 0===a?o:E(d())},S},ud}(),hd=ss(dd);const fd=new gs("health-indicator");class pd{start(){this.isStarted||(this.isStarted=!0,fd.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,fd.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(e){fd.info("onPeerDisconnected: received libp2p event"),this.debouncedAssessHealth()}onPeerIdentify(e){fd.info("onPeerIdentify: received libp2p event"),this.debouncedAssessHealth()}async assessHealth(){const e=this.libp2p.getConnections();if(0===e.length)return fd.info("assessHealth: no connections, setting to Unhealthy"),void this.updateAndDispatchHealthEvent(Ls.Unhealthy);const t=await Promise.all(e.map((async e=>{try{return await this.libp2p.peerStore.get(e.remotePeer)}catch(t){return fd.warn(`assessHealth: failed to get peer ${e.remotePeer}, skipping`),null}}))),r=t.filter((e=>null==e?void 0:e.protocols.includes(To))).length,n=t.filter((e=>null==e?void 0:e.protocols.includes(No))).length;let i;0===r||0===n?i=Ls.Unhealthy:r>=2&&n>=2?i=Ls.SufficientlyHealthy:1===r&&1===n?i=Ls.MinimallyHealthy:(fd.error(`assessHealth: unexpected state, cannot identify health status of the node: Filter:${r}; LightPush:${n}`),i=this.value),fd.info(`assessHealth: node identified as ${i} Filter:${r}; LightPush:${n}`),this.updateAndDispatchHealthEvent(i)}updateAndDispatchHealthEvent(e){this.value!==e&&(this.value=e,this.events.dispatchEvent(new CustomEvent(xs.Health,{detail:this.value})))}constructor(e){(0,L.default)(this,"isStarted",!1),(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"events",void 0),(0,L.default)(this,"value",Ls.Unhealthy),(0,L.default)(this,"debouncedAssessHealth",void 0),this.libp2p=e.libp2p,this.events=e.events,this.onPeerIdentify=this.onPeerIdentify.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this),this.debouncedAssessHealth=hd((()=>{this.assessHealth()}),100)}}const gd=e=>new Promise(((t,r)=>setTimeout((()=>r(Error("Task timeout"))),e))),md=new gs("sdk:retry-manager");class vd{start(){this.intervalID=setInterval((()=>{this.processQueue()}),this.retryIntervalMs)}stop(){this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}push(e,t,r){this.queue.push({maxAttempts:t,callback:e,routingInfo:r})}processQueue(){if(0!==this.queue.length)for(;this.queue.length&&this.inProgress<5;){const e=this.queue.shift();e&&this.scheduleTask(e)}}scheduleTask(e){setTimeout((async()=>this.taskExecutor(e)),100)}async taskExecutor(e){if(e.maxAttempts<=0)return void md.warn("scheduleTask: max attempts has reached, removing from queue");const t=(await this.peerManager.getPeers({protocol:Is.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}))[0];if(!t)return md.warn("scheduleTask: no peers, putting back to queue"),void this.queue.push((0,M.default)((0,D.default)({},e),{maxAttempts:e.maxAttempts-1}));try{this.inProgress+=1;const r=await Promise.race([gd(1e4),e.callback(t)]);if(void 0===r)throw Error("Task timeout");if(r.failure)throw Error(r.failure.error);if(md.info("scheduleTask: executed successfully"),0===e.maxAttempts)return void md.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push((0,M.default)((0,D.default)({},e),{maxAttempts:e.maxAttempts-1}))}catch(n){const i=n;if(md.error("scheduleTask: task execution failed with error:",i),((r=i.message)===_s.REMOTE_PEER_REJECTED||r===_s.NO_RESPONSE||r===_s.RLN_PROOF_GENERATION||r===_s.NO_PEER_AVAILABLE)&&await this.peerManager.renewPeer(t,{protocol:Is.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}),0===e.maxAttempts)return void md.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push((0,M.default)((0,D.default)({},e),{maxAttempts:e.maxAttempts-1}))}finally{this.inProgress-=1}var r}constructor(e){(0,L.default)(this,"intervalID",null),(0,L.default)(this,"retryIntervalMs",void 0),(0,L.default)(this,"inProgress",0),(0,L.default)(this,"queue",[]),(0,L.default)(this,"peerManager",void 0),this.peerManager=e.peerManager,this.retryIntervalMs=e.retryIntervalMs||1e3}}const yd=new gs("sdk:light-push"),bd={autoRetry:!0,retryIntervalMs:1e3,maxAttempts:3,numPeersToUse:1};class wd{get multicodec(){return this.protocol.multicodec}start(){this.retryManager.start()}stop(){this.retryManager.stop()}async send(e,t,r={}){r=(0,D.default)({useLegacy:!1},this.config,r);const{pubsubTopic:n}=e;yd.info("send: attempting to send a message to pubsubTopic:",n);const i=await this.peerManager.getPeers({protocol:r.useLegacy?"light-push-v2":Is.LightPush,pubsubTopic:e.pubsubTopic}),s=(null==i?void 0:i.length)>0?await Promise.all(i.map((n=>this.protocol.send(e,t,n,r.useLegacy).catch((()=>({success:null,failure:{error:_s.GENERIC_FAIL}})))))):[],o=s.length?{successes:s.filter((e=>e.success)).map((e=>e.success)),failures:s.filter((e=>e.failure)).map((e=>e.failure))}:{successes:[],failures:[{error:_s.NO_PEER_AVAILABLE}]};if(r.autoRetry&&0===o.successes.length){const n=n=>this.protocol.send(e,t,n,r.useLegacy);this.retryManager.push(n.bind(this),r.maxAttempts||3,e.routingInfo)}return o}constructor(e){(0,L.default)(this,"config",void 0),(0,L.default)(this,"retryManager",void 0),(0,L.default)(this,"peerManager",void 0),(0,L.default)(this,"protocol",void 0),this.config=(0,D.default)({},bd,e.options||{}),this.peerManager=e.peerManager,this.protocol=new qo(e.libp2p),this.retryManager=new vd({peerManager:e.peerManager,retryIntervalMs:this.config.retryIntervalMs})}}const Ed=new gs("store-sdk");class Sd{get multicodec(){return this.protocol.multicodec}async*queryGenerator(e,t){const{decodersAsMap:r,queryOptions:n}=this.buildQueryParams(e,t);for(const e of n){var i;const n=null!==(i=null==t?void 0:t.peerId)&&void 0!==i?i:await this.getPeerToUse(e.pubsubTopic);if(!n)throw Ed.error("No peers available to query"),Error("No peers available to query");Ed.info("Querying store with options: "+JSON.stringify(e));const s=this.protocol.queryPerPage(e,r,n);for await(const e of s)yield e}}async queryWithOrderedCallback(e,t,r){Ed.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){Ed.info("Querying store with promise callback");let n=!1;for await(const i of this.queryGenerator(e,r)){const e=i.map((async e=>{n||(n=!!await t(e))}));if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(Yr);return await Promise.all(n.map((async e=>{e&&!r&&(r=!!await t(e))}))),r}createCursor(e){return ms(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw Ed.error("No decoders provided"),Error("No decoders provided");const t=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(t.length>1)throw Ed.error("API does not support querying multiple pubsub topics at once"),Error("API does not support querying multiple pubsub topics at once");const r=t[0],n=new Map;e.forEach((e=>{if(n.has(e.contentTopic))throw Ed.error("API does not support different decoder per content topic"),Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)}));const i=e.filter((e=>e.pubsubTopic===r)).map((e=>e.contentTopic));if(0===i.length)throw Ed.error("No decoders found for topic "+r),Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:i,decodersAsMap:n}}async getPeerToUse(e){const t=await this.peerManager.getPeers({protocol:Is.Store,pubsubTopic:e});return this.options.peers?await this.getPeerFromConfigurationOrFirst(t,this.options.peers):t[0]}async getPeerFromConfigurationOrFirst(e,t){const r=t.map(Mc),n=[];for(const t of r){const r=e.find((e=>{var r;return e.toString()===(null===(r=t.getPeerId())||void 0===r?void 0:r.toString())}));if(r)return r;n.push(t)}for(;n.length;){const e=n.pop();if(!e)return;try{if(await this.libp2p.dial(e))return qu(e.getPeerId())}catch(t){Ed.warn(`Failed to dial peer from options.peers list for Store protocol. Peer:${e.getPeerId()}, error:${t}`)}}return Ed.warn(`Passed node to use for Store not found: ${t.toString()}. Attempting to use first available peers.`),e[0]}buildQueryParams(e,t){var r;let n,i,s;if((null==t?void 0:t.messageHashes)&&t.messageHashes.length>0)n=t.pubsubTopic||(null===(r=e[0])||void 0===r?void 0:r.pubsubTopic)||"",i=[],s=new Map,e.forEach((e=>{s.set(e.contentTopic,e)}));else{const t=this.validateDecodersAndPubsubTopic(e);n=t.pubsubTopic,i=t.contentTopics,s=t.decodersAsMap}const o=[];if((null==t?void 0:t.timeStart)&&(null==t?void 0:t.timeEnd)){let e=t.timeStart;const r=t.timeEnd;for(;r.getTime()-e.getTime()>this.protocol.maxTimeLimit;){const t=new Date(e.getTime()+this.protocol.maxTimeLimit);o.push([e,t]),e=t}0===o.length&&(Ed.info("Using single time range"),o.push([e,r]))}return 0===o.length?(Ed.info("No sub time ranges"),{decodersAsMap:s,queryOptions:[(0,D.default)({pubsubTopic:n,contentTopics:i,includeData:!0,paginationForward:!0},t)]}):(Ed.info(`Building ${o.length} sub time ranges`),{decodersAsMap:s,queryOptions:o.map((([e,r])=>(0,M.default)((0,D.default)({pubsubTopic:n,contentTopics:i,includeData:!0,paginationForward:!0},t),{timeStart:e,timeEnd:r})))})}constructor(e){(0,L.default)(this,"options",void 0),(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"peerManager",void 0),(0,L.default)(this,"protocol",void 0),this.options=e.options||{},this.peerManager=e.peerManager,this.libp2p=e.libp2p,this.protocol=new Xo(e.libp2p)}}const Ad=new gs("wait-for-remote-peer");function Id(e,t){return e.map((e=>async function(e,t){Ad.info(`Waiting for ${e} peer.`),await new Promise((r=>{const n=async i=>{var s,o;if(null===(s=i.detail)||void 0===s||null===(o=s.protocols)||void 0===o?void 0:o.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(i.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&Ad.error("Connection closed. Some peers can be on different shard."),Ad.error("Error waiting for metadata: "+e)}}};t.addEventListener("peer:identify",n)}))}(e,t)))}async function _d(e,t){const r=[];if(e.relay&&t.includes(Is.Relay)&&r.push(e.relay.waitForPeers()),e.store&&t.includes(Is.Store)&&r.push(...Id([Go],e.libp2p)),e.lightPush&&t.includes(Is.LightPush)){const t=Id([No,Mo],e.libp2p);r.push(Promise.any(t))}return e.filter&&t.includes(Is.Filter)&&r.push(...Id([To],e.libp2p)),Promise.all(r)}const Cd=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(Error(t))),e))),kd=new gs("sdk:waku");class xd{get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}get health(){return this.healthIndicator.toValue()}async dial(e,t){const r=null!=t?t:[];void 0===t&&(this.relay&&r.push(Is.Relay),this.store&&r.push(Is.Store),this.filter&&r.push(Is.Filter),this.lightPush&&r.push(Is.LightPush));const n=[];return r.includes(Is.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>n.push(e))):kd.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Is.Store)&&(this.store?n.push(this.store.multicodec):kd.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Is.LightPush)&&(this.lightPush?n.push(...this.lightPush.multicodec):kd.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Is.Filter)&&(this.filter?n.push(this.filter.multicodec):kd.error("Filter codec not included in dial codec: protocol not mounted locally")),kd.info(`Dialing to ${null==e?void 0:e.toString()} with protocols ${r}`),await this.connectionManager.dial(e,n)}async hangUp(e){return kd.info(`Hanging up peer:${null==e?void 0:e.toString()}.`),this.connectionManager.hangUp(e)}async start(){var e,t;this._nodeStateLock||this.isStarted()||(this._nodeStateLock=!0,await this.libp2p.start(),await(null===(e=this.filter)||void 0===e?void 0:e.start()),this.connectionManager.start(),this.peerManager.start(),this.healthIndicator.start(),null===(t=this.lightPush)||void 0===t||t.start(),this._nodeStateLock=!1,this._nodeStarted=!0)}async stop(){var e,t;!this._nodeStateLock&&this.isStarted()&&(this._nodeStateLock=!0,null===(e=this.lightPush)||void 0===e||e.stop(),await(null===(t=this.filter)||void 0===t?void 0:t.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(e,t){return async function(e,t,r){t=(null==t?void 0:t.length)?t:function(e){const t=[];return e.relay&&t.push(Is.Relay),e.filter&&t.push(Is.Filter),e.store&&t.push(Is.Store),e.lightPush&&t.push(Is.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");for(const r of t)switch(r){case Is.Relay:if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");break;case Is.LightPush:if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");break;case Is.Store:if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");break;case Is.Filter:if(!e.filter)throw Error("Cannot wait for Filter peer: protocol not mounted")}const i=[_d(e,t)];n.length>0&&!t.includes(Is.Relay)&&i.push(async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,i=function(e){const t=new Map,r={[Is.Filter]:[To],[Is.LightPush]:[No,Mo],[Is.Store]:[Go]};for(const n of e)r[n]&&r[n].forEach((e=>{t.set(e,!1)}));return t}(t);if(r.length&&n)for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some((e=>i.has(e)))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach((e=>{i.has(e)&&i.set(e,!0)})),Array.from(i.values()).every((e=>e))))return}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&Ad.error("Connection closed. Some peers can be on different shard."),Ad.error("Error while iterating through peers: "+e);continue}else Ad.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`)}(e,t)),r?await async function(e,t,r){await Promise.race([e,Cd(t,"Timed out waiting for a remote peer.")])}(Promise.any(i),r):await Promise.any(i)}(this,e,t)}isStarted(){return this._nodeStarted&&"started"===this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}createDecoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return function(e,t){return new Ss(e,t)}(e.contentTopic,t)}createEncoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return Es({contentTopic:e.contentTopic,ephemeral:e.ephemeral,routingInfo:t})}createRoutingInfo(e,t){return gi(this.networkConfig,{contentTopic:e,shardId:t})}constructor(e,t,r,n){(0,L.default)(this,"libp2p",void 0),(0,L.default)(this,"relay",void 0),(0,L.default)(this,"store",void 0),(0,L.default)(this,"filter",void 0),(0,L.default)(this,"lightPush",void 0),(0,L.default)(this,"events",new es),(0,L.default)(this,"networkConfig",void 0),(0,L.default)(this,"_nodeStateLock",!1),(0,L.default)(this,"_nodeStarted",!1),(0,L.default)(this,"connectionManager",void 0),(0,L.default)(this,"peerManager",void 0),(0,L.default)(this,"healthIndicator",void 0),this.relay=n,this.libp2p=t,this.networkConfig=e.networkConfig||Rs,r=(0,D.default)({filter:!1,lightpush:!1,store:!1},r);const i=this.libp2p.peerId.toString();this.connectionManager=new Zc({libp2p:t,relay:this.relay,events:this.events,networkConfig:this.networkConfig,config:null==e?void 0:e.connectionManager}),this.peerManager=new nd({libp2p:t,config:{numPeersToUse:e.numPeersToUse},connectionManager:this.connectionManager}),this.healthIndicator=new pd({libp2p:t,events:this.events}),r.store&&(this.store=new Sd({libp2p:t,peerManager:this.peerManager,options:null==e?void 0:e.store})),r.lightpush&&(this.lightPush=new wd({libp2p:t,peerManager:this.peerManager,options:null==e?void 0:e.lightPush})),r.filter&&(this.filter=new ld({libp2p:t,peerManager:this.peerManager,options:e.filter})),kd.info("Waku node created",i,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}}const Td=4194304;let Pd=class extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidMessageLengthError"),(0,L.default)(this,"code","ERR_INVALID_MSG_LENGTH")}},Rd=class extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidDataLengthError"),(0,L.default)(this,"code","ERR_MSG_DATA_TOO_LONG")}},Ld=class extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidDataLengthLengthError"),(0,L.default)(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},Dd=class extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","UnexpectedEOFError"),(0,L.default)(this,"code","ERR_UNEXPECTED_EOF")}};function Md(e){return null!=e[Symbol.asyncIterator]}function Nd(e,t){if(e.byteLength>t)throw new Rd("Message length too long")}const Od=e=>{const t=ie(e),r=Y(t);return ae(e,r),Od.bytes=t,r};function Ud(e,t){var r,n;const i=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:Od,s=null!==(n=null==t?void 0:t.maxDataLength)&&void 0!==n?n:Td;function*o(e){Nd(e,s);const t=i(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Md(e)?async function*(){for await(const t of e)yield*o(t)}():function*(){for(const t of e)yield*o(t)}()}var Fd;Od.bytes=0,Ud.single=(e,t)=>{var r;const n=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:Od;var i;return Nd(e,null!==(i=null==t?void 0:t.maxDataLength)&&void 0!==i?i:Td),new qs(n(e.byteLength),e)},(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Fd||(Fd={}));const Bd=e=>{const t=le(e);return Bd.bytes=ie(t),t};function $d(e,t){const r=new qs;let n=Fd.LENGTH,i=-1;var s,o,a;const l=null!==(s=null==t?void 0:t.lengthDecoder)&&void 0!==s?s:Bd,u=null!==(o=null==t?void 0:t.maxLengthLength)&&void 0!==o?o:8,c=null!==(a=null==t?void 0:t.maxDataLength)&&void 0!==a?a:Td;function*d(){for(;r.byteLength>0;){if(n===Fd.LENGTH)try{if(i=l(r),i<0)throw new Pd("Invalid message length");if(i>c)throw new Rd("Message length too long");const e=l.bytes;r.consume(e),null!=(null==t?void 0:t.onLength)&&t.onLength(i),n=Fd.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>u)throw new Ld("Message length length too long");break}throw e}if(n===Fd.DATA){if(r.byteLength<i)break;const e=r.sublist(0,i);r.consume(i),null!=(null==t?void 0:t.onData)&&t.onData(e),yield e,n=Fd.LENGTH}}}return Md(e)?async function*(){for await(const t of e)r.append(t),yield*d();if(r.byteLength>0)throw new Dd("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*d();if(r.byteLength>0)throw new Dd("Unexpected end of input")}()}Bd.bytes=0,$d.fromReader=(e,t)=>{let r=1;return $d(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),(0,M.default)((0,D.default)({},null!=t?t:{}),{onLength(e){r=e}}))};class qd extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","UnexpectedEOFError"),(0,L.default)(this,"code","ERR_UNEXPECTED_EOF")}}function zd(e,t){const r=ao();e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());const i=new qs;return{async read(e){var t;if(null==e||null===(t=e.signal)||void 0===t||t.throwIfAborted(),null==(null==e?void 0:e.bytes)){const{done:t,value:r}=await io(n.next(),null==e?void 0:e.signal);return!0===t?null:r}for(;i.byteLength<e.bytes;){const{value:t,done:r}=await io(n.next(),null==e?void 0:e.signal);if(!0===r)throw new qd("unexpected end of input");i.append(t)}const r=i.sublist(0,e.bytes);return i.consume(e.bytes),r},async write(e,t){var n;null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap(){if(i.byteLength>0){const r=e.source;e.source=async function*(){!1===(null==t?void 0:t.yieldBytes)?yield i:yield*i,yield*r}()}return e}}}class jd extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidMessageLengthError"),(0,L.default)(this,"code","ERR_INVALID_MSG_LENGTH")}}class Kd extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidDataLengthError"),(0,L.default)(this,"code","ERR_MSG_DATA_TOO_LONG")}}class Vd extends Error{constructor(...e){super(...e),(0,L.default)(this,"name","InvalidDataLengthLengthError"),(0,L.default)(this,"code","ERR_MSG_LENGTH_TOO_LONG")}}function Hd(e,t={}){const r=zd(e,t);var n,i;null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=ie(t.maxDataLength));const s=null!==(n=null==t?void 0:t.lengthDecoder)&&void 0!==n?n:le,o=null!==(i=null==t?void 0:t.lengthEncoder)&&void 0!==i?i:ae;return{async read(e){let n=-1;const i=new qs;for(;;){i.append(await r.read((0,M.default)((0,D.default)({},e),{bytes:1})));try{n=s(i)}catch(e){if(e instanceof RangeError)continue;throw e}if(n<0)throw new jd("Invalid message length");if(null!=(null==t?void 0:t.maxLengthLength)&&i.byteLength>t.maxLengthLength)throw new Vd("message length length too long");if(n>-1)break}if(null!=(null==t?void 0:t.maxDataLength)&&n>t.maxDataLength)throw new Kd("message length too long");return r.read((0,M.default)((0,D.default)({},e),{bytes:n}))},async write(e,t){await r.write(new qs(o(e.byteLength),e),t)},async writeV(e,t){const n=new qs(...e.flatMap((e=>[o(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function Wd(){const e=Qs();let t=!1;return{async sink(r){if(t)throw Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const Gd=65535,Xd=!!(null===(s=globalThis.process)||void 0===s||null===(o=s.env)||void 0===o?void 0:o.DUMP_SESSION_KEYS);function Zd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Yd(e){if("boolean"!=typeof e)throw Error("boolean expected, not "+e)}function Qd(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function Jd(e,...t){if(!Zd(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function eh(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function th(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function rh(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const nh=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function ih(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Zd(e))throw Error("Uint8Array expected, got "+typeof e);e=ah(e)}return e}function sh(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw Error("invalid output length, expected "+e+", got: "+t.length);if(r&&t.byteOffset%4!=0)throw Error("invalid output, must be aligned");return t}function oh(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s);e.setUint32(t+4,o,n),e.setUint32(t+0,a,n)}function ah(e){return Uint8Array.from(e)}const lh=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),uh=lh("expand 16-byte k"),ch=lh("expand 32-byte k"),dh=th(uh),hh=th(ch);function fh(e,t){return e<<t|e>>>32-t}function ph(e){return e.byteOffset%4==0}const gh=2**32-1,mh=new Uint32Array;const vh=(e,t)=>255&e[t++]|(255&e[t++])<<8;class yh{process(e,t,r=!1){const n=r?0:2048,{h:i,r:s}=this,o=s[0],a=s[1],l=s[2],u=s[3],c=s[4],d=s[5],h=s[6],f=s[7],p=s[8],g=s[9],m=vh(e,t+0),v=vh(e,t+2),y=vh(e,t+4),b=vh(e,t+6),w=vh(e,t+8),E=vh(e,t+10),S=vh(e,t+12),A=vh(e,t+14);let I=i[0]+(8191&m),_=i[1]+(8191&(m>>>13|v<<3)),C=i[2]+(8191&(v>>>10|y<<6)),k=i[3]+(8191&(y>>>7|b<<9)),x=i[4]+(8191&(b>>>4|w<<12)),T=i[5]+(w>>>1&8191),P=i[6]+(8191&(w>>>14|E<<2)),R=i[7]+(8191&(E>>>11|S<<5)),L=i[8]+(8191&(S>>>8|A<<8)),D=i[9]+(A>>>5|n),M=0,N=M+I*o+_*(5*g)+C*(5*p)+k*(5*f)+x*(5*h);M=N>>>13,N&=8191,N+=T*(5*d)+P*(5*c)+R*(5*u)+L*(5*l)+D*(5*a),M+=N>>>13,N&=8191;let O=M+I*a+_*o+C*(5*g)+k*(5*p)+x*(5*f);M=O>>>13,O&=8191,O+=T*(5*h)+P*(5*d)+R*(5*c)+L*(5*u)+D*(5*l),M+=O>>>13,O&=8191;let U=M+I*l+_*a+C*o+k*(5*g)+x*(5*p);M=U>>>13,U&=8191,U+=T*(5*f)+P*(5*h)+R*(5*d)+L*(5*c)+D*(5*u),M+=U>>>13,U&=8191;let F=M+I*u+_*l+C*a+k*o+x*(5*g);M=F>>>13,F&=8191,F+=T*(5*p)+P*(5*f)+R*(5*h)+L*(5*d)+D*(5*c),M+=F>>>13,F&=8191;let B=M+I*c+_*u+C*l+k*a+x*o;M=B>>>13,B&=8191,B+=T*(5*g)+P*(5*p)+R*(5*f)+L*(5*h)+D*(5*d),M+=B>>>13,B&=8191;let $=M+I*d+_*c+C*u+k*l+x*a;M=$>>>13,$&=8191,$+=T*o+P*(5*g)+R*(5*p)+L*(5*f)+D*(5*h),M+=$>>>13,$&=8191;let q=M+I*h+_*d+C*c+k*u+x*l;M=q>>>13,q&=8191,q+=T*a+P*o+R*(5*g)+L*(5*p)+D*(5*f),M+=q>>>13,q&=8191;let z=M+I*f+_*h+C*d+k*c+x*u;M=z>>>13,z&=8191,z+=T*l+P*a+R*o+L*(5*g)+D*(5*p),M+=z>>>13,z&=8191;let j=M+I*p+_*f+C*h+k*d+x*c;M=j>>>13,j&=8191,j+=T*u+P*l+R*a+L*o+D*(5*g),M+=j>>>13,j&=8191;let K=M+I*g+_*p+C*f+k*h+x*d;M=K>>>13,K&=8191,K+=T*c+P*u+R*l+L*a+D*o,M+=K>>>13,K&=8191,M=(M<<2)+M|0,M=M+N|0,N=8191&M,M>>>=13,O+=M,i[0]=N,i[1]=O,i[2]=U,i[3]=F,i[4]=B,i[5]=$,i[6]=q,i[7]=z,i[8]=j,i[9]=K}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let i=(1^n)-1;for(let e=0;e<10;e++)r[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let s=e[0]+t[0];e[0]=65535&s;for(let r=1;r<8;r++)s=(e[r]+t[r]|0)+(s>>>16)|0,e[r]=65535&s;rh(r)}update(e){eh(this),Jd(e=ih(e));const{buffer:t,blockLen:r}=this,n=e.length;for(let i=0;i<n;){const s=Math.min(r-this.pos,n-i);if(s!==r)t.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-i;i+=r)this.process(e,i)}return this}destroy(){rh(this.h,this.r,this.buffer,this.pad)}digestInto(e){eh(this),function(e,t){Jd(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,h:r}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=r[t]>>>0,e[i++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}constructor(e){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,Jd(e=ih(e),32);const t=vh(e,0),r=vh(e,2),n=vh(e,4),i=vh(e,6),s=vh(e,8),o=vh(e,10),a=vh(e,12),l=vh(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|i<<9),this.r[4]=255&(i>>>4|s<<12),this.r[5]=s>>>1&8190,this.r[6]=8191&(s>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|l<<8),this.r[9]=l>>>5&127;for(let t=0;t<8;t++)this.pad[t]=vh(e,16+2*t)}}const bh=function(e){const t=(t,r)=>e(r).update(ih(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new yh(e)));const wh=function(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw Error("core must be a function");return Qd(i),Qd(o),Yd(s),Yd(r),(t,a,l,u,c=0)=>{Jd(t),Jd(a),Jd(l);const d=l.length;if(void 0===u&&(u=new Uint8Array(d)),Jd(u),Qd(c),c<0||c>=gh)throw Error("arx: counter overflow");if(u.length<d)throw Error(`arx: output (${u.length}) is shorter than data (${d})`);const h=[];let f,p,g=t.length;if(32===g)h.push(f=ah(t)),p=hh;else{if(16!==g||!r)throw Error("arx: invalid 32-byte key, got length="+g);f=new Uint8Array(32),f.set(t),f.set(t,16),p=dh,h.push(f)}ph(a)||h.push(a=ah(a));const m=th(f);if(n){if(24!==a.length)throw Error("arx: extended nonce must be 24 bytes");n(p,m,th(a.subarray(0,16)),m),a=a.subarray(16)}const v=16-i;if(v!==a.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(12!==v){const e=new Uint8Array(12);e.set(a,s?0:12-a.length),a=e,h.push(a)}const y=th(a);return function(e,t,r,n,i,s,o,a){const l=i.length,u=new Uint8Array(64),c=th(u),d=ph(i)&&ph(s),h=d?th(i):mh,f=d?th(s):mh;for(let p=0;p<l;o++){if(e(t,r,n,c,o,a),o>=gh)throw Error("arx: counter overflow");const g=Math.min(64,l-p);if(d&&64===g){const e=p/4;if(p%4!=0)throw Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,f[t]=h[t]^c[r];p+=64}else{for(let e,t=0;t<g;t++)e=p+t,s[e]=i[e]^u[t];p+=g}}}(e,p,m,y,l,u,c,o),rh(...h),u}}((function(e,t,r,n,i,s=20){let o=e[0],a=e[1],l=e[2],u=e[3],c=t[0],d=t[1],h=t[2],f=t[3],p=t[4],g=t[5],m=t[6],v=t[7],y=i,b=r[0],w=r[1],E=r[2],S=o,A=a,I=l,_=u,C=c,k=d,x=h,T=f,P=p,R=g,L=m,D=v,M=y,N=b,O=w,U=E;for(let e=0;e<s;e+=2)S=S+C|0,M=fh(M^S,16),P=P+M|0,C=fh(C^P,12),S=S+C|0,M=fh(M^S,8),P=P+M|0,C=fh(C^P,7),A=A+k|0,N=fh(N^A,16),R=R+N|0,k=fh(k^R,12),A=A+k|0,N=fh(N^A,8),R=R+N|0,k=fh(k^R,7),I=I+x|0,O=fh(O^I,16),L=L+O|0,x=fh(x^L,12),I=I+x|0,O=fh(O^I,8),L=L+O|0,x=fh(x^L,7),_=_+T|0,U=fh(U^_,16),D=D+U|0,T=fh(T^D,12),_=_+T|0,U=fh(U^_,8),D=D+U|0,T=fh(T^D,7),S=S+k|0,U=fh(U^S,16),L=L+U|0,k=fh(k^L,12),S=S+k|0,U=fh(U^S,8),L=L+U|0,k=fh(k^L,7),A=A+x|0,M=fh(M^A,16),D=D+M|0,x=fh(x^D,12),A=A+x|0,M=fh(M^A,8),D=D+M|0,x=fh(x^D,7),I=I+T|0,N=fh(N^I,16),P=P+N|0,T=fh(T^P,12),I=I+T|0,N=fh(N^I,8),P=P+N|0,T=fh(T^P,7),_=_+C|0,O=fh(O^_,16),R=R+O|0,C=fh(C^R,12),_=_+C|0,O=fh(O^_,8),R=R+O|0,C=fh(C^R,7);let F=0;n[F++]=o+S|0,n[F++]=a+A|0,n[F++]=l+I|0,n[F++]=u+_|0,n[F++]=c+C|0,n[F++]=d+k|0,n[F++]=h+x|0,n[F++]=f+T|0,n[F++]=p+P|0,n[F++]=g+R|0,n[F++]=m+L|0,n[F++]=v+D|0,n[F++]=y+M|0,n[F++]=b+N|0,n[F++]=w+O|0,n[F++]=E+U|0}),{counterRight:!1,counterLength:4,allowShortKeys:!1}),Eh=new Uint8Array(16),Sh=(e,t)=>{e.update(t);const r=t.length%16;r&&e.update(Eh.subarray(r))},Ah=new Uint8Array(32);function Ih(e,t,r,n,i){const s=e(t,r,Ah),o=bh.create(s);i&&Sh(o,i),Sh(o,n);const a=function(e,t,r){Yd(r);const n=new Uint8Array(16),i=(s=n,new DataView(s.buffer,s.byteOffset,s.byteLength));var s;return oh(i,0,BigInt(t),r),oh(i,8,BigInt(e),r),n}(n.length,i?i.length:0,!0);o.update(a);const l=o.digest();return rh(s,a),l}const _h=((e,t)=>{function r(r,...n){if(Jd(r),!nh)throw Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw Error("nonce / iv required");e.varSizeNonce?Jd(t):Jd(t,e.nonceLength)}const i=e.tagLength;i&&void 0!==n[1]&&Jd(n[1]);const s=t(r,...n),o=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");Jd(t)}};let a=!1;return{encrypt(e,t){if(a)throw Error("cannot encrypt() twice with same key + nonce");return a=!0,Jd(e),o(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(Jd(e),i&&e.length<i)throw Error("invalid ciphertext length: smaller than tagLength="+i);return o(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:12,tagLength:16},(Ch=wh,(e,t,r)=>({encrypt(n,i){const s=n.length;(i=sh(s+16,i,!1)).set(n);const o=i.subarray(0,-16);Ch(e,t,o,o,1);const a=Ih(Ch,e,t,o,r);return i.set(a,s),rh(a),i},decrypt(n,i){i=sh(n.length-16,i,!1);const s=n.subarray(0,-16),o=n.subarray(-16),a=Ih(Ch,e,t,s,r);if(!((e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r})(o,a))throw Error("invalid tag");return i.set(n.subarray(0,-16)),Ch(e,t,i,i,1),rh(a),i}})));var Ch;const kh=Uint8Array.from([0]),xh=Uint8Array.of(),Th={hashSHA256:e=>ti(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return rn(e),void 0===r&&(r=new Uint8Array(e.outputLen)),lu(e,bn(r),bn(t))}(ti,t,e),n=function(e,t,r,n=32){rn(e),en(n);const i=e.outputLen;if(n>255*i)throw Error("Length should be <= 255*HashLen");const s=Math.ceil(n/i);void 0===r&&(r=xh);const o=new Uint8Array(s*i),a=lu.create(e,t),l=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let e=0;e<s;e++)kh[0]=e+1,l.update(0===e?xh:u).update(r).update(kh).digestInto(u),o.set(u,i*e),a._cloneInto(l);return a.destroy(),l.destroy(),sn(u,kh),o.slice(0,n)}(ti,r,void 0,96),i=n;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){const e=jl.utils.randomPrivateKey();return{publicKey:jl.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:jl.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>jl.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>_h(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,i)=>_h(n,t,r).decrypt(e.subarray(),i)},Ph=Th,Rh=e=>{const t=Y(2);return t[0]=e>>8,t[1]=e,t};Rh.bytes=2;const Lh=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function Dh(e,t){t.enabled&&Xd&&(e?(t("LOCAL_STATIC_PUBLIC_KEY "+ri(e.publicKey,"hex")),t("LOCAL_STATIC_PRIVATE_KEY "+ri(e.privateKey,"hex"))):t("Missing local static keys."))}function Mh(e,t){t.enabled&&Xd&&(e?(t("LOCAL_PUBLIC_EPHEMERAL_KEY "+ri(e.publicKey,"hex")),t("LOCAL_PRIVATE_EPHEMERAL_KEY "+ri(e.privateKey,"hex"))):t("Missing local ephemeral keys."))}function Nh(e,t){t.enabled&&Xd&&t(e?"REMOTE_EPHEMERAL_PUBLIC_KEY "+ri(e.subarray(),"hex"):"Missing remote ephemeral keys.")}function Oh(e,t,r){r.enabled&&Xd&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&ri(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&ri(t.k,"hex")}`))}Lh.bytes=2;class Uh extends Error{constructor(e="Invalid crypto exchange"){super(e),(0,L.default)(this,"code",void 0),this.code=Uh.code}}(0,L.default)(Uh,"code","ERR_INVALID_CRYPTO_EXCHANGE");class Fh{increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw Error("Cipherstate has reached maximum n, a new handshake must be performed")}constructor(e=0){(0,L.default)(this,"n",void 0),(0,L.default)(this,"bytes",void 0),(0,L.default)(this,"view",void 0),this.n=e,this.bytes=Z(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}}const Bh=Z(0);class $h{hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}constructor(e,t,r=0){(0,L.default)(this,"k",void 0),(0,L.default)(this,"n",void 0),(0,L.default)(this,"crypto",void 0),this.crypto=e,this.k=t,this.n=new Fh(r)}}class qh{mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new $h(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new qs(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,Bh);return[new $h(this.crypto,e),new $h(this.crypto,t)]}constructor(e,t){(0,L.default)(this,"cs",void 0),(0,L.default)(this,"ck",void 0),(0,L.default)(this,"h",void 0),(0,L.default)(this,"crypto",void 0),this.crypto=e;const r=Zt(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=Z(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new $h(e)}}class zh{writeE(){if(this.e)throw Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw Error("ephemeral keypair is not set");if(!this.re)throw 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 Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw Error("static keypair is not set");if(!this.re)throw 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 Error("static keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw Error("message is not long enough");const n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}constructor(e){(0,L.default)(this,"ss",void 0),(0,L.default)(this,"s",void 0),(0,L.default)(this,"e",void 0),(0,L.default)(this,"rs",void 0),(0,L.default)(this,"re",void 0),(0,L.default)(this,"initiator",void 0),(0,L.default)(this,"crypto",void 0);const{crypto:t,protocolName:r,prologue:n,initiator:i,s:s,e:o,rs:a,re:l}=e;this.crypto=t,this.ss=new qh(t,r),this.ss.mixHash(n),this.initiator=i,this.s=s,this.e=o,this.rs=a,this.re=l}}class jh extends zh{writeMessageA(e){return new qs(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new qs(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new qs(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Uh("handshake stage 0 validation fail: "+e.message)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new Uh("handshake stage 1 validation fail: "+e.message)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new Uh("handshake stage 2 validation fail: "+e.message)}}}var Kh,Vh;async function Hh(e,t,r){const n=await e.sign(Gh(t));return Vh.encode({identityKey:Lu(e.publicKey),identitySig:n,extensions:r})}async function Wh(e,t,r){try{const n=Vh.decode(e),i=Ru(n.identityKey);if(!1===(null==r?void 0:r.equals(i)))throw Error(`Payload identity key ${i} does not match expected remote identity key ${r}`);if(!t)throw Error("Remote static does not exist");const s=Gh(t);if(!await i.verify(s,n.identitySig))throw Error("Invalid payload signature");return n}catch(e){throw new xi(e.message)}}function Gh(e){const t=Zt("noise-libp2p-static-key:");return e instanceof Uint8Array?Ms([t,e],t.length+e.length):(e.prepend(t),e)}(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);if(null!=e.streamMuxers)for(const r of e.streamMuxers)t.uint32(18),t.string(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={webtransportCerthashes:[],streamMuxers:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:var s;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.webtransportCerthashes)&&n.webtransportCerthashes.length===r.limits.webtransportCerthashes)throw new Xr('Decode error - map field "webtransportCerthashes" had too many elements');n.webtransportCerthashes.push(e.bytes());break;case 2:var o;if(null!=(null===(o=r.limits)||void 0===o?void 0:o.streamMuxers)&&n.streamMuxers.length===r.limits.streamMuxers)throw new Xr('Decode error - map field "streamMuxers" had too many elements');n.streamMuxers.push(e.string());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Kh||(Kh={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),Kh.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={identityKey:Z(0),identitySig:Z(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.identityKey=e.bytes();break;case 2:n.identitySig=e.bytes();break;case 4:var s;n.extensions=Kh.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.extensions});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Vh||(Vh={}));let Xh=Symbol.toStringTag,Zh=rs;class Yh{async secureOutbound(e,t){var r,n;const i=Hd(e,{lengthEncoder:Rh,lengthDecoder:Lh,maxDataLength:Gd}),s=await this.performHandshakeInitiator(i,this.components.privateKey,null==t||null===(r=t.remotePeer)||void 0===r?void 0:r.publicKey,t),o=await this.createSecureConnection(i,s);e.source=o.source,e.sink=o.sink;const a=Ru(s.payload.identityKey);return{conn:e,remoteExtensions:s.payload.extensions,remotePeer:zu(a),streamMuxer:!0===(null==t?void 0:t.skipStreamMuxerNegotiation)?void 0:this.getStreamMuxer(null===(n=s.payload.extensions)||void 0===n?void 0:n.streamMuxers)}}getStreamMuxer(e){if(null==e||0===e.length)return;const t=this.components.upgrader.getStreamMuxers();if(null!=t)for(const r of e){const e=t.get(r);if(null!=e)return e}if(e.length)throw new Ti("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){var r,n;const i=Hd(e,{lengthEncoder:Rh,lengthDecoder:Lh,maxDataLength:Gd}),s=await this.performHandshakeResponder(i,this.components.privateKey,null==t||null===(r=t.remotePeer)||void 0===r?void 0:r.publicKey,t),o=await this.createSecureConnection(i,s);e.source=o.source,e.sink=o.sink;const a=Ru(s.payload.identityKey);return{conn:e,remoteExtensions:s.payload.extensions,remotePeer:zu(a),streamMuxer:!0===(null==t?void 0:t.skipStreamMuxerNegotiation)?void 0:this.getStreamMuxer(null===(n=s.payload.extensions)||void 0===n?void 0:n.streamMuxers)}}async performHandshakeInitiator(e,t,r,n){let i;const s=!0===(null==n?void 0:n.skipStreamMuxerNegotiation)?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{var o;i=await async function(e,t){const{log:r,connection:n,crypto:i,privateKey:s,prologue:o,s:a,remoteIdentityKey:l,extensions:u}=e,c=await Hh(s,a.publicKey,u),d=new jh({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});Dh(d.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(Bh),t),r.trace("Stage 0 - Initiator finished sending first message."),Mh(d.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const h=d.readMessageB(await n.read(t));var f,p;r.trace("Stage 1 - Initiator received the message."),Nh(d.re,r),f=d.rs,(p=r).enabled&&Xd&&p(f?"REMOTE_STATIC_PUBLIC_KEY "+ri(f.subarray(),"hex"):"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await Wh(h,d.rs,l);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(c),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[m,v]=d.ss.split();return Oh(m,v,r),{payload:g,encrypt:e=>m.encryptWithAd(Bh,e),decrypt:(e,t)=>v.decryptWithAd(Bh,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:(0,D.default)({streamMuxers:s,webtransportCerthashes:[]},this.extensions)},n),null===(o=this.metrics)||void 0===o||o.xxHandshakeSuccesses.increment()}catch(e){var a;throw null===(a=this.metrics)||void 0===a||a.xxHandshakeErrors.increment(),e}return i}async performHandshakeResponder(e,t,r,n){let i;const s=!0===(null==n?void 0:n.skipStreamMuxerNegotiation)?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{var o;i=await async function(e,t){const{log:r,connection:n,crypto:i,privateKey:s,prologue:o,s:a,remoteIdentityKey:l,extensions:u}=e,c=await Hh(s,a.publicKey,u),d=new jh({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});Dh(d.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),Nh(d.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(c),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Mh(d.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const h=d.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const f=await Wh(h,d.rs,l),[p,g]=d.ss.split();return Oh(p,g,r),{payload:f,encrypt:e=>g.encryptWithAd(Bh,e),decrypt:(e,t)=>p.decryptWithAd(Bh,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:(0,D.default)({streamMuxers:s,webtransportCerthashes:[]},this.extensions)},n),null===(o=this.metrics)||void 0===o||o.xxHandshakeSuccesses.increment()}catch(e){var a;throw null===(a=this.metrics)||void 0===a||a.xxHandshakeErrors.increment(),e}return i}async createSecureConnection(e,t){const[r,n]=function(){const e=Wd(),t=Wd();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),i=e.unwrap();return await uo(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=65519){let i,s=r+65519;s>n.length&&(s=n.length),i=n instanceof Uint8Array?e.encrypt(n.subarray(r,s)):e.encrypt(n.sublist(r,s)),null==t||t.encryptedPackets.increment(),yield new qs(Rh(i.byteLength),i)}}}(t,this.metrics),i,(e=>$d(e,{lengthDecoder:Lh})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=Gd){let i=r+Gd;if(i>n.length&&(i=n.length),i-16<r)throw Error("Invalid chunk");const s=n.sublist(r,i),o=n.subarray(r,i-16);try{const r=e.decrypt(s,o);null==t||t.decryptedPackets.increment(),yield r}catch(e){throw null==t||t.decryptErrors.increment(),e}}}}(t,this.metrics),r),n}constructor(e,t={}){(0,L.default)(this,"protocol","/noise"),(0,L.default)(this,"crypto",void 0),(0,L.default)(this,"prologue",void 0),(0,L.default)(this,"staticKey",void 0),(0,L.default)(this,"extensions",void 0),(0,L.default)(this,"metrics",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,Xh,"@chainsafe/libp2p-noise"),(0,L.default)(this,Zh,["@libp2p/connection-encryption","@chainsafe/libp2p-noise"]);const{staticNoiseKey:r,extensions:n,crypto:i,prologueBytes:s}=t,{metrics:o}=e;this.components=e;const a=null!=i?i:Ph;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(a),this.extensions=(0,D.default)({webtransportCerthashes:[]},n),this.metrics=o?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(o):void 0,this.staticKey=r?a.generateX25519KeyPairFromSeed(r):a.generateX25519KeyPair(),this.prologue=null!=s?s:Z(0)}}function Qh(e={}){return t=>new Yh(t,e)}const Jh=Rf("dns4"),ef=Rf("dns6"),tf=Rf("dnsaddr"),rf=Pf(Rf("dns"),tf,Jh,ef),nf=Pf(Rf("ip4"),Rf("ip6")),sf=Pf(Tf(nf,Rf("tcp")),Tf(rf,Rf("tcp"))),of=Tf(nf,Rf("udp")),af=Tf(of,Rf("utp")),lf=Tf(of,Rf("quic")),uf=Tf(of,Rf("quic-v1")),cf=Pf(Tf(sf,Rf("ws")),Tf(rf,Rf("ws"))),df=Pf(Tf(cf,Rf("p2p")),cf),hf=Pf(Tf(sf,Rf("wss")),Tf(rf,Rf("wss")),Tf(sf,Rf("tls"),Rf("ws")),Tf(rf,Rf("tls"),Rf("ws"))),ff=Pf(Tf(hf,Rf("p2p")),hf),pf=Pf(Tf(sf,Rf("http")),Tf(nf,Rf("http")),Tf(rf,Rf("http"))),gf=Pf(Tf(sf,Rf("https")),Tf(nf,Rf("https")),Tf(rf,Rf("https"))),mf=Tf(of,Rf("webrtc-direct"),Rf("certhash")),vf=Pf(Tf(mf,Rf("p2p")),mf),yf=Tf(uf,Rf("webtransport"),Rf("certhash"),Rf("certhash")),bf=Pf(Tf(yf,Rf("p2p")),yf),wf=Pf(Tf(df,Rf("p2p-webrtc-star"),Rf("p2p")),Tf(ff,Rf("p2p-webrtc-star"),Rf("p2p")),Tf(df,Rf("p2p-webrtc-star")),Tf(ff,Rf("p2p-webrtc-star")));Pf(Tf(df,Rf("p2p-websocket-star"),Rf("p2p")),Tf(ff,Rf("p2p-websocket-star"),Rf("p2p")),Tf(df,Rf("p2p-websocket-star")),Tf(ff,Rf("p2p-websocket-star")));const Ef=Pf(Tf(pf,Rf("p2p-webrtc-direct"),Rf("p2p")),Tf(gf,Rf("p2p-webrtc-direct"),Rf("p2p")),Tf(pf,Rf("p2p-webrtc-direct")),Tf(gf,Rf("p2p-webrtc-direct"))),Sf=Pf(cf,hf,pf,gf,wf,Ef,sf,af,lf,rf,vf,bf);Pf(Tf(Sf,Rf("p2p-stardust"),Rf("p2p")),Tf(Sf,Rf("p2p-stardust")));const Af=Pf(Tf(Sf,Rf("p2p")),wf,Ef,vf,bf,Rf("p2p")),If=Pf(Tf(Af,Rf("p2p-circuit"),Af),Tf(Af,Rf("p2p-circuit")),Tf(Rf("p2p-circuit"),Af),Tf(Sf,Rf("p2p-circuit")),Tf(Rf("p2p-circuit"),Sf),Rf("p2p-circuit")),_f=()=>Pf(Tf(If,_f),If),Cf=_f(),kf=Pf(Tf(Cf,Af,Cf),Tf(Af,Cf),Tf(Cf,Af),Cf,Af);function xf(e){return function(t){let r;try{r=Mc(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function Tf(...e){function t(t){if(t.length<e.length)return null;let r=t;return e.some((e=>(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:xf(t),partialMatch:t}}function Pf(...e){function t(t){let r=null;return e.some((e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)})),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:xf(t),partialMatch:t}}function Rf(e){const t=e;return{toString:()=>t,matches(e){let r;try{r=Mc(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:e=>0===e.length?null:e[0]===t?e.slice(1):null}}Pf(Tf(Cf,Rf("webrtc"),Rf("p2p")),Tf(Cf,Rf("webrtc")),Tf(Sf,Rf("webrtc"),Rf("p2p")),Tf(Sf,Rf("webrtc")),Rf("webrtc"));let Lf=wi,Df=Symbol.toStringTag,Mf=rs;class Nf extends es{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((e=>{this.log.error(e)}))}),this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const r of this.list){var e,t;if(await this.components.peerStore.merge(r.id,{tags:{[null!==(e=this._init.tagName)&&void 0!==e?e:"bootstrap"]:{value:null!==(t=this._init.tagValue)&&void 0!==t?t:50,ttl:this._init.tagTTL}},multiaddrs:r.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:r}),this.components.connectionManager.openConnection(r.id).catch((e=>{this.log.error("could not dial bootstrap peer %p",r.id,e)}))}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw Error("Bootstrap requires a list of peer addresses");var r;super(),(0,L.default)(this,"log",void 0),(0,L.default)(this,"timer",void 0),(0,L.default)(this,"list",void 0),(0,L.default)(this,"timeout",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,"_init",void 0),(0,L.default)(this,Lf,this),(0,L.default)(this,Df,"@libp2p/bootstrap"),(0,L.default)(this,Mf,["@libp2p/peer-discovery"]),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=null!==(r=t.timeout)&&void 0!==r?r:1e3,this.list=[];for(const e of t.list){if(!kf.matches(e)){this.log.error("Invalid multiaddr");continue}const t=Mc(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:qu(r),multiaddrs:[t]};this.list.push(n)}this._init=t}}var Of;(0,L.default)(Nf,"tag","bootstrap"),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={publicKey:Z(0),payloadType:Z(0),payload:Z(0),signature:Z(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Of||(Of={}));class Uf extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class Ff{marshal(){return null==this.marshaled&&(this.marshaled=Of.encode({publicKey:Lu(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Ns(this.marshal(),e.marshal())}async validate(e,t){const r=Bf(e,this.payloadType,this.payload);return this.publicKey.verify(r.subarray(),this.signature,t)}constructor(e){(0,L.default)(this,"publicKey",void 0),(0,L.default)(this,"payloadType",void 0),(0,L.default)(this,"payload",void 0),(0,L.default)(this,"signature",void 0),(0,L.default)(this,"marshaled",void 0);const{publicKey:t,payloadType:r,payload:n,signature:i}=e;this.publicKey=t,this.payloadType=r,this.payload=n,this.signature=i}}(0,L.default)(Ff,"createFromProtobuf",(e=>{const t=Of.decode(e),r=Ru(t.publicKey);return new Ff({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})})),(0,L.default)(Ff,"seal",(async(e,t,r)=>{if(null==t)throw Error("Missing private key");const n=e.domain,i=e.codec,s=e.marshal(),o=Bf(n,i,s),a=await t.sign(o.subarray(),r);return new Ff({publicKey:t.publicKey,payloadType:i,payload:s,signature:a})})),(0,L.default)(Ff,"openAndCertify",(async(e,t,r)=>{const n=Ff.createFromProtobuf(e);if(!await n.validate(t,r))throw new Uf("Envelope signature is not valid for the given domain");return n}));const Bf=(e,t,r)=>{const n=Zt(e),i=ae(n.byteLength),s=ae(t.length),o=ae(r.length);return new qs(i,n,s,t,o,r)},$f=Uint8Array.from([3,1]);var qf,zf;(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:Z(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=Gr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const i={peerId:Z(0),seq:0n,addresses:[]},s=null==r?t.len:t.pos+r;for(;t.pos<s;){const r=t.uint32();switch(r>>>3){case 1:i.peerId=t.bytes();break;case 2:i.seq=t.uint64();break;case 3:var o,a;if(null!=(null===(o=n.limits)||void 0===o?void 0:o.addresses)&&i.addresses.length===n.limits.addresses)throw new Xr('Decode error - map field "addresses" had too many elements');i.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:null===(a=n.limits)||void 0===a?void 0:a.addresses$}));break;default:t.skipType(7&r)}}return i}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(qf||(qf={}));class jf{marshal(){return null==this.marshaled&&(this.marshaled=qf.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof jf&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every(((e,r)=>t[r].equals(e))))}(this.multiaddrs,e.multiaddrs)}constructor(e){(0,L.default)(this,"peerId",void 0),(0,L.default)(this,"multiaddrs",void 0),(0,L.default)(this,"seqNumber",void 0),(0,L.default)(this,"domain",jf.DOMAIN),(0,L.default)(this,"codec",jf.CODEC),(0,L.default)(this,"marshaled",void 0);const{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=null!=r?r:[],this.seqNumber=null!=n?n:BigInt(Date.now())}}function Kf(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}function Vf(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}(0,L.default)(jf,"createFromProtobuf",(e=>{var t;const r=qf.decode(e),n=ju(Tt(r.peerId)),i=(null!==(t=r.addresses)&&void 0!==t?t:[]).map((e=>Mc(e.multiaddr))),s=r.seq;return new jf({peerId:n,multiaddrs:i,seqNumber:s})})),(0,L.default)(jf,"DOMAIN","libp2p-peer-record"),(0,L.default)(jf,"CODEC",$f);const Hf=null!==(zf=globalThis.CustomEvent)&&void 0!==zf?zf:Event;function Wf(e,t){const r=Hd(e,t),n={async read(e,t){const n=await r.read(t);return e.decode(n)},async write(e,t,n){await r.write(t.encode(e),n)},async writeV(e,t,n){await r.writeV(e.map((e=>t.encode(e))),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Gf;(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={listenAddrs:[],protocols:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:var s;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.listenAddrs)&&n.listenAddrs.length===r.limits.listenAddrs)throw new Xr('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:var o;if(null!=(null===(o=r.limits)||void 0===o?void 0:o.protocols)&&n.protocols.length===r.limits.protocols)throw new Xr('Decode error - map field "protocols" had too many elements');n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(Gf||(Gf={}));const Xf="ipfs",Zf=5e3,Yf=1,Qf=1,Jf=10,ep=8192,tp=!0,rp=!0;class np{isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:Zt(this.host.agentVersion),ProtocolVersion:Zt(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}constructor(e,t){var r,n,i,s,o,a,l,u,c;(0,L.default)(this,"host",void 0),(0,L.default)(this,"protocol",void 0),(0,L.default)(this,"started",void 0),(0,L.default)(this,"timeout",void 0),(0,L.default)(this,"peerId",void 0),(0,L.default)(this,"privateKey",void 0),(0,L.default)(this,"peerStore",void 0),(0,L.default)(this,"registrar",void 0),(0,L.default)(this,"addressManager",void 0),(0,L.default)(this,"maxInboundStreams",void 0),(0,L.default)(this,"maxOutboundStreams",void 0),(0,L.default)(this,"maxMessageSize",void 0),(0,L.default)(this,"maxObservedAddresses",void 0),(0,L.default)(this,"events",void 0),(0,L.default)(this,"runOnLimitedConnection",void 0),(0,L.default)(this,"log",void 0),this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=null!==(i=t.timeout)&&void 0!==i?i:Zf,this.maxInboundStreams=null!==(s=t.maxInboundStreams)&&void 0!==s?s:Yf,this.maxOutboundStreams=null!==(o=t.maxOutboundStreams)&&void 0!==o?o:Qf,this.maxMessageSize=null!==(a=t.maxMessageSize)&&void 0!==a?a:ep,this.maxObservedAddresses=null!==(l=t.maxObservedAddresses)&&void 0!==l?l:Jf,this.runOnLimitedConnection=null!==(u=t.runOnLimitedConnection)&&void 0!==u?u:rp,this.host={protocolVersion:(null!==(c=t.protocolPrefix)&&void 0!==c?c:Xf)+"/0.1.0",agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n?n:r.userAgent)}}}var ip,sp={},op=(ip||(ip=1,function(){var e,t,r,n,i,s,o,a;a=e=>[(-16777216&e)>>>24,(16711680&e)>>>16,(65280&e)>>>8,255&e].join("."),o=e=>{var r,n,i,s,o,a;for(r=[],i=s=0;s<=3&&0!==e.length;i=++s){if(i>0){if("."!==e[0])throw Error("Invalid IP");e=e.substring(1)}o=(a=t(e))[0],n=a[1],e=e.substring(n),r.push(o)}if(0!==e.length)throw Error("Invalid IP");switch(r.length){case 1:if(r[0]>4294967295)throw Error("Invalid IP");return r[0]>>>0;case 2:if(r[0]>255||r[1]>16777215)throw Error("Invalid IP");return(r[0]<<24|r[1])>>>0;case 3:if(r[0]>255||r[1]>255||r[2]>65535)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2])>>>0;case 4:if(r[0]>255||r[1]>255||r[2]>255||r[3]>255)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0;default:throw Error("Invalid IP")}},n=(r=e=>e.charCodeAt(0))("0"),s=r("a"),i=r("A"),t=e=>{var t,o,a,l,u;for(l=0,t=10,o="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,o="7")),u=a;a<e.length;){if("0"<=e[a]&&e[a]<=o)l=l*t+(r(e[a])-n)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")l=l*t+(10+r(e[a])-s)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;l=l*t+(10+r(e[a])-i)>>>0}}if(l>4294967295)throw Error("too large");a++}if(a===u)throw Error("empty octet");return[l,a]},e=function(){function e(e,t){var r,n,i;if("string"!=typeof e)throw Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=o(t)}catch(e){throw Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(o(e)&this.maskLong)>>>0}catch(t){throw Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(o(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(a(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=o(this.first),r=o(this.last),t=0;n<=r;)e(a(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),sp.ip2long=o,sp.long2ip=a,sp.Netmask=e}()),sp);const ap=["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"].map((e=>new op.Netmask(e)));function lp(e){for(const t of ap)if(t.contains(e))return!0;return!1}function up(e){return Ju(e)?lp(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return lp(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):function(e){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)}(e)?function(e){const t=e.split(":");return lp(t[t.length-1])}(e):ec(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^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(e)||/^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(e)||/^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(e)||/^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(e)||/^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(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}function cp(e){try{for(const{code:t}of e.getComponents())if(t!==rc)return 4===t||t===tc}catch(e){}return!1}function dp(e){try{if(!cp(e))return!1;const[[,r]]=e.stringTuples();var t;return null!=r&&null!==(t=up(r))&&void 0!==t&&t}catch(e){}return!0}const hp=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),fp=e=>({match:t=>hp((t=>t===e)).match(t),pattern:e}),pp=()=>({match:e=>hp((e=>"string"==typeof e)).match(e),pattern:"{string}"}),gp=()=>({match:e=>hp((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),mp=()=>({match(e){if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{ot.decode("z"+e[1])}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),vp=()=>({match(e){if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{dt.decode(e[1])}catch(e){return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),yp=e=>({match(t){const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),bp=(...e)=>({match(t){let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.length<r.length)&&(r=e)}return null!=r&&r},pattern:`or(${e.map((e=>e.pattern)).join(", ")})`}),wp=(...e)=>({match(t){for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function Ep(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:e=>!1!==t(e),exactMatch(e){const r=t(e);return!1!==r&&0===r.length}}}const Sp=Ep(mp()),Ap=wp(fp("dns4"),pp()),Ip=wp(fp("dns6"),pp()),_p=wp(fp("dnsaddr"),pp()),Cp=wp(fp("dns"),pp());Ep(Ap,yp(mp())),Ep(Ip,yp(mp())),Ep(_p,yp(mp())),Ep(bp(Cp,_p,Ap,Ip),yp(mp()));const kp=wp(fp("ip4"),hp(Ju)),xp=wp(fp("ip6"),hp(ec)),Tp=bp(kp,xp),Pp=bp(Tp,Cp,Ap,Ip,_p),Rp=Ep(bp(Tp,wp(bp(Cp,_p,Ap,Ip),yp(mp())))),Lp=Ep(kp),Dp=Ep(xp);Ep(Tp);const Mp=wp(Pp,fp("tcp"),gp()),Np=wp(Pp,fp("udp"),gp()),Op=Ep(wp(Mp,yp(mp())));Ep(Np);const Up=wp(Np,fp("quic"),yp(mp())),Fp=wp(Np,fp("quic-v1"),yp(mp())),Bp=bp(Up,Fp);Ep(Up);const $p=Ep(Fp),qp=bp(Pp,Mp,Np,Up,Fp),zp=bp(wp(qp,fp("ws"),yp(mp()))),jp=Ep(zp),Kp=bp(wp(qp,fp("wss"),yp(mp())),wp(qp,fp("tls"),yp(wp(fp("sni"),pp())),fp("ws"),yp(mp()))),Vp=Ep(Kp),Hp=wp(Np,fp("webrtc-direct"),yp(vp()),yp(vp()),yp(mp())),Wp=Ep(Hp),Gp=wp(Fp,fp("webtransport"),yp(vp()),yp(vp()),yp(mp())),Xp=Ep(Gp),Zp=bp(zp,Kp,wp(Mp,yp(mp())),wp(Bp,yp(mp())),wp(Pp,yp(mp())),Hp,Gp,mp());Ep(Zp);const Yp=Ep(wp(Zp,fp("p2p-circuit"),mp())),Qp=Ep(bp(wp(Zp,fp("p2p-circuit"),fp("webrtc"),yp(mp())),wp(Zp,fp("webrtc"),yp(mp())),wp(fp("webrtc"),yp(mp()))));Ep(bp(wp(Pp,fp("tcp"),gp(),fp("http"),yp(mp())),wp(Pp,fp("http"),yp(mp())))),Ep(bp(wp(Pp,fp("tcp"),bp(wp(fp("443"),fp("http")),wp(gp(),fp("https")),wp(gp(),fp("tls"),fp("http"))),yp(mp())),wp(Pp,fp("tls"),fp("http"),yp(mp())),wp(Pp,fp("https"),yp(mp())))),Ep(bp(wp(fp("memory"),pp(),yp(mp()))));let Jp=rs;class eg extends np{async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t=(0,M.default)((0,D.default)({},t),{signal:e})}try{r=await e.newStream(this.protocol,(0,M.default)((0,D.default)({},t),{runOnLimitedConnection:this.runOnLimitedConnection}));const n=Wf(r,{maxDataLength:this.maxMessageSize}).pb(Gf),i=await n.read(t);return await r.close(t),i}catch(e){throw null==r||r.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:i,observedAddr:s}=r;if(null==n)throw new Ki("public key was missing from identify message");const o=Ku(Ru(n).toCID());if(!e.remotePeer.equals(o))throw new Ki("identified peer does not match the expected peer");if(this.peerId.equals(o))throw new Ki("identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("identify completed for peer %p and protocols %o",o,i),async function(e,t,r,n,i){if(r("received identify from %p",n.remotePeer),null==i)throw new Ki("message was null or undefined");const s={};if(i.listenAddrs.length>0&&(s.addresses=i.listenAddrs.map((e=>({isCertified:!1,multiaddr:Mc(e)})))),i.protocols.length>0&&(s.protocols=i.protocols),null!=i.publicKey){const e=Ru(i.publicKey);if(!zu(e).equals(n.remotePeer))throw new Ki("public key did not match remote PeerId");s.publicKey=e}let o;if(null!=i.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);let t=i.signedPeerRecord;const a=await Ff.openAndCertify(t,jf.DOMAIN);let l=jf.createFromProtobuf(a.payload);const u=Ku(a.publicKey.toCID());if(!l.peerId.equals(u))throw new Ki("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(l.peerId))throw new Ki("signing key does not match remote PeerId");let c;try{c=await e.get(l.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=c&&(s.metadata=c.metadata,null!=c.peerRecordEnvelope)){const e=Ff.createFromProtobuf(c.peerRecordEnvelope),n=jf.createFromProtobuf(e.payload);n.seqNumber>=l.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,l.seqNumber),l=n,t=c.peerRecordEnvelope)}s.peerRecordEnvelope=t,s.addresses=l.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),o={seq:l.seqNumber,addresses:l.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,s),await e.patch(n.remotePeer,s),null!=i.agentVersion||null!=i.protocolVersion){const t={};null!=i.agentVersion&&(t.AgentVersion=Zt(i.agentVersion)),null!=i.protocolVersion&&(t.ProtocolVersion=Zt(i.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map((e=>Mc(e))),observedAddr:null==i.observedAddr?void 0:Mc(i.observedAddr),protocols:i.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return Mc(e)}catch(e){}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),dp(t))return void this.log.trace("our observed address was private");const r=t.getComponents();r[0].code!==tc&&(r[0].code!==rc||r[1].code!==tc)||function(e){try{for(const{code:r,value:n}of e.getComponents())if(null!=n&&r===tc)return t=n,new Tc("2000::/3").contains(t)}catch(e){}var t;return!1}(t)?Op.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address")}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=await this.peerStore.get(this.peerId),i=this.addressManager.getAddresses().map((e=>e.decapsulateCode(Nc("p2p").code)));let s=e.peerRecordEnvelope;if(i.length>0&&null==s){const e=new jf({peerId:this.peerId,multiaddrs:i});s=(await Ff.seal(e,this.privateKey)).marshal().subarray()}let o=t.remoteAddr.bytes;Rp.matches(t.remoteAddr)||(o=void 0);const a=Wf(r).pb(Gf);await a.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Lu(this.privateKey.publicKey),listenAddrs:i.map((e=>e.bytes)),signedPeerRecord:s,observedAddr:o,protocols:e.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}constructor(e,t={}){var r,n;super(e,(0,M.default)((0,D.default)({},t),{protocol:`/${null!==(r=t.protocolPrefix)&&void 0!==r?r:Xf}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")})),(0,L.default)(this,Jp,["@libp2p/identify"]),(null!==(n=t.runOnConnectionOpen)&&void 0!==n?n:tp)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{e.name!==ji.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}}function tg(e={}){return t=>new eg(t,e)}function rg(e,t){var r,n;const i=null===(n=(r=function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw Error("argument is not an iterator or iterable")}(e)).return)||void 0===n?void 0:n.call(r);var s;null!=(s=i)&&"function"==typeof s.then&&"function"==typeof s.catch&&"function"==typeof s.finally&&i.catch((e=>{t.error("could not cause iterator to return",e)}))}const ng=()=>{const e=Error("Delay aborted");return e.name="AbortError",e},ig=new WeakMap,sg=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:i}={})=>{if(null==i?void 0:i.aborted)return Promise.reject(ng());let s,o,a;const l=null!=e?e:clearTimeout,u=()=>{l(s),a(ng())},c=new Promise(((e,l)=>{o=()=>{i&&i.removeEventListener("abort",u),e(n)},a=l,s=(null!=t?t:setTimeout)(o,r)}));return i&&i.addEventListener("abort",u,{once:!0}),ig.set(c,(()=>{l(s),s=null,o()})),c}}();class og extends Error{constructor(e="Rate limit exceeded",t){super(e),(0,L.default)(this,"remainingPoints",void 0),(0,L.default)(this,"msBeforeNext",void 0),(0,L.default)(this,"consumedPoints",void 0),(0,L.default)(this,"isFirstInDuration",void 0),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}let ag=(H=class extends Error{constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},(0,L.default)(H,"name","QueueFullError"),H);class lg{async consume(e,t=1,r={}){const n=this.getKey(e),i=this._getKeySecDuration(r);let s=this.memoryStorage.incrby(n,t,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(n,s.consumedPoints,this.blockDuration)),new og("Rate limit exceeded",s);if(this.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){let e=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=s.consumedPoints*this.execEvenlyMinDelayMs),await sg(e)}return s}penalty(e,t=1,r={}){const n=this.getKey(e),i=this._getKeySecDuration(r),s=this.memoryStorage.incrby(n,t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,r={}){const n=this.getKey(e),i=this._getKeySecDuration(r),s=this.memoryStorage.incrby(n,-t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,t){const r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){const n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=(null==e?void 0:e.customDuration)&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}constructor(e={}){var t,r,n,i,s,o;(0,L.default)(this,"memoryStorage",void 0),(0,L.default)(this,"points",void 0),(0,L.default)(this,"duration",void 0),(0,L.default)(this,"blockDuration",void 0),(0,L.default)(this,"execEvenly",void 0),(0,L.default)(this,"execEvenlyMinDelayMs",void 0),(0,L.default)(this,"keyPrefix",void 0),this.points=null!==(t=e.points)&&void 0!==t?t:4,this.duration=null!==(r=e.duration)&&void 0!==r?r:1,this.blockDuration=null!==(n=e.blockDuration)&&void 0!==n?n:0,this.execEvenly=null!==(i=e.execEvenly)&&void 0!==i&&i,this.execEvenlyMinDelayMs=null!==(s=e.execEvenlyMinDelayMs)&&void 0!==s?s:1e3*this.duration/this.points,this.keyPrefix=null!==(o=e.keyPrefix)&&void 0!==o?o:"rlflx",this.memoryStorage=new ug}}class ug{incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const i=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||i>0?(n.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,i=this.storage.get(e);null!=i&&clearTimeout(i.timeoutId);const s={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,s),n>0&&(s.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=s.timeoutId.unref&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:s.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}constructor(){(0,L.default)(this,"storage",void 0),this.storage=new Map}}var cg;(e=>{e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"})(cg||(cg={}));const dg=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),hg=Object.freeze({NEW_STREAM:cg.NEW_STREAM,MESSAGE:cg.MESSAGE_INITIATOR,CLOSE:cg.CLOSE_INITIATOR,RESET:cg.RESET_INITIATOR}),fg=Object.freeze({MESSAGE:cg.MESSAGE_RECEIVER,CLOSE:cg.CLOSE_RECEIVER,RESET:cg.RESET_RECEIVER}),pg=1048576;class gg{write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new Ki("Unprocessed message queue size too large!");const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}const{id:r,type:n,length:i,offset:s}=this._headerInfo;if(this._buffer.length-s<i)break;const o={id:r,type:n};n!==cg.NEW_STREAM&&n!==cg.MESSAGE_INITIATOR&&n!==cg.MESSAGE_RECEIVER||(o.data=this._buffer.sublist(s,s+i)),t.push(o),this._buffer.consume(s+i),this._headerInfo=null}return t}_decodeHeader(e){const{value:t,offset:r}=yg(e),{value:n,offset:i}=yg(e,r),s=7&t;if(null==dg[s])throw Error("Invalid type received: "+s);if(n>this._maxMessageSize)throw new Ki("Message size too large");return{id:t>>3,type:s,offset:r+i,length:n}}constructor(e=pg,t=4194304){(0,L.default)(this,"_buffer",void 0),(0,L.default)(this,"_headerInfo",void 0),(0,L.default)(this,"_maxMessageSize",void 0),(0,L.default)(this,"_maxUnprocessedMessageQueueSize",void 0),this._buffer=new qs,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}}const mg=128,vg=127;function yg(e,t=0){let r,n=0,i=0,s=t;const o=e.length;do{if(s>=o||i>49)throw t=0,new RangeError("Could not decode varint");r=e.get(s++),n+=i<28?(r&vg)<<i:(r&vg)*Math.pow(2,i),i+=7}while(r>=mg);return{value:n,offset:t=s-t}}const bg=10240,wg=new class{write(e,t){const r=this._pool;let n=this._poolOffset;ae(e.id<<3|e.type,r,n),n+=ie(e.id<<3|e.type),e.type!==cg.NEW_STREAM&&e.type!==cg.MESSAGE_INITIATOR&&e.type!==cg.MESSAGE_RECEIVER||null==e.data?(ae(0,r,n),n+=ie(0)):(ae(e.data.length,r,n),n+=ie(e.data.length));const i=r.subarray(this._poolOffset,n);bg-n<100?(this._pool=Y(bg),this._poolOffset=0):this._poolOffset=n,t.append(i),e.type!==cg.NEW_STREAM&&e.type!==cg.MESSAGE_INITIATOR&&e.type!==cg.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}constructor(){(0,L.default)(this,"_pool",void 0),(0,L.default)(this,"_poolOffset",void 0),this._pool=Y(bg),this._poolOffset=0}};class Eg extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}}function Sg(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class Ag{async sink(e){if("ready"!==this.writeStatus)throw new Ui(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);Sg(e)&&await e}const r=()=>{rg(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new qs(r):r;const e=this.sendData(r,t);Sg(e)&&(this.sendingData=Qs(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(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(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){var t;null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),null===(t=this.onCloseRead)||void 0===t||t.call(this),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){var t;null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),null===(t=this.onCloseWrite)||void 0===t||t.call(this),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){"open"===this.status&&(this.log.trace("closing gracefully"),this.status="closing",await io(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),null==e?void 0:e.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(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(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await io(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await io(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await io(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){var t;if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");const r=this.sendReset();Sg(r)&&r.catch((e=>{this.log.error("error sending reset message",e)})),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),null===(t=this.onAbort)||void 0===t||t.call(this,e)}reset(){var e;if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;const t=new Oi("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),null===(e=this.onReset)||void 0===e||e.call(this)}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}constructor(e){var t,r;(0,L.default)(this,"id",void 0),(0,L.default)(this,"direction",void 0),(0,L.default)(this,"timeline",void 0),(0,L.default)(this,"protocol",void 0),(0,L.default)(this,"metadata",void 0),(0,L.default)(this,"source",void 0),(0,L.default)(this,"status",void 0),(0,L.default)(this,"readStatus",void 0),(0,L.default)(this,"writeStatus",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,"sinkController",void 0),(0,L.default)(this,"sinkEnd",void 0),(0,L.default)(this,"closed",void 0),(0,L.default)(this,"endErr",void 0),(0,L.default)(this,"streamSource",void 0),(0,L.default)(this,"onEnd",void 0),(0,L.default)(this,"onCloseRead",void 0),(0,L.default)(this,"onCloseWrite",void 0),(0,L.default)(this,"onReset",void 0),(0,L.default)(this,"onAbort",void 0),(0,L.default)(this,"sendCloseWriteTimeout",void 0),(0,L.default)(this,"sendingData",void 0),this.sinkController=new AbortController,this.sinkEnd=Qs(),this.closed=Qs(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=null!==(t=e.metadata)&&void 0!==t?t:{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=null!==(r=e.sendCloseWriteTimeout)&&void 0!==r?r:5e3,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=ro({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}}class Ig extends Ag{async sendNewStream(){await this.send({id:this.streamId,type:hg.NEW_STREAM,data:new qs(Zt(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}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(){}constructor(e){super(e),(0,L.default)(this,"name",void 0),(0,L.default)(this,"streamId",void 0),(0,L.default)(this,"send",void 0),(0,L.default)(this,"types",void 0),(0,L.default)(this,"maxDataSize",void 0),this.types="outbound"===e.direction?hg:fg,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}}function _g(e){const t=(0,M.default)((0,D.default)({},e),{type:`${dg[e.type]} (${e.type})`});return e.type===cg.NEW_STREAM&&(t.data=ri(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==cg.MESSAGE_INITIATOR&&e.type!==cg.MESSAGE_RECEIVER||(t.data=ri(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class Cg{get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Ni("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;var t;const r=null!==(t=null==e?void 0:e.signal)&&void 0!==t?t:AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map((async e=>e.close({signal:r})))),this._source.end(),await this._source.onEmpty({signal:r}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:i}=e;var s;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(null!==(s=this._init.maxOutboundStreams)&&void 0!==s?s:1024))throw new Yi("Too many outbound streams open");if(i.has(t))throw Error(`${n} stream ${t} already exists!`);const o=function(e){const{id:t,name:r,send:n,onEnd:i,type:s="initiator",maxMsgSize:o=pg}=e;return new Ig({id:"initiator"===s?"i"+t:"r"+t,streamId:t,name:""+(null!=r?r:t),direction:"initiator"===s?"outbound":"inbound",maxDataSize:o,onEnd:i,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${s}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,_g(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,o.protocol),i.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(o)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return i.set(t,o),o}_createSink(){return async e=>{const t=()=>{rg(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new gg(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",_g(e)),e.type===cg.NEW_STREAM){var n;if(this._streams.receivers.size===(null!==(n=this._init.maxInboundStreams)&&void 0!==n?n:1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:cg.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch(e){return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:ri(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const i=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==i){this.log("missing stream %s for message type %s",t,dg[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch(e){return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(Error("Too many messages for missing streams"))}return}var s;const o=null!==(s=this._init.maxStreamBufferSize)&&void 0!==s?s:4194304;try{switch(r){case cg.MESSAGE_INITIATOR:case cg.MESSAGE_RECEIVER:if(i.sourceReadableLength()>o)throw this._source.push({id:e.id,type:r===cg.MESSAGE_INITIATOR?cg.RESET_RECEIVER:cg.RESET_INITIATOR}),new Eg("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");i.sourcePush(e.data);break;case cg.CLOSE_INITIATOR:case cg.CLOSE_RECEIVER:i.remoteCloseWrite();break;case cg.RESET_INITIATOR:case cg.RESET_RECEIVER:i.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),i.abort(e)}}constructor(e,t){var r,n;(0,L.default)(this,"protocol","/mplex/6.7.0"),(0,L.default)(this,"sink",void 0),(0,L.default)(this,"source",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,"_streamId",void 0),(0,L.default)(this,"_streams",void 0),(0,L.default)(this,"_init",void 0),(0,L.default)(this,"_source",void 0),(0,L.default)(this,"closeController",void 0),(0,L.default)(this,"rateLimiter",void 0),(0,L.default)(this,"closeTimeout",void 0),(0,L.default)(this,"logger",void 0),t=null!=t?t:{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=null!==(r=t.closeTimeout)&&void 0!==r?r:500,this.sink=this._createSink(),this._source=ro({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=uo(this._source,(e=>async function*(e){for await(const t of e){const e=new qs;wg.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new lg({points:null!==(n=t.disconnectThreshold)&&void 0!==n?n:5,duration:1})}}let kg=Symbol.toStringTag,xg=rs;class Tg{createStreamMuxer(e={}){return new Cg(this.components,(0,D.default)({},e,this._init))}constructor(e,t={}){(0,L.default)(this,"protocol","/mplex/6.7.0"),(0,L.default)(this,"_init",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,kg,"@libp2p/mplex"),(0,L.default)(this,xg,["@libp2p/stream-multiplexing"]),this.components=e,this._init=t}}function Pg(e={}){return t=>new Tg(t,e)}let Rg=Symbol.toStringTag,Lg=rs;class Dg{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(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:t}=e,r=Date.now(),n=zd(t);let i=!1;Promise.resolve().then((async()=>{for(;;){const e=AbortSignal.timeout(this.timeout);e.addEventListener("abort",(()=>{null==t||t.abort(new Hi("ping timeout"))}));const r=await n.read({bytes:32,signal:e});await n.write(r,{signal:e}),i=!0}})).catch((r=>{i&&"UnexpectedEOFError"===r.name&&"ready"!==t.readStatus||(this.log.error("incoming ping from %p failed with error - %e",e.connection.remotePeer,r),null==t||t.abort(r))})).finally((()=>{const n=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,n);const i=AbortSignal.timeout(this.timeout);t.close({signal:i}).catch((r=>{this.log.error("error closing ping stream from %p - %e",e.connection.remotePeer,r),null==t||t.abort(r)}))}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=iu(32),i=await this.components.connectionManager.openConnection(e,t);let s;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t=(0,M.default)((0,D.default)({},t),{signal:e})}try{s=await i.newStream(this.protocol,(0,M.default)((0,D.default)({},t),{runOnLimitedConnection:this.runOnLimitedConnection}));const e=zd(s),[,o]=await Promise.all([e.write(n,t),e.read((0,M.default)((0,D.default)({},t),{bytes:32}))]),a=Date.now()-r;if(!Ns(n,o.subarray()))throw new Vi(`Received wrong ping ack after ${a}ms`);return this.log("ping %p complete in %dms",i.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",i.remotePeer,e),null==s||s.abort(e),e}finally{null!=s&&await s.close(t)}}constructor(e,t={}){var r,n,i,s,o;(0,L.default)(this,"protocol",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,"started",void 0),(0,L.default)(this,"timeout",void 0),(0,L.default)(this,"maxInboundStreams",void 0),(0,L.default)(this,"maxOutboundStreams",void 0),(0,L.default)(this,"runOnLimitedConnection",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,Rg,"@libp2p/ping"),(0,L.default)(this,Lg,["@libp2p/ping"]),this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${null!==(r=t.protocolPrefix)&&void 0!==r?r:"ipfs"}/ping/1.0.0`,this.timeout=null!==(n=t.timeout)&&void 0!==n?n:1e4,this.maxInboundStreams=null!==(i=t.maxInboundStreams)&&void 0!==i?i:2,this.maxOutboundStreams=null!==(s=t.maxOutboundStreams)&&void 0!==s?s:1,this.runOnLimitedConnection=null===(o=t.runOnLimitedConnection)||void 0===o||o,this.handleMessage=this.handleMessage.bind(this)}}function Mg(e={}){return t=>new Dg(t,e)}const Ng=[6,53,56,54,55];function Og(e){var t;return null===(t=Fg("sni",e))||void 0===t?void 0:t.value}function Ug(e){var t;const r=null===(t=Fg("tcp",e))||void 0===t?void 0:t.value;return null==r?"":":"+r}function Fg(e,t){return t.find((t=>t.name===e))}function Bg(e){return e.some((({code:e})=>448===e))}function $g(e,t){const r=qg[e.name];if(null==r)throw Error("Can't interpret protocol "+e.name);const n=r(e,t);return e.code===tc?`[${n}]`:n}const qg={ip4:e=>e.value,ip6:(e,t)=>0===t.length?e.value:`[${e.value}]`,tcp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`tcp://${$g(r,t)}:${e.value}`},udp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`udp://${$g(r,t)}:${e.value}`},dnsaddr:e=>e.value,dns4:e=>e.value,dns6:e=>e.value,dns:e=>e.value,ipfs(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+$g(r,t)},p2p(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+$g(r,t)},http(e,t){const r=Bg(t),n=Og(t),i=Ug(t);if(r&&null!=n)return`https://${n}${i}`;const s=r?"https://":"http://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=$g(o,t);return a=null==a?void 0:a.replace("tcp://",""),`${s}${a}`},"http-path"(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");var n;return`${$g(r,t)}${decodeURIComponent(null!==(n=e.value)&&void 0!==n?n:"")}`},tls(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return $g(r,t)},sni(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return $g(r,t)},https(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=$g(r,t);return n=null==n?void 0:n.replace("tcp://",""),"https://"+n},ws(e,t){const r=Bg(t),n=Og(t),i=Ug(t);if(r&&null!=n)return`wss://${n}${i}`;const s=r?"wss://":"ws://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=$g(o,t);return a=null==a?void 0:a.replace("tcp://",""),`${s}${a}`},wss(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=$g(r,t);return n=null==n?void 0:n.replace("tcp://",""),"wss://"+n}};var zg,jg,Kg=async e=>{if(e.readyState>=2)throw Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",i),e.removeEventListener("error",s)}function i(){n(),t()}function s(t){var i;n(),r(null!==(i=t.error)&&void 0!==i?i:Error("connect ECONNREFUSED "+e.url))}e.addEventListener("open",i),e.addEventListener("error",s)}))},Vg=(e,t)=>((t=null!=t?t:{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await Kg(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise(((t,r)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))}),Hg={},Wg={},Gg=function(){if(jg)return Hg;jg=1,Object.defineProperty(Hg,"__esModule",{value:!0});const e=function(){if(zg)return Wg;zg=1,Object.defineProperty(Wg,"__esModule",{value:!0});class e{push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&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 e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:()=>{const e=this.pushQueue.shift();return e?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),e):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}}class t{constructor(t,{highWaterMark:r=100,lowWaterMark:n=1}={}){const i=new e;i.highWaterMark=r,i.lowWaterMark=n,i.removeCallback=t({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on(e,t){i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}return Wg.EventIterator=t,Wg.default=t,Wg}();return Hg.EventIterator=e.EventIterator,Hg.subscribe=function(t,r,n){return new e.EventIterator((({push:e})=>(this.addEventListener(t,e,r),()=>this.removeEventListener(t,e,r))),n)},Hg.default=e.EventIterator,Hg}();function Xg(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null==e||null===(t=e.constructor)||void 0===t?void 0:t.name)&&"number"==typeof(null==e?void 0:e.byteLength)}var Zg=WebSocket;const Yg={"http:":"ws:","https:":"wss:"};function Qg(e,t){t=null!=t?t:{};const r=((e,t)=>{var r;if(e.startsWith("//")&&(e=`${null!==(r=null==t?void 0:t.protocol)&&void 0!==r?r:"ws:"}${e}`),e.startsWith("/")&&null!=t){var n;const r=null!==(n=t.protocol)&&void 0!==n?n:"ws:",i=t.host,s=null!=t.port&&!0!==(null==i?void 0:i.endsWith(":"+t.port))?":"+t.port:"";e=`${r}//${i}${s}${e}`}const i=new URL(e);for(const[e,t]of Object.entries(Yg))i.protocol===e&&(i.protocol=t);return i})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=null!=t?t:{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(i)return void t();if(null!=n)return void r(n);const s=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{s(t)},a=t=>{s((()=>{var n;r(null!==(n=t.error)&&void 0!==n?n:Error("connect ECONNREFUSED "+e.url))}))};e.addEventListener("open",o),e.addEventListener("error",a)}))},r=async function*(){const r=new Gg.EventIterator((({push:t,stop:r,fail:n})=>{const i=e=>{let r=null;"string"==typeof e.data&&(r=Zt(e.data)),Xg(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},s=e=>{var t;n(null!==(t=e.error)&&void 0!==t?t:Error("Socket error"))};return e.addEventListener("message",i),e.addEventListener("error",s),e.addEventListener("close",r),()=>{e.removeEventListener("message",i),e.removeEventListener("error",s),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield Xg(e)?new Uint8Array(e):e}();let n,i=1===e.readyState;return e.addEventListener("open",(()=>{i=!0,n=null})),e.addEventListener("close",(()=>{i=!1,n=null})),e.addEventListener("error",(t=>{var r;i||(n=null!==(r=t.error)&&void 0!==r?r:Error("connect ECONNREFUSED "+e.url))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,i=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,i=parseInt(t.port,10)}catch(e){}if(null==n||null==i)throw Error("Remote connection did not have address and/or port");return{sink:Vg(e,t),source:r,async connected(){await r.connected()},async close(){e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||await new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()}))},destroy(){null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:i,socket:e}})(new Zg(r.toString(),t.websocket),t)}class Jg extends Event{constructor(e,t){super(e),(0,L.default)(this,"type",void 0),(0,L.default)(this,"detail",void 0),this.type=e,this.detail=t}}function em(e){return e.filter((e=>Vp.exactMatch(e)||jp.exactMatch(e)))}function tm(e){return e.filter((e=>Vp.exactMatch(e)))}let rm=_i,nm=Symbol.toStringTag,im=rs;class sm{async dial(e,t){var r;this.log("dialing %s",e),t=null!=t?t:{};const n=function(e,t,r){var n;const i=r.logger.forComponent("libp2p:websockets:maconn"),s=r.metrics,o=null!==(n=r.metricPrefix)&&void 0!==n?n:"",a={log:i,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&i.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){var r;const n=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t=(0,M.default)((0,D.default)({},t),{signal:e})}const s=()=>{const{host:e,port:t}=a.remoteAddr.toOptions();i("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-n),this.abort(new ki("Socket close timeout"))};null===(r=t.signal)||void 0===r||r.addEventListener("abort",s);try{await e.close()}catch(e){i.error("error closing WebSocket gracefully",e),this.abort(e)}finally{var o;null===(o=t.signal)||void 0===o||o.removeEventListener("abort",s),a.timeline.close=Date.now()}},abort(t){const{host:r,port:n}=a.remoteAddr.toOptions();i("timeout closing stream to %s:%s due to error",r,n,t),e.destroy(),a.timeline.close=Date.now(),null==s||s.increment({[o+"error"]:!0})}};return e.socket.addEventListener("close",(()=>{null==s||s.increment({[o+"close"]:!0}),null==a.timeline.close&&(a.timeline.close=Date.now())}),{once:!0}),a}(await this._connect(e,t),e,{logger:this.logger,metrics:null===(r=this.metrics)||void 0===r?void 0:r.dialerEvents});this.log("new outbound connection %s",n.remoteAddr);const i=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),i}async _connect(e,t){var r,n;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();const i=e.toOptions();this.log("dialing %s:%s",i.host,i.port);const s=Qs(),o=Qg(function(e){const t=Mc(e).getComponents(),r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");const n=qg[r.name];if(null==n)throw Error("No interpreter found for "+r.name);var i;let s=null!==(i=n(r,t))&&void 0!==i?i:"";return Ng.includes(r.code)&&(s=s.replace(/^.*:\/\//,""),s="443"===r.value?"https://"+s:"http://"+s),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}(e),this.init);o.socket.addEventListener("error",(()=>{var t;const r=new Mi("Could not connect to "+e.toString());this.log.error("connection error:",r),null===(t=this.metrics)||void 0===t||t.dialerEvents.increment({error:!0}),s.reject(r)}));try{var a;null===(a=t.onProgress)||void 0===a||a.call(t,new Jg("websockets:open-connection")),await io(Promise.race([o.connected(),s.promise]),t.signal)}catch(e){var l,u;throw(null===(l=t.signal)||void 0===l?void 0:l.aborted)&&(null===(u=this.metrics)||void 0===u||u.dialerEvents.increment({abort:!0})),o.close().catch((e=>{this.log.error("error closing raw socket",e)})),e}return this.log("connected %s",e),null===(n=this.metrics)||void 0===n||n.dialerEvents.increment({connect:!0}),o}createListener(e){return function(){throw Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),this.init)}listenFilter(e){var t,r;return e=Array.isArray(e)?e:[e],null!=(null===(t=this.init)||void 0===t?void 0:t.filter)?null===(r=this.init)||void 0===r?void 0:r.filter(e):em(e)}dialFilter(e){return this.listenFilter(e)}constructor(e,t={}){(0,L.default)(this,"log",void 0),(0,L.default)(this,"init",void 0),(0,L.default)(this,"logger",void 0),(0,L.default)(this,"metrics",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,rm,!0),(0,L.default)(this,nm,"@libp2p/websockets"),(0,L.default)(this,im,["@libp2p/transport"]),this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}}function om(e={}){return t=>new sm(t,e)}function am(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}const{hasOwnProperty:lm}=Object.prototype,{propertyIsEnumerable:um}=Object,cm=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},dm={concatArrays:!1,ignoreUndefined:!1},hm=e=>{const t=[];for(const r in e)lm.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)um.call(e,n)&&t.push(n)}return t};function fm(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return hm(e).forEach((r=>{cm(t,r,fm(e[r]))})),t}(e):am(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return hm(e).forEach((r=>{cm(t,r,fm(e[r]))})),t}(e):e}const pm=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?cm(e,r,mm(e[r],t[r],n)):cm(e,r,fm(t[r])))})),e),gm=(e,t,r)=>{let n=e.slice(0,0),i=0;return[e,t].forEach((t=>{const s=[];for(let r=0;r<t.length;r++)lm.call(t,r)&&(s.push(r+""),cm(n,i++,t===e?t[r]:fm(t[r])));n=pm(n,t,hm(t).filter((e=>!s.includes(e))),r)})),n};function mm(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?gm(e,t,r):am(t)&&am(e)?pm(e,t,hm(t),r):fm(t)}function vm(...e){const t=mm(fm(dm),void 0!==this&&this||{},dm);let r={_:{}};for(const n of e)if(void 0!==n){if(!am(n))throw new TypeError("`"+n+"` is not an Option Object");r=mm(r,{_:n},t)}return r._}var ym,bm={exports:{}},wm=(ym||(ym=1,function(e){var t={}.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new i(n,s||e,o),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],a]:e._events[l].push(a):(e._events[l]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=Array(s);i<s;i++)o[i]=n[i].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,i,s,o){var a=r?r+e:e;if(!this._events[a])return!1;var l,u,c=this._events[a],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,s),!0;case 6:return c.fn.call(c.context,t,n,i,s,o),!0}for(u=1,l=Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,f=c.length;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!l)for(h=1,l=Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,i){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||i&&!a.once||n&&a.context!==n||o(this,s);else{for(var l=0,u=[],c=a.length;l<c;l++)(a[l].fn!==t||i&&!a[l].once||n&&a[l].context!==n)&&u.push(a[l]);u.length?this._events[s]=1===u.length?u[0]:u:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(bm)),bm.exports),Em=ss(wm);class Sm extends Error{constructor(e){super(e),this.name="TimeoutError"}}let Am=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};const Im=e=>void 0===globalThis.DOMException?new Am(e):new DOMException(e),_m=e=>{const t=void 0===e.reason?Im("This operation was aborted."):e.reason;return t instanceof Error?t:Im(t)};let Cm=(W=new WeakMap,class{enqueue(e,t){const r={priority:(t=(0,D.default)({priority:0},t)).priority,id:t.id,run:e};if(0===this.size||(0,C.default)(this,W)[this.size-1].priority>=t.priority)return void(0,C.default)(this,W).push(r);const n=function(e,t,r){let n=0,i=e.length;for(;i>0;){const s=Math.trunc(i/2);let o=n+s;r(e[o],t)<=0?(n=++o,i-=s+1):i=s}return n}((0,C.default)(this,W),r,((e,t)=>t.priority-e.priority));(0,C.default)(this,W).splice(n,0,r)}setPriority(e,t){const r=(0,C.default)(this,W).findIndex((t=>t.id===e));if(-1===r)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[n]=(0,C.default)(this,W).splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){const e=(0,C.default)(this,W).shift();return null==e?void 0:e.run}filter(e){return(0,C.default)(this,W).filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return(0,C.default)(this,W).length}constructor(){(0,k.default)(this,W,{writable:!0,value:[]})}});var km,xm,Tm=new WeakMap,Pm=new WeakMap,Rm=new WeakMap,Lm=new WeakMap,Dm=new WeakMap,Mm=new WeakMap,Nm=new WeakMap,Om=new WeakMap,Um=new WeakMap,Fm=new WeakMap,Bm=new WeakMap,$m=new WeakMap,qm=new WeakMap,zm=new WeakMap,jm=new WeakMap,Km=new WeakMap,Vm=new WeakMap,Hm=new WeakSet,Wm=new WeakSet,Gm=new WeakMap,Xm=new WeakSet,Zm=new WeakSet,Ym=new WeakSet,Qm=new WeakSet,Jm=new WeakSet,ev=new WeakSet;class tv extends Em{get concurrency(){return(0,C.default)(this,$m)}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);(0,x.default)(this,$m,e),(0,P.default)(this,Qm,cv).call(this)}setPriority(e,t){(0,C.default)(this,Um).setPriority(e,t)}async add(e,t={}){var r;return null!==(r=(a=t).id)&&void 0!==r||(a.id=""+(0,T.default)(this,jm).value++),t=(0,D.default)({timeout:this.timeout,throwOnTimeout:(0,C.default)(this,zm)},t),new Promise(((r,n)=>{(0,C.default)(this,Um).enqueue((async()=>{(0,T.default)(this,Bm).value++,(0,T.default)(this,Rm).value++;try{var i;null===(i=t.signal)||void 0===i||i.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=function(e,t){const{milliseconds:r,fallback:n,message:i,customTimers:s={setTimeout:setTimeout,clearTimeout:clearTimeout}}=t;let o,a;const l=new Promise(((l,u)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&u(_m(e)),a=()=>{u(_m(e))},e.addEventListener("abort",a,{once:!0})}if(r===1/0)return void e.then(l,u);const c=new Sm;o=s.setTimeout.call(void 0,(()=>{if(n)try{l(n())}catch(e){u(e)}else"function"==typeof e.cancel&&e.cancel(),!1===i?l():i instanceof Error?u(i):(c.message=null!=i?i:`Promise timed out after ${r} milliseconds`,u(c))}),r),(async()=>{try{l(await e)}catch(e){u(e)}})()})).finally((()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)}));return l.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},l}(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,(0,P.default)(this,Jm,dv).call(this,t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof Sm&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{(0,P.default)(this,Hm,iv).call(this)}}),t),this.emit("add"),(0,P.default)(this,Xm,av).call(this)}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return(0,C.default)(this,qm)?((0,x.default)(this,qm,!1),(0,P.default)(this,Qm,cv).call(this),this):this}pause(){(0,x.default)(this,qm,!0)}clear(){(0,x.default)(this,Um,new((0,C.default)(this,Fm)))}async onEmpty(){0!==(0,C.default)(this,Um).size&&await(0,P.default)(this,ev,hv).call(this,"empty")}async onSizeLessThan(e){(0,C.default)(this,Um).size<e||await(0,P.default)(this,ev,hv).call(this,"next",(()=>(0,C.default)(this,Um).size<e))}async onIdle(){0===(0,C.default)(this,Bm)&&0===(0,C.default)(this,Um).size||await(0,P.default)(this,ev,hv).call(this,"idle")}get size(){return(0,C.default)(this,Um).size}sizeBy(e){return(0,C.default)(this,Um).filter(e).length}get pending(){return(0,C.default)(this,Bm)}get isPaused(){return(0,C.default)(this,qm)}constructor(e){var t,r,n,i;if(super(),(0,k.default)(this,Km,{get:rv,set:void 0}),(0,k.default)(this,Vm,{get:nv,set:void 0}),(0,R.default)(this,Hm),(0,R.default)(this,Wm),(0,k.default)(this,Gm,{get:ov,set:void 0}),(0,R.default)(this,Xm),(0,R.default)(this,Zm),(0,R.default)(this,Ym),(0,R.default)(this,Qm),(0,R.default)(this,Jm),(0,R.default)(this,ev),(0,k.default)(this,Tm,{writable:!0,value:void 0}),(0,k.default)(this,Pm,{writable:!0,value:void 0}),(0,k.default)(this,Rm,{writable:!0,value:0}),(0,k.default)(this,Lm,{writable:!0,value:void 0}),(0,k.default)(this,Dm,{writable:!0,value:void 0}),(0,k.default)(this,Mm,{writable:!0,value:0}),(0,k.default)(this,Nm,{writable:!0,value:void 0}),(0,k.default)(this,Om,{writable:!0,value:void 0}),(0,k.default)(this,Um,{writable:!0,value:void 0}),(0,k.default)(this,Fm,{writable:!0,value:void 0}),(0,k.default)(this,Bm,{writable:!0,value:0}),(0,k.default)(this,$m,{writable:!0,value:void 0}),(0,k.default)(this,qm,{writable:!0,value:void 0}),(0,k.default)(this,zm,{writable:!0,value:void 0}),(0,k.default)(this,jm,{writable:!0,value:1n}),(0,L.default)(this,"timeout",void 0),!("number"==typeof(e=(0,D.default)({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Cm},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(n=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==n?n:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(i=null===(r=e.interval)||void 0===r?void 0:r.toString())&&void 0!==i?i:""}\` (${typeof e.interval})`);(0,x.default)(this,Tm,e.carryoverConcurrencyCount),(0,x.default)(this,Pm,e.intervalCap===1/0||0===e.interval),(0,x.default)(this,Lm,e.intervalCap),(0,x.default)(this,Dm,e.interval),(0,x.default)(this,Um,new e.queueClass),(0,x.default)(this,Fm,e.queueClass),this.concurrency=e.concurrency,this.timeout=e.timeout,(0,x.default)(this,zm,!0===e.throwOnTimeout),(0,x.default)(this,qm,!1===e.autoStart)}}function rv(){return(0,C.default)(this,Pm)||(0,C.default)(this,Rm)<(0,C.default)(this,Lm)}function nv(){return(0,C.default)(this,Bm)<(0,C.default)(this,$m)}function iv(){(0,T.default)(this,Bm).value--,(0,P.default)(this,Xm,av).call(this),this.emit("next")}function sv(){(0,P.default)(this,Ym,uv).call(this),(0,P.default)(this,Zm,lv).call(this),(0,x.default)(this,Om,void 0)}function ov(){const e=Date.now();if(void 0===(0,C.default)(this,Nm)){const t=(0,C.default)(this,Mm)-e;if(!(t<0))return void 0===(0,C.default)(this,Om)&&(0,x.default)(this,Om,setTimeout((()=>{(0,P.default)(this,Wm,sv).call(this)}),t)),!0;(0,x.default)(this,Rm,(0,C.default)(this,Tm)?(0,C.default)(this,Bm):0)}return!1}function av(){if(0===(0,C.default)(this,Um).size)return(0,C.default)(this,Nm)&&clearInterval((0,C.default)(this,Nm)),(0,x.default)(this,Nm,void 0),this.emit("empty"),0===(0,C.default)(this,Bm)&&this.emit("idle"),!1;if(!(0,C.default)(this,qm)){const e=!(0,C.default)(this,Gm);if((0,C.default)(this,Km)&&(0,C.default)(this,Vm)){const t=(0,C.default)(this,Um).dequeue();return!!t&&(this.emit("active"),t(),e&&(0,P.default)(this,Zm,lv).call(this),!0)}}return!1}function lv(){(0,C.default)(this,Pm)||void 0!==(0,C.default)(this,Nm)||((0,x.default)(this,Nm,setInterval((()=>{(0,P.default)(this,Ym,uv).call(this)}),(0,C.default)(this,Dm))),(0,x.default)(this,Mm,Date.now()+(0,C.default)(this,Dm)))}function uv(){0===(0,C.default)(this,Rm)&&0===(0,C.default)(this,Bm)&&(0,C.default)(this,Nm)&&(clearInterval((0,C.default)(this,Nm)),(0,x.default)(this,Nm,void 0)),(0,x.default)(this,Rm,(0,C.default)(this,Tm)?(0,C.default)(this,Bm):0),(0,P.default)(this,Qm,cv).call(this)}function cv(){for(;(0,P.default)(this,Xm,av).call(this););}async function dv(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}async function hv(e,t){return new Promise((r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}function fv(e){const t=[mv.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function pv(e){var t,r,n,i,s,o,a,l,u,c,d,h,f,p,g,m,v;return{Status:null!==(t=e.Status)&&void 0!==t?t:0,TC:null!==(n=null!==(r=e.TC)&&void 0!==r?r:e.flag_tc)&&void 0!==n&&n,RD:null!==(s=null!==(i=e.RD)&&void 0!==i?i:e.flag_rd)&&void 0!==s&&s,RA:null!==(a=null!==(o=e.RA)&&void 0!==o?o:e.flag_ra)&&void 0!==a&&a,AD:null!==(u=null!==(l=e.AD)&&void 0!==l?l:e.flag_ad)&&void 0!==u&&u,CD:null!==(d=null!==(c=e.CD)&&void 0!==c?c:e.flag_cd)&&void 0!==d&&d,Question:(null!==(f=null!==(h=e.Question)&&void 0!==h?h:e.questions)&&void 0!==f?f:[]).map((e=>({name:e.name,type:mv[e.type]}))),Answer:(null!==(g=null!==(p=e.Answer)&&void 0!==p?p:e.answers)&&void 0!==g?g:[]).map((e=>({name:e.name,type:mv[e.type],TTL:null!==(v=null!==(m=e.TTL)&&void 0!==m?m:e.ttl)&&void 0!==v?v:60,data:e.data instanceof Uint8Array?ri(e.data):e.data})))}}function gv(e,t={}){var r;const n=new tv({concurrency:null!==(r=t.queryConcurrency)&&void 0!==r?r:4});return async(t,r={})=>{var i;const s=new URLSearchParams;s.set("name",t),fv(r.types).forEach((e=>{s.append("type",mv[e])})),null===(i=r.onProgress)||void 0===i||i.call(r,new Jg("dns:query",{detail:t}));const o=await n.add((async()=>{var t;const n=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:null==r?void 0:r.signal});if(200!==n.status)throw Error(`Unexpected HTTP status: ${n.status} - ${n.statusText}`);const i=pv(await n.json());return null===(t=r.onProgress)||void 0===t||t.call(r,new Jg("dns:response",{detail:i})),i}),{signal:r.signal});if(null==o)throw Error("No DNS response received");return o}}var mv,vv=(xm||(xm=1,km=e=>{if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function i(i,s){r[i]=s,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:e=>void 0!==r[e]||void 0!==n[e],remove(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(i(e,t),t):void 0},set(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear(){r=Object.create(null),n=Object.create(null)}}}),km),yv=ss(vv);class bv{get(e,t){let r=!0;const n=[];for(const i of t){const t=this.getAnswers(e,i);if(0===t.length){r=!1;break}n.push(...t)}if(r)return pv({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>(0,M.default)((0,D.default)({},t),{TTL:Math.round((e-Date.now())/1e3),type:mv[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){var r;const n=`${e.toLowerCase()}-${t.type}`,i=null!==(r=this.lru.get(n))&&void 0!==r?r:[];var s;i.push({expires:Date.now()+1e3*(null!==(s=t.TTL)&&void 0!==s?s:60),value:t}),this.lru.set(n,i)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}constructor(e){(0,L.default)(this,"lru",void 0),this.lru=yv(e)}}class wv{async query(e,t={}){var r;const n=fv(t.types),i=!1!==t.cached?this.cache.get(e,n):void 0;if(null!=i)return null===(r=t.onProgress)||void 0===r||r.call(t,new Jg("dns:cache",{detail:i})),i;var s;const o=e.split(".").pop()+".",a=(null!==(s=this.resolvers[o])&&void 0!==s?s:this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),l=[];for(const r of a){var u;if(!0===(null===(u=t.signal)||void 0===u?void 0:u.aborted))break;try{const i=await r(e,(0,M.default)((0,D.default)({},t),{types:n}));for(const t of i.Answer)this.cache.add(e,t);return i}catch(e){var c;l.push(e),null===(c=t.onProgress)||void 0===c||c.call(t,new Jg("dns:error",{detail:e}))}}if(1===l.length)throw l[0];throw new AggregateError(l,`DNS lookup of ${e} ${n} failed`)}constructor(e){var t,r,n;(0,L.default)(this,"resolvers",void 0),(0,L.default)(this,"cache",void 0),this.resolvers={},this.cache=(t=null!==(r=e.cacheSize)&&void 0!==r?r:1e3,new bv(t)),Object.entries(null!==(n=e.resolvers)&&void 0!==n?n:{}).forEach((([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e+="."),this.resolvers[e]=t})),null==this.resolvers["."]&&(this.resolvers["."]=[gv("https://cloudflare-dns.com/dns-query"),gv("https://dns.google/resolve")])}}(e=>{e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"})(mv||(mv={}));const Ev=-1,Sv={},Av={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Ev,"ip6zone"],[43,8,"ipcidr"],[53,Ev,"dns",!0],[54,Ev,"dns4",!0],[55,Ev,"dns6",!0],[56,Ev,"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,Ev,"unix",!1,!0],[421,Ev,"ipfs"],[421,Ev,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Ev,"garlic64"],[448,0,"tls"],[449,Ev,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Ev,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Ev,"http-path"],[777,Ev,"memory"]].forEach((e=>{const t=function(e,t,r,n,i){return{code:e,size:t,name:r,resolvable:!!n,path:!!i}}(...e);Av[t.code]=t,Sv[t.name]=t}));const{code:Iv}=function(e){if(null!=Sv[e])return Sv[e];throw Error("no protocol with name: "+e)}("dnsaddr");class _v extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const Cv=async function(e,t={}){var r;const n=null!==(r=t.maxRecursiveDepth)&&void 0!==r?r:32;if(0===n)throw new _v("Max recursive depth reached");var i,s;const[,o]=null!==(i=e.stringTuples().find((([e])=>e===Iv)))&&void 0!==i?i:[],a=null!==(s=null==t?void 0:t.dns)&&void 0!==s?s:function(e={}){return new wv(e)}(),l=await a.query("_dnsaddr."+o,{signal:null==t?void 0:t.signal,types:[mv.TXT]}),u=e.getPeerId(),c=[];for(const e of l.Answer){const r=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==r)continue;if(null!=u&&!r.includes(u))continue;const i=Mc(r);if(r.startsWith("/dnsaddr")){const e=await i.resolve((0,M.default)((0,D.default)({},t),{maxRecursiveDepth:n-1}));c.push(...e.map((e=>e.toString())))}else c.push(i.toString())}return c},kv={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:Cv}},transportManager:{faultTolerance:Ci.FATAL_ALL}};const xv=1e3,Tv=6e4,Pv=36e5,Rv=864e5;function Lv(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e+="").length>100)throw Error("Value exceeds the maximum length of 100 characters.");const t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return r*Rv;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Pv;case"minutes":case"minute":case"mins":case"min":case"m":return r*Tv;case"seconds":case"second":case"secs":case"sec":case"s":return r*xv;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return(null==t?void 0:t.long)?function(e){const t=Math.abs(e);return t>=Rv?Dv(e,t,Rv,"day"):t>=Pv?Dv(e,t,Pv,"hour"):t>=Tv?Dv(e,t,Tv,"minute"):t>=xv?Dv(e,t,xv,"second"):e+" ms"}(e):function(e){const t=Math.abs(e);return t>=Rv?Math.round(e/Rv)+"d":t>=Pv?Math.round(e/Pv)+"h":t>=Tv?Math.round(e/Tv)+"m":t>=xv?Math.round(e/xv)+"s":e+"ms"}(e);throw Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw Error(r)}}function Dv(e,t,r,n){const i=t>=1.5*r;return`${Math.round(e/r)} ${n}${i?"s":""}`}const Mv=function(){try{return localStorage}catch(e){}}();var Nv,Ov;const Uv=null!==(Ov=null!==(Nv=console.debug)&&void 0!==Nv?Nv:console.log)&&void 0!==Ov?Ov:()=>{};var Fv,Bv,$v=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){var t;return e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(RegExp("^"+e.substr(1)+"$")):t.names.push(RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Lv,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Lv(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)},save(e){try{e?null==Mv||Mv.setItem("debug",e):null==Mv||Mv.removeItem("debug")}catch(e){}},load(){let e;try{e=null==Mv?void 0:Mv.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors(){var e,t,r,n,i;return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==(null===(e=navigator.userAgent)||void 0===e?void 0:e.toLowerCase().match(/(edge|trident)\/(\d+)/)))&&("undefined"!=typeof document&&(null===(t=document.documentElement)||void 0===t||null===(r=t.style)||void 0===r?void 0:r.WebkitAppearance)||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=(null===(n=navigator.userAgent)||void 0===n?void 0:n.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&(null===(i=navigator.userAgent)||void 0===i?void 0:i.toLowerCase().match(/applewebkit\/(\d+)/)))},setupFormatters(e){e.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},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"],storage:Mv,log:Uv});function qv(){return{forComponent:e=>zv(e)}}function zv(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(e+":trace");return $v.enabled(e+":trace")&&null!=$v.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=$v(e+":trace")),Object.assign($v(e),{error:$v(e+":error"),trace:t,newScope:t=>zv(`${e}:${t}`)})}function jv(e){if(null!=e&&0!==(e=e.trim()).length)return e}function Kv(e,t){const r={[Symbol.iterator]:()=>r,next(){const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}function Vv(e){return ju(Tt(ot.decode("z"+e)))}$v.formatters.b=e=>null==e?"undefined":ot.baseEncode(e),$v.formatters.t=e=>null==e?"undefined":We.baseEncode(e),$v.formatters.m=e=>null==e?"undefined":ut.baseEncode(e),$v.formatters.p=e=>null==e?"undefined":e.toString(),$v.formatters.c=e=>null==e?"undefined":e.toString(),$v.formatters.k=e=>null==e?"undefined":e.toString(),$v.formatters.a=e=>null==e?"undefined":e.toString(),$v.formatters.e=e=>null==e?"undefined":null!==(Bv=null!==(Fv=jv(e.stack))&&void 0!==Fv?Fv:jv(e.message))&&void 0!==Bv?Bv:e.toString();let Hv=Symbol.iterator;class Wv{[Hv](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Kv(this.map.entries(),(e=>[e[1].key,e[1].value]))}forEach(e){this.map.forEach((t=>{e(t.value,t.key,this)}))}get(e){var t;return null===(t=this.map.get(e.toString()))||void 0===t?void 0:t.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Kv(this.map.values(),(e=>e.key))}values(){return Kv(this.map.values(),(e=>e.value))}get size(){return this.map.size}constructor(e){if((0,L.default)(this,"map",void 0),this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),{key:t,value:r})}}let Gv=Symbol.iterator;class Xv{get size(){return this.set.size}[Gv](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Kv(this.set.entries(),(e=>{const t=Vv(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=Vv(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return Kv(this.set.values(),(e=>Vv(e)))}intersection(e){const t=new Xv;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new Xv;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new Xv;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}constructor(e){if((0,L.default)(this,"set",void 0),this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}}const Zv={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Yv={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Qv=new globalThis.TextEncoder;const Jv={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!Zv[t])throw Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw Error("The `utf8Buffer` option must have a length greater than zero");const n=Zv[t];let i=Yv[t],s=e;for(;s.length>0;){const e=Qv.encodeInto(s,r);s=s.slice(e.read);for(let s=0;s<e.written;s++)i^=BigInt(r[s]),i=BigInt.asUintN(t,i*n)}return i}(e,t,r);e=Qv.encode(e)}return function(e,t){const r=Zv[t];let n=Yv[t];for(let i=0;i<e.length;i++)n^=BigInt(e[i]),n=BigInt.asUintN(t,n*r);return n}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t="0"+t),Zt(t,"base16")}(Jv.hash(e,t))};class ey{hash(){return this.h.hash(this.fp,this.seed)}equals(e){return(null==e?void 0:e.fp)instanceof Uint8Array&&Ns(this.fp,e.fp)}constructor(e,t,r,n=2){if((0,L.default)(this,"fp",void 0),(0,L.default)(this,"h",void 0),(0,L.default)(this,"seed",void 0),n>64)throw new TypeError("Invalid Fingerprint Size");const i=t.hashV(e,r),s=Z(n);for(let e=0;e<s.length;e++)s[e]=i[e];0===s.length&&(s[0]=7),this.fp=s,this.h=t,this.seed=r}}function ty(e,t){return Math.floor(Math.random()*(t-e))+e}class ry{has(e){if(!(e instanceof ey))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof ey))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof ey))throw new TypeError("Invalid Fingerprint");const t=ty(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof ey))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}constructor(e){(0,L.default)(this,"contents",void 0),this.contents=Array(e).fill(null)}}class ny{add(e){"string"==typeof e&&(e=Zt(e));const t=new ey(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new ry(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new ry(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const i=[r,n];let s=i[ty(0,i.length-1)];null==this.buckets[s]&&(this.buckets[s]=new ry(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[s].swap(t);if(null!=e&&(s=(s^e.hash())%this.filterSize,null==this.buckets[s]&&(this.buckets[s]=new ry(this.bucketSize)),this.buckets[s].add(e)))return this.count++,!0}return!1}has(e){var t,r,n;"string"==typeof e&&(e=Zt(e));const i=new ey(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,o=null!==(n=null===(t=this.buckets[s])||void 0===t?void 0:t.has(i))&&void 0!==n&&n;if(o)return o;const a=(s^i.hash())%this.filterSize;var l;return null!==(l=null===(r=this.buckets[a])||void 0===r?void 0:r.has(i))&&void 0!==l&&l}remove(e){var t,r,n;"string"==typeof e&&(e=Zt(e));const i=new ey(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,o=null!==(n=null===(t=this.buckets[s])||void 0===t?void 0:t.remove(i))&&void 0!==n&&n;if(o)return this.count--,o;var a;const l=(s^i.hash())%this.filterSize,u=null!==(a=null===(r=this.buckets[l])||void 0===r?void 0:r.remove(i))&&void 0!==a&&a;return u&&this.count--,u}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}constructor(e){var t,r,n,i;(0,L.default)(this,"bucketSize",void 0),(0,L.default)(this,"filterSize",void 0),(0,L.default)(this,"fingerprintSize",void 0),(0,L.default)(this,"buckets",void 0),(0,L.default)(this,"count",void 0),(0,L.default)(this,"hash",void 0),(0,L.default)(this,"seed",void 0),this.filterSize=e.filterSize,this.bucketSize=null!==(t=e.bucketSize)&&void 0!==t?t:4,this.fingerprintSize=null!==(r=e.fingerprintSize)&&void 0!==r?r:2,this.count=0,this.buckets=[],this.hash=null!==(n=e.hash)&&void 0!==n?n:Jv,this.seed=null!==(i=e.seed)&&void 0!==i?i:ty(0,1024)}}const iy={1:.5,2:.84,4:.95,8:.98};class sy{add(e){if("string"==typeof e&&(e=Zt(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new ny({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=Zt(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=Zt(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce(((e,t)=>e+t.count),0)}constructor(e){var t,r,n,i,s,o;(0,L.default)(this,"filterSize",void 0),(0,L.default)(this,"bucketSize",void 0),(0,L.default)(this,"fingerprintSize",void 0),(0,L.default)(this,"scale",void 0),(0,L.default)(this,"filterSeries",void 0),(0,L.default)(this,"hash",void 0),(0,L.default)(this,"seed",void 0),this.bucketSize=null!==(t=e.bucketSize)&&void 0!==t?t:4,this.filterSize=null!==(r=e.filterSize)&&void 0!==r?r:262144/this.bucketSize,this.fingerprintSize=null!==(n=e.fingerprintSize)&&void 0!==n?n:2,this.scale=null!==(i=e.scale)&&void 0!==i?i:2,this.hash=null!==(s=e.hash)&&void 0!==s?s:Jv,this.seed=null!==(o=e.seed)&&void 0!==o?o:ty(0,1024),this.filterSeries=[new ny({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}}function oy(e,t=.001){return new sy((0,D.default)({},function(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/iy[r]),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}(e,t)))}class ay extends Wv{set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}constructor(e){super(),(0,L.default)(this,"metric",void 0);const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}}let ly=(G=class extends Error{constructor(e="The operation was aborted",...t){super(e,...t),(0,L.default)(this,"name","AbortError")}},(0,L.default)(G,"name","AbortError"),G);async function uy(e,t,r,n){const i=new ly(null==n?void 0:n.errorMessage);var s;null!=(null==n?void 0:n.errorCode)&&(i.code=n.errorCode);const o=null!==(s=null==n?void 0:n.errorEvent)&&void 0!==s?s:"error";return!0===(null==r?void 0:r.aborted)?Promise.reject(i):new Promise(((s,a)=>{function l(){dy(r,"abort",d),dy(e,t,u),dy(e,o,c)}const u=e=>{try{var t;if(!1===(null==n||null===(t=n.filter)||void 0===t?void 0:t.call(n,e)))return}catch(e){return l(),void a(e)}l(),s(e)},c=e=>{var t,r;l(),a(e instanceof Error?e:null!==(r=null!==(t=e.detail)&&void 0!==t?t:null==n?void 0:n.error)&&void 0!==r?r:Error(`The "${null==n?void 0:n.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{l(),a(i)};cy(r,"abort",d),cy(e,t,u),cy(e,o,c)}))}function cy(e,t,r){null!=e&&(hy(e)?e.addEventListener(t,r):e.addListener(t,r))}function dy(e,t,r){null!=e&&(hy(e)?e.removeEventListener(t,r):e.removeListener(t,r))}function hy(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class fy extends Error{constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}(0,L.default)(fy,"name","QueueFullError");let py=class{onAbort(){var e,t;this.deferred.reject(null!==(t=null===(e=this.signal)||void 0===e?void 0:e.reason)&&void 0!==t?t:new ly)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}constructor(e){var t;(0,L.default)(this,"deferred",void 0),(0,L.default)(this,"signal",void 0),this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),null===(t=this.signal)||void 0===t||t.addEventListener("abort",this.onAbort)}},gy=class{abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>{var r;return e&&!0===(null===(r=t.signal)||void 0===r?void 0:r.aborted)}),!0)&&(this.controller.abort(new ly),this.cleanup())}async join(e={}){var t;const r=new py(e.signal);return this.recipients.push(r),null===(t=e.signal)||void 0===t||t.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{var e;this.controller.signal.throwIfAborted();const t=await io(this.fn((0,M.default)((0,D.default)({},null!==(e=this.options)&&void 0!==e?e:{}),{signal:this.controller.signal})),this.controller.signal);this.recipients.forEach((e=>{e.deferred.resolve(t)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}constructor(e,t){(0,L.default)(this,"id",void 0),(0,L.default)(this,"fn",void 0),(0,L.default)(this,"options",void 0),(0,L.default)(this,"recipients",void 0),(0,L.default)(this,"status",void 0),(0,L.default)(this,"timeline",void 0),(0,L.default)(this,"controller",void 0),this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}};function my(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}let vy=(F=Symbol.asyncIterator,class extends es{[F](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){var r;if(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.size===this.maxSize)throw new fy;const n=new gy(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then((e=>(this.safeDispatchEvent("success",{detail:{job:n,result:e}}),e))).catch((e=>{if("queued"===n.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===n){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:n,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new ly)})),this.clear()}async onEmpty(e){0!==this.size&&await uy(this,"empty",null==e?void 0:e.signal)}async onSizeLessThan(e,t){this.size<e||await uy(this,"next",null==t?void 0:t.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await uy(this,"idle",null==e?void 0:e.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){var t,r;null==e||null===(t=e.signal)||void 0===t||t.throwIfAborted();const n=ro({objectMode:!0}),i=e=>{null!=e?this.abort():this.clear(),n.end(e)},s=e=>{null!=e.detail&&n.push(e.detail.result)},o=e=>{i(e.detail.error)},a=()=>{i()},l=()=>{i(new ly("Queue aborted"))};this.addEventListener("success",s),this.addEventListener("failure",o),this.addEventListener("idle",a),null==e||null===(r=e.signal)||void 0===r||r.addEventListener("abort",l);try{yield*n}finally{var u;this.removeEventListener("success",s),this.removeEventListener("failure",o),this.removeEventListener("idle",a),null==e||null===(u=e.signal)||void 0===u||u.removeEventListener("abort",l),i()}}constructor(e={}){var t,r,n;super(),(0,L.default)(this,"concurrency",void 0),(0,L.default)(this,"maxSize",void 0),(0,L.default)(this,"queue",void 0),(0,L.default)(this,"pending",void 0),(0,L.default)(this,"sort",void 0),(0,L.default)(this,"autoStart",void 0),this.concurrency=null!==(t=e.concurrency)&&void 0!==t?t:1/0,this.maxSize=null!==(r=e.maxSize)&&void 0!==r?r:1/0,this.pending=0,this.autoStart=null===(n=e.autoStart)||void 0===n||n,this.sort=e.sort,this.queue=[],this.emitEmpty=my(this.emitEmpty.bind(this),1),this.emitIdle=my(this.emitIdle.bind(this),1)}});const yy="lock:worker:request-read",by="lock:worker:abort-read-request",wy="lock:worker:release-read",Ey="lock:master:grant-read",Sy="lock:master:error-read",Ay="lock:worker:request-write",Iy="lock:worker:abort-write-request",_y="lock:worker:release-write",Cy="lock:master:grant-write",ky="lock:master:error-write",xy="lock:worker:finalize",Ty="mortice",Py={singleProcess:!1},Ry=(e,t,r,n,i,s,o,a,l)=>u=>{if(null==u.data)return;const c={type:u.data.type,name:u.data.name,identifier:u.data.identifier};c.type===i&&e.safeDispatchEvent(r,{detail:{name:c.name,identifier:c.identifier,async handler(){t.postMessage({type:l,name:c.name,identifier:c.identifier}),await new Promise((e=>{const r=n=>{if(null==(null==n?void 0:n.data))return;const i=n.data.type,s=(n.data.name,n.data.identifier);i===a&&s===c.identifier&&(t.removeEventListener("message",r),e())};t.addEventListener("message",r)}))},onError(e){t.postMessage({type:o,name:c.name,identifier:c.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),c.type===s&&e.safeDispatchEvent(n,{detail:{name:c.name,identifier:c.identifier}}),c.type===xy&&e.safeDispatchEvent("finalizeRequest",{detail:{name:c.name}})};class Ly{readLock(e){return this.sendRequest(yy,by,Ey,Sy,wy,e)}writeLock(e){return this.sendRequest(Ay,Iy,Cy,ky,_y,e)}finalize(){this.channel.postMessage({type:xy,name:this.name}),this.channel.close()}async sendRequest(e,t,r,n,i,s){var o;null==s||null===(o=s.signal)||void 0===o||o.throwIfAborted();const a=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise(((e,o)=>{var l;const u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};null==s||null===(l=s.signal)||void 0===l||l.addEventListener("abort",u,{once:!0});const c=t=>{var l,d,h;if((null===(l=t.data)||void 0===l?void 0:l.identifier)===a&&((null===(d=t.data)||void 0===d?void 0:d.type)===r&&(this.channel.removeEventListener("message",c),null==s||null===(h=s.signal)||void 0===h||h.removeEventListener("abort",u),e((()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})}))),t.data.type===n)){var f;this.channel.removeEventListener("message",c),null==s||null===(f=s.signal)||void 0===f||f.removeEventListener("abort",u);const e=Error();null!=t.data.error&&(e.message=t.data.error.message,e.name=t.data.error.name,e.stack=t.data.error.stack),o(e)}};this.channel.addEventListener("message",c)}))}constructor(e){(0,L.default)(this,"name",void 0),(0,L.default)(this,"channel",void 0),this.name=e,this.channel=new BroadcastChannel(Ty)}}const Dy=new Map;let My;function Ny(e){return"function"==typeof(null==e?void 0:e.readLock)&&"function"==typeof(null==e?void 0:e.writeLock)}async function Oy(e,t){var r;let n,i;const s=new Promise(((e,t)=>{n=e,i=t})),o=()=>{i(new ly)};return null==t||null===(r=t.signal)||void 0===r||r.addEventListener("abort",o,{once:!0}),e.add((async()=>{await new Promise((e=>{n((()=>{var r;null==t||null===(r=t.signal)||void 0===r||r.removeEventListener("abort",o),e()}))}))}),{signal:null==t?void 0:t.signal}).catch((e=>{i(e)})),s}const Uy={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Fy(e){const t=Object.assign({},Uy,e);return((e,t)=>{let r=Dy.get(e);if(null!=r)return r;const n=function(e){if(null==My&&(My=(e=>{if(e=Object.assign({},Py,e),globalThis.document||e.singleProcess){const e=new BroadcastChannel(Ty),t=new es;return e.addEventListener("message",Ry(t,e,"requestReadLock","abortReadLockRequest",yy,by,Sy,wy,Ey)),e.addEventListener("message",Ry(t,e,"requestWriteLock","abortWriteLockRequest",Ay,Iy,ky,_y,Cy)),t}return new Ly(e.name)})(e),!Ny(My))){const e=My;e.addEventListener("requestReadLock",(t=>{const r=t.detail.name,n=t.detail.identifier,i=Dy.get(r);if(null==i)return;const s=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&s.abort()};e.addEventListener("abortReadLockRequest",o),i.readLock({signal:s.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortReadLockRequest",o)}))})),e.addEventListener("requestWriteLock",(t=>{const r=t.detail.name,n=t.detail.identifier,i=Dy.get(r);if(null==i)return;const s=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&s.abort()};e.addEventListener("abortWriteLockRequest",o),i.writeLock({signal:s.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortWriteLockRequest",o)}))})),e.addEventListener("finalizeRequest",(e=>{const t=e.detail.name,r=Dy.get(t);null!=r&&r.finalize()}))}return My}(t);if(Ny(n))return r=n,Dy.set(e,r),r;const i=new vy({concurrency:1});let s;return r={async readLock(e){if(null!=s)return Oy(s,e);s=new vy({concurrency:t.concurrency,autoStart:!1});const r=s,n=Oy(s,e);return i.add((async()=>{r.start(),await r.onIdle().then((()=>{s===r&&(s=null)}))})),n},writeLock:async e=>(s=null,Oy(i,e)),finalize(){Dy.delete(e)},queue:i},Dy.set(e,r),!0===t.autoFinalize&&i.addEventListener("idle",(()=>{r.finalize()}),{once:!0}),r})(t.name,t)}var By,$y,qy;function zy(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let r;return"RSA"===e.type&&(r=e.toMultihash()),zu(Ru(t.publicKey,r))}function jy(e,t,r){const n=new Map,i=BigInt(Date.now());for(const[e,r]of t.tags.entries())null!=r.expiry&&r.expiry<i||n.set(e,r);var s;return(0,M.default)((0,D.default)({},t),{id:zy(e,t),addresses:t.addresses.filter((({observed:e})=>null!=e&&e>Date.now()-r)).map((({multiaddr:e,isCertified:t})=>({multiaddr:Mc(e),isCertified:null!=t&&t}))),metadata:t.metadata,peerRecordEnvelope:null!==(s=t.peerRecordEnvelope)&&void 0!==s?s:void 0,tags:n})}function Ky(e,t){return Hy(e.addresses,t.addresses,((e,t)=>e.isCertified===t.isCertified&&!!Ns(e.multiaddr,t.multiaddr)))&&Hy(e.protocols,t.protocols,((e,t)=>e===t))&&Vy(e.publicKey,t.publicKey)&&Vy(e.peerRecordEnvelope,t.peerRecordEnvelope)&&Wy(e.metadata,t.metadata,((e,t)=>Ns(e,t)))&&function(e,t){return Wy(e,t,((e,t)=>e.value===t.value&&e.expiry===t.expiry))}(e.tags,t.tags)}function Vy(e,t){return null==e&&null==t||null!=e&&null!=t&&Ns(e,t)}function Hy(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!r(e[n],t[n]))return!1;return!0}function Wy(e,t,r){if(e.size!==t.size)return!1;for(const[n,i]of e.entries()){const e=t.get(n);if(null==e)return!1;if(!r(i,e))return!1}return!0}(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:"",value:Z(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),qy.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={key:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.string();break;case 2:var s;n.value=qy.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.value});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Gr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),$y.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,i]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:i},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,i]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:i},r);null!=t.updated&&(r.uint32(64),r.uint64Number(t.updated)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const i={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==r?t.len:t.pos+r;for(;t.pos<s;){const r=t.uint32();switch(r>>>3){case 1:var o,a;if(null!=(null===(o=n.limits)||void 0===o?void 0:o.addresses)&&i.addresses.length===n.limits.addresses)throw new Xr('Decode error - map field "addresses" had too many elements');i.addresses.push($y.codec().decode(t,t.uint32(),{limits:null===(a=n.limits)||void 0===a?void 0:a.addresses$}));break;case 2:var l;if(null!=(null===(l=n.limits)||void 0===l?void 0:l.protocols)&&i.protocols.length===n.limits.protocols)throw new Xr('Decode error - map field "protocols" had too many elements');i.protocols.push(t.string());break;case 4:i.publicKey=t.bytes();break;case 5:i.peerRecordEnvelope=t.bytes();break;case 6:{var u;if(null!=(null===(u=n.limits)||void 0===u?void 0:u.metadata)&&i.metadata.size===n.limits.metadata)throw new Zr('Decode error - map field "metadata" had too many elements');const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());i.metadata.set(r.key,r.value);break}case 7:{var c,d;if(null!=(null===(c=n.limits)||void 0===c?void 0:c.tags)&&i.tags.size===n.limits.tags)throw new Zr('Decode error - map field "tags" had too many elements');const r=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:null===(d=n.limits)||void 0===d?void 0:d.tags$value}});i.tags.set(r.key,r.value);break}case 8:i.updated=t.uint64Number();break;default:t.skipType(7&r)}}return i}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(By||(By={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:Z(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})($y||($y={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(qy||(qy={}));const Gy="/",Xy=(new TextEncoder).encode(Gy),Zy=Xy[0];let Yy=Symbol.toStringTag;class Qy{toString(e="utf8"){return ri(this._buf,e)}uint8Array(){return this._buf}get[Yy](){return`Key(${this.toString()})`}static withNamespaces(e){return new Qy(e.join(Gy))}static random(){return new Qy(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Qy(e):"function"==typeof e.uint8Array?new Qy(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Xy),this._buf[0]!==Zy){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Zy,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Zy;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;e<t.length;e++){if(r.length<e+1)return!1;const n=t[e],i=r[e];if(n<i)return!0;if(n>i)return!1}return t.length<r.length}reverse(){return Qy.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Gy).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new Qy(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Gy)||(e+=Gy),e+=this.type(),new Qy(e)}parent(){const e=this.list();return 1===e.length?new Qy(Gy):new Qy(e.slice(0,-1).join(Gy))}child(e){return this.toString()===Gy?e:e.toString()===Gy?this:new Qy(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){var t;return Qy.withNamespaces([...this.namespaces(),...(t=e.map((e=>e.namespaces())),[].concat(...t))])}constructor(e,t){if((0,L.default)(this,"_buf",void 0),"string"==typeof e)this._buf=Zt(e);else{if(!(e instanceof Uint8Array))throw Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Zy)throw Error("Invalid key")}}const Jy="/peers/";function eb(e){if(!Si(e)||null==e.type)throw new Pi("Invalid PeerId");const t=e.toCID().toString();return new Qy(`${Jy}${t}`)}async function tb(e,t,r,n,i){const s=new Map;for(const n of r){if(null==n)continue;if(n.multiaddr instanceof Uint8Array&&(n.multiaddr=Mc(n.multiaddr)),!Dc(n.multiaddr))throw new Pi("Multiaddr was invalid");if(!await t(e,n.multiaddr,i))continue;var o;const r=null!==(o=n.isCertified)&&void 0!==o&&o,a=n.multiaddr.toString(),l=s.get(a);null!=l?n.isCertified=l.isCertified||r:s.set(a,{multiaddr:n.multiaddr,isCertified:r})}return[...s.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((({isCertified:t,multiaddr:r})=>{const n=r.getPeerId();return e.equals(n)&&(r=r.decapsulate(Mc("/p2p/"+e))),{isCertified:t,multiaddr:r.bytes}}))}async function rb(e,t,r,n){var i,s;if(null==t)throw new Pi("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Pi("publicKey bytes do not match peer id publicKey bytes");const o=null===(i=n.existingPeer)||void 0===i?void 0:i.peer;if(null!=o&&!e.equals(o.id))throw new Pi("peer id did not match existing peer id");var a,l,u,c;let d,h=null!==(a=null==o?void 0:o.addresses)&&void 0!==a?a:[],f=new Set(null!==(l=null==o?void 0:o.protocols)&&void 0!==l?l:[]),p=null!==(u=null==o?void 0:o.metadata)&&void 0!==u?u:new Map,g=null!==(c=null==o?void 0:o.tags)&&void 0!==c?c:new Map,m=null==o?void 0:o.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(h=[],null!=t.multiaddrs&&h.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&h.push(...t.addresses)),null!=t.protocols&&(f=new Set(t.protocols)),null!=t.metadata&&(p=nb(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:ib})),null!=t.tags&&(g=nb(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:sb,map:ob})),null!=t.peerRecordEnvelope&&(m=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&h.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&h.push(...t.addresses),null!=t.protocols&&(f=new Set([...f,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?p.delete(t):p.set(t,r);p=nb([...p.entries()],{validate:ib})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(g);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);g=nb([...r.entries()],{validate:sb,map:ob})}null!=t.peerRecordEnvelope&&(m=t.peerRecordEnvelope)}var v;null!=(null==o?void 0:o.id.publicKey)?d=Lu(o.id.publicKey):null!=t.publicKey?d=Lu(t.publicKey):null!=e.publicKey&&(d=Lu(e.publicKey));const y={addresses:await tb(e,null!==(v=n.addressFilter)&&void 0!==v?v:async()=>!0,h,null===(s=n.existingPeer)||void 0===s||s.peerPB.addresses,n),protocols:[...f.values()].sort(((e,t)=>e.localeCompare(t))),metadata:p,tags:g,publicKey:d,peerRecordEnvelope:m};return y.addresses.forEach((e=>{var t,r,i,s;e.observed=null!==(s=null===(t=null===(r=null===(i=n.existingPeer)||void 0===i?void 0:i.peerPB.addresses)||void 0===r?void 0:r.find((e=>Ns(e.multiaddr,e.multiaddr))))||void 0===t?void 0:t.observed)&&void 0!==s?s:Date.now()})),"RSA"!==e.type&&delete y.publicKey,y}function nb(e,t){var r;const n=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);var i;for(const[s,o]of e.sort((([e],[t])=>e.localeCompare(t))))null!=o&&n.set(s,null!==(i=null===(r=t.map)||void 0===r?void 0:r.call(t,s,o))&&void 0!==i?i:o);return n}function ib(e,t){if("string"!=typeof e)throw new Pi("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Pi("Metadata value must be a Uint8Array")}function sb(e,t){if("string"!=typeof e)throw new Pi("Tag name must be a string");if(null!=t.value){if(parseInt(""+t.value,10)!==t.value)throw new Pi("Tag value must be an integer");if(t.value<0||t.value>100)throw new Pi("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(""+t.ttl,10)!==t.ttl)throw new Pi("Tag ttl must be an integer");if(t.ttl<0)throw new Pi("Tag ttl must be between greater than 0")}}function ob(e,t){let r;var n;null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl)));const i={value:null!==(n=t.value)&&void 0!==n?n:0};return null!=r&&(i.expiry=r),i}function ab(e){const t=e.toString().split("/")[2];return Ku($t.parse(t,We))}function lb(e,t,r){return function(e,t,r){return jy(e,By.decode(t),r)}(ab(e),t,r)}var ub=new WeakSet,cb=new WeakSet,db=new WeakSet;class hb{getLock(e){let t=this.locks.get(e);return null==t&&(t={refs:0,lock:Fy({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,0===t.refs&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){const r=this.getLock(e);try{const n=await r.lock.readLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async getWriteLock(e,t){const r=this.getLock(e);try{const n=await r.lock.writeLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async has(e,t){try{return await this.load(e,t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(eb(e),t)}async load(e,t){const r=eb(e),n=await this.datastore.get(r,t),i=By.decode(n);if((0,P.default)(this,db,gb).call(this,e,i))throw await this.datastore.delete(r,t),new Fi;return jy(e,i,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,r){const n=await(0,P.default)(this,ub,fb).call(this,e,r),i=await rb(e,t,"patch",(0,M.default)((0,D.default)({},r),{addressFilter:this.addressFilter}));return(0,P.default)(this,cb,pb).call(this,e,i,n)}async patch(e,t,r){const n=await(0,P.default)(this,ub,fb).call(this,e,r),i=await rb(e,t,"patch",(0,M.default)((0,D.default)({},r),{addressFilter:this.addressFilter,existingPeer:n}));return(0,P.default)(this,cb,pb).call(this,e,i,n)}async merge(e,t,r){const n=await(0,P.default)(this,ub,fb).call(this,e,r),i=await rb(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return(0,P.default)(this,cb,pb).call(this,e,i,n)}async*all(e){for await(const{key:t,value:r}of this.datastore.query(function(e,t){var r,n;return{prefix:Jy,filters:(null!==(r=e.filters)&&void 0!==r?r:[]).map((e=>({key:r,value:n})=>e(lb(r,n,t)))),orders:(null!==(n=e.orders)&&void 0!==n?n:[]).map((e=>(r,n)=>e(lb(r.key,r.value,t),lb(n.key,n.value,t))))}}(null!=e?e:{},this.maxAddressAge),e)){const n=ab(t);if(n.equals(this.peerId))continue;const i=By.decode(r);(0,P.default)(this,db,gb).call(this,n,i)?await this.datastore.delete(t,e):yield jy(n,i,this.peerId.equals(n)?1/0:this.maxAddressAge)}}constructor(e,t={}){var r,n;(0,R.default)(this,ub),(0,R.default)(this,cb),(0,R.default)(this,db),(0,L.default)(this,"peerId",void 0),(0,L.default)(this,"datastore",void 0),(0,L.default)(this,"locks",void 0),(0,L.default)(this,"addressFilter",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,"maxAddressAge",void 0),(0,L.default)(this,"maxPeerAge",void 0),this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=function(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new ay({name:t,metrics:r}):new Wv,n}({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=null!==(r=t.maxAddressAge)&&void 0!==r?r:36e5,this.maxPeerAge=null!==(n=t.maxPeerAge)&&void 0!==n?n:216e5}}async function fb(e,t){try{const r=eb(e),n=await this.datastore.get(r,t),i=By.decode(n);if((0,P.default)(this,db,gb).call(this,e,i))throw await this.datastore.delete(r,t),new Fi;return{peerPB:i,peer:jy(e,i,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async function pb(e,t,r,n){t.updated=Date.now();const i=By.encode(t);return await this.datastore.put(eb(e),i,n),{peer:jy(e,t,this.maxAddressAge),previous:null==r?void 0:r.peer,updated:null==r||!Ky(t,r.peerPB)}}function gb(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;const r=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,i=t.addresses.filter((e=>null!=e.observed&&e.observed>n));return r&&0===i.length}var mb=new WeakSet;let vb=Symbol.toStringTag;class yb{async forEach(e,t){for await(const r of this.store.all(t))e(r)}async all(e){return Ds(this.store.all(e))}async delete(e,t){const r=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{r()}}async has(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),null==r||r()}}async get(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{null==r||r()}}async getInfo(e,t){const r=await this.get(e,t);return{id:r.id,multiaddrs:r.addresses.map((({multiaddr:e})=>e))}}async save(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.save(e,t,r);return(0,P.default)(this,mb,bb).call(this,e,n),n.peer}finally{null==n||n()}}async patch(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.patch(e,t,r);return(0,P.default)(this,mb,bb).call(this,e,n),n.peer}finally{null==n||n()}}async merge(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.merge(e,t,r);return(0,P.default)(this,mb,bb).call(this,e,n),n.peer}finally{null==n||n()}}async consumePeerRecord(e,t,r){const n=Si(t)?t:Si(null==t?void 0:t.expectedPeer)?t.expectedPeer:void 0,i=Si(t)||void 0===t?r:t,s=await Ff.openAndCertify(e,jf.DOMAIN,i),o=Ku(s.publicKey.toCID());if(!1===(null==n?void 0:n.equals(o)))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",n,o),!1;const a=jf.createFromProtobuf(s.payload);let l;try{l=await this.get(o,i)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=(null==l?void 0:l.peerRecordEnvelope)){const e=Ff.createFromProtobuf(l.peerRecordEnvelope),t=jf.createFromProtobuf(e.payload);if(t.seqNumber>=a.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),!1}return await this.patch(a.peerId,{peerRecordEnvelope:e,addresses:a.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))},i),!0}constructor(e,t={}){(0,R.default)(this,mb),(0,L.default)(this,"store",void 0),(0,L.default)(this,"events",void 0),(0,L.default)(this,"peerId",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,vb,"@libp2p/peer-store"),this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new hb(e,t)}}function bb(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}class wb extends Error{constructor(e="Not Found"){super(e),(0,L.default)(this,"name",wb.name),(0,L.default)(this,"code",wb.code)}}function Eb(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push(e){n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}(e),{value:i,done:s}=n.next();if(!0===s)return function*(){}();const o=t(i,r++);if("function"==typeof o.then)return async function*(){await o&&(yield i);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield i);for(const e of n)a(e,r++)&&(yield e)}()}function Sb(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Ds(e);yield*r.sort(t)}():function*(){const r=Ds(e);yield*r.sort(t)}()}function Ab(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()}(0,L.default)(wb,"name","NotFoundError"),(0,L.default)(wb,"code","ERR_NOT_FOUND");class Ib{put(e,t,r){return Promise.reject(Error(".put is not implemented"))}get(e,t){return Promise.reject(Error(".get is not implemented"))}has(e,t){return Promise.reject(Error(".has is not implemented"))}delete(e,t){return Promise.reject(Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await Vf(this.putMany(e,r)),e=[],await Vf(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw Error("._all is not implemented")}async*_allKeys(e,t){throw Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=Eb(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Eb(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Sb(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=Eb(r,(()=>t++>=n))}return null!=e.limit&&(r=Ab(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=Eb(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Eb(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Sb(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=Eb(r,(()=>n++>=t))}return null!=e.limit&&(r=Ab(r,e.limit)),r}}class _b extends Ib{put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw new wb;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new Qy(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new Qy(e)}constructor(){super(),(0,L.default)(this,"data",void 0),this.data=new Map}}class Cb extends Map{set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}constructor(e){super(),(0,L.default)(this,"metric",void 0);const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}}function kb(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new Cb({name:t,metrics:r}):new Map,n}const xb=864e13;class Tb{has(e){const t=this.findHost(e);for(const e of this.mappings.values())if(e.domain===t)return!0;return!1}add(e,t){t.forEach((t=>{this.log("add DNS mapping %s to %s",t,e);const r=!0===up(t);this.mappings.set(t,{domain:e,verified:r,expires:r?xb-Date.now():0,lastVerified:r?xb-Date.now():void 0})}))}remove(e){const t=this.findHost(e);let r=!1;for(const[e,n]of this.mappings.entries())n.domain===t&&(this.log("removing %s to %s DNS mapping %e",e,n.domain,Error("where")),this.mappings.delete(e),r=r||n.verified);return r}getAll(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r].multiaddr.stringTuples(),i=n[0][1];if(null!=i)for(const[s,o]of this.mappings.entries())i===s&&this.maybeAddSNITuple(n,o.domain)&&(e.splice(r,1),r--,t.push({multiaddr:Mc("/"+n.map((e=>[Nc(e[0]).name,e[1]].join("/"))).join("/")),verified:o.verified,type:"dns-mapping",expires:o.expires,lastVerified:o.lastVerified}))}return t}maybeAddSNITuple(e,t){var r;for(let n=0;n<e.length;n++)if(448===e[n][0]&&449!==(null===(r=e[n+1])||void 0===r?void 0:r[0]))return e.splice(n+1,0,[449,t]),!0;return!1}confirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,i]of this.mappings.entries())i.domain===r&&(this.log("marking %s to %s DNS mapping as verified",e,i.domain),n=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return n}unconfirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,i]of this.mappings.entries())i.domain===r&&(this.log("removing verification of %s to %s DNS mapping",e,i.domain),n=n||i.verified,i.verified=!1,i.expires=Date.now()+t);return n}findHost(e){for(const t of e.stringTuples()){if(449===t[0])return t[1];if(53===t[0]||54===t[0]||55===t[0]||56===t[0])return t[1]}}constructor(e,t={}){(0,L.default)(this,"log",void 0),(0,L.default)(this,"mappings",void 0),this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=kb({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}}class Pb{has(e){const t=e.stringTuples();for(const e of this.mappings.values())for(const r of e)if(r.externalIp===t[0][1])return!0;return!1}add(e,t,r,n=t,i="tcp"){var s;const o=`${e}-${t}-${i}`,a=null!==(s=this.mappings.get(o))&&void 0!==s?s:[],l={internalIp:e,internalPort:t,externalIp:r,externalPort:n,externalFamily:Ju(r)?4:6,protocol:i,verified:!1,expires:0};a.push(l),this.mappings.set(o,a)}remove(e){var t,r;const n=e.stringTuples(),i=null!==(t=n[0][1])&&void 0!==t?t:"",s=6===n[1][0]?"tcp":"udp",o=parseInt(null!==(r=n[1][1])&&void 0!==r?r:"0");let a=!1;for(const[e,t]of this.mappings.entries()){for(let e=0;e<t.length;e++){const r=t[e];r.externalIp===i&&r.externalPort===o&&r.protocol===s&&(this.log("removing %s:%s to %s:%s %s IP mapping",r.externalIp,r.externalPort,i,o,s),a=a||r.verified,t.splice(e,1),e--)}0===t.length&&this.mappings.delete(e)}return a}getAll(e){const t=[];for(const{multiaddr:r}of e){const e=r.stringTuples();let n;if(4!==e[0][0]&&41!==e[0][0]||6!==e[1][0]?4!==e[0][0]&&41!==e[0][0]||273!==e[1][0]||(n=`${e[0][1]}-${e[1][1]}-udp`):n=`${e[0][1]}-${e[1][1]}-tcp`,null==n)continue;const i=this.mappings.get(n);if(null!=i)for(const r of i)e[0][0]=4===r.externalFamily?4:41,e[0][1]=r.externalIp,e[1][1]=""+r.externalPort,t.push({multiaddr:Mc("/"+e.map((e=>[Nc(e[0]).name,e[1]].join("/"))).join("/")),verified:r.verified,type:"ip-mapping",expires:r.expires,lastVerified:r.lastVerified})}return t}confirm(e,t){const r=e.stringTuples()[0][1];let n=!1;for(const e of this.mappings.values())for(const i of e)i.externalIp===r&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),n=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return n}unconfirm(e,t){var r,n;const i=e.stringTuples(),s=null!==(r=i[0][1])&&void 0!==r?r:"",o=6===i[1][0]?"tcp":"udp",a=parseInt(null!==(n=i[1][1])&&void 0!==n?n:"0");let l=!1;for(const e of this.mappings.values())for(let r=0;r<e.length;r++){const n=e[r];n.externalIp===s&&n.externalPort===a&&n.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",n.externalIp,n.externalPort,s,a,o),l=l||n.verified,n.verified=!1,n.expires=Date.now()+t)}return l}constructor(e,t={}){(0,L.default)(this,"log",void 0),(0,L.default)(this,"mappings",void 0),this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=kb({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}}class Rb{has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(const t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(dp(e)||function(e){try{for(const{code:t,value:r}of e.getComponents())if(t!==rc&&null!=r){if(4===t)return r.startsWith("169.254.");if(t===tc)return r.toLowerCase().startsWith("fe80")}}catch(e){}return!1}(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map((([e,t])=>({multiaddr:Mc(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified})))}remove(e){var t,r;const n=null!==(r=null===(t=this.addresses.get(e.toString()))||void 0===t?void 0:t.verified)&&void 0!==r&&r;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),n}confirm(e,t){var r;const n=e.toString(),i=null!==(r=this.addresses.get(n))&&void 0!==r?r:{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,i),s}constructor(e,t={}){var r;(0,L.default)(this,"log",void 0),(0,L.default)(this,"addresses",void 0),(0,L.default)(this,"maxObservedAddresses",void 0),this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=kb({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=null!==(r=t.maxObservedAddresses)&&void 0!==r?r:10}}const Lb=[4,tc,53,54,55,56];function Db(e){try{for(const{code:t}of e.getComponents())if(t!==rc)return Lb.includes(t)}catch(e){}return!1}class Mb{get(e,t){if(dp(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};const r=this.toKey(e);let n=this.addresses.get(r);return null==n&&(n={verified:!Db(e),expires:0},this.addresses.set(r,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){const t=this.toKey(e);return this.addresses.has(t)}remove(e){var t,r;const n=this.toKey(e),i=null!==(r=null===(t=this.addresses.get(n))||void 0===t?void 0:t.verified)&&void 0!==r&&r;return this.log("removing observed address %a",e),this.addresses.delete(n),i}confirm(e,t){var r;const n=this.toKey(e),i=null!==(r=this.addresses.get(n))&&void 0!==r?r:{verified:!1,expires:0,lastVerified:0},s=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.addresses.set(n,i),s}unconfirm(e,t){var r;const n=this.toKey(e),i=null!==(r=this.addresses.get(n))&&void 0!==r?r:{verified:!1,expires:0},s=i.verified;return i.verified=!1,i.expires=Date.now()+t,this.addresses.set(n,i),s}toKey(e){if(Db(e)){const t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}constructor(e,t={}){var r;(0,L.default)(this,"log",void 0),(0,L.default)(this,"addresses",void 0),(0,L.default)(this,"maxObservedAddresses",void 0),this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=kb({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=null!==(r=t.maxObservedAddresses)&&void 0!==r?r:10}}const Nb=6e5,Ob=3e5,Ub=e=>e;function Fb(e,t){const r=e.getPeerId();return null!=r&&qu(r).equals(t)&&(e=e.decapsulate(Mc("/p2p/"+t.toString()))),e}let Bb=Symbol.toStringTag;class $b{_updatePeerStoreAddresses(){const e=this.getAddresses().map((e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate("/p2p/"+this.components.peerId.toString()):e));this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch((e=>{this.log.error("error updating addresses",e)}))}getListenAddrs(){return Array.from(this.listen).map((e=>Mc(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>Mc(e)))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map((e=>Mc(e)))}getObservedAddrs(){return this.observed.getAll().map((e=>e.multiaddr))}addObservedAddr(e){const t=e.stringTuples(),r=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(r)||(this.observedAddressFilter.add(r),e=Fb(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=Fb(e,this.components.peerId);let r=!0;var n,i,s,o,a;(("transport"===(null==t?void 0:t.type)||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,null!==(n=null==t?void 0:t.ttl)&&void 0!==n?n:this.addressVerificationTTL)&&r&&(r=!1),("dns-mapping"===(null==t?void 0:t.type)||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,null!==(i=null==t?void 0:t.ttl)&&void 0!==i?i:this.addressVerificationTTL)&&r&&(r=!1),("ip-mapping"===(null==t?void 0:t.type)||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,null!==(s=null==t?void 0:t.ttl)&&void 0!==s?s:this.addressVerificationTTL)&&r&&(r=!1),"observed"===(null==t?void 0:t.type)||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,null!==(o=null==t?void 0:t.ttl)&&void 0!==o?o:this.addressVerificationTTL),r=!1):!this.observed.confirm(e,null!==(a=null==t?void 0:t.ttl)&&void 0!==a?a:this.addressVerificationTTL)&&r&&(r=!1));r||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){var r,n,i;e=Fb(e,this.components.peerId),this.observed.has(e)&&this.observed.remove(e),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,null!==(r=null==t?void 0:t.ttl)&&void 0!==r?r:this.addressVerificationRetry),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,null!==(n=null==t?void 0:t.ttl)&&void 0!==n?n:this.addressVerificationRetry),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,null!==(i=null==t?void 0:t.ttl)&&void 0!==i?i:this.addressVerificationRetry)}getAddresses(){const e=new Set,t=this.getAddressesWithMetadata().filter((t=>{if(!t.verified)return!1;const r=t.multiaddr.toString();return!e.has(r)&&(e.add(r),!0)})).map((e=>e.multiaddr));return this.announceFilter(t.map((e=>{const t=Mc(e),r=t.getComponents().pop();return(null==r?void 0:r.value)===this.components.peerId.toString()?t:t.encapsulate("/p2p/"+this.components.peerId.toString())})))}getAddressesWithMetadata(){const e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach((t=>{t.updateAnnounceAddrs(e)})),e.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})));let t=[];t=t.concat(this.components.transportManager.getAddrs().map((e=>this.transportAddresses.get(e,this.addressVerificationTTL))));const r=this.getAppendAnnounceAddrs();return r.length>0&&(this.components.transportManager.getListeners().forEach((e=>{e.updateAnnounceAddrs(r)})),t=t.concat(r.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Mc("/dns/"+e))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,r,n=t,i="tcp"){this.ipMappings.add(e,t,r,n,i),this.observed.removePrefixed(`/ip${Ju(r)?4:6}/${r}/${i}/${n}`)}removePublicAddressMapping(e,t,r,n=t,i="tcp"){this.ipMappings.remove(Mc(`/ip${Ju(r)?4:6}/${r}/${i}/${n}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;const t=e.toOptions();if(6===t.family||"127.0.0.1"===t.host||!0===up(t.host))return!1;const r=this.components.transportManager.getListeners(),n=[e=>jp.exactMatch(e)||Vp.exactMatch(e),e=>Op.exactMatch(e),e=>$p.exactMatch(e)];for(const i of n){if(!i(e))continue;const n=r.filter((e=>e.getAddrs().filter((e=>4===e.toOptions().family&&i(e))).length>0));if(1!==n.length)continue;const s=n[0].getAddrs().filter((e=>"127.0.0.1"!==e.toOptions().host)).pop();if(null==s)continue;const o=s.toOptions();return this.observed.remove(e),this.ipMappings.add(o.host,o.port,t.host,t.port,t.transport),!0}return!1}constructor(e,t={}){(0,L.default)(this,"log",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,"listen",void 0),(0,L.default)(this,"announce",void 0),(0,L.default)(this,"appendAnnounce",void 0),(0,L.default)(this,"announceFilter",void 0),(0,L.default)(this,"observed",void 0),(0,L.default)(this,"dnsMappings",void 0),(0,L.default)(this,"ipMappings",void 0),(0,L.default)(this,"transportAddresses",void 0),(0,L.default)(this,"observedAddressFilter",void 0),(0,L.default)(this,"addressVerificationTTL",void 0),(0,L.default)(this,"addressVerificationRetry",void 0),(0,L.default)(this,Bb,"@libp2p/address-manager");const{listen:r=[],announce:n=[],appendAnnounce:i=[]}=t;var s,o,a;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.appendAnnounce=new Set(i.map((e=>e.toString()))),this.observed=new Rb(e,t),this.dnsMappings=new Tb(e,t),this.ipMappings=new Pb(e,t),this.transportAddresses=new Mb(e,t),this.announceFilter=null!==(s=t.announceFilter)&&void 0!==s?s:Ub,this.observedAddressFilter=oy(1024),this.addressVerificationTTL=null!==(o=t.addressVerificationTTL)&&void 0!==o?o:Nb,this.addressVerificationRetry=null!==(a=t.addressVerificationRetry)&&void 0!==a?a:Ob,this._updatePeerStoreAddresses=Kf(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}}var qb;(e=>{e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"})(qb||(qb={}));class zb extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class jb extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class Kb extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class Vb extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class Hb extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class Wb extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class Gb extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class Xb extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class Zb extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class Yb extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class Qb extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Jb extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class ew extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class tw extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class rw extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class nw extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class iw{isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>ts(e))).map((async t=>{var r;await(null===(r=t[e])||void 0===r?void 0:r.call(t))})))}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")}constructor(e={}){(0,L.default)(this,"components",{}),(0,L.default)(this,"_started",!1),this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=qv())}}const sw=["metrics","connectionProtector","dns"],ow=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function aw(e){return Array.isArray(null==e?void 0:e[rs])?e[rs]:[]}function lw(e){return Array.isArray(null==e?void 0:e[ns])?e[ns]:[]}function uw(e){var t,r;return null!==(r=null!==(t=null==e?void 0:e[Symbol.toStringTag])&&void 0!==t?t:null==e?void 0:e.toString())&&void 0!==r?r:"unknown"}function cw(e={}){return(0,D.default)({denyDialPeer:async()=>!1,async denyDialMultiaddr(e){if(jp.matches(e))return!1;const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&!!up(""+t[0][1])},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0},e)}function dw(e){if(Si(e))return{peerId:e,multiaddrs:[]};let t,r=Array.isArray(e)?e:[e];if(r.length>0){const e=r[0].getPeerId();t=null==e?void 0:qu(e),r.forEach((e=>{if(!Dc(e))throw new $i("Invalid multiaddr");const r=e.getPeerId();if(null==r){if(null!=t)throw new Pi("Multiaddrs must all have the same peer id or have no peer id")}else{const e=qu(r);if(!0!==(null==t?void 0:t.equals(e)))throw new Pi("Multiaddrs must all have the same peer id or have no peer id")}}))}return r=r.filter((e=>!Sp.exactMatch(e))),{peerId:t,multiaddrs:r}}const hw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function fw(e){try{let t;if(t="string"==typeof e?Mc(e):e,!t.protoNames().includes("ipcidr")){const e=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(e)}return function(e){let t,r;if(e.getComponents().forEach((e=>{"ip4"!==e.name&&"ip6"!==e.name||(r=e.value),"ipcidr"===e.name&&(t=e.value)})),null==t||null==r)throw Error("Invalid multiaddr");return new Tc(r,t)}(t)}catch(t){throw Error("Can't convert to IpNet, Invalid multiaddr format: "+e)}}class pw{start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch((e=>{this.log.error("error while pruning connections %e",e)}))}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length,r=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,r),t<=r)return;const n=new Wv;for(const t of e){const r=t.remotePeer;if(!n.has(r)){n.set(r,0);try{const e=await this.peerStore.get(r);n.set(r,[...e.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"NotFoundError"!==e.name&&this.log.error("error loading peer tags",e)}}}const i=this.sortConnections(e,n),s=Math.max(t-r,0),o=[];for(const e of i)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address)))||o.push(e),o.length===s)break;await Promise.all(o.map((async e=>{await async function(e,t){var r,n,i;const s=null!==(n=null==e||null===(r=e.streams)||void 0===r?void 0:r.map((e=>e.protocol)))&&void 0!==n?n:[],o=null!==(i=null==t?void 0:t.closableProtocols)&&void 0!==i?i:hw;if(!(s.filter((e=>null!=e&&!o.includes(e))).length>0))try{await(null==e?void 0:e.close(t))}catch(t){null==e||e.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:o})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0)).sort(((e,r)=>{var n,i;const s=null!==(n=t.get(e.remotePeer))&&void 0!==n?n:0,o=null!==(i=t.get(r.remotePeer))&&void 0!==i?i:0;return s>o?1:s<o?-1:0}))}constructor(e,t={}){var r;(0,L.default)(this,"connectionManager",void 0),(0,L.default)(this,"peerStore",void 0),(0,L.default)(this,"allow",void 0),(0,L.default)(this,"events",void 0),(0,L.default)(this,"log",void 0),this.allow=(null!==(r=t.allow)&&void 0!==r?r:[]).map((e=>fw(e))),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}}const gw="last-dial-failure",mw="last-dial-success";class vw{onAbort(){var e,t;this.deferred.reject(null!==(t=null===(e=this.signal)||void 0===e?void 0:e.reason)&&void 0!==t?t:new ki)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}constructor(e){var t;(0,L.default)(this,"deferred",void 0),(0,L.default)(this,"signal",void 0),this.signal=e,this.deferred=Qs(),this.onAbort=this.onAbort.bind(this),null===(t=this.signal)||void 0===t||t.addEventListener("abort",this.onAbort)}}class yw{abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>{var r;return e&&!0===(null===(r=t.signal)||void 0===r?void 0:r.aborted)}),!0)&&(this.controller.abort(new ki),this.cleanup())}async join(e={}){var t;const r=new vw(e.signal);return this.recipients.push(r),null===(t=e.signal)||void 0===t||t.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{var e;this.controller.signal.throwIfAborted();const t=await io(this.fn((0,M.default)((0,D.default)({},null!==(e=this.options)&&void 0!==e?e:{}),{signal:this.controller.signal})),this.controller.signal);this.recipients.forEach((e=>{e.deferred.resolve(t)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}constructor(e,t){(0,L.default)(this,"id",void 0),(0,L.default)(this,"fn",void 0),(0,L.default)(this,"options",void 0),(0,L.default)(this,"recipients",void 0),(0,L.default)(this,"status",void 0),(0,L.default)(this,"timeline",void 0),(0,L.default)(this,"controller",void 0),this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}}class bw extends es{emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){var r;if(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.size===this.maxSize)throw new ag;const n=new yw(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then((e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:n,result:e}}),e))).catch((e=>{if("queued"===n.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===n){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:n,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new ki)})),this.clear()}async onEmpty(e){0!==this.size&&await uy(this,"empty",null==e?void 0:e.signal)}async onSizeLessThan(e,t){this.size<e||await uy(this,"next",null==t?void 0:t.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await uy(this,"idle",null==e?void 0:e.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){var t,r;null==e||null===(t=e.signal)||void 0===t||t.throwIfAborted();const n=ro({objectMode:!0}),i=e=>{null!=e?this.abort():this.clear(),n.end(e)},s=e=>{null!=e.detail&&n.push(e.detail)},o=e=>{i(e.detail.error)},a=()=>{i()},l=()=>{i(new ki("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",a),null==e||null===(r=e.signal)||void 0===r||r.addEventListener("abort",l);try{yield*n}finally{var u;this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",a),null==e||null===(u=e.signal)||void 0===u||u.removeEventListener("abort",l),i()}}constructor(e={}){var t,r,n;super(),(0,L.default)(this,"concurrency",void 0),(0,L.default)(this,"maxSize",void 0),(0,L.default)(this,"queue",void 0),(0,L.default)(this,"pending",void 0),(0,L.default)(this,"sort",void 0),this.concurrency=null!==(r=e.concurrency)&&void 0!==r?r:1/0,this.maxSize=null!==(n=e.maxSize)&&void 0!==n?n:1/0,this.pending=0,null!=e.metricName&&(null===(t=e.metrics)||void 0===t||t.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})})),this.sort=e.sort,this.queue=[],this.emitEmpty=Kf(this.emitEmpty.bind(this),1),this.emitIdle=Kf(this.emitIdle.bind(this),1)}}class ww extends bw{constructor(e={}){super((0,M.default)((0,D.default)({},e),{sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0}))}}function Ew(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)null!=(null==t?void 0:t.removeEventListener)&&t.removeEventListener("abort",r)}for(const t of e){if(!0===(null==t?void 0:t.aborted)){r();break}null!=(null==t?void 0:t.addEventListener)&&t.addEventListener("abort",r)}const n=t.signal;return n.clear=function(){for(const t of e)null!=(null==t?void 0:t.removeEventListener)&&t.removeEventListener("abort",r)},n}function Sw(e){if(!cp(e))return!1;const{address:t}=e.nodeAddress();var r;return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r=t)||/^::1$/.test(r)}function Aw(e,t){const r=Op.exactMatch(e.multiaddr),n=Op.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;const i=Vp.exactMatch(e.multiaddr),s=Vp.exactMatch(t.multiaddr);if(i&&!s)return-1;if(!i&&s)return 1;const o=jp.exactMatch(e.multiaddr),a=jp.exactMatch(t.multiaddr);if(o&&!a)return-1;if(!o&&a)return 1;const l=Qp.exactMatch(e.multiaddr),u=Qp.exactMatch(t.multiaddr);if(l&&!u)return-1;if(!l&&u)return 1;const c=Wp.exactMatch(e.multiaddr),d=Wp.exactMatch(t.multiaddr);if(c&&!d)return-1;if(!c&&d)return 1;const h=Xp.exactMatch(e.multiaddr),f=Xp.exactMatch(t.multiaddr);return h&&!f?-1:!h&&f?1:0}function Iw(e,t){const r=Sw(e.multiaddr),n=Sw(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function _w(e,t){const r=dp(e.multiaddr),n=dp(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function Cw(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function kw(e,t){const r=Yp.exactMatch(e.multiaddr),n=Yp.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}class xw{start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){var r,n;const{peerId:i,multiaddrs:s}=dw(e),o=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(i)||s.find((t=>t.equals(e.remoteAddr))))));if("open"===(null==o?void 0:o.status))return this.log("already connected to %a",o.remoteAddr),null===(r=t.onProgress)||void 0===r||r.call(t,new Jg("dial-queue:already-connected")),o;const a=this.queue.queue.find((e=>{if(!0===(null==i?void 0:i.equals(e.options.peerId)))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of s)if(t.has(e.toString()))return!0;return!1}));if(null!=a){var l;this.log("joining existing dial target for %p",i);for(const e of s)a.options.multiaddrs.add(e.toString());return null===(l=t.onProgress)||void 0===l||l.call(t,new Jg("dial-queue:already-in-dial-queue")),a.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Gi("Dial queue is full");var u,c;return this.log("creating dial target for %p",i,s.map((e=>e.toString()))),null===(n=t.onProgress)||void 0===n||n.call(t,new Jg("dial-queue:add-to-dial-queue")),this.queue.add((async e=>{var t;null===(t=e.onProgress)||void 0===t||t.call(e,new Jg("dial-queue:start-dial"));const r=Ew([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,r)}finally{r.clear()}}),{peerId:i,priority:null!==(u=t.priority)&&void 0!==u?u:jw,multiaddrs:new Set(s.map((e=>e.toString()))),signal:null!==(c=t.signal)&&void 0!==c?c:AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){const r=e.peerId,n=e.multiaddrs,i=new Set;let s=0===e.multiaddrs.size,o=0,a=0;const l=[];for(this.log("starting dial to %p",r);s||n.size>0;){var u;a++,s=!1;const c=[],d=new Set(e.multiaddrs);n.clear(),this.log("calculating addrs to dial %p from %s",r,[...d]);const h=await this.calculateMultiaddrs(r,d,(0,M.default)((0,D.default)({},e),{signal:t}));for(const e of h)i.has(e.multiaddr.toString())?this.log.trace("skipping previously failed multiaddr %a while dialing %p",e.multiaddr,r):c.push(e);this.log("%s dial to %p with %s",1===a?"starting":"continuing",r,c.map((e=>e.multiaddr.toString()))),null==e||null===(u=e.onProgress)||void 0===u||u.call(e,new Jg("dial-queue:calculated-addresses",c));for(const n of c){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,e.peerId),new Gi("Peer had more than maxPeerAddrsToDial");o++;try{const i=await this.components.transportManager.dial(n.multiaddr,(0,M.default)((0,D.default)({},e),{signal:t}));this.log("dial to %a succeeded",n.multiaddr);try{await this.components.peerStore.merge(i.remotePeer,{multiaddrs:[i.remoteAddr],metadata:{[mw]:Zt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}return i}catch(e){if(this.log.error("dial failed to %a",n.multiaddr,e),i.add(n.multiaddr.toString()),null!=r)try{await this.components.peerStore.merge(r,{metadata:{[gw]:Zt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Hi(e.message);l.push(e)}}}if(1===l.length)throw l[0];throw new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:Mc(e),isCertified:!1})));if(null!=e){var i,s;if(this.components.peerId.equals(e))throw new Gi("Tried to dial self");if(!0===await(null===(s=(i=this.components.connectionGater).denyDialPeer)||void 0===s?void 0:s.call(i,e)))throw new Xb("The dial request is blocked by gater.allowDialPeer");if(0===n.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map((({multiaddr:e})=>e.toString())))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e,r);this.log("found multiaddrs for %p in the peer routing",e,n.map((({multiaddr:e})=>e.toString()))),n.push(...t.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){"NoPeerRoutersError"===t.name?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}let o=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of Lc.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(e.multiaddr,(0,M.default)((0,D.default)({dns:this.components.dns},r),{log:this.log}));return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map((e=>({multiaddr:e,isCertified:!1})))})))).flat();if(null!=e){const t="/p2p/"+e.toString();o=o.map((e=>{const r=e.multiaddr.getComponents().pop();return"p2p"!==(null==r?void 0:r.name)?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e}))}const a=o.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),l=new Map;for(const e of a){const t=e.multiaddr.toString(),r=l.get(t);null==r?l.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const u=[...l.values()];if(0===u.length)throw new Qb("The dial request has no valid addresses");const c=[];for(const e of u)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const d=null==this.addressSorter?c.sort(Aw).sort(Cw).sort(kw).sort(_w).sort(Iw):c.sort(this.addressSorter);if(0===d.length)throw new Xb("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",null!=e?e:"unknown peer",o.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",null!=e?e:"unknown peer",d.map((({multiaddr:e})=>e.toString()))),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnLimitedConnection||null!=r.find((e=>!Yp.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}constructor(e,t={}){var r,n,i,s,o,a;(0,L.default)(this,"queue",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,"addressSorter",void 0),(0,L.default)(this,"maxPeerAddrsToDial",void 0),(0,L.default)(this,"maxDialQueueLength",void 0),(0,L.default)(this,"dialTimeout",void 0),(0,L.default)(this,"shutDownController",void 0),(0,L.default)(this,"connections",void 0),(0,L.default)(this,"log",void 0),this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=null!==(r=t.maxPeerAddrsToDial)&&void 0!==r?r:25,this.maxDialQueueLength=null!==(n=t.maxDialQueueLength)&&void 0!==n?n:500,this.dialTimeout=null!==(i=t.dialTimeout)&&void 0!==i?i:1e4,this.connections=null!==(s=t.connections)&&void 0!==s?s:new Wv,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[e,r]of Object.entries(null!==(o=t.resolvers)&&void 0!==o?o:{}))Lc.set(e,r);this.queue=new ww({concurrency:null!==(a=t.maxParallelDials)&&void 0!==a?a:50,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",(e=>{var t;(null===(t=e.detail)||void 0===t?void 0:t.name)!==ki.name&&this.log.error("error in dial queue - %e",e.detail)}))}}class Tw extends bw{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}var Pw,Rw,Lw,Dw,Mw,Nw={};var Ow=ss(Mw?Dw:(Mw=1,Dw=function(){var e,t;return Lw||(Lw=1,e=Nw,t=function(){if(Rw)return Pw;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.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))}return Rw=1,Pw=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((()=>{n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((()=>{n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((()=>{r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){this.attempt(e)},e.prototype.start=function(e){this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var i=this._errors[n],s=i.message,o=(e[s]||0)+1;e[s]=o,o>=r&&(t=i,r=o)}return t},Pw}(),e.operation=r=>{var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<t.retries;i++)n.push(this.createTimeout(i,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(i,t)),n.sort(((e,t)=>e-t)),n},e.createTimeout=(e,t)=>{var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var i in n=[],t)"function"==typeof t[i]&&n.push(i);for(var s=0;s<n.length;s++){var o=n[s],a=t[o];t[o]=function(n){var i=e.operation(r),s=[].slice.call(arguments,1),o=s.pop();s.push((function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))})),i.attempt((()=>{n.apply(t,s)}))}.bind(t,a),t[o].options=r}}),Nw}()));const Uw={}.toString,Fw=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);class Bw extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const $w=(e,t,r)=>{const n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};class qw{async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);zw(t)&&(this.queue.has(e)||this.queue.add((async t=>{await async function(e,t){return new Promise(((r,n)=>{var i,s,o;t=(0,D.default)({},t),null!==(i=(l=t).onFailedAttempt)&&void 0!==i||(l.onFailedAttempt=()=>{}),null!==(s=(u=t).shouldRetry)&&void 0!==s||(u.shouldRetry=()=>!0),null!==(o=(c=t).retries)&&void 0!==o||(c.retries=10);const a=Ow.operation(t),d=()=>{var e;a.stop(),n(null===(e=t.signal)||void 0===e?void 0:e.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",d,{once:!0});const h=()=>{var e;null===(e=t.signal)||void 0===e||e.removeEventListener("abort",d),a.stop()};a.attempt((async i=>{try{const t=await e(i);h(),r(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof Bw)throw e.originalError;if(e instanceof TypeError&&!function(e){var t;return!(!e||(t=e,"[object Error]"!==Uw.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:Fw.has(e.message))}(e))throw e;if($w(e,i,t),await t.shouldRetry(e)||(a.stop(),n(e)),await t.onFailedAttempt(e),!a.retry(e))throw a.mainError()}catch(e){$w(e,i,t),h(),n(e)}}}))}))}((async r=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:null==t?void 0:t.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,r,this.retries,t),t}}),{signal:null==t?void 0:t.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})}),{peerId:e}).catch((async r=>{this.log.error("failed to reconnect to %p - %e",e,r);const n={};[...t.tags.keys()].forEach((e=>{e.startsWith(Ii)&&(n[e]=void 0)})),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})})).catch((async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)})))}start(){this.started=!0}async afterStart(){Promise.resolve().then((async()=>{const e=await this.peerStore.all({filters:[e=>zw(e)]});await Promise.all(e.map((async e=>{await this.connectionManager.openConnection(e.id).catch((e=>{this.log.error(e)}))})))})).catch((e=>{this.log.error(e)}))}stop(){this.started=!1,this.queue.abort()}constructor(e,t={}){var r,n;(0,L.default)(this,"log",void 0),(0,L.default)(this,"queue",void 0),(0,L.default)(this,"started",void 0),(0,L.default)(this,"peerStore",void 0),(0,L.default)(this,"retries",void 0),(0,L.default)(this,"retryInterval",void 0),(0,L.default)(this,"backoffFactor",void 0),(0,L.default)(this,"connectionManager",void 0),(0,L.default)(this,"events",void 0),this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Tw({concurrency:null!==(r=t.maxParallelReconnects)&&void 0!==r?r:5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=null!==(n=t.retries)&&void 0!==n?n:5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}}function zw(e){for(const t of e.tags.keys())if(t.startsWith(Ii))return!0;return!1}const jw=50;let Kw=Symbol.toStringTag;class Vw{async start(){var e,t,r;null===(e=this.metrics)||void 0===e||e.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const r of t)e[r.direction]++;return e}}),null===(t=this.metrics)||void 0===t||t.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const n of this.connections.values())for(const i of n)for(const n of i.streams){var t;const i=`${n.direction} ${null!==(t=n.protocol)&&void 0!==t?t:"unnegotiated"}`;var r;e[i]=(null!==(r=e[i])&&void 0!==r?r:0)+1}return e}}),null===(r=this.metrics)||void 0===r||r.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const i of this.connections.values())for(const s of i){const i={};for(const e of s.streams){var t;const n=`${e.direction} ${null!==(t=e.protocol)&&void 0!==t?t:"unnegotiated"}`;var r;i[n]=(null!==(r=i[n])&&void 0!==r?r:0)+1}var n;for(const[t,r]of Object.entries(i))e[t]=null!==(n=e[t])&&void 0!==n?n:[],e[t].push(r)}const i={};for(let[t,r]of Object.entries(e)){r=r.sort(((e,t)=>e-t));const e=Math.floor(.9*r.length);i[t]=r[e]}return i}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)ts(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStart&&await e.beforeStart()}))),await Promise.all(t.map((async e=>{await e.start()}))),await Promise.all(t.map((async e=>{null!=e.afterStart&&await e.afterStart()})))}(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 async function(...e){const t=[];for(const r of e)ts(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStop&&await e.beforeStop()}))),await Promise.all(t.map((async e=>{await e.stop()}))),await Promise.all(t.map((async e=>{null!=e.afterStop&&await e.afterStop()})))}(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new Pi("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;var r;const n=t.remotePeer,i=!this.connections.has(n),s=null!==(r=this.connections.get(n))&&void 0!==r?r:[];s.push(t),this.connections.set(n,s),null!=n.publicKey&&"RSA"===n.type&&await this.peerStore.patch(n,{publicKey:n.publicKey}),i&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){var t;const{detail:r}=e,n=r.remotePeer,i=(null!==(t=this.connections.get(n))&&void 0!==t?t:[]).filter((e=>e.id!==r.id));this.connections.set(n,i),0===i.length&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){var t;if(null!=e)return null!==(t=this.connections.get(e))&&void 0!==t?t:[];let r=[];for(const e of this.connections.values())r=r.concat(e);return r}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Wi("Not started");this.outboundPendingConnections++;try{var r;null===(r=t.signal)||void 0===r||r.throwIfAborted();const{peerId:s}=dw(e);if(this.peerId.equals(s))throw new Bi("Can not dial self");if(null!=s&&!0!==t.force){var n;this.log("dial %p",s);const e=this.getConnections(s).find((e=>null==e.limits));if(null!=e)return this.log("had an existing non-limited connection to %p",s),null===(n=t.onProgress)||void 0===n||n.call(t,new Jg("dial-queue:already-connected")),e}var i;const o=await this.dialQueue.dial(e,(0,M.default)((0,D.default)({},t),{priority:null!==(i=t.priority)&&void 0!==i?i:jw}));if("open"!==o.status)throw new Di("Remote closed connection during opening");let a=this.connections.get(o.remotePeer);null==a&&(a=[],this.connections.set(o.remotePeer,a));let l=!1;for(const e of a)if(e.id===o.id&&(l=!0),!0!==t.force&&e.id!==o.id&&e.remoteAddr.equals(o.remoteAddr))return o.abort(new $i("Duplicate multiaddr connection")),e;return l||a.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){var r;const n=null!==(r=this.connections.get(e))&&void 0!==r?r:[];await Promise.all(n.map((async e=>{try{await e.close(t)}catch(t){e.abort(t)}})))}async acceptIncomingConnection(e){if(this.deny.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch(r){return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map((t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>Mc(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}constructor(e,t={}){var r,n,i,s,o,a,l,u,c,d,h;if((0,L.default)(this,"started",void 0),(0,L.default)(this,"connections",void 0),(0,L.default)(this,"allow",void 0),(0,L.default)(this,"deny",void 0),(0,L.default)(this,"maxIncomingPendingConnections",void 0),(0,L.default)(this,"incomingPendingConnections",void 0),(0,L.default)(this,"outboundPendingConnections",void 0),(0,L.default)(this,"maxConnections",void 0),(0,L.default)(this,"dialQueue",void 0),(0,L.default)(this,"reconnectQueue",void 0),(0,L.default)(this,"connectionPruner",void 0),(0,L.default)(this,"inboundConnectionRateLimiter",void 0),(0,L.default)(this,"peerStore",void 0),(0,L.default)(this,"metrics",void 0),(0,L.default)(this,"events",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,"peerId",void 0),(0,L.default)(this,Kw,"@libp2p/connection-manager"),this.maxConnections=null!==(n=t.maxConnections)&&void 0!==n?n:100,this.maxConnections<1)throw new Pi("Connection Manager maxConnections must be greater than 0");this.connections=new Wv,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(null!==(i=t.allow)&&void 0!==i?i:[]).map((e=>fw(e))),this.deny=(null!==(s=t.deny)&&void 0!==s?s:[]).map((e=>fw(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=null!==(o=t.maxIncomingPendingConnections)&&void 0!==o?o:10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new lg({points:null!==(a=t.inboundConnectionThreshold)&&void 0!==a?a:5,duration:1}),this.connectionPruner=new pw({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:null===(r=t.allow)||void 0===r?void 0:r.map((e=>Mc(e)))}),this.dialQueue=new xw(e,{addressSorter:t.addressSorter,maxParallelDials:null!==(l=t.maxParallelDials)&&void 0!==l?l:50,maxDialQueueLength:null!==(u=t.maxDialQueueLength)&&void 0!==u?u:500,maxPeerAddrsToDial:null!==(c=t.maxPeerAddrsToDial)&&void 0!==c?c:25,dialTimeout:null!==(d=t.dialTimeout)&&void 0!==d?d:1e4,resolvers:null!==(h=t.resolvers)&&void 0!==h?h:{dnsaddr:Cv},connections:this.connections}),this.reconnectQueue=new qw({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}}class Hw{alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,i=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}constructor(e){(0,L.default)(this,"movingAverage",void 0),(0,L.default)(this,"variance",void 0),(0,L.default)(this,"deviation",void 0),(0,L.default)(this,"forecast",void 0),(0,L.default)(this,"timeSpan",void 0),(0,L.default)(this,"previousTime",void 0),this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}}class Ww{getTimeoutSignal(e={}){var t;let r=Math.round(this.next.movingAverage*(null!==(t=e.timeoutFactor)&&void 0!==t?t:this.timeoutMultiplier));r<this.minTimeout&&(r=this.minTimeout),r>this.maxTimeout&&(r=this.maxTimeout);const n=AbortSignal.timeout(r),i=Ew([e.signal,n]);return i.start=Date.now(),i.timeout=r,i}cleanUp(e){var t,r;const n=Date.now()-e.start;e.aborted?(this.failure.push(n),this.next.push(n*this.failureMultiplier),null===(t=this.metric)||void 0===t||t.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:n})):(this.success.push(n),this.next.push(n),null===(r=this.metric)||void 0===r||r.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:n}))}constructor(e={}){var t,r;(0,L.default)(this,"success",void 0),(0,L.default)(this,"failure",void 0),(0,L.default)(this,"next",void 0),(0,L.default)(this,"metric",void 0),(0,L.default)(this,"timeoutMultiplier",void 0),(0,L.default)(this,"failureMultiplier",void 0),(0,L.default)(this,"minTimeout",void 0),(0,L.default)(this,"maxTimeout",void 0);const n=null!==(r=e.interval)&&void 0!==r?r:5e3;var i,s,o,a;this.success=new Hw(n),this.failure=new Hw(n),this.next=new Hw(n),this.failureMultiplier=null!==(i=e.failureMultiplier)&&void 0!==i?i:2,this.timeoutMultiplier=null!==(s=e.timeoutMultiplier)&&void 0!==s?s:1.2,this.minTimeout=null!==(o=e.minTimeout)&&void 0!==o?o:5e3,this.maxTimeout=null!==(a=e.maxTimeout)&&void 0!==a?a:6e4,null!=e.metricName&&(this.metric=null===(t=e.metrics)||void 0===t?void 0:t.registerMetricGroup(e.metricName))}}let Gw=Symbol.toStringTag,Xw=rs;class Zw{start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((e=>{Promise.resolve().then((async()=>{let t=Date.now();try{var r;const n=this.timeout.getTimeoutSignal({signal:null===(r=this.abortController)||void 0===r?void 0:r.signal}),i=zd(await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}));t=Date.now(),await Promise.all([i.write(iu(32),{signal:n}),i.read({bytes:32,signal:n})]),e.rtt=Date.now()-t,await i.unwrap().close({signal:n})}catch(r){if("UnsupportedProtocolError"!==r.name)throw r;e.rtt=(Date.now()-t)/2}})).catch((t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){var e;null===(e=this.abortController)||void 0===e||e.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}constructor(e,t={}){var r,n,i,s;(0,L.default)(this,"protocol",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,"heartbeatInterval",void 0),(0,L.default)(this,"pingIntervalMs",void 0),(0,L.default)(this,"abortController",void 0),(0,L.default)(this,"timeout",void 0),(0,L.default)(this,"abortConnectionOnPingFailure",void 0),(0,L.default)(this,Gw,"@libp2p/connection-monitor"),(0,L.default)(this,Xw,["@libp2p/connection-monitor"]),this.components=e,this.protocol=`/${null!==(r=t.protocolPrefix)&&void 0!==r?r:"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=null!==(n=t.pingInterval)&&void 0!==n?n:1e4,this.abortConnectionOnPingFailure=null===(i=t.abortConnectionOnPingFailure)||void 0===i||i,this.timeout=new Ww((0,M.default)((0,D.default)({},null!==(s=t.pingTimeout)&&void 0!==s?s:{}),{metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"}))}}let Yw=Symbol.toStringTag;class Qw{isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new Kb("No content routers available");const r=this,n=new Xv;for await(const i of lo(...r.routers.filter((e=>e.findProviders instanceof Function)).map((r=>r.findProviders(e,t)))))null!=i&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),n.has(i.id)||(n.add(i.id),yield i))}async provide(e,t={}){if(0===this.routers.length)throw new Kb("No content routers available");await Promise.all(this.routers.filter((e=>e.provide instanceof Function)).map((async r=>{await r.provide(e,t)})))}async cancelReprovide(e,t={}){if(0===this.routers.length)throw new Kb("No content routers available");await Promise.all(this.routers.filter((e=>e.cancelReprovide instanceof Function)).map((async r=>{await r.cancelReprovide(e,t)})))}async put(e,t,r){if(!this.isStarted())throw new Wi;await Promise.all(this.routers.filter((e=>e.put instanceof Function)).map((async n=>{await n.put(e,t,r)})))}async get(e,t){if(!this.isStarted())throw new Wi;return Promise.any(this.routers.filter((e=>e.get instanceof Function)).map((async r=>r.get(e,t))))}constructor(e,t){var r,n,i,s,o,a,l,u,c,d,h;(0,L.default)(this,"routers",void 0),(0,L.default)(this,"started",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,Yw,"@libp2p/content-routing"),this.routers=null!==(a=t.routers)&&void 0!==a?a:[],this.started=!1,this.components=e,this.findProviders=null!==(l=null===(r=e.metrics)||void 0===r?void 0:r.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>(0,M.default)((0,D.default)({},t),{cid:e.toString()}),getAttributesFromYieldedValue:(e,t)=>(0,M.default)((0,D.default)({},t),{providers:[...Array.isArray(t.providers)?t.providers:[],e.id.toString()]})}))&&void 0!==l?l:this.findProviders,this.provide=null!==(u=null===(n=e.metrics)||void 0===n?void 0:n.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>(0,M.default)((0,D.default)({},t),{cid:e.toString()})}))&&void 0!==u?u:this.provide,this.cancelReprovide=null!==(c=null===(i=e.metrics)||void 0===i?void 0:i.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>(0,M.default)((0,D.default)({},t),{cid:e.toString()})}))&&void 0!==c?c:this.cancelReprovide,this.put=null!==(d=null===(s=e.metrics)||void 0===s?void 0:s.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([e])=>({key:ri(e,"base36")})}))&&void 0!==d?d:this.put,this.get=null!==(h=null===(o=e.metrics)||void 0===o?void 0:o.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:ri(e,"base36")})}))&&void 0!==h?h:this.get}}let Jw=Symbol.toStringTag;class eE{async findPeer(e,t){if(0===this.routers.length)throw new Vb("No peer routers available");if(e.toString()===this.peerId.toString())throw new Hb("Should not try to find self");const r=this,n=lo(...this.routers.filter((e=>e.findPeer instanceof Function)).map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs},t),e;throw new Fi}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Vb("No peer routers available");const r=this,n=oy(1024);for await(const i of async function*(e,t={}){var r;let n=null!==(r=t.concurrency)&&void 0!==r?r:1/0;var i;n<1&&(n=1/0);const s=null!==(i=t.ordered)&&void 0!==i&&i,o=new EventTarget,a=[];let l,u=Qs(),c=Qs(),d=!1,h=!1;function f(){var e;return s?null===(e=a[0])||void 0===e?void 0:e.done:!!a.find((e=>e.done))}function*p(){for(;a.length>0&&a[0].done;){const e=a[0];if(a.shift(),!e.ok)throw h=!0,u.resolve(),e.err;yield e.value,u.resolve()}}function*g(){for(;f();)for(let e=0;e<a.length;e++)if(a[e].done){const t=a[e];if(a.splice(e,1),e--,!t.ok)throw h=!0,u.resolve(),t.err;yield t.value,u.resolve()}}for(o.addEventListener("task-complete",(()=>{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(a.length===n&&(u=Qs(),await u.promise),h)break;const e={done:!1};a.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,o.dispatchEvent(new Hf("task-complete"))}),(t=>{e.done=!0,e.err=t,o.dispatchEvent(new Hf("task-complete"))}))}d=!0,o.dispatchEvent(new Hf("task-complete"))}catch(e){l=e,o.dispatchEvent(new Hf("task-complete"))}}));;){if(f()||(c=Qs(),await c.promise),null!=l)throw l;if(s?yield*p():yield*g(),null!=l)throw l;if(d&&0===a.length)break}}(async function*(){const n=lo(...r.routers.filter((e=>e.getClosestPeers instanceof Function)).map((r=>r.getClosestPeers(e,t))));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,(0,M.default)((0,D.default)({},t),{useCache:!1}))}catch(e){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=i&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),n.has(i.id.toMultihash().bytes)||(n.add(i.id.toMultihash().bytes),yield i))}constructor(e,t={}){var r,n,i,s,o;(0,L.default)(this,"log",void 0),(0,L.default)(this,"peerId",void 0),(0,L.default)(this,"peerStore",void 0),(0,L.default)(this,"routers",void 0),(0,L.default)(this,Jw,"@libp2p/peer-routing"),this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=null!==(i=t.routers)&&void 0!==i?i:[],this.findPeer=null!==(s=null===(r=e.metrics)||void 0===r?void 0:r.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>(0,M.default)((0,D.default)({},t),{peer:e.toString()})}))&&void 0!==s?s:this.findPeer,this.getClosestPeers=null!==(o=null===(n=e.metrics)||void 0===n?void 0:n.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>(0,M.default)((0,D.default)({},t),{key:ri(e,"base36")}),getAttributesFromYieldedValue:(e,t)=>(0,M.default)((0,D.default)({},t),{peers:[...Array.isArray(t.peers)?t.peers:[],e.id.toString()]})}))&&void 0!==o?o:this.getClosestPeers}}let tE=Symbol.toStringTag;class rE extends es{start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=Ew([this.shutdownController.signal,null==e?void 0:e.signal]);try{for(;;){var r;null===(r=this.needNext)||void 0===r||r.resolve(),this.needNext=Qs();const e=await uy(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{var n;t.clear(),this.walkers--,0===this.walkers&&(null===(n=this.walkController)||void 0===n||n.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=Ew([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=iu(32);let n=Date.now();for await(const i of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:i}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await io(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("random walk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).catch((e=>{this.log.error("random walk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1}))}constructor(e){super(),(0,L.default)(this,"peerRouting",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,"walking",void 0),(0,L.default)(this,"walkers",void 0),(0,L.default)(this,"shutdownController",void 0),(0,L.default)(this,"walkController",void 0),(0,L.default)(this,"needNext",void 0),(0,L.default)(this,tE,"@libp2p/random-walk"),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}}let nE=Symbol.toStringTag;class iE{getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new Wb("No handler registered for protocol "+e);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e)&&!0!==(null==r?void 0:r.force))throw new Gb("Handler already registered for protocol "+e);const n=vm.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},r)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach((e=>{this.handlers.delete(e)})),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(null==t)throw new Pi("invalid topology");const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail,r={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,r).then((e=>{for(const s of e.protocols){var r,n,i;const e=this.topologies.get(s);if(null!=e)for(const s of e.values())!1!==(null===(r=s.filter)||void 0===r?void 0:r.has(t))&&(null===(n=s.filter)||void 0===n||n.remove(t),null===(i=s.onDisconnect)||void 0===i||i.call(s,t))}})).catch((e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){var t;const{peer:r,previous:n}=e.detail,i=(null!==(t=null==n?void 0:n.protocols)&&void 0!==t?t:[]).filter((e=>!r.protocols.includes(e)));for(const e of i){var s,o,a;const t=this.topologies.get(e);if(null!=t)for(const e of t.values())!1!==(null===(s=e.filter)||void 0===s?void 0:s.has(r.id))&&(null===(o=e.filter)||void 0===o||o.remove(r.id),null===(a=e.onDisconnect)||void 0===a||a.call(e,r.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){var i,s,o;const t=this.topologies.get(e);if(null!=t)for(const e of t.values())null!=r.limits&&!0!==e.notifyOnLimitedConnection||!0!==(null===(i=e.filter)||void 0===i?void 0:i.has(n))&&(null===(s=e.filter)||void 0===s||s.add(n),null===(o=e.onConnect)||void 0===o||o.call(e,n,r))}}constructor(e){var t;(0,L.default)(this,"log",void 0),(0,L.default)(this,"topologies",void 0),(0,L.default)(this,"handlers",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,nE,"@libp2p/registrar"),this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,null===(t=e.metrics)||void 0===t||t.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const e={};for(const[t,r]of this.topologies)e[t]=r.size;return e}}),this.handlers=kb({name:"libp2p_registrar_protocol_handlers",metrics:e.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)}}let sE=Symbol.toStringTag;class oE{add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Pi("Transport must have a valid tag");if(this.transports.has(t))throw new Pi("There is already a transport with the tag "+t);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){var r;const n=this.dialTransportForMultiaddr(e);if(null==n)throw new nw("No transport available for address "+e);return null==t||null===(r=t.onProgress)||void 0===r||r.call(t,new Jg("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,(0,M.default)((0,D.default)({},t),{upgrader:this.components.upgrader}))}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Wi("Not started");if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach((e=>{t.errors.set(e.toString(),new Zb)}));const r=[];for(const[i,s]of this.transports.entries()){const o=s.listenFilter(e);for(const e of o){this.log("creating listener for %s on %a",i,e);const o=s.createListener({upgrader:this.components.upgrader});var n;let a=null!==(n=this.listeners.get(i))&&void 0!==n?n:[];null==a&&(a=[],this.listeners.set(i,a)),a.push(o),o.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:o})})),o.addEventListener("close",(()=>{const e=a.findIndex((e=>e===o));a.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:o})})),Lp.matches(e)?t.ipv4.attempts++:Dp.matches(e)&&t.ipv6.attempts++,r.push(o.listen(e).then((()=>{t.errors.delete(e.toString()),Lp.matches(e)&&t.ipv4.success++,Dp.matches(e)&&t.ipv6.success++}),(r=>{throw this.log.error("transport %s could not listen on address %a - %e",i,e,r),t.errors.set(e.toString(),r),r})))}}const i=await Promise.allSettled(r);if(!(i.length>0&&i.every((e=>"fulfilled"===e.status))))if(this.ipv6Unsupported(t))this.log("all IPv4 addresses succeed but all IPv6 failed");else{var s;if(this.faultTolerance!==Ci.NO_FATAL)throw new Yb("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:\n"+[...t.errors.entries()].map((([e,t])=>`\n  ${e}: ${(""+(null!==(s=t.stack)&&void 0!==s?s:t)).split("\n").join("\n  ")}\n`)).join(""));this.log("failed to listen on any address but fault tolerance allows this")}}ipv6Unsupported(e){if(0===e.ipv4.attempts||0===e.ipv6.attempts)return!1;const t=e.ipv4.attempts===e.ipv4.success,r=0===e.ipv6.success;return t&&r}async remove(e){var t;const r=null!==(t=this.listeners.get(e))&&void 0!==t?t:[];this.log.trace("removing transport %s",e);const n=[];for(this.log.trace("closing listeners for %s",e);r.length>0;){const e=r.pop();null!=e&&n.push(e.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}constructor(e,t={}){var r;(0,L.default)(this,"log",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,"transports",void 0),(0,L.default)(this,"listeners",void 0),(0,L.default)(this,"faultTolerance",void 0),(0,L.default)(this,"started",void 0),(0,L.default)(this,sE,"@libp2p/transport-manager"),this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=kb({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=kb({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=null!==(r=t.faultTolerance)&&void 0!==r?r:Ci.FATAL_ALL}}const aE="/multistream/1.0.0",lE=1024,uE=Zt("\n");async function cE(e,t,r){await e.write(t,r)}async function dE(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==uE[0])throw t.log.error("Invalid mss message - missing newline",r),new Ki("Missing newline");return r.sublist(0,-1)}(e,t);return ri(r.subarray())}async function hE(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),i=e.source;let s=!1,o=!1;const a=Qs();let l=!1,u=!1;const c=Qs();let d=!1,h=!1;const f=Qs(),p=Hd({sink:n,source:i},(0,M.default)((0,D.default)({},r),{maxDataLength:lE}));async function g(){if(o)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;o=!0;try{l||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(u)await c.promise;else{u=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',aE,t),await p.writeV([Zt(aE+"\n"),Zt(t+"\n")]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',aE,t)}finally{l=!0,u=!1,c.resolve()}}}()),d||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(h)await f.promise;else{h=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await dE(p,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===aE&&(e=await dE(p,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new ji("protocol selection failed")}finally{d=!0,h=!1,f.resolve()}}}())}finally{o=!1,s=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=p.unwrap();await n(async function*(){let n=!1;for await(const i of e){if(u&&await c.promise,l)yield i;else{u=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',aE,t,i.byteLength);const e=t+"\n";yield new qs(Uint8Array.from([19]),Zt(aE+"\n"),ae(e.length),Zt(e),i).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',aE,t,i.byteLength),l=!0,u=!1,c.resolve(),g().catch((e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)}))}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*p.unwrap().source}(),null!=e.closeRead){const t=e.closeRead.bind(e);e.closeRead=async e=>{s||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{s||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];u&&r.push(c.promise),h&&r.push(f.promise),r.length>0?await io(Promise.all(r),null==e?void 0:e.signal):(s=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=Hd(e,(0,M.default)((0,D.default)({},r),{maxDataLength:lE})),i=t.shift();if(null==i)throw Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',aE,i);const s=Zt(aE+"\n"),o=Zt(i+"\n");await async function(e,t,r){await e.writeV(t,r)}(n,[s,o],r),r.log.trace("select: reading multistream-select header");let a=await dE(n,r);if(r.log.trace('select: read "%s"',a),a===aE&&(r.log.trace("select: reading protocol response"),a=await dE(n,r),r.log.trace('select: read "%s"',a)),a===i)return{stream:n.unwrap(),protocol:i};for(const e of t){r.log.trace('select: write "%s"',e),await cE(n,Zt(e+"\n"),r),r.log.trace("select: reading protocol response");const t=await dE(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new ji("protocol selection failed")}async function fE(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=Hd(e,(0,M.default)((0,D.default)({},r),{maxDataLength:lE,maxLengthLength:2}));for(;;){r.log.trace("handle: reading incoming string");const e=await dE(n,r);if(r.log.trace('handle: read "%s"',e),e!==aE){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await cE(n,Zt(e+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log.trace('handle: respond with "na" for "%s"',e),await cE(n,Zt("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const i=new qs(...t.map((e=>Ud.single(Zt(e+"\n")))),Zt("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await cE(n,i,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',aE,e),await cE(n,Zt(aE+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',aE,e)}}let pE=Symbol.toStringTag,gE=yi;class mE{get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Li("the connection is being closed");if("closed"===this.status)throw new Di("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=this.limits&&!0!==(null==t?void 0:t.runOnLimitedConnection))throw new Xi("Cannot open protocol stream on limited connection");const r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){const t=AbortSignal.timeout(500);e=(0,M.default)((0,D.default)({},e),{signal:t})}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}constructor(e){(0,L.default)(this,"id",void 0),(0,L.default)(this,"remoteAddr",void 0),(0,L.default)(this,"remotePeer",void 0),(0,L.default)(this,"direction",void 0),(0,L.default)(this,"timeline",void 0),(0,L.default)(this,"multiplexer",void 0),(0,L.default)(this,"encryption",void 0),(0,L.default)(this,"status",void 0),(0,L.default)(this,"limits",void 0),(0,L.default)(this,"log",void 0),(0,L.default)(this,"tags",void 0),(0,L.default)(this,"_newStream",void 0),(0,L.default)(this,"_close",void 0),(0,L.default)(this,"_abort",void 0),(0,L.default)(this,"_getStreams",void 0),(0,L.default)(this,pE,"Connection"),(0,L.default)(this,gE,!0);const{remoteAddr:t,remotePeer:r,newStream:n,close:i,abort:s,getStreams:o}=e;this.id=`${parseInt(1e9*Math.random()+"").toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate("/p2p/"+this.remotePeer)),this._newStream=n,this._close=i,this._abort=s,this._getStreams=o,this.tags=[]}}function vE(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}let yE=Symbol.toStringTag;class bE{async shouldBlockConnection(e,...t){const r=this.components.connectionGater[e];if(null!=r&&!0===await r.apply(this.components.connectionGater,t))throw new Jb("The multiaddr connection is blocked by gater."+e)}createInboundAbortSignal(e){return Ew([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}async upgradeInbound(e,t){let r=!1;const n=this.createInboundAbortSignal(t.signal);try{var i;if(null===(i=this.metrics.dials)||void 0===i||i.increment({inbound:!0}),r=await io(this.components.connectionManager.acceptIncomingConnection(e),n),!r)throw new ew("Connection denied");await io(this.shouldBlockConnection("denyInboundConnection",e),n),await this._performUpgrade(e,"inbound",(0,M.default)((0,D.default)({},t),{signal:n}))}catch(e){var s,o,a;throw null===(s=this.metrics.errors)||void 0===s||s.increment({inbound:!0}),null===(o=this.metrics.inboundErrors)||void 0===o||o.increment({[null!==(a=e.name)&&void 0!==a?a:"Error"]:!0}),e}finally{n.clear(),r&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{var r;null===(r=this.metrics.dials)||void 0===r||r.increment({outbound:!0});const n=e.remoteAddr.getPeerId();let i;null!=n&&(i=qu(n),await io(this.shouldBlockConnection("denyOutboundConnection",i,e),t.signal));let s="outbound";return!1===t.initiator&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(e){var n,i,s;throw null===(n=this.metrics.errors)||void 0===n||n.increment({outbound:!0}),null===(i=this.metrics.outboundErrors)||void 0===i||i.increment({[null!==(s=e.name)&&void 0!==s?s:"Error"]:!0}),e}}async _performUpgrade(e,t,r){var n;let i,s,o,a,l;null===(n=this.components.metrics)||void 0===n||n.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let u=e;if(!0!==(null==r?void 0:r.skipProtection)){const n=this.components.connectionProtector;null!=n&&(e.log("protecting the %s connection",t),u=await n.protect(e,r))}try{if(i=u,!0!==(null==r?void 0:r.skipEncryption)){var c;null==r||null===(c=r.onProgress)||void 0===c||c.call(r,new Jg(`upgrader:encrypt-${t}-connection`)),({conn:i,remotePeer:s,protocol:l,streamMuxer:a}=await("inbound"===t?this._encryptInbound(u,r):this._encryptOutbound(u,r)));const e=(0,D.default)({},u,i);await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e)}else{const r=e.remoteAddr.getPeerId();if(null==r)throw new $i(t+" connection that skipped encryption must have a peer id");const n=qu(r);l="native",s=n}if(s.equals(this.components.peerId)){const t=new Bi("Can not dial self");throw e.abort(t),t}if(o=i,null!=(null==r?void 0:r.muxerFactory))a=r.muxerFactory;else if(null==a&&this.streamMuxers.size>0){var d;null==r||null===(d=r.onProgress)||void 0===d||d.call(r,new Jg(`upgrader:multiplex-${t}-connection`));const e=await("inbound"===t?this._multiplexInbound((0,D.default)({},u,i),this.streamMuxers,r):this._multiplexOutbound((0,D.default)({},u,i),this.streamMuxers,r));a=e.muxerFactory,o=e.stream}}catch(r){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===t?"from":"to",e.remoteAddr,r),r}return await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:l,direction:t,maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s,limits:null==r?void 0:r.limits})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:i,remotePeer:s,muxerFactory:o,limits:a}=e;let l,u,c;null!=o&&(l=o.createStreamMuxer({direction:r,onIncomingStream:e=>{if(null==c)return;const t=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then((async()=>{var r;const n=this.components.registrar.getProtocols(),{stream:i,protocol:o}=await fE(e,n,{signal:t,log:e.log,yieldBytes:!1});if(null==c)return;c.log("incoming stream opened on %s",o);const a=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(o,this.components.registrar);if(vE(o,"inbound",c)===a){const t=new Zi(`Too many inbound protocol streams for protocol "${o}" - limit ${a}`);throw e.abort(t),t}e.source=i.source,e.sink=i.sink,e.protocol=o,null!=i.closeWrite&&(e.closeWrite=i.closeWrite),null!=i.closeRead&&(e.closeRead=i.closeRead),null!=i.close&&(e.close=i.close),await this.components.peerStore.merge(s,{protocols:[o]},{signal:t}),null===(r=this.components.metrics)||void 0===r||r.trackProtocolStream(e,c),this._onStream({connection:c,stream:e,protocol:o})})).catch((async r=>{c.log.error("error handling incoming stream id %s - %e",e.id,r),null==e.timeline.close&&await e.close({signal:t}).catch((t=>e.abort(t)))}))}}),u=async(t,n={})=>{if(null==l)throw new tw("Connection is not multiplexed");c.log.trace("starting new stream for protocols %s",t);const i=await l.newStream();c.log.trace("started new stream %s for protocols %s",i.id,t);try{var o;if(null==n.signal){i.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);const e=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);n=(0,M.default)((0,D.default)({},n),{signal:e})}i.log.trace("selecting protocol from protocols %s",t);const{stream:e,protocol:r}=await hE(i,t,(0,M.default)((0,D.default)({},n),{log:i.log,yieldBytes:!0}));i.log.trace("selected protocol %s",r);const a=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}var n;return null!==(n=r.maxOutboundStreams)&&void 0!==n?n:64}(r,this.components.registrar,n),l=vE(r,"outbound",c);if(l>=a){const e=new Yi(`Too many outbound protocol streams for protocol "${r}" - ${l}/${a}`);throw i.abort(e),e}return await this.components.peerStore.merge(s,{protocols:[r]}),i.source=e.source,i.sink=e.sink,i.protocol=r,null!=e.closeWrite&&(i.closeWrite=e.closeWrite),null!=e.closeRead&&(i.closeRead=e.closeRead),null!=e.close&&(i.close=e.close),null===(o=this.components.metrics)||void 0===o||o.trackProtocolStream(i,c),i}catch(n){throw c.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===r?"from":"to",e.maConn.remoteAddr,t,n),null==i.timeline.close&&i.abort(n),n}},Promise.all([l.sink(i.source),i.sink(l.source)]).catch((e=>{c.log.error("error piping data through muxer - %e",e)})));const d=n.timeline;var h,f;return n.timeline=new Proxy(d,{set:(...e)=>("close"===e[1]&&null!=e[2]&&null==d.close&&(async()=>{try{"open"===c.status&&await c.close()}catch(e){c.log.error("error closing connection after timeline close %e",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:c})}})().catch((e=>{c.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),h={remoteAddr:n.remoteAddr,remotePeer:s,status:"open",direction:r,timeline:n.timeline,multiplexer:null==l?void 0:l.protocol,encryption:t,limits:a,logger:this.components.logger,newStream:null!=u?u:()=>{throw new tw("Connection is not multiplexed")},getStreams:()=>null!==(f=null==l?void 0:l.streams)&&void 0!==f?f:[],async close(e){await(null==l?void 0:l.close(e)),await n.close(e)},abort(e){n.abort(e),null==l||l.abort(e)}},c=new mE(h),this.events.safeDispatchEvent("connection:open",{detail:c}),c.__maConnTimeline=d,c}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:i,options:s}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==s.runOnLimitedConnection)throw new Xi("Cannot open protocol stream on limited connection");i({connection:t,stream:r})}async _encryptInbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{const{stream:n,protocol:i}=await fE(e,r,(0,M.default)((0,D.default)({},t),{log:e.log})),s=this.connectionEncrypters.get(i);if(null==s)throw new rw("no crypto module found for "+i);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,i),(0,M.default)((0,D.default)({},await s.secureInbound(n,t)),{protocol:i})}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new rw(t.message)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:i}=await hE(e,r,(0,M.default)((0,D.default)({},t),{log:e.log,yieldBytes:!0})),s=this.connectionEncrypters.get(i);if(null==s)throw new rw("no crypto module found for "+i);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,i),(0,M.default)((0,D.default)({},await s.secureOutbound(n,t)),{protocol:i})}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new rw(t.message)}}async _multiplexOutbound(e,t,r){const n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);const{stream:i,protocol:s}=await hE(e,n,(0,M.default)((0,D.default)({},r),{log:e.log,yieldBytes:!0}));return e.log("selected %s as muxer protocol",s),{stream:i,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new tw(t+"")}}async _multiplexInbound(e,t,r){const n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{const{stream:i,protocol:s}=await fE(e,n,(0,M.default)((0,D.default)({},r),{log:e.log}));return{stream:i,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new tw(t+"")}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}constructor(e,t){var r,n,i,s,o,a,l;(0,L.default)(this,"components",void 0),(0,L.default)(this,"connectionEncrypters",void 0),(0,L.default)(this,"streamMuxers",void 0),(0,L.default)(this,"inboundUpgradeTimeout",void 0),(0,L.default)(this,"inboundStreamProtocolNegotiationTimeout",void 0),(0,L.default)(this,"outboundStreamProtocolNegotiationTimeout",void 0),(0,L.default)(this,"events",void 0),(0,L.default)(this,"metrics",void 0),(0,L.default)(this,yE,"@libp2p/upgrader"),this.components=e,this.connectionEncrypters=kb({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=kb({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=null!==(o=t.inboundUpgradeTimeout)&&void 0!==o?o:1e4,this.inboundStreamProtocolNegotiationTimeout=null!==(a=t.inboundStreamProtocolNegotiationTimeout)&&void 0!==a?a:1e4,this.outboundStreamProtocolNegotiationTimeout=null!==(l=t.outboundStreamProtocolNegotiationTimeout)&&void 0!==l?l:1e4,this.events=e.events,this.metrics={dials:null===(r=e.metrics)||void 0===r?void 0:r.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:null===(n=e.metrics)||void 0===n?void 0:n.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:null===(i=e.metrics)||void 0===i?void 0:i.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:null===(s=e.metrics)||void 0===s?void 0:s.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}}const wE="2.8.11",EE="js-libp2p";function SE(e,t){return`${null!=e?e:EE}/${null!=t?t:wE} browser/${globalThis.navigator.userAgent}`}var AE=new WeakSet;class IE extends es{configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{var e,t,r,n;await(null===(t=(e=this.components).beforeStart)||void 0===t?void 0:t.call(e)),await this.components.start(),await(null===(n=(r=this.components).afterStart)||void 0===n?void 0:n.call(r)),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){var e,t,r,n;"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(null===(t=(e=this.components).beforeStop)||void 0===t?void 0:t.call(e)),await this.components.stop(),await(null===(n=(r=this.components).afterStop)||void 0===n?void 0:n.call(r)),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new Xv;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,(0,D.default)({priority:75},t))}async dialProtocol(e,t,r={}){if(null==t)throw new Pi("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Pi("no protocols were provided to open a stream");return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){var r;Dc(e)&&(e=qu(null!==(r=e.getPeerId())&&void 0!==r?r:"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const r=await this.peerStore.get(e,t);if(null!=r.id.publicKey)return r.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}const r=Ms([Zt("/pk/"),e.toMultihash().bytes]),n=Ru(await this.contentRouting.get(r,t));return await this.peerStore.patch(e,{publicKey:n},t),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.handle(e,t,r)})))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.unhandle(e,t)})))}async register(e,t,r){return this.components.registrar.register(e,t,r)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}constructor(e){var t,r,n,i,s,o,a,l,u,c;super(),(0,R.default)(this,AE),(0,L.default)(this,"peerId",void 0),(0,L.default)(this,"peerStore",void 0),(0,L.default)(this,"contentRouting",void 0),(0,L.default)(this,"peerRouting",void 0),(0,L.default)(this,"metrics",void 0),(0,L.default)(this,"services",void 0),(0,L.default)(this,"logger",void 0),(0,L.default)(this,"status",void 0),(0,L.default)(this,"components",void 0),(0,L.default)(this,"log",void 0),this.status="stopped";const d=new es,h=d.dispatchEvent.bind(d);var f,p,g,m,v;d.dispatchEvent=e=>{const t=h(e),r=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||r},this.peerId=e.peerId,this.logger=null!==(f=e.logger)&&void 0!==f?f:qv(),this.log=this.logger.forComponent("libp2p"),this.services={};const y=null!==(p=null===(t=e.nodeInfo)||void 0===t?void 0:t.name)&&void 0!==p?p:EE,b=null!==(g=null===(r=e.nodeInfo)||void 0===r?void 0:r.version)&&void 0!==g?g:wE,w=this.components=function(e={}){const t=new iw(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!ow.includes(r)){const e=t.components[r];if(null==e&&!sw.includes(r))throw new zb(r+" not set");return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:y,version:b,userAgent:null!==(m=null===(n=e.nodeInfo)||void 0===n?void 0:n.userAgent)&&void 0!==m?m:SE(y,b)},logger:this.logger,events:d,datastore:null!==(v=e.datastore)&&void 0!==v?v:new _b,connectionGater:cw(e.connectionGater),dns:e.dns});var E,S,A,I,_;null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new yb(e,t)}(w,(0,D.default)({addressFilter:this.components.connectionGater.filterMultiaddrForPeer},e.peerStore))),w.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};w.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(w)),this.components.upgrader=new bE(this.components,{connectionEncrypters:(null!==(E=e.connectionEncrypters)&&void 0!==E?E:[]).map(((e,t)=>this.configureComponent("connection-encryption-"+t,e(this.components)))),streamMuxers:(null!==(S=e.streamMuxers)&&void 0!==S?S:[]).map(((e,t)=>this.configureComponent("stream-muxers-"+t,e(this.components)))),inboundUpgradeTimeout:null===(i=e.connectionManager)||void 0===i?void 0:i.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:null!==(A=null===(s=e.connectionManager)||void 0===s?void 0:s.inboundStreamProtocolNegotiationTimeout)&&void 0!==A?A:null===(o=e.connectionManager)||void 0===o?void 0:o.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:null!==(I=null===(a=e.connectionManager)||void 0===a?void 0:a.outboundStreamProtocolNegotiationTimeout)&&void 0!==I?I:null===(l=e.connectionManager)||void 0===l?void 0:l.protocolNegotiationTimeout}),this.configureComponent("transportManager",new oE(this.components,e.transportManager)),this.configureComponent("connectionManager",new Vw(this.components,e.connectionManager)),!1!==(null===(u=e.connectionMonitor)||void 0===u?void 0:u.enabled)&&this.configureComponent("connectionMonitor",new Zw(this.components,e.connectionMonitor)),this.configureComponent("registrar",new iE(this.components)),this.configureComponent("addressManager",new $b(this.components,e.addresses));const C=(null!==(_=e.peerRouters)&&void 0!==_?_:[]).map(((e,t)=>this.configureComponent("peer-router-"+t,e(this.components))));var k;this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new eE(this.components,{routers:C}));const x=(null!==(k=e.contentRouters)&&void 0!==k?k:[]).map(((e,t)=>this.configureComponent("content-router-"+t,e(this.components))));var T;if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Qw(this.components,{routers:x})),this.configureComponent("randomWalk",new rE(this.components)),(null!==(T=e.peerDiscovery)&&void 0!==T?T:[]).forEach(((e,t)=>{this.configureComponent("peer-discovery-"+t,e(this.components)).addEventListener("peer",(e=>{(0,P.default)(this,AE,_E).call(this,e)}))})),null===(c=e.transports)||void 0===c||c.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent("transport-"+t,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){var M,N;const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[bi]&&(this.log("registering service %s for content routing",t),x.push(r[bi])),null!=r[Ai]&&(this.log("registering service %s for peer routing",t),C.push(r[Ai])),null!=r[wi]&&(this.log("registering service %s for peer discovery",t),null===(N=(M=r[wi]).addEventListener)||void 0===N||N.call(M,"peer",(e=>{(0,P.default)(this,AE,_E).call(this,e)})))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of aw(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of lw(r))if(!0!==t[e])throw new jb(`Service "${uw(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(w)}}function _E(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error("peer discovery mechanism discovered self")}function CE(){try{return!1}catch(e){return!1}}const kE="enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",xE="enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",TE=Ts.BOOTSTRAP,PE="Invalid record id";var RE=Object.freeze({__proto__:null,default:{}});const LE=BigInt(0),DE=BigInt(1),ME=BigInt(2),NE=BigInt(3),OE=BigInt(8),UE=Object.freeze({a:LE,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:DE,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),FE=(e,t)=>(e+t/ME)/t,BE={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=UE,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-DE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=FE(s*e,t),l=FE(-n*e,t);let u=gS(e-a*r-l*i,t),c=gS(-a*n-l*s,t);const d=u>o,h=c>o;if(d&&(u=t-u),h&&(c=t-c),u>o||c>o)throw Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:d,k1:u,k2neg:h,k2:c}}},$E=32,qE=32;function zE(e){const{a:t,b:r}=UE,n=gS(e*e),i=gS(n*e);return gS(i+t*e+r)}const jE=UE.a===LE;class KE extends Error{constructor(e){super(e)}}function VE(e){if(!(e instanceof HE))throw new TypeError("JacobianPoint expected")}class HE{static fromAffine(e){if(!(e instanceof XE))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(XE.ZERO)?HE.ZERO:new HE(e.x,e.y,DE)}static toAffineBatch(e){const t=function(e,t=UE.P){const r=Array(e.length),n=vS(e.reduce(((e,n,i)=>n===LE?e:(r[i]=e,gS(e*n,t))),DE),t);return e.reduceRight(((e,n,i)=>n===LE?e:(r[i]=gS(e*r[i],t),gS(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return HE.toAffineBatch(e).map(HE.fromAffine)}equals(e){VE(e);const{x:t,y:r,z:n}=this,{x:i,y:s,z:o}=e,a=gS(n*n),l=gS(o*o),u=gS(t*l),c=gS(i*a),d=gS(gS(r*o)*l),h=gS(gS(s*n)*a);return u===c&&d===h}negate(){return new HE(this.x,gS(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=gS(e*e),i=gS(t*t),s=gS(i*i),o=e+i,a=gS(ME*(gS(o*o)-n-s)),l=gS(NE*n),u=gS(l*l),c=gS(u-ME*a),d=gS(l*(a-c)-OE*s),h=gS(ME*t*r);return new HE(c,d,h)}add(e){VE(e);const{x:t,y:r,z:n}=this,{x:i,y:s,z:o}=e;if(i===LE||s===LE)return this;if(t===LE||r===LE)return e;const a=gS(n*n),l=gS(o*o),u=gS(t*l),c=gS(i*a),d=gS(gS(r*o)*l),h=gS(gS(s*n)*a),f=gS(c-u),p=gS(h-d);if(f===LE)return p===LE?this.double():HE.ZERO;const g=gS(f*f),m=gS(f*g),v=gS(u*g),y=gS(p*p-m-ME*v),b=gS(p*(v-y)-d*m),w=gS(n*o*f);return new HE(y,b,w)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=HE.ZERO;if("bigint"==typeof e&&e===LE)return t;let r=pS(e);if(r===DE)return this;if(!jE){let e=t,n=this;for(;r>LE;)r&DE&&(e=e.add(n)),n=n.double(),r>>=DE;return e}let{k1neg:n,k1:i,k2neg:s,k2:o}=BE.splitScalar(r),a=t,l=t,u=this;for(;i>LE||o>LE;)i&DE&&(a=a.add(u)),o&DE&&(l=l.add(u)),u=u.double(),i>>=DE,o>>=DE;return n&&(a=a.negate()),s&&(l=l.negate()),l=new HE(gS(l.x*BE.beta),l.y,l.z),a.add(l)}precomputeWindow(e){const t=jE?128/e+1:256/e+1,r=[];let n=this,i=n;for(let s=0;s<t;s++){i=n,r.push(i);for(let t=1;t<2**(e-1);t++)i=i.add(n),r.push(i);n=i.double()}return r}wNAF(e,t){!t&&this.equals(HE.BASE)&&(t=XE.BASE);const r=t&&t._WINDOW_SIZE||1;if(256%r)throw Error("Point#wNAF: Invalid precomputation window, must be power of 2");let n=t&&GE.get(t);n||(n=this.precomputeWindow(r),t&&1!==r&&(n=HE.normalizeZ(n),GE.set(t,n)));let i=HE.ZERO,s=HE.BASE;const o=1+(jE?128/r:256/r),a=2**(r-1),l=BigInt(2**r-1),u=2**r,c=BigInt(r);for(let t=0;t<o;t++){const r=t*a;let o=Number(e&l);e>>=c,o>a&&(o-=u,e+=DE);const d=r,h=r+Math.abs(o)-1,f=t%2!=0,p=o<0;0===o?s=s.add(WE(f,n[d])):i=i.add(WE(p,n[h]))}return{p:i,f:s}}multiply(e,t){let r,n,i=pS(e);if(jE){const{k1neg:e,k1:s,k2neg:o,k2:a}=BE.splitScalar(i);let{p:l,f:u}=this.wNAF(s,t),{p:c,f:d}=this.wNAF(a,t);l=WE(e,l),c=WE(o,c),c=new HE(gS(c.x*BE.beta),c.y,c.z),r=l.add(c),n=u.add(d)}else{const{p:e,f:s}=this.wNAF(i,t);r=e,n=s}return HE.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,i=this.equals(HE.ZERO);null==e&&(e=i?OE:vS(n));const s=e,o=gS(s*s),a=gS(o*s),l=gS(t*o),u=gS(r*a),c=gS(n*s);if(i)return XE.ZERO;if(c!==DE)throw Error("invZ was invalid");return new XE(l,u)}constructor(e,t,r){this.x=e,this.y=t,this.z=r}}function WE(e,t){const r=t.negate();return e?r:t}HE.BASE=new HE(UE.Gx,UE.Gy,DE),HE.ZERO=new HE(LE,DE,LE);const GE=new WeakMap;class XE{_setWindowSize(e){this._WINDOW_SIZE=e,GE.delete(this)}hasEvenY(){return this.y%ME===LE}static fromCompressedHex(e){const t=32===e.length,r=hS(t?e:e.subarray(1));if(!AS(r))throw Error("Point is not on curve");let n=function(e){const{P:t}=UE,r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),l=e*e*e%t,u=l*l*e%t,c=mS(u,NE)*u%t,d=mS(c,NE)*u%t,h=mS(d,ME)*l%t,f=mS(h,n)*h%t,p=mS(f,i)*f%t,g=mS(p,o)*p%t,m=mS(g,a)*g%t,v=mS(m,o)*p%t,y=mS(v,NE)*u%t,b=mS(y,s)*f%t,w=mS(b,r)*l%t,E=mS(w,ME);if(E*E%t!==e)throw Error("Cannot find square root");return E}(zE(r));const i=(n&DE)===DE;t?i&&(n=gS(-n)):!(1&~e[0])!==i&&(n=gS(-n));const s=new XE(r,n);return s.assertValidity(),s}static fromUncompressedHex(e){const t=hS(e.subarray(1,33)),r=hS(e.subarray(33,65)),n=new XE(t,r);return n.assertValidity(),n}static fromHex(e){const t=fS(e),r=t.length,n=t[0];if(r===$E)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw Error("Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not "+r)}static fromPrivateKey(e){return XE.BASE.multiply(_S(e))}static fromSignature(e,t,r){const{r:n,s:i}=CS(t);if(![0,1,2,3].includes(r))throw Error("Cannot recover: invalid recovery bit");const s=yS(fS(e)),{n:o}=UE,a=2===r||3===r?n+o:n,l=vS(a,o),u=gS(-s*l,o),c=gS(i*l,o),d=1&r?"03":"02",h=XE.fromHex(d+lS(a)),f=XE.BASE.multiplyAndAddUnsafe(h,u,c);if(!f)throw Error("Cannot recover signature: point at infinify");return f.assertValidity(),f}toRawBytes(e=!1){return oS(this.toHex(e))}toHex(e=!1){const t=lS(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${lS(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!AS(t)||!AS(r))throw Error(e);const n=gS(r*r);if(gS(n-zE(t))!==LE)throw Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new XE(this.x,gS(-this.y))}double(){return HE.fromAffine(this).double().toAffine()}add(e){return HE.fromAffine(this).add(HE.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return HE.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=HE.fromAffine(this),i=t===LE||t===DE||this!==XE.BASE?n.multiplyUnsafe(t):n.multiply(t),s=HE.fromAffine(e).multiplyUnsafe(r),o=i.add(s);return o.equals(HE.ZERO)?void 0:o.toAffine()}constructor(e,t){this.x=e,this.y=t}}function ZE(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function YE(e){if(e.length<2||2!==e[0])throw Error("Invalid signature integer tag: "+nS(e));const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw Error("Invalid signature integer: trailing length");return{data:hS(r),left:e.subarray(t+2)}}XE.BASE=new XE(UE.Gx,UE.Gy),XE.ZERO=new XE(LE,LE);class QE{static fromCompact(e){const t=JE(e),r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(r+": Expected string or Uint8Array");const n=t?nS(e):e;if(128!==n.length)throw Error(r+": Expected 64-byte hex");return new QE(dS(n.slice(0,64)),dS(n.slice(64,128)))}static fromDER(e){const t=JE(e);if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:r,s:n}=function(e){if(e.length<2||48!=e[0])throw Error("Invalid signature tag: "+nS(e));if(e[1]!==e.length-2)throw Error("Invalid signature: incorrect length");const{data:t,left:r}=YE(e.subarray(2)),{data:n,left:i}=YE(r);if(i.length)throw Error("Invalid signature: left bytes after parsing: "+nS(i));return{r:t,s:n}}(t?e:oS(e));return new QE(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!SS(e))throw Error("Invalid Signature: r must be 0 < r < n");if(!SS(t))throw Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=UE.n>>DE;return this.s>e}normalizeS(){return this.hasHighS()?new QE(this.r,gS(-this.s,UE.n)):this}toDERRawBytes(){return oS(this.toDERHex())}toDERHex(){const e=ZE(cS(this.s)),t=ZE(cS(this.r)),r=e.length/2,n=t.length/2,i=cS(r),s=cS(n);return`30${cS(n+r+4)}02${s}${t}02${i}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return oS(this.toCompactHex())}toCompactHex(){return lS(this.r)+lS(this.s)}constructor(e,t){this.r=e,this.s=t,this.assertValidity()}}function JE(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function eS(e){if(!JE(e))throw Error("Uint8Array expected")}function tS(...e){if(e.every(eS),1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.length}return r}const rS=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function nS(e){eS(e);let t="";for(let r=0;r<e.length;r++)t+=rS[e[r]];return t}const iS={_0:48,_9:57,A:65,F:70,a:97,f:102};function sS(e){return e>=iS._0&&e<=iS._9?e-iS._0:e>=iS.A&&e<=iS.F?e-(iS.A-10):e>=iS.a&&e<=iS.f?e-(iS.a-10):void 0}function oS(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,i=0;t<r;t++,i+=2){const r=sS(e.charCodeAt(i)),s=sS(e.charCodeAt(i+1));if(void 0===r||void 0===s){const t=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+i)}n[t]=16*r+s}return n}const aS=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function lS(e){if("bigint"!=typeof e)throw Error("Expected bigint");if(!(LE<=e&&e<aS))throw Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function uS(e){const t=oS(lS(e));if(32!==t.length)throw Error("Error: expected 32 bytes");return t}function cS(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function dS(e){if("string"!=typeof e)throw new TypeError("hexToNumber: expected string, got "+typeof e);return BigInt("0x"+e)}function hS(e){return dS(nS(e))}function fS(e){return JE(e)?Uint8Array.from(e):oS(e)}function pS(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&SS(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function gS(e,t=UE.P){const r=e%t;return r>=LE?r:t+r}function mS(e,t){const{P:r}=UE;let n=e;for(;t-- >LE;)n*=n,n%=r;return n}function vS(e,t=UE.P){if(e===LE||t<=LE)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=gS(e,t),n=t,i=LE,s=DE;for(;r!==LE;){const e=n%r,t=i-s*(n/r);n=r,r=e,i=s,s=t}if(n!==DE)throw Error("invert: does not exist");return gS(i,t)}function yS(e,t=!1){const r=function(e){const t=8*e.length-256,r=hS(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n:n}=UE;return r>=n?r-n:r}let bS,wS;class ES{hmac(...e){return DS.hmacSha256(this.k,...e)}hmacSync(...e){return wS(this.k,...e)}checkSync(){if("function"!=typeof wS)throw new KE("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return tS(...t)}generateSync(){this.checkSync(),this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return tS(...t)}constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}}function SS(e){return LE<e&&e<UE.n}function AS(e){return LE<e&&e<UE.P}function IS(e,t,r,n=!0){const{n:i}=UE,s=yS(e,!0);if(!SS(s))return;const o=vS(s,i),a=XE.BASE.multiply(s),l=gS(a.x,i);if(l===LE)return;const u=gS(o*gS(t+r*l,i),i);if(u===LE)return;let c=new QE(l,u),d=(a.x===c.r?0:2)|Number(a.y&DE);return n&&c.hasHighS()&&(c=c.normalizeS(),d^=1),{sig:c,recovery:d}}function _S(e){let t;if("bigint"==typeof e)t=e;else if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw Error("Expected 32 bytes of private key");t=dS(e)}else{if(!JE(e))throw new TypeError("Expected valid private key");if(e.length!==qE)throw Error("Expected 32 bytes of private key");t=hS(e)}if(!SS(t))throw Error("Expected private key: 0 < key < n");return t}function CS(e){if(e instanceof QE)return e.assertValidity(),e;try{return QE.fromDER(e)}catch(t){return QE.fromCompact(e)}}function kS(e){return hS(e.length>$E?e.slice(0,$E):e)}function xS(e){const t=kS(e),r=gS(t,UE.n);return TS(r<LE?t:r)}function TS(e){return uS(e)}const PS={strict:!0};XE.BASE._setWindowSize(8);const RS={node:RE,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},LS={},DS={bytesToHex:nS,hexToBytes:oS,concatBytes:tS,mod:gS,invert:vS,isValidPrivateKey(e){try{return _S(e),!0}catch(e){return!1}},_bigintTo32Bytes:uS,_normalizePrivateKey:_S,hashToPrivateKey(e){if((e=fS(e)).length<40||e.length>1024)throw Error("Expected valid bytes of private key as per FIPS 186");return uS(gS(hS(e),UE.n-DE)+DE)},randomBytes(e=32){if(RS.web)return RS.web.getRandomValues(new Uint8Array(e));if(RS.node){const{randomBytes:t}=RS.node;return Uint8Array.from(t(e))}throw Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>DS.hashToPrivateKey(DS.randomBytes(40)),precompute(e=8,t=XE.BASE){const r=t===XE.BASE?t:new XE(t.x,t.y);return r._setWindowSize(e),r.multiply(NE),r},async sha256(...e){if(RS.web){const t=await RS.web.subtle.digest("SHA-256",tS(...e));return new Uint8Array(t)}if(RS.node){const{createHash:t}=RS.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw Error("The environment doesn't have sha256 function")},async hmacSha256(e,...t){if(RS.web){const r=await RS.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=tS(...t),i=await RS.web.subtle.sign("HMAC",r,n);return new Uint8Array(i)}if(RS.node){const{createHmac:r}=RS.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,async taggedHash(e,...t){let r=LS[e];if(void 0===r){const t=await DS.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=tS(t,t),LS[e]=r}return DS.sha256(r,...t)},taggedHashSync(e,...t){if("function"!=typeof bS)throw new KE("sha256Sync is undefined, you need to set it");let r=LS[e];if(void 0===r){const t=bS(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=tS(t,t),LS[e]=r}return bS(r,...t)},_JacobianPoint:HE};Object.defineProperties(DS,{sha256Sync:{configurable:!1,get:()=>bS,set(e){bS||(bS=e)}},hmacSha256Sync:{configurable:!1,get:()=>wS,set(e){wS||(wS=e)}}});var MS,NS,OS={exports:{}},US=(MS||(MS=1,NS=OS,function(){var e="input is invalid type",t="object"==typeof window,r=t?window:{};r.JS_SHA3_NO_WINDOW&&(t=!1);var n=!t&&"object"==typeof self;!r.JS_SHA3_NO_NODE_JS&&"object"==typeof X&&X.versions&&X.versions.node?r=is:n&&(r=self);for(var i=!r.JS_SHA3_NO_COMMON_JS&&NS.exports,s=!r.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,o="0123456789abcdef".split(""),a=[4,1024,262144,67108864],l=[0,8,16,24],u=[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],c=[224,256,384,512],d=[128,256],h=["hex","buffer","arrayBuffer","array","digest"],f={128:168,256:136},p=r.JS_SHA3_NO_NODE_JS||!Array.isArray?e=>"[object Array]"==={}.toString.call(e):Array.isArray,g=!s||!r.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:e=>"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer,m=t=>{var r=typeof t;if("string"===r)return[t,!0];if("object"!==r||null===t)throw Error(e);if(s&&t.constructor===ArrayBuffer)return[new Uint8Array(t),!1];if(!p(t)&&!g(t))throw Error(e);return[t,!1]},v=e=>0===m(e)[0].length,y=e=>{for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},b=(e,t,r)=>n=>new M(e,t,e).update(n)[r](),w=(e,t,r)=>(n,i)=>new M(e,t,i).update(n)[r](),E=(e,t,r)=>(t,n,i,s)=>C["cshake"+e].update(t,n,i,s)[r](),S=(e,t,r)=>(t,n,i,s)=>C["kmac"+e].update(t,n,i,s)[r](),A=(e,t,r,n)=>{for(var i=0;i<h.length;++i){var s=h[i];e[s]=t(r,n,s)}return e},I=(e,t)=>{var r=b(e,t,"hex");return r.create=()=>new M(e,t,e),r.update=e=>r.create().update(e),A(r,b,e,t)},_=[{name:"keccak",padding:[1,256,65536,16777216],bits:c,createMethod:I},{name:"sha3",padding:[6,1536,393216,100663296],bits:c,createMethod:I},{name:"shake",padding:[31,7936,2031616,520093696],bits:d,createMethod(e,t){var r=w(e,t,"hex");return r.create=r=>new M(e,t,r),r.update=(e,t)=>r.create(t).update(e),A(r,w,e,t)}},{name:"cshake",padding:a,bits:d,createMethod(e,t){var r=f[e],n=E(e,0,"hex");return n.create=(n,i,s)=>v(i)&&v(s)?C["shake"+e].create(n):new M(e,t,n).bytepad([i,s],r),n.update=(e,t,r,i)=>n.create(t,r,i).update(e),A(n,E,e,t)}},{name:"kmac",padding:a,bits:d,createMethod(e,t){var r=f[e],n=S(e,0,"hex");return n.create=(n,i,s)=>new N(e,t,i).bytepad(["KMAC",s],r).bytepad([n],r),n.update=(e,t,r,i)=>n.create(e,r,i).update(t),A(n,S,e,t)}}],C={},k=[],x=0;x<_.length;++x)for(var T=_[x],P=T.bits,R=0;R<P.length;++R){var L=T.name+"_"+P[R];if(k.push(L),C[L]=T.createMethod(P[R],T.padding),"sha3"!==T.name){var D=T.name+P[R];k.push(D),C[D]=C[L]}}function M(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function N(e,t,r){M.call(this,e,t,r)}M.prototype.update=function(e){if(this.finalized)throw Error("finalize already called");var t=m(e);e=t[0];for(var r,n,i=t[1],s=this.blocks,o=this.byteCount,a=e.length,u=this.blockCount,c=0,d=this.s;c<a;){if(this.reset)for(this.reset=!1,s[0]=this.block,r=1;r<u+1;++r)s[r]=0;if(i)for(r=this.start;c<a&&r<o;++c)(n=e.charCodeAt(c))<128?s[r>>2]|=n<<l[3&r++]:n<2048?(s[r>>2]|=(192|n>>6)<<l[3&r++],s[r>>2]|=(128|63&n)<<l[3&r++]):n<55296||n>=57344?(s[r>>2]|=(224|n>>12)<<l[3&r++],s[r>>2]|=(128|n>>6&63)<<l[3&r++],s[r>>2]|=(128|63&n)<<l[3&r++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++c)),s[r>>2]|=(240|n>>18)<<l[3&r++],s[r>>2]|=(128|n>>12&63)<<l[3&r++],s[r>>2]|=(128|n>>6&63)<<l[3&r++],s[r>>2]|=(128|63&n)<<l[3&r++]);else for(r=this.start;c<a&&r<o;++c)s[r>>2]|=e[c]<<l[3&r++];if(this.lastByteIndex=r,r>=o){for(this.start=r-o,this.block=s[u],r=0;r<u;++r)d[r]^=s[r];O(d),this.reset=!0}else this.start=r}return this},M.prototype.encode=function(e,t){var r=255&e,n=1,i=[r];for(r=255&(e>>=8);r>0;)i.unshift(r),r=255&(e>>=8),++n;return t?i.push(n):i.unshift(n),this.update(i),i.length},M.prototype.encodeString=function(e){var t=m(e);e=t[0];var r=t[1],n=0,i=e.length;if(r)for(var s=0;s<e.length;++s){var o=e.charCodeAt(s);o<128?n+=1:o<2048?n+=2:o<55296||o>=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++s)),n+=4)}else n=i;return n+=this.encode(8*n),this.update(e),n},M.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var i=(t-r%t)%t,s=[];return s.length=i,this.update(s),this},M.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];O(n)}},M.prototype.toString=M.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,a=0,l="";a<n;){for(s=0;s<t&&a<n;++s,++a)e=r[s],l+=o[e>>4&15]+o[15&e]+o[e>>12&15]+o[e>>8&15]+o[e>>20&15]+o[e>>16&15]+o[e>>28&15]+o[e>>24&15];a%t==0&&(r=y(r),O(r),s=0)}return i&&(e=r[s],l+=o[e>>4&15]+o[15&e],i>1&&(l+=o[e>>12&15]+o[e>>8&15]),i>2&&(l+=o[e>>20&15]+o[e>>16&15])),l},M.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var l=new Uint32Array(e);o<n;){for(s=0;s<t&&o<n;++s,++o)l[o]=r[s];o%t==0&&(r=y(r),O(r))}return i&&(l[o]=r[s],e=e.slice(0,a)),e},M.prototype.buffer=M.prototype.arrayBuffer,M.prototype.digest=M.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,i=this.outputBlocks,s=this.extraBytes,o=0,a=0,l=[];a<i;){for(o=0;o<r&&a<i;++o,++a)e=a<<2,t=n[o],l[e]=255&t,l[e+1]=t>>8&255,l[e+2]=t>>16&255,l[e+3]=t>>24&255;a%r==0&&(n=y(n),O(n))}return s&&(e=a<<2,t=n[o],l[e]=255&t,s>1&&(l[e+1]=t>>8&255),s>2&&(l[e+2]=t>>16&255)),l},N.prototype=new M,N.prototype.finalize=function(){return this.encode(this.outputBits,!0),M.prototype.finalize.call(this)};var O=e=>{var t,r,n,i,s,o,a,l,c,d,h,f,p,g,m,v,y,b,w,E,S,A,I,_,C,k,x,T,P,R,L,D,M,N,O,U,F,B,$,q,z,j,K,V,H,W,G,X,Z,Y,Q,J,ee,te,re,ne,ie,se,oe,ae,le,ue,ce;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],l=e[4]^e[14]^e[24]^e[34]^e[44],c=e[5]^e[15]^e[25]^e[35]^e[45],d=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(f=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(l<<1|c>>>31),r=s^(c<<1|l>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(d<<1|h>>>31),r=a^(h<<1|d>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=l^(f<<1|p>>>31),r=c^(p<<1|f>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=d^(i<<1|s>>>31),r=h^(s<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],m=e[1],W=e[11]<<4|e[10]>>>28,G=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,le=e[30]<<9|e[31]>>>23,j=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,v=e[13]<<12|e[12]>>>20,y=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,R=e[33]<<13|e[32]>>>19,L=e[32]<<13|e[33]>>>19,ue=e[42]<<2|e[43]>>>30,ce=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,U=e[14]<<6|e[15]>>>26,F=e[15]<<6|e[14]>>>26,b=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,Y=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,D=e[45]<<29|e[44]>>>3,M=e[44]<<29|e[45]>>>3,_=e[6]<<28|e[7]>>>4,C=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,B=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,J=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,H=e[9]<<27|e[8]>>>5,k=e[18]<<20|e[19]>>>12,x=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,z=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=g^~v&b,e[1]=m^~y&w,e[10]=_^~k&T,e[11]=C^~x&P,e[20]=N^~U&B,e[21]=O^~F&$,e[30]=V^~W&X,e[31]=H^~G&Z,e[40]=te^~ne&se,e[41]=re^~ie&oe,e[2]=v^~b&E,e[3]=y^~w&S,e[12]=k^~T&R,e[13]=x^~P&L,e[22]=U^~B&q,e[23]=F^~$&z,e[32]=W^~X&Y,e[33]=G^~Z&Q,e[42]=ne^~se&ae,e[43]=ie^~oe&le,e[4]=b^~E&A,e[5]=w^~S&I,e[14]=T^~R&D,e[15]=P^~L&M,e[24]=B^~q&j,e[25]=$^~z&K,e[34]=X^~Y&J,e[35]=Z^~Q&ee,e[44]=se^~ae&ue,e[45]=oe^~le&ce,e[6]=E^~A&g,e[7]=S^~I&m,e[16]=R^~D&_,e[17]=L^~M&C,e[26]=q^~j&N,e[27]=z^~K&O,e[36]=Y^~J&V,e[37]=Q^~ee&H,e[46]=ae^~ue&te,e[47]=le^~ce&re,e[8]=A^~g&v,e[9]=I^~m&y,e[18]=D^~_&k,e[19]=M^~C&x,e[28]=j^~N&U,e[29]=K^~O&F,e[38]=J^~V&W,e[39]=ee^~H&G,e[48]=ue^~te&ne,e[49]=ce^~re&ie,e[0]^=u[n],e[1]^=u[n+1]};if(i)NS.exports=C;else for(x=0;x<k.length;++x)r[k[x]]=C[k[x]]}()),OS.exports),FS=ss(US);function BS(e){return new Uint8Array(FS.keccak256.arrayBuffer(e))}function $S(e,t,r){try{return function(e,t,r,n=PS){let i;try{i=CS(e),t=fS(t)}catch(e){return!1}const{r:s,s:o}=i;if(n.strict&&i.hasHighS())return!1;const a=yS(t);let l;try{l=function(e){return e instanceof XE?(e.assertValidity(),e):XE.fromHex(e)}(r)}catch(e){return!1}const{n:u}=UE,c=vS(o,u),d=gS(a*c,u),h=gS(s*c,u),f=XE.BASE.multiplyAndAddUnsafe(l,d,h);return!!f&&gS(f.x,u)===s}(QE.fromCompact(e.slice(0,64)),t,r)}catch(e){return!1}}function qS(e,t){switch(t){case"udp":return qS(e,"udp4")||qS(e,"udp6");case"tcp":return qS(e,"tcp4")||qS(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const i=t.slice(0,3);let s;switch(i){case"udp":s=r?e.get("udp6"):e.get("udp");break;case"tcp":s=r?e.get("tcp6"):e.get("tcp");break;default:return}return s?function(e,t,r,n){let i=Mc("/"+e+"/"+Pc(e,r));return i=i.encapsulate(Mc("/"+t+"/"+Pc(t,n))),i}(r?"ip6":"ip4",i,n,s):void 0}const zS=parseInt("11111",2),jS=parseInt("10000000",2),KS=parseInt("01111111",2),VS={0:GS,1:GS,2(e,t){const r=WS(e,t),n=t.offset,i=t.offset+r,s=[];for(let t=n;t<i;t++)t===n&&0===e[t]||s.push(e[t]);return t.offset+=r,Uint8Array.from(s)},3(e,t){const r=WS(e,t),n=e[t.offset];t.offset++;const i=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return i},4(e,t){const r=WS(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=WS(e,t),n=t.offset+r,i=e[t.offset];t.offset++;let s=0,o=0;i<40?(s=0,o=i):i<80?(s=1,o=i-40):(s=2,o=i-80);let a=`${s}.${o}`,l=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,l.push(127&r),r<128){l.reverse();let e=0;for(let t=0;t<l.length;t++)e+=l[t]<<7*t;a+="."+e,l=[]}}return a},16:GS,22:GS,48:GS};function HS(e,t={offset:0}){const r=e[t.offset]&zS;if(t.offset++,null!=VS[r])return VS[r](e,t);throw Error("No decoder for tag "+r)}function WS(e,t){let r=0;if((e[t.offset]&jS)===jS){const n=e[t.offset]&KS;let i="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)i+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(i,16)}else r=e[t.offset],t.offset++;return r}function GS(e,t){WS(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=HS(e,t);if(null===n)break;r.push(n)}return r}function XS(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new qs;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new qs(Uint8Array.from([t.byteLength|jS]),t)}function ZS(e){const t=new qs;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new qs(Uint8Array.from([2]),XS(t),t)}function YS(e){const t=Uint8Array.from([0]),r=new qs(t,e);return new qs(Uint8Array.from([3]),XS(r),r)}function QS(e,t=48){const r=new qs;for(const t of e)r.append(t);return new qs(Uint8Array.from([t]),XS(r),r)}const JS=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),eA=Uint8Array.from([6,5,43,129,4,0,34]),tA=Uint8Array.from([6,5,43,129,4,0,35]),rA={ext:!0,kty:"EC",crv:"P-256"},nA={ext:!0,kty:"EC",crv:"P-384"},iA={ext:!0,kty:"EC",crv:"P-521"};function sA(e){if("P-256"===e)return JS;if("P-384"===e)return eA;if("P-521"===e)return tA;throw new Pi("Invalid curve "+e)}class oA{get raw(){var e,t,r;return null==this._raw&&(this._raw=(e=this.jwk,QS([ZS(Uint8Array.from([1])),QS([sA(e.crv)],160),QS([YS(new qs(Uint8Array.from([4]),Zt(null!==(t=e.x)&&void 0!==t?t:"","base64url"),Zt(null!==(r=e.y)&&void 0!==r?r:"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return Lt.digest(AA(this))}toCID(){return $t.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ns(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){var i,s,o;const a=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:null!==(o=e.crv)&&void 0!==o?o:"P-256"},!1,["verify"]);null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();const l=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},a,t,r.subarray());return null==n||null===(s=n.signal)||void 0===s||s.throwIfAborted(),l}(this.jwk,t,e,r)}constructor(e){(0,L.default)(this,"type","ECDSA"),(0,L.default)(this,"jwk",void 0),(0,L.default)(this,"_raw",void 0),this.jwk=e}}class aA extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class lA extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var uA={get(e=globalThis){const t=e.crypto;if(null==(null==t?void 0:t.subtle))throw new lA("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 t}};let cA;const dA=(async()=>{try{return await uA.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch(e){return!1}})();function hA(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class fA{toMultihash(){return Lt.digest(AA(this))}toCID(){return $t.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ns(this.raw,e.raw)}verify(e,t,r){var n;null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();const i=async function(e,t,r){return null==cA&&(cA=await dA),cA?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await uA.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await uA.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return zl.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return hA(i)?i.then((e=>{var t;return null==r||null===(t=r.signal)||void 0===t||t.throwIfAborted(),e})):i}constructor(e){(0,L.default)(this,"type","Ed25519"),(0,L.default)(this,"raw",void 0),this.raw=pA(e,32)}}function pA(e,t){if((e=Uint8Array.from(null!=e?e:[])).length!==t)throw new Pi(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var gA,mA,vA,yA;(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(gA||(gA={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(mA||(mA={})),(e=>{e.codec=()=>Wr(mA)})(gA||(gA={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),gA.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=gA.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(vA||(vA={})),(e=>{let t;e.codec=()=>(null==t&&(t=Gr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),gA.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=gA.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>cr(t,e.codec()),e.decode=(t,r)=>Ie(t,e.codec(),r)})(yA||(yA={}));class bA{get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Pi("JWK was missing components");return QS([wA,YS(QS([ZS(Zt(e.n,"base64url")),ZS(Zt(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return $t.createV1(114,this._multihash)}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ns(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){var i,s;const o=await uA.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();const a=await uA.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,r instanceof Uint8Array?r:r.subarray());return null==n||null===(s=n.signal)||void 0===s||s.throwIfAborted(),a}(this.jwk,t,e,r)}constructor(e,t){(0,L.default)(this,"type","RSA"),(0,L.default)(this,"jwk",void 0),(0,L.default)(this,"_raw",void 0),(0,L.default)(this,"_multihash",void 0),this.jwk=e,this._multihash=t}}const wA=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class EA{toMultihash(){return Lt.digest(AA(this))}toCID(){return $t.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ns(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const i=Mt.digest(r instanceof Uint8Array?r:r.subarray());if(hA(i))return i.then((({digest:r})=>{var i;return null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted(),ku.verify(t,r,e)})).catch((e=>{if("AbortError"===e.name)throw e;throw new aA(e+"")}));try{var s;return null==n||null===(s=n.signal)||void 0===s||s.throwIfAborted(),ku.verify(t,i.digest,e)}catch(e){throw new aA(e+"")}}(this._key,t,e,r)}constructor(e){(0,L.default)(this,"type","secp256k1"),(0,L.default)(this,"raw",void 0),(0,L.default)(this,"_key",void 0),this._key=function(e){try{return ku.ProjectivePoint.fromHex(e),e}catch(e){throw new Ri(e+"")}}(e),this.raw=function(e){return ku.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}}function SA(e){var t,r,n;if(32===e.byteLength)return n=pA(n=e,32),new fA(n);if(33===e.byteLength)return function(e){return new EA(e)}(e);const i=HS(e),s=null===(t=i[1])||void 0===t?void 0:t[0];if("1.2.840.10045.3.1.7"===s||"1.3.132.0.34"===s||"1.3.132.0.35"===s)return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=ri(t.subarray(1,33),"base64url"),n=ri(t.subarray(33),"base64url"),new oA((0,M.default)((0,D.default)({},rA),{key_ops:["verify"],x:r,y:n}));if(97===t.byteLength)return r=ri(t.subarray(1,49),"base64url"),n=ri(t.subarray(49),"base64url"),new oA((0,M.default)((0,D.default)({},nA),{key_ops:["verify"],x:r,y:n}));if(133===t.byteLength)return r=ri(t.subarray(1,67),"base64url"),n=ri(t.subarray(67),"base64url"),new oA((0,M.default)((0,D.default)({},iA),{key_ops:["verify"],x:r,y:n}));throw new Pi(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(i);if("1.2.840.113549.1.1.1"===(null===(r=i[0])||void 0===r?void 0:r[0]))return function(e,t,r){const n=function(e){const t=HS(e[1],{offset:0});return{kty:"RSA",n:ri(t[0],"base64url"),e:ri(t[1],"base64url")}}(e);return null==r&&(r=xt(18,ti(vA.encode({Type:gA.RSA,Data:t})))),new bA(n,r)}(i,e);throw new Pi("Could not extract public key from raw bytes")}function AA(e){return vA.encode({Type:gA[e.type],Data:e.raw})}const IA=Symbol.for("nodejs.util.inspect.custom");let _A=Symbol.toStringTag,CA=Ei,kA=IA;class xA{get[_A](){return`PeerId(${this.toString()})`}toString(){return null==this.string&&(this.string=ot.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return $t.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){var t;if(null==e)return!1;if(e instanceof Uint8Array)return Ns(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=(null===(t=null==e?void 0:e.toMultihash())||void 0===t?void 0:t.bytes))return Ns(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[kA](){return`PeerId(${this.toString()})`}constructor(e){(0,L.default)(this,"type",void 0),(0,L.default)(this,"multihash",void 0),(0,L.default)(this,"publicKey",void 0),(0,L.default)(this,"string",void 0),(0,L.default)(this,CA,!0),this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}}class TA extends xA{constructor(e){super((0,M.default)((0,D.default)({},e),{type:"RSA"})),(0,L.default)(this,"type","RSA"),(0,L.default)(this,"publicKey",void 0),this.publicKey=e.publicKey}}class PA extends xA{constructor(e){super((0,M.default)((0,D.default)({},e),{type:"Ed25519"})),(0,L.default)(this,"type","Ed25519"),(0,L.default)(this,"publicKey",void 0),this.publicKey=e.publicKey}}class RA extends xA{constructor(e){super((0,M.default)((0,D.default)({},e),{type:"secp256k1"})),(0,L.default)(this,"type","secp256k1"),(0,L.default)(this,"publicKey",void 0),this.publicKey=e.publicKey}}function LA(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let i=0;return e.forEach((e=>{if(e.getPeerId())throw Error("`multiaddr` field MUST not contain peer id");n.setUint16(i,e.bytes.length),i+=2,r.set(e.bytes,i),i+=e.bytes.length})),r}function DA(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class MA extends Map{set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){const e=this.get("id");if(!e)throw Error("id not found.");return oi(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw Error(PE)}get rs(){const e=this.get("rs");if(e)return mi(e)}get rsv(){const e=this.get("rsv");if(e)return mi(e)}get ip(){return NA(this,"ip","ip4")}set ip(e){UA(this,"ip","ip4",e)}get tcp(){return OA(this,"tcp","tcp")}set tcp(e){FA(this,"tcp","tcp",e)}get udp(){return OA(this,"udp","udp")}set udp(e){FA(this,"udp","udp",e)}get ip6(){return NA(this,"ip6","ip6")}set ip6(e){UA(this,"ip6","ip6",e)}get tcp6(){return OA(this,"tcp6","tcp")}set tcp6(e){FA(this,"tcp6","tcp",e)}get udp6(){return OA(this,"udp6","udp")}set udp6(e){FA(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r<e.length;){const n=new DataView(e.buffer,r,2).getUint16(0);r+=2;const i=e.slice(r,r+n);r+=n,t.push(Mc(i))}return t}(e)}set multiaddrs(e){BA(this,"multiaddrs",e,LA)}get waku2(){const e=this.get("waku2");if(e)return function(e){const t={relay:!1,store:!1,filter:!1,lightPush:!1};return e%2&&(t.relay=!0),(e>>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){BA(this,"waku2",e,(e=>new Uint8Array([DA(e)])))}constructor(e={},t=BigInt(1),r){super(Object.entries(e)),(0,L.default)(this,"seq",void 0),(0,L.default)(this,"signature",void 0),this.seq=t,this.signature=r}}function NA(e,t,r){const n=e.get(t);if(n)return Pc(r,n)}function OA(e,t,r){const n=e.get(t);if(n)return Number(Pc(r,n))}function UA(e,t,r,n){BA(e,t,n,Rc.bind({},r))}function FA(e,t,r,n){UA(e,t,r,null==n?void 0:n.toString(10))}function BA(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}const $A=new gs("enr");var qA,zA;(e=>{e.TCP="tcp",e.UDP="udp"})(qA||(qA={})),(e=>{e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"})(zA||(zA={}));class jA extends MA{static create(e={},t=BigInt(1),r){const n=new jA(e,t,r);try{const e=n.publicKey;e&&(n.peerId=function(e){const t=SA(e);if("secp256k1"!==t.type)throw Error("Keypair type not implemented");return function(e){if("Ed25519"===e.type)return new PA({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new RA({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new TA({multihash:e.toCID().multihash,publicKey:e});throw new Qi}(t)}(e))}catch(e){$A.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=XE.fromHex(e).toRawBytes(!1);return si(BS(t.slice(1)))}(this.publicKey):void 0;throw Error(PE)}get shardInfo(){return this.rs&&this.rsv&&$A.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const t of Object.values(zA)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}var t;const r=null!==(t=this.multiaddrs)&&void 0!==t?t:[];return e.concat(r).map((e=>this.peerId?e.encapsulate("/p2p/"+this.peerId.toString()):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate("/p2p/"+this.peerId.toString())}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const e=this.peerId;return this.multiaddrs.map((t=>t.encapsulate("/p2p/"+e.toString())))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw Error(PE);if(!this.publicKey)throw Error("Failed to verify ENR: No public key");return $S(t,BS(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw Error(PE);return this.signature=await async function(e,t){return async function(e,t,r={}){const{seed:n,m:i,d:s}=function(e,t,r){if(null==e)throw Error(`sign: expected valid message hash, not "${e}"`);const n=fS(e),i=_S(t),s=[TS(i),xS(n)];if(null!=r){!0===r&&(r=DS.randomBytes($E));const e=fS(r);if(e.length!==$E)throw Error("sign: Expected 32 bytes of extra data");s.push(e)}return{seed:tS(...s),m:kS(n),d:i}}(e,t,r.extraEntropy),o=new ES(32,qE);let a;for(await o.reseed(n);!(a=IS(await o.generate(),i,s,r.canonical));)await o.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},t),o=i?r.toDERRawBytes():r.toCompactRawBytes();return s?[o,n]:o}(a,r)}(BS(t),e,{der:!1})}(t,e),this.signature}constructor(...e){super(...e),(0,L.default)(this,"peerId",void 0),(0,L.default)(this,"getLocationMultiaddr",qS.bind({},this))}}(0,L.default)(jA,"RECORD_PREFIX","enr:");let KA=!1,VA=!1;const HA={debug:1,default:2,info:2,warning:3,error:4,off:5};let WA=HA.default,GA=null;const XA=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw Error("missing "+e.join(", "))}catch(e){return e.message}return null}();var ZA,YA;(e=>{e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"})(ZA||(ZA={})),(e=>{e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"})(YA||(YA={}));const QA="0123456789abcdef";class JA{_log(e,t){const r=e.toLowerCase();null==HA[r]&&this.throwArgumentError("invalid log level name","logLevel",e)}debug(...e){this._log(JA.levels.DEBUG,e)}info(...e){this._log(JA.levels.INFO,e)}warn(...e){this._log(JA.levels.WARNING,e)}makeError(e,t,r){if(VA)return this.makeError("censored error",t,{});t||(t=JA.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=QA[t[e]>>4],r+=QA[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}})),n.push("code="+t),n.push("version="+this.version);const i=e;let s="";switch(t){case YA.NUMERIC_FAULT:{s="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":s+="-"+t;break;case"negative-power":case"negative-width":s+="-unsupported";break;case"unbound-bitwise-result":s+="-unbound-result"}break}case YA.CALL_EXCEPTION:case YA.INSUFFICIENT_FUNDS:case YA.MISSING_NEW:case YA.NONCE_EXPIRED:case YA.REPLACEMENT_UNDERPRICED:case YA.TRANSACTION_REPLACED:case YA.UNPREDICTABLE_GAS_LIMIT:s=t}s&&(e+=" [ See: https://links.ethers.org/v5-errors-"+s+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=Error(e);return o.reason=i,o.code=t,Object.keys(r).forEach((e=>{o[e]=r[e]})),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,JA.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){XA&&this.throwError("platform missing String.prototype.normalize",JA.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:XA})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,JA.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,JA.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,JA.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,JA.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",JA.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",JA.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",JA.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return GA||(GA=new JA("logger/5.8.0")),GA}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",JA.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),KA){if(!e)return;this.globalLogger().throwError("error censorship permanent",JA.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}VA=!!e,KA=!!t}static setLogLevel(e){const t=HA[e.toLowerCase()];null!=t?WA=t:JA.globalLogger().warn("invalid log level - "+e)}static from(e){return new JA(e)}constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}}JA.errors=YA,JA.levels=ZA;const eI=new JA("bytes/5.8.0");function tI(e){return!!e.toHexString}function rI(e){return e.slice||(e.slice=function(){const t=[].slice.call(arguments);return rI(new Uint8Array([].slice.apply(e,t)))}),e}function nI(e){return"number"==typeof e&&e==e&&e%1==0}function iI(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!nI(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!nI(r)||r<0||r>=256)return!1}return!0}function sI(e,t){if(t||(t={}),"number"==typeof e){eI.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(e/256+"");return 0===t.length&&t.push(0),rI(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),tI(e)&&(e=e.toHexString()),oI(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":eI.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return rI(new Uint8Array(n))}return iI(e)?rI(new Uint8Array(e)):eI.throwArgumentError("invalid arrayify value","value",e)}function oI(e){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))}const aI="0123456789abcdef";function lI(e,t){if(t||(t={}),"number"==typeof e){eI.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=aI[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),tI(e))return e.toHexString();if(oI(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":eI.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(iI(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=aI[(240&n)>>4]+aI[15&n]}return t}return eI.throwArgumentError("invalid hexlify value","value",e)}const uI=new JA("rlp/5.8.0");function cI(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function dI(e,t,r){let n=0;for(let i=0;i<r;i++)n=256*n+e[t+i];return n}function hI(e){if(Array.isArray(e)){let t=[];if(e.forEach((e=>{t=t.concat(hI(e))})),t.length<=55)return t.unshift(192+t.length),t;const r=cI(t.length);return r.unshift(247+r.length),r.concat(t)}var t;oI(t=e)&&!(t.length%2)||iI(t)||uI.throwArgumentError("RLP object must be BytesLike","object",e);const r=[].slice.call(sI(e));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;const n=cI(r.length);return n.unshift(183+n.length),n.concat(r)}function fI(e,t,r,n){const i=[];for(;r<t+1+n;){const s=pI(e,r);i.push(s.result),(r+=s.consumed)>t+1+n&&uI.throwError("child data too short",JA.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:i}}function pI(e,t){if(0===e.length&&uI.throwError("data too short",JA.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&uI.throwError("data short segment too short",JA.errors.BUFFER_OVERRUN,{});const n=dI(e,t+1,r);return t+1+r+n>e.length&&uI.throwError("data long segment too short",JA.errors.BUFFER_OVERRUN,{}),fI(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&uI.throwError("data array too short",JA.errors.BUFFER_OVERRUN,{}),fI(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&uI.throwError("data array too short",JA.errors.BUFFER_OVERRUN,{});const n=dI(e,t+1,r);return t+1+r+n>e.length&&uI.throwError("data array too short",JA.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:lI(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&uI.throwError("data too short",JA.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:lI(e.slice(t+1,t+1+r))}}return{consumed:1,result:lI(e[t])}}const gI=new gs("enr:decoder");class mI{static fromString(e){if(!e.startsWith(jA.RECORD_PREFIX))throw Error(`"string encoded ENR must start with '${jA.RECORD_PREFIX}'`);return mI.fromRLP(Zt(e.slice(4),"base64url"))}static fromRLP(e){return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw Error("Decoded ENR must be an array");if(e.length%2!=0)throw Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),i={};for(let e=0;e<n.length;e+=2)try{i[oi(n[e])]=n[e+1]}catch(t){gI.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}const s=function(e){return e.length?BigInt("0x"+si(e)):BigInt(0)}(r),o=jA.create(i,s,t);return function(e,t,r,n){const i=ni(lI(hI([e,...t])));if(!r.verify(i,n))throw Error("Unable to verify ENR signature")}(r,n,o,t),o}(function(e){const t=sI(e),r=pI(t,0);return r.consumed!==t.length&&uI.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(ni))}}var vI=new WeakMap,yI=new WeakMap,bI=new WeakMap,wI=new WeakMap,EI=new WeakMap,SI=new WeakMap,AI=new WeakSet,II=new WeakSet,_I=new WeakSet,CI=new WeakSet,kI=new WeakSet,xI=new WeakSet,TI=new WeakSet,PI=new WeakSet;let RI=Symbol.iterator,LI=Symbol.toStringTag,DI=Symbol.for("nodejs.util.inspect.custom");class MI extends Map{get __oldCache(){return(0,C.default)(this,bI)}get(e){if((0,C.default)(this,yI).has(e)){const t=(0,C.default)(this,yI).get(e);return(0,P.default)(this,CI,FI).call(this,e,t)}if((0,C.default)(this,bI).has(e)){const t=(0,C.default)(this,bI).get(e);if(!1===(0,P.default)(this,II,OI).call(this,e,t))return(0,P.default)(this,TI,qI).call(this,e,t),t.value}}set(e,t,{maxAge:r=(0,C.default)(this,EI)}={}){const n="number"==typeof r&&r!==1/0?Date.now()+r:void 0;return(0,C.default)(this,yI).has(e)?(0,C.default)(this,yI).set(e,{value:t,expiry:n}):(0,P.default)(this,xI,$I).call(this,e,{value:t,expiry:n}),this}has(e){return(0,C.default)(this,yI).has(e)?!(0,P.default)(this,II,OI).call(this,e,(0,C.default)(this,yI).get(e)):!!(0,C.default)(this,bI).has(e)&&!(0,P.default)(this,II,OI).call(this,e,(0,C.default)(this,bI).get(e))}peek(e){return(0,C.default)(this,yI).has(e)?(0,P.default)(this,kI,BI).call(this,e,(0,C.default)(this,yI)):(0,C.default)(this,bI).has(e)?(0,P.default)(this,kI,BI).call(this,e,(0,C.default)(this,bI)):void 0}expiresIn(e){var t;const r=null!==(t=(0,C.default)(this,yI).get(e))&&void 0!==t?t:(0,C.default)(this,bI).get(e);if(r)return r.expiry?r.expiry-Date.now():1/0}delete(e){const t=(0,C.default)(this,yI).delete(e);return t&&(0,T.default)(this,vI).value--,(0,C.default)(this,bI).delete(e)||t}clear(){(0,C.default)(this,yI).clear(),(0,C.default)(this,bI).clear(),(0,x.default)(this,vI,0)}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");const t=[...(0,P.default)(this,PI,zI).call(this)],r=t.length-e;r<0?((0,x.default)(this,yI,new Map(t)),(0,x.default)(this,bI,new Map),(0,x.default)(this,vI,t.length)):(r>0&&(0,P.default)(this,AI,NI).call(this,t.slice(0,r)),(0,x.default)(this,bI,new Map(t.slice(r))),(0,x.default)(this,yI,new Map),(0,x.default)(this,vI,0)),(0,x.default)(this,wI,e)}evict(e=1){const t=Number(e);if(!t||t<=0)return;const r=[...(0,P.default)(this,PI,zI).call(this)],n=Math.trunc(Math.min(t,Math.max(r.length-1,0)));n<=0||((0,P.default)(this,AI,NI).call(this,r.slice(0,n)),(0,x.default)(this,bI,new Map(r.slice(n))),(0,x.default)(this,yI,new Map),(0,x.default)(this,vI,0))}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[RI](){for(const e of(0,C.default)(this,yI)){const[t,r]=e;!1===(0,P.default)(this,II,OI).call(this,t,r)&&(yield[t,r.value])}for(const e of(0,C.default)(this,bI)){const[t,r]=e;(0,C.default)(this,yI).has(t)||!1===(0,P.default)(this,II,OI).call(this,t,r)&&(yield[t,r.value])}}*entriesDescending(){let e=[...(0,C.default)(this,yI)];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,i]=r;!1===(0,P.default)(this,II,OI).call(this,n,i)&&(yield[n,i.value])}e=[...(0,C.default)(this,bI)];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,i]=r;(0,C.default)(this,yI).has(n)||!1===(0,P.default)(this,II,OI).call(this,n,i)&&(yield[n,i.value])}}*entriesAscending(){for(const[e,t]of(0,P.default)(this,PI,zI).call(this))yield[e,t.value]}get size(){if(!(0,C.default)(this,vI))return(0,C.default)(this,bI).size;let e=0;for(const t of(0,C.default)(this,bI).keys())(0,C.default)(this,yI).has(t)||e++;return Math.min((0,C.default)(this,vI)+e,(0,C.default)(this,wI))}get maxSize(){return(0,C.default)(this,wI)}get maxAge(){return(0,C.default)(this,EI)}entries(){return this.entriesAscending()}forEach(e,t=this){for(const[r,n]of this.entriesAscending())e.call(t,n,r,this)}get[LI](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[DI](){return this.toString()}constructor(e={}){if(super(),(0,R.default)(this,AI),(0,R.default)(this,II),(0,R.default)(this,_I),(0,R.default)(this,CI),(0,R.default)(this,kI),(0,R.default)(this,xI),(0,R.default)(this,TI),(0,R.default)(this,PI),(0,k.default)(this,vI,{writable:!0,value:0}),(0,k.default)(this,yI,{writable:!0,value:new Map}),(0,k.default)(this,bI,{writable:!0,value:new Map}),(0,k.default)(this,wI,{writable:!0,value:void 0}),(0,k.default)(this,EI,{writable:!0,value:void 0}),(0,k.default)(this,SI,{writable:!0,value:void 0}),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if("number"==typeof e.maxAge&&0===e.maxAge)throw new TypeError("`maxAge` must be a number greater than 0");(0,x.default)(this,wI,e.maxSize),(0,x.default)(this,EI,e.maxAge||1/0),(0,x.default)(this,SI,e.onEviction)}}function NI(e){if("function"==typeof(0,C.default)(this,SI))for(const[t,r]of e)(0,C.default)(this,SI).call(this,t,r.value)}function OI(e,t){return"number"==typeof t.expiry&&t.expiry<=Date.now()&&("function"==typeof(0,C.default)(this,SI)&&(0,C.default)(this,SI).call(this,e,t.value),this.delete(e))}function UI(e,t){if(!1===(0,P.default)(this,II,OI).call(this,e,t))return t.value}function FI(e,t){return t.expiry?(0,P.default)(this,_I,UI).call(this,e,t):t.value}function BI(e,t){const r=t.get(e);return(0,P.default)(this,CI,FI).call(this,e,r)}function $I(e,t){(0,C.default)(this,yI).set(e,t),(0,T.default)(this,vI).value++,(0,C.default)(this,vI)>=(0,C.default)(this,wI)&&((0,x.default)(this,vI,0),(0,P.default)(this,AI,NI).call(this,(0,C.default)(this,bI)),(0,x.default)(this,bI,(0,C.default)(this,yI)),(0,x.default)(this,yI,new Map))}function qI(e,t){(0,C.default)(this,bI).delete(e),(0,P.default)(this,xI,$I).call(this,e,t)}function*zI(){for(const e of(0,C.default)(this,bI)){const[t,r]=e;(0,C.default)(this,yI).has(t)||!1===(0,P.default)(this,II,OI).call(this,t,r)&&(yield e)}for(const e of(0,C.default)(this,yI)){const[t,r]=e;!1===(0,P.default)(this,II,OI).call(this,t,r)&&(yield e)}}function jI(e,t,r){return`${e}?name=${t}&type=${r}`}async function KI(e,t){const r=await fetch(e,{headers:new Headers({accept:"application/dns-json"}),signal:t});return await r.json()}function VI(e,t){return`${t}_${e}`}const HI=Object.assign($v("dns-over-http-resolver"),{error:$v("dns-over-http-resolver:error")});class WI{cancel(){this._abortControllers.forEach((e=>{e.abort()}))}getServers(){return this._servers}_getShuffledServers(){const e=[...this._servers];for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*t),n=e[t];e[t]=e[r],e[r]=n}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw Error(t+" is not supported")}}async resolve4(e){const t="A",r=this._cache.get(VI(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const i=new AbortController;this._abortControllers.push(i);try{const n=await this._request(jI(r,e,t),i.signal),s=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(VI(e,t),s,{maxAge:o}),s}catch(s){i.signal.aborted&&(n=!0),HI.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==i))}}if(n)throw Object.assign(Error("queryA ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){const t="AAAA",r=this._cache.get(VI(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const i=new AbortController;this._abortControllers.push(i);try{const n=await this._request(jI(r,e,t),i.signal),s=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(VI(e,t),s,{maxAge:o}),s}catch(s){i.signal.aborted&&(n=!0),HI.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==i))}}if(n)throw Object.assign(Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){const t="TXT",r=this._TXTcache.get(VI(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const i=new AbortController;this._abortControllers.push(i);try{const n=await this._request(jI(r,e,t),i.signal),s=n.Answer.map((e=>[e.data.replace(/['"]+/g,"")])),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._TXTcache.set(VI(e,t),s,{maxAge:o}),s}catch(s){i.signal.aborted&&(n=!0),HI.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==i))}}if(n)throw Object.assign(Error("queryTxt ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}constructor(e={}){var t,r,n;(0,L.default)(this,"_cache",void 0),(0,L.default)(this,"_TXTcache",void 0),(0,L.default)(this,"_servers",void 0),(0,L.default)(this,"_request",void 0),(0,L.default)(this,"_abortControllers",void 0),this._cache=new MI({maxSize:null!==(t=null==e?void 0:e.maxCache)&&void 0!==t?t:100}),this._TXTcache=new MI({maxSize:null!==(r=null==e?void 0:e.maxCache)&&void 0!==r?r:100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=null!==(n=e.request)&&void 0!==n?n:KI,this._abortControllers=[]}}const GI=new gs("dns-over-https");class XI{static async create(){return new XI}async resolveTXT(e){let t;try{t=await this.resolver.resolveTxt(e)}catch(e){throw GI.error("query failed: ",e),Error("DNS query failed")}if(!t)throw Error("Could not resolve "+e);const r=[];return t.forEach((e=>{"string"==typeof e?r.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?r.push(e):r.push(oi(e))})):r.push(oi(e))})),r}constructor(e=new WI){(0,L.default)(this,"resolver",void 0),this.resolver=e}}var ZI,YI={exports:{}},QI=(ZI||(ZI=1,(e=>{(()=>{var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof X&&X.versions&&X.versions.node&&(t=is);var r=!t.HI_BASE32_NO_COMMON_JS&&e.exports,n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),i={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},s=[0,0,0,0,0,0,0,0],o=(e,t)=>{t.length>10&&(t="..."+t.substr(-10));var r=Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},a=e=>{if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");for(var t,r,n,s,o,a,l,u,c=[],d=0,h=(e=e.replace(/=/g,"")).length,f=0,p=h>>3<<3;f<p;)t=i[e.charAt(f++)],r=i[e.charAt(f++)],n=i[e.charAt(f++)],s=i[e.charAt(f++)],o=i[e.charAt(f++)],a=i[e.charAt(f++)],l=i[e.charAt(f++)],u=i[e.charAt(f++)],c[d++]=255&(t<<3|r>>>2),c[d++]=255&(r<<6|n<<1|s>>>4),c[d++]=255&(s<<4|o>>>1),c[d++]=255&(o<<7|a<<2|l>>>3),c[d++]=255&(l<<5|u);var g=h-p;return 2===g?(t=i[e.charAt(f++)],r=i[e.charAt(f++)],c[d++]=255&(t<<3|r>>>2)):4===g?(t=i[e.charAt(f++)],r=i[e.charAt(f++)],n=i[e.charAt(f++)],s=i[e.charAt(f++)],c[d++]=255&(t<<3|r>>>2),c[d++]=255&(r<<6|n<<1|s>>>4)):5===g?(t=i[e.charAt(f++)],r=i[e.charAt(f++)],n=i[e.charAt(f++)],s=i[e.charAt(f++)],o=i[e.charAt(f++)],c[d++]=255&(t<<3|r>>>2),c[d++]=255&(r<<6|n<<1|s>>>4),c[d++]=255&(s<<4|o>>>1)):7===g&&(t=i[e.charAt(f++)],r=i[e.charAt(f++)],n=i[e.charAt(f++)],s=i[e.charAt(f++)],o=i[e.charAt(f++)],a=i[e.charAt(f++)],l=i[e.charAt(f++)],c[d++]=255&(t<<3|r>>>2),c[d++]=255&(r<<6|n<<1|s>>>4),c[d++]=255&(s<<4|o>>>1),c[d++]=255&(o<<7|a<<2|l>>>3)),c},l=(e,t)=>{if(!t)return(e=>{for(var t,r,n="",i=e.length,s=0,a=0;s<i;)if((t=e[s++])<=127)n+=String.fromCharCode(t);else{t>191&&t<=223?(r=31&t,a=1):t<=239?(r=15&t,a=2):t<=247?(r=7&t,a=3):o(s,n);for(var l=0;l<a;++l)((t=e[s++])<128||t>191)&&o(s,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&o(s,n),r>1114111&&o(s,n),r<=65535?n+=String.fromCharCode(r):(n+=String.fromCharCode(55296+((r-=65536)>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n})(a(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");var r,n,s,l,u,c,d,h,f="",p=e.indexOf("=");-1===p&&(p=e.length);for(var g=0,m=p>>3<<3;g<m;)r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],l=i[e.charAt(g++)],u=i[e.charAt(g++)],c=i[e.charAt(g++)],d=i[e.charAt(g++)],h=i[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|d>>>3))+String.fromCharCode(255&(d<<5|h));var v=p-m;return 2===v?(r=i[e.charAt(g++)],n=i[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))):4===v?(r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],l=i[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|l>>>4))):5===v?(r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],l=i[e.charAt(g++)],u=i[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))):7===v&&(r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],l=i[e.charAt(g++)],u=i[e.charAt(g++)],c=i[e.charAt(g++)],d=i[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|d>>>3))),f},u={encode(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?(e=>{for(var t,r,i,s,o,a="",l=e.length,u=0,c=5*parseInt(l/5);u<c;)t=e[u++],r=e[u++],i=e[u++],s=e[u++],o=e[u++],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|i>>>4)]+n[31&(i<<1|s>>>7)]+n[s>>>2&31]+n[31&(s<<3|o>>>5)]+n[31&o];var d=l-c;return 1===d?(t=e[u],a+=n[t>>>3]+n[t<<2&31]+"======"):2===d?(t=e[u++],r=e[u],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===d?(t=e[u++],r=e[u++],i=e[u],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|i>>>4)]+n[i<<1&31]+"==="):4===d&&(t=e[u++],r=e[u++],i=e[u++],s=e[u],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|i>>>4)]+n[31&(i<<1|s>>>7)]+n[s>>>2&31]+n[s<<3&31]+"="),a})(e):t?(e=>{for(var t,r,i,s,o,a="",l=e.length,u=0,c=5*parseInt(l/5);u<c;)t=e.charCodeAt(u++),r=e.charCodeAt(u++),i=e.charCodeAt(u++),s=e.charCodeAt(u++),o=e.charCodeAt(u++),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|i>>>4)]+n[31&(i<<1|s>>>7)]+n[s>>>2&31]+n[31&(s<<3|o>>>5)]+n[31&o];var d=l-c;return 1===d?(t=e.charCodeAt(u),a+=n[t>>>3]+n[t<<2&31]+"======"):2===d?(t=e.charCodeAt(u++),r=e.charCodeAt(u),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===d?(t=e.charCodeAt(u++),r=e.charCodeAt(u++),i=e.charCodeAt(u),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|i>>>4)]+n[i<<1&31]+"==="):4===d&&(t=e.charCodeAt(u++),r=e.charCodeAt(u++),i=e.charCodeAt(u++),s=e.charCodeAt(u),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|i>>>4)]+n[31&(i<<1|s>>>7)]+n[s>>>2&31]+n[s<<3&31]+"="),a})(e):(e=>{var t,r,i,o,a,l,u,c=!1,d="",h=0,f=0,p=e.length;if(""===e)return d;do{for(s[0]=s[5],s[1]=s[6],s[2]=s[7],u=f;h<p&&u<5;++h)(l=e.charCodeAt(h))<128?s[u++]=l:l<2048?(s[u++]=192|l>>6,s[u++]=128|63&l):l<55296||l>=57344?(s[u++]=224|l>>12,s[u++]=128|l>>6&63,s[u++]=128|63&l):(l=65536+((1023&l)<<10|1023&e.charCodeAt(++h)),s[u++]=240|l>>18,s[u++]=128|l>>12&63,s[u++]=128|l>>6&63,s[u++]=128|63&l);f=u-5,h===p&&++h,h>p&&u<6&&(c=!0),t=s[0],u>4?(r=s[1],i=s[2],o=s[3],a=s[4],d+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|i>>>4)]+n[31&(i<<1|o>>>7)]+n[o>>>2&31]+n[31&(o<<3|a>>>5)]+n[31&a]):1===u?d+=n[t>>>3]+n[t<<2&31]+"======":2===u?(r=s[1],d+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===u?(r=s[1],i=s[2],d+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|i>>>4)]+n[i<<1&31]+"==="):(r=s[1],i=s[2],o=s[3],d+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|i>>>4)]+n[31&(i<<1|o>>>7)]+n[o>>>2&31]+n[o<<3&31]+"=")}while(!c);return d})(e)},decode:l};l.asBytes=a,r?e.exports=u:t.base32=u})()})(YI)),YI.exports),JI=ss(QI);class e_{static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=e_.parseRootValues(e),n=JI.decode.asBytes(t),i=e.split(" sig")[0],s=ai(i);if(!$S(Zt(r.signature,"base64url").slice(0,64),BS(s),new Uint8Array(n)))throw Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree root entry");t.shift();const[r,n,i,s]=t;if(!r)throw Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw Error("Could not parse 'l' value from ENRTree root entry");if(!i)throw Error("Could not parse 'seq' value from ENRTree root entry");if(!s)throw Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(i),signature:s}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw Error("Could not parse public key from ENRTree tree entry");if(!n)throw Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}(0,L.default)(e_,"RECORD_PREFIX",jA.RECORD_PREFIX),(0,L.default)(e_,"TREE_PREFIX","enrtree:"),(0,L.default)(e_,"BRANCH_PREFIX","enrtree-branch:"),(0,L.default)(e_,"ROOT_PREFIX","enrtree-root:");const t_=new gs("discovery:fetch_nodes");async function*r_(e,t=10,r=3){const n=new Set;let i=0,s=0;for(;i<t&&s<r;){i++;const t=await e();t&&t.nodeId?n.has(t.nodeId)||(n.add(t.nodeId),t.waku2&&(yield t),t_.info(`got new peer candidate from DNS address=${t.nodeId}@${t.ip}`)):s++}}const n_=new gs("discovery:dns");class i_{static async dnsOverHttp(e){return e||(e=await XI.create()),new i_(e)}async*getNextPeer(e){for(const t of function(e){if(e.length<=1)return e;for(let t=0;t<e.length;t++){const r=Math.floor(Math.random()*Math.floor(e.length)),n=e[t];e[t]=e[r],e[r]=n}return e}(e)){const{publicKey:e,domain:r}=e_.parseTree(t),n={domain:r,publicKey:e,visits:{}};for await(const e of r_((()=>this._search(r,n))))yield e}}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,i;t.visits[e]=!0;const s=function(e){return e.startsWith(e_.ROOT_PREFIX)?e_.ROOT_PREFIX:e.startsWith(e_.BRANCH_PREFIX)?e_.BRANCH_PREFIX:e.startsWith(e_.RECORD_PREFIX)?e_.RECORD_PREFIX:""}(r);try{switch(s){case e_.ROOT_PREFIX:return n=e_.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case e_.BRANCH_PREFIX:return i=e_.parseBranch(r),n=function(e,t){const r={};for(const[n,i]of e.entries())t.visits[i]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(i,t),await this._search(n,t);case e_.RECORD_PREFIX:return mI.fromString(r);default:return null}}catch(t){return n_.error(`Failed to search DNS tree ${s} at subdomain ${e}: ${t}`),null}}catch(t){return n_.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw Error("Received empty result array while fetching TXT record");if(!n[0].length)throw Error("Received empty TXT record");const i=n.join("");return this._DNSTreeCache[e]=i,i}constructor(e){(0,L.default)(this,"dns",void 0),(0,L.default)(this,"_DNSTreeCache",void 0),this._DNSTreeCache={},this.dns=e}}const s_=new gs("peer-discovery-dns");let o_=wi,a_=Symbol.toStringTag;class l_ extends es{async start(){s_.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const t=await i_.dnsOverHttp();this.nextPeer=t.getNextPeer.bind(t,e)}for await(const r of this.nextPeer()){if(!this._started)return;const{peerInfo:n,shardInfo:i}=r;if(!n)continue;var e,t;const s={[TE]:{value:null!==(e=this._options.tagValue)&&void 0!==e?e:50,ttl:null!==(t=this._options.tagTTL)&&void 0!==t?t:1e8}};let o=!1;await this._components.peerStore.has(n.id)?(await this._components.peerStore.get(n.id)).tags.has(TE)||(o=!0,await this._components.peerStore.merge(n.id,{tags:s})):(o=!0,await this._components.peerStore.save(n.id,(0,D.default)({tags:s},i&&{metadata:{shardInfo:vi(i)}}))),o&&this.dispatchEvent(new CustomEvent("peer",{detail:n}))}}stop(){this._started=!1}get[o_](){return!0}get[a_](){return"@waku/bootstrap"}constructor(e,t){super(),(0,L.default)(this,"nextPeer",void 0),(0,L.default)(this,"_started",void 0),(0,L.default)(this,"_components",void 0),(0,L.default)(this,"_options",void 0),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;s_.info("Use following EIP-1459 ENR Tree URLs: ",r)}}const u_=Ts.PEER_EXCHANGE,c_="/vac/waku/peer-exchange/2.0.0-alpha1";class d_{static createRequest(e){const{numPeers:t}=e;return new d_({query:{numPeers:t},response:void 0})}encode(){return $r.encode(this.proto)}static decode(e){const t=$r.decode(e);return new d_(t)}get query(){return this.proto.query}get response(){return this.proto.response}constructor(e){(0,L.default)(this,"proto",void 0),this.proto=e}}const h_=new gs("peer-exchange");class f_{async query(e){var t;const{numPeers:r,peerId:n}=e,i=d_.createRequest({numPeers:BigInt(r)});if(!await this.components.peerStore.has(n))return{peerInfos:null,error:ks.NO_PEER_AVAILABLE};const s=await this.streamManager.getStream(n);if(!s)return h_.error("Failed to get a stream for remote peer:"+(null==n||null===(t=n.toString)||void 0===t?void 0:t.call(n))),{peerInfos:null,error:ks.NO_STREAM_AVAILABLE};const o=await uo([i.encode()],Ud,s,$d,(async e=>await Ds(e)));try{const e=new qs;o.forEach((t=>{e.append(t)}));const{response:t}=d_.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(Yr).map((async e=>({ENR:await mI.fromRLP(e)})))),error:null}:(h_.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:ks.EMPTY_PAYLOAD})}catch(e){return h_.error("Failed to decode push reply",e),{peerInfos:null,error:ks.DECODE_FAILED}}}constructor(e){(0,L.default)(this,"components",void 0),(0,L.default)(this,"streamManager",void 0),this.components=e,this.streamManager=new yo(c_,e)}}const p_=new gs("peer-exchange-discovery");let g_=wi,m_=Symbol.toStringTag;class v_ extends es{start(){this.isStarted||(p_.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&&(p_.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[g_](){return!0}get[m_](){return"@waku/peer-exchange"}async handleDiscoveredPeer(e){this.runQuery(e.detail.peerId,e.detail.protocols)}async handlePeriodicDiscovery(){const e=this.components.connectionManager.getConnections();await Promise.all(e.map((async e=>{try{const t=e.remotePeer.toString();if(this.peerExpirationRecords.has(t)&&!(this.peerExpirationRecords.get(t)<=Date.now()))return null;const r=await this.components.peerStore.get(e.remotePeer);return this.runQuery(e.remotePeer,r.protocols)}catch(e){return p_.warn("Error getting peer info",e),null}})))}async runQuery(e,t){if(t.includes(c_)&&!this.queryingPeers.has(e.toString())){try{this.queryingPeers.add(e.toString()),await this.query(e)}catch(e){p_.error("Error querying peer",e)}this.peerExpirationRecords.set(e.toString(),Date.now()+this.options.TTL),this.queryingPeers.delete(e.toString())}else p_.info(`Skipping peer ${e} as it is already querying or does not support peer exchange`)}async query(e){const t=e.toString();p_.info("Querying peer exchange for "+t);const{error:r,peerInfos:n}=await this.peerExchange.query({numPeers:60,peerId:e});if(r)p_.error(`Peer exchange query to ${t} failed`,r);else for(const{ENR:e}of n){if(!e){p_.warn(`No ENR in peerInfo object from ${t}, skipping`);continue}const{peerInfo:r,shardInfo:n}=e;if(!r){p_.warn(`No peerInfo in ENR from ${t}, skipping`);continue}const i=!await this.hasShardInfo(r.id)&&n?{metadata:{shardInfo:vi(n)}}:void 0;await this.components.peerStore.merge(r.id,(0,D.default)({tags:{[u_]:{value:50}}},i,r.multiaddrs&&{multiaddrs:r.multiaddrs})),p_.info("Discovered peer: "+r.id.toString()),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r.id,multiaddrs:r.multiaddrs}}))}}async hasShardInfo(e){try{const t=await this.components.peerStore.get(e);return!!t&&t.metadata.has("shardInfo")}catch(t){p_.warn("Error getting shard info for "+e.toString(),t)}return!1}constructor(e,t={}){var r;super(),(0,L.default)(this,"components",void 0),(0,L.default)(this,"peerExchange",void 0),(0,L.default)(this,"options",void 0),(0,L.default)(this,"isStarted",!1),(0,L.default)(this,"queryingPeers",new Set),(0,L.default)(this,"peerExpirationRecords",new Map),(0,L.default)(this,"continuousDiscoveryInterval",null),this.components=e,this.peerExchange=new f_(e),this.options=(0,M.default)((0,D.default)({},t),{TTL:null!==(r=t.TTL)&&void 0!==r?r:3e4}),this.handleDiscoveredPeer=this.handleDiscoveredPeer.bind(this)}}const y_=Ts.PEER_CACHE,b_=e=>!!e&&"object"==typeof e&&"id"in e&&"string"==typeof e.id&&"multiaddrs"in e&&Array.isArray(e.multiaddrs);class w_{get(){return[]}set(e){}remove(){}}class E_{get(){try{const e=localStorage.getItem("waku:peers");return(e?JSON.parse(e):[]).filter(b_)}catch(e){return[]}}set(e){try{localStorage.setItem("waku:peers",JSON.stringify(e))}catch(e){}}remove(){try{localStorage.removeItem("waku:peers")}catch(e){}}}const S_=new gs("peer-cache");let A_=Symbol.toStringTag;class I_ extends es{get[A_](){return"@waku/"+y_}async start(){this.isStarted||(S_.info("Starting Peer Cache Discovery"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),await this.discoverPeers(),this.isStarted=!0)}stop(){this.isStarted&&(S_.info("Stopping Peer Cache Discovery"),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer),this.isStarted=!1)}async discoverPeers(){const e=this.readPeerInfoFromCache();for(const t of e){const e=qu(t.id),r=t.multiaddrs.map((e=>Mc(e)));await this.components.peerStore.has(e)||(await this.components.peerStore.save(e,{multiaddrs:r,tags:{[y_]:{value:50}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:e,multiaddrs:r}})))}}readPeerInfoFromCache(){try{return this.cache.get()}catch(e){return S_.error("Error parsing peers from cache:",e),[]}}writePeerInfoToCache(e){try{this.cache.set(e)}catch(e){S_.error("Error saving peers to cache:",e)}}constructor(e,t){var r;super(),(0,L.default)(this,"components",void 0),(0,L.default)(this,"isStarted",!1),(0,L.default)(this,"cache",void 0),(0,L.default)(this,"handleDiscoveredPeer",(e=>{const{peerId:t,listenAddrs:r}=e.detail,n=r.map((e=>e.toString())),i=t.toString(),s=this.readPeerInfoFromCache(),o=s.findIndex((e=>e.id===i));-1!==o?s[o].multiaddrs=n:s.push({id:i,multiaddrs:n}),this.writePeerInfoToCache(s)})),this.components=e,this.cache=null!==(r=null==t?void 0:t.cache)&&void 0!==r?r:(()=>{try{if("undefined"!=typeof localStorage)return new E_}catch(e){}return new w_})()}}function __(e,t){const r=[kE,xE],n=[];var i;return(null==e?void 0:e.dns)&&n.push((i=r,e=>new l_(e,{enrUrls:i}))),((null==e?void 0:e.peerCache)||t)&&n.push(function(e={}){return t=>new I_(t,e)}({cache:t})),(null==e?void 0:e.peerExchange)&&n.push(function(e={}){return t=>new v_(t,e)}()),n}const C_=new gs("sdk:create");async function k_(e,t,r){var n;return!(null==t?void 0:t.hideWebSocketInfo)&&CE(),async function(e={}){var t;null!==(t=(d=e).privateKey)&&void 0!==t||(d.privateKey=await Pu());const r=new IE((0,M.default)((0,D.default)({},await async function(e){var t,r;const n=vm(kv,e);if(null===n.connectionProtector&&null!=(null===(t=globalThis.process)||void 0===t||null===(r=t.env)||void 0===r?void 0:r.LIBP2P_FORCE_PNET))throw new Pi("Private network is enforced, but no protector was provided");return n}(e)),{peerId:(n=e.privateKey,zu(n.publicKey))}));var n;return!1!==e.start&&await r.start(),r}((0,M.default)((0,D.default)({transports:[om({filter:!1===(null==t?void 0:t.filterMultiaddrs)||CE()?em:tm})],streamMuxers:[Pg()],connectionEncrypters:[Qh()]},t),{services:(0,D.default)({identify:tg({agentVersion:null!=r?r:"js-waku"}),ping:Mg({maxInboundStreams:null!==(n=null==t?void 0:t.pingMaxInboundStreams)&&void 0!==n?n:10}),metadata:ed(e)},null==t?void 0:t.services)}))}var x_=0,T_={size:0,kind:17,base:null,node:null,finalizer:null},P_={size:0,kind:17,base:null,node:null,finalizer:null},R_={size:0,kind:17,base:null,node:null,finalizer:null},L_={size:0,kind:17,base:null,node:null,finalizer:null},D_={size:0,kind:17,base:null,node:null,finalizer:null},M_={size:0,kind:22,base:null,node:null,finalizer:null},N_={size:0,kind:28,base:null,node:null,finalizer:null},O_={size:0,kind:22,base:null,node:null,finalizer:null},U_={size:0,kind:17,base:null,node:null,finalizer:null},F_={size:0,kind:17,base:null,node:null,finalizer:null},B_={size:0,kind:17,base:null,node:null,finalizer:null},$_={size:0,kind:17,base:null,node:null,finalizer:null};$_.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},B_.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},F_.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},O_.base=U_,M_.base=U_;var q_={kind:2,len:5,offset:0,typ:null,name:null,sons:[{kind:1,offset:"parent",len:0,typ:O_,name:"parent",sons:null},{kind:1,offset:"name",len:0,typ:{size:0,kind:29,base:null,node:null,finalizer:null},name:"name",sons:null},{kind:1,offset:"message",len:0,typ:N_,name:"msg",sons:null},{kind:1,offset:"trace",len:0,typ:N_,name:"trace",sons:null},{kind:1,offset:"up",len:0,typ:M_,name:"up",sons:null}]};function z_(e,t){throw e.name=t,0==x_&&function(e){var t=[[]];0!=e.message.length?(t[0].push.call(t[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),t[0].push.apply(t[0],e.message)):t[0].push.call(t[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),t[0].push.call(t[0],32,91),function(e,t,r){null===e[0]&&(e[0]=[]);var n=e[0].length;e[0].length+=r.length;for(var i=0;i<r.length;++i)e[0][n+i]=r.charCodeAt(i)}(t,0,e.name),t[0].push.call(t[0],93,10);var r=function(e){for(var t=rC(e.length),r=0,n=0;r<e.length;){var i=e[r];if(i<128)t[n]=String.fromCharCode(i),r+=1;else{var s=rC(0);e:for(;;){var o=i.toString(16);if(1==(null==o?0:o.length)?s.push("%0"):s.push("%"),s.push(o),r+=1,e.length<=r||e[r]<128)break e;i=e[r]}++x_;try{t[n]=decodeURIComponent(s.join("")),--x_}catch(e){--x_,t[n]=s.join("")}}n+=1}if(t.length<n)for(var a=t.length;a<n;++a)t.push(null);else t.length=n;return t.join("")}(t[0]);throw void 0!==Error?Error(r):r}(e),e}function j_(e,t){return 0==t&&nC(),-1==t&&2147483647==e&&iC(),Math.trunc(e%t)}function K_(e){return e<0?-1*e:e}function V_(e,t){var r=e*t;return sC(r),r}function H_(e,t){var r=e-t;return sC(r),r}function W_(e,t){var r=e+t;return sC(r),r}U_.node=q_,D_.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},U_.base=D_,F_.base=U_,B_.base=F_,$_.base=B_,L_.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},L_.base=B_,R_.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},R_.base=F_,P_.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},P_.base=F_,T_.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},T_.base=F_;var G_,X_,Z_,Y_,Q_,J_=function(){for(var e={},t=0;t<arguments.length;++t){var r=arguments[t];if("object"==typeof r)for(var n=r[0];n<=r[1];++n)e[n]=!0;else e[r]=!0}return e}(17,16,4,18,27,19,23,22,21);function eC(e,t,r){var n=null;switch(r.kind){case 21:case 22:case 23:case 5:n=function(e){return!(null!=J_[e.base.kind])}(r)?[t[0],t[1]]:t;break;case 19:if(null==e)e={};else for(var i in e)delete e[i];for(var i in t)e[i]=t[i];n=e;break;case 18:case 17:lC(n=null!=r.base?eC(e,t,r.base):17==r.kind?null==e?{m_type:r}:e:null==e?{}:e,t,r.node);break;case 4:case 16:if(ArrayBuffer.isView(t))null==e||e.length!=t.length?e=new t.constructor(t):e.set(t,0),n=e;else if(null===t)n=null;else{null!=e&&e.length==t.length||(e=Array(t.length)),n=e;for(var s=0;s<t.length;++s)n[s]=eC(n[s],t[s],r.base)}break;case 24:case 27:if(null===t)n=null;else for(null!=e&&e.length==t.length||(e=Array(t.length)),n=e,s=0;s<t.length;++s)n[s]=eC(n[s],t[s],r.base);break;case 28:null!==t&&(n=t.slice(0));break;default:n=t}return n}function tC(e,t,r){var n=0;return t<=e&&e<=r?n=e:function(e,t,r){z_({message:eC(null,r<t?[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]:[105,110,100,101,120,32].concat(aC(e),[32,110,111,116,32,105,110,32],aC(t),[32,46,46,32],aC(r)),N_),parent:null,m_type:P_,name:null,trace:[],up:null},"IndexDefect")}(e,t,r),n}function rC(e){var t=[];t=Array(e);for(var r=0;r<e;++r)t[r]=null;return t}function nC(){z_({message:[100,105,118,105,115,105,111,110,32,98,121,32,122,101,114,111],parent:null,m_type:$_,name:null,trace:[],up:null},"DivByZeroDefect")}function iC(){z_({message:[111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119],parent:null,m_type:L_,name:null,trace:[],up:null},"OverflowDefect")}function sC(e){(e>2147483647||e<-2147483648)&&iC()}function oC(e,t,r){!function(e,t,r,n,i){var s,o=e[t].length;if(e[t].length<(s=function(e,t,r){var n=0;return t<=e&&e<=r?n=e:z_({message:[118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101],parent:null,m_type:R_,name:null,trace:[],up:null},"RangeDefect"),n}(W_(o,i),0,2147483647)))for(var a=e[t].length;a<s;++a)e[t].push(0);else e[t].length=s;for(var l=0,u=0;u<i;)l=u,e[t][tC(W_(o,l),0,e[t].length-1)]=r.charCodeAt(tC(W_(0,l),0,r.length-1)),u=W_(u,1)}(e,t,r,0,null==r?0:r.length)}function aC(e){var t=[[]];return function(e,t,r){!function(e,t,r){oC(e,t,r+"")}(e,t,r)}(t,0,e),t[0]}function lC(e,t,r){switch(r.kind){case 0:break;case 1:e[r.offset]=eC(e[r.offset],t[r.offset],r.typ);break;case 2:for(var n=0;n<r.sons.length;n++)lC(e,t,r.sons[n]);break;case 3:for(e[r.offset]=eC(e[r.offset],t[r.offset],r.typ),n=0;n<r.sons.length;++n)lC(e,t,r.sons[n][1])}}function uC(e,t){var r=65535,n=(e&r)>>>0,i=(t&r)>>>0;return(n*i>>>0)+((((e>>>16&r)>>>0)*i>>>0)+(n*((t>>>16&r)>>>0)>>>0)>>>0<<16>>>0)>>>0}function cC(e,t){return(e<<t>>>0|e>>>H_(32,t))>>>0}function dC(e){return function(e){for(var t=e.length,r=(a=t,Math.trunc(a/4)),n=0,i=0;i<V_(r,4);){for(var s=0,o=4;0<o;)o=H_(o,1),s=(s<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[tC(W_(i,o),0,e.length-1)]))))>>>0;i=W_(i,4),s=cC(s=uC(s,3432918353),15),n=3864292196+(5*(n=cC(n=(n^(s=uC(s,461845907)))>>>0,13))>>>0)>>>0}for(var a,l=0,u=j_(t,4);0<u;)u=H_(u,1),l=(l<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[tC(W_(i,u),0,e.length-1)]))))>>>0;return l=uC(l,3432918353),l=uC(l=cC(l,15),461845907),n=uC(n=((n=((n=(n^l)>>>0)^Number(BigInt.asUintN(32,BigInt(t))))>>>0)^n>>>16)>>>0,2246822507),n=((n=uC(n=(n^n>>>13)>>>0,3266489909))^n>>>16)>>>0,Number(BigInt.asIntN(32,BigInt(n)))}(e.slice(0,e.length-1+1))}0!=(0,1,X_=j_(K_(dC(G_=[100,117,109,109,121])),1),Z_=j_(K_(dC(G_.concat([32,98]))),1),j_(K_(W_(X_,V_(0,Z_))),1))&&function(e){z_({message:eC(null,e,N_),m_type:T_,parent:null,name:null,trace:[],up:null},"AssertionDefect")}([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]),(e=>{e.Send="send",e.Receive="receive",e.SendEphemeral="sendEphemeral"})(Y_||(Y_={})),(e=>{e.OutMessageSent="sds:out:message-sent",e.InMessageDelivered="sds:in:message-delivered",e.InMessageReceived="sds:in:message-received",e.OutMessageAcknowledged="sds:out:message-acknowledged",e.OutMessagePossiblyAcknowledged="sds:out:message-possibly-acknowledged",e.InMessageMissing="sds:in:message-missing",e.OutSyncSent="sds:out:sync-sent",e.InSyncReceived="sds:in:sync-received",e.InMessageLost="sds:in:message-irretrievably-lost",e.ErrorTask="sds:error-task"})(Q_||(Q_={}));var hC,fC,pC={exports:{}};hC||(hC=1,function(e,t){!function(){var r,n="Expected a function",i="__lodash_hash_undefined__",s="__lodash_placeholder__",o=32,a=128,l=1/0,u=9007199254740991,c=NaN,d=4294967295,h=[["ary",a],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",o],["partialRight",64],["rearg",256]],f="[object Arguments]",p="[object Array]",g="[object Boolean]",m="[object Date]",v="[object Error]",y="[object Function]",b="[object GeneratorFunction]",w="[object Map]",E="[object Number]",S="[object Object]",A="[object Promise]",I="[object RegExp]",_="[object Set]",C="[object String]",k="[object Symbol]",x="[object WeakMap]",T="[object ArrayBuffer]",P="[object DataView]",R="[object Float32Array]",L="[object Float64Array]",D="[object Int8Array]",M="[object Int16Array]",N="[object Int32Array]",O="[object Uint8Array]",U="[object Uint8ClampedArray]",F="[object Uint16Array]",B="[object Uint32Array]",$=/\b__p \+= '';/g,q=/\b(__p \+=) '' \+/g,z=/(__e\(.*?\)|\b__t\)) \+\n'';/g,j=/&(?:amp|lt|gt|quot|#39);/g,K=/[&<>"']/g,V=RegExp(j.source),H=RegExp(K.source),W=/<%-([\s\S]+?)%>/g,G=/<%([\s\S]+?)%>/g,X=/<%=([\s\S]+?)%>/g,Z=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Y=/^\w*$/,Q=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,J=/[\\^$.*+?()[\]{}|]/g,ee=RegExp(J.source),te=/^\s+/,re=/\s/,ne=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,ie=/\{\n\/\* \[wrapped with (.+)\] \*/,se=/,? & /,oe=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ae=/[()=,{}\[\]\/\s]/,le=/\\(\\)?/g,ue=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ce=/\w*$/,de=/^[-+]0x[0-9a-f]+$/i,he=/^0b[01]+$/i,fe=/^\[object .+?Constructor\]$/,pe=/^0o[0-7]+$/i,ge=/^(?:0|[1-9]\d*)$/,me=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ve=/($^)/,ye=/['\n\r\u2028\u2029\\]/g,be="\ud800-\udfff",we="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ee="\\u2700-\\u27bf",Se="a-z\\xdf-\\xf6\\xf8-\\xff",Ae="A-Z\\xc0-\\xd6\\xd8-\\xde",Ie="\\ufe0e\\ufe0f",_e="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\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",Ce="[\ud800-\udfff]",ke="["+_e+"]",xe="["+we+"]",Te="\\d+",Pe="["+Ee+"]",Re="["+Se+"]",Le="[^"+be+_e+Te+Ee+Se+Ae+"]",De="\ud83c[\udffb-\udfff]",Me="[^\ud800-\udfff]",Ne="(?:\ud83c[\udde6-\uddff]){2}",Oe="[\ud800-\udbff][\udc00-\udfff]",Ue="["+Ae+"]",Fe="\\u200d",Be="(?:"+Re+"|"+Le+")",$e="(?:"+Ue+"|"+Le+")",qe="(?:['โ€™](?:d|ll|m|re|s|t|ve))?",ze="(?:['โ€™](?:D|LL|M|RE|S|T|VE))?",je="(?:"+xe+"|"+De+")?",Ke="["+Ie+"]?",Ve=Ke+je+"(?:"+Fe+"(?:"+[Me,Ne,Oe].join("|")+")"+Ke+je+")*",He="(?:"+[Pe,Ne,Oe].join("|")+")"+Ve,We="(?:"+[Me+xe+"?",xe,Ne,Oe,Ce].join("|")+")",Ge=RegExp("['โ€™]","g"),Xe=RegExp(xe,"g"),Ze=RegExp(De+"(?="+De+")|"+We+Ve,"g"),Ye=RegExp([Ue+"?"+Re+"+"+qe+"(?="+[ke,Ue,"$"].join("|")+")",$e+"+"+ze+"(?="+[ke,Ue+Be,"$"].join("|")+")",Ue+"?"+Be+"+"+qe,Ue+"+"+ze,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])|\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Te,He].join("|"),"g"),Qe=RegExp("["+Fe+be+we+Ie+"]"),Je=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,et=["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"],tt=-1,rt={};rt[R]=rt[L]=rt[D]=rt[M]=rt[N]=rt[O]=rt[U]=rt[F]=rt[B]=!0,rt[f]=rt[p]=rt[T]=rt[g]=rt[P]=rt[m]=rt[v]=rt[y]=rt[w]=rt[E]=rt[S]=rt[I]=rt[_]=rt[C]=rt[x]=!1;var nt={};nt[f]=nt[p]=nt[T]=nt[P]=nt[g]=nt[m]=nt[R]=nt[L]=nt[D]=nt[M]=nt[N]=nt[w]=nt[E]=nt[S]=nt[I]=nt[_]=nt[C]=nt[k]=nt[O]=nt[U]=nt[F]=nt[B]=!0,nt[v]=nt[y]=nt[x]=!1;var it={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},st=parseFloat,ot=parseInt,at="object"==typeof is&&is&&is.Object===Object&&is,lt="object"==typeof self&&self&&self.Object===Object&&self,ut=at||lt||Function("return this")(),ct=t&&!t.nodeType&&t,dt=ct&&e&&!e.nodeType&&e,ht=dt&&dt.exports===ct,ft=ht&&at.process,pt=(()=>{try{return dt&&dt.require&&dt.require("util").types||ft&&ft.binding&&ft.binding("util")}catch(e){}})(),gt=pt&&pt.isArrayBuffer,mt=pt&&pt.isDate,vt=pt&&pt.isMap,yt=pt&&pt.isRegExp,bt=pt&&pt.isSet,wt=pt&&pt.isTypedArray;function Et(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}function St(e,t,r,n){for(var i=-1,s=null==e?0:e.length;++i<s;){var o=e[i];t(n,o,r(o),e)}return n}function At(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}function It(e,t){for(var r=null==e?0:e.length;r--&&!1!==t(e[r],r,e););return e}function _t(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}function Ct(e,t){for(var r=-1,n=null==e?0:e.length,i=0,s=[];++r<n;){var o=e[r];t(o,r,e)&&(s[i++]=o)}return s}function kt(e,t){return!(null==e||!e.length)&&Ut(e,t,0)>-1}function xt(e,t,r){for(var n=-1,i=null==e?0:e.length;++n<i;)if(r(t,e[n]))return!0;return!1}function Tt(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}function Pt(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}function Rt(e,t,r,n){var i=-1,s=null==e?0:e.length;for(n&&s&&(r=e[++i]);++i<s;)r=t(r,e[i],i,e);return r}function Lt(e,t,r,n){var i=null==e?0:e.length;for(n&&i&&(r=e[--i]);i--;)r=t(r,e[i],i,e);return r}function Dt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var Mt=qt("length");function Nt(e,t,r){var n;return r(e,((e,r,i)=>{if(t(e,r,i))return n=r,!1})),n}function Ot(e,t,r,n){for(var i=e.length,s=r+(n?1:-1);n?s--:++s<i;)if(t(e[s],s,e))return s;return-1}function Ut(e,t,r){return t==t?((e,t,r)=>{for(var n=r-1,i=e.length;++n<i;)if(e[n]===t)return n;return-1})(e,t,r):Ot(e,Bt,r)}function Ft(e,t,r,n){for(var i=r-1,s=e.length;++i<s;)if(n(e[i],t))return i;return-1}function Bt(e){return e!=e}function $t(e,t){var r=null==e?0:e.length;return r?Kt(e,t)/r:c}function qt(e){return t=>null==t?r:t[e]}function zt(e){return t=>null==e?r:e[t]}function jt(e,t,r,n,i){return i(e,((e,i,s)=>{r=n?(n=!1,e):t(r,e,i,s)})),r}function Kt(e,t){for(var n,i=-1,s=e.length;++i<s;){var o=t(e[i]);o!==r&&(n=n===r?o:n+o)}return n}function Vt(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}function Ht(e){return e?e.slice(0,lr(e)+1).replace(te,""):e}function Wt(e){return t=>e(t)}function Gt(e,t){return Tt(t,(t=>e[t]))}function Xt(e,t){return e.has(t)}function Zt(e,t){for(var r=-1,n=e.length;++r<n&&Ut(t,e[r],0)>-1;);return r}function Yt(e,t){for(var r=e.length;r--&&Ut(t,e[r],0)>-1;);return r}var Qt=zt({"ร€":"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","ล’":"Oe","ล“":"oe","ล‰":"'n","ลฟ":"s"}),Jt=zt({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function er(e){return"\\"+it[e]}function tr(e){return Qe.test(e)}function rr(e){var t=-1,r=Array(e.size);return e.forEach(((e,n)=>{r[++t]=[n,e]})),r}function nr(e,t){return r=>e(t(r))}function ir(e,t){for(var r=-1,n=e.length,i=0,o=[];++r<n;){var a=e[r];a!==t&&a!==s||(e[r]=s,o[i++]=r)}return o}function sr(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=e})),r}function or(e){return tr(e)?(e=>{for(var t=Ze.lastIndex=0;Ze.test(e);)++t;return t})(e):Mt(e)}function ar(e){return tr(e)?(e=>e.match(Ze)||[])(e):(e=>e.split(""))(e)}function lr(e){for(var t=e.length;t--&&re.test(e.charAt(t)););return t}var ur=zt({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"}),cr=function e(t){var re,be=(t=null==t?ut:cr.defaults(ut.Object(),t,cr.pick(ut,et))).Array,we=t.Date,Ee=t.Error,Se=t.Function,Ae=t.Math,Ie=t.Object,_e=t.RegExp,Ce=t.String,ke=t.TypeError,xe=be.prototype,Te=Se.prototype,Pe=Ie.prototype,Re=t["__core-js_shared__"],Le=Te.toString,De=Pe.hasOwnProperty,Me=0,Ne=(re=/[^.]+$/.exec(Re&&Re.keys&&Re.keys.IE_PROTO||""))?"Symbol(src)_1."+re:"",Oe=Pe.toString,Ue=Le.call(Ie),Fe=ut._,Be=_e("^"+Le.call(De).replace(J,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),$e=ht?t.Buffer:r,qe=t.Symbol,ze=t.Uint8Array,je=$e?$e.allocUnsafe:r,Ke=nr(Ie.getPrototypeOf,Ie),Ve=Ie.create,He=Pe.propertyIsEnumerable,We=xe.splice,Ze=qe?qe.isConcatSpreadable:r,Qe=qe?qe.iterator:r,it=qe?qe.toStringTag:r,at=(()=>{try{var e=as(Ie,"defineProperty");return e({},"",{}),e}catch(e){}})(),lt=t.clearTimeout!==ut.clearTimeout&&t.clearTimeout,ct=we&&we.now!==ut.Date.now&&we.now,dt=t.setTimeout!==ut.setTimeout&&t.setTimeout,ft=Ae.ceil,pt=Ae.floor,Mt=Ie.getOwnPropertySymbols,zt=$e?$e.isBuffer:r,dr=t.isFinite,hr=xe.join,fr=nr(Ie.keys,Ie),pr=Ae.max,gr=Ae.min,mr=we.now,vr=t.parseInt,yr=Ae.random,br=xe.reverse,wr=as(t,"DataView"),Er=as(t,"Map"),Sr=as(t,"Promise"),Ar=as(t,"Set"),Ir=as(t,"WeakMap"),_r=as(Ie,"create"),Cr=Ir&&new Ir,kr={},xr=Ds(wr),Tr=Ds(Er),Pr=Ds(Sr),Rr=Ds(Ar),Lr=Ds(Ir),Dr=qe?qe.prototype:r,Mr=Dr?Dr.valueOf:r,Nr=Dr?Dr.toString:r;function Or(e){if(Yo(e)&&!$o(e)&&!(e instanceof $r)){if(e instanceof Br)return e;if(De.call(e,"__wrapped__"))return Ms(e)}return new Br(e)}var Ur=(()=>{function e(){}return t=>{if(!Zo(t))return{};if(Ve)return Ve(t);e.prototype=t;var n=new e;return e.prototype=r,n}})();function Fr(){}function Br(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=r}function $r(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=d,this.__views__=[]}function qr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function zr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function jr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Kr(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new jr;++t<r;)this.add(e[t])}function Vr(e){var t=this.__data__=new zr(e);this.size=t.size}function Hr(e,t){var r=$o(e),n=!r&&Bo(e),i=!r&&!n&&Ko(e),s=!r&&!n&&!i&&sa(e),o=r||n||i||s,a=o?Vt(e.length,Ce):[],l=a.length;for(var u in e)!t&&!De.call(e,u)||o&&("length"==u||i&&("offset"==u||"parent"==u)||s&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||ps(u,l))||a.push(u);return a}function Wr(e){var t=e.length;return t?e[Kn(0,t-1)]:r}function Gr(e,t){return Ps(_i(e),nn(t,0,e.length))}function Xr(e){return Ps(_i(e))}function Zr(e,t,n){(n!==r&&!Oo(e[t],n)||n===r&&!(t in e))&&tn(e,t,n)}function Yr(e,t,n){var i=e[t];De.call(e,t)&&Oo(i,n)&&(n!==r||t in e)||tn(e,t,n)}function Qr(e,t){for(var r=e.length;r--;)if(Oo(e[r][0],t))return r;return-1}function Jr(e,t,r,n){return un(e,((e,i,s)=>{t(n,e,r(e),s)})),n}function en(e,t){return e&&Ci(t,ka(t),e)}function tn(e,t,r){"__proto__"==t&&at?at(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}function rn(e,t){for(var n=-1,i=t.length,s=be(i),o=null==e;++n<i;)s[n]=o?r:Sa(e,t[n]);return s}function nn(e,t,n){return e==e&&(n!==r&&(e=e<=n?e:n),t!==r&&(e=e>=t?e:t)),e}function sn(e,t,n,i,s,o){var a,l=1&t,u=2&t,c=4&t;if(n&&(a=s?n(e,i,s,o):n(e)),a!==r)return a;if(!Zo(e))return e;var d=$o(e);if(d){if(a=(e=>{var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&De.call(e,"index")&&(r.index=e.index,r.input=e.input),r})(e),!l)return _i(e,a)}else{var h=cs(e),p=h==y||h==b;if(Ko(e))return bi(e,l);if(h==S||h==f||p&&!s){if(a=u||p?{}:hs(e),!l)return u?((e,t)=>Ci(e,us(e),t))(e,((e,t)=>e&&Ci(t,xa(t),e))(a,e)):((e,t)=>Ci(e,ls(e),t))(e,en(a,e))}else{if(!nt[h])return s?e:{};a=((e,t,r)=>{var n=e.constructor;switch(t){case T:return wi(e);case g:case m:return new n(+e);case P:return((e,t)=>{var r=t?wi(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)})(e,r);case R:case L:case D:case M:case N:case O:case U:case F:case B:return Ei(e,r);case w:return new n;case E:case C:return new n(e);case I:return(e=>{var t=new e.constructor(e.source,ce.exec(e));return t.lastIndex=e.lastIndex,t})(e);case _:return new n;case k:return(e=>Mr?Ie(Mr.call(e)):{})(e)}})(e,h,l)}}o||(o=new Vr);var v=o.get(e);if(v)return v;o.set(e,a),ra(e)?e.forEach((r=>{a.add(sn(r,t,n,r,e,o))})):Qo(e)&&e.forEach(((r,i)=>{a.set(i,sn(r,t,n,i,e,o))}));var A=d?r:(c?u?es:Ji:u?xa:ka)(e);return At(A||e,((r,i)=>{A&&(r=e[i=r]),Yr(a,i,sn(r,t,n,i,e,o))})),a}function on(e,t,n){var i=n.length;if(null==e)return!i;for(e=Ie(e);i--;){var s=n[i],o=t[s],a=e[s];if(a===r&&!(s in e)||!o(a))return!1}return!0}function an(e,t,i){if("function"!=typeof e)throw new ke(n);return Cs((()=>{e.apply(r,i)}),t)}function ln(e,t,r,n){var i=-1,s=kt,o=!0,a=e.length,l=[],u=t.length;if(!a)return l;r&&(t=Tt(t,Wt(r))),n?(s=xt,o=!1):t.length>=200&&(s=Xt,o=!1,t=new Kr(t));e:for(;++i<a;){var c=e[i],d=null==r?c:r(c);if(c=n||0!==c?c:0,o&&d==d){for(var h=u;h--;)if(t[h]===d)continue e;l.push(c)}else s(t,d,n)||l.push(c)}return l}Or.templateSettings={escape:W,evaluate:G,interpolate:X,variable:"",imports:{_:Or}},Or.prototype=Fr.prototype,Or.prototype.constructor=Or,Br.prototype=Ur(Fr.prototype),Br.prototype.constructor=Br,$r.prototype=Ur(Fr.prototype),$r.prototype.constructor=$r,qr.prototype.clear=function(){this.__data__=_r?_r(null):{},this.size=0},qr.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},qr.prototype.get=function(e){var t=this.__data__;if(_r){var n=t[e];return n===i?r:n}return De.call(t,e)?t[e]:r},qr.prototype.has=function(e){var t=this.__data__;return _r?t[e]!==r:De.call(t,e)},qr.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=_r&&t===r?i:t,this},zr.prototype.clear=function(){this.__data__=[],this.size=0},zr.prototype.delete=function(e){var t=this.__data__,r=Qr(t,e);return!(r<0||(r==t.length-1?t.pop():We.call(t,r,1),--this.size,0))},zr.prototype.get=function(e){var t=this.__data__,n=Qr(t,e);return n<0?r:t[n][1]},zr.prototype.has=function(e){return Qr(this.__data__,e)>-1},zr.prototype.set=function(e,t){var r=this.__data__,n=Qr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},jr.prototype.clear=function(){this.size=0,this.__data__={hash:new qr,map:new(Er||zr),string:new qr}},jr.prototype.delete=function(e){var t=ss(this,e).delete(e);return this.size-=t?1:0,t},jr.prototype.get=function(e){return ss(this,e).get(e)},jr.prototype.has=function(e){return ss(this,e).has(e)},jr.prototype.set=function(e,t){var r=ss(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},Kr.prototype.add=Kr.prototype.push=function(e){return this.__data__.set(e,i),this},Kr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.clear=function(){this.__data__=new zr,this.size=0},Vr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Vr.prototype.get=function(e){return this.__data__.get(e)},Vr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof zr){var n=r.__data__;if(!Er||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new jr(n)}return r.set(e,t),this.size=r.size,this};var un=Ti(vn),cn=Ti(yn,!0);function dn(e,t){var r=!0;return un(e,((e,n,i)=>r=!!t(e,n,i))),r}function hn(e,t,n){for(var i=-1,s=e.length;++i<s;){var o=e[i],a=t(o);if(null!=a&&(l===r?a==a&&!ia(a):n(a,l)))var l=a,u=o}return u}function fn(e,t){var r=[];return un(e,((e,n,i)=>{t(e,n,i)&&r.push(e)})),r}function pn(e,t,r,n,i){var s=-1,o=e.length;for(r||(r=fs),i||(i=[]);++s<o;){var a=e[s];t>0&&r(a)?t>1?pn(a,t-1,r,n,i):Pt(i,a):n||(i[i.length]=a)}return i}var gn=Pi(),mn=Pi(!0);function vn(e,t){return e&&gn(e,t,ka)}function yn(e,t){return e&&mn(e,t,ka)}function bn(e,t){return Ct(t,(t=>Wo(e[t])))}function wn(e,t){for(var n=0,i=(t=gi(t,e)).length;null!=e&&n<i;)e=e[Ls(t[n++])];return n&&n==i?e:r}function En(e,t,r){var n=t(e);return $o(e)?n:Pt(n,r(e))}function Sn(e){return null==e?e===r?"[object Undefined]":"[object Null]":it&&it in Ie(e)?(e=>{var t=De.call(e,it),n=e[it];try{e[it]=r;var i=!0}catch(e){}var s=Oe.call(e);return i&&(t?e[it]=n:delete e[it]),s})(e):(e=>Oe.call(e))(e)}function An(e,t){return e>t}function In(e,t){return null!=e&&De.call(e,t)}function _n(e,t){return null!=e&&t in Ie(e)}function Cn(e,t,n){for(var i=n?xt:kt,s=e[0].length,o=e.length,a=o,l=be(o),u=1/0,c=[];a--;){var d=e[a];a&&t&&(d=Tt(d,Wt(t))),u=gr(d.length,u),l[a]=!n&&(t||s>=120&&d.length>=120)?new Kr(a&&d):r}d=e[0];var h=-1,f=l[0];e:for(;++h<s&&c.length<u;){var p=d[h],g=t?t(p):p;if(p=n||0!==p?p:0,!(f?Xt(f,g):i(c,g,n))){for(a=o;--a;){var m=l[a];if(!(m?Xt(m,g):i(e[a],g,n)))continue e}f&&f.push(g),c.push(p)}}return c}function kn(e,t,n){var i=null==(e=As(e,t=gi(t,e)))?e:e[Ls(Vs(t))];return null==i?r:Et(i,e,n)}function xn(e){return Yo(e)&&Sn(e)==f}function Tn(e,t,n,i,s){return e===t||(null==e||null==t||!Yo(e)&&!Yo(t)?e!=e&&t!=t:((e,t,n,i,s,o)=>{var a=$o(e),l=$o(t),u=a?p:cs(e),c=l?p:cs(t),d=(u=u==f?S:u)==S,h=(c=c==f?S:c)==S,y=u==c;if(y&&Ko(e)){if(!Ko(t))return!1;a=!0,d=!1}if(y&&!d)return o||(o=new Vr),a||sa(e)?Yi(e,t,n,i,s,o):((e,t,r,n,i,s,o)=>{switch(r){case P:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case T:return!(e.byteLength!=t.byteLength||!s(new ze(e),new ze(t)));case g:case m:case E:return Oo(+e,+t);case v:return e.name==t.name&&e.message==t.message;case I:case C:return e==t+"";case w:var a=rr;case _:var l=1&n;if(a||(a=sr),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=2,o.set(e,t);var c=Yi(a(e),a(t),n,i,s,o);return o.delete(e),c;case k:if(Mr)return Mr.call(e)==Mr.call(t)}return!1})(e,t,u,n,i,s,o);if(!(1&n)){var b=d&&De.call(e,"__wrapped__"),A=h&&De.call(t,"__wrapped__");if(b||A){var x=b?e.value():e,R=A?t.value():t;return o||(o=new Vr),s(x,R,n,i,o)}}return!!y&&(o||(o=new Vr),((e,t,n,i,s,o)=>{var a=1&n,l=Ji(e),u=l.length;if(u!=Ji(t).length&&!a)return!1;for(var c=u;c--;){var d=l[c];if(!(a?d in t:De.call(t,d)))return!1}var h=o.get(e),f=o.get(t);if(h&&f)return h==t&&f==e;var p=!0;o.set(e,t),o.set(t,e);for(var g=a;++c<u;){var m=e[d=l[c]],v=t[d];if(i)var y=a?i(v,m,d,t,e,o):i(m,v,d,e,t,o);if(!(y===r?m===v||s(m,v,n,i,o):y)){p=!1;break}g||(g="constructor"==d)}if(p&&!g){var b=e.constructor,w=t.constructor;b==w||!("constructor"in e)||!("constructor"in t)||"function"==typeof b&&b instanceof b&&"function"==typeof w&&w instanceof w||(p=!1)}return o.delete(e),o.delete(t),p})(e,t,n,i,s,o))})(e,t,n,i,Tn,s))}function Pn(e,t,n,i){var s=n.length,o=s,a=!i;if(null==e)return!o;for(e=Ie(e);s--;){var l=n[s];if(a&&l[2]?l[1]!==e[l[0]]:!(l[0]in e))return!1}for(;++s<o;){var u=(l=n[s])[0],c=e[u],d=l[1];if(a&&l[2]){if(c===r&&!(u in e))return!1}else{var h=new Vr;if(i)var f=i(c,d,u,e,t,h);if(!(f===r?Tn(d,c,3,i,h):f))return!1}}return!0}function Rn(e){return!(!Zo(e)||(e=>!!Ne&&Ne in e)(e))&&(Wo(e)?Be:fe).test(Ds(e))}function Ln(e){return"function"==typeof e?e:null==e?Ja:"object"==typeof e?$o(e)?Un(e[0],e[1]):On(e):ll(e)}function Dn(e){if(!bs(e))return fr(e);var t=[];for(var r in Ie(e))De.call(e,r)&&"constructor"!=r&&t.push(r);return t}function Mn(e,t){return e<t}function Nn(e,t){var r=-1,n=zo(e)?be(e.length):[];return un(e,((e,i,s)=>{n[++r]=t(e,i,s)})),n}function On(e){var t=os(e);return 1==t.length&&t[0][2]?Es(t[0][0],t[0][1]):r=>r===e||Pn(r,e,t)}function Un(e,t){return ms(e)&&ws(t)?Es(Ls(e),t):n=>{var i=Sa(n,e);return i===r&&i===t?Aa(n,e):Tn(t,i,3)}}function Fn(e,t,n,i,s){e!==t&&gn(t,((o,a)=>{if(s||(s=new Vr),Zo(o))((e,t,n,i,s,o,a)=>{var l=Is(e,n),u=Is(t,n),c=a.get(u);if(c)Zr(e,n,c);else{var d=o?o(l,u,n+"",e,t,a):r,h=d===r;if(h){var f=$o(u),p=!f&&Ko(u),g=!f&&!p&&sa(u);d=u,f||p||g?$o(l)?d=l:jo(l)?d=_i(l):p?(h=!1,d=bi(u,!0)):g?(h=!1,d=Ei(u,!0)):d=[]:ea(u)||Bo(u)?(d=l,Bo(l)?d=fa(l):Zo(l)&&!Wo(l)||(d=hs(u))):h=!1}h&&(a.set(u,d),s(d,u,i,o,a),a.delete(u)),Zr(e,n,d)}})(e,t,a,n,Fn,i,s);else{var l=i?i(Is(e,a),o,a+"",e,t,s):r;l===r&&(l=o),Zr(e,a,l)}}),xa)}function Bn(e,t){var n=e.length;if(n)return ps(t+=t<0?n:0,n)?e[t]:r}function $n(e,t,r){t=t.length?Tt(t,(e=>$o(e)?t=>wn(t,1===e.length?e[0]:e):e)):[Ja];var n=-1;t=Tt(t,Wt(is()));var i=Nn(e,(e=>{var r=Tt(t,(t=>t(e)));return{criteria:r,index:++n,value:e}}));return((e,t)=>{var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e})(i,((e,t)=>((e,t,r)=>{for(var n=-1,i=e.criteria,s=t.criteria,o=i.length,a=r.length;++n<o;){var l=Si(i[n],s[n]);if(l)return n>=a?l:l*("desc"==r[n]?-1:1)}return e.index-t.index})(e,t,r)))}function qn(e,t,r){for(var n=-1,i=t.length,s={};++n<i;){var o=t[n],a=wn(e,o);r(a,o)&&Xn(s,gi(o,e),a)}return s}function zn(e,t,r,n){var i=n?Ft:Ut,s=-1,o=t.length,a=e;for(e===t&&(t=_i(t)),r&&(a=Tt(e,Wt(r)));++s<o;)for(var l=0,u=t[s],c=r?r(u):u;(l=i(a,c,l,n))>-1;)a!==e&&We.call(a,l,1),We.call(e,l,1);return e}function jn(e,t){for(var r=e?t.length:0,n=r-1;r--;){var i=t[r];if(r==n||i!==s){var s=i;ps(i)?We.call(e,i,1):ai(e,i)}}return e}function Kn(e,t){return e+pt(yr()*(t-e+1))}function Vn(e,t){var r="";if(!e||t<1||t>u)return r;do{t%2&&(r+=e),(t=pt(t/2))&&(e+=e)}while(t);return r}function Hn(e,t){return ks(Ss(e,t,Ja),e+"")}function Wn(e){return Wr(Oa(e))}function Gn(e,t){var r=Oa(e);return Ps(r,nn(t,0,r.length))}function Xn(e,t,n,i){if(!Zo(e))return e;for(var s=-1,o=(t=gi(t,e)).length,a=o-1,l=e;null!=l&&++s<o;){var u=Ls(t[s]),c=n;if("__proto__"===u||"constructor"===u||"prototype"===u)return e;if(s!=a){var d=l[u];(c=i?i(d,u,l):r)===r&&(c=Zo(d)?d:ps(t[s+1])?[]:{})}Yr(l,u,c),l=l[u]}return e}var Zn=Cr?(e,t)=>(Cr.set(e,t),e):Ja,Yn=at?(e,t)=>at(e,"toString",{configurable:!0,enumerable:!1,value:Za(t),writable:!0}):Ja;function Qn(e){return Ps(Oa(e))}function Jn(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var s=be(i);++n<i;)s[n]=e[n+t];return s}function ei(e,t){var r;return un(e,((e,n,i)=>!(r=t(e,n,i)))),!!r}function ti(e,t,r){var n=0,i=null==e?n:e.length;if("number"==typeof t&&t==t&&i<=2147483647){for(;n<i;){var s=n+i>>>1,o=e[s];null!==o&&!ia(o)&&(r?o<=t:o<t)?n=s+1:i=s}return i}return ri(e,t,Ja,r)}function ri(e,t,n,i){var s=0,o=null==e?0:e.length;if(0===o)return 0;for(var a=(t=n(t))!=t,l=null===t,u=ia(t),c=t===r;s<o;){var d=pt((s+o)/2),h=n(e[d]),f=h!==r,p=null===h,g=h==h,m=ia(h);if(a)var v=i||g;else v=c?g&&(i||f):l?g&&f&&(i||!p):u?g&&f&&!p&&(i||!m):!p&&!m&&(i?h<=t:h<t);v?s=d+1:o=d}return gr(o,4294967294)}function ni(e,t){for(var r=-1,n=e.length,i=0,s=[];++r<n;){var o=e[r],a=t?t(o):o;if(!r||!Oo(a,l)){var l=a;s[i++]=0===o?0:o}}return s}function ii(e){return"number"==typeof e?e:ia(e)?c:+e}function si(e){if("string"==typeof e)return e;if($o(e))return Tt(e,si)+"";if(ia(e))return Nr?Nr.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function oi(e,t,r){var n=-1,i=kt,s=e.length,o=!0,a=[],l=a;if(r)o=!1,i=xt;else if(s>=200){var u=t?null:Vi(e);if(u)return sr(u);o=!1,i=Xt,l=new Kr}else l=t?[]:a;e:for(;++n<s;){var c=e[n],d=t?t(c):c;if(c=r||0!==c?c:0,o&&d==d){for(var h=l.length;h--;)if(l[h]===d)continue e;t&&l.push(d),a.push(c)}else i(l,d,r)||(l!==a&&l.push(d),a.push(c))}return a}function ai(e,t){return null==(e=As(e,t=gi(t,e)))||delete e[Ls(Vs(t))]}function li(e,t,r,n){return Xn(e,t,r(wn(e,t)),n)}function ui(e,t,r,n){for(var i=e.length,s=n?i:-1;(n?s--:++s<i)&&t(e[s],s,e););return r?Jn(e,n?0:s,n?s+1:i):Jn(e,n?s+1:0,n?i:s)}function ci(e,t){var r=e;return r instanceof $r&&(r=r.value()),Rt(t,((e,t)=>t.func.apply(t.thisArg,Pt([e],t.args))),r)}function di(e,t,r){var n=e.length;if(n<2)return n?oi(e[0]):[];for(var i=-1,s=be(n);++i<n;)for(var o=e[i],a=-1;++a<n;)a!=i&&(s[i]=ln(s[i]||o,e[a],t,r));return oi(pn(s,1),t,r)}function hi(e,t,n){for(var i=-1,s=e.length,o=t.length,a={};++i<s;){var l=i<o?t[i]:r;n(a,e[i],l)}return a}function fi(e){return jo(e)?e:[]}function pi(e){return"function"==typeof e?e:Ja}function gi(e,t){return $o(e)?e:ms(e,t)?[e]:Rs(pa(e))}var mi=Hn;function vi(e,t,n){var i=e.length;return n=n===r?i:n,!t&&n>=i?e:Jn(e,t,n)}var yi=lt||(e=>ut.clearTimeout(e));function bi(e,t){if(t)return e.slice();var r=e.length,n=je?je(r):new e.constructor(r);return e.copy(n),n}function wi(e){var t=new e.constructor(e.byteLength);return new ze(t).set(new ze(e)),t}function Ei(e,t){var r=t?wi(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function Si(e,t){if(e!==t){var n=e!==r,i=null===e,s=e==e,o=ia(e),a=t!==r,l=null===t,u=t==t,c=ia(t);if(!l&&!c&&!o&&e>t||o&&a&&u&&!l&&!c||i&&a&&u||!n&&u||!s)return 1;if(!i&&!o&&!c&&e<t||c&&n&&s&&!i&&!o||l&&n&&s||!a&&s||!u)return-1}return 0}function Ai(e,t,r,n){for(var i=-1,s=e.length,o=r.length,a=-1,l=t.length,u=pr(s-o,0),c=be(l+u),d=!n;++a<l;)c[a]=t[a];for(;++i<o;)(d||i<s)&&(c[r[i]]=e[i]);for(;u--;)c[a++]=e[i++];return c}function Ii(e,t,r,n){for(var i=-1,s=e.length,o=-1,a=r.length,l=-1,u=t.length,c=pr(s-a,0),d=be(c+u),h=!n;++i<c;)d[i]=e[i];for(var f=i;++l<u;)d[f+l]=t[l];for(;++o<a;)(h||i<s)&&(d[f+r[o]]=e[i++]);return d}function _i(e,t){var r=-1,n=e.length;for(t||(t=be(n));++r<n;)t[r]=e[r];return t}function Ci(e,t,n,i){var s=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var l=t[o],u=i?i(n[l],e[l],l,n,e):r;u===r&&(u=e[l]),s?tn(n,l,u):Yr(n,l,u)}return n}function ki(e,t){return(r,n)=>{var i=$o(r)?St:Jr,s=t?t():{};return i(r,e,is(n,2),s)}}function xi(e){return Hn(((t,n)=>{var i=-1,s=n.length,o=s>1?n[s-1]:r,a=s>2?n[2]:r;for(o=e.length>3&&"function"==typeof o?(s--,o):r,a&&gs(n[0],n[1],a)&&(o=s<3?r:o,s=1),t=Ie(t);++i<s;){var l=n[i];l&&e(t,l,i,o)}return t}))}function Ti(e,t){return(r,n)=>{if(null==r)return r;if(!zo(r))return e(r,n);for(var i=r.length,s=t?i:-1,o=Ie(r);(t?s--:++s<i)&&!1!==n(o[s],s,o););return r}}function Pi(e){return(t,r,n)=>{for(var i=-1,s=Ie(t),o=n(t),a=o.length;a--;){var l=o[e?a:++i];if(!1===r(s[l],l,s))break}return t}}function Ri(e){return t=>{var n=tr(t=pa(t))?ar(t):r,i=n?n[0]:t.charAt(0),s=n?vi(n,1).join(""):t.slice(1);return i[e]()+s}}function Li(e){return t=>Rt(Wa(Ba(t).replace(Ge,"")),e,"")}function Di(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=Ur(e.prototype),n=e.apply(r,t);return Zo(n)?n:r}}function Mi(e){return(t,n,i)=>{var s=Ie(t);if(!zo(t)){var o=is(n,3);t=ka(t),n=e=>o(s[e],e,s)}var a=e(t,n,i);return a>-1?s[o?t[a]:a]:r}}function Ni(e){return Qi((function(t){var i=t.length,s=i,o=Br.prototype.thru;for(e&&t.reverse();s--;){var a=t[s];if("function"!=typeof a)throw new ke(n);if(o&&!l&&"wrapper"==rs(a))var l=new Br([],!0)}for(s=l?s:i;++s<i;){var u=rs(a=t[s]),c="wrapper"==u?ts(a):r;l=c&&vs(c[0])&&424==c[1]&&!c[4].length&&1==c[9]?l[rs(c[0])].apply(l,c[3]):1==a.length&&vs(a)?l[u]():l.thru(a)}return function(){var e=arguments,r=e[0];if(l&&1==e.length&&$o(r))return l.plant(r).value();for(var n=0,s=i?t[n].apply(this,e):r;++n<i;)s=t[n].call(this,s);return s}}))}function Oi(e,t,n,i,s,o,l,u,c,d){var h=t&a,f=1&t,p=2&t,g=24&t,m=512&t,v=p?r:Di(e);return function a(){for(var y=arguments.length,b=be(y),w=y;w--;)b[w]=arguments[w];if(g)var E=ns(a),S=((e,t)=>{for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n})(b,E);if(i&&(b=Ai(b,i,s,g)),o&&(b=Ii(b,o,l,g)),y-=S,g&&y<d){var A=ir(b,E);return ji(e,t,Oi,a.placeholder,n,b,A,u,c,d-y)}var I=f?n:this,_=p?I[e]:e;return y=b.length,u?b=((e,t)=>{for(var n=e.length,i=gr(t.length,n),s=_i(e);i--;){var o=t[i];e[i]=ps(o,n)?s[o]:r}return e})(b,u):m&&y>1&&b.reverse(),h&&c<y&&(b.length=c),this&&this!==ut&&this instanceof a&&(_=v||Di(_)),_.apply(I,b)}}function Ui(e,t){return(r,n)=>((e,t,r,n)=>(vn(e,((e,i,s)=>{t(n,r(e),i,s)})),n))(r,e,t(n),{})}function Fi(e,t){return(n,i)=>{var s;if(n===r&&i===r)return t;if(n!==r&&(s=n),i!==r){if(s===r)return i;"string"==typeof n||"string"==typeof i?(n=si(n),i=si(i)):(n=ii(n),i=ii(i)),s=e(n,i)}return s}}function Bi(e){return Qi((function(t){return t=Tt(t,Wt(is())),Hn((function(r){var n=this;return e(t,(e=>Et(e,n,r)))}))}))}function $i(e,t){var n=(t=t===r?" ":si(t)).length;if(n<2)return n?Vn(t,e):t;var i=Vn(t,ft(e/or(t)));return tr(t)?vi(ar(i),0,e).join(""):i.slice(0,e)}function qi(e){return(t,n,i)=>(i&&"number"!=typeof i&&gs(t,n,i)&&(n=i=r),t=ua(t),n===r?(n=t,t=0):n=ua(n),((e,t,r,n)=>{for(var i=-1,s=pr(ft((t-e)/(r||1)),0),o=be(s);s--;)o[n?s:++i]=e,e+=r;return o})(t,n,i=i===r?t<n?1:-1:ua(i),e))}function zi(e){return(t,r)=>("string"==typeof t&&"string"==typeof r||(t=ha(t),r=ha(r)),e(t,r))}function ji(e,t,n,i,s,a,l,u,c,d){var h=8&t;t|=h?o:64,4&(t&=~(h?64:o))||(t&=-4);var f=[e,t,s,h?a:r,h?l:r,h?r:a,h?r:l,u,c,d],p=n.apply(r,f);return vs(e)&&_s(p,f),p.placeholder=i,xs(p,e,t)}function Ki(e){var t=Ae[e];return(e,r)=>{if(e=ha(e),(r=null==r?0:gr(ca(r),292))&&dr(e)){var n=(pa(e)+"e").split("e");return+((n=(pa(t(n[0]+"e"+(+n[1]+r)))+"e").split("e"))[0]+"e"+(+n[1]-r))}return t(e)}}var Vi=Ar&&1/sr(new Ar([,-0]))[1]==l?e=>new Ar(e):il;function Hi(e){return t=>{var r=cs(t);return r==w?rr(t):r==_?function(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=[e,e]})),r}(t):((e,t)=>Tt(t,(t=>[t,e[t]])))(t,e(t))}}function Wi(e,t,i,l,u,c,d,h){var f=2&t;if(!f&&"function"!=typeof e)throw new ke(n);var p=l?l.length:0;if(p||(t&=-97,l=u=r),d=d===r?d:pr(ca(d),0),h=h===r?h:ca(h),p-=u?u.length:0,64&t){var g=l,m=u;l=u=r}var v=f?r:ts(e),y=[e,t,i,l,u,g,m,c,d,h];if(v&&((e,t)=>{var r=e[1],n=t[1],i=r|n,o=i<131,l=n==a&&8==r||n==a&&256==r&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==r;if(!o&&!l)return e;1&n&&(e[2]=t[2],i|=1&r?0:4);var u=t[3];if(u){var c=e[3];e[3]=c?Ai(c,u,t[4]):u,e[4]=c?ir(e[3],s):t[4]}(u=t[5])&&(c=e[5],e[5]=c?Ii(c,u,t[6]):u,e[6]=c?ir(e[5],s):t[6]),(u=t[7])&&(e[7]=u),n&a&&(e[8]=null==e[8]?t[8]:gr(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=i})(y,v),e=y[0],t=y[1],i=y[2],l=y[3],u=y[4],!(h=y[9]=y[9]===r?f?0:e.length:pr(y[9]-p,0))&&24&t&&(t&=-25),t&&1!=t)b=8==t||16==t?function(e,t,n){var i=Di(e);return function s(){for(var o=arguments.length,a=be(o),l=o,u=ns(s);l--;)a[l]=arguments[l];var c=o<3&&a[0]!==u&&a[o-1]!==u?[]:ir(a,u);return(o-=c.length)<n?ji(e,t,Oi,s.placeholder,r,a,c,r,r,n-o):Et(this&&this!==ut&&this instanceof s?i:e,this,a)}}(e,t,h):t!=o&&33!=t||u.length?Oi.apply(r,y):function(e,t,r,n){var i=1&t,s=Di(e);return function t(){for(var o=-1,a=arguments.length,l=-1,u=n.length,c=be(u+a),d=this&&this!==ut&&this instanceof t?s:e;++l<u;)c[l]=n[l];for(;a--;)c[l++]=arguments[++o];return Et(d,i?r:this,c)}}(e,t,i,l);else var b=function(e,t,r){var n=1&t,i=Di(e);return function t(){return(this&&this!==ut&&this instanceof t?i:e).apply(n?r:this,arguments)}}(e,t,i);return xs((v?Zn:_s)(b,y),e,t)}function Gi(e,t,n,i){return e===r||Oo(e,Pe[n])&&!De.call(i,n)?t:e}function Xi(e,t,n,i,s,o){return Zo(e)&&Zo(t)&&(o.set(t,e),Fn(e,t,r,Xi,o),o.delete(t)),e}function Zi(e){return ea(e)?r:e}function Yi(e,t,n,i,s,o){var a=1&n,l=e.length,u=t.length;if(l!=u&&!(a&&u>l))return!1;var c=o.get(e),d=o.get(t);if(c&&d)return c==t&&d==e;var h=-1,f=!0,p=2&n?new Kr:r;for(o.set(e,t),o.set(t,e);++h<l;){var g=e[h],m=t[h];if(i)var v=a?i(m,g,h,t,e,o):i(g,m,h,e,t,o);if(v!==r){if(v)continue;f=!1;break}if(p){if(!Dt(t,((e,t)=>{if(!Xt(p,t)&&(g===e||s(g,e,n,i,o)))return p.push(t)}))){f=!1;break}}else if(g!==m&&!s(g,m,n,i,o)){f=!1;break}}return o.delete(e),o.delete(t),f}function Qi(e){return ks(Ss(e,r,$s),e+"")}function Ji(e){return En(e,ka,ls)}function es(e){return En(e,xa,us)}var ts=Cr?e=>Cr.get(e):il;function rs(e){for(var t=e.name+"",r=kr[t],n=De.call(kr,t)?r.length:0;n--;){var i=r[n],s=i.func;if(null==s||s==e)return i.name}return t}function ns(e){return(De.call(Or,"placeholder")?Or:e).placeholder}function is(){var e=Or.iteratee||el;return e=e===el?Ln:e,arguments.length?e(arguments[0],arguments[1]):e}function ss(e,t){var r,n,i=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?i["string"==typeof t?"string":"hash"]:i.map}function os(e){for(var t=ka(e),r=t.length;r--;){var n=t[r],i=e[n];t[r]=[n,i,ws(i)]}return t}function as(e,t){var n=((e,t)=>null==e?r:e[t])(e,t);return Rn(n)?n:r}var ls=Mt?e=>null==e?[]:(e=Ie(e),Ct(Mt(e),(t=>He.call(e,t)))):dl,us=Mt?e=>{for(var t=[];e;)Pt(t,ls(e)),e=Ke(e);return t}:dl,cs=Sn;function ds(e,t,r){for(var n=-1,i=(t=gi(t,e)).length,s=!1;++n<i;){var o=Ls(t[n]);if(!(s=null!=e&&r(e,o)))break;e=e[o]}return s||++n!=i?s:!!(i=null==e?0:e.length)&&Xo(i)&&ps(o,i)&&($o(e)||Bo(e))}function hs(e){return"function"!=typeof e.constructor||bs(e)?{}:Ur(Ke(e))}function fs(e){return $o(e)||Bo(e)||!!(Ze&&e&&e[Ze])}function ps(e,t){var r=typeof e;return!!(t=null==t?u:t)&&("number"==r||"symbol"!=r&&ge.test(e))&&e>-1&&e%1==0&&e<t}function gs(e,t,r){if(!Zo(r))return!1;var n=typeof t;return!!("number"==n?zo(r)&&ps(t,r.length):"string"==n&&t in r)&&Oo(r[t],e)}function ms(e,t){if($o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!ia(e))||Y.test(e)||!Z.test(e)||null!=t&&e in Ie(t)}function vs(e){var t=rs(e),r=Or[t];if("function"!=typeof r||!(t in $r.prototype))return!1;if(e===r)return!0;var n=ts(r);return!!n&&e===n[0]}(wr&&cs(new wr(new ArrayBuffer(1)))!=P||Er&&cs(new Er)!=w||Sr&&cs(Sr.resolve())!=A||Ar&&cs(new Ar)!=_||Ir&&cs(new Ir)!=x)&&(cs=e=>{var t=Sn(e),n=t==S?e.constructor:r,i=n?Ds(n):"";if(i)switch(i){case xr:return P;case Tr:return w;case Pr:return A;case Rr:return _;case Lr:return x}return t});var ys=Re?Wo:hl;function bs(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Pe)}function ws(e){return e==e&&!Zo(e)}function Es(e,t){return n=>null!=n&&n[e]===t&&(t!==r||e in Ie(n))}function Ss(e,t,n){return t=pr(t===r?e.length-1:t,0),function(){for(var r=arguments,i=-1,s=pr(r.length-t,0),o=be(s);++i<s;)o[i]=r[t+i];i=-1;for(var a=be(t+1);++i<t;)a[i]=r[i];return a[t]=n(o),Et(e,this,a)}}function As(e,t){return t.length<2?e:wn(e,Jn(t,0,-1))}function Is(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var _s=Ts(Zn),Cs=dt||((e,t)=>ut.setTimeout(e,t)),ks=Ts(Yn);function xs(e,t,r){var n=t+"";return ks(e,((e,t)=>{var r=t.length;if(!r)return e;var n=r-1;return t[n]=(r>1?"& ":"")+t[n],t=t.join(r>2?", ":" "),e.replace(ne,"{\n/* [wrapped with "+t+"] */\n")})(n,((e,t)=>(At(h,(r=>{var n="_."+r[0];t&r[1]&&!kt(e,n)&&e.push(n)})),e.sort()))((e=>{var t=e.match(ie);return t?t[1].split(se):[]})(n),r)))}function Ts(e){var t=0,n=0;return function(){var i=mr(),s=16-(i-n);if(n=i,s>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(r,arguments)}}function Ps(e,t){var n=-1,i=e.length,s=i-1;for(t=t===r?i:t;++n<t;){var o=Kn(n,s),a=e[o];e[o]=e[n],e[n]=a}return e.length=t,e}var Rs=(e=>{var t=Po((e=>{var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(Q,((e,r,n,i)=>{t.push(n?i.replace(le,"$1"):r||e)})),t}),(e=>(500===r.size&&r.clear(),e))),r=t.cache;return t})();function Ls(e){if("string"==typeof e||ia(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Ds(e){if(null!=e){try{return Le.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Ms(e){if(e instanceof $r)return e.clone();var t=new Br(e.__wrapped__,e.__chain__);return t.__actions__=_i(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Ns=Hn(((e,t)=>jo(e)?ln(e,pn(t,1,jo,!0)):[])),Os=Hn(((e,t)=>{var n=Vs(t);return jo(n)&&(n=r),jo(e)?ln(e,pn(t,1,jo,!0),is(n,2)):[]})),Us=Hn(((e,t)=>{var n=Vs(t);return jo(n)&&(n=r),jo(e)?ln(e,pn(t,1,jo,!0),r,n):[]}));function Fs(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:ca(r);return i<0&&(i=pr(n+i,0)),Ot(e,is(t,3),i)}function Bs(e,t,n){var i=null==e?0:e.length;if(!i)return-1;var s=i-1;return n!==r&&(s=ca(n),s=n<0?pr(i+s,0):gr(s,i-1)),Ot(e,is(t,3),s,!0)}function $s(e){return null!=e&&e.length?pn(e,1):[]}function qs(e){return e&&e.length?e[0]:r}var zs=Hn((e=>{var t=Tt(e,fi);return t.length&&t[0]===e[0]?Cn(t):[]})),js=Hn((e=>{var t=Vs(e),n=Tt(e,fi);return t===Vs(n)?t=r:n.pop(),n.length&&n[0]===e[0]?Cn(n,is(t,2)):[]})),Ks=Hn((e=>{var t=Vs(e),n=Tt(e,fi);return(t="function"==typeof t?t:r)&&n.pop(),n.length&&n[0]===e[0]?Cn(n,r,t):[]}));function Vs(e){var t=null==e?0:e.length;return t?e[t-1]:r}var Hs=Hn(Ws);function Ws(e,t){return e&&e.length&&t&&t.length?zn(e,t):e}var Gs=Qi(((e,t)=>{var r=null==e?0:e.length,n=rn(e,t);return jn(e,Tt(t,(e=>ps(e,r)?+e:e)).sort(Si)),n}));function Xs(e){return null==e?e:br.call(e)}var Zs=Hn((e=>oi(pn(e,1,jo,!0)))),Ys=Hn((e=>{var t=Vs(e);return jo(t)&&(t=r),oi(pn(e,1,jo,!0),is(t,2))})),Qs=Hn((e=>{var t=Vs(e);return t="function"==typeof t?t:r,oi(pn(e,1,jo,!0),r,t)}));function Js(e){if(!e||!e.length)return[];var t=0;return e=Ct(e,(e=>{if(jo(e))return t=pr(e.length,t),!0})),Vt(t,(t=>Tt(e,qt(t))))}function eo(e,t){if(!e||!e.length)return[];var n=Js(e);return null==t?n:Tt(n,(e=>Et(t,r,e)))}var to=Hn(((e,t)=>jo(e)?ln(e,t):[])),ro=Hn((e=>di(Ct(e,jo)))),no=Hn((e=>{var t=Vs(e);return jo(t)&&(t=r),di(Ct(e,jo),is(t,2))})),io=Hn((e=>{var t=Vs(e);return t="function"==typeof t?t:r,di(Ct(e,jo),r,t)})),so=Hn(Js),oo=Hn((e=>{var t=e.length,n=t>1?e[t-1]:r;return n="function"==typeof n?(e.pop(),n):r,eo(e,n)}));function ao(e){var t=Or(e);return t.__chain__=!0,t}function lo(e,t){return t(e)}var uo=Qi((function(e){var t=e.length,n=t?e[0]:0,i=this.__wrapped__,s=t=>rn(t,e);return!(t>1||this.__actions__.length)&&i instanceof $r&&ps(n)?((i=i.slice(n,+n+(t?1:0))).__actions__.push({func:lo,args:[s],thisArg:r}),new Br(i,this.__chain__).thru((e=>(t&&!e.length&&e.push(r),e)))):this.thru(s)})),co=ki(((e,t,r)=>{De.call(e,r)?++e[r]:tn(e,r,1)})),ho=Mi(Fs),fo=Mi(Bs);function po(e,t){return($o(e)?At:un)(e,is(t,3))}function go(e,t){return($o(e)?It:cn)(e,is(t,3))}var mo=ki(((e,t,r)=>{De.call(e,r)?e[r].push(t):tn(e,r,[t])})),vo=Hn(((e,t,r)=>{var n=-1,i="function"==typeof t,s=zo(e)?be(e.length):[];return un(e,(e=>{s[++n]=i?Et(t,e,r):kn(e,t,r)})),s})),yo=ki(((e,t,r)=>{tn(e,r,t)}));function bo(e,t){return($o(e)?Tt:Nn)(e,is(t,3))}var wo=ki(((e,t,r)=>{e[r?0:1].push(t)}),(()=>[[],[]])),Eo=Hn(((e,t)=>{if(null==e)return[];var r=t.length;return r>1&&gs(e,t[0],t[1])?t=[]:r>2&&gs(t[0],t[1],t[2])&&(t=[t[0]]),$n(e,pn(t,1),[])})),So=ct||(()=>ut.Date.now());function Ao(e,t,n){return t=n?r:t,t=e&&null==t?e.length:t,Wi(e,a,r,r,r,r,t)}function Io(e,t){var i;if("function"!=typeof t)throw new ke(n);return e=ca(e),function(){return--e>0&&(i=t.apply(this,arguments)),e<=1&&(t=r),i}}var _o=Hn(((e,t,r)=>{var n=1;if(r.length){var i=ir(r,ns(_o));n|=o}return Wi(e,n,t,r,i)})),Co=Hn(((e,t,r)=>{var n=3;if(r.length){var i=ir(r,ns(Co));n|=o}return Wi(t,n,e,r,i)}));function ko(e,t,i){var s,o,a,l,u,c,d=0,h=!1,f=!1,p=!0;if("function"!=typeof e)throw new ke(n);function g(t){var n=s,i=o;return s=o=r,d=t,l=e.apply(i,n)}function m(e){var n=e-c;return c===r||n>=t||n<0||f&&e-d>=a}function v(){var e=So();if(m(e))return y(e);u=Cs(v,(e=>{var r=t-(e-c);return f?gr(r,a-(e-d)):r})(e))}function y(e){return u=r,p&&s?g(e):(s=o=r,l)}function b(){var e=So(),n=m(e);if(s=arguments,o=this,c=e,n){if(u===r)return(e=>(d=e,u=Cs(v,t),h?g(e):l))(c);if(f)return yi(u),u=Cs(v,t),g(c)}return u===r&&(u=Cs(v,t)),l}return t=ha(t)||0,Zo(i)&&(h=!!i.leading,a=(f="maxWait"in i)?pr(ha(i.maxWait)||0,t):a,p="trailing"in i?!!i.trailing:p),b.cancel=()=>{u!==r&&yi(u),d=0,s=c=o=u=r},b.flush=()=>u===r?l:y(So()),b}var xo=Hn(((e,t)=>an(e,1,t))),To=Hn(((e,t,r)=>an(e,ha(t)||0,r)));function Po(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new ke(n);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],s=r.cache;if(s.has(i))return s.get(i);var o=e.apply(this,n);return r.cache=s.set(i,o)||s,o};return r.cache=new(Po.Cache||jr),r}function Ro(e){if("function"!=typeof e)throw new ke(n);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Po.Cache=jr;var Lo=mi((function(e,t){var r=(t=1==t.length&&$o(t[0])?Tt(t[0],Wt(is())):Tt(pn(t,1),Wt(is()))).length;return Hn((function(n){for(var i=-1,s=gr(n.length,r);++i<s;)n[i]=t[i].call(this,n[i]);return Et(e,this,n)}))})),Do=Hn(((e,t)=>{var n=ir(t,ns(Do));return Wi(e,o,r,t,n)})),Mo=Hn(((e,t)=>{var n=ir(t,ns(Mo));return Wi(e,64,r,t,n)})),No=Qi(((e,t)=>Wi(e,256,r,r,r,t)));function Oo(e,t){return e===t||e!=e&&t!=t}var Uo=zi(An),Fo=zi(((e,t)=>e>=t)),Bo=xn(function(){return arguments}())?xn:e=>Yo(e)&&De.call(e,"callee")&&!He.call(e,"callee"),$o=be.isArray,qo=gt?Wt(gt):e=>Yo(e)&&Sn(e)==T;function zo(e){return null!=e&&Xo(e.length)&&!Wo(e)}function jo(e){return Yo(e)&&zo(e)}var Ko=zt||hl,Vo=mt?Wt(mt):e=>Yo(e)&&Sn(e)==m;function Ho(e){if(!Yo(e))return!1;var t=Sn(e);return t==v||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!ea(e)}function Wo(e){if(!Zo(e))return!1;var t=Sn(e);return t==y||t==b||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Go(e){return"number"==typeof e&&e==ca(e)}function Xo(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=u}function Zo(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Yo(e){return null!=e&&"object"==typeof e}var Qo=vt?Wt(vt):e=>Yo(e)&&cs(e)==w;function Jo(e){return"number"==typeof e||Yo(e)&&Sn(e)==E}function ea(e){if(!Yo(e)||Sn(e)!=S)return!1;var t=Ke(e);if(null===t)return!0;var r=De.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Le.call(r)==Ue}var ta=yt?Wt(yt):e=>Yo(e)&&Sn(e)==I,ra=bt?Wt(bt):e=>Yo(e)&&cs(e)==_;function na(e){return"string"==typeof e||!$o(e)&&Yo(e)&&Sn(e)==C}function ia(e){return"symbol"==typeof e||Yo(e)&&Sn(e)==k}var sa=wt?Wt(wt):e=>Yo(e)&&Xo(e.length)&&!!rt[Sn(e)],oa=zi(Mn),aa=zi(((e,t)=>e<=t));function la(e){if(!e)return[];if(zo(e))return na(e)?ar(e):_i(e);if(Qe&&e[Qe])return(e=>{for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r})(e[Qe]());var t=cs(e);return(t==w?rr:t==_?sr:Oa)(e)}function ua(e){return e?(e=ha(e))===l||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function ca(e){var t=ua(e),r=t%1;return t==t?r?t-r:t:0}function da(e){return e?nn(ca(e),0,d):0}function ha(e){if("number"==typeof e)return e;if(ia(e))return c;if(Zo(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Zo(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Ht(e);var r=he.test(e);return r||pe.test(e)?ot(e.slice(2),r?2:8):de.test(e)?c:+e}function fa(e){return Ci(e,xa(e))}function pa(e){return null==e?"":si(e)}var ga=xi(((e,t)=>{if(bs(t)||zo(t))Ci(t,ka(t),e);else for(var r in t)De.call(t,r)&&Yr(e,r,t[r])})),ma=xi(((e,t)=>{Ci(t,xa(t),e)})),va=xi(((e,t,r,n)=>{Ci(t,xa(t),e,n)})),ya=xi(((e,t,r,n)=>{Ci(t,ka(t),e,n)})),ba=Qi(rn),wa=Hn(((e,t)=>{e=Ie(e);var n=-1,i=t.length,s=i>2?t[2]:r;for(s&&gs(t[0],t[1],s)&&(i=1);++n<i;)for(var o=t[n],a=xa(o),l=-1,u=a.length;++l<u;){var c=a[l],d=e[c];(d===r||Oo(d,Pe[c])&&!De.call(e,c))&&(e[c]=o[c])}return e})),Ea=Hn((e=>(e.push(r,Xi),Et(Pa,r,e))));function Sa(e,t,n){var i=null==e?r:wn(e,t);return i===r?n:i}function Aa(e,t){return null!=e&&ds(e,t,_n)}var Ia=Ui(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),e[t]=r}),Za(Ja)),_a=Ui(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),De.call(e,t)?e[t].push(r):e[t]=[r]}),is),Ca=Hn(kn);function ka(e){return zo(e)?Hr(e):Dn(e)}function xa(e){return zo(e)?Hr(e,!0):function(e){if(!Zo(e))return(e=>{var t=[];if(null!=e)for(var r in Ie(e))t.push(r);return t})(e);var t=bs(e),r=[];for(var n in e)("constructor"!=n||!t&&De.call(e,n))&&r.push(n);return r}(e)}var Ta=xi(((e,t,r)=>{Fn(e,t,r)})),Pa=xi(((e,t,r,n)=>{Fn(e,t,r,n)})),Ra=Qi(((e,t)=>{var r={};if(null==e)return r;var n=!1;t=Tt(t,(t=>(t=gi(t,e),n||(n=t.length>1),t))),Ci(e,es(e),r),n&&(r=sn(r,7,Zi));for(var i=t.length;i--;)ai(r,t[i]);return r})),La=Qi(((e,t)=>null==e?{}:((e,t)=>qn(e,t,((t,r)=>Aa(e,r))))(e,t)));function Da(e,t){if(null==e)return{};var r=Tt(es(e),(e=>[e]));return t=is(t),qn(e,r,((e,r)=>t(e,r[0])))}var Ma=Hi(ka),Na=Hi(xa);function Oa(e){return null==e?[]:Gt(e,ka(e))}var Ua=Li(((e,t,r)=>(t=t.toLowerCase(),e+(r?Fa(t):t))));function Fa(e){return Ha(pa(e).toLowerCase())}function Ba(e){return(e=pa(e))&&e.replace(me,Qt).replace(Xe,"")}var $a=Li(((e,t,r)=>e+(r?"-":"")+t.toLowerCase())),qa=Li(((e,t,r)=>e+(r?" ":"")+t.toLowerCase())),za=Ri("toLowerCase"),ja=Li(((e,t,r)=>e+(r?"_":"")+t.toLowerCase())),Ka=Li(((e,t,r)=>e+(r?" ":"")+Ha(t))),Va=Li(((e,t,r)=>e+(r?" ":"")+t.toUpperCase())),Ha=Ri("toUpperCase");function Wa(e,t,n){return e=pa(e),(t=n?r:t)===r?(e=>Je.test(e))(e)?(e=>e.match(Ye)||[])(e):(e=>e.match(oe)||[])(e):e.match(t)||[]}var Ga=Hn(((e,t)=>{try{return Et(e,r,t)}catch(e){return Ho(e)?e:new Ee(e)}})),Xa=Qi(((e,t)=>(At(t,(t=>{t=Ls(t),tn(e,t,_o(e[t],e))})),e)));function Za(e){return()=>e}var Ya=Ni(),Qa=Ni(!0);function Ja(e){return e}function el(e){return Ln("function"==typeof e?e:sn(e,1))}var tl=Hn(((e,t)=>r=>kn(r,e,t))),rl=Hn(((e,t)=>r=>kn(e,r,t)));function nl(e,t,r){var n=ka(t),i=bn(t,n);null!=r||Zo(t)&&(i.length||!n.length)||(r=t,t=e,e=this,i=bn(t,ka(t)));var s=!(Zo(r)&&"chain"in r&&!r.chain),o=Wo(e);return At(i,(function(r){var n=t[r];e[r]=n,o&&(e.prototype[r]=function(){var t=this.__chain__;if(s||t){var r=e(this.__wrapped__);return(r.__actions__=_i(this.__actions__)).push({func:n,args:arguments,thisArg:e}),r.__chain__=t,r}return n.apply(e,Pt([this.value()],arguments))})})),e}function il(){}var sl=Bi(Tt),ol=Bi(_t),al=Bi(Dt);function ll(e){return ms(e)?qt(Ls(e)):(e=>t=>wn(t,e))(e)}var ul=qi(),cl=qi(!0);function dl(){return[]}function hl(){return!1}var fl=Fi(((e,t)=>e+t),0),pl=Ki("ceil"),gl=Fi(((e,t)=>e/t),1),ml=Ki("floor"),vl=Fi(((e,t)=>e*t),1),yl=Ki("round"),bl=Fi(((e,t)=>e-t),0);return Or.after=function(e,t){if("function"!=typeof t)throw new ke(n);return e=ca(e),function(){if(--e<1)return t.apply(this,arguments)}},Or.ary=Ao,Or.assign=ga,Or.assignIn=ma,Or.assignInWith=va,Or.assignWith=ya,Or.at=ba,Or.before=Io,Or.bind=_o,Or.bindAll=Xa,Or.bindKey=Co,Or.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return $o(e)?e:[e]},Or.chain=ao,Or.chunk=(e,t,n)=>{t=(n?gs(e,t,n):t===r)?1:pr(ca(t),0);var i=null==e?0:e.length;if(!i||t<1)return[];for(var s=0,o=0,a=be(ft(i/t));s<i;)a[o++]=Jn(e,s,s+=t);return a},Or.compact=e=>{for(var t=-1,r=null==e?0:e.length,n=0,i=[];++t<r;){var s=e[t];s&&(i[n++]=s)}return i},Or.concat=function(){var e=arguments.length;if(!e)return[];for(var t=be(e-1),r=arguments[0],n=e;n--;)t[n-1]=arguments[n];return Pt($o(r)?_i(r):[r],pn(t,1))},Or.cond=function(e){var t=null==e?0:e.length,r=is();return e=t?Tt(e,(e=>{if("function"!=typeof e[1])throw new ke(n);return[r(e[0]),e[1]]})):[],Hn((function(r){for(var n=-1;++n<t;){var i=e[n];if(Et(i[0],this,r))return Et(i[1],this,r)}}))},Or.conforms=e=>(e=>{var t=ka(e);return r=>on(r,e,t)})(sn(e,1)),Or.constant=Za,Or.countBy=co,Or.create=(e,t)=>{var r=Ur(e);return null==t?r:en(r,t)},Or.curry=function e(t,n,i){var s=Wi(t,8,r,r,r,r,r,n=i?r:n);return s.placeholder=e.placeholder,s},Or.curryRight=function e(t,n,i){var s=Wi(t,16,r,r,r,r,r,n=i?r:n);return s.placeholder=e.placeholder,s},Or.debounce=ko,Or.defaults=wa,Or.defaultsDeep=Ea,Or.defer=xo,Or.delay=To,Or.difference=Ns,Or.differenceBy=Os,Or.differenceWith=Us,Or.drop=(e,t,n)=>{var i=null==e?0:e.length;return i?Jn(e,(t=n||t===r?1:ca(t))<0?0:t,i):[]},Or.dropRight=(e,t,n)=>{var i=null==e?0:e.length;return i?Jn(e,0,(t=i-(t=n||t===r?1:ca(t)))<0?0:t):[]},Or.dropRightWhile=(e,t)=>e&&e.length?ui(e,is(t,3),!0,!0):[],Or.dropWhile=(e,t)=>e&&e.length?ui(e,is(t,3),!0):[],Or.fill=(e,t,n,i)=>{var s=null==e?0:e.length;return s?(n&&"number"!=typeof n&&gs(e,t,n)&&(n=0,i=s),((e,t,n,i)=>{var s=e.length;for((n=ca(n))<0&&(n=-n>s?0:s+n),(i=i===r||i>s?s:ca(i))<0&&(i+=s),i=n>i?0:da(i);n<i;)e[n++]=t;return e})(e,t,n,i)):[]},Or.filter=(e,t)=>($o(e)?Ct:fn)(e,is(t,3)),Or.flatMap=(e,t)=>pn(bo(e,t),1),Or.flatMapDeep=(e,t)=>pn(bo(e,t),l),Or.flatMapDepth=(e,t,n)=>(n=n===r?1:ca(n),pn(bo(e,t),n)),Or.flatten=$s,Or.flattenDeep=e=>null!=e&&e.length?pn(e,l):[],Or.flattenDepth=(e,t)=>null!=e&&e.length?pn(e,t=t===r?1:ca(t)):[],Or.flip=e=>Wi(e,512),Or.flow=Ya,Or.flowRight=Qa,Or.fromPairs=e=>{for(var t=-1,r=null==e?0:e.length,n={};++t<r;){var i=e[t];n[i[0]]=i[1]}return n},Or.functions=e=>null==e?[]:bn(e,ka(e)),Or.functionsIn=e=>null==e?[]:bn(e,xa(e)),Or.groupBy=mo,Or.initial=e=>null!=e&&e.length?Jn(e,0,-1):[],Or.intersection=zs,Or.intersectionBy=js,Or.intersectionWith=Ks,Or.invert=Ia,Or.invertBy=_a,Or.invokeMap=vo,Or.iteratee=el,Or.keyBy=yo,Or.keys=ka,Or.keysIn=xa,Or.map=bo,Or.mapKeys=(e,t)=>{var r={};return t=is(t,3),vn(e,((e,n,i)=>{tn(r,t(e,n,i),e)})),r},Or.mapValues=(e,t)=>{var r={};return t=is(t,3),vn(e,((e,n,i)=>{tn(r,n,t(e,n,i))})),r},Or.matches=e=>On(sn(e,1)),Or.matchesProperty=(e,t)=>Un(e,sn(t,1)),Or.memoize=Po,Or.merge=Ta,Or.mergeWith=Pa,Or.method=tl,Or.methodOf=rl,Or.mixin=nl,Or.negate=Ro,Or.nthArg=e=>(e=ca(e),Hn((t=>Bn(t,e)))),Or.omit=Ra,Or.omitBy=(e,t)=>Da(e,Ro(is(t))),Or.once=e=>Io(2,e),Or.orderBy=(e,t,n,i)=>null==e?[]:($o(t)||(t=null==t?[]:[t]),$o(n=i?r:n)||(n=null==n?[]:[n]),$n(e,t,n)),Or.over=sl,Or.overArgs=Lo,Or.overEvery=ol,Or.overSome=al,Or.partial=Do,Or.partialRight=Mo,Or.partition=wo,Or.pick=La,Or.pickBy=Da,Or.property=ll,Or.propertyOf=e=>t=>null==e?r:wn(e,t),Or.pull=Hs,Or.pullAll=Ws,Or.pullAllBy=(e,t,r)=>e&&e.length&&t&&t.length?zn(e,t,is(r,2)):e,Or.pullAllWith=(e,t,n)=>e&&e.length&&t&&t.length?zn(e,t,r,n):e,Or.pullAt=Gs,Or.range=ul,Or.rangeRight=cl,Or.rearg=No,Or.reject=(e,t)=>($o(e)?Ct:fn)(e,Ro(is(t,3))),Or.remove=(e,t)=>{var r=[];if(!e||!e.length)return r;var n=-1,i=[],s=e.length;for(t=is(t,3);++n<s;){var o=e[n];t(o,n,e)&&(r.push(o),i.push(n))}return jn(e,i),r},Or.rest=(e,t)=>{if("function"!=typeof e)throw new ke(n);return Hn(e,t=t===r?t:ca(t))},Or.reverse=Xs,Or.sampleSize=(e,t,n)=>(t=(n?gs(e,t,n):t===r)?1:ca(t),($o(e)?Gr:Gn)(e,t)),Or.set=(e,t,r)=>null==e?e:Xn(e,t,r),Or.setWith=(e,t,n,i)=>(i="function"==typeof i?i:r,null==e?e:Xn(e,t,n,i)),Or.shuffle=e=>($o(e)?Xr:Qn)(e),Or.slice=(e,t,n)=>{var i=null==e?0:e.length;return i?(n&&"number"!=typeof n&&gs(e,t,n)?(t=0,n=i):(t=null==t?0:ca(t),n=n===r?i:ca(n)),Jn(e,t,n)):[]},Or.sortBy=Eo,Or.sortedUniq=e=>e&&e.length?ni(e):[],Or.sortedUniqBy=(e,t)=>e&&e.length?ni(e,is(t,2)):[],Or.split=(e,t,n)=>(n&&"number"!=typeof n&&gs(e,t,n)&&(t=n=r),(n=n===r?d:n>>>0)?(e=pa(e))&&("string"==typeof t||null!=t&&!ta(t))&&!(t=si(t))&&tr(e)?vi(ar(e),0,n):e.split(t,n):[]),Or.spread=function(e,t){if("function"!=typeof e)throw new ke(n);return t=null==t?0:pr(ca(t),0),Hn((function(r){var n=r[t],i=vi(r,0,t);return n&&Pt(i,n),Et(e,this,i)}))},Or.tail=e=>{var t=null==e?0:e.length;return t?Jn(e,1,t):[]},Or.take=(e,t,n)=>e&&e.length?Jn(e,0,(t=n||t===r?1:ca(t))<0?0:t):[],Or.takeRight=(e,t,n)=>{var i=null==e?0:e.length;return i?Jn(e,(t=i-(t=n||t===r?1:ca(t)))<0?0:t,i):[]},Or.takeRightWhile=(e,t)=>e&&e.length?ui(e,is(t,3),!1,!0):[],Or.takeWhile=(e,t)=>e&&e.length?ui(e,is(t,3)):[],Or.tap=(e,t)=>(t(e),e),Or.throttle=(e,t,r)=>{var i=!0,s=!0;if("function"!=typeof e)throw new ke(n);return Zo(r)&&(i="leading"in r?!!r.leading:i,s="trailing"in r?!!r.trailing:s),ko(e,t,{leading:i,maxWait:t,trailing:s})},Or.thru=lo,Or.toArray=la,Or.toPairs=Ma,Or.toPairsIn=Na,Or.toPath=e=>$o(e)?Tt(e,Ls):ia(e)?[e]:_i(Rs(pa(e))),Or.toPlainObject=fa,Or.transform=(e,t,r)=>{var n=$o(e),i=n||Ko(e)||sa(e);if(t=is(t,4),null==r){var s=e&&e.constructor;r=i?n?new s:[]:Zo(e)&&Wo(s)?Ur(Ke(e)):{}}return(i?At:vn)(e,((e,n,i)=>t(r,e,n,i))),r},Or.unary=e=>Ao(e,1),Or.union=Zs,Or.unionBy=Ys,Or.unionWith=Qs,Or.uniq=e=>e&&e.length?oi(e):[],Or.uniqBy=(e,t)=>e&&e.length?oi(e,is(t,2)):[],Or.uniqWith=(e,t)=>(t="function"==typeof t?t:r,e&&e.length?oi(e,r,t):[]),Or.unset=(e,t)=>null==e||ai(e,t),Or.unzip=Js,Or.unzipWith=eo,Or.update=(e,t,r)=>null==e?e:li(e,t,pi(r)),Or.updateWith=(e,t,n,i)=>(i="function"==typeof i?i:r,null==e?e:li(e,t,pi(n),i)),Or.values=Oa,Or.valuesIn=e=>null==e?[]:Gt(e,xa(e)),Or.without=to,Or.words=Wa,Or.wrap=(e,t)=>Do(pi(t),e),Or.xor=ro,Or.xorBy=no,Or.xorWith=io,Or.zip=so,Or.zipObject=(e,t)=>hi(e||[],t||[],Yr),Or.zipObjectDeep=(e,t)=>hi(e||[],t||[],Xn),Or.zipWith=oo,Or.entries=Ma,Or.entriesIn=Na,Or.extend=ma,Or.extendWith=va,nl(Or,Or),Or.add=fl,Or.attempt=Ga,Or.camelCase=Ua,Or.capitalize=Fa,Or.ceil=pl,Or.clamp=(e,t,n)=>(n===r&&(n=t,t=r),n!==r&&(n=(n=ha(n))==n?n:0),t!==r&&(t=(t=ha(t))==t?t:0),nn(ha(e),t,n)),Or.clone=e=>sn(e,4),Or.cloneDeep=e=>sn(e,5),Or.cloneDeepWith=(e,t)=>sn(e,5,t="function"==typeof t?t:r),Or.cloneWith=(e,t)=>sn(e,4,t="function"==typeof t?t:r),Or.conformsTo=(e,t)=>null==t||on(e,t,ka(t)),Or.deburr=Ba,Or.defaultTo=(e,t)=>null==e||e!=e?t:e,Or.divide=gl,Or.endsWith=(e,t,n)=>{e=pa(e),t=si(t);var i=e.length,s=n=n===r?i:nn(ca(n),0,i);return(n-=t.length)>=0&&e.slice(n,s)==t},Or.eq=Oo,Or.escape=e=>(e=pa(e))&&H.test(e)?e.replace(K,Jt):e,Or.escapeRegExp=e=>(e=pa(e))&&ee.test(e)?e.replace(J,"\\$&"):e,Or.every=(e,t,n)=>{var i=$o(e)?_t:dn;return n&&gs(e,t,n)&&(t=r),i(e,is(t,3))},Or.find=ho,Or.findIndex=Fs,Or.findKey=(e,t)=>Nt(e,is(t,3),vn),Or.findLast=fo,Or.findLastIndex=Bs,Or.findLastKey=(e,t)=>Nt(e,is(t,3),yn),Or.floor=ml,Or.forEach=po,Or.forEachRight=go,Or.forIn=(e,t)=>null==e?e:gn(e,is(t,3),xa),Or.forInRight=(e,t)=>null==e?e:mn(e,is(t,3),xa),Or.forOwn=(e,t)=>e&&vn(e,is(t,3)),Or.forOwnRight=(e,t)=>e&&yn(e,is(t,3)),Or.get=Sa,Or.gt=Uo,Or.gte=Fo,Or.has=(e,t)=>null!=e&&ds(e,t,In),Or.hasIn=Aa,Or.head=qs,Or.identity=Ja,Or.includes=(e,t,r,n)=>{e=zo(e)?e:Oa(e),r=r&&!n?ca(r):0;var i=e.length;return r<0&&(r=pr(i+r,0)),na(e)?r<=i&&e.indexOf(t,r)>-1:!!i&&Ut(e,t,r)>-1},Or.indexOf=(e,t,r)=>{var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:ca(r);return i<0&&(i=pr(n+i,0)),Ut(e,t,i)},Or.inRange=(e,t,n)=>(t=ua(t),n===r?(n=t,t=0):n=ua(n),((e,t,r)=>e>=gr(t,r)&&e<pr(t,r))(e=ha(e),t,n)),Or.invoke=Ca,Or.isArguments=Bo,Or.isArray=$o,Or.isArrayBuffer=qo,Or.isArrayLike=zo,Or.isArrayLikeObject=jo,Or.isBoolean=e=>!0===e||!1===e||Yo(e)&&Sn(e)==g,Or.isBuffer=Ko,Or.isDate=Vo,Or.isElement=e=>Yo(e)&&1===e.nodeType&&!ea(e),Or.isEmpty=e=>{if(null==e)return!0;if(zo(e)&&($o(e)||"string"==typeof e||"function"==typeof e.splice||Ko(e)||sa(e)||Bo(e)))return!e.length;var t=cs(e);if(t==w||t==_)return!e.size;if(bs(e))return!Dn(e).length;for(var r in e)if(De.call(e,r))return!1;return!0},Or.isEqual=(e,t)=>Tn(e,t),Or.isEqualWith=(e,t,n)=>{var i=(n="function"==typeof n?n:r)?n(e,t):r;return i===r?Tn(e,t,r,n):!!i},Or.isError=Ho,Or.isFinite=e=>"number"==typeof e&&dr(e),Or.isFunction=Wo,Or.isInteger=Go,Or.isLength=Xo,Or.isMap=Qo,Or.isMatch=(e,t)=>e===t||Pn(e,t,os(t)),Or.isMatchWith=(e,t,n)=>(n="function"==typeof n?n:r,Pn(e,t,os(t),n)),Or.isNaN=e=>Jo(e)&&e!=+e,Or.isNative=e=>{if(ys(e))throw new Ee("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Rn(e)},Or.isNil=e=>null==e,Or.isNull=e=>null===e,Or.isNumber=Jo,Or.isObject=Zo,Or.isObjectLike=Yo,Or.isPlainObject=ea,Or.isRegExp=ta,Or.isSafeInteger=e=>Go(e)&&e>=-9007199254740991&&e<=u,Or.isSet=ra,Or.isString=na,Or.isSymbol=ia,Or.isTypedArray=sa,Or.isUndefined=e=>e===r,Or.isWeakMap=e=>Yo(e)&&cs(e)==x,Or.isWeakSet=e=>Yo(e)&&"[object WeakSet]"==Sn(e),Or.join=(e,t)=>null==e?"":hr.call(e,t),Or.kebabCase=$a,Or.last=Vs,Or.lastIndexOf=(e,t,n)=>{var i=null==e?0:e.length;if(!i)return-1;var s=i;return n!==r&&(s=(s=ca(n))<0?pr(i+s,0):gr(s,i-1)),t==t?((e,t,r)=>{for(var n=r+1;n--;)if(e[n]===t)return n;return n})(e,t,s):Ot(e,Bt,s,!0)},Or.lowerCase=qa,Or.lowerFirst=za,Or.lt=oa,Or.lte=aa,Or.max=e=>e&&e.length?hn(e,Ja,An):r,Or.maxBy=(e,t)=>e&&e.length?hn(e,is(t,2),An):r,Or.mean=e=>$t(e,Ja),Or.meanBy=(e,t)=>$t(e,is(t,2)),Or.min=e=>e&&e.length?hn(e,Ja,Mn):r,Or.minBy=(e,t)=>e&&e.length?hn(e,is(t,2),Mn):r,Or.stubArray=dl,Or.stubFalse=hl,Or.stubObject=()=>({}),Or.stubString=()=>"",Or.stubTrue=()=>!0,Or.multiply=vl,Or.nth=(e,t)=>e&&e.length?Bn(e,ca(t)):r,Or.noConflict=function(){return ut._===this&&(ut._=Fe),this},Or.noop=il,Or.now=So,Or.pad=(e,t,r)=>{e=pa(e);var n=(t=ca(t))?or(e):0;if(!t||n>=t)return e;var i=(t-n)/2;return $i(pt(i),r)+e+$i(ft(i),r)},Or.padEnd=(e,t,r)=>{e=pa(e);var n=(t=ca(t))?or(e):0;return t&&n<t?e+$i(t-n,r):e},Or.padStart=(e,t,r)=>{e=pa(e);var n=(t=ca(t))?or(e):0;return t&&n<t?$i(t-n,r)+e:e},Or.parseInt=(e,t,r)=>(r||null==t?t=0:t&&(t=+t),vr(pa(e).replace(te,""),t||0)),Or.random=(e,t,n)=>{if(n&&"boolean"!=typeof n&&gs(e,t,n)&&(t=n=r),n===r&&("boolean"==typeof t?(n=t,t=r):"boolean"==typeof e&&(n=e,e=r)),e===r&&t===r?(e=0,t=1):(e=ua(e),t===r?(t=e,e=0):t=ua(t)),e>t){var i=e;e=t,t=i}if(n||e%1||t%1){var s=yr();return gr(e+s*(t-e+st("1e-"+((s+"").length-1))),t)}return Kn(e,t)},Or.reduce=function(e,t,r){var n=$o(e)?Rt:jt,i=arguments.length<3;return n(e,is(t,4),r,i,un)},Or.reduceRight=function(e,t,r){var n=$o(e)?Lt:jt,i=arguments.length<3;return n(e,is(t,4),r,i,cn)},Or.repeat=(e,t,n)=>(t=(n?gs(e,t,n):t===r)?1:ca(t),Vn(pa(e),t)),Or.replace=function(){var e=arguments,t=pa(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Or.result=(e,t,n)=>{var i=-1,s=(t=gi(t,e)).length;for(s||(s=1,e=r);++i<s;){var o=null==e?r:e[Ls(t[i])];o===r&&(i=s,o=n),e=Wo(o)?o.call(e):o}return e},Or.round=yl,Or.runInContext=e,Or.sample=e=>($o(e)?Wr:Wn)(e),Or.size=e=>{if(null==e)return 0;if(zo(e))return na(e)?or(e):e.length;var t=cs(e);return t==w||t==_?e.size:Dn(e).length},Or.snakeCase=ja,Or.some=(e,t,n)=>{var i=$o(e)?Dt:ei;return n&&gs(e,t,n)&&(t=r),i(e,is(t,3))},Or.sortedIndex=(e,t)=>ti(e,t),Or.sortedIndexBy=(e,t,r)=>ri(e,t,is(r,2)),Or.sortedIndexOf=(e,t)=>{var r=null==e?0:e.length;if(r){var n=ti(e,t);if(n<r&&Oo(e[n],t))return n}return-1},Or.sortedLastIndex=(e,t)=>ti(e,t,!0),Or.sortedLastIndexBy=(e,t,r)=>ri(e,t,is(r,2),!0),Or.sortedLastIndexOf=(e,t)=>{if(null!=e&&e.length){var r=ti(e,t,!0)-1;if(Oo(e[r],t))return r}return-1},Or.startCase=Ka,Or.startsWith=(e,t,r)=>(e=pa(e),r=null==r?0:nn(ca(r),0,e.length),t=si(t),e.slice(r,r+t.length)==t),Or.subtract=bl,Or.sum=e=>e&&e.length?Kt(e,Ja):0,Or.sumBy=(e,t)=>e&&e.length?Kt(e,is(t,2)):0,Or.template=(e,t,n)=>{var i=Or.templateSettings;n&&gs(e,t,n)&&(t=r),e=pa(e),t=va({},t,i,Gi);var s,o,a=va({},t.imports,i.imports,Gi),l=ka(a),u=Gt(a,l),c=0,d=t.interpolate||ve,h="__p += '",f=_e((t.escape||ve).source+"|"+d.source+"|"+(d===X?ue:ve).source+"|"+(t.evaluate||ve).source+"|$","g"),p="//# sourceURL="+(De.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++tt+"]")+"\n";e.replace(f,((t,r,n,i,a,l)=>(n||(n=i),h+=e.slice(c,l).replace(ye,er),r&&(s=!0,h+="' +\n__e("+r+") +\n'"),a&&(o=!0,h+="';\n"+a+";\n__p += '"),n&&(h+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),c=l+t.length,t))),h+="';\n";var g=De.call(t,"variable")&&t.variable;if(g){if(ae.test(g))throw new Ee("Invalid `variable` option passed into `_.template`")}else h="with (obj) {\n"+h+"\n}\n";h=(o?h.replace($,""):h).replace(q,"$1").replace(z,"$1;"),h="function("+(g||"obj")+") {\n"+(g?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(s?", __e = _.escape":"")+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+h+"return __p\n}";var m=Ga((()=>Se(l,p+"return "+h).apply(r,u)));if(m.source=h,Ho(m))throw m;return m},Or.times=(e,t)=>{if((e=ca(e))<1||e>u)return[];var r=d,n=gr(e,d);t=is(t),e-=d;for(var i=Vt(n,t);++r<e;)t(r);return i},Or.toFinite=ua,Or.toInteger=ca,Or.toLength=da,Or.toLower=e=>pa(e).toLowerCase(),Or.toNumber=ha,Or.toSafeInteger=e=>e?nn(ca(e),-9007199254740991,u):0===e?e:0,Or.toString=pa,Or.toUpper=e=>pa(e).toUpperCase(),Or.trim=(e,t,n)=>{if((e=pa(e))&&(n||t===r))return Ht(e);if(!e||!(t=si(t)))return e;var i=ar(e),s=ar(t);return vi(i,Zt(i,s),Yt(i,s)+1).join("")},Or.trimEnd=(e,t,n)=>{if((e=pa(e))&&(n||t===r))return e.slice(0,lr(e)+1);if(!e||!(t=si(t)))return e;var i=ar(e);return vi(i,0,Yt(i,ar(t))+1).join("")},Or.trimStart=(e,t,n)=>{if((e=pa(e))&&(n||t===r))return e.replace(te,"");if(!e||!(t=si(t)))return e;var i=ar(e);return vi(i,Zt(i,ar(t))).join("")},Or.truncate=(e,t)=>{var n=30,i="...";if(Zo(t)){var s="separator"in t?t.separator:s;n="length"in t?ca(t.length):n,i="omission"in t?si(t.omission):i}var o=(e=pa(e)).length;if(tr(e)){var a=ar(e);o=a.length}if(n>=o)return e;var l=n-or(i);if(l<1)return i;var u=a?vi(a,0,l).join(""):e.slice(0,l);if(s===r)return u+i;if(a&&(l+=u.length-l),ta(s)){if(e.slice(l).search(s)){var c,d=u;for(s.global||(s=_e(s.source,pa(ce.exec(s))+"g")),s.lastIndex=0;c=s.exec(d);)var h=c.index;u=u.slice(0,h===r?l:h)}}else if(e.indexOf(si(s),l)!=l){var f=u.lastIndexOf(s);f>-1&&(u=u.slice(0,f))}return u+i},Or.unescape=e=>(e=pa(e))&&V.test(e)?e.replace(j,ur):e,Or.uniqueId=e=>{var t=++Me;return pa(e)+t},Or.upperCase=Va,Or.upperFirst=Ha,Or.each=po,Or.eachRight=go,Or.first=qs,nl(Or,(()=>{var e={};return vn(Or,((t,r)=>{De.call(Or.prototype,r)||(e[r]=t)})),e})(),{chain:!1}),Or.VERSION="4.17.21",At(["bind","bindKey","curry","curryRight","partial","partialRight"],(e=>{Or[e].placeholder=Or})),At(["drop","take"],(function(e,t){$r.prototype[e]=function(n){n=n===r?1:pr(ca(n),0);var i=this.__filtered__&&!t?new $r(this):this.clone();return i.__filtered__?i.__takeCount__=gr(n,i.__takeCount__):i.__views__.push({size:gr(n,d),type:e+(i.__dir__<0?"Right":"")}),i},$r.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),At(["filter","map","takeWhile"],(function(e,t){var r=t+1,n=1==r||3==r;$r.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:is(e,3),type:r}),t.__filtered__=t.__filtered__||n,t}})),At(["head","last"],(function(e,t){var r="take"+(t?"Right":"");$r.prototype[e]=function(){return this[r](1).value()[0]}})),At(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");$r.prototype[e]=function(){return this.__filtered__?new $r(this):this[r](1)}})),$r.prototype.compact=function(){return this.filter(Ja)},$r.prototype.find=function(e){return this.filter(e).head()},$r.prototype.findLast=function(e){return this.reverse().find(e)},$r.prototype.invokeMap=Hn((function(e,t){return"function"==typeof e?new $r(this):this.map((r=>kn(r,e,t)))})),$r.prototype.reject=function(e){return this.filter(Ro(is(e)))},$r.prototype.slice=function(e,t){e=ca(e);var n=this;return n.__filtered__&&(e>0||t<0)?new $r(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==r&&(n=(t=ca(t))<0?n.dropRight(-t):n.take(t-e)),n)},$r.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},$r.prototype.toArray=function(){return this.take(d)},vn($r.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),i=/^(?:head|last)$/.test(t),s=Or[i?"take"+("last"==t?"Right":""):t],o=i||/^find/.test(t);s&&(Or.prototype[t]=function(){var t=this.__wrapped__,a=i?[1]:arguments,l=t instanceof $r,u=a[0],c=l||$o(t),d=e=>{var t=s.apply(Or,Pt([e],a));return i&&h?t[0]:t};c&&n&&"function"==typeof u&&1!=u.length&&(l=c=!1);var h=this.__chain__,f=!!this.__actions__.length,p=o&&!h,g=l&&!f;if(!o&&c){t=g?t:new $r(this);var m=e.apply(t,a);return m.__actions__.push({func:lo,args:[d],thisArg:r}),new Br(m,h)}return p&&g?e.apply(this,a):(m=this.thru(d),p?i?m.value()[0]:m.value():m)})})),At(["pop","push","shift","sort","splice","unshift"],(function(e){var t=xe[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Or.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var i=this.value();return t.apply($o(i)?i:[],e)}return this[r]((r=>t.apply($o(r)?r:[],e)))}})),vn($r.prototype,((e,t)=>{var r=Or[t];if(r){var n=r.name+"";De.call(kr,n)||(kr[n]=[]),kr[n].push({name:t,func:r})}})),kr[Oi(r,2).name]=[{name:"wrapper",func:r}],$r.prototype.clone=function(){var e=new $r(this.__wrapped__);return e.__actions__=_i(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=_i(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=_i(this.__views__),e},$r.prototype.reverse=function(){if(this.__filtered__){var e=new $r(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},$r.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,r=$o(e),n=t<0,i=r?e.length:0,s=((e,t,r)=>{for(var n=-1,i=r.length;++n<i;){var s=r[n],o=s.size;switch(s.type){case"drop":e+=o;break;case"dropRight":t-=o;break;case"take":t=gr(t,e+o);break;case"takeRight":e=pr(e,t-o)}}return{start:e,end:t}})(0,i,this.__views__),o=s.start,a=s.end,l=a-o,u=n?a:o-1,c=this.__iteratees__,d=c.length,h=0,f=gr(l,this.__takeCount__);if(!r||!n&&i==l&&f==l)return ci(e,this.__actions__);var p=[];e:for(;l--&&h<f;){for(var g=-1,m=e[u+=t];++g<d;){var v=c[g],y=v.iteratee,b=v.type,w=y(m);if(2==b)m=w;else if(!w){if(1==b)continue e;break e}}p[h++]=m}return p},Or.prototype.at=uo,Or.prototype.chain=function(){return ao(this)},Or.prototype.commit=function(){return new Br(this.value(),this.__chain__)},Or.prototype.next=function(){this.__values__===r&&(this.__values__=la(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?r:this.__values__[this.__index__++]}},Or.prototype.plant=function(e){for(var t,n=this;n instanceof Fr;){var i=Ms(n);i.__index__=0,i.__values__=r,t?s.__wrapped__=i:t=i;var s=i;n=n.__wrapped__}return s.__wrapped__=e,t},Or.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof $r){var t=e;return this.__actions__.length&&(t=new $r(this)),(t=t.reverse()).__actions__.push({func:lo,args:[Xs],thisArg:r}),new Br(t,this.__chain__)}return this.thru(Xs)},Or.prototype.toJSON=Or.prototype.valueOf=Or.prototype.value=function(){return ci(this.__wrapped__,this.__actions__)},Or.prototype.first=Or.prototype.head,Qe&&(Or.prototype[Qe]=function(){return this}),Or}();dt?((dt.exports=cr)._=cr,ct._=cr):ut._=cr}()}(pC,pC.exports)),new gs("sds:message"),new gs("sds:message-channel"),new gs("sdk:query-on-connect"),(e=>{e.MessagesRetrieved="messages:retrieved"})(fC||(fC={})),new gs("sdk:missing-message-retriever"),new gs("sdk:reliable-channel"),_s.ENCODE_FAILED,_s.EMPTY_PAYLOAD,_s.SIZE_TOO_BIG,_s.RLN_PROOF_GENERATION;const{floor:gC,random:mC}=Math,vC="Trystero",yC=(e,t)=>Array(e).fill().map(t),bC=yC(20,(()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[gC(62*mC())])).join(""),wC=Promise.all.bind(Promise),EC="undefined"!=typeof window,{entries:SC,fromEntries:AC,keys:IC}=Object,_C=()=>{},CC=e=>Error(`${vC}: ${e}`),kC=new TextEncoder,xC=new TextDecoder,TC=e=>kC.encode(e),PC=e=>xC.decode(e),RC=(...e)=>e.join("@"),LC=JSON.stringify,DC=JSON.parse;let MC=null,NC=null;const OC=()=>{MC||(MC=new Promise((e=>{NC=e})).finally((()=>{NC=null,MC=null})))},UC=()=>null==NC?void 0:NC(),FC="AES-GCM",BC={},$C=async e=>(h=BC)[f=e]||(h[f]=Array.from(await(async(e,t)=>new Uint8Array(await crypto.subtle.digest("SHA-1",TC(t))))(0,e)).map((e=>e.toString(36))).join("")),qC=async(e,t)=>{const r=crypto.getRandomValues(new Uint8Array(16));var n;return r.join(",")+"$"+(n=await crypto.subtle.encrypt({name:FC,iv:r},await e,TC(t)),btoa(String.fromCharCode.apply(null,new Uint8Array(n))))},zC=async(e,t)=>{const[r,n]=t.split("$");return PC(await crypto.subtle.decrypt({name:FC,iv:new Uint8Array(r.split(","))},await e,(e=>{const t=atob(e);return new Uint8Array(t.length).map(((e,r)=>t.charCodeAt(r))).buffer})(n)))},jC="icegatheringstatechange",KC="offer";var VC=(e,{rtcConfig:t,rtcPolyfill:r,turnConfig:n})=>{const i=new(r||RTCPeerConnection)((0,D.default)({iceServers:HC.concat(n||[])},t)),s={};let o=!1,a=!1,l=null;const u=e=>{e.binaryType="arraybuffer",e.bufferedAmountLowThreshold=65535,e.onmessage=e=>{var t;return null===(t=s.data)||void 0===t?void 0:t.call(s,e.data)},e.onopen=()=>{var e;return null===(e=s.connect)||void 0===e?void 0:e.call(s)},e.onclose=()=>{var e;return null===(e=s.close)||void 0===e?void 0:e.call(s)},e.onerror=e=>{var t;return null===(t=s.error)||void 0===t?void 0:t.call(s,e)}},c=e=>Promise.race([new Promise((t=>{const r=()=>{"complete"===e.iceGatheringState&&(e.removeEventListener(jC,r),t())};e.addEventListener(jC,r),r()})),new Promise((e=>setTimeout(e,5e3)))]).then((()=>({type:e.localDescription.type,sdp:e.localDescription.sdp.replace(/a=ice-options:trickle\s\n/g,"")})));return e?(l=i.createDataChannel("data"),u(l)):i.ondatachannel=({channel:e})=>{l=e,u(e)},i.onnegotiationneeded=async()=>{try{var e;o=!0,await i.setLocalDescription();const t=await c(i);null===(e=s.signal)||void 0===e||e.call(s,t)}catch(e){var t;null===(t=s.error)||void 0===t||t.call(s,e)}finally{o=!1}},i.onconnectionstatechange=()=>{var e;["disconnected","failed","closed"].includes(i.connectionState)&&(null===(e=s.close)||void 0===e||e.call(s))},i.ontrack=e=>{var t,r;null===(t=s.track)||void 0===t||t.call(s,e.track,e.streams[0]),null===(r=s.stream)||void 0===r||r.call(s,e.streams[0])},i.onremovestream=e=>{var t;return null===(t=s.stream)||void 0===t?void 0:t.call(s,e.stream)},e&&(i.canTrickleIceCandidates||i.onnegotiationneeded()),{created:Date.now(),connection:i,get channel(){return l},get isDead(){return"closed"===i.connectionState},async signal(t){var r;if("open"!==(null==l?void 0:l.readyState)||(null===(r=t.sdp)||void 0===r?void 0:r.includes("a=rtpmap")))try{if(t.type===KC){var n;if(o||"stable"!==i.signalingState&&!a){if(e)return;await wC([i.setLocalDescription({type:"rollback"}),i.setRemoteDescription(t)])}else await i.setRemoteDescription(t);await i.setLocalDescription();const r=await c(i);return null===(n=s.signal)||void 0===n||n.call(s,r),r}if("answer"===t.type){a=!0;try{await i.setRemoteDescription(t)}finally{a=!1}}}catch(e){var u;null===(u=s.error)||void 0===u||u.call(s,e)}},sendData:e=>l.send(e),destroy(){null==l||l.close(),i.close(),o=!1,a=!1},setHandlers:e=>Object.assign(s,e),offerPromise:e?new Promise((e=>s.signal=t=>{t.type===KC&&e(t)})):Promise.resolve(),addStream:e=>e.getTracks().forEach((t=>i.addTrack(t,e))),removeStream:e=>i.getSenders().filter((t=>e.getTracks().includes(t.track))).forEach((e=>i.removeTrack(e))),addTrack:(e,t)=>i.addTrack(e,t),removeTrack(e){const t=i.getSenders().find((t=>t.track===e));t&&i.removeTrack(t)},replaceTrack(e,t){const r=i.getSenders().find((t=>t.track===e));if(r)return r.replaceTrack(t)}}};const HC=[...yC(3,((e,t)=>`stun:stun${t||""}.l.google.com:19302`)),"stun:stun.cloudflare.com:3478"].map((e=>({urls:e}))),WC=Object.getPrototypeOf(Uint8Array),GC=16369,XC=255,ZC="bufferedamountlow",YC=e=>"@_"+e;const QC=e=>`/${vC}-${e}/0/msg/json`,JC=(e,t,r)=>e.lightPush.send(e.createEncoder({contentTopic:QC(t),ephemeral:!0}),{payload:TC(r)},{autoRetry:!0}),ek=(({init:e,subscribe:t,announce:r})=>{const n={};let i,s,o,a,l=!1;return(u,c,d)=>{var h;const{appId:f}=u;if(null===(h=n[f])||void 0===h?void 0:h[c])return n[f][c];const C={},k={},x=RC(vC,f,c),T=$C(x),P=$C(RC(x,bC)),R=(async(e,t,r)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},TC(`${e}:${t}:${r}`)),{name:FC},!1,["encrypt","decrypt"]))(u.password||"",f,c),L=e=>async t=>({type:t.type,sdp:await e(R,t.sdp)}),N=L(zC),O=L(qC),U=()=>VC(!0,u),F=(e,t,r)=>{var n;k[t]?k[t]!==e&&e.destroy():(k[t]=e,V(e,t),null===(n=C[t])||void 0===n||n.forEach(((e,t)=>{t!==r&&e.destroy()})),delete C[t])},B=(e,t)=>{k[t]===e&&delete k[t]},$=e=>(s.push(...yC(e,U)),wC(s.splice(0,e).map((e=>e.offerPromise.then(O).then((t=>({peer:e,offer:t}))))))),q=(e,t)=>null==d?void 0:d({error:`incorrect password (${u.password}) when decrypting ${t}`,appId:f,peerId:e,roomId:c});if(!u)throw CC("requires a config map as the first argument");if(!f&&!u.firebaseApp)throw CC("config map is missing appId field");if(!c)throw CC("roomId argument required");if(!l){const t=e(u);s=yC(20,U),i=Array.isArray(t)?t:[t],l=!0,o=setInterval((()=>s=s.filter((e=>{const t=Date.now()-e.created<57333;return t||e.destroy(),t}))),59052.99),a=u.manualRelayReconnection?_C:(()=>{if(EC){const e=new AbortController;return addEventListener("online",UC,{signal:e.signal}),addEventListener("offline",OC,{signal:e.signal}),()=>e.abort()}return _C})()}const z=i.map((()=>5333)),j=[],K=i.map((async(e,r)=>t(await e,await T,await P,(e=>async(t,r,n)=>{const[i,s]=await wC([T,P]);if(t!==i&&t!==s)return;const{peerId:o,offer:a,answer:l,peer:c}="string"==typeof r?DC(r):r;if(o!==bC&&!k[o])if(!o||a||l){if(a){var d;if((null===(d=C[o])||void 0===d?void 0:d[e])&&bC>o)return;const t=VC(!1,u);let r;t.setHandlers({connect:()=>F(t,o,e),close:()=>B(t,o)});try{r=await N(a)}catch(e){return void q(o,"offer")}if(t.isDead)return;const[i,s]=await wC([$C(RC(x,o)),t.signal(r)]);n(i,LC({peerId:bC,answer:await O(s)}))}else if(l){let t;try{t=await N(l)}catch(e){return void q(o,"answer")}if(c)c.setHandlers({connect:()=>F(c,o,e),close:()=>B(c,o)}),c.signal(t);else{var h;const r=null===(h=C[o])||void 0===h?void 0:h[e];r&&!r.isDead&&r.signal(t)}}}else{var f;if(null===(f=C[o])||void 0===f?void 0:f[e])return;const[[{peer:t,offer:r}],i]=await wC([$(1),$C(RC(x,o))]);(S=C)[A=o]||(S[A]=[]),C[o][e]=t,setTimeout((()=>((e,t)=>{var r;if(k[e])return;const n=null===(r=C[e])||void 0===r?void 0:r[t];n&&(delete C[e][t],n.destroy())})(o,e)),.9*z[e]),t.setHandlers({connect:()=>F(t,o,e),close:()=>B(t,o)}),n(i,LC({peerId:bC,offer:r}))}})(r),$)));wC([T,P]).then((([e,t])=>{const n=async(i,s)=>{const o=await r(i,e,t);"number"==typeof o&&(z[s]=o),j[s]=setTimeout((()=>n(i,s)),z[s])};K.forEach((async(e,t)=>{await e,n(await i[t],t)}))}));let V=_C;return(I=n)[_=f]||(I[_]={}),n[f][c]=((e,t,r)=>{const n={},i={},s={},o={},a={},l={},u={},c={onPeerJoin:_C,onPeerLeave:_C,onPeerStream:_C,onPeerTrack:_C},d=(e,t)=>(e?Array.isArray(e)?e:[e]:IC(n)).flatMap((e=>{const r=n[e];return r?t(e,r):(console.warn(`${vC}: no peer with id ${e} found`),[])})),h=e=>{n[e]&&(n[e].destroy(),delete n[e],delete o[e],delete a[e],c.onPeerLeave(e),t(e))},f=e=>{if(i[e])return s[e];if(!e)throw CC("action type argument is required");const t=TC(e);if(t.byteLength>12)throw CC(`action type string "${e}" (${t.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const r=new Uint8Array(12);r.set(t);let o=0;return i[e]={onComplete:_C,onProgress:_C,setOnComplete:t=>i[e]=(0,M.default)((0,D.default)({},i[e]),{onComplete:t}),setOnProgress:t=>i[e]=(0,M.default)((0,D.default)({},i[e]),{onProgress:t}),async send(e,t,i,s){if(i&&"object"!=typeof i)throw CC("action meta argument must be an object");const a=typeof e;if("undefined"===a)throw CC("action data cannot be undefined");const l="string"!==a,u=e instanceof Blob,c=u||e instanceof ArrayBuffer||e instanceof WC;if(i&&!c)throw CC("action meta argument can only be used with binary data");const h=c?new Uint8Array(u?await e.arrayBuffer():e):TC(l?LC(e):e),f=i?TC(LC(i)):null,p=Math.ceil(h.byteLength/GC)+(i?1:0)||1,g=yC(p,((e,t)=>{const n=t===p-1,s=i&&0===t,a=new Uint8Array(15+(s?f.byteLength:n?h.byteLength-GC*(p-(i?2:1)):GC));return a.set(r),a.set([o],12),a.set([n|s<<1|c<<2|l<<3],13),a.set([Math.round((t+1)/p*XC)],14),a.set(i?s?f:h.subarray((t-1)*GC,t*GC):h.subarray(t*GC,(t+1)*GC),15),a}));return o=o+1&XC,wC(d(t,(async(e,t)=>{const{channel:r}=t;let o=0;for(;o<p;){const a=g[o];if(r.bufferedAmount>r.bufferedAmountLowThreshold&&await new Promise((e=>{const t=()=>{r.removeEventListener(ZC,t),e()};r.addEventListener(ZC,t)})),!n[e])break;t.sendData(a),o++,null==s||s(a[14]/XC,e,i)}})))}},(p=s)[g=e]||(p[g]=[i[e].send,i[e].setOnComplete,i[e].setOnProgress])},S=async()=>{await N(""),await new Promise((e=>setTimeout(e,99))),SC(n).forEach((([e,t])=>{t.destroy(),delete n[e]})),r()},[A,I]=f(YC("ping")),[_,C]=f(YC("pong")),[k,x]=f(YC("signal")),[T,P]=f(YC("stream")),[R,L]=f(YC("track")),[N,O]=f(YC("leave"));return e(((e,t)=>{n[t]||(n[t]=e,e.setHandlers({data:e=>((e,t)=>{const r=new Uint8Array(t),n=PC(r.subarray(0,12)).replaceAll("\0",""),[s]=r.subarray(12,13),[a]=r.subarray(13,14),[l]=r.subarray(14,15),u=r.subarray(15),c=!!(1&a),d=!!(2&a),h=!!(4&a),f=!!(8&a);if(!i[n])return void console.warn(`${vC}: received message with unregistered type (${n})`);(m=o)[v=e]||(m[v]={}),(y=o[e])[b=n]||(y[b]={});const p=(w=o[e][n])[E=s]||(w[E]={chunks:[]});if(d?p.meta=DC(PC(u)):p.chunks.push(u),i[n].onProgress(l/XC,e,p.meta),!c)return;const g=new Uint8Array(p.chunks.reduce(((e,t)=>e+t.byteLength),0));if(p.chunks.reduce(((e,t)=>(g.set(t,e),e+t.byteLength)),0),delete o[e][n][s],h)i[n].onComplete(g,e,p.meta);else{const t=PC(g);i[n].onComplete(f?DC(t):t,e)}})(t,e),stream(e){c.onPeerStream(e,t,l[t]),delete l[t]},track(e,r){c.onPeerTrack(e,r,t,u[t]),delete u[t]},signal:e=>k(e,t),close:()=>h(t),error(e){console.error(e),h(t)}}),c.onPeerJoin(t))})),I(((e,t)=>_("",t))),C(((e,t)=>{var r;null===(r=a[t])||void 0===r||r.call(a),delete a[t]})),x(((e,t)=>{var r;return null===(r=n[t])||void 0===r?void 0:r.signal(e)})),P(((e,t)=>l[t]=e)),L(((e,t)=>u[t]=e)),O(((e,t)=>h(t))),EC&&addEventListener("beforeunload",S),{makeAction:f,leave:S,async ping(e){if(!e)throw CC("ping() must be called with target peer ID");const t=Date.now();return A("",e),await new Promise((t=>a[e]=t)),Date.now()-t},getPeers:()=>AC(SC(n).map((([e,t])=>[e,t.connection]))),addStream:(e,t,r)=>d(t,(async(t,n)=>{r&&await T(r,t),n.addStream(e)})),removeStream:(e,t)=>d(t,((t,r)=>r.removeStream(e))),addTrack:(e,t,r,n)=>d(r,(async(r,i)=>{n&&await R(n,r),i.addTrack(e,t)})),removeTrack:(e,t)=>d(t,((t,r)=>r.removeTrack(e))),replaceTrack:(e,t,r,n)=>d(r,(async(r,i)=>{n&&await R(n,r),i.replaceTrack(e,t)})),onPeerJoin:e=>c.onPeerJoin=e,onPeerLeave:e=>c.onPeerLeave=e,onPeerStream:e=>c.onPeerStream=e,onPeerTrack:e=>c.onPeerTrack=e}})((e=>V=e),(e=>delete k[e]),(()=>{delete n[f][c],j.forEach(clearTimeout),K.forEach((async e=>(await e)())),clearInterval(o),a(),l=!1}))}})({init:()=>async function(e={}){const t=await async function(e){var t,r,n;const i=null!==(n=(null!==(r=e.networkConfig)&&void 0!==r?r:Rs).clusterId)&&void 0!==n?n:1;var s,o;C_.info("Creating Waku node with cluster id: ",i);const a=null!==(s=null==e?void 0:e.libp2p)&&void 0!==s?s:{},l=null!==(o=a.peerDiscovery)&&void 0!==o?o:[];(null==e?void 0:e.defaultBootstrap)?l.push(...__((0,D.default)({dns:!0,peerExchange:!0,peerCache:!0},e.discovery),e.peerCache)):l.push(...__(e.discovery,e.peerCache));const u=[...e.bootstrapPeers||[],...(null===(t=e.store)||void 0===t?void 0:t.peers)||[]];var c;return u.length&&l.push((c={list:u},e=>new Nf(e,c))),a.peerDiscovery=l,k_(i,a,null==e?void 0:e.userAgent)}(e),r=new xd(e,t,{store:!0,lightpush:!0,filter:!0});return!1!==(null==e?void 0:e.autoStart)&&await r.start(),r}({defaultBootstrap:!0,discovery:{dns:!0,peerExchange:!0,peerCache:!0}}).then((async e=>(await e.start(),await e.waitForPeers(),e))),async subscribe(e,t,r,n){const i=await wC([t,r].map((t=>{const r=e.createDecoder({contentTopic:QC(t)});return e.filter.subscribe(r,(t=>r=>{r.payload&&n(t,PC(r.payload),((t,r)=>JC(e,t,r)))})(t)),()=>e.filter.unsubscribe(r)})));return()=>i.forEach((e=>e()))},announce:(e,t)=>JC(e,t,LC({peerId:bC}))})})),r.register("e963W",(function(e,n){t(e.exports,"default",(function(){return o}));var i=r("2wTKP"),s=r("6br39");function o(e,t){var r=(0,i.default)(e,t,"get");return(0,s.default)(e,r)}})),r.register("2wTKP",(function(e,r){function n(e,t,r){if(!t.has(e))throw new TypeError("attempted to "+r+" private field on non-instance");return t.get(e)}t(e.exports,"default",(function(){return n}))})),r.register("6br39",(function(e,r){function n(e,t){return t.get?t.get.call(e):t.value}t(e.exports,"default",(function(){return n}))})),r.register("lvOWe",(function(e,n){t(e.exports,"default",(function(){return s}));var i=r("jb4AR");function s(e,t,r){(0,i.default)(e,t),t.set(e,r)}})),r.register("jb4AR",(function(e,r){function n(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}t(e.exports,"default",(function(){return n}))})),r.register("ezKE5",(function(e,n){t(e.exports,"default",(function(){return o}));var i=r("2wTKP"),s=r("iceM3");function o(e,t,r){var n=(0,i.default)(e,t,"set");return(0,s.default)(e,n,r),r}})),r.register("iceM3",(function(e,r){function n(e,t,r){if(t.set)t.set.call(e,r);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=r}}t(e.exports,"default",(function(){return n}))})),r.register("dpALB",(function(e,n){t(e.exports,"default",(function(){return o}));var i=r("2wTKP"),s=r("14QXB");function o(e,t){var r=(0,i.default)(e,t,"update");return(0,s.default)(e,r)}})),r.register("14QXB",(function(e,r){function n(e,t){if(t.set){if(!t.get)throw new TypeError("attempted to read set only private field");return"__destrWrapper"in t||(t.__destrWrapper={set value(r){t.set.call(e,r)},get value(){return t.get.call(e)}}),t.__destrWrapper}if(!t.writable)throw new TypeError("attempted to set read only private field");return t}t(e.exports,"default",(function(){return n}))})),r.register("1VQD5",(function(e,r){function n(e,t,r){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return r}t(e.exports,"default",(function(){return n}))})),r.register("cJcuy",(function(e,n){t(e.exports,"default",(function(){return s}));var i=r("jb4AR");function s(e,t){(0,i.default)(e,t),t.add(e)}}));