libp2p 2.7.3-e1f868f03 → 2.7.3-e2f49432b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -3,7 +3,7 @@
3
3
  `).map(s=>` ${s}`).join(`
4
4
  `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
5
5
  ${e.join(`
6
- `)}`:`${t} :`}};Ld=Qt;C.Constructed=Ld;Qt.NAME="CONSTRUCTED";var Po=class extends Te{fromBER(e,t,n){return t}toBER(e){return it}};Po.override="EndOfContentValueBlock";var Pd,No=class extends Ee{constructor(e={}){super(e,Po),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Pd=No;C.EndOfContent=Pd;No.NAME=rs;var Nd,an=class extends Ee{constructor(e={}){super(e,Te),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let s=new Uint8Array(n);s[0]=5,s[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Nd=an;C.Null=Nd;an.NAME="NULL";var Do=class extends Nt(Te){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=H.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let s=H.BufferSourceConverter.toUint8Array(e);return Pt(this,s,t,n)?(this.valueHexView=s.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,yl.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Do.NAME="BooleanValueBlock";var Dd,Ro=class extends Ee{constructor(e={}){super(e,Do),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Dd=Ro;C.Boolean=Dd;Ro.NAME="BOOLEAN";var Mo=class extends Nt(ht){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=ht.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let o=0;o<this.value.length;o++){let i=this.value[o].constructor.NAME;if(i===rs){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Id)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,n),this.blockLength=n;return s}toBER(e,t){return this.isConstructed?ht.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Mo.NAME="OctetStringValueBlock";var Rd,Oo=class r extends Ee{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Mo),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let o=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(o.byteLength){let i=fi(o,0,o.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Qt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${H.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return H.BufferSourceConverter.concat(e)}};Rd=Oo;C.OctetString=Rd;Oo.NAME=Id;var Uo=class extends Nt(ht){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let s=-1;if(this.isConstructed){if(s=ht.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let a of this.value){let c=a.constructor.NAME;if(c===rs){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Bd)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return s}let o=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=fi(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return ht.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return it;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Uo.NAME="BitStringValueBlock";var Md,cn=class extends Ee{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Uo),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Qt.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let s of t)e.push(s.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Md=cn;C.BitString=Md;cn.NAME=Bd;var Od;function by(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=o[i-f]+a[c-f]+t[0];break;default:l=o[i-f]+t[0]}switch(t[0]=l/10,!0){case f>=o.length:o=_o(new Uint8Array([l%10]),o);break;default:o[i-f]=l%10}}return t[0]>0&&(o=_o(t,o)),o}function Cd(r){if(r>=es.length)for(let e=es.length;e<=r;e++){let t=new Uint8Array([0]),n=es[e-1].slice(0);for(let s=n.length-1;s>=0;s--){let o=new Uint8Array([(n[s]<<1)+t[0]]);t[0]=o[0]/10,n[s]=o[0]%10}t[0]>0&&(n=_o(t,n)),es.push(n)}return es[r]}function xy(r,e){let t=0,n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=o[i-u]-a[c-u]-t,!0){case l<0:t=1,o[i-u]=l+10;break;default:t=0,o[i-u]=l}if(t>0)for(let f=i-c+1;f>=0;f--,u++)if(l=o[i-u]-t,l<0)t=1,o[i-u]=l+10;else{t=0,o[i-u]=l;break}return o.slice()}var ns=class extends Nt(Te){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=yl.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Ad(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,s=0){let o=this.fromBER(e,t,n);if(o===-1)return o;let i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):s!==0&&i.length<s&&(s-i.length>1&&(s=i.length+1),this.valueHexView=i.subarray(s-i.length)),o}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let s=super.fromBER(e,t,n);return s===-1||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,s,o=this.valueHexView,i="",a=!1;for(let c=o.byteLength-1;c>=0;c--){s=o[c];for(let l=0;l<8;l++){if((s&1)===1)switch(n){case e:t=xy(Cd(n),t),i="-";break;default:t=by(t,Cd(n))}n++,s>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=_d.charAt(t[c]));return a===!1&&(i+=_d.charAt(0)),i}};Od=ns;ns.NAME="IntegerValueBlock";Object.defineProperty(Od.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Ud,Ae=class r extends Ee{constructor(e={}){super(e,ns),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Co(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Co();let t=BigInt(e),n=new ts,s=t.toString(16).replace(/^-/,""),o=new Uint8Array(H.Convert.FromHex(s));if(t<0){let a=new Uint8Array(o.length+(o[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${H.Convert.ToHex(a)}`)+t,u=H.BufferSourceConverter.toUint8Array(H.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else o[0]&128&&n.write(new Uint8Array([0])),n.write(o);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Ud=Ae;C.Integer=Ud;Ae.NAME="INTEGER";var Fd,Fo=class extends Ae{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Fd=Fo;C.Enumerated=Fd;Fo.NAME="ENUMERATED";var ss=class extends Nt(Te){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let s=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Co();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let s=0;s<n.length;s++)n[s]=parseInt(t.slice(s*7,s*7+7),2)+(s+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",it;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n}toString(){let e="";if(this.isHexOnly)e=H.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};ss.NAME="sidBlock";var Vo=class extends Te{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new ss;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.value.length===0&&(o.isFirstSid=!0),this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let s=this.value[n].toBER(e);if(s.byteLength===0)return this.error=this.value[n].error,it;t.push(s)}return wl(t)}fromString(e){this.value=[];let t=0,n=0,s="",o=!1;do if(n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1,o){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(s,10);if(isNaN(c))return;i.valueDec=c+a,o=!1}else{let i=new ss;if(s>Number.MAX_SAFE_INTEGER){Co();let a=BigInt(s);i.valueBigInt=a}else if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,o=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),t?(s=`{${s}}`,this.value[n].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Vo.NAME="ObjectIdentifierValueBlock";var Vd,ln=class extends Ee{constructor(e={}){super(e,Vo),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Vd=ln;C.ObjectIdentifier=Vd;ln.NAME="OBJECT IDENTIFIER";var os=class extends Nt(kt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let s=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",it;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n.buffer}toString(){let e="";return this.isHexOnly?e=H.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};os.NAME="relativeSidBlock";var Ho=class extends Te{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new os;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e,t){let n=[];for(let s=0;s<this.value.length;s++){let o=this.value[s].toBER(e);if(o.byteLength===0)return this.error=this.value[s].error,it;n.push(o)}return wl(n)}fromString(e){this.value=[];let t=0,n=0,s="";do{n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1;let o=new os;if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return!0;this.value.push(o)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(s=`{${s}}`),e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Ho.NAME="RelativeObjectIdentifierValueBlock";var Hd,Ko=class extends Ee{constructor(e={}){super(e,Ho),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Hd=Ko;C.RelativeObjectIdentifier=Hd;Ko.NAME="RelativeObjectIdentifier";var Kd,Tt=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Kd=Tt;C.Sequence=Kd;Tt.NAME="SEQUENCE";var $d,$o=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};$d=$o;C.Set=$d;$o.NAME="SET";var qo=class extends Nt(Te){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=un}toJSON(){return{...super.toJSON(),value:this.value}}};qo.NAME="StringValueBlock";var zo=class extends qo{};zo.NAME="SimpleStringValueBlock";var Ue=class extends ko{constructor({...e}={}){super(e,zo)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,H.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);this.valueBlock.value=e}};Ue.NAME="SIMPLE STRING";var Go=class extends Ue{fromBuffer(e){this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=H.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=H.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Go.NAME="Utf8StringValueBlock";var qd,Lt=class extends Go{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};qd=Lt;C.Utf8String=qd;Lt.NAME="UTF8String";var Wo=class extends Ue{fromBuffer(e){this.valueBlock.value=H.Convert.ToUtf16String(e),this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf16String(e))}};Wo.NAME="BmpStringValueBlock";var zd,jo=class extends Wo{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};zd=jo;C.BmpString=zd;jo.NAME="BMPString";var Zo=class extends Ue{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let s=0;s<n.length;s+=4)n[s]=n[s+3],n[s+1]=n[s+2],n[s+2]=0,n[s+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let s=0;s<t;s++){let o=Jt(e.charCodeAt(s),8),i=new Uint8Array(o);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[s*4+c+a]=i[c]}this.valueBlock.value=e}};Zo.NAME="UniversalStringValueBlock";var Gd,Xo=class extends Zo{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Gd=Xo;C.UniversalString=Gd;Xo.NAME="UniversalString";var Wd,Yo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Wd=Yo;C.NumericString=Wd;Yo.NAME="NumericString";var jd,Jo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};jd=Jo;C.PrintableString=jd;Jo.NAME="PrintableString";var Zd,Qo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Zd=Qo;C.TeletexString=Zd;Qo.NAME="TeletexString";var Xd,ei=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Xd=ei;C.VideotexString=Xd;ei.NAME="VideotexString";var Yd,ti=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Yd=ti;C.IA5String=Yd;ti.NAME="IA5String";var Jd,ri=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Jd=ri;C.GraphicString=Jd;ri.NAME="GraphicString";var Qd,is=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Qd=is;C.VisibleString=Qd;is.NAME="VisibleString";var eh,ni=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};eh=ni;C.GeneralString=eh;ni.NAME="GeneralString";var th,si=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};th=si;C.CharacterString=th;si.NAME="CharacterString";var rh,as=class extends is{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let s=0;s<e.length;s++)this.valueBlock.valueHexView[s]=e.charCodeAt(s)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,H.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let s=parseInt(n[1],10);s>=50?this.year=1900+s:this.year=2e3+s,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=qe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=qe(this.month,2),t[2]=qe(this.day,2),t[3]=qe(this.hour,2),t[4]=qe(this.minute,2),t[5]=qe(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};rh=as;C.UTCTime=rh;as.NAME="UTCTime";var nh,oi=class extends as{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",s="",o=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),m="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(m=n.substring(d+1),n=n.substring(0,d),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(m.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*p,m.length===4){if(p=parseInt(m.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=f*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");o=f.valueOf(),s=n.substring(0,l)}else s=n;switch(!0){case s.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*o;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case s.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*o;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case s.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*o;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(s);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(qe(this.year,4)),t.push(qe(this.month,2)),t.push(qe(this.day,2)),t.push(qe(this.hour,2)),t.push(qe(this.minute,2)),t.push(qe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(qe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};nh=oi;C.GeneralizedTime=nh;oi.NAME="GeneralizedTime";var sh,ii=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};sh=ii;C.DATE=sh;ii.NAME="DATE";var oh,ai=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};oh=ai;C.TimeOfDay=oh;ai.NAME="TimeOfDay";var ih,ci=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};ih=ci;C.DateTime=ih;ci.NAME="DateTime";var ah,li=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};ah=li;C.Duration=ah;li.NAME="Duration";var ch,ui=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};ch=ui;C.TIME=ch;ui.NAME="TIME";function z(r,e="utf8"){let t=xo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function fn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return Qr(r)}var cs=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},ls=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},di=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var lh={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new di("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 e}};var er=lh;async function uh(r){let e=await er.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Ey(e);return{privateKey:t[0],publicKey:t[1]}}async function fh(r,e){let t=await er.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await er.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function dh(r,e,t){let n=await er.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return er.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Ey(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required");return Promise.all([er.get().subtle.exportKey("jwk",r.privateKey),er.get().subtle.exportKey("jwk",r.publicKey)])}function vl(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return N(r.n,"base64url").length*8}var dn=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=us.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return dh(this._key,t,e)}},fs=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=us.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return fh(this._key,e)}};var hi=8192,El=18;function hh(r){let{result:e}=xl(r),t=e.valueBlock.value;return{n:pt(t[1]),e:pt(t[2]),d:pt(t[3]),p:pt(t[4]),q:pt(t[5]),dp:pt(t[6]),dq:pt(t[7]),qi:pt(t[8]),kty:"RSA",alg:"RS256"}}function Ay(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new D("JWK was missing components");let t=new Tt({value:[new Ae({value:0}),Ae.fromBigInt(mt(N(r.n,"base64url"))),Ae.fromBigInt(mt(N(r.e,"base64url"))),Ae.fromBigInt(mt(N(r.d,"base64url"))),Ae.fromBigInt(mt(N(r.p,"base64url"))),Ae.fromBigInt(mt(N(r.q,"base64url"))),Ae.fromBigInt(mt(N(r.dp,"base64url"))),Ae.fromBigInt(mt(N(r.dq,"base64url"))),Ae.fromBigInt(mt(N(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function ph(r){let{result:e}=xl(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:pt(t[0]),e:pt(t[1])}}function Al(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let t=new Tt({value:[new Tt({value:[new ln({value:"1.2.840.113549.1.1.1"}),new an]}),new cn({valueHex:new Tt({value:[Ae.fromBigInt(mt(N(r.n,"base64url"))),Ae.fromBigInt(mt(N(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function pt(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return z(e,"base64url")}function mt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}function mh(r){let e=hh(r);return gh(e)}function Sl(r){let e=ph(r);if(vl(e)>hi)throw new Hr("Key size is too large");let t=sn(dt.encode({Type:ge.RSA,Data:r})),n=Qe(El,t);return new dn(e,n)}function gh(r){if(vl(r)>hi)throw new D("Key size is too large");let e=yh(r),t=sn(dt.encode({Type:ge.RSA,Data:Al(e.publicKey)})),n=Qe(El,t);return new fs(e.privateKey,new dn(e.publicKey,n))}async function _l(r){if(r>hi)throw new D("Key size is too large");let e=await uh(r),t=sn(dt.encode({Type:ge.RSA,Data:Al(e.publicKey)})),n=Qe(El,t);return new fs(e.privateKey,new dn(e.publicKey,n))}function yh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var pi=class extends Jr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Of(e);let n=qn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?e.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),o.fill(0)}update(e){return Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),Xr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Cl=(r,e,t)=>new pi(r,e).update(t).digest();Cl.create=(r,e)=>new pi(r,e);function wh(r){r.lowS!==void 0&&rt("lowS",r.lowS),r.prehash!==void 0&&rt("prehash",r.prehash)}function Sy(r){let e=Wn(r);ut(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:s}=e;if(t){if(!n.eql(s,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:_y,hexToBytes:Cy}=co,Il=class extends Error{constructor(e=""){super(e)}},Dt={Err:Il,_tlv:{encode:(r,e)=>{let{Err:t}=Dt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=ur(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?ur(s.length/2|128):"";return ur(r)+o+s+e},decode(r,e){let{Err:t}=Dt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Dt;if(r<Rt)throw new e("integer: negative integers are not allowed");let t=ur(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Dt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return _y(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Dt,s=typeof r=="string"?Cy(r):r;tn(s);let{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Dt,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},Rt=BigInt(0),xe=BigInt(1),QE=BigInt(2),bh=BigInt(3),e2=BigInt(4);function Iy(r){let e=Sy(r),{Fp:t}=e,n=jt(e.n,e.nBitLength),s=e.toBytes||((g,h,w)=>{let x=h.toAffine();return It(Uint8Array.from([4]),t.toBytes(x.x),t.toBytes(x.y))}),o=e.fromBytes||(g=>{let h=g.subarray(1),w=t.fromBytes(h.subarray(0,t.BYTES)),x=t.fromBytes(h.subarray(t.BYTES,2*t.BYTES));return{x:w,y:x}});function i(g){let{a:h,b:w}=e,x=t.sqr(g),y=t.mul(x,g);return t.add(t.add(y,t.mul(g,h)),w)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return zn(g,xe,e.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:x,n:y}=e;if(h&&typeof g!="bigint"){if(zt(g)&&(g=_t(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(w*2,"0")}let E;try{E=typeof g=="bigint"?g:Ct(oe("private key",g,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof g)}return x&&(E=Q(E,y)),Ke("private key",E,xe,y),E}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=hr((g,h)=>{let{px:w,py:x,pz:y}=g;if(t.eql(y,t.ONE))return{x:w,y:x};let E=g.is0();h==null&&(h=E?t.ONE:t.inv(y));let _=t.mul(w,h),L=t.mul(x,h),I=t.mul(y,h);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:_,y:L}}),f=hr(g=>{if(g.is0()){if(e.allowInfinityPoint&&!t.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=g.toAffine();if(!t.isValid(h)||!t.isValid(w))throw new Error("bad point: x or y not FE");let x=t.sqr(w),y=i(h);if(!t.eql(x,y))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,x){if(this.px=h,this.py=w,this.pz=x,h==null||!t.isValid(h))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(x==null||!t.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:x}=h||{};if(!h||!t.isValid(w)||!t.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let y=E=>t.eql(E,t.ZERO);return y(w)&&y(x)?d.ZERO:new d(w,x,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=t.invertBatch(h.map(x=>x.pz));return h.map((x,y)=>x.toAffine(w[y])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(o(oe("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return ho(d,n,h,w)}_setWindowSize(h){p.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(t.isOdd)return!t.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=t.eql(t.mul(w,L),t.mul(E,y)),T=t.eql(t.mul(x,L),t.mul(_,y));return I&&T}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:h,b:w}=e,x=t.mul(w,bh),{px:y,py:E,pz:_}=this,L=t.ZERO,I=t.ZERO,T=t.ZERO,k=t.mul(y,y),re=t.mul(E,E),W=t.mul(_,_),V=t.mul(y,E);return V=t.add(V,V),T=t.mul(y,_),T=t.add(T,T),L=t.mul(h,T),I=t.mul(x,W),I=t.add(L,I),L=t.sub(re,I),I=t.add(re,I),I=t.mul(L,I),L=t.mul(V,L),T=t.mul(x,T),W=t.mul(h,W),V=t.sub(k,W),V=t.mul(h,V),V=t.add(V,T),T=t.add(k,k),k=t.add(T,k),k=t.add(k,W),k=t.mul(k,V),I=t.add(I,k),W=t.mul(E,_),W=t.add(W,W),k=t.mul(W,V),L=t.sub(L,k),T=t.mul(W,re),T=t.add(T,T),T=t.add(T,T),new d(L,I,T)}add(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=t.ZERO,T=t.ZERO,k=t.ZERO,re=e.a,W=t.mul(e.b,bh),V=t.mul(w,E),he=t.mul(x,_),S=t.mul(y,L),P=t.add(w,x),v=t.add(E,_);P=t.mul(P,v),v=t.add(V,he),P=t.sub(P,v),v=t.add(w,y);let b=t.add(E,L);return v=t.mul(v,b),b=t.add(V,S),v=t.sub(v,b),b=t.add(x,y),I=t.add(_,L),b=t.mul(b,I),I=t.add(he,S),b=t.sub(b,I),k=t.mul(re,v),I=t.mul(W,S),k=t.add(I,k),I=t.sub(he,k),k=t.add(he,k),T=t.mul(I,k),he=t.add(V,V),he=t.add(he,V),S=t.mul(re,S),v=t.mul(W,v),he=t.add(he,S),S=t.sub(V,S),S=t.mul(re,S),v=t.add(v,S),V=t.mul(he,v),T=t.add(T,V),V=t.mul(b,v),I=t.mul(P,I),I=t.sub(I,V),V=t.mul(P,he),k=t.mul(b,k),k=t.add(k,V),new d(I,T,k)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return p.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:x}=e;Ke("scalar",h,Rt,x);let y=d.ZERO;if(h===Rt)return y;if(this.is0()||h===xe)return this;if(!w||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:E,k1:_,k2neg:L,k2:I}=w.splitScalar(h),T=y,k=y,re=this;for(;_>Rt||I>Rt;)_&xe&&(T=T.add(re)),I&xe&&(k=k.add(re)),re=re.double(),_>>=xe,I>>=xe;return E&&(T=T.negate()),L&&(k=k.negate()),k=new d(t.mul(k.px,w.beta),k.py,k.pz),T.add(k)}multiply(h){let{endo:w,n:x}=e;Ke("scalar",h,xe,x);let y,E;if(w){let{k1neg:_,k1:L,k2neg:I,k2:T}=w.splitScalar(h),{p:k,f:re}=this.wNAF(L),{p:W,f:V}=this.wNAF(T);k=p.constTimeNegate(_,k),W=p.constTimeNegate(I,W),W=new d(t.mul(W.px,w.beta),W.py,W.pz),y=k.add(W),E=re.add(V)}else{let{p:_,f:L}=this.wNAF(h);y=_,E=L}return d.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,w,x){let y=d.BASE,E=(L,I)=>I===Rt||I===xe||!L.equals(y)?L.multiplyUnsafe(I):L.multiply(I),_=E(this,w).add(E(h,x));return _.is0()?void 0:_}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=e;if(h===xe)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=e;return h===xe?this:w?w(d,this):this.multiplyUnsafe(e.h)}toRawBytes(h=!0){return rt("isCompressed",h),this.assertValidity(),s(d,this,h)}toHex(h=!0){return rt("isCompressed",h),_t(this.toRawBytes(h))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let m=e.nBitLength,p=fo(d,e.endo?Math.ceil(m/2):m);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function By(r){let e=Wn(r);return ut(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function xh(r){let e=By(r),{Fp:t,n}=e,s=t.BYTES+1,o=2*t.BYTES+1;function i(S){return Q(S,n)}function a(S){return lo(S,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Iy({...e,toBytes(S,P,v){let b=P.toAffine(),A=t.toBytes(b.x),B=It;return rt("isCompressed",v),v?B(Uint8Array.from([P.hasEvenY()?2:3]),A):B(Uint8Array.from([4]),A,t.toBytes(b.y))},fromBytes(S){let P=S.length,v=S[0],b=S.subarray(1);if(P===s&&(v===2||v===3)){let A=Ct(b);if(!zn(A,xe,t.ORDER))throw new Error("Point is not on curve");let B=u(A),R;try{R=t.sqrt(B)}catch(K){let O=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+O)}let M=(R&xe)===xe;return(v&1)===1!==M&&(R=t.neg(R)),{x:A,y:R}}else if(P===o&&v===4){let A=t.fromBytes(b.subarray(0,t.BYTES)),B=t.fromBytes(b.subarray(t.BYTES,2*t.BYTES));return{x:A,y:B}}else{let A=s,B=o;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+B+", got "+P)}}}),d=S=>_t(Wt(S,e.nByteLength));function m(S){let P=n>>xe;return S>P}function p(S){return m(S)?i(-S):S}let g=(S,P,v)=>Ct(S.slice(P,v));class h{constructor(P,v,b){this.r=P,this.s=v,this.recovery=b,this.assertValidity()}static fromCompact(P){let v=e.nByteLength;return P=oe("compactSignature",P,v*2),new h(g(P,0,v),g(P,v,2*v))}static fromDER(P){let{r:v,s:b}=Dt.toSig(oe("DER",P));return new h(v,b)}assertValidity(){Ke("r",this.r,xe,n),Ke("s",this.s,xe,n)}addRecoveryBit(P){return new h(this.r,this.s,P)}recoverPublicKey(P){let{r:v,s:b,recovery:A}=this,B=L(oe("msgHash",P));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?v+e.n:v;if(R>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let M=(A&1)===0?"02":"03",F=c.fromHex(M+d(R)),K=a(R),O=i(-B*K),J=i(b*K),te=c.BASE.multiplyAndAddUnsafe(F,O,J);if(!te)throw new Error("point at infinify");return te.assertValidity(),te}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return fr(this.toDERHex())}toDERHex(){return Dt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return fr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(S){try{return l(S),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let S=Bc(e.n);return Xf(e.randomBytes(S),e.n)},precompute(S=8,P=c.BASE){return P._setWindowSize(S),P.multiply(BigInt(3)),P}};function x(S,P=!0){return c.fromPrivateKey(S).toRawBytes(P)}function y(S){let P=zt(S),v=typeof S=="string",b=(P||v)&&S.length;return P?b===s||b===o:v?b===2*s||b===2*o:S instanceof c}function E(S,P,v=!0){if(y(S))throw new Error("first arg must be private key");if(!y(P))throw new Error("second arg must be public key");return c.fromHex(P).multiply(l(S)).toRawBytes(v)}let _=e.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");let P=Ct(S),v=S.length*8-e.nBitLength;return v>0?P>>BigInt(v):P},L=e.bits2int_modN||function(S){return i(_(S))},I=Gn(e.nBitLength);function T(S){return Ke("num < 2^"+e.nBitLength,S,Rt,I),Wt(S,e.nByteLength)}function k(S,P,v=re){if(["recovered","canonical"].some(be=>be in v))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:A}=e,{lowS:B,prehash:R,extraEntropy:M}=v;B==null&&(B=!0),S=oe("msgHash",S),wh(v),R&&(S=oe("prehashed msgHash",b(S)));let F=L(S),K=l(P),O=[T(K),T(F)];if(M!=null&&M!==!1){let be=M===!0?A(t.BYTES):M;O.push(oe("extraEntropy",be))}let J=It(...O),te=F;function we(be){let ve=_(be);if(!f(ve))return;let _e=a(ve),He=c.BASE.multiply(ve).toAffine(),Ne=i(He.x);if(Ne===Rt)return;let lt=i(_e*i(te+Ne*K));if(lt===Rt)return;let yt=(He.x===Ne?0:2)|Number(He.y&xe),Mn=lt;return B&&m(lt)&&(Mn=p(lt),yt^=1),new h(Ne,Mn,yt)}return{seed:J,k2sig:we}}let re={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function V(S,P,v=re){let{seed:b,k2sig:A}=k(S,P,v),B=e;return Sc(B.hash.outputLen,B.nByteLength,B.hmac)(b,A)}c.BASE._setWindowSize(8);function he(S,P,v,b=W){let A=S;P=oe("msgHash",P),v=oe("publicKey",v);let{lowS:B,prehash:R,format:M}=b;if(wh(b),"strict"in b)throw new Error("options.strict was renamed to lowS");if(M!==void 0&&M!=="compact"&&M!=="der")throw new Error("format must be compact or der");let F=typeof A=="string"||zt(A),K=!F&&!M&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!F&&!K)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let O,J;try{if(K&&(O=new h(A.r,A.s)),F){try{M!=="compact"&&(O=h.fromDER(A))}catch(yt){if(!(yt instanceof Dt.Err))throw yt}!O&&M!=="der"&&(O=h.fromCompact(A))}J=c.fromHex(v)}catch{return!1}if(!O||B&&O.hasHighS())return!1;R&&(P=e.hash(P));let{r:te,s:we}=O,be=L(P),ve=a(we),_e=i(be*ve),He=i(te*ve),Ne=c.BASE.multiplyAndAddUnsafe(J,_e,He)?.toAffine();return Ne?i(Ne.x)===te:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:E,sign:V,verify:he,ProjectivePoint:c,Signature:h,utils:w}}function ky(r){return{hash:r,hmac:(e,...t)=>Cl(r,e,yc(...t)),randomBytes:Qr}}function vh(r,e){let t=n=>xh({...r,...ky(n)});return{...t(e),create:t}}var Sh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Eh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ty=BigInt(1),Bl=BigInt(2),Ah=(r,e)=>(r+e/Bl)/e;function Ly(r){let e=Sh,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=se(u,t,e)*u%e,d=se(f,t,e)*u%e,m=se(d,Bl,e)*l%e,p=se(m,s,e)*m%e,g=se(p,o,e)*p%e,h=se(g,a,e)*g%e,w=se(h,c,e)*h%e,x=se(w,a,e)*g%e,y=se(x,t,e)*u%e,E=se(y,i,e)*p%e,_=se(E,n,e)*l%e,L=se(_,Bl,e);if(!kl.eql(kl.sqr(L),r))throw new Error("Cannot find square root");return L}var kl=jt(Sh,void 0,void 0,{sqrt:Ly}),Xe=vh({a:BigInt(0),b:BigInt(7),Fp:kl,n:Eh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Eh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ty*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,i=BigInt("0x100000000000000000000000000000000"),a=Ah(o*r,e),c=Ah(-n*r,e),l=Q(r-a*t-c*s,e),u=Q(-a*n-c*o,e),f=l>i,d=u>i;if(f&&(l=e-l),d&&(u=e-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},sn),l2=BigInt(0);var u2=Xe.ProjectivePoint;function Fe(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Ce(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}function Tl(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function _h(r,e){let t=rn.digest(e instanceof Uint8Array?e:e.subarray());if(Tl(t))return t.then(({digest:n})=>Xe.sign(n,r).toDERRawBytes()).catch(n=>{throw new cs(String(n))});try{return Xe.sign(t.digest,r).toDERRawBytes()}catch(n){throw new cs(String(n))}}function Ch(r,e,t){let n=rn.digest(t instanceof Uint8Array?t:t.subarray());if(Tl(n))return n.then(({digest:s})=>Xe.verify(e,s,r)).catch(s=>{throw new ls(String(s))});try{return Xe.verify(e,n.digest,r)}catch(s){throw new ls(String(s))}}var ds=class{type="secp256k1";raw;_key;constructor(e){this._key=kh(e),this.raw=Ih(this._key)}toMultihash(){return At.digest(ft(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return Ch(this._key,t,e)}},mi=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Bh(e),this.publicKey=new ds(t??Th(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return _h(this.raw,e)}};function Ll(r){return new ds(r)}async function Lh(){let r=Py();return new mi(r)}function Ih(r){return Xe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Bh(r){try{return Xe.getPublicKey(r,!0),r}catch(e){throw new On(String(e))}}function kh(r){try{return Xe.ProjectivePoint.fromHex(r),r}catch(e){throw new Hr(String(e))}}function Th(r){try{return Xe.getPublicKey(r,!0)}catch(e){throw new On(String(e))}}function Py(){return Xe.utils.randomPrivateKey()}async function Ph(r,e){if(r==="Ed25519")return ad();if(r==="secp256k1")return Lh();if(r==="RSA")return _l(e??2048);throw new Ht}function hn(r){let{Type:e,Data:t}=dt.decode(r),n=t??new Uint8Array;switch(e){case ge.RSA:return Sl(n);case ge.Ed25519:return Rc(n);case ge.secp256k1:return Ll(n);default:throw new Ht}}function Nh(r){let{Type:e,Data:t}=dt.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return Rc(n);case ge.secp256k1:return Ll(n);default:throw new Ht}}function ft(r){return dt.encode({Type:ge[r.type],Data:r.raw})}var Dh=Symbol.for("nodejs.util.inspect.custom"),Ny=114,hs=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[zs]=!0;toString(){return this.string==null&&(this.string=X.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(Ny,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ce(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ce(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Dh](){return`PeerId(${this.toString()})`}},ps=class extends hs{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ms=class extends hs{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},gs=class extends hs{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Dy=2336,ys=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=At.digest(N(this.url))}[Dh](){return`PeerId(${this.url})`}[zs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(Dy,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};var Ry=114,Rh=2336;function gt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=et(X.decode(`z${r}`));else{if(e==null)throw new D('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=et(e.decode(r))}return pn(t)}function Pl(r){if(r.type==="Ed25519")return new ms({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new gs({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ps({multihash:r.toCID().multihash,publicKey:r});throw new Ht}function Mh(r){return Pl(r.publicKey)}function pn(r){if(Oy(r))return new ps({multihash:r});if(My(r))try{let e=Nh(r);if(e.type==="Ed25519")return new ms({multihash:r,publicKey:e});if(e.type==="secp256k1")return new gs({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new ys(new URL(t))}throw new Xs("Supplied PeerID Multihash is invalid")}function gi(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ry&&r.code!==Rh)throw new Zs("Supplied PeerID CID is invalid");if(r.code===Rh){let e=z(r.multihash.digest);return new ys(new URL(e))}return pn(r.multihash)}function My(r){return r.code===At.code}function Oy(r){return r.code===rn.code}var fe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Dl=Vr(Uh(),1);var bs=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Rl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Fh=r=>globalThis.DOMException===void 0?new Rl(r):new DOMException(r),Vh=r=>{let e=r.reason===void 0?Fh("This operation was aborted."):r.reason;return e instanceof Error?e:Fh(e)};function xs(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:m}=e;m.aborted&&f(Vh(m)),a=()=>{f(Vh(m))},m.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new bs;i=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?u():s instanceof Error?f(s):(d.message=s??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(m){f(m)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},l}function Ml(r,e,t){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;t(r[i],e)<=0?(n=++i,s-=o+1):s=o}return n}var vs=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let s=Ml(this.#e,n,(o,i)=>i.priority-o.priority);this.#e.splice(s,0,n)}setPriority(e,t){let n=this.#e.findIndex(o=>o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[s]=this.#e.splice(n,1);this.enqueue(s.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var tr=class extends Dl.default{#e;#t;#o=0;#a;#c;#p=0;#n;#l;#r;#m;#s=0;#u;#i;#g;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:vs,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#x(){return this.#t||this.#o<this.#a}get#v(){return this.#s<this.#u}#E(){this.#s--,this.#f(),this.emit("next")}#A(){this.#w(),this.#y(),this.#l=void 0}get#S(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#o=this.#e?this.#s:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#A()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#S;if(this.#x&&this.#v){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#o===0&&this.#s===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#o=this.#e?this.#s:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#d()}async#_(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#r.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#b++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,s)=>{this.#r.enqueue(async()=>{this.#s++,this.#o++;try{t.signal?.throwIfAborted();let o=e({signal:t.signal});t.timeout&&(o=xs(Promise.resolve(o),{milliseconds:t.timeout})),t.signal&&(o=Promise.race([o,this.#_(t.signal)]));let i=await o;n(i),this.emit("completed",i)}catch(o){if(o instanceof bs&&!t.throwOnTimeout){n();return}s(o),this.emit("error",o)}finally{this.#E()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#d(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#h("next",()=>this.#r.size<e)}async onIdle(){this.#s===0&&this.#r.size===0||await this.#h("idle")}async#h(e,t){return new Promise(n=>{let s=()=>{t&&!t()||(this.off(e,s),n())};this.on(e,s)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#i}};function wi(r){let e=[je.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Ol=60;function bi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:je[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:je[e.type],TTL:e.TTL??e.ttl??Ol,data:e.data instanceof Uint8Array?z(e.data):e.data}))}}var Vy=4;function Ul(r,e={}){let t=new tr({concurrency:e.queryConcurrency??Vy});return async(n,s={})=>{let o=new URLSearchParams;o.set("name",n),wi(s.types).forEach(a=>{o.append("type",je[a])}),s.onProgress?.(new fe("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${o}`,{headers:{accept:"application/dns-json"},signal:s?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=bi(await a.json());return s.onProgress?.(new fe("dns:response",{detail:c})),c},{signal:s.signal});if(i==null)throw new Error("No DNS response received");return i}}function Hh(){return[Ul("https://cloudflare-dns.com/dns-query"),Ul("https://dns.google/resolve")]}var qh=Vr($h(),1);var Fl=class{lru;constructor(e){this.lru=(0,qh.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return bi({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:je[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??Ol)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function zh(r){return new Fl(r)}var Hy=1e3,xi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=zh(e.cacheSize??Hy),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Hh())}async query(e,t={}){let n=wi(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new fe("dns:cache",{detail:s})),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new fe("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(je||(je={}));function Gh(r={}){return new xi(r)}var vi=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let 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(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Wh=45,Ky=15,mn=new vi;function Ei(r){if(!(r.length>Ky))return mn.new(r).parseWith(()=>mn.readIPv4Addr())}function Ai(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Wh))return mn.new(r).parseWith(()=>mn.readIPv6Addr())}function xr(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Wh)return;let t=mn.new(r).parseWith(()=>mn.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function jh(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function Zh(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function Vl(r){switch(r.length){case vr:return r.join(".");case Er:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Xh(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function Yh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var vr=4,Er=16,XA=parseInt("0xFFFF",16),$y=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Es(r,e){e.length===Er&&r.length===vr&&jh(e,0,11)&&(e=e.slice(12)),e.length===vr&&r.length===Er&&Zh(r,$y,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function Jh(r,e){if(typeof e=="string"&&(e=xr(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Hl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=vr,s=Ei(e);if(s==null&&(n=Er,s=Ai(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Kl(o,8*n);return{network:Es(s,i),mask:i}}function Kl(r,e){if(e!==8*vr&&e!==8*Er)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var gn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Hl(e));else{let n=xr(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=xr(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=Kl(s,8*n.length);this.network=Es(n,this.mask)}}contains(e){return Jh({network:this.network,mask:this.mask},e)}toString(){let e=Xh(this.mask),t=e!==-1?String(e):Yh(this.mask);return Vl(this.network)+"/"+t}};function at(r){return!!Ei(r)}function yn(r){return!!Ai(r)}function Si(r){return!!xr(r)}var Qh=at,qy=yn,$l=function(r){let e=0;if(r=r.toString().trim(),Qh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(qy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=Qh(t[n]),i;o&&(i=$l(t[n]),t[n]=z(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){let o=parseInt(t[n],16);s[e++]=o>>8&255,s[e++]=o&255}return s}throw new Error("invalid ip address")},ep=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let s=[];for(let o=0;o<t;o++)s.push(r[e+o]);return s.join(".")}if(t===16){let s=[];for(let o=0;o<t;o+=2)s.push(n.getUint16(e+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var wn={},ql={},Gy=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"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,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Gy.forEach(r=>{let e=Wy(...r);ql[e.code]=e,wn[e.name]=e});function Wy(r,e,t,n,s){return{code:r,size:e,name:t,resolvable:!!n,path:!!s}}function G(r){if(typeof r=="number"){if(ql[r]!=null)return ql[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(wn[r]!=null)return wn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var jy=G("ip4"),Zy=G("ip6"),Xy=G("ipcidr");function jl(r,e){switch(G(r).code){case 4:case 41:return Jy(e);case 42:return Wl(e);case 43:return z(e,"base10");case 6:case 273:case 33:case 132:return np(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Wl(e);case 421:return rw(e);case 444:return rp(e);case 445:return rp(e);case 466:return tw(e);case 481:return globalThis.encodeURIComponent(Wl(e));default:return z(e,"base16")}}function Zl(r,e){switch(G(r).code){case 4:return tp(e);case 41:return tp(e);case 42:return Gl(e);case 43:return N(e,"base10");case 6:case 273:case 33:case 132:return Yl(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gl(e);case 421:return Qy(e);case 444:return nw(e);case 445:return sw(e);case 466:return ew(e);case 481:return Gl(globalThis.decodeURIComponent(e));default:return N(e,"base16")}}function Xl(r){let e,t;if(r.stringTuples().forEach(([n,s])=>{(n===jy.code||n===Zy.code)&&(t=s),n===Xy.code&&(e=s)}),e==null||t==null)throw new Error("Invalid multiaddr");return new gn(t,e)}var zl=Object.values(Xn).map(r=>r.decoder),Yy=function(){let r=zl[0].or(zl[1]);return zl.slice(2).forEach(e=>r=r.or(e)),r}();function tp(r){if(!Si(r))throw new Error("invalid ip address");return $l(r)}function Jy(r){let e=ep(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Si(e))throw new Error("invalid ip address");return e}function Yl(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function np(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Gl(r){let e=N(r),t=Uint8Array.from(Be(e.length));return Fe([t,e],t.length+e.length)}function Wl(r){let e=st(r);if(r=r.slice(de(e)),r.length!==e)throw new Error("inconsistent lengths");return z(r)}function Qy(r){let e;r[0]==="Q"||r[0]==="1"?e=et(X.decode(`z${r}`)).bytes:e=pe.parse(r).multihash.bytes;let t=Uint8Array.from(Be(e.length));return Fe([t,e],t.length+e.length)}function ew(r){let e=Yy.decode(r),t=Uint8Array.from(Be(e.length));return Fe([t,e],t.length+e.length)}function tw(r){let e=st(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+z(t,"base64url")}function rw(r){let e=st(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return z(t,"base58btc")}function nw(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Ge.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Yl(n);return Fe([t,s],t.length+s.length)}function sw(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ge.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Yl(n);return Fe([t,s],t.length+s.length)}function rp(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=z(e,"base32"),s=np(t);return`${n}:${s}`}function sp(r){r=Jl(r);let e=[],t=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<s.length;o++){let i=s[o],a=G(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(o++,o>=s.length)throw new _i("invalid address: "+r);if(a.path===!0){n=Jl(s.slice(o).join("/")),e.push([a.code,Zl(a.code,n)]),t.push([a.code,n]);break}let c=Zl(a.code,s[o]);e.push([a.code,c]),t.push([a.code,jl(a.code,c)])}return{string:op(t),bytes:Ci(e),tuples:e,stringTuples:t,path:n}}function Ql(r){let e=[],t=[],n=null,s=0;for(;s<r.length;){let o=st(r,s),i=de(o),a=G(o),c=ow(a,r.slice(s+i));if(c===0){e.push([o]),t.push([o]),s+=i;continue}let l=r.slice(s+i,s+i+c);if(s+=c+i,s>r.length)throw new _i("Invalid address Uint8Array: "+z(r,"base16"));e.push([o,l]);let u=jl(o,l);if(t.push([o,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:op(t),tuples:e,stringTuples:t,path:n}}function op(r){let e=[];return r.map(t=>{let n=G(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Jl(e.join("/"))}function Ci(r){return Fe(r.map(e=>{let t=G(e[0]),n=Uint8Array.from(Be(t.code));return e.length>1&&e[1]!=null&&(n=Fe([n,e[1]])),n}))}function ow(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=st(e instanceof Uint8Array?e:Uint8Array.from(e));return t+de(t)}}function Jl(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}var _i=class extends Error{static name="ParseError";name="ParseError";constructor(e){super(`Error parsing address: ${e}`)}};var iw=Symbol.for("nodejs.util.inspect.custom"),tu=Symbol.for("@multiformats/js-multiaddr/multiaddr"),aw=[G("dns").code,G("dns4").code,G("dns6").code,G("dnsaddr").code],eu=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},Ii=class r{bytes;#e;#t;#o;#a;[tu]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Ql(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=sp(e)}else if(rr(e))t=Ql(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#o=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="",i=G("tcp"),a=G("udp"),c=G("ip4"),l=G("ip6"),u=G("dns6"),f=G("ip6zone");for(let[m,p]of this.stringTuples())m===f.code&&(o=`%${p??""}`),aw.includes(m)&&(t=i.name==="tcp"?"tcp":"udp",s=443,n=`${p??""}${o}`,e=m===u.code?6:4),(m===i.code||m===a.code)&&(t=G(m).name==="tcp"?"tcp":"udp",s=parseInt(p??"")),(m===c.code||m===l.code)&&(t=G(m).name==="tcp"?"tcp":"udp",n=`${p??""}${o}`,e=m===l.code?6:4);if(e==null||t==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:s}}protos(){return this.#t.map(([e])=>Object.assign({},G(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>G(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#o.map(([e,t])=>t==null?[e]:[e,t])}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Ci(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,s])=>{n===wn.p2p.code&&e.push([n,s]),n===wn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?z(X.decode(`z${n}`),"base58btc"):z(pe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ce(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=bn.get(t.name);if(n==null)throw new eu(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>j(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new 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(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[iw](){return`Multiaddr(${this.#e})`}};var bn=new Map;function rr(r){return!!r?.[tu]}function j(r){return new Ii(r)}var cw=32,{code:lw}=G("dnsaddr"),ru=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},Ar=async function(e,t={}){let n=t.maxRecursiveDepth??cw;if(n===0)throw new ru("Max recursive depth reached");let[,s]=e.stringTuples().find(([l])=>l===lw)??[],i=await(t?.dns??Gh()).query(`_dnsaddr.${s}`,{signal:t?.signal,types:[je.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let u=l.data.replace(/["']/g,"").trim().split("=")[1];if(u==null||a!=null&&!u.includes(a))continue;let f=j(u);if(u.startsWith("/dnsaddr")){let d=await f.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(m=>m.toString()))}else c.push(f.toString())}return c};var pp=Vr(hp(),1),Ti=pp.default;var mw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ar}},transportManager:{faultTolerance:cr.FATAL_ALL}};async function mp(r){let e=Ti(mw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new D("Private network is enforced, but no protector was provided");return e}function gw(r,e){try{if(typeof r=="string"&&r.length>0)return yw(r);if(typeof r=="number"&&isFinite(r))return e?.long?bw(r):ww(r);throw new Error("Value is not a string or number.")}catch(t){let n=xw(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function yw(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Pi=gw;function ww(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function bw(r){let e=Math.abs(r);return e>=864e5?Li(r,e,864e5,"day"):e>=36e5?Li(r,e,36e5,"hour"):e>=6e4?Li(r,e,6e4,"minute"):e>=1e3?Li(r,e,1e3,"second"):`${r} ms`}function Li(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}function xw(r){return typeof r=="object"&&r!==null&&"message"in r}function su(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=Pi,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,m,p;function g(...h){if(!g.enabled)return;let w=g,x=Number(new Date),y=x-(f||x);w.diff=y,w.prev=f,w.curr=x,f=x,h[0]=t.coerce(h[0]),typeof h[0]!="string"&&h.unshift("%O");let E=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(L,I)=>{if(L==="%%")return"%";E++;let T=t.formatters[I];if(typeof T=="function"){let k=h[E];L=T.call(w,k),h.splice(E,1),E--}return L}),t.formatArgs.call(w,h),(w.log||t.log).apply(w,h)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(m!==t.namespaces&&(m=t.namespaces,p=t.enabled(u)),p),set:h=>{d=h}}),typeof t.init=="function"&&t.init(g),g}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),m=d.length;for(f=0;f<m;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Ni=Iw(),vw=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Ew(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Aw(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Pi(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}var Sw=console.debug??console.log??(()=>{});function _w(r){try{r?Ni?.setItem("debug",r):Ni?.removeItem("debug")}catch{}}function Cw(){let r;try{r=Ni?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Iw(){try{return localStorage}catch{}}function Bw(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var gp=su({formatArgs:Aw,save:_w,load:Cw,useColors:Ew,setupFormatters:Bw,colors:vw,storage:Ni,log:Sw});var ze=gp;ze.formatters.b=r=>r==null?"undefined":X.baseEncode(r);ze.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);ze.formatters.m=r=>r==null?"undefined":Yc.baseEncode(r);ze.formatters.p=r=>r==null?"undefined":r.toString();ze.formatters.c=r=>r==null?"undefined":r.toString();ze.formatters.k=r=>r==null?"undefined":r.toString();ze.formatters.a=r=>r==null?"undefined":r.toString();ze.formatters.e=r=>r==null?"undefined":yp(r.stack)??yp(r.message)??r.toString();function kw(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Di(){return{forComponent(r){return Tw(r)}}}function Tw(r){let e=kw(`${r}:trace`);return ze.enabled(`${r}:trace`)&&ze.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=ze(`${r}:trace`)),Object.assign(ze(r),{error:ze(`${r}:error`),trace:e})}function yp(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Sr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function Ri(r){let e=et(X.decode(`z${r}`));return pn(e)}var Mt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Sr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Sr(this.map.values(),e=>e.key)}values(){return Sr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var _r=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Sr(this.set.entries(),e=>{let t=Ri(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Ri(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Sr(this.set.values(),e=>Ri(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var bp=Symbol.for("@achingbrain/uint8arraylist");function wp(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Mi(r){return!!r?.[bp]}var ye=class r{bufs;length;[bp]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Mi(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Mi(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=wp(this.bufs,e);return t.buf[t.index]}set(e,t){let n=wp(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Mi(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Fe(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Fe(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,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(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Mi(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=le(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=le(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=le(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=le(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=le(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=le(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=le(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=le(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ce(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var ou={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},xp={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},vp=new globalThis.TextEncoder;function Lw(r,e){let t=ou[e],n=xp[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function Pw(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ou[e],s=xp[e],o=r;for(;o.length>0;){let i=vp.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function iu(r,{size:e=32,utf8Buffer:t}={}){if(!ou[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Pw(r,e,t);r=vp.encode(r)}return Lw(r,e)}var As={hash:r=>Number(iu(r,{size:32})),hashV:(r,e)=>Nw(As.hash(r,e))};function Nw(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),N(e,"base16")}var au=64,ct=class{fp;h;seed;constructor(e,t,n,s=2){if(s>au)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=le(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ce(this.fp,e.fp):!1}};function Cr(r,e){return Math.floor(Math.random()*(e-r))+r}var Ir=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");let t=Cr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Dw=500,Ss=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??As,this.seed=e.seed??Cr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=N(e));let t=new ct(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ir(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Ir(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Cr(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize));for(let a=0;a<Dw;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=N(e));let t=new ct(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=N(e));let t=new ct(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Rw={1:.5,2:.84,4:.95,8:.98};function Mw(r=.001){return r>.002?2:r>1e-5?4:8}function Ep(r,e=.001){let t=Mw(e),n=Rw[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),au);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Oi=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??As,this.seed=e.seed??Cr(0,Math.pow(2,10)),this.filterSeries=[new Ss({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=N(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Ss({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=N(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=N(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)}};function _s(r,e=.001,t){return new Oi({...Ep(r,e),...t??{}})}var Cs;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:le(0),payloadType:le(0),payload:le(0),signature:le(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Cs||(Cs={}));var Ui=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var En=class r{static createFromProtobuf=async e=>{let t=Cs.decode(e),n=hn(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t==null)throw new Error("Missing private key");let n=e.domain,s=e.codec,o=e.marshal(),i=Ap(n,s,o),a=await t.sign(i.subarray());return new r({publicKey:t.publicKey,payloadType:s,payload:o,signature:a})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new Ui("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Cs.encode({publicKey:ft(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ce(this.marshal(),e.marshal())}async validate(e){let t=Ap(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},Ap=(r,e,t)=>{let n=N(r),s=Be(n.byteLength),o=Be(e.length),i=Be(t.length);return new ye(s,n,o,e,i,t)};function Sp(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var _p="libp2p-peer-record",Cp=Uint8Array.from([3,1]);var Is;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:le(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),s),n.encode=o=>Me(o,n.codec()),n.decode=(o,i)=>Re(o,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Oe((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s,o={})=>{let i={peerId:le(0),seq:0n,addresses:[]},a=s==null?n.len:n.pos+s;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new wr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Me(n,r.codec()),r.decode=(n,s)=>Re(n,r.codec(),s)})(Is||(Is={}));var Br=class r{static createFromProtobuf=e=>{let t=Is.decode(e),n=pn(et(t.peerId)),s=(t.addresses??[]).map(i=>j(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=_p;static CODEC=Cp;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Is.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 r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Sp(this.multiaddrs,e.multiaddrs))}};function Ow(r){return r[Symbol.asyncIterator]!=null}function Uw(r){if(Ow(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Bs=Uw;var nr={},An=r=>{r.addEventListener("message",e=>{An.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{An.dispatchEvent("message",r,e)})};An.addEventListener=(r,e)=>{nr[r]==null&&(nr[r]=[]),nr[r].push(e)};An.removeEventListener=(r,e)=>{nr[r]!=null&&(nr[r]=nr[r].filter(t=>t===e))};An.dispatchEvent=function(r,e,t){nr[r]!=null&&nr[r].forEach(n=>n(e,t))};var cu=An;var lu="lock:worker:request-read",uu="lock:worker:release-read",fu="lock:master:grant-read",du="lock:worker:request-write",hu="lock:worker:release-write",pu="lock:master:grant-write";var Ip=(r=21)=>Math.random().toString().substring(2);var Bp=(r,e,t,n,s)=>(o,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{o.postMessage({type:s,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u?.data==null)return;let f={type:u.data.type,name:u.data.name,identifier:u.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",l),c())};o.addEventListener("message",l)})}}}))},kp=(r,e,t,n)=>async()=>{let s=Ip();return globalThis.postMessage({type:e,identifier:s,name:r}),new Promise(o=>{let i=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===s&&(globalThis.removeEventListener("message",i),o(()=>{globalThis.postMessage({type:n,identifier:s,name:r})}))};globalThis.addEventListener("message",i)})},Fw={singleProcess:!1},Tp=r=>{if(r=Object.assign({},Fw,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return cu.addEventListener("message",Bp(t,"requestReadLock",lu,uu,fu)),cu.addEventListener("message",Bp(t,"requestWriteLock",du,hu,pu)),t}return{isWorker:!0,readLock:t=>kp(t,lu,fu,uu),writeLock:t=>kp(t,du,pu,hu)}};var kr={},sr;async function mu(r,e){let t,n=new Promise(s=>{t=s});return r.add(async()=>xs((async()=>{await new Promise(s=>{t(()=>{s()})})})(),{milliseconds:e.timeout})),n}var Vw=(r,e)=>{if(sr.isWorker===!0)return{readLock:sr.readLock(r,e),writeLock:sr.writeLock(r,e)};let t=new tr({concurrency:1}),n;return{async readLock(){if(n!=null)return mu(n,e);n=new tr({concurrency:e.concurrency,autoStart:!1});let s=n,o=mu(n,e);return t.add(async()=>{s.start(),await s.onIdle().then(()=>{n===s&&(n=null)})}),o},async writeLock(){return n=null,mu(t,e)}}},Hw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function gu(r){let e=Object.assign({},Hw,r);return sr==null&&(sr=Tp(e),sr.isWorker!==!0&&(sr.addEventListener("requestReadLock",t=>{kr[t.data.name]!=null&&kr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),sr.addEventListener("requestWriteLock",async t=>{kr[t.data.name]!=null&&kr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),kr[e.name]==null&&(kr[e.name]=Vw(e.name,e)),kr[e.name]}var Sn;(function(r){let e;(function(s){let o;s.codec=()=>(o==null&&(o=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:le(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),o),s.encode=i=>Me(i,s.codec()),s.decode=(i,a)=>Re(i,s.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(s){let o;s.codec=()=>(o==null&&(o=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Vi.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Vi.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),o),s.encode=i=>Me(i,s.codec()),s.decode=(i,a)=>Re(i,s.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Oe((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.addresses!=null)for(let a of s.addresses)o.uint32(10),Fi.codec().encode(a,o);if(s.protocols!=null)for(let a of s.protocols)o.uint32(18),o.string(a);if(s.publicKey!=null&&(o.uint32(34),o.bytes(s.publicKey)),s.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(s.peerRecordEnvelope)),s.metadata!=null&&s.metadata.size!==0)for(let[a,c]of s.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(s.tags!=null&&s.tags.size!==0)for(let[a,c]of s.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new wr('Decode error - map field "addresses" had too many elements');a.addresses.push(Fi.codec().decode(s,s.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new wr('Decode error - map field "protocols" had too many elements');a.protocols.push(s.string());break}case 4:{a.publicKey=s.bytes();break}case 5:{a.peerRecordEnvelope=s.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Qn('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(s,s.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Qn('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(s,s.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>Me(s,r.codec()),r.decode=(s,o)=>Re(s,r.codec(),o)})(Sn||(Sn={}));var Fi;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={multiaddr:le(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Fi||(Fi={}));var Vi;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Vi||(Vi={}));function _n(r,e){let t=Sn.decode(e);if(t.publicKey!=null&&r.publicKey==null){let o=hn(t.publicKey);r=Pl(o)}let n=new Map,s=BigInt(Date.now());for(let[o,i]of t.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:o,isCertified:i})=>({multiaddr:j(o),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ot="/",Lp=new TextEncoder().encode(Ot),Hi=Lp[0],Tr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=N(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Hi)throw new Error("Invalid key")}toString(e="utf8"){return z(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ot))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Lp),this._buf[0]!==Hi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Hi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Hi;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ot).slice(1)}type(){return Kw(this.baseNamespace())}name(){return $w(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ot)||(e+=Ot),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ot):new r(e.slice(0,-1).join(Ot))}child(e){return this.toString()===Ot?e:e.toString()===Ot?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...qw(e.map(t=>t.namespaces()))])}};function Kw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function $w(r){let e=r.split(":");return e[e.length-1]}function qw(r){return[].concat(...r)}var yu="/peers/";function Cn(r){if(!Gs(r)||r.type==null)throw new D("Invalid PeerId");let e=r.toCID().toString();return new Tr(`${yu}${e}`)}async function Pp(r,e,t){let n=new Map;for(let s of t){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=j(s.multiaddr)),!rr(s.multiaddr))throw new D("Multiaddr was invalid");if(!await e(r,s.multiaddr))continue;let o=s.isCertified??!1,i=s.multiaddr.toString(),a=n.get(i);a!=null?s.isCertified=a.isCertified||o:n.set(i,{multiaddr:s.multiaddr,isCertified:o})}return[...n.values()].sort((s,o)=>s.multiaddr.toString().localeCompare(o.multiaddr.toString())).map(({isCertified:s,multiaddr:o})=>({isCertified:s,multiaddr:o.bytes}))}async function $i(r,e,t,n){if(e==null)throw new D("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new D("publicKey bytes do not match peer id publicKey bytes");let s=n.existingPeer;if(s!=null&&!r.equals(s.id))throw new D("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ki(d,{validate:Np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ki(d,{validate:Dp,map:Rp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[m,p]of d)p==null?a.delete(m):a.set(m,p);a=Ki([...a.entries()],{validate:Np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),m=new Map(c);for(let[p,g]of d)g==null?m.delete(p):m.set(p,g);c=Ki([...m.entries()],{validate:Dp,map:Rp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=ft(s.id.publicKey):e.publicKey!=null?u=ft(e.publicKey):r.publicKey!=null&&(u=ft(r.publicKey));let f={addresses:await Pp(r,n.addressFilter??(async()=>!0),o),protocols:[...i.values()].sort((d,m)=>d.localeCompare(m)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return r.type!=="RSA"&&delete f.publicKey,f}function Ki(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function Np(r,e){if(typeof r!="string")throw new D("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new D("Metadata value must be a Uint8Array")}function Dp(r,e){if(typeof r!="string")throw new D("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new D("Tag value must be an integer");if(e.value<0||e.value>100)throw new D("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new D("Tag ttl must be an integer");if(e.ttl<0)throw new D("Tag ttl must be between greater than 0")}}function Rp(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function qi(r,e){let t=r.toString().split("/")[2],n=pe.parse(t,Ge),s=gi(n);return _n(s,e)}function zw(r){return r==null?{}:{prefix:yu,filters:(r.filters??[]).map(e=>({key:t,value:n})=>e(qi(t,n))),orders:(r.orders??[]).map(e=>(t,n)=>e(qi(t.key,t.value),qi(n.key,n.value)))}}var zi=class{peerId;datastore;lock;addressFilter;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=gu({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Cn(e))}async delete(e){if(this.peerId.equals(e))throw new D("Cannot delete self peer");await this.datastore.delete(Cn(e))}async load(e){let t=await this.datastore.get(Cn(e));return _n(e,t)}async save(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await $i(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,o,n,s)}async patch(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await $i(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,n,s)}async merge(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await $i(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,n,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(zw(e??{}))){let s=qi(t,n);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Cn(e)),n=_n(e,t);return{existingBuf:t,existingPeer:n}}catch(t){t.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",t)}return{}}async#t(e,t,n,s){let o=Sn.encode(t);return n!=null&&ce(o,n)?{peer:_n(e,o),previous:s,updated:!1}:(await this.datastore.put(Cn(e),o),{peer:_n(e,o),previous:s,updated:!0})}};var wu=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new zi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let s of this.store.all(t))e(s)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Bs(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let s=await this.store.save(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let s=await this.store.patch(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let s=await this.store.merge(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await En.openAndCertify(e,Br.DOMAIN),s=gi(n.publicKey.toCID());if(t?.equals(s)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,s),!1;let o=Br.createFromProtobuf(n.payload),i;try{i=await this.get(s)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await En.createFromProtobuf(i.peerRecordEnvelope),c=Br.createFromProtobuf(a.payload);if(c.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Mp(r,e={}){return new wu(r,e)}var Gi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function Gw(r){return r[Symbol.asyncIterator]!=null}function Ww(r){if(Gw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var bu=Ww;function jw(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Op=jw;function Zw(r){return r[Symbol.asyncIterator]!=null}function Xw(r,e){let t=0;if(Zw(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Op(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=e(s,t++);if(typeof i.then=="function")return async function*(){await i&&(yield s);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)}()}var Lr=Xw;function Yw(r){return r[Symbol.asyncIterator]!=null}function Jw(r,e){return Yw(r)?async function*(){yield*(await Bs(r)).sort(e)}():function*(){yield*Bs(r).sort(e)}()}var xu=Jw;function Qw(r){return r[Symbol.asyncIterator]!=null}function eb(r,e){return Qw(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var vu=eb;var Wi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:s}of e)await this.put(n,s,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await bu(this.putMany(e,n)),e=[],await bu(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let s=e.prefix;n=Lr(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Lr(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>xu(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=Lr(n,()=>s++>=o)}return e.limit!=null&&(n=vu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=Lr(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Lr(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>xu(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=Lr(n,()=>o++>=s)}return e.limit!=null&&(n=vu(n,e.limit)),n}};var ji=class extends Wi{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw new Gi;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Tr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Tr(e)}};function Up(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Vp=Vr(Fp(),1),tb=["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"],rb=tb.map(r=>new Vp.Netmask(r));function Eu(r){for(let e of rb)if(e.contains(r))return!0;return!1}function nb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function sb(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Eu(s)}function ob(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function ib(r){let e=r.split(":"),t=e[e.length-1];return Eu(t)}function ab(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function or(r){return at(r)?Eu(r):nb(r)?sb(r):ob(r)?ib(r):yn(r)?ab(r):void 0}var cb=r=>r.toString().split("/").slice(1),In=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),$=r=>({match:e=>In(t=>t===r).match(e),pattern:r}),Pr=()=>({match:r=>In(e=>typeof e=="string").match(r),pattern:"{string}"}),Ts=()=>({match:r=>In(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),ee=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{X.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ls=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Jc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Pe=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function ie(...r){function e(s){let o=cb(s);for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var Xi=q($("dns4"),Pr()),Yi=q($("dns6"),Pr()),Ji=q($("dnsaddr"),Pr()),Su=q($("dns"),Pr()),aI=ie(Xi,Z(ee())),cI=ie(Yi,Z(ee())),lI=ie(Ji,Z(ee())),uI=ie(Pe(Su,Ji,Xi,Yi),Z(ee())),Hp=q($("ip4"),In(at)),Kp=q($("ip6"),In(yn)),_u=Pe(Hp,Kp),Ut=Pe(_u,Su,Xi,Yi,Ji),fI=ie(Pe(_u,q(Pe(Su,Ji,Xi,Yi),Z(ee())))),Cu=ie(Hp),Iu=ie(Kp),dI=ie(_u),Bu=q(Ut,$("tcp"),Ts()),Ps=q(Ut,$("udp"),Ts()),Ns=ie(q(Bu,Z(ee()))),hI=ie(Ps),ku=q(Ps,$("quic"),Z(ee())),Qi=q(Ps,$("quic-v1"),Z(ee())),lb=Pe(ku,Qi),pI=ie(ku),$p=ie(Qi),Au=Pe(Ut,Bu,Ps,ku,Qi),qp=Pe(q(Au,$("ws"),Z(ee()))),Nr=ie(qp),zp=Pe(q(Au,$("wss"),Z(ee())),q(Au,$("tls"),Z(q($("sni"),Pr())),$("ws"),Z(ee()))),Ds=ie(zp),Gp=q(Ps,$("webrtc-direct"),Z(Ls()),Z(Ls()),Z(ee())),Tu=ie(Gp),Wp=q(Qi,$("webtransport"),Z(Ls()),Z(Ls()),Z(ee())),Lu=ie(Wp),Zi=Pe(qp,zp,q(Bu,Z(ee())),q(lb,Z(ee())),q(Ut,Z(ee())),Gp,Wp,ee()),mI=ie(Zi),ub=q(Zi,$("p2p-circuit"),ee()),Rs=ie(ub),fb=Pe(q(Zi,$("p2p-circuit"),$("webrtc"),Z(ee())),q(Zi,$("webrtc"),Z(ee())),q($("webrtc"),Z(ee()))),Pu=ie(fb),db=Pe(q(Ut,$("tcp"),Ts(),$("http"),Z(ee())),q(Ut,$("http"),Z(ee()))),gI=ie(db),hb=Pe(q(Ut,$("tcp"),Pe(q($("443"),$("http")),q(Ts(),$("https"))),Z(ee())),q(Ut,$("tls"),$("http"),Z(ee())),q(Ut,$("https"),Z(ee()))),yI=ie(hb),pb=Pe(q($("memory"),Pr(),Z(ee()))),wI=ie(pb);var jp=864e13;var mb=448,Nu=449,gb=53,yb=54,wb=55,bb=56,ea=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=or(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?jp-Date.now():0,lastVerified:s?jp-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[s,o]of this.mappings.entries())o.domain===t&&(this.log("removing %s to %s DNS mapping %e",s,o.domain,new Error("where")),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr.stringTuples(),i=o[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(o,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:j(`/${o.map(u=>[G(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===mb&&e[n+1]?.[0]!==Nu)return e.splice(n+1,0,[Nu,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),s=!1;for(let[o,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",o,i.domain),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){let n=this.findHost(e),s=!1;for(let[o,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",o,i.domain),s=s||i.verified,i.verified=!1,i.expires=Date.now()+t);return s}findHost(e){for(let t of e.stringTuples())if(t[0]===Nu||t[0]===gb||t[0]===yb||t[0]===wb||t[0]===bb)return t[1]}};var Du=4,Ru=41,Mu=6,xb=273,ta=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t[0][1])return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:at(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",s=t[1][0]===Mu?"tcp":"udp",o=parseInt(t[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===o&&u.protocol===s&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,o,s),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(e){let t=[];for(let{multiaddr:n}of e){let s=n.stringTuples(),o;if((s[0][0]===Du||s[0][0]===Ru)&&s[1][0]===Mu?o=`${s[0][1]}-${s[1][1]}-tcp`:(s[0][0]===Du||s[0][0]===Ru)&&s[1][0]===xb&&(o=`${s[0][1]}-${s[1][1]}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)s[0][0]=a.externalFamily===4?Du:Ru,s[0][1]=a.externalIp,s[1][1]=`${a.externalPort}`,t.push({multiaddr:j(`/${s.map(c=>[G(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let s=e.stringTuples()[0][1],o=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===s&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=e.stringTuples(),s=n[0][1]??"",o=n[1][0]===Mu?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===s&&u.externalPort===i&&u.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,s,i,o),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function Zp(r){try{let[[e,t]]=r.stringTuples();if(t==null)return!1;if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}catch{}return!1}function ra(r){try{let[[e]]=r.stringTuples();return e===4||e===41}catch{}return!1}function Dr(r){try{if(!ra(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:or(e)??!1}catch{}return!0}var vb={maxObservedAddresses:10},na=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??vb.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Dr(e)||Zp(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:j(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var Eb=[4,41,53,54,55,56];function Ou(r){try{let[[e]]=r.stringTuples();return Eb.includes(e)}catch{}return!1}var Ab={maxObservedAddresses:10},sa=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??Ab.maxObservedAddresses}get(e,t){if(Dr(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!Ou(e),expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){if(Ou(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var Xp=6e4,Yp={maxObservedAddresses:10,addressVerificationTTL:Xp*10,addressVerificationRetry:Xp*5},Sb=r=>r;function Uu(r,e){let t=r.getPeerId();return t!=null&&gt(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var oa=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new na(e,t),this.dnsMappings=new ea(e,t),this.ipMappings=new ta(e,t),this.transportAddresses=new sa(e,t),this.announceFilter=t.announceFilter??Sb,this.observedAddressFilter=_s(1024),this.addressVerificationTTL=t.addressVerificationTTL??Yp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Yp.addressVerificationRetry,this._updatePeerStoreAddresses=Up(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>j(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Uu(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Uu(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Uu(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=j(n);return s.protos().pop()?.path===!0||s.getPeerId()===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(e)}),e.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];return t=t.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL))),t=t.concat(this.getAppendAnnounceAddrs().map(n=>({multiaddr:n,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(j(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${at(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(j(`/ip${at(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||or(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),s=[o=>Nr.exactMatch(o)||Ds.exactMatch(o),o=>Ns.exactMatch(o),o=>$p.exactMatch(o)];for(let o of s){if(!o(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};var Jp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Jp||(Jp={}));var ia=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},aa=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Bn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ms=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},ca=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},la=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},ua=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Os=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},kn=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},fa=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},da=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Rr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Mr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ha=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var Fu=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Di())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>to(t)).map(async t=>{await t[e]?.()}))}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")}},Cb=["metrics","connectionProtector","dns"],Ib=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Qp(r={}){let e=new Fu(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!Ib.includes(s)){let i=e.components[s];if(i==null&&!Cb.includes(s))throw new ia(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function em(r){let e={};for(let t of Object.values(r.components))for(let n of Bb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of kb(t))if(e[n]!==!0)throw new aa(`Service "${Tb(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Bb(r){return Array.isArray(r?.[Fn])?r[Fn]:[]}function kb(r){return Array.isArray(r?.[ic])?r[ic]:[]}function Tb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Lb=4,Pb=41;function tm(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(Nr.matches(e))return!1;let t=e.stringTuples();return t[0][0]===Lb||t[0][0]===Pb?!!or(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var rm=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Nb=new WeakMap;function Db({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(rm());let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(rm())},u=()=>{s&&s.removeEventListener("abort",l)},f=new Promise((d,m)=>{i=()=>{u(),d(n)},a=m,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",l,{once:!0}),Nb.set(f,()=>{c(o),o=null,i()}),f}}var Rb=Db(),nm=Rb;var pa=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},ma=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ga=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Vu}async consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new pa("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await nm(a)}return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&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)}},Vu=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function ya(r){if(Gs(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:gt(t),r.forEach(n=>{if(!rr(n))throw new Vt("Invalid multiaddr");let s=n.getPeerId();if(s==null){if(e!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let o=gt(s);if(e?.equals(o)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Mb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function sm(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??Mb;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}var om="last-dial-failure",im="last-dial-success";var wa=100,ba=50;async function am(r,e){let t=!1;for(let s of bn.keys())if(t=r.protoNames().includes(s),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(s=>s.toString())),n}function Us(r){try{let e;if(typeof r=="string"?e=j(r):e=r,!e.protoNames().includes("ipcidr")){let n=e.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(n)}return Xl(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Ob={maxConnections:wa,allow:[]},xa=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Ob.maxConnections,this.allow=(t.allow??[]).map(n=>Us(n)),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)}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(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new Mt;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((u,f)=>u+f.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let s=this.sortConnections(e,n),o=Math.max(t-this.maxConnections,0),i=[];for(let a of s)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>l.contains(a.remoteAddr.nodeAddress().address))||i.push(a),i.length===o)break;await Promise.all(i.map(async a=>{await sm(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};function ue(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var va=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Tn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new va(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new va(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Hu=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ea(r={}){return Ub(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ub(r,e){e=e??{};let t=e.onEnd,n=new Tn,s,o,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{o=x=>{o=null,n.push(x);try{h(r(n))}catch(y){w(y)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},l=h=>o!=null?o(h):(n.push(h),s),u=h=>(n=new Tn,o!=null?o({error:h}):(n.push({error:h}),s)),f=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?s:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new Tn,d(),{done:!0}),p=h=>(d(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,y;w!=null&&(x=new Promise((E,_)=>{y=()=>{_(new Hu)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,x])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},t==null)return s;let g=s;return s={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(h){return g.end(h),t!=null&&(t(h),t=void 0),s},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},s}var Ku=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Ln(r,e,t,n){let s=new Ku(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{function a(){t?.removeEventListener("abort",u),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),o(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(s)};t?.addEventListener("abort",u),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Aa=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function ir(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Aa(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new Aa(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Sa=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ue(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Fb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var _a=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Fb(),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)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Je),this.cleanup())}async join(e={}){let t=new Sa(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await ir(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),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=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Nn=class extends xt{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(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),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ma;let n=new _a(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Je)}),this.clear()}async onEmpty(e){this.size!==0&&await Ln(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ln(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ln(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ea({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new Je("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ca=class extends Nn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Ft(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}function cm(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function $u(r){if(!ra(r))return!1;let{address:e}=r.nodeAddress();return cm(e)}function Vb(r,e){let t=Ns.exactMatch(r.multiaddr),n=Ns.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let s=Ds.exactMatch(r.multiaddr),o=Ds.exactMatch(e.multiaddr);if(s&&!o)return-1;if(!s&&o)return 1;let i=Nr.exactMatch(r.multiaddr),a=Nr.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Pu.exactMatch(r.multiaddr),l=Pu.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Tu.exactMatch(r.multiaddr),f=Tu.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Lu.exactMatch(r.multiaddr),m=Lu.exactMatch(e.multiaddr);return d&&!m?-1:!d&&m?1:0}function Hb(r,e){let t=$u(r.multiaddr),n=$u(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Kb(r,e){let t=Dr(r.multiaddr),n=Dr(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function $b(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function qb(r,e){let t=Rs.exactMatch(r.multiaddr),n=Rs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function lm(r){return r.sort(Vb).sort($b).sort(qb).sort(Kb).sort(Hb)}var Ia={maxParallelDials:ba,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Ar}},Ba=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Ia.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Ia.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Ia.dialTimeout,this.connections=t.connections??new Mt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(let[n,s]of Object.entries(t.resolvers??{}))bn.set(n,s);this.queue=new Ca({concurrency:t.maxParallelDials??Ia.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==Je.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:s}=ya(e),o=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:s.find(c=>c.equals(a.remoteAddr)));if(o?.status==="open")return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new fe("dial-queue:already-connected")),o;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of s)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of s)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new fe("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new qr("Dial queue is full");return this.log("creating dial target for %p",n,s.map(a=>a.toString())),t.onProgress?.(new fe("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new fe("dial-queue:start-dial"));let c=Ft([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:t.priority??Wu,multiaddrs:new Set(s.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,s=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||s.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);s.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let m of d){if(o.has(m.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",m.multiaddr,n);continue}u.push(m)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(m=>m.multiaddr.toString())),e?.onProgress?.(new fe("dial-queue:calculated-addresses",u));for(let m of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new qr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(m.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",m.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[im]:N(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}return p}catch(p){if(this.log.error("dial failed to %a",m.multiaddr,p),o.add(m.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[om]:N(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(t.aborted)throw new Js(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(f=>({multiaddr:j(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new qr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Os("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);s.push(...f.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:d})=>d.toString())),s.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let o=(await Promise.all(s.map(async f=>{let d=await am(f.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(m=>({multiaddr:m,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;o=o.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=o.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),m=a.get(d);if(m!=null){m.isCertified=m.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new kn("The dial request has no valid addresses");let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?lm(l):l.sort(this.addressSorter);if(u.length===0)throw new Os("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!Rs.matches(s.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ka=class extends Nn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var gm=Vr(pm(),1);var Gb=Object.prototype.toString,Wb=r=>Gb.call(r)==="[object Error]",jb=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"]);function ju(r){return r&&Wb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:jb.has(r.message):!1}var Zu=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},mm=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Xu(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let s=gm.default.operation(e),o=()=>{s.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),s.stop()};s.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Zu)throw c.originalError;if(c instanceof TypeError&&!ju(c))throw c;if(mm(c,a,e),await e.shouldRetry(c)||(s.stop(),n(c)),await e.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(l){mm(l,a,e),i(),n(l)}}})})}var Ta=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new ka({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);ym(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Xu(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(oc)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>ym(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function ym(r){for(let e of r.tags.keys())if(e.startsWith(oc))return!0;return!1}var Wu=50,Yu={maxConnections:wa,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},La=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Yu.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new Mt,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=(t.allow??[]).map(n=>Us(n)),this.deny=(t.deny??[]).map(n=>Us(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Yu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ga({points:t.inboundConnectionThreshold??Yu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new xa({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:t.allow?.map(n=>j(n))}),this.dialQueue=new Ba(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??ba,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Ar},connections:this.connections}),this.reconnectQueue=new Ta({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let s of n.streams){let o=`${s.direction} ${s.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await bf(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 xf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(s){this.log.error(s)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new bt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=ya(e);if(this.peerId.equals(n))throw new $r("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new fe("dial-queue:already-connected")),a}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Wu});if(s.status!=="open")throw new Kr("Remote closed connection during opening");let o=this.connections.get(s.remotePeer);o==null&&(o=[],this.connections.set(s.remotePeer,o));let i=!1;for(let a of o)if(a.id===s.id&&(i=!0),t.force!==!0&&a.id!==s.id&&a.remoteAddr.equals(s.remoteAddr))return s.abort(new Vt("Duplicate multiaddr connection")),a;return i||o.push(s),s}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await s.close(t)}catch(o){s.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(s=>s.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(s=>s.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()){let s=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(s,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s),!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(){let 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(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Dn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var Yb=1.2,Jb=2,Qb=2e3,Pa=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Dn(e.interval??5e3),this.failure=new Dn(e.interval??5e3),this.next=new Dn(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Jb,this.timeoutMultiplier=e.timeoutMultiplier??Yb,this.minTimeout=e.minTimeout??Qb,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),s=Ft([e.signal,n]);return s.start=Date.now(),s.timeout=t,s}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Ju=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ue(),this.haveNext=ue()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ue(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ue(),await ir(this.readNext.promise,t?.signal,t)}};function wm(){return new Ju}var Na=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Qu=class extends Error{code;constructor(e,t){super(e),this.code=t}},ef=class extends Qu{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Da(r,e){let t=wm();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let s=new ye;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new ef("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new ye:d}for(;s.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Na("unexpected end of input");s.append(f)}let u=s.sublist(0,i);return s.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield s:yield*s,yield*i}()}return r}}}var ex=1e4,tx="1.0.0",rx="ping",nx="ipfs",bm=32,sx=!0,Ra=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??nx}/${rx}/${tx}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??ex,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??sx,this.timeout=new Pa({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Fn]=["@libp2p/connection-monitor"];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{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=Da(s);t=Date.now(),await Promise.all([o.write(fn(bm),{signal:n}),o.read(bm,{signal:n})]),e.rtt=Date.now()-t,await o.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;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(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function ox(r){return r[Symbol.asyncIterator]!=null}function ix(...r){let e=[];for(let t of r)ox(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ea({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Fs=ix;var Ma=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()}),getAttributesFromYieldedValue:(n,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");let n=this,s=new _r;for await(let o of Fs(...n.routers.map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new bt;await Promise.all(this.routers.map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new bt;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Oa=globalThis.CustomEvent??Event;async function*tf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,s=new EventTarget,o=[],i=ue(),a=ue(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(i=ue(),await i.promise),u)break;let g={done:!1};o.push(g),p().then(h=>{g.done=!0,g.ok=!0,g.value=h,s.dispatchEvent(new Oa("task-complete"))},h=>{g.done=!0,g.err=h,s.dispatchEvent(new Oa("task-complete"))})}c=!0,s.dispatchEvent(new Oa("task-complete"))}catch(p){l=p,s.dispatchEvent(new Oa("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(p=>p.done)}function*d(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*m(){for(;f();)for(let p=0;p<o.length;p++)if(o[p].done){let g=o[p];if(o.splice(p,1),p--,g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=ue(),await a.promise),l!=null)throw l;if(n?yield*d():yield*m(),c&&o.length===0)break}}var Ua=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,key:z(n,"base36")}),getAttributesFromYieldedValue:(n,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Ms("No peer routers available");if(e.toString()===this.peerId.toString())throw new ca("Should not try to find self");let n=this,s=Fs(...this.routers.map(o=>async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),o;throw new js}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ms("No peer routers available");let n=this,s=_s(1024);for await(let o of tf(async function*(){let i=Fs(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};var Fa=class extends xt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),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}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ft([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await Ln(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Ft([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=fn(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await ir(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("random walk errored",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var rf=32,nf=64,Va=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new la(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new ua(`Handler already registered for protocol ${e}`);let s=Ti.bind({ignoreUndefined:!0})({maxInboundStreams:rf,maxOutboundStreams:nf},n);this.handlers.set(e,{handler:t,options:s}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new D("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let s of n.protocols){let o=this.topologies.get(s);if(o!=null)for(let i of o.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));for(let o of s){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,s=e.detail.peerId;for(let o of t){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),a.onConnect?.(s,n))}}};var sf=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function xm(r){let{name:e,metrics:t}=r,n;return t!=null?n=new sf({name:e,metrics:t}):n=new Map,n}var Ha=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=xm({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??cr.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new D("Transport must have a valid tag");if(this.transports.has(t))throw new D(`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(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let s=n.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new ha(`No transport available for address ${String(e)}`);return t?.onProgress?.(new fe("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new bt("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={unsupportedAddresses:new Set(e.map(o=>o.toString())),ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}},n=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Cu.matches(c)?t.ipv4.attempts++:Iu.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.unsupportedAddresses.delete(c.toString()),Cu.matches(c)&&t.ipv4.success++,Iu.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,f),f}))}}let s=await Promise.allSettled(n);if(!(s.length>0&&s.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===cr.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new kn(`No configured transport could listen on these addresses, please remove them from your config: ${[...t.unsupportedAddresses].join(", ")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let s=t.pop();s!=null&&n.push(s.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Se="/multistream/1.0.0";var Ka=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},$a=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},qa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Vs(r,e={}){let t=Da(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??st,s=e?.lengthEncoder??Be;return{read:async i=>{let a=-1,c=new ye;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Ka("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new qa("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new $a("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new ye(s(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ye(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var ax=N(`
6
+ `)}`:`${t} :`}};Ld=Qt;C.Constructed=Ld;Qt.NAME="CONSTRUCTED";var Po=class extends Te{fromBER(e,t,n){return t}toBER(e){return it}};Po.override="EndOfContentValueBlock";var Pd,No=class extends Ee{constructor(e={}){super(e,Po),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Pd=No;C.EndOfContent=Pd;No.NAME=rs;var Nd,an=class extends Ee{constructor(e={}){super(e,Te),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let s=new Uint8Array(n);s[0]=5,s[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Nd=an;C.Null=Nd;an.NAME="NULL";var Do=class extends Nt(Te){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=H.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let s=H.BufferSourceConverter.toUint8Array(e);return Pt(this,s,t,n)?(this.valueHexView=s.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,yl.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Do.NAME="BooleanValueBlock";var Dd,Ro=class extends Ee{constructor(e={}){super(e,Do),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Dd=Ro;C.Boolean=Dd;Ro.NAME="BOOLEAN";var Mo=class extends Nt(ht){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=ht.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let o=0;o<this.value.length;o++){let i=this.value[o].constructor.NAME;if(i===rs){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Id)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,n),this.blockLength=n;return s}toBER(e,t){return this.isConstructed?ht.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Mo.NAME="OctetStringValueBlock";var Rd,Oo=class r extends Ee{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Mo),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let o=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(o.byteLength){let i=fi(o,0,o.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Qt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${H.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return H.BufferSourceConverter.concat(e)}};Rd=Oo;C.OctetString=Rd;Oo.NAME=Id;var Uo=class extends Nt(ht){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let s=-1;if(this.isConstructed){if(s=ht.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let a of this.value){let c=a.constructor.NAME;if(c===rs){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Bd)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return s}let o=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=fi(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return ht.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return it;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Uo.NAME="BitStringValueBlock";var Md,cn=class extends Ee{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Uo),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Qt.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let s of t)e.push(s.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Md=cn;C.BitString=Md;cn.NAME=Bd;var Od;function by(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=o[i-f]+a[c-f]+t[0];break;default:l=o[i-f]+t[0]}switch(t[0]=l/10,!0){case f>=o.length:o=_o(new Uint8Array([l%10]),o);break;default:o[i-f]=l%10}}return t[0]>0&&(o=_o(t,o)),o}function Cd(r){if(r>=es.length)for(let e=es.length;e<=r;e++){let t=new Uint8Array([0]),n=es[e-1].slice(0);for(let s=n.length-1;s>=0;s--){let o=new Uint8Array([(n[s]<<1)+t[0]]);t[0]=o[0]/10,n[s]=o[0]%10}t[0]>0&&(n=_o(t,n)),es.push(n)}return es[r]}function xy(r,e){let t=0,n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=o[i-u]-a[c-u]-t,!0){case l<0:t=1,o[i-u]=l+10;break;default:t=0,o[i-u]=l}if(t>0)for(let f=i-c+1;f>=0;f--,u++)if(l=o[i-u]-t,l<0)t=1,o[i-u]=l+10;else{t=0,o[i-u]=l;break}return o.slice()}var ns=class extends Nt(Te){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=yl.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Ad(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,s=0){let o=this.fromBER(e,t,n);if(o===-1)return o;let i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):s!==0&&i.length<s&&(s-i.length>1&&(s=i.length+1),this.valueHexView=i.subarray(s-i.length)),o}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let s=super.fromBER(e,t,n);return s===-1||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,s,o=this.valueHexView,i="",a=!1;for(let c=o.byteLength-1;c>=0;c--){s=o[c];for(let l=0;l<8;l++){if((s&1)===1)switch(n){case e:t=xy(Cd(n),t),i="-";break;default:t=by(t,Cd(n))}n++,s>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=_d.charAt(t[c]));return a===!1&&(i+=_d.charAt(0)),i}};Od=ns;ns.NAME="IntegerValueBlock";Object.defineProperty(Od.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Ud,Ae=class r extends Ee{constructor(e={}){super(e,ns),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Co(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Co();let t=BigInt(e),n=new ts,s=t.toString(16).replace(/^-/,""),o=new Uint8Array(H.Convert.FromHex(s));if(t<0){let a=new Uint8Array(o.length+(o[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${H.Convert.ToHex(a)}`)+t,u=H.BufferSourceConverter.toUint8Array(H.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else o[0]&128&&n.write(new Uint8Array([0])),n.write(o);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Ud=Ae;C.Integer=Ud;Ae.NAME="INTEGER";var Fd,Fo=class extends Ae{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Fd=Fo;C.Enumerated=Fd;Fo.NAME="ENUMERATED";var ss=class extends Nt(Te){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let s=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Co();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let s=0;s<n.length;s++)n[s]=parseInt(t.slice(s*7,s*7+7),2)+(s+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",it;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n}toString(){let e="";if(this.isHexOnly)e=H.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};ss.NAME="sidBlock";var Vo=class extends Te{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new ss;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.value.length===0&&(o.isFirstSid=!0),this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let s=this.value[n].toBER(e);if(s.byteLength===0)return this.error=this.value[n].error,it;t.push(s)}return wl(t)}fromString(e){this.value=[];let t=0,n=0,s="",o=!1;do if(n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1,o){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(s,10);if(isNaN(c))return;i.valueDec=c+a,o=!1}else{let i=new ss;if(s>Number.MAX_SAFE_INTEGER){Co();let a=BigInt(s);i.valueBigInt=a}else if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,o=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),t?(s=`{${s}}`,this.value[n].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Vo.NAME="ObjectIdentifierValueBlock";var Vd,ln=class extends Ee{constructor(e={}){super(e,Vo),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Vd=ln;C.ObjectIdentifier=Vd;ln.NAME="OBJECT IDENTIFIER";var os=class extends Nt(kt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let s=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",it;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n.buffer}toString(){let e="";return this.isHexOnly?e=H.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};os.NAME="relativeSidBlock";var Ho=class extends Te{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new os;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e,t){let n=[];for(let s=0;s<this.value.length;s++){let o=this.value[s].toBER(e);if(o.byteLength===0)return this.error=this.value[s].error,it;n.push(o)}return wl(n)}fromString(e){this.value=[];let t=0,n=0,s="";do{n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1;let o=new os;if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return!0;this.value.push(o)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(s=`{${s}}`),e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Ho.NAME="RelativeObjectIdentifierValueBlock";var Hd,Ko=class extends Ee{constructor(e={}){super(e,Ho),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Hd=Ko;C.RelativeObjectIdentifier=Hd;Ko.NAME="RelativeObjectIdentifier";var Kd,Tt=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Kd=Tt;C.Sequence=Kd;Tt.NAME="SEQUENCE";var $d,$o=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};$d=$o;C.Set=$d;$o.NAME="SET";var qo=class extends Nt(Te){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=un}toJSON(){return{...super.toJSON(),value:this.value}}};qo.NAME="StringValueBlock";var zo=class extends qo{};zo.NAME="SimpleStringValueBlock";var Ue=class extends ko{constructor({...e}={}){super(e,zo)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,H.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);this.valueBlock.value=e}};Ue.NAME="SIMPLE STRING";var Go=class extends Ue{fromBuffer(e){this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=H.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=H.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Go.NAME="Utf8StringValueBlock";var qd,Lt=class extends Go{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};qd=Lt;C.Utf8String=qd;Lt.NAME="UTF8String";var Wo=class extends Ue{fromBuffer(e){this.valueBlock.value=H.Convert.ToUtf16String(e),this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf16String(e))}};Wo.NAME="BmpStringValueBlock";var zd,jo=class extends Wo{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};zd=jo;C.BmpString=zd;jo.NAME="BMPString";var Zo=class extends Ue{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let s=0;s<n.length;s+=4)n[s]=n[s+3],n[s+1]=n[s+2],n[s+2]=0,n[s+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let s=0;s<t;s++){let o=Jt(e.charCodeAt(s),8),i=new Uint8Array(o);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[s*4+c+a]=i[c]}this.valueBlock.value=e}};Zo.NAME="UniversalStringValueBlock";var Gd,Xo=class extends Zo{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Gd=Xo;C.UniversalString=Gd;Xo.NAME="UniversalString";var Wd,Yo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Wd=Yo;C.NumericString=Wd;Yo.NAME="NumericString";var jd,Jo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};jd=Jo;C.PrintableString=jd;Jo.NAME="PrintableString";var Zd,Qo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Zd=Qo;C.TeletexString=Zd;Qo.NAME="TeletexString";var Xd,ei=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Xd=ei;C.VideotexString=Xd;ei.NAME="VideotexString";var Yd,ti=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Yd=ti;C.IA5String=Yd;ti.NAME="IA5String";var Jd,ri=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Jd=ri;C.GraphicString=Jd;ri.NAME="GraphicString";var Qd,is=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Qd=is;C.VisibleString=Qd;is.NAME="VisibleString";var eh,ni=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};eh=ni;C.GeneralString=eh;ni.NAME="GeneralString";var th,si=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};th=si;C.CharacterString=th;si.NAME="CharacterString";var rh,as=class extends is{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let s=0;s<e.length;s++)this.valueBlock.valueHexView[s]=e.charCodeAt(s)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,H.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let s=parseInt(n[1],10);s>=50?this.year=1900+s:this.year=2e3+s,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=qe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=qe(this.month,2),t[2]=qe(this.day,2),t[3]=qe(this.hour,2),t[4]=qe(this.minute,2),t[5]=qe(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};rh=as;C.UTCTime=rh;as.NAME="UTCTime";var nh,oi=class extends as{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",s="",o=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),m="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(m=n.substring(d+1),n=n.substring(0,d),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(m.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*p,m.length===4){if(p=parseInt(m.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=f*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");o=f.valueOf(),s=n.substring(0,l)}else s=n;switch(!0){case s.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*o;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case s.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*o;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case s.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*o;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(s);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(qe(this.year,4)),t.push(qe(this.month,2)),t.push(qe(this.day,2)),t.push(qe(this.hour,2)),t.push(qe(this.minute,2)),t.push(qe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(qe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};nh=oi;C.GeneralizedTime=nh;oi.NAME="GeneralizedTime";var sh,ii=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};sh=ii;C.DATE=sh;ii.NAME="DATE";var oh,ai=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};oh=ai;C.TimeOfDay=oh;ai.NAME="TimeOfDay";var ih,ci=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};ih=ci;C.DateTime=ih;ci.NAME="DateTime";var ah,li=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};ah=li;C.Duration=ah;li.NAME="Duration";var ch,ui=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};ch=ui;C.TIME=ch;ui.NAME="TIME";function z(r,e="utf8"){let t=xo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function fn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return Qr(r)}var cs=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},ls=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},di=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var lh={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new di("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 e}};var er=lh;async function uh(r){let e=await er.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Ey(e);return{privateKey:t[0],publicKey:t[1]}}async function fh(r,e){let t=await er.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await er.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function dh(r,e,t){let n=await er.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return er.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Ey(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required");return Promise.all([er.get().subtle.exportKey("jwk",r.privateKey),er.get().subtle.exportKey("jwk",r.publicKey)])}function vl(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return N(r.n,"base64url").length*8}var dn=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=us.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return dh(this._key,t,e)}},fs=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=us.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return fh(this._key,e)}};var hi=8192,El=18;function hh(r){let{result:e}=xl(r),t=e.valueBlock.value;return{n:pt(t[1]),e:pt(t[2]),d:pt(t[3]),p:pt(t[4]),q:pt(t[5]),dp:pt(t[6]),dq:pt(t[7]),qi:pt(t[8]),kty:"RSA",alg:"RS256"}}function Ay(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new D("JWK was missing components");let t=new Tt({value:[new Ae({value:0}),Ae.fromBigInt(mt(N(r.n,"base64url"))),Ae.fromBigInt(mt(N(r.e,"base64url"))),Ae.fromBigInt(mt(N(r.d,"base64url"))),Ae.fromBigInt(mt(N(r.p,"base64url"))),Ae.fromBigInt(mt(N(r.q,"base64url"))),Ae.fromBigInt(mt(N(r.dp,"base64url"))),Ae.fromBigInt(mt(N(r.dq,"base64url"))),Ae.fromBigInt(mt(N(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function ph(r){let{result:e}=xl(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:pt(t[0]),e:pt(t[1])}}function Al(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let t=new Tt({value:[new Tt({value:[new ln({value:"1.2.840.113549.1.1.1"}),new an]}),new cn({valueHex:new Tt({value:[Ae.fromBigInt(mt(N(r.n,"base64url"))),Ae.fromBigInt(mt(N(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function pt(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return z(e,"base64url")}function mt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}function mh(r){let e=hh(r);return gh(e)}function Sl(r){let e=ph(r);if(vl(e)>hi)throw new Hr("Key size is too large");let t=sn(dt.encode({Type:ge.RSA,Data:r})),n=Qe(El,t);return new dn(e,n)}function gh(r){if(vl(r)>hi)throw new D("Key size is too large");let e=yh(r),t=sn(dt.encode({Type:ge.RSA,Data:Al(e.publicKey)})),n=Qe(El,t);return new fs(e.privateKey,new dn(e.publicKey,n))}async function _l(r){if(r>hi)throw new D("Key size is too large");let e=await uh(r),t=sn(dt.encode({Type:ge.RSA,Data:Al(e.publicKey)})),n=Qe(El,t);return new fs(e.privateKey,new dn(e.publicKey,n))}function yh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var pi=class extends Jr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Of(e);let n=qn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?e.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),o.fill(0)}update(e){return Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),Xr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Cl=(r,e,t)=>new pi(r,e).update(t).digest();Cl.create=(r,e)=>new pi(r,e);function wh(r){r.lowS!==void 0&&rt("lowS",r.lowS),r.prehash!==void 0&&rt("prehash",r.prehash)}function Sy(r){let e=Wn(r);ut(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:s}=e;if(t){if(!n.eql(s,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:_y,hexToBytes:Cy}=co,Il=class extends Error{constructor(e=""){super(e)}},Dt={Err:Il,_tlv:{encode:(r,e)=>{let{Err:t}=Dt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=ur(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?ur(s.length/2|128):"";return ur(r)+o+s+e},decode(r,e){let{Err:t}=Dt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Dt;if(r<Rt)throw new e("integer: negative integers are not allowed");let t=ur(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Dt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return _y(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Dt,s=typeof r=="string"?Cy(r):r;tn(s);let{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Dt,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},Rt=BigInt(0),xe=BigInt(1),QE=BigInt(2),bh=BigInt(3),e2=BigInt(4);function Iy(r){let e=Sy(r),{Fp:t}=e,n=jt(e.n,e.nBitLength),s=e.toBytes||((g,h,w)=>{let x=h.toAffine();return It(Uint8Array.from([4]),t.toBytes(x.x),t.toBytes(x.y))}),o=e.fromBytes||(g=>{let h=g.subarray(1),w=t.fromBytes(h.subarray(0,t.BYTES)),x=t.fromBytes(h.subarray(t.BYTES,2*t.BYTES));return{x:w,y:x}});function i(g){let{a:h,b:w}=e,x=t.sqr(g),y=t.mul(x,g);return t.add(t.add(y,t.mul(g,h)),w)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return zn(g,xe,e.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:x,n:y}=e;if(h&&typeof g!="bigint"){if(zt(g)&&(g=_t(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(w*2,"0")}let E;try{E=typeof g=="bigint"?g:Ct(oe("private key",g,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof g)}return x&&(E=Q(E,y)),Ke("private key",E,xe,y),E}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=hr((g,h)=>{let{px:w,py:x,pz:y}=g;if(t.eql(y,t.ONE))return{x:w,y:x};let E=g.is0();h==null&&(h=E?t.ONE:t.inv(y));let _=t.mul(w,h),L=t.mul(x,h),I=t.mul(y,h);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:_,y:L}}),f=hr(g=>{if(g.is0()){if(e.allowInfinityPoint&&!t.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=g.toAffine();if(!t.isValid(h)||!t.isValid(w))throw new Error("bad point: x or y not FE");let x=t.sqr(w),y=i(h);if(!t.eql(x,y))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,x){if(this.px=h,this.py=w,this.pz=x,h==null||!t.isValid(h))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(x==null||!t.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:x}=h||{};if(!h||!t.isValid(w)||!t.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let y=E=>t.eql(E,t.ZERO);return y(w)&&y(x)?d.ZERO:new d(w,x,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=t.invertBatch(h.map(x=>x.pz));return h.map((x,y)=>x.toAffine(w[y])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(o(oe("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return ho(d,n,h,w)}_setWindowSize(h){p.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(t.isOdd)return!t.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=t.eql(t.mul(w,L),t.mul(E,y)),T=t.eql(t.mul(x,L),t.mul(_,y));return I&&T}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:h,b:w}=e,x=t.mul(w,bh),{px:y,py:E,pz:_}=this,L=t.ZERO,I=t.ZERO,T=t.ZERO,k=t.mul(y,y),re=t.mul(E,E),W=t.mul(_,_),V=t.mul(y,E);return V=t.add(V,V),T=t.mul(y,_),T=t.add(T,T),L=t.mul(h,T),I=t.mul(x,W),I=t.add(L,I),L=t.sub(re,I),I=t.add(re,I),I=t.mul(L,I),L=t.mul(V,L),T=t.mul(x,T),W=t.mul(h,W),V=t.sub(k,W),V=t.mul(h,V),V=t.add(V,T),T=t.add(k,k),k=t.add(T,k),k=t.add(k,W),k=t.mul(k,V),I=t.add(I,k),W=t.mul(E,_),W=t.add(W,W),k=t.mul(W,V),L=t.sub(L,k),T=t.mul(W,re),T=t.add(T,T),T=t.add(T,T),new d(L,I,T)}add(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=t.ZERO,T=t.ZERO,k=t.ZERO,re=e.a,W=t.mul(e.b,bh),V=t.mul(w,E),he=t.mul(x,_),S=t.mul(y,L),P=t.add(w,x),v=t.add(E,_);P=t.mul(P,v),v=t.add(V,he),P=t.sub(P,v),v=t.add(w,y);let b=t.add(E,L);return v=t.mul(v,b),b=t.add(V,S),v=t.sub(v,b),b=t.add(x,y),I=t.add(_,L),b=t.mul(b,I),I=t.add(he,S),b=t.sub(b,I),k=t.mul(re,v),I=t.mul(W,S),k=t.add(I,k),I=t.sub(he,k),k=t.add(he,k),T=t.mul(I,k),he=t.add(V,V),he=t.add(he,V),S=t.mul(re,S),v=t.mul(W,v),he=t.add(he,S),S=t.sub(V,S),S=t.mul(re,S),v=t.add(v,S),V=t.mul(he,v),T=t.add(T,V),V=t.mul(b,v),I=t.mul(P,I),I=t.sub(I,V),V=t.mul(P,he),k=t.mul(b,k),k=t.add(k,V),new d(I,T,k)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return p.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:x}=e;Ke("scalar",h,Rt,x);let y=d.ZERO;if(h===Rt)return y;if(this.is0()||h===xe)return this;if(!w||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:E,k1:_,k2neg:L,k2:I}=w.splitScalar(h),T=y,k=y,re=this;for(;_>Rt||I>Rt;)_&xe&&(T=T.add(re)),I&xe&&(k=k.add(re)),re=re.double(),_>>=xe,I>>=xe;return E&&(T=T.negate()),L&&(k=k.negate()),k=new d(t.mul(k.px,w.beta),k.py,k.pz),T.add(k)}multiply(h){let{endo:w,n:x}=e;Ke("scalar",h,xe,x);let y,E;if(w){let{k1neg:_,k1:L,k2neg:I,k2:T}=w.splitScalar(h),{p:k,f:re}=this.wNAF(L),{p:W,f:V}=this.wNAF(T);k=p.constTimeNegate(_,k),W=p.constTimeNegate(I,W),W=new d(t.mul(W.px,w.beta),W.py,W.pz),y=k.add(W),E=re.add(V)}else{let{p:_,f:L}=this.wNAF(h);y=_,E=L}return d.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,w,x){let y=d.BASE,E=(L,I)=>I===Rt||I===xe||!L.equals(y)?L.multiplyUnsafe(I):L.multiply(I),_=E(this,w).add(E(h,x));return _.is0()?void 0:_}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=e;if(h===xe)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=e;return h===xe?this:w?w(d,this):this.multiplyUnsafe(e.h)}toRawBytes(h=!0){return rt("isCompressed",h),this.assertValidity(),s(d,this,h)}toHex(h=!0){return rt("isCompressed",h),_t(this.toRawBytes(h))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let m=e.nBitLength,p=fo(d,e.endo?Math.ceil(m/2):m);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function By(r){let e=Wn(r);return ut(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function xh(r){let e=By(r),{Fp:t,n}=e,s=t.BYTES+1,o=2*t.BYTES+1;function i(S){return Q(S,n)}function a(S){return lo(S,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Iy({...e,toBytes(S,P,v){let b=P.toAffine(),A=t.toBytes(b.x),B=It;return rt("isCompressed",v),v?B(Uint8Array.from([P.hasEvenY()?2:3]),A):B(Uint8Array.from([4]),A,t.toBytes(b.y))},fromBytes(S){let P=S.length,v=S[0],b=S.subarray(1);if(P===s&&(v===2||v===3)){let A=Ct(b);if(!zn(A,xe,t.ORDER))throw new Error("Point is not on curve");let B=u(A),R;try{R=t.sqrt(B)}catch(K){let O=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+O)}let M=(R&xe)===xe;return(v&1)===1!==M&&(R=t.neg(R)),{x:A,y:R}}else if(P===o&&v===4){let A=t.fromBytes(b.subarray(0,t.BYTES)),B=t.fromBytes(b.subarray(t.BYTES,2*t.BYTES));return{x:A,y:B}}else{let A=s,B=o;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+B+", got "+P)}}}),d=S=>_t(Wt(S,e.nByteLength));function m(S){let P=n>>xe;return S>P}function p(S){return m(S)?i(-S):S}let g=(S,P,v)=>Ct(S.slice(P,v));class h{constructor(P,v,b){this.r=P,this.s=v,this.recovery=b,this.assertValidity()}static fromCompact(P){let v=e.nByteLength;return P=oe("compactSignature",P,v*2),new h(g(P,0,v),g(P,v,2*v))}static fromDER(P){let{r:v,s:b}=Dt.toSig(oe("DER",P));return new h(v,b)}assertValidity(){Ke("r",this.r,xe,n),Ke("s",this.s,xe,n)}addRecoveryBit(P){return new h(this.r,this.s,P)}recoverPublicKey(P){let{r:v,s:b,recovery:A}=this,B=L(oe("msgHash",P));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?v+e.n:v;if(R>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let M=(A&1)===0?"02":"03",F=c.fromHex(M+d(R)),K=a(R),O=i(-B*K),J=i(b*K),te=c.BASE.multiplyAndAddUnsafe(F,O,J);if(!te)throw new Error("point at infinify");return te.assertValidity(),te}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return fr(this.toDERHex())}toDERHex(){return Dt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return fr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(S){try{return l(S),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let S=Bc(e.n);return Xf(e.randomBytes(S),e.n)},precompute(S=8,P=c.BASE){return P._setWindowSize(S),P.multiply(BigInt(3)),P}};function x(S,P=!0){return c.fromPrivateKey(S).toRawBytes(P)}function y(S){let P=zt(S),v=typeof S=="string",b=(P||v)&&S.length;return P?b===s||b===o:v?b===2*s||b===2*o:S instanceof c}function E(S,P,v=!0){if(y(S))throw new Error("first arg must be private key");if(!y(P))throw new Error("second arg must be public key");return c.fromHex(P).multiply(l(S)).toRawBytes(v)}let _=e.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");let P=Ct(S),v=S.length*8-e.nBitLength;return v>0?P>>BigInt(v):P},L=e.bits2int_modN||function(S){return i(_(S))},I=Gn(e.nBitLength);function T(S){return Ke("num < 2^"+e.nBitLength,S,Rt,I),Wt(S,e.nByteLength)}function k(S,P,v=re){if(["recovered","canonical"].some(be=>be in v))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:A}=e,{lowS:B,prehash:R,extraEntropy:M}=v;B==null&&(B=!0),S=oe("msgHash",S),wh(v),R&&(S=oe("prehashed msgHash",b(S)));let F=L(S),K=l(P),O=[T(K),T(F)];if(M!=null&&M!==!1){let be=M===!0?A(t.BYTES):M;O.push(oe("extraEntropy",be))}let J=It(...O),te=F;function we(be){let ve=_(be);if(!f(ve))return;let _e=a(ve),He=c.BASE.multiply(ve).toAffine(),Ne=i(He.x);if(Ne===Rt)return;let lt=i(_e*i(te+Ne*K));if(lt===Rt)return;let yt=(He.x===Ne?0:2)|Number(He.y&xe),Mn=lt;return B&&m(lt)&&(Mn=p(lt),yt^=1),new h(Ne,Mn,yt)}return{seed:J,k2sig:we}}let re={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function V(S,P,v=re){let{seed:b,k2sig:A}=k(S,P,v),B=e;return Sc(B.hash.outputLen,B.nByteLength,B.hmac)(b,A)}c.BASE._setWindowSize(8);function he(S,P,v,b=W){let A=S;P=oe("msgHash",P),v=oe("publicKey",v);let{lowS:B,prehash:R,format:M}=b;if(wh(b),"strict"in b)throw new Error("options.strict was renamed to lowS");if(M!==void 0&&M!=="compact"&&M!=="der")throw new Error("format must be compact or der");let F=typeof A=="string"||zt(A),K=!F&&!M&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!F&&!K)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let O,J;try{if(K&&(O=new h(A.r,A.s)),F){try{M!=="compact"&&(O=h.fromDER(A))}catch(yt){if(!(yt instanceof Dt.Err))throw yt}!O&&M!=="der"&&(O=h.fromCompact(A))}J=c.fromHex(v)}catch{return!1}if(!O||B&&O.hasHighS())return!1;R&&(P=e.hash(P));let{r:te,s:we}=O,be=L(P),ve=a(we),_e=i(be*ve),He=i(te*ve),Ne=c.BASE.multiplyAndAddUnsafe(J,_e,He)?.toAffine();return Ne?i(Ne.x)===te:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:E,sign:V,verify:he,ProjectivePoint:c,Signature:h,utils:w}}function ky(r){return{hash:r,hmac:(e,...t)=>Cl(r,e,yc(...t)),randomBytes:Qr}}function vh(r,e){let t=n=>xh({...r,...ky(n)});return{...t(e),create:t}}var Sh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Eh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ty=BigInt(1),Bl=BigInt(2),Ah=(r,e)=>(r+e/Bl)/e;function Ly(r){let e=Sh,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=se(u,t,e)*u%e,d=se(f,t,e)*u%e,m=se(d,Bl,e)*l%e,p=se(m,s,e)*m%e,g=se(p,o,e)*p%e,h=se(g,a,e)*g%e,w=se(h,c,e)*h%e,x=se(w,a,e)*g%e,y=se(x,t,e)*u%e,E=se(y,i,e)*p%e,_=se(E,n,e)*l%e,L=se(_,Bl,e);if(!kl.eql(kl.sqr(L),r))throw new Error("Cannot find square root");return L}var kl=jt(Sh,void 0,void 0,{sqrt:Ly}),Xe=vh({a:BigInt(0),b:BigInt(7),Fp:kl,n:Eh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Eh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ty*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,i=BigInt("0x100000000000000000000000000000000"),a=Ah(o*r,e),c=Ah(-n*r,e),l=Q(r-a*t-c*s,e),u=Q(-a*n-c*o,e),f=l>i,d=u>i;if(f&&(l=e-l),d&&(u=e-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},sn),l2=BigInt(0);var u2=Xe.ProjectivePoint;function Fe(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Ce(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}function Tl(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function _h(r,e){let t=rn.digest(e instanceof Uint8Array?e:e.subarray());if(Tl(t))return t.then(({digest:n})=>Xe.sign(n,r).toDERRawBytes()).catch(n=>{throw new cs(String(n))});try{return Xe.sign(t.digest,r).toDERRawBytes()}catch(n){throw new cs(String(n))}}function Ch(r,e,t){let n=rn.digest(t instanceof Uint8Array?t:t.subarray());if(Tl(n))return n.then(({digest:s})=>Xe.verify(e,s,r)).catch(s=>{throw new ls(String(s))});try{return Xe.verify(e,n.digest,r)}catch(s){throw new ls(String(s))}}var ds=class{type="secp256k1";raw;_key;constructor(e){this._key=kh(e),this.raw=Ih(this._key)}toMultihash(){return At.digest(ft(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return Ch(this._key,t,e)}},mi=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Bh(e),this.publicKey=new ds(t??Th(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return _h(this.raw,e)}};function Ll(r){return new ds(r)}async function Lh(){let r=Py();return new mi(r)}function Ih(r){return Xe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Bh(r){try{return Xe.getPublicKey(r,!0),r}catch(e){throw new On(String(e))}}function kh(r){try{return Xe.ProjectivePoint.fromHex(r),r}catch(e){throw new Hr(String(e))}}function Th(r){try{return Xe.getPublicKey(r,!0)}catch(e){throw new On(String(e))}}function Py(){return Xe.utils.randomPrivateKey()}async function Ph(r,e){if(r==="Ed25519")return ad();if(r==="secp256k1")return Lh();if(r==="RSA")return _l(e??2048);throw new Ht}function hn(r){let{Type:e,Data:t}=dt.decode(r),n=t??new Uint8Array;switch(e){case ge.RSA:return Sl(n);case ge.Ed25519:return Rc(n);case ge.secp256k1:return Ll(n);default:throw new Ht}}function Nh(r){let{Type:e,Data:t}=dt.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return Rc(n);case ge.secp256k1:return Ll(n);default:throw new Ht}}function ft(r){return dt.encode({Type:ge[r.type],Data:r.raw})}var Dh=Symbol.for("nodejs.util.inspect.custom"),Ny=114,hs=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[zs]=!0;toString(){return this.string==null&&(this.string=X.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(Ny,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ce(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ce(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Dh](){return`PeerId(${this.toString()})`}},ps=class extends hs{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ms=class extends hs{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},gs=class extends hs{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Dy=2336,ys=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=At.digest(N(this.url))}[Dh](){return`PeerId(${this.url})`}[zs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(Dy,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};var Ry=114,Rh=2336;function gt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=et(X.decode(`z${r}`));else{if(e==null)throw new D('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=et(e.decode(r))}return pn(t)}function Pl(r){if(r.type==="Ed25519")return new ms({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new gs({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ps({multihash:r.toCID().multihash,publicKey:r});throw new Ht}function Mh(r){return Pl(r.publicKey)}function pn(r){if(Oy(r))return new ps({multihash:r});if(My(r))try{let e=Nh(r);if(e.type==="Ed25519")return new ms({multihash:r,publicKey:e});if(e.type==="secp256k1")return new gs({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new ys(new URL(t))}throw new Xs("Supplied PeerID Multihash is invalid")}function gi(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ry&&r.code!==Rh)throw new Zs("Supplied PeerID CID is invalid");if(r.code===Rh){let e=z(r.multihash.digest);return new ys(new URL(e))}return pn(r.multihash)}function My(r){return r.code===At.code}function Oy(r){return r.code===rn.code}var fe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Dl=Vr(Uh(),1);var bs=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Rl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Fh=r=>globalThis.DOMException===void 0?new Rl(r):new DOMException(r),Vh=r=>{let e=r.reason===void 0?Fh("This operation was aborted."):r.reason;return e instanceof Error?e:Fh(e)};function xs(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:m}=e;m.aborted&&f(Vh(m)),a=()=>{f(Vh(m))},m.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new bs;i=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?u():s instanceof Error?f(s):(d.message=s??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(m){f(m)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},l}function Ml(r,e,t){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;t(r[i],e)<=0?(n=++i,s-=o+1):s=o}return n}var vs=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let s=Ml(this.#e,n,(o,i)=>i.priority-o.priority);this.#e.splice(s,0,n)}setPriority(e,t){let n=this.#e.findIndex(o=>o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[s]=this.#e.splice(n,1);this.enqueue(s.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var tr=class extends Dl.default{#e;#t;#o=0;#a;#c;#p=0;#n;#l;#r;#m;#s=0;#u;#i;#g;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:vs,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#x(){return this.#t||this.#o<this.#a}get#v(){return this.#s<this.#u}#E(){this.#s--,this.#f(),this.emit("next")}#A(){this.#w(),this.#y(),this.#l=void 0}get#S(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#o=this.#e?this.#s:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#A()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#S;if(this.#x&&this.#v){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#o===0&&this.#s===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#o=this.#e?this.#s:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#d()}async#_(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#r.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#b++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,s)=>{this.#r.enqueue(async()=>{this.#s++,this.#o++;try{t.signal?.throwIfAborted();let o=e({signal:t.signal});t.timeout&&(o=xs(Promise.resolve(o),{milliseconds:t.timeout})),t.signal&&(o=Promise.race([o,this.#_(t.signal)]));let i=await o;n(i),this.emit("completed",i)}catch(o){if(o instanceof bs&&!t.throwOnTimeout){n();return}s(o),this.emit("error",o)}finally{this.#E()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#d(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#h("next",()=>this.#r.size<e)}async onIdle(){this.#s===0&&this.#r.size===0||await this.#h("idle")}async#h(e,t){return new Promise(n=>{let s=()=>{t&&!t()||(this.off(e,s),n())};this.on(e,s)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#i}};function wi(r){let e=[je.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Ol=60;function bi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:je[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:je[e.type],TTL:e.TTL??e.ttl??Ol,data:e.data instanceof Uint8Array?z(e.data):e.data}))}}var Vy=4;function Ul(r,e={}){let t=new tr({concurrency:e.queryConcurrency??Vy});return async(n,s={})=>{let o=new URLSearchParams;o.set("name",n),wi(s.types).forEach(a=>{o.append("type",je[a])}),s.onProgress?.(new fe("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${o}`,{headers:{accept:"application/dns-json"},signal:s?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=bi(await a.json());return s.onProgress?.(new fe("dns:response",{detail:c})),c},{signal:s.signal});if(i==null)throw new Error("No DNS response received");return i}}function Hh(){return[Ul("https://cloudflare-dns.com/dns-query"),Ul("https://dns.google/resolve")]}var qh=Vr($h(),1);var Fl=class{lru;constructor(e){this.lru=(0,qh.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return bi({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:je[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??Ol)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function zh(r){return new Fl(r)}var Hy=1e3,xi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=zh(e.cacheSize??Hy),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Hh())}async query(e,t={}){let n=wi(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new fe("dns:cache",{detail:s})),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new fe("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(je||(je={}));function Gh(r={}){return new xi(r)}var vi=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let 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(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Wh=45,Ky=15,mn=new vi;function Ei(r){if(!(r.length>Ky))return mn.new(r).parseWith(()=>mn.readIPv4Addr())}function Ai(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Wh))return mn.new(r).parseWith(()=>mn.readIPv6Addr())}function xr(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Wh)return;let t=mn.new(r).parseWith(()=>mn.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function jh(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function Zh(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function Vl(r){switch(r.length){case vr:return r.join(".");case Er:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Xh(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function Yh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var vr=4,Er=16,XA=parseInt("0xFFFF",16),$y=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Es(r,e){e.length===Er&&r.length===vr&&jh(e,0,11)&&(e=e.slice(12)),e.length===vr&&r.length===Er&&Zh(r,$y,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function Jh(r,e){if(typeof e=="string"&&(e=xr(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Hl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=vr,s=Ei(e);if(s==null&&(n=Er,s=Ai(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Kl(o,8*n);return{network:Es(s,i),mask:i}}function Kl(r,e){if(e!==8*vr&&e!==8*Er)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var gn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Hl(e));else{let n=xr(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=xr(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=Kl(s,8*n.length);this.network=Es(n,this.mask)}}contains(e){return Jh({network:this.network,mask:this.mask},e)}toString(){let e=Xh(this.mask),t=e!==-1?String(e):Yh(this.mask);return Vl(this.network)+"/"+t}};function at(r){return!!Ei(r)}function yn(r){return!!Ai(r)}function Si(r){return!!xr(r)}var Qh=at,qy=yn,$l=function(r){let e=0;if(r=r.toString().trim(),Qh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(qy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=Qh(t[n]),i;o&&(i=$l(t[n]),t[n]=z(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){let o=parseInt(t[n],16);s[e++]=o>>8&255,s[e++]=o&255}return s}throw new Error("invalid ip address")},ep=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let s=[];for(let o=0;o<t;o++)s.push(r[e+o]);return s.join(".")}if(t===16){let s=[];for(let o=0;o<t;o+=2)s.push(n.getUint16(e+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var wn={},ql={},Gy=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"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,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Gy.forEach(r=>{let e=Wy(...r);ql[e.code]=e,wn[e.name]=e});function Wy(r,e,t,n,s){return{code:r,size:e,name:t,resolvable:!!n,path:!!s}}function G(r){if(typeof r=="number"){if(ql[r]!=null)return ql[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(wn[r]!=null)return wn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var jy=G("ip4"),Zy=G("ip6"),Xy=G("ipcidr");function jl(r,e){switch(G(r).code){case 4:case 41:return Jy(e);case 42:return Wl(e);case 43:return z(e,"base10");case 6:case 273:case 33:case 132:return np(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Wl(e);case 421:return rw(e);case 444:return rp(e);case 445:return rp(e);case 466:return tw(e);case 481:return globalThis.encodeURIComponent(Wl(e));default:return z(e,"base16")}}function Zl(r,e){switch(G(r).code){case 4:return tp(e);case 41:return tp(e);case 42:return Gl(e);case 43:return N(e,"base10");case 6:case 273:case 33:case 132:return Yl(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gl(e);case 421:return Qy(e);case 444:return nw(e);case 445:return sw(e);case 466:return ew(e);case 481:return Gl(globalThis.decodeURIComponent(e));default:return N(e,"base16")}}function Xl(r){let e,t;if(r.stringTuples().forEach(([n,s])=>{(n===jy.code||n===Zy.code)&&(t=s),n===Xy.code&&(e=s)}),e==null||t==null)throw new Error("Invalid multiaddr");return new gn(t,e)}var zl=Object.values(Xn).map(r=>r.decoder),Yy=function(){let r=zl[0].or(zl[1]);return zl.slice(2).forEach(e=>r=r.or(e)),r}();function tp(r){if(!Si(r))throw new Error("invalid ip address");return $l(r)}function Jy(r){let e=ep(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Si(e))throw new Error("invalid ip address");return e}function Yl(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function np(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Gl(r){let e=N(r),t=Uint8Array.from(Be(e.length));return Fe([t,e],t.length+e.length)}function Wl(r){let e=st(r);if(r=r.slice(de(e)),r.length!==e)throw new Error("inconsistent lengths");return z(r)}function Qy(r){let e;r[0]==="Q"||r[0]==="1"?e=et(X.decode(`z${r}`)).bytes:e=pe.parse(r).multihash.bytes;let t=Uint8Array.from(Be(e.length));return Fe([t,e],t.length+e.length)}function ew(r){let e=Yy.decode(r),t=Uint8Array.from(Be(e.length));return Fe([t,e],t.length+e.length)}function tw(r){let e=st(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+z(t,"base64url")}function rw(r){let e=st(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return z(t,"base58btc")}function nw(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Ge.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Yl(n);return Fe([t,s],t.length+s.length)}function sw(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ge.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Yl(n);return Fe([t,s],t.length+s.length)}function rp(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=z(e,"base32"),s=np(t);return`${n}:${s}`}function sp(r){r=Jl(r);let e=[],t=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<s.length;o++){let i=s[o],a=G(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(o++,o>=s.length)throw new _i("invalid address: "+r);if(a.path===!0){n=Jl(s.slice(o).join("/")),e.push([a.code,Zl(a.code,n)]),t.push([a.code,n]);break}let c=Zl(a.code,s[o]);e.push([a.code,c]),t.push([a.code,jl(a.code,c)])}return{string:op(t),bytes:Ci(e),tuples:e,stringTuples:t,path:n}}function Ql(r){let e=[],t=[],n=null,s=0;for(;s<r.length;){let o=st(r,s),i=de(o),a=G(o),c=ow(a,r.slice(s+i));if(c===0){e.push([o]),t.push([o]),s+=i;continue}let l=r.slice(s+i,s+i+c);if(s+=c+i,s>r.length)throw new _i("Invalid address Uint8Array: "+z(r,"base16"));e.push([o,l]);let u=jl(o,l);if(t.push([o,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:op(t),tuples:e,stringTuples:t,path:n}}function op(r){let e=[];return r.map(t=>{let n=G(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Jl(e.join("/"))}function Ci(r){return Fe(r.map(e=>{let t=G(e[0]),n=Uint8Array.from(Be(t.code));return e.length>1&&e[1]!=null&&(n=Fe([n,e[1]])),n}))}function ow(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=st(e instanceof Uint8Array?e:Uint8Array.from(e));return t+de(t)}}function Jl(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}var _i=class extends Error{static name="ParseError";name="ParseError";constructor(e){super(`Error parsing address: ${e}`)}};var iw=Symbol.for("nodejs.util.inspect.custom"),tu=Symbol.for("@multiformats/js-multiaddr/multiaddr"),aw=[G("dns").code,G("dns4").code,G("dns6").code,G("dnsaddr").code],eu=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},Ii=class r{bytes;#e;#t;#o;#a;[tu]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Ql(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=sp(e)}else if(rr(e))t=Ql(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#o=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="",i=G("tcp"),a=G("udp"),c=G("ip4"),l=G("ip6"),u=G("dns6"),f=G("ip6zone");for(let[m,p]of this.stringTuples())m===f.code&&(o=`%${p??""}`),aw.includes(m)&&(t=i.name==="tcp"?"tcp":"udp",s=443,n=`${p??""}${o}`,e=m===u.code?6:4),(m===i.code||m===a.code)&&(t=G(m).name==="tcp"?"tcp":"udp",s=parseInt(p??"")),(m===c.code||m===l.code)&&(t=G(m).name==="tcp"?"tcp":"udp",n=`${p??""}${o}`,e=m===l.code?6:4);if(e==null||t==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:s}}protos(){return this.#t.map(([e])=>Object.assign({},G(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>G(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#o.map(([e,t])=>t==null?[e]:[e,t])}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Ci(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,s])=>{n===wn.p2p.code&&e.push([n,s]),n===wn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?z(X.decode(`z${n}`),"base58btc"):z(pe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ce(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=bn.get(t.name);if(n==null)throw new eu(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>j(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new 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(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[iw](){return`Multiaddr(${this.#e})`}};var bn=new Map;function rr(r){return!!r?.[tu]}function j(r){return new Ii(r)}var cw=32,{code:lw}=G("dnsaddr"),ru=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},Ar=async function(e,t={}){let n=t.maxRecursiveDepth??cw;if(n===0)throw new ru("Max recursive depth reached");let[,s]=e.stringTuples().find(([l])=>l===lw)??[],i=await(t?.dns??Gh()).query(`_dnsaddr.${s}`,{signal:t?.signal,types:[je.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let u=l.data.replace(/["']/g,"").trim().split("=")[1];if(u==null||a!=null&&!u.includes(a))continue;let f=j(u);if(u.startsWith("/dnsaddr")){let d=await f.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(m=>m.toString()))}else c.push(f.toString())}return c};var pp=Vr(hp(),1),Ti=pp.default;var mw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ar}},transportManager:{faultTolerance:cr.FATAL_ALL}};async function mp(r){let e=Ti(mw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new D("Private network is enforced, but no protector was provided");return e}function gw(r,e){try{if(typeof r=="string"&&r.length>0)return yw(r);if(typeof r=="number"&&isFinite(r))return e?.long?bw(r):ww(r);throw new Error("Value is not a string or number.")}catch(t){let n=xw(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function yw(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Pi=gw;function ww(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function bw(r){let e=Math.abs(r);return e>=864e5?Li(r,e,864e5,"day"):e>=36e5?Li(r,e,36e5,"hour"):e>=6e4?Li(r,e,6e4,"minute"):e>=1e3?Li(r,e,1e3,"second"):`${r} ms`}function Li(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}function xw(r){return typeof r=="object"&&r!==null&&"message"in r}function su(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=Pi,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,m,p;function g(...h){if(!g.enabled)return;let w=g,x=Number(new Date),y=x-(f||x);w.diff=y,w.prev=f,w.curr=x,f=x,h[0]=t.coerce(h[0]),typeof h[0]!="string"&&h.unshift("%O");let E=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(L,I)=>{if(L==="%%")return"%";E++;let T=t.formatters[I];if(typeof T=="function"){let k=h[E];L=T.call(w,k),h.splice(E,1),E--}return L}),t.formatArgs.call(w,h),(w.log||t.log).apply(w,h)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(m!==t.namespaces&&(m=t.namespaces,p=t.enabled(u)),p),set:h=>{d=h}}),typeof t.init=="function"&&t.init(g),g}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),m=d.length;for(f=0;f<m;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Ni=Iw(),vw=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Ew(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Aw(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Pi(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}var Sw=console.debug??console.log??(()=>{});function _w(r){try{r?Ni?.setItem("debug",r):Ni?.removeItem("debug")}catch{}}function Cw(){let r;try{r=Ni?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Iw(){try{return localStorage}catch{}}function Bw(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var gp=su({formatArgs:Aw,save:_w,load:Cw,useColors:Ew,setupFormatters:Bw,colors:vw,storage:Ni,log:Sw});var ze=gp;ze.formatters.b=r=>r==null?"undefined":X.baseEncode(r);ze.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);ze.formatters.m=r=>r==null?"undefined":Yc.baseEncode(r);ze.formatters.p=r=>r==null?"undefined":r.toString();ze.formatters.c=r=>r==null?"undefined":r.toString();ze.formatters.k=r=>r==null?"undefined":r.toString();ze.formatters.a=r=>r==null?"undefined":r.toString();ze.formatters.e=r=>r==null?"undefined":yp(r.stack)??yp(r.message)??r.toString();function kw(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Di(){return{forComponent(r){return Tw(r)}}}function Tw(r){let e=kw(`${r}:trace`);return ze.enabled(`${r}:trace`)&&ze.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=ze(`${r}:trace`)),Object.assign(ze(r),{error:ze(`${r}:error`),trace:e})}function yp(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Sr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function Ri(r){let e=et(X.decode(`z${r}`));return pn(e)}var Mt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Sr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Sr(this.map.values(),e=>e.key)}values(){return Sr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var _r=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Sr(this.set.entries(),e=>{let t=Ri(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Ri(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Sr(this.set.values(),e=>Ri(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var bp=Symbol.for("@achingbrain/uint8arraylist");function wp(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Mi(r){return!!r?.[bp]}var ye=class r{bufs;length;[bp]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Mi(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Mi(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=wp(this.bufs,e);return t.buf[t.index]}set(e,t){let n=wp(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Mi(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Fe(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Fe(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,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(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Mi(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=le(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=le(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=le(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=le(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=le(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=le(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=le(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=le(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ce(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var ou={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},xp={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},vp=new globalThis.TextEncoder;function Lw(r,e){let t=ou[e],n=xp[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function Pw(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ou[e],s=xp[e],o=r;for(;o.length>0;){let i=vp.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function iu(r,{size:e=32,utf8Buffer:t}={}){if(!ou[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Pw(r,e,t);r=vp.encode(r)}return Lw(r,e)}var As={hash:r=>Number(iu(r,{size:32})),hashV:(r,e)=>Nw(As.hash(r,e))};function Nw(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),N(e,"base16")}var au=64,ct=class{fp;h;seed;constructor(e,t,n,s=2){if(s>au)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=le(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ce(this.fp,e.fp):!1}};function Cr(r,e){return Math.floor(Math.random()*(e-r))+r}var Ir=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");let t=Cr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Dw=500,Ss=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??As,this.seed=e.seed??Cr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=N(e));let t=new ct(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ir(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Ir(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Cr(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize));for(let a=0;a<Dw;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=N(e));let t=new ct(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=N(e));let t=new ct(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Rw={1:.5,2:.84,4:.95,8:.98};function Mw(r=.001){return r>.002?2:r>1e-5?4:8}function Ep(r,e=.001){let t=Mw(e),n=Rw[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),au);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Oi=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??As,this.seed=e.seed??Cr(0,Math.pow(2,10)),this.filterSeries=[new Ss({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=N(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Ss({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=N(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=N(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)}};function _s(r,e=.001,t){return new Oi({...Ep(r,e),...t??{}})}var Cs;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:le(0),payloadType:le(0),payload:le(0),signature:le(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Cs||(Cs={}));var Ui=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var En=class r{static createFromProtobuf=async e=>{let t=Cs.decode(e),n=hn(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t==null)throw new Error("Missing private key");let n=e.domain,s=e.codec,o=e.marshal(),i=Ap(n,s,o),a=await t.sign(i.subarray());return new r({publicKey:t.publicKey,payloadType:s,payload:o,signature:a})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new Ui("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Cs.encode({publicKey:ft(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ce(this.marshal(),e.marshal())}async validate(e){let t=Ap(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},Ap=(r,e,t)=>{let n=N(r),s=Be(n.byteLength),o=Be(e.length),i=Be(t.length);return new ye(s,n,o,e,i,t)};function Sp(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var _p="libp2p-peer-record",Cp=Uint8Array.from([3,1]);var Is;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:le(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),s),n.encode=o=>Me(o,n.codec()),n.decode=(o,i)=>Re(o,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Oe((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s,o={})=>{let i={peerId:le(0),seq:0n,addresses:[]},a=s==null?n.len:n.pos+s;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new wr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Me(n,r.codec()),r.decode=(n,s)=>Re(n,r.codec(),s)})(Is||(Is={}));var Br=class r{static createFromProtobuf=e=>{let t=Is.decode(e),n=pn(et(t.peerId)),s=(t.addresses??[]).map(i=>j(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=_p;static CODEC=Cp;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Is.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 r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Sp(this.multiaddrs,e.multiaddrs))}};function Ow(r){return r[Symbol.asyncIterator]!=null}function Uw(r){if(Ow(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Bs=Uw;var nr={},An=r=>{r.addEventListener("message",e=>{An.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{An.dispatchEvent("message",r,e)})};An.addEventListener=(r,e)=>{nr[r]==null&&(nr[r]=[]),nr[r].push(e)};An.removeEventListener=(r,e)=>{nr[r]!=null&&(nr[r]=nr[r].filter(t=>t===e))};An.dispatchEvent=function(r,e,t){nr[r]!=null&&nr[r].forEach(n=>n(e,t))};var cu=An;var lu="lock:worker:request-read",uu="lock:worker:release-read",fu="lock:master:grant-read",du="lock:worker:request-write",hu="lock:worker:release-write",pu="lock:master:grant-write";var Ip=(r=21)=>Math.random().toString().substring(2);var Bp=(r,e,t,n,s)=>(o,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{o.postMessage({type:s,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u?.data==null)return;let f={type:u.data.type,name:u.data.name,identifier:u.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",l),c())};o.addEventListener("message",l)})}}}))},kp=(r,e,t,n)=>async()=>{let s=Ip();return globalThis.postMessage({type:e,identifier:s,name:r}),new Promise(o=>{let i=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===s&&(globalThis.removeEventListener("message",i),o(()=>{globalThis.postMessage({type:n,identifier:s,name:r})}))};globalThis.addEventListener("message",i)})},Fw={singleProcess:!1},Tp=r=>{if(r=Object.assign({},Fw,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return cu.addEventListener("message",Bp(t,"requestReadLock",lu,uu,fu)),cu.addEventListener("message",Bp(t,"requestWriteLock",du,hu,pu)),t}return{isWorker:!0,readLock:t=>kp(t,lu,fu,uu),writeLock:t=>kp(t,du,pu,hu)}};var kr={},sr;async function mu(r,e){let t,n=new Promise(s=>{t=s});return r.add(async()=>xs((async()=>{await new Promise(s=>{t(()=>{s()})})})(),{milliseconds:e.timeout})),n}var Vw=(r,e)=>{if(sr.isWorker===!0)return{readLock:sr.readLock(r,e),writeLock:sr.writeLock(r,e)};let t=new tr({concurrency:1}),n;return{async readLock(){if(n!=null)return mu(n,e);n=new tr({concurrency:e.concurrency,autoStart:!1});let s=n,o=mu(n,e);return t.add(async()=>{s.start(),await s.onIdle().then(()=>{n===s&&(n=null)})}),o},async writeLock(){return n=null,mu(t,e)}}},Hw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function gu(r){let e=Object.assign({},Hw,r);return sr==null&&(sr=Tp(e),sr.isWorker!==!0&&(sr.addEventListener("requestReadLock",t=>{kr[t.data.name]!=null&&kr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),sr.addEventListener("requestWriteLock",async t=>{kr[t.data.name]!=null&&kr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),kr[e.name]==null&&(kr[e.name]=Vw(e.name,e)),kr[e.name]}var Sn;(function(r){let e;(function(s){let o;s.codec=()=>(o==null&&(o=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:le(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),o),s.encode=i=>Me(i,s.codec()),s.decode=(i,a)=>Re(i,s.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(s){let o;s.codec=()=>(o==null&&(o=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Vi.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Vi.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),o),s.encode=i=>Me(i,s.codec()),s.decode=(i,a)=>Re(i,s.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Oe((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.addresses!=null)for(let a of s.addresses)o.uint32(10),Fi.codec().encode(a,o);if(s.protocols!=null)for(let a of s.protocols)o.uint32(18),o.string(a);if(s.publicKey!=null&&(o.uint32(34),o.bytes(s.publicKey)),s.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(s.peerRecordEnvelope)),s.metadata!=null&&s.metadata.size!==0)for(let[a,c]of s.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(s.tags!=null&&s.tags.size!==0)for(let[a,c]of s.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new wr('Decode error - map field "addresses" had too many elements');a.addresses.push(Fi.codec().decode(s,s.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new wr('Decode error - map field "protocols" had too many elements');a.protocols.push(s.string());break}case 4:{a.publicKey=s.bytes();break}case 5:{a.peerRecordEnvelope=s.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Qn('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(s,s.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Qn('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(s,s.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>Me(s,r.codec()),r.decode=(s,o)=>Re(s,r.codec(),o)})(Sn||(Sn={}));var Fi;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={multiaddr:le(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Fi||(Fi={}));var Vi;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Vi||(Vi={}));function _n(r,e){let t=Sn.decode(e);if(t.publicKey!=null&&r.publicKey==null){let o=hn(t.publicKey);r=Pl(o)}let n=new Map,s=BigInt(Date.now());for(let[o,i]of t.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:o,isCertified:i})=>({multiaddr:j(o),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ot="/",Lp=new TextEncoder().encode(Ot),Hi=Lp[0],Tr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=N(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Hi)throw new Error("Invalid key")}toString(e="utf8"){return z(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ot))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Lp),this._buf[0]!==Hi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Hi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Hi;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ot).slice(1)}type(){return Kw(this.baseNamespace())}name(){return $w(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ot)||(e+=Ot),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ot):new r(e.slice(0,-1).join(Ot))}child(e){return this.toString()===Ot?e:e.toString()===Ot?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...qw(e.map(t=>t.namespaces()))])}};function Kw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function $w(r){let e=r.split(":");return e[e.length-1]}function qw(r){return[].concat(...r)}var yu="/peers/";function Cn(r){if(!Gs(r)||r.type==null)throw new D("Invalid PeerId");let e=r.toCID().toString();return new Tr(`${yu}${e}`)}async function Pp(r,e,t){let n=new Map;for(let s of t){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=j(s.multiaddr)),!rr(s.multiaddr))throw new D("Multiaddr was invalid");if(!await e(r,s.multiaddr))continue;let o=s.isCertified??!1,i=s.multiaddr.toString(),a=n.get(i);a!=null?s.isCertified=a.isCertified||o:n.set(i,{multiaddr:s.multiaddr,isCertified:o})}return[...n.values()].sort((s,o)=>s.multiaddr.toString().localeCompare(o.multiaddr.toString())).map(({isCertified:s,multiaddr:o})=>({isCertified:s,multiaddr:o.bytes}))}async function $i(r,e,t,n){if(e==null)throw new D("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new D("publicKey bytes do not match peer id publicKey bytes");let s=n.existingPeer;if(s!=null&&!r.equals(s.id))throw new D("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ki(d,{validate:Np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ki(d,{validate:Dp,map:Rp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[m,p]of d)p==null?a.delete(m):a.set(m,p);a=Ki([...a.entries()],{validate:Np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),m=new Map(c);for(let[p,g]of d)g==null?m.delete(p):m.set(p,g);c=Ki([...m.entries()],{validate:Dp,map:Rp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=ft(s.id.publicKey):e.publicKey!=null?u=ft(e.publicKey):r.publicKey!=null&&(u=ft(r.publicKey));let f={addresses:await Pp(r,n.addressFilter??(async()=>!0),o),protocols:[...i.values()].sort((d,m)=>d.localeCompare(m)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return r.type!=="RSA"&&delete f.publicKey,f}function Ki(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function Np(r,e){if(typeof r!="string")throw new D("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new D("Metadata value must be a Uint8Array")}function Dp(r,e){if(typeof r!="string")throw new D("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new D("Tag value must be an integer");if(e.value<0||e.value>100)throw new D("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new D("Tag ttl must be an integer");if(e.ttl<0)throw new D("Tag ttl must be between greater than 0")}}function Rp(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function qi(r,e){let t=r.toString().split("/")[2],n=pe.parse(t,Ge),s=gi(n);return _n(s,e)}function zw(r){return r==null?{}:{prefix:yu,filters:(r.filters??[]).map(e=>({key:t,value:n})=>e(qi(t,n))),orders:(r.orders??[]).map(e=>(t,n)=>e(qi(t.key,t.value),qi(n.key,n.value)))}}var zi=class{peerId;datastore;lock;addressFilter;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=gu({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Cn(e))}async delete(e){if(this.peerId.equals(e))throw new D("Cannot delete self peer");await this.datastore.delete(Cn(e))}async load(e){let t=await this.datastore.get(Cn(e));return _n(e,t)}async save(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await $i(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,o,n,s)}async patch(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await $i(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,n,s)}async merge(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await $i(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,n,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(zw(e??{}))){let s=qi(t,n);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Cn(e)),n=_n(e,t);return{existingBuf:t,existingPeer:n}}catch(t){t.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",t)}return{}}async#t(e,t,n,s){let o=Sn.encode(t);return n!=null&&ce(o,n)?{peer:_n(e,o),previous:s,updated:!1}:(await this.datastore.put(Cn(e),o),{peer:_n(e,o),previous:s,updated:!0})}};var wu=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new zi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let s of this.store.all(t))e(s)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Bs(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let s=await this.store.save(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let s=await this.store.patch(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let s=await this.store.merge(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await En.openAndCertify(e,Br.DOMAIN),s=gi(n.publicKey.toCID());if(t?.equals(s)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,s),!1;let o=Br.createFromProtobuf(n.payload),i;try{i=await this.get(s)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await En.createFromProtobuf(i.peerRecordEnvelope),c=Br.createFromProtobuf(a.payload);if(c.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Mp(r,e={}){return new wu(r,e)}var Gi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function Gw(r){return r[Symbol.asyncIterator]!=null}function Ww(r){if(Gw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var bu=Ww;function jw(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Op=jw;function Zw(r){return r[Symbol.asyncIterator]!=null}function Xw(r,e){let t=0;if(Zw(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Op(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=e(s,t++);if(typeof i.then=="function")return async function*(){await i&&(yield s);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)}()}var Lr=Xw;function Yw(r){return r[Symbol.asyncIterator]!=null}function Jw(r,e){return Yw(r)?async function*(){yield*(await Bs(r)).sort(e)}():function*(){yield*Bs(r).sort(e)}()}var xu=Jw;function Qw(r){return r[Symbol.asyncIterator]!=null}function eb(r,e){return Qw(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var vu=eb;var Wi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:s}of e)await this.put(n,s,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await bu(this.putMany(e,n)),e=[],await bu(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let s=e.prefix;n=Lr(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Lr(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>xu(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=Lr(n,()=>s++>=o)}return e.limit!=null&&(n=vu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=Lr(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Lr(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>xu(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=Lr(n,()=>o++>=s)}return e.limit!=null&&(n=vu(n,e.limit)),n}};var ji=class extends Wi{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw new Gi;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Tr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Tr(e)}};function Up(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Vp=Vr(Fp(),1),tb=["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"],rb=tb.map(r=>new Vp.Netmask(r));function Eu(r){for(let e of rb)if(e.contains(r))return!0;return!1}function nb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function sb(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Eu(s)}function ob(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function ib(r){let e=r.split(":"),t=e[e.length-1];return Eu(t)}function ab(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function or(r){return at(r)?Eu(r):nb(r)?sb(r):ob(r)?ib(r):yn(r)?ab(r):void 0}var cb=r=>r.toString().split("/").slice(1),In=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),$=r=>({match:e=>In(t=>t===r).match(e),pattern:r}),Pr=()=>({match:r=>In(e=>typeof e=="string").match(r),pattern:"{string}"}),Ts=()=>({match:r=>In(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),ee=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{X.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ls=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Jc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Pe=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function ie(...r){function e(s){let o=cb(s);for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var Xi=q($("dns4"),Pr()),Yi=q($("dns6"),Pr()),Ji=q($("dnsaddr"),Pr()),Su=q($("dns"),Pr()),aI=ie(Xi,Z(ee())),cI=ie(Yi,Z(ee())),lI=ie(Ji,Z(ee())),uI=ie(Pe(Su,Ji,Xi,Yi),Z(ee())),Hp=q($("ip4"),In(at)),Kp=q($("ip6"),In(yn)),_u=Pe(Hp,Kp),Ut=Pe(_u,Su,Xi,Yi,Ji),fI=ie(Pe(_u,q(Pe(Su,Ji,Xi,Yi),Z(ee())))),Cu=ie(Hp),Iu=ie(Kp),dI=ie(_u),Bu=q(Ut,$("tcp"),Ts()),Ps=q(Ut,$("udp"),Ts()),Ns=ie(q(Bu,Z(ee()))),hI=ie(Ps),ku=q(Ps,$("quic"),Z(ee())),Qi=q(Ps,$("quic-v1"),Z(ee())),lb=Pe(ku,Qi),pI=ie(ku),$p=ie(Qi),Au=Pe(Ut,Bu,Ps,ku,Qi),qp=Pe(q(Au,$("ws"),Z(ee()))),Nr=ie(qp),zp=Pe(q(Au,$("wss"),Z(ee())),q(Au,$("tls"),Z(q($("sni"),Pr())),$("ws"),Z(ee()))),Ds=ie(zp),Gp=q(Ps,$("webrtc-direct"),Z(Ls()),Z(Ls()),Z(ee())),Tu=ie(Gp),Wp=q(Qi,$("webtransport"),Z(Ls()),Z(Ls()),Z(ee())),Lu=ie(Wp),Zi=Pe(qp,zp,q(Bu,Z(ee())),q(lb,Z(ee())),q(Ut,Z(ee())),Gp,Wp,ee()),mI=ie(Zi),ub=q(Zi,$("p2p-circuit"),ee()),Rs=ie(ub),fb=Pe(q(Zi,$("p2p-circuit"),$("webrtc"),Z(ee())),q(Zi,$("webrtc"),Z(ee())),q($("webrtc"),Z(ee()))),Pu=ie(fb),db=Pe(q(Ut,$("tcp"),Ts(),$("http"),Z(ee())),q(Ut,$("http"),Z(ee()))),gI=ie(db),hb=Pe(q(Ut,$("tcp"),Pe(q($("443"),$("http")),q(Ts(),$("https"))),Z(ee())),q(Ut,$("tls"),$("http"),Z(ee())),q(Ut,$("https"),Z(ee()))),yI=ie(hb),pb=Pe(q($("memory"),Pr(),Z(ee()))),wI=ie(pb);var jp=864e13;var mb=448,Nu=449,gb=53,yb=54,wb=55,bb=56,ea=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=or(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?jp-Date.now():0,lastVerified:s?jp-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[s,o]of this.mappings.entries())o.domain===t&&(this.log("removing %s to %s DNS mapping %e",s,o.domain,new Error("where")),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr.stringTuples(),i=o[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(o,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:j(`/${o.map(u=>[G(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===mb&&e[n+1]?.[0]!==Nu)return e.splice(n+1,0,[Nu,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),s=!1;for(let[o,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",o,i.domain),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){let n=this.findHost(e),s=!1;for(let[o,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",o,i.domain),s=s||i.verified,i.verified=!1,i.expires=Date.now()+t);return s}findHost(e){for(let t of e.stringTuples())if(t[0]===Nu||t[0]===gb||t[0]===yb||t[0]===wb||t[0]===bb)return t[1]}};var Du=4,Ru=41,Mu=6,xb=273,ta=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t[0][1])return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:at(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",s=t[1][0]===Mu?"tcp":"udp",o=parseInt(t[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===o&&u.protocol===s&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,o,s),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(e){let t=[];for(let{multiaddr:n}of e){let s=n.stringTuples(),o;if((s[0][0]===Du||s[0][0]===Ru)&&s[1][0]===Mu?o=`${s[0][1]}-${s[1][1]}-tcp`:(s[0][0]===Du||s[0][0]===Ru)&&s[1][0]===xb&&(o=`${s[0][1]}-${s[1][1]}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)s[0][0]=a.externalFamily===4?Du:Ru,s[0][1]=a.externalIp,s[1][1]=`${a.externalPort}`,t.push({multiaddr:j(`/${s.map(c=>[G(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let s=e.stringTuples()[0][1],o=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===s&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=e.stringTuples(),s=n[0][1]??"",o=n[1][0]===Mu?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===s&&u.externalPort===i&&u.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,s,i,o),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function Zp(r){try{let[[e,t]]=r.stringTuples();if(t==null)return!1;if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}catch{}return!1}function ra(r){try{let[[e]]=r.stringTuples();return e===4||e===41}catch{}return!1}function Dr(r){try{if(!ra(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:or(e)??!1}catch{}return!0}var vb={maxObservedAddresses:10},na=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??vb.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Dr(e)||Zp(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:j(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var Eb=[4,41,53,54,55,56];function Ou(r){try{let[[e]]=r.stringTuples();return Eb.includes(e)}catch{}return!1}var Ab={maxObservedAddresses:10},sa=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??Ab.maxObservedAddresses}get(e,t){if(Dr(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!Ou(e),expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){if(Ou(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var Xp=6e4,Yp={maxObservedAddresses:10,addressVerificationTTL:Xp*10,addressVerificationRetry:Xp*5},Sb=r=>r;function Uu(r,e){let t=r.getPeerId();return t!=null&&gt(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var oa=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new na(e,t),this.dnsMappings=new ea(e,t),this.ipMappings=new ta(e,t),this.transportAddresses=new sa(e,t),this.announceFilter=t.announceFilter??Sb,this.observedAddressFilter=_s(1024),this.addressVerificationTTL=t.addressVerificationTTL??Yp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Yp.addressVerificationRetry,this._updatePeerStoreAddresses=Up(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>j(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Uu(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Uu(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Uu(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=j(n);return s.protos().pop()?.path===!0||s.getPeerId()===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(e)}),e.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];return t=t.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL))),t=t.concat(this.getAppendAnnounceAddrs().map(n=>({multiaddr:n,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(j(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${at(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(j(`/ip${at(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||or(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),s=[o=>Nr.exactMatch(o)||Ds.exactMatch(o),o=>Ns.exactMatch(o),o=>$p.exactMatch(o)];for(let o of s){if(!o(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};var Jp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Jp||(Jp={}));var ia=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},aa=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Bn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ms=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},ca=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},la=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},ua=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Os=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},kn=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},fa=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},da=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Rr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Mr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ha=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var Fu=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Di())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>to(t)).map(async t=>{await t[e]?.()}))}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")}},Cb=["metrics","connectionProtector","dns"],Ib=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Qp(r={}){let e=new Fu(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!Ib.includes(s)){let i=e.components[s];if(i==null&&!Cb.includes(s))throw new ia(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function em(r){let e={};for(let t of Object.values(r.components))for(let n of Bb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of kb(t))if(e[n]!==!0)throw new aa(`Service "${Tb(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Bb(r){return Array.isArray(r?.[Fn])?r[Fn]:[]}function kb(r){return Array.isArray(r?.[ic])?r[ic]:[]}function Tb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Lb=4,Pb=41;function tm(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(Nr.matches(e))return!1;let t=e.stringTuples();return t[0][0]===Lb||t[0][0]===Pb?!!or(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var rm=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Nb=new WeakMap;function Db({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(rm());let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(rm())},u=()=>{s&&s.removeEventListener("abort",l)},f=new Promise((d,m)=>{i=()=>{u(),d(n)},a=m,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",l,{once:!0}),Nb.set(f,()=>{c(o),o=null,i()}),f}}var Rb=Db(),nm=Rb;var pa=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},ma=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ga=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Vu}async consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new pa("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await nm(a)}return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&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)}},Vu=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function ya(r){if(Gs(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:gt(t),r.forEach(n=>{if(!rr(n))throw new Vt("Invalid multiaddr");let s=n.getPeerId();if(s==null){if(e!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let o=gt(s);if(e?.equals(o)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Mb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function sm(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??Mb;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}var om="last-dial-failure",im="last-dial-success";var wa=100,ba=50;async function am(r,e){let t=!1;for(let s of bn.keys())if(t=r.protoNames().includes(s),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(s=>s.toString())),n}function Us(r){try{let e;if(typeof r=="string"?e=j(r):e=r,!e.protoNames().includes("ipcidr")){let n=e.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(n)}return Xl(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Ob={maxConnections:wa,allow:[]},xa=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Ob.maxConnections,this.allow=(t.allow??[]).map(n=>Us(n)),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)}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(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new Mt;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((u,f)=>u+f.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let s=this.sortConnections(e,n),o=Math.max(t-this.maxConnections,0),i=[];for(let a of s)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>l.contains(a.remoteAddr.nodeAddress().address))||i.push(a),i.length===o)break;await Promise.all(i.map(async a=>{await sm(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};function ue(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var va=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Tn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new va(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new va(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Hu=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ea(r={}){return Ub(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ub(r,e){e=e??{};let t=e.onEnd,n=new Tn,s,o,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{o=x=>{o=null,n.push(x);try{h(r(n))}catch(y){w(y)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},l=h=>o!=null?o(h):(n.push(h),s),u=h=>(n=new Tn,o!=null?o({error:h}):(n.push({error:h}),s)),f=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?s:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new Tn,d(),{done:!0}),p=h=>(d(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,y;w!=null&&(x=new Promise((E,_)=>{y=()=>{_(new Hu)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,x])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},t==null)return s;let g=s;return s={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(h){return g.end(h),t!=null&&(t(h),t=void 0),s},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},s}var Ku=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Ln(r,e,t,n){let s=new Ku(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{function a(){t?.removeEventListener("abort",u),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),o(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(s)};t?.addEventListener("abort",u),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Aa=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function ir(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Aa(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new Aa(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Sa=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ue(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Fb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var _a=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Fb(),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)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Je),this.cleanup())}async join(e={}){let t=new Sa(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await ir(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),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=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Nn=class extends xt{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(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),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ma;let n=new _a(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Je)}),this.clear()}async onEmpty(e){this.size!==0&&await Ln(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ln(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ln(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ea({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new Je("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ca=class extends Nn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Ft(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}function cm(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function $u(r){if(!ra(r))return!1;let{address:e}=r.nodeAddress();return cm(e)}function Vb(r,e){let t=Ns.exactMatch(r.multiaddr),n=Ns.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let s=Ds.exactMatch(r.multiaddr),o=Ds.exactMatch(e.multiaddr);if(s&&!o)return-1;if(!s&&o)return 1;let i=Nr.exactMatch(r.multiaddr),a=Nr.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Pu.exactMatch(r.multiaddr),l=Pu.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Tu.exactMatch(r.multiaddr),f=Tu.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Lu.exactMatch(r.multiaddr),m=Lu.exactMatch(e.multiaddr);return d&&!m?-1:!d&&m?1:0}function Hb(r,e){let t=$u(r.multiaddr),n=$u(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Kb(r,e){let t=Dr(r.multiaddr),n=Dr(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function $b(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function qb(r,e){let t=Rs.exactMatch(r.multiaddr),n=Rs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function lm(r){return r.sort(Vb).sort($b).sort(qb).sort(Kb).sort(Hb)}var Ia={maxParallelDials:ba,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Ar}},Ba=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Ia.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Ia.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Ia.dialTimeout,this.connections=t.connections??new Mt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(let[n,s]of Object.entries(t.resolvers??{}))bn.set(n,s);this.queue=new Ca({concurrency:t.maxParallelDials??Ia.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==Je.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:s}=ya(e),o=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:s.find(c=>c.equals(a.remoteAddr)));if(o?.status==="open")return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new fe("dial-queue:already-connected")),o;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of s)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of s)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new fe("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new qr("Dial queue is full");return this.log("creating dial target for %p",n,s.map(a=>a.toString())),t.onProgress?.(new fe("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new fe("dial-queue:start-dial"));let c=Ft([this.shutDownController.signal,a.signal]);let l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new fe("dial-queue:calculated-addresses",l)),l.map(({multiaddr:u})=>u.toString()).forEach(u=>{a?.multiaddrs.add(u)})}catch(u){throw c.clear(),u}try{let u=0,f=[];for(let d of l){if(u===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",u,n),new qr("Peer had more than maxPeerAddrsToDial");u++;try{let m=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",d.multiaddr);try{await this.components.peerStore.merge(m.remotePeer,{multiaddrs:[m.remoteAddr],metadata:{[im]:N(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return m}catch(m){if(this.log.error("dial failed to %a",d.multiaddr,m),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[om]:N(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new Js(m.message);f.push(m)}}throw f.length===1?f[0]:new AggregateError(f,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??Wu,multiaddrs:new Set(s.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(f=>({multiaddr:j(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new qr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Os("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);s.push(...f.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:d})=>d.toString())),s.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,f)}}}let o=(await Promise.all(s.map(async f=>{let d=await am(f.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(m=>({multiaddr:m,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;o=o.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=o.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),m=a.get(d);if(m!=null){m.isCertified=m.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new kn("The dial request has no valid addresses");let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?lm(l):l.sort(this.addressSorter);if(u.length===0)throw new Os("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!Rs.matches(s.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ka=class extends Nn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var gm=Vr(pm(),1);var Gb=Object.prototype.toString,Wb=r=>Gb.call(r)==="[object Error]",jb=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"]);function ju(r){return r&&Wb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:jb.has(r.message):!1}var Zu=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},mm=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Xu(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let s=gm.default.operation(e),o=()=>{s.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),s.stop()};s.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Zu)throw c.originalError;if(c instanceof TypeError&&!ju(c))throw c;if(mm(c,a,e),await e.shouldRetry(c)||(s.stop(),n(c)),await e.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(l){mm(l,a,e),i(),n(l)}}})})}var Ta=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new ka({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);ym(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Xu(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(oc)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>ym(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function ym(r){for(let e of r.tags.keys())if(e.startsWith(oc))return!0;return!1}var Wu=50,Yu={maxConnections:wa,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},La=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Yu.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new Mt,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=(t.allow??[]).map(n=>Us(n)),this.deny=(t.deny??[]).map(n=>Us(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Yu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ga({points:t.inboundConnectionThreshold??Yu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new xa({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:t.allow?.map(n=>j(n))}),this.dialQueue=new Ba(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??ba,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Ar},connections:this.connections}),this.reconnectQueue=new Ta({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let s of n.streams){let o=`${s.direction} ${s.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await bf(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 xf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(s){this.log.error(s)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new bt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=ya(e);if(this.peerId.equals(n))throw new $r("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new fe("dial-queue:already-connected")),a}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Wu});if(s.status!=="open")throw new Kr("Remote closed connection during opening");let o=this.connections.get(s.remotePeer);o==null&&(o=[],this.connections.set(s.remotePeer,o));let i=!1;for(let a of o)if(a.id===s.id&&(i=!0),t.force!==!0&&a.id!==s.id&&a.remoteAddr.equals(s.remoteAddr))return s.abort(new Vt("Duplicate multiaddr connection")),a;return i||o.push(s),s}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await s.close(t)}catch(o){s.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(s=>s.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(s=>s.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()){let s=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(s,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s),!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(){let 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(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Dn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var Yb=1.2,Jb=2,Qb=2e3,Pa=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Dn(e.interval??5e3),this.failure=new Dn(e.interval??5e3),this.next=new Dn(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Jb,this.timeoutMultiplier=e.timeoutMultiplier??Yb,this.minTimeout=e.minTimeout??Qb,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),s=Ft([e.signal,n]);return s.start=Date.now(),s.timeout=t,s}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Ju=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ue(),this.haveNext=ue()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ue(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ue(),await ir(this.readNext.promise,t?.signal,t)}};function wm(){return new Ju}var Na=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Qu=class extends Error{code;constructor(e,t){super(e),this.code=t}},ef=class extends Qu{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Da(r,e){let t=wm();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let s=new ye;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new ef("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new ye:d}for(;s.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Na("unexpected end of input");s.append(f)}let u=s.sublist(0,i);return s.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield s:yield*s,yield*i}()}return r}}}var ex=1e4,tx="1.0.0",rx="ping",nx="ipfs",bm=32,sx=!0,Ra=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??nx}/${rx}/${tx}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??ex,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??sx,this.timeout=new Pa({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Fn]=["@libp2p/connection-monitor"];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{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=Da(s);t=Date.now(),await Promise.all([o.write(fn(bm),{signal:n}),o.read(bm,{signal:n})]),e.rtt=Date.now()-t,await o.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;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(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function ox(r){return r[Symbol.asyncIterator]!=null}function ix(...r){let e=[];for(let t of r)ox(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ea({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Fs=ix;var Ma=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()}),getAttributesFromYieldedValue:(n,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");let n=this,s=new _r;for await(let o of Fs(...n.routers.map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new bt;await Promise.all(this.routers.map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new bt;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Oa=globalThis.CustomEvent??Event;async function*tf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,s=new EventTarget,o=[],i=ue(),a=ue(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(i=ue(),await i.promise),u)break;let g={done:!1};o.push(g),p().then(h=>{g.done=!0,g.ok=!0,g.value=h,s.dispatchEvent(new Oa("task-complete"))},h=>{g.done=!0,g.err=h,s.dispatchEvent(new Oa("task-complete"))})}c=!0,s.dispatchEvent(new Oa("task-complete"))}catch(p){l=p,s.dispatchEvent(new Oa("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(p=>p.done)}function*d(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*m(){for(;f();)for(let p=0;p<o.length;p++)if(o[p].done){let g=o[p];if(o.splice(p,1),p--,g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=ue(),await a.promise),l!=null)throw l;if(n?yield*d():yield*m(),c&&o.length===0)break}}var Ua=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,key:z(n,"base36")}),getAttributesFromYieldedValue:(n,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Ms("No peer routers available");if(e.toString()===this.peerId.toString())throw new ca("Should not try to find self");let n=this,s=Fs(...this.routers.map(o=>async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),o;throw new js}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ms("No peer routers available");let n=this,s=_s(1024);for await(let o of tf(async function*(){let i=Fs(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};var Fa=class extends xt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),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}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ft([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await Ln(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Ft([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=fn(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await ir(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("random walk errored",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var rf=32,nf=64,Va=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new la(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new ua(`Handler already registered for protocol ${e}`);let s=Ti.bind({ignoreUndefined:!0})({maxInboundStreams:rf,maxOutboundStreams:nf},n);this.handlers.set(e,{handler:t,options:s}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new D("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let s of n.protocols){let o=this.topologies.get(s);if(o!=null)for(let i of o.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));for(let o of s){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,s=e.detail.peerId;for(let o of t){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),a.onConnect?.(s,n))}}};var sf=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function xm(r){let{name:e,metrics:t}=r,n;return t!=null?n=new sf({name:e,metrics:t}):n=new Map,n}var Ha=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=xm({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??cr.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new D("Transport must have a valid tag");if(this.transports.has(t))throw new D(`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(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let s=n.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new ha(`No transport available for address ${String(e)}`);return t?.onProgress?.(new fe("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new bt("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={unsupportedAddresses:new Set(e.map(o=>o.toString())),ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}},n=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Cu.matches(c)?t.ipv4.attempts++:Iu.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.unsupportedAddresses.delete(c.toString()),Cu.matches(c)&&t.ipv4.success++,Iu.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,f),f}))}}let s=await Promise.allSettled(n);if(!(s.length>0&&s.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===cr.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new kn(`No configured transport could listen on these addresses, please remove them from your config: ${[...t.unsupportedAddresses].join(", ")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let s=t.pop();s!=null&&n.push(s.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Se="/multistream/1.0.0";var Ka=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},$a=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},qa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Vs(r,e={}){let t=Da(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??st,s=e?.lengthEncoder??Be;return{read:async i=>{let a=-1,c=new ye;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Ka("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new qa("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new $a("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new ye(s(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ye(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var ax=N(`
7
7
  `);async function Ur(r,e,t){await r.write(e,t)}async function vm(r,e,t){await r.writeV(e,t)}async function cx(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==ax[0])throw e.log.error("Invalid mss message - missing newline",t),new Ys("Missing newline");return t.sublist(0,-1)}async function ar(r,e){let t=await cx(r,e);return z(t.subarray())}async function Hs(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return lx(r,e[0],t);let n=Vs(r,{...t,maxDataLength:1024}),s=e.shift();if(s==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Se,s);let o=N(`${Se}
8
8
  `),i=N(`${s}
9
9
  `);await vm(n,[o,i],t),t.log.trace("select: reading multistream-select header");let a=await ar(n,t);if(t.log.trace('select: read "%s"',a),a===Se&&(t.log.trace("select: reading protocol response"),a=await ar(n,t),t.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(let c of e){t.log.trace('select: write "%s"',c),await Ur(n,N(`${c}
@@ -16,7 +16,7 @@ ${e.join(`
16
16
  `),t),t.log.trace('handle: responded with "%s" for "%s"',s,s),{stream:n.unwrap(),protocol:s};if(s==="ls"){let o=new ye(...e.map(i=>Xa.single(N(`${i}
17
17
  `))),N(`
18
18
  `));t.log.trace('handle: respond with "%s" for %s',e,s),await Ur(n,o,t),t.log.trace('handle: responded with "%s" for %s',e,s);continue}t.log.trace('handle: respond with "na" for "%s"',s),await Ur(n,N(`na
19
- `),t),t.log('handle: responded with "na" for "%s"',s)}}var dx=500,lf=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:s,close:o,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,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}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=s,this._close=o,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[wf]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Ws("the connection is being closed");if(this.status==="closed")throw new Kr("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new zr("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(dx);e={...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(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(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())}};function Sm(r){return new lf(r)}function px(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return rf}function mx(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??nf}function _m(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var Ya=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new fa(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Ft([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,s=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new da("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",{...t,signal:s})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),o}finally{s.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),s;n!=null&&(s=gt(n),await this.shouldBlockConnection("denyOutboundConnection",s,e));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let s,o,i,a,c;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),l=await u.protect(e,n))}try{if(s=l,n?.skipEncryption!==!0){n?.onProgress?.(new fe(`upgrader:encrypt-${t}-connection`)),{conn:s,remotePeer:o,protocol:c}=await(t==="inbound"?this._encryptInbound(l,n):this._encryptOutbound(l,n));let u={...l,...s};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,u)}else{let u=e.remoteAddr.getPeerId();if(u==null)throw new Vt(`${t} connection that skipped encryption must have a peer id`);let f=gt(u);c="native",o=f}if(o.equals(this.components.peerId)){let u=new $r("Can not dial self");throw e.abort(u),u}if(i=s,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new fe(`upgrader:multiplex-${t}-connection`));let u=await(t==="inbound"?this._multiplexInbound({...l,...s},this.streamMuxers,n):this._multiplexOutbound({...l,...s},this.streamMuxers,n));a=u.muxerFactory,i=u.stream}}catch(u){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,u),u}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:o,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:s,upgradedConn:o,remotePeer:i,muxerFactory:a,limits:c}=e,l,u,f;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{f!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),h=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:w,protocol:x}=await $s(p,g,{signal:h,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",x);let y=px(x,this.components.registrar);if(_m(x,"inbound",f)===y){let _=new Qs(`Too many inbound protocol streams for protocol "${x}" - limit ${y}`);throw p.abort(_),_}p.source=w.source,p.sink=w.sink,p.protocol=x,w.closeWrite!=null&&(p.closeWrite=w.closeWrite),w.closeRead!=null&&(p.closeRead=w.closeRead),w.close!=null&&(p.close=w.close),await this.components.peerStore.merge(i,{protocols:[x]}),this.components.metrics?.trackProtocolStream(p,f),this._onStream({connection:f,stream:p,protocol:x})}).catch(async g=>{f.log.error("error handling incoming stream id %s - %e",p.id,g),p.timeline.close==null&&await p.close()})}}),u=async(p,g={})=>{if(l==null)throw new Rr("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",p);let h=await l.newStream();f.log.trace("started new stream %s for protocols %s",h.id,p);try{if(g.signal==null){h.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let _=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:_}}h.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:x}=await Hs(h,p,{...g,log:h.log,yieldBytes:!0});h.log.trace("selected protocol %s",x);let y=mx(x,this.components.registrar,g),E=_m(x,"outbound",f);if(E>=y){let _=new eo(`Too many outbound protocol streams for protocol "${x}" - ${E}/${y}`);throw h.abort(_),_}return await this.components.peerStore.merge(i,{protocols:[x]}),h.source=w.source,h.sink=w.sink,h.protocol=x,w.closeWrite!=null&&(h.closeWrite=w.closeWrite),w.closeRead!=null&&(h.closeRead=w.closeRead),w.close!=null&&(h.close=w.close),this.components.metrics?.trackProtocolStream(h,f),h}catch(w){throw f.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,w),h.timeline.close==null&&h.abort(w),w}},Promise.all([l.sink(o.source),o.sink(l.source)]).catch(p=>{f.log.error("error piping data through muxer - %e",p)}));let d=s.timeline;s.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(g){f.log.error("error closing connection after timeline close %e",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(g=>{f.log.error("error thrown while dispatching connection:close event %e",g)}),Reflect.set(...p))}),s.timeline.upgraded=Date.now();let m=()=>{throw new Rr("Connection is not multiplexed")};return f=Sm({remoteAddr:s.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:s.timeline,multiplexer:l?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:u??m,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await s.close(p)},abort:p=>{s.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f.__maConnTimeline=d,f}_onStream(e){let{connection:t,stream:n,protocol:s}=e,{handler:o,options:i}=this.components.registrar.getHandler(s);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new zr("Cannot open protocol stream on limited connection");o({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:s,protocol:o}=await $s(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(o);if(i==null)throw new Mr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await i.secureInbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,s),new Mr(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:s,protocol:o}=await Hs(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(o);if(i==null)throw new Mr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await i.secureOutbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,s),new Mr(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let{stream:o,protocol:i}=await Hs(e,s,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new Rr(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{let{stream:o,protocol:i}=await $s(e,s,{...n,log:e.log}),a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new Rr(String(o))}}};var Ja="2.7.3-e1f868f03",Qa="js-libp2p";function Im(r,e){return`${r??Qa}/${e??Ja} browser/${globalThis.navigator.userAgent}`}var ec=class extends xt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new xt,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??Di(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=e.nodeInfo?.name??Qa,o=e.nodeInfo?.version??Ja,i=this.components=Qp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:o,userAgent:e.nodeInfo?.userAgent??Im(s,o)},logger:this.logger,events:t,datastore:e.datastore??new ji,connectionGater:tm(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",Mp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Ya(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Ha(this.components,e.transportManager)),this.configureComponent("connectionManager",new La(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Ra(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Va(this.components)),this.configureComponent("addressManager",new oa(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ua(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ma(this.components,{routers:c})),this.configureComponent("randomWalk",new Fa(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[rc]!=null&&(this.log("registering service %s for content routing",l),c.push(f[rc])),f[sc]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[sc])),f[nc]!=null&&(this.log("registering service %s for peer discovery",l),f[nc].addEventListener?.("peer",d=>{this.#e(d)}))}em(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),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(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),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(){let e=new _r;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){rr(e)&&(e=gt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Fe([N("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=hn(s);return await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function gx(r={}){r.privateKey??=await Ph("Ed25519");let e=new ec({...await mp(r),peerId:Mh(r.privateKey)});return r.start!==!1&&await e.start(),e}return Hm(yx);})();
19
+ `),t),t.log('handle: responded with "na" for "%s"',s)}}var dx=500,lf=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:s,close:o,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,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}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=s,this._close=o,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[wf]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Ws("the connection is being closed");if(this.status==="closed")throw new Kr("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new zr("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(dx);e={...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(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(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())}};function Sm(r){return new lf(r)}function px(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return rf}function mx(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??nf}function _m(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var Ya=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new fa(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Ft([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,s=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new da("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",{...t,signal:s})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),o}finally{s.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),s;n!=null&&(s=gt(n),await this.shouldBlockConnection("denyOutboundConnection",s,e));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let s,o,i,a,c;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),l=await u.protect(e,n))}try{if(s=l,n?.skipEncryption!==!0){n?.onProgress?.(new fe(`upgrader:encrypt-${t}-connection`)),{conn:s,remotePeer:o,protocol:c}=await(t==="inbound"?this._encryptInbound(l,n):this._encryptOutbound(l,n));let u={...l,...s};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,u)}else{let u=e.remoteAddr.getPeerId();if(u==null)throw new Vt(`${t} connection that skipped encryption must have a peer id`);let f=gt(u);c="native",o=f}if(o.equals(this.components.peerId)){let u=new $r("Can not dial self");throw e.abort(u),u}if(i=s,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new fe(`upgrader:multiplex-${t}-connection`));let u=await(t==="inbound"?this._multiplexInbound({...l,...s},this.streamMuxers,n):this._multiplexOutbound({...l,...s},this.streamMuxers,n));a=u.muxerFactory,i=u.stream}}catch(u){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,u),u}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:o,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:s,upgradedConn:o,remotePeer:i,muxerFactory:a,limits:c}=e,l,u,f;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{f!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),h=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:w,protocol:x}=await $s(p,g,{signal:h,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",x);let y=px(x,this.components.registrar);if(_m(x,"inbound",f)===y){let _=new Qs(`Too many inbound protocol streams for protocol "${x}" - limit ${y}`);throw p.abort(_),_}p.source=w.source,p.sink=w.sink,p.protocol=x,w.closeWrite!=null&&(p.closeWrite=w.closeWrite),w.closeRead!=null&&(p.closeRead=w.closeRead),w.close!=null&&(p.close=w.close),await this.components.peerStore.merge(i,{protocols:[x]}),this.components.metrics?.trackProtocolStream(p,f),this._onStream({connection:f,stream:p,protocol:x})}).catch(async g=>{f.log.error("error handling incoming stream id %s - %e",p.id,g),p.timeline.close==null&&await p.close()})}}),u=async(p,g={})=>{if(l==null)throw new Rr("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",p);let h=await l.newStream();f.log.trace("started new stream %s for protocols %s",h.id,p);try{if(g.signal==null){h.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let _=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:_}}h.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:x}=await Hs(h,p,{...g,log:h.log,yieldBytes:!0});h.log.trace("selected protocol %s",x);let y=mx(x,this.components.registrar,g),E=_m(x,"outbound",f);if(E>=y){let _=new eo(`Too many outbound protocol streams for protocol "${x}" - ${E}/${y}`);throw h.abort(_),_}return await this.components.peerStore.merge(i,{protocols:[x]}),h.source=w.source,h.sink=w.sink,h.protocol=x,w.closeWrite!=null&&(h.closeWrite=w.closeWrite),w.closeRead!=null&&(h.closeRead=w.closeRead),w.close!=null&&(h.close=w.close),this.components.metrics?.trackProtocolStream(h,f),h}catch(w){throw f.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,w),h.timeline.close==null&&h.abort(w),w}},Promise.all([l.sink(o.source),o.sink(l.source)]).catch(p=>{f.log.error("error piping data through muxer - %e",p)}));let d=s.timeline;s.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(g){f.log.error("error closing connection after timeline close %e",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(g=>{f.log.error("error thrown while dispatching connection:close event %e",g)}),Reflect.set(...p))}),s.timeline.upgraded=Date.now();let m=()=>{throw new Rr("Connection is not multiplexed")};return f=Sm({remoteAddr:s.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:s.timeline,multiplexer:l?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:u??m,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await s.close(p)},abort:p=>{s.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f.__maConnTimeline=d,f}_onStream(e){let{connection:t,stream:n,protocol:s}=e,{handler:o,options:i}=this.components.registrar.getHandler(s);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new zr("Cannot open protocol stream on limited connection");o({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:s,protocol:o}=await $s(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(o);if(i==null)throw new Mr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await i.secureInbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,s),new Mr(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:s,protocol:o}=await Hs(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(o);if(i==null)throw new Mr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await i.secureOutbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,s),new Mr(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let{stream:o,protocol:i}=await Hs(e,s,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new Rr(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{let{stream:o,protocol:i}=await $s(e,s,{...n,log:e.log}),a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new Rr(String(o))}}};var Ja="2.7.3-e2f49432b",Qa="js-libp2p";function Im(r,e){return`${r??Qa}/${e??Ja} browser/${globalThis.navigator.userAgent}`}var ec=class extends xt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new xt,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??Di(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=e.nodeInfo?.name??Qa,o=e.nodeInfo?.version??Ja,i=this.components=Qp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:o,userAgent:e.nodeInfo?.userAgent??Im(s,o)},logger:this.logger,events:t,datastore:e.datastore??new ji,connectionGater:tm(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",Mp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Ya(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Ha(this.components,e.transportManager)),this.configureComponent("connectionManager",new La(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Ra(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Va(this.components)),this.configureComponent("addressManager",new oa(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ua(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ma(this.components,{routers:c})),this.configureComponent("randomWalk",new Fa(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[rc]!=null&&(this.log("registering service %s for content routing",l),c.push(f[rc])),f[sc]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[sc])),f[nc]!=null&&(this.log("registering service %s for peer discovery",l),f[nc].addEventListener?.("peer",d=>{this.#e(d)}))}em(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),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(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),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(){let e=new _r;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){rr(e)&&(e=gt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Fe([N("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=hn(s);return await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function gx(r={}){r.privateKey??=await Ph("Ed25519");let e=new ec({...await mp(r),peerId:Mh(r.privateKey)});return r.start!==!1&&await e.start(),e}return Hm(yx);})();
20
20
  /*! Bundled license information:
21
21
 
22
22
  pvtsutils/build/index.js: