libp2p 2.1.6 → 2.1.7

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/README.md CHANGED
@@ -74,14 +74,6 @@ We are in the process of writing better documentation, blog posts, tutorials and
74
74
 
75
75
  To sum up, libp2p is a "network stack" -- a protocol suite -- that cleanly separates concerns, and enables sophisticated applications to only use the protocols they absolutely need, without giving up interoperability and upgradeability. libp2p grew out of IPFS, but it is built so that lots of people can use it, for lots of different projects.
76
76
 
77
- # Roadmap
78
-
79
- The js-libp2p roadmap can be found here: <https://github.com/libp2p/js-libp2p/blob/main/ROADMAP.md>
80
-
81
- It represents current projects the js-libp2p maintainers are focused on and provides an estimation of completion targets.
82
-
83
- It is complementary to the overarching libp2p project roadmap: <https://github.com/libp2p/specs/blob/master/ROADMAP.md>
84
-
85
77
  # Usage
86
78
 
87
79
  ### Configuration
package/dist/index.min.js CHANGED
@@ -3,7 +3,7 @@
3
3
  `).map(o=>` ${o}`).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} :`}};th=Qt;k.Constructed=th;Qt.NAME="CONSTRUCTED";var ms=class extends Le{fromBER(e,t,n){return t}toBER(e){return ct}};ms.override="EndOfContentValueBlock";var rh,gs=class extends Se{constructor(e={}){super(e,ms),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};rh=gs;k.EndOfContent=rh;gs.NAME=zn;var nh,Qr=class extends Se{constructor(e={}){super(e,Le),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 o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};nh=Qr;k.Null=nh;Qr.NAME="NULL";var ys=class extends Pt(Le){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=q.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 o=q.BufferSourceConverter.toUint8Array(e);return Nt(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,jc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ys.NAME="BooleanValueBlock";var oh,ws=class extends Se{constructor(e={}){super(e,ys),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}`}};oh=ws;k.Boolean=oh;ws.NAME="BOOLEAN";var bs=class extends Pt(pt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=pt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===zn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Yf)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?pt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};bs.NAME="OctetStringValueBlock";var sh,xs=class r extends Se{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},bs),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 s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=js(s,0,s.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} : ${q.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 q.BufferSourceConverter.concat(e)}};sh=xs;k.OctetString=sh;xs.NAME=Yf;var vs=class extends Pt(pt){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 o=-1;if(this.isConstructed){if(o=pt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===zn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Jf)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=q.BufferSourceConverter.toUint8Array(e);if(!Nt(this,s,t,n))return-1;let i=s.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=js(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 pt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ct;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}}};vs.NAME="BitStringValueBlock";var ih,en=class extends Se{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},vs),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 o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};ih=en;k.BitString=ih;en.NAME=Jf;var ah;function M0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=cs(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=cs(t,s)),s}function Xf(r){if(r>=Kn.length)for(let e=Kn.length;e<=r;e++){let t=new Uint8Array([0]),n=Kn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=cs(t,n)),Kn.push(n)}return Kn[r]}function U0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Gn=class extends Pt(Le){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=jc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Wf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}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 o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}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,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=U0(Xf(n),t),i="-";break;default:t=M0(t,Xf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Zf.charAt(t[c]));return a===!1&&(i+=Zf.charAt(0)),i}};ah=Gn;Gn.NAME="IntegerValueBlock";Object.defineProperty(ah.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var ch,_e=class r extends Se{constructor(e={}){super(e,Gn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return ls(),BigInt(this.valueBlock.toString())}static fromBigInt(e){ls();let t=BigInt(e),n=new qn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+t,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);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()}`}};ch=_e;k.Integer=ch;_e.NAME="INTEGER";var lh,Es=class extends _e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};lh=Es;k.Enumerated=lh;Es.NAME="ENUMERATED";var Wn=class extends Pt(Le){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 o=q.BufferSourceConverter.toUint8Array(e);if(!Nt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(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=wr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){ls();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+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 o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ct;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=q.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}}};Wn.NAME="sidBlock";var As=class extends Le{constructor({value:e=rn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ct;t.push(o)}return Zc(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){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(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Wn;if(o>Number.MAX_SAFE_INTEGER){ls();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!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 o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}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}};As.NAME="ObjectIdentifierValueBlock";var uh,tn=class extends Se{constructor(e={}){super(e,As),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()}}};uh=tn;k.ObjectIdentifier=uh;tn.NAME="OBJECT IDENTIFIER";var jn=class extends Pt(kt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Nt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(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=wr(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 o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ct;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};jn.NAME="relativeSidBlock";var Ss=class extends Le{constructor({value:e=rn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new jn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,ct;n.push(s)}return Zc(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new jn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}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 o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}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}};Ss.NAME="RelativeObjectIdentifierValueBlock";var fh,_s=class extends Se{constructor(e={}){super(e,Ss),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()}}};fh=_s;k.RelativeObjectIdentifier=fh;_s.NAME="RelativeObjectIdentifier";var hh,Tt=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};hh=Tt;k.Sequence=hh;Tt.NAME="SEQUENCE";var dh,Bs=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};dh=Bs;k.Set=dh;Bs.NAME="SET";var Is=class extends Pt(Le){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=rn}toJSON(){return{...super.toJSON(),value:this.value}}};Is.NAME="StringValueBlock";var Cs=class extends Is{};Cs.NAME="SimpleStringValueBlock";var Oe=class extends hs{constructor({...e}={}){super(e,Cs)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Oe.NAME="SIMPLE STRING";var ks=class extends Oe{fromBuffer(e){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=q.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(e)),this.valueBlock.value=e}};ks.NAME="Utf8StringValueBlock";var ph,Lt=class extends ks{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};ph=Lt;k.Utf8String=ph;Lt.NAME="UTF8String";var Ts=class extends Oe{fromBuffer(e){this.valueBlock.value=q.Convert.ToUtf16String(e),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(e))}};Ts.NAME="BmpStringValueBlock";var mh,Ls=class extends Ts{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};mh=Ls;k.BmpString=mh;Ls.NAME="BMPString";var Ns=class extends Oe{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+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 o=0;o<t;o++){let s=Jt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};Ns.NAME="UniversalStringValueBlock";var gh,Ps=class extends Ns{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};gh=Ps;k.UniversalString=gh;Ps.NAME="UniversalString";var yh,Rs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};yh=Rs;k.NumericString=yh;Rs.NAME="NumericString";var wh,Ds=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};wh=Ds;k.PrintableString=wh;Ds.NAME="PrintableString";var bh,Ms=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};bh=Ms;k.TeletexString=bh;Ms.NAME="TeletexString";var xh,Us=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};xh=Us;k.VideotexString=xh;Us.NAME="VideotexString";var vh,Os=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};vh=Os;k.IA5String=vh;Os.NAME="IA5String";var Eh,Fs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Eh=Fs;k.GraphicString=Eh;Fs.NAME="GraphicString";var Ah,Zn=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Ah=Zn;k.VisibleString=Ah;Zn.NAME="VisibleString";var Sh,Vs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Sh=Vs;k.GeneralString=Sh;Vs.NAME="GeneralString";var _h,Hs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};_h=Hs;k.CharacterString=_h;Hs.NAME="CharacterString";var Bh,Xn=class extends Zn{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 o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}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,q.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);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 o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,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}}};Bh=Xn;k.UTCTime=Bh;Xn.NAME="UTCTime";var Ih,$s=class extends Xn{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="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.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 l=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.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}}};Ih=$s;k.GeneralizedTime=Ih;$s.NAME="GeneralizedTime";var Ch,Ks=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Ch=Ks;k.DATE=Ch;Ks.NAME="DATE";var kh,qs=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};kh=qs;k.TimeOfDay=kh;qs.NAME="TimeOfDay";var Th,zs=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Th=zs;k.DateTime=Th;zs.NAME="DateTime";var Lh,Gs=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Lh=Gs;k.Duration=Lh;Gs.NAME="Duration";var Nh,Ws=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Nh=Ws;k.TIME=Nh;Ws.NAME="TIME";function H(r,e="utf8"){let t=ns[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function nn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return Gr(r)}var Yn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Jn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Zs=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ph={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Zs("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=Ph;async function Rh(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 F0(e);return{privateKey:t[0],publicKey:t[1]}}async function Dh(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 Mh(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 F0(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 Jc(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return P(r.n,"base64url").length*8}var on=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Qn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return ge.createV1(114,this._multihash)}toString(){return W.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 Mh(this._key,t,e)}},eo=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Qn.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return Dh(this._key,e)}};var Xs=8192,Qc=18;function Uh(r){let{result:e}=Yc(r),t=e.valueBlock.value;return{n:H(mt(t[1].toBigInt()),"base64url"),e:H(mt(t[2].toBigInt()),"base64url"),d:H(mt(t[3].toBigInt()),"base64url"),p:H(mt(t[4].toBigInt()),"base64url"),q:H(mt(t[5].toBigInt()),"base64url"),dp:H(mt(t[6].toBigInt()),"base64url"),dq:H(mt(t[7].toBigInt()),"base64url"),qi:H(mt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function V0(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 _e({value:0}),_e.fromBigInt(gt(P(r.n,"base64url"))),_e.fromBigInt(gt(P(r.e,"base64url"))),_e.fromBigInt(gt(P(r.d,"base64url"))),_e.fromBigInt(gt(P(r.p,"base64url"))),_e.fromBigInt(gt(P(r.q,"base64url"))),_e.fromBigInt(gt(P(r.dp,"base64url"))),_e.fromBigInt(gt(P(r.dq,"base64url"))),_e.fromBigInt(gt(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Oh(r){let{result:e}=Yc(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:H(mt(t[0].toBigInt()),"base64url"),e:H(mt(t[1].toBigInt()),"base64url")}}function el(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let t=new Tt({value:[new Tt({value:[new tn({value:"1.2.840.113549.1.1.1"}),new Qr]}),new en({valueHex:new Tt({value:[_e.fromBigInt(gt(P(r.n,"base64url"))),_e.fromBigInt(gt(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function mt(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function gt(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 Fh(r){let e=Uh(r);return Vh(e)}function tl(r){let e=Oh(r);if(Jc(e)>Xs)throw new Rr("Key size is too large");let t=Yr(dt.encode({Type:we.RSA,Data:r})),n=tt(Qc,t);return new on(e,n)}function Vh(r){if(Jc(r)>Xs)throw new D("Key size is too large");let e=Hh(r),t=Yr(dt.encode({Type:we.RSA,Data:el(e.publicKey)})),n=tt(Qc,t);return new eo(e.privateKey,new on(e.publicKey,n))}async function rl(r){if(r>Xs)throw new D("Key size is too large");let e=await Rh(r),t=Yr(dt.encode({Type:we.RSA,Data:el(e.publicKey)})),n=tt(Qc,t);return new eo(e.privateKey,new on(e.publicKey,n))}function Hh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Ys=class extends zr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,lf(e);let n=Pn(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return qr(this),this.iHash.update(e),this}digestInto(e){qr(this),Kr(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:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,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()}},nl=(r,e,t)=>new Ys(r,e).update(t).digest();nl.create=(r,e)=>new Ys(r,e);function $h(r){r.lowS!==void 0&&ot("lowS",r.lowS),r.prehash!==void 0&&ot("prehash",r.prehash)}function H0(r){let e=Mn(r);ft(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:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("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("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:$0,hexToBytes:K0}=Wo,Rt={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Rt;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,o=lr(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?lr(o.length/2|128):"";return`${lr(r)}${s}${o}${e}`},decode(r,e){let{Err:t}=Rt,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 o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&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 u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;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}=Rt;if(r<Dt)throw new e("integer: negative integers are not allowed");let t=lr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected assertion");return t},decode(r){let{Err:e}=Rt;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 $0(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Rt,o=typeof r=="string"?K0(r):r;jr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("Invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Rt,n=`${e.encode(2,t.encode(r.r))}${e.encode(2,t.encode(r.s))}`;return e.encode(48,n)}},Dt=BigInt(0),Ee=BigInt(1),u2=BigInt(2),Kh=BigInt(3),f2=BigInt(4);function q0(r){let e=H0(r),{Fp:t}=e,n=jt(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return It(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),s=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function i(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Rn(m,Ee,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(zt(m)&&(m=_t(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:Bt(le("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(x=J(x,w)),$e("private key",x,Ee,w),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=hr((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(w));let A=t.mul(y,g),_=t.mul(b,g),v=t.mul(w,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),l=hr(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=i(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(b)?d.ZERO:new d(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(d.fromAffine)}static fromHex(g){let y=d.fromAffine(s(le("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,y){return Xo(d,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){l(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.eql(t.mul(y,_),t.mul(x,w)),B=t.eql(t.mul(b,_),t.mul(A,w));return v&&B}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,Kh),{px:w,py:x,pz:A}=this,_=t.ZERO,v=t.ZERO,B=t.ZERO,T=t.mul(w,w),re=t.mul(x,x),V=t.mul(A,A),F=t.mul(w,x);return F=t.add(F,F),B=t.mul(w,A),B=t.add(B,B),_=t.mul(g,B),v=t.mul(b,V),v=t.add(_,v),_=t.sub(re,v),v=t.add(re,v),v=t.mul(_,v),_=t.mul(F,_),B=t.mul(b,B),V=t.mul(g,V),F=t.sub(T,V),F=t.mul(g,F),F=t.add(F,B),B=t.add(T,T),T=t.add(B,T),T=t.add(T,V),T=t.mul(T,F),v=t.add(v,T),V=t.mul(x,A),V=t.add(V,V),T=t.mul(V,F),_=t.sub(_,T),B=t.mul(V,re),B=t.add(B,B),B=t.add(B,B),new d(_,v,B)}add(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.ZERO,B=t.ZERO,T=t.ZERO,re=e.a,V=t.mul(e.b,Kh),F=t.mul(y,x),R=t.mul(b,A),C=t.mul(w,_),L=t.add(y,b),S=t.add(x,A);L=t.mul(L,S),S=t.add(F,R),L=t.sub(L,S),S=t.add(y,w);let E=t.add(x,_);return S=t.mul(S,E),E=t.add(F,C),S=t.sub(S,E),E=t.add(b,w),v=t.add(A,_),E=t.mul(E,v),v=t.add(R,C),E=t.sub(E,v),T=t.mul(re,S),v=t.mul(V,C),T=t.add(v,T),v=t.sub(R,T),T=t.add(R,T),B=t.mul(v,T),R=t.add(F,F),R=t.add(R,F),C=t.mul(re,C),S=t.mul(V,S),R=t.add(R,C),C=t.sub(F,C),C=t.mul(re,C),S=t.add(S,C),F=t.mul(R,S),B=t.add(B,F),F=t.mul(E,S),v=t.mul(L,v),v=t.sub(v,F),F=t.mul(L,R),T=t.mul(E,T),T=t.add(T,F),new d(v,B,T)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){$e("scalar",g,Dt,e.n);let y=d.ZERO;if(g===Dt)return y;if(g===Ee)return this;let{endo:b}=e;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:x,k2neg:A,k2:_}=b.splitScalar(g),v=y,B=y,T=this;for(;x>Dt||_>Dt;)x&Ee&&(v=v.add(T)),_&Ee&&(B=B.add(T)),T=T.double(),x>>=Ee,_>>=Ee;return w&&(v=v.negate()),A&&(B=B.negate()),B=new d(t.mul(B.px,b.beta),B.py,B.pz),v.add(B)}multiply(g){let{endo:y,n:b}=e;$e("scalar",g,Ee,b);let w,x;if(y){let{k1neg:A,k1:_,k2neg:v,k2:B}=y.splitScalar(g),{p:T,f:re}=this.wNAF(_),{p:V,f:F}=this.wNAF(B);T=p.constTimeNegate(A,T),V=p.constTimeNegate(v,V),V=new d(t.mul(V.px,y.beta),V.py,V.pz),w=T.add(V),x=re.add(F)}else{let{p:A,f:_}=this.wNAF(g);w=A,x=_}return d.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=d.BASE,x=(_,v)=>v===Dt||v===Ee||!_.equals(w)?_.multiplyUnsafe(v):_.multiply(v),A=x(this,y).add(x(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===Ee)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===Ee?this:y?y(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return ot("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return ot("isCompressed",g),_t(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,p=Zo(d,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function z0(r){let e=Mn(r);return ft(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function qh(r){let e=z0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(C){return J(C,n)}function a(C){return jo(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=q0({...e,toBytes(C,L,S){let E=L.toAffine(),I=t.toBytes(E.x),N=It;return ot("isCompressed",S),S?N(Uint8Array.from([L.hasEvenY()?2:3]),I):N(Uint8Array.from([4]),I,t.toBytes(E.y))},fromBytes(C){let L=C.length,S=C[0],E=C.subarray(1);if(L===o&&(S===2||S===3)){let I=Bt(E);if(!Rn(I,Ee,t.ORDER))throw new Error("Point is not on curve");let N=f(I),M;try{M=t.sqrt(N)}catch(z){let K=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+K)}let U=(M&Ee)===Ee;return(S&1)===1!==U&&(M=t.neg(M)),{x:I,y:M}}else if(L===s&&S===4){let I=t.fromBytes(E.subarray(0,t.BYTES)),N=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:I,y:N}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=C=>_t(Wt(C,e.nByteLength));function h(C){let L=n>>Ee;return C>L}function p(C){return h(C)?i(-C):C}let m=(C,L,S)=>Bt(C.slice(L,S));class g{constructor(L,S,E){this.r=L,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(L){let S=e.nByteLength;return L=le("compactSignature",L,S*2),new g(m(L,0,S),m(L,S,2*S))}static fromDER(L){let{r:S,s:E}=Rt.toSig(le("DER",L));return new g(S,E)}assertValidity(){$e("r",this.r,Ee,n),$e("s",this.s,Ee,n)}addRecoveryBit(L){return new g(this.r,this.s,L)}recoverPublicKey(L){let{r:S,s:E,recovery:I}=this,N=_(le("msgHash",L));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");let M=I===2||I===3?S+e.n:S;if(M>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=I&1?"03":"02",$=c.fromHex(U+d(M)),z=a(M),K=i(-N*z),Y=i(E*z),Q=c.BASE.multiplyAndAddUnsafe($,K,Y);if(!Q)throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return ur(this.toDERHex())}toDERHex(){return Rt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ur(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(C){try{return u(C),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let C=ac(e.n);return Ef(e.randomBytes(C),e.n)},precompute(C=8,L=c.BASE){return L._setWindowSize(C),L.multiply(BigInt(3)),L}};function b(C,L=!0){return c.fromPrivateKey(C).toRawBytes(L)}function w(C){let L=zt(C),S=typeof C=="string",E=(L||S)&&C.length;return L?E===o||E===s:S?E===2*o||E===2*s:C instanceof c}function x(C,L,S=!0){if(w(C))throw new Error("first arg must be private key");if(!w(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(u(C)).toRawBytes(S)}let A=e.bits2int||function(C){let L=Bt(C),S=C.length*8-e.nBitLength;return S>0?L>>BigInt(S):L},_=e.bits2int_modN||function(C){return i(A(C))},v=Dn(e.nBitLength);function B(C){return $e(`num < 2^${e.nBitLength}`,C,Dt,v),Wt(C,e.nByteLength)}function T(C,L,S=re){if(["recovered","canonical"].some(ve=>ve in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:I}=e,{lowS:N,prehash:M,extraEntropy:U}=S;N==null&&(N=!0),C=le("msgHash",C),$h(S),M&&(C=le("prehashed msgHash",E(C)));let $=_(C),z=u(L),K=[B(z),B($)];if(U!=null&&U!==!1){let ve=U===!0?I(t.BYTES):U;K.push(le("extraEntropy",ve))}let Y=It(...K),Q=$;function xe(ve){let Ae=A(ve);if(!l(Ae))return;let Pe=a(Ae),me=c.BASE.multiply(Ae).toAffine(),He=i(me.x);if(He===Dt)return;let wt=i(Pe*i(Q+He*z));if(wt===Dt)return;let Sn=(me.x===He?0:2)|Number(me.y&Ee),_n=wt;return N&&h(wt)&&(_n=p(wt),Sn^=1),new g(He,_n,Sn)}return{seed:Y,k2sig:xe}}let re={lowS:e.lowS,prehash:!1},V={lowS:e.lowS,prehash:!1};function F(C,L,S=re){let{seed:E,k2sig:I}=T(C,L,S),N=e;return nc(N.hash.outputLen,N.nByteLength,N.hmac)(E,I)}c.BASE._setWindowSize(8);function R(C,L,S,E=V){let I=C;if(L=le("msgHash",L),S=le("publicKey",S),"strict"in E)throw new Error("options.strict was renamed to lowS");$h(E);let{lowS:N,prehash:M}=E,U,$;try{if(typeof I=="string"||zt(I))try{U=g.fromDER(I)}catch(me){if(!(me instanceof Rt.Err))throw me;U=g.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){let{r:me,s:He}=I;U=new g(me,He)}else throw new Error("PARSE");$=c.fromHex(S)}catch(me){if(me.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(N&&U.hasHighS())return!1;M&&(L=e.hash(L));let{r:z,s:K}=U,Y=_(L),Q=a(K),xe=i(Y*Q),ve=i(z*Q),Ae=c.BASE.multiplyAndAddUnsafe($,xe,ve)?.toAffine();return Ae?i(Ae.x)===z:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:F,verify:R,ProjectivePoint:c,Signature:g,utils:y}}function G0(r){return{hash:r,hmac:(e,...t)=>nl(r,e,Za(...t)),randomBytes:Gr}}function zh(r,e){let t=n=>qh({...r,...G0(n)});return Object.freeze({...t(e),create:t})}var jh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Gh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),W0=BigInt(1),ol=BigInt(2),Wh=(r,e)=>(r+e/ol)/e;function j0(r){let e=jh,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=oe(f,t,e)*f%e,d=oe(l,t,e)*f%e,h=oe(d,ol,e)*u%e,p=oe(h,o,e)*h%e,m=oe(p,s,e)*p%e,g=oe(m,a,e)*m%e,y=oe(g,c,e)*g%e,b=oe(y,a,e)*m%e,w=oe(b,t,e)*f%e,x=oe(w,i,e)*p%e,A=oe(x,n,e)*u%e,_=oe(A,ol,e);if(!sl.eql(sl.sqr(_),r))throw new Error("Cannot find square root");return _}var sl=jt(jh,void 0,void 0,{sqrt:j0}),Ye=zh({a:BigInt(0),b:BigInt(7),Fp:sl,n:Gh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Gh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-W0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Wh(s*r,e),c=Wh(-n*r,e),u=J(r-a*t-c*o,e),f=J(-a*n-c*s,e),l=u>i,d=f>i;if(l&&(u=e-u),d&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},Yr),x2=BigInt(0);var v2=Ye.ProjectivePoint;function Fe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ie(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function il(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Zh(r,e){let t=Zr.digest(e instanceof Uint8Array?e:e.subarray());if(il(t))return t.then(({digest:n})=>Ye.sign(n,r).toDERRawBytes()).catch(n=>{throw new Yn(String(n))});try{return Ye.sign(t.digest,r).toDERRawBytes()}catch(n){throw new Yn(String(n))}}function Xh(r,e,t){let n=Zr.digest(t instanceof Uint8Array?t:t.subarray());if(il(n))return n.then(({digest:o})=>Ye.verify(e,o,r)).catch(o=>{throw new Jn(String(o))});try{return Ye.verify(e,n.digest,r)}catch(o){throw new Jn(String(o))}}var to=class{type="secp256k1";raw;_key;constructor(e){this._key=Qh(e),this.raw=Yh(this._key)}toMultihash(){return At.digest(ht(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return W.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 Xh(this._key,t,e)}},Js=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Jh(e),this.publicKey=new to(t??ed(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return Zh(this.raw,e)}};function al(r){return new to(r)}async function td(){let r=Z0();return new Js(r)}function Yh(r){return Ye.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Jh(r){try{return Ye.getPublicKey(r,!0),r}catch(e){throw new Bn(String(e))}}function Qh(r){try{return Ye.ProjectivePoint.fromHex(r),r}catch(e){throw new Rr(String(e))}}function ed(r){try{return Ye.getPublicKey(r,!0)}catch(e){throw new Bn(String(e))}}function Z0(){return Ye.utils.randomPrivateKey()}async function rd(r,e){if(r==="Ed25519")return Lf();if(r==="secp256k1")return td();if(r==="RSA")return rl(e??2048);throw new Ht}function sn(r){let{Type:e,Data:t}=dt.decode(r),n=t??new Uint8Array;switch(e){case we.RSA:return tl(n);case we.Ed25519:return hc(n);case we.secp256k1:return al(n);default:throw new Ht}}function nd(r){let{Type:e,Data:t}=dt.decode(r.digest),n=t??new Uint8Array;switch(e){case we.Ed25519:return hc(n);case we.secp256k1:return al(n);default:throw new Ht}}function ht(r){return dt.encode({Type:we[r.type],Data:r.raw})}var od=Symbol.for("nodejs.util.inspect.custom"),X0=114,ro=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()})`}[Lo]=!0;toString(){return this.string==null&&(this.string=W.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ge.createV1(X0,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")}[od](){return`PeerId(${this.toString()})`}},no=class extends ro{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},oo=class extends ro{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},so=class extends ro{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Y0=2336,io=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=At.digest(P(this.url))}[od](){return`PeerId(${this.url})`}[Lo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ge.createV1(Y0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};var J0=114,sd=2336;function yt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=rt(W.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=rt(e.decode(r))}return an(t)}function cl(r){if(r.type==="Ed25519")return new oo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new so({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new no({multihash:r.toCID().multihash,publicKey:r});throw new Ht}function id(r){return cl(r.publicKey)}function an(r){if(ey(r))return new no({multihash:r});if(Q0(r))try{let e=nd(r);if(e.type==="Ed25519")return new oo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new so({multihash:r,publicKey:e})}catch{let t=H(r.digest);return new io(new URL(t))}throw new Mo("Supplied PeerID Multihash is invalid")}function Qs(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==J0&&r.code!==sd)throw new Do("Supplied PeerID CID is invalid");if(r.code===sd){let e=H(r.multihash.digest);return new io(new URL(e))}return an(r.multihash)}function Q0(r){return r.code===At.code}function ey(r){return r.code===Zr.code}var he=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var ul=ar(cd(),1);var co=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},fl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ld=r=>globalThis.DOMException===void 0?new fl(r):new DOMException(r),ud=r=>{let e=r.reason===void 0?ld("This operation was aborted."):r.reason;return e instanceof Error?e:ld(e)};function lo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=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:d}=e;d.aborted&&f(ud(d)),d.addEventListener("abort",()=>{f(ud(d))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new co;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function hl(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var uo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=hl(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}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 ul.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:uo,...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#b(){return this.#t||this.#s<this.#a}get#x(){return this.#o<this.#u}#v(){this.#o--,this.#f(),this.emit("next")}#E(){this.#w(),this.#y(),this.#l=void 0}get#A(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#E()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#A;if(this.#b&&this.#x){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.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){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.#h()}async#S(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=lo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#S(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof co&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},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.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};function ti(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var dl=60;function ri(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:Ze[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ze[e.type],TTL:e.TTL??e.ttl??dl,data:e.data instanceof Uint8Array?H(e.data):e.data}))}}var ny=4;function pl(r,e={}){let t=new tr({concurrency:e.queryConcurrency??ny});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ti(o.types).forEach(a=>{s.append("type",Ze[a])}),o.onProgress?.(new he("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=ri(await a.json());return o.onProgress?.(new he("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function fd(){return[pl("https://cloudflare-dns.com/dns-query"),pl("https://dns.google/resolve")]}var pd=ar(dd(),1);var ml=class{lru;constructor(e){this.lru=(0,pd.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return ri({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ze[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??dl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function md(r){return new ml(r)}var oy=1e3,ni=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=md(e.cacheSize??oy),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["."]=fd())}async query(e,t={}){let n=ti(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new he("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new he("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));function gd(r={}){return new ni(r)}var oi=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}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 o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var yd=45,sy=15,cn=new oi;function gl(r){if(!(r.length>sy))return cn.new(r).parseWith(()=>cn.readIPv4Addr())}function yl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>yd))return cn.new(r).parseWith(()=>cn.readIPv6Addr())}function si(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>yd))return cn.new(r).parseWith(()=>cn.readIPAddr())}var lA=parseInt("0xFFFF",16),uA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ln(r){return!!gl(r)}function un(r){return!!yl(r)}function ii(r){return!!si(r)}var xd=ln,uy=un,wl=function(r){let e=0;if(r=r.toString().trim(),xd(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(uy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=xd(t[n]),i;s&&(i=wl(t[n]),t[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,H(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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},vd=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var fn={},bl={},hy=[[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"]];hy.forEach(r=>{let e=dy(...r);bl[e.code]=e,fn[e.name]=e});function dy(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function X(r){if(typeof r=="number"){if(bl[r]!=null)return bl[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(fn[r]!=null)return fn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var WA=X("ip4"),jA=X("ip6"),ZA=X("ipcidr");function Al(r,e){switch(X(r).code){case 4:case 41:return my(e);case 42:return El(e);case 6:case 273:case 33:case 132:return Sd(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return El(e);case 421:return by(e);case 444:return Ad(e);case 445:return Ad(e);case 466:return wy(e);case 481:return globalThis.encodeURIComponent(El(e));default:return H(e,"base16")}}function Sl(r,e){switch(X(r).code){case 4:return Ed(e);case 41:return Ed(e);case 42:return vl(e);case 6:case 273:case 33:case 132:return _l(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return vl(e);case 421:return gy(e);case 444:return xy(e);case 445:return vy(e);case 466:return yy(e);case 481:return vl(globalThis.decodeURIComponent(e));default:return P(e,"base16")}}var xl=Object.values(Fn).map(r=>r.decoder),py=function(){let r=xl[0].or(xl[1]);return xl.slice(2).forEach(e=>r=r.or(e)),r}();function Ed(r){if(!ii(r))throw new Error("invalid ip address");return wl(r)}function my(r){let e=vd(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ii(e))throw new Error("invalid ip address");return e}function _l(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Sd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function vl(r){let e=P(r),t=Uint8Array.from(ke(e.length));return Fe([t,e],t.length+e.length)}function El(r){let e=it(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return H(r)}function gy(r){let e;r[0]==="Q"||r[0]==="1"?e=rt(W.decode(`z${r}`)).bytes:e=ge.parse(r).multihash.bytes;let t=Uint8Array.from(ke(e.length));return Fe([t,e],t.length+e.length)}function yy(r){let e=py.decode(r),t=Uint8Array.from(ke(e.length));return Fe([t,e],t.length+e.length)}function wy(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+H(t,"base64url")}function by(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return H(t,"base58btc")}function xy(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=We.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 o=_l(n);return Fe([t,o],t.length+o.length)}function vy(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=We.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 o=_l(n);return Fe([t,o],t.length+o.length)}function Ad(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=H(e,"base32"),o=Sd(t);return`${n}:${o}`}function _d(r){r=Bl(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=X(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Id("invalid address: "+r);if(a.path===!0){n=Bl(o.slice(s).join("/")),e.push([a.code,Sl(a.code,n)]),t.push([a.code,n]);break}let c=Sl(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Al(a.code,c)])}return{string:Bd(t),bytes:Cl(e),tuples:e,stringTuples:t,path:n}}function Il(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=it(r,o),i=pe(s),a=X(s),c=Ey(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Id("Invalid address Uint8Array: "+H(r,"base16"));e.push([s,u]);let f=Al(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Bd(t),tuples:e,stringTuples:t,path:n}}function Bd(r){let e=[];return r.map(t=>{let n=X(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Bl(e.join("/"))}function Cl(r){return Fe(r.map(e=>{let t=X(e[0]),n=Uint8Array.from(ke(t.code));return e.length>1&&e[1]!=null&&(n=Fe([n,e[1]])),n}))}function Ey(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=it(e instanceof Uint8Array?e:Uint8Array.from(e));return t+pe(t)}}function Bl(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Id(r){return new Error("Error parsing address: "+r)}var Ay=Symbol.for("nodejs.util.inspect.custom"),Tl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Sy=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],kl=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},ai=class r{bytes;#e;#t;#s;#a;[Tl]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Il(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=_d(e)}else if(rr(e))t=Il(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.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=X("tcp"),a=X("udp"),c=X("ip4"),u=X("ip6"),f=X("dns6"),l=X("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),Sy.includes(h)&&(t=i.name,o=443,n=`${p??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=X(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(t=X(h).name,n=`${p??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==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:o}}protos(){return this.#t.map(([e])=>Object.assign({},X(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>X(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Cl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===fn.p2p.code&&e.push([n,o]),n===fn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?H(W.decode(`z${n}`),"base58btc"):H(ge.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(s=>s.resolvable);if(t==null)return[this];let n=hn.get(t.name);if(n==null)throw new kl(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>se(s))}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)}[Ay](){return`Multiaddr(${this.#e})`}};var hn=new Map;function rr(r){return!!r?.[Tl]}function se(r){return new ai(r)}var _y=32,{code:By}=X("dnsaddr"),Ll=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},br=async function(e,t={}){let n=t.maxRecursiveDepth??_y;if(n===0)throw new Ll("Max recursive depth reached");let[,o]=e.stringTuples().find(([u])=>u===By)??[],i=await(t?.dns??gd()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Ze.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=se(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var Md=ar(Dd(),1),ui=Md.default;var Ny={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:br}},transportManager:{faultTolerance:Ft.FATAL_ALL}};async function Ud(r){let e=ui(Ny,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 Py(r,e){try{if(typeof r=="string"&&r.length>0)return Ry(r);if(typeof r=="number"&&isFinite(r))return e?.long?My(r):Dy(r);throw new Error("Value is not a string or number.")}catch(t){let n=Uy(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function Ry(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 hi=Py;function Dy(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 My(r){let e=Math.abs(r);return e>=864e5?fi(r,e,864e5,"day"):e>=36e5?fi(r,e,36e5,"hour"):e>=6e4?fi(r,e,6e4,"minute"):e>=1e3?fi(r,e,1e3,"second"):`${r} ms`}function fi(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Uy(r){return typeof r=="object"&&r!==null&&"message"in r}function Pl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=hi,t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(l||b);y.diff=w,y.prev=l,y.curr=b,l=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,v)=>{if(_==="%%")return"%";x++;let B=t.formatters[v];if(typeof B=="function"){let T=g[x];_=B.call(y,T),g.splice(x,1),x--}return _}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(f)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let d=t(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(f))return!1;for(l=0,d=t.names.length;l<d;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){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 di=qy(),Oy=["#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 Fy(){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 Vy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+hi(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,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var Hy=console.debug??console.log??(()=>{});function $y(r){try{r?di?.setItem("debug",r):di?.removeItem("debug")}catch{}}function Ky(){let r;try{r=di?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function qy(){try{return localStorage}catch{}}function zy(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Od=Pl({formatArgs:Vy,save:$y,load:Ky,useColors:Fy,setupFormatters:zy,colors:Oy,storage:di,log:Hy});var ze=Od;ze.formatters.b=r=>r==null?"undefined":W.baseEncode(r);ze.formatters.t=r=>r==null?"undefined":We.baseEncode(r);ze.formatters.m=r=>r==null?"undefined":Cc.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":r.stack??r.message;function Gy(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 pi(){return{forComponent(r){return Wy(r)}}}function Wy(r){let e=Gy(`${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 xr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function mi(r){let e=rt(W.decode(`z${r}`));return an(e)}var lt=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 xr(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 xr(this.map.values(),e=>e.key)}values(){return xr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var vr=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 xr(this.set.entries(),e=>{let t=mi(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=mi(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return xr(this.set.values(),e=>mi(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 Kd=Symbol.for("@achingbrain/uint8arraylist");function $d(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function yi(r){return!!r?.[Kd]}var be=class r{bufs;length;[Kd]=!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(yi(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(yi(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=$d(this.bufs,e);return t.buf[t.index]}set(e,t){let n=$d(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(yi(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:o}=this._subList(e,t);return Fe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Fe(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){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(!yi(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}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=Ie(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 o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,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 o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,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 o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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=Ie(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 o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,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 o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,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 o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,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 o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,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 o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Rl=64,ut=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Rl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ue(o);for(let a=0;a<i.length;a++)i[a]=s[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 Er(r,e){return Math.floor(Math.random()*(e-r))+r}var Ar=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ut))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ut))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 ut))throw new TypeError("Invalid Fingerprint");let t=Er(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ut))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Dl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},qd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},zd=new globalThis.TextEncoder;function jy(r,e){let t=Dl[e],n=qd[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Zy(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Dl[e],o=qd[e],s=r;for(;s.length>0;){let i=zd.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Ml(r,{size:e=32,utf8Buffer:t}={}){if(!Dl[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 Zy(r,e,t);r=zd.encode(r)}return jy(r,e)}var Xy=ar(Hd(),1);var ho={hash:r=>Number(Ml(r,{size:32})),hashV:(r,e)=>Yy(ho.hash(r,e))};function Yy(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),P(e,"base16")}var Jy=500,po=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??ho,this.seed=e.seed??Er(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=P(e));let t=new ut(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ar(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ar(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Er(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ar(this.bucketSize));for(let a=0;a<Jy;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 Ar(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=P(e));let t=new ut(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=P(e));let t=new ut(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Qy={1:.5,2:.84,4:.95,8:.98};function ew(r=.001){return r>.002?2:r>1e-5?4:8}function Gd(r,e=.001){let t=ew(e),n=Qy[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Rl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var wi=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??ho,this.seed=e.seed??Er(0,Math.pow(2,10)),this.filterSeries=[new po({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=P(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 po({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=P(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=P(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 Ul(r,e=.001,t){return new wi({...Gd(r,e),...t??{}})}var mo;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:ue(0),payloadType:ue(0),payload:ue(0),signature:ue(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(mo||(mo={}));var bi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var mn=class r{static createFromProtobuf=async e=>{let t=mo.decode(e),n=sn(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,o=e.codec,s=e.marshal(),i=Wd(n,o,s),a=await t.sign(i.subarray());return new r({publicKey:t.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new bi("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=mo.encode({publicKey:ht(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=Wd(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},Wd=(r,e,t)=>{let n=P(r),o=ke(n.byteLength),s=ke(e.length),i=ke(t.length);return new be(o,n,s,e,i,t)};function jd(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Zd="libp2p-peer-record",Xd=Uint8Array.from([3,1]);var go;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ue((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>Me(s,n.codec()),n.decode=(s,i)=>De(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ue((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ue(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;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(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new yr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Me(n,r.codec()),r.decode=(n,o)=>De(n,r.codec(),o)})(go||(go={}));var Sr=class r{static createFromProtobuf=e=>{let t=go.decode(e),n=an(rt(t.peerId)),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Zd;static CODEC=Xd;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=go.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||!jd(this.multiaddrs,e.multiaddrs))}};function tw(r){return r[Symbol.asyncIterator]!=null}function rw(r){if(tw(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 yo=rw;var nr={},gn=r=>{r.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)})};gn.addEventListener=(r,e)=>{nr[r]==null&&(nr[r]=[]),nr[r].push(e)};gn.removeEventListener=(r,e)=>{nr[r]!=null&&(nr[r]=nr[r].filter(t=>t===e))};gn.dispatchEvent=function(r,e,t){nr[r]!=null&&nr[r].forEach(n=>n(e,t))};var Ol=gn;var Fl="lock:worker:request-read",Vl="lock:worker:release-read",Hl="lock:master:grant-read",$l="lock:worker:request-write",Kl="lock:worker:release-write",ql="lock:master:grant-write";var Yd=(r=21)=>Math.random().toString().substring(2);var Jd=(r,e,t,n,o)=>(s,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()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},Qd=(r,e,t,n)=>async()=>{let o=Yd();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},nw={singleProcess:!1},ep=r=>{if(r=Object.assign({},nw,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Ol.addEventListener("message",Jd(t,"requestReadLock",Fl,Vl,Hl)),Ol.addEventListener("message",Jd(t,"requestWriteLock",$l,Kl,ql)),t}return{isWorker:!0,readLock:t=>Qd(t,Fl,Hl,Vl),writeLock:t=>Qd(t,$l,ql,Kl)}};var _r={},or;async function zl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>lo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var ow=(r,e)=>{if(or.isWorker===!0)return{readLock:or.readLock(r,e),writeLock:or.writeLock(r,e)};let t=new tr({concurrency:1}),n;return{async readLock(){if(n!=null)return zl(n,e);n=new tr({concurrency:e.concurrency,autoStart:!1});let o=n,s=zl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,zl(t,e)}}},sw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Gl(r){let e=Object.assign({},sw,r);return or==null&&(or=ep(e),or.isWorker!==!0&&(or.addEventListener("requestReadLock",t=>{_r[t.data.name]!=null&&_r[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),or.addEventListener("requestWriteLock",async t=>{_r[t.data.name]!=null&&_r[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),_r[e.name]==null&&(_r[e.name]=ow(e.name,e)),_r[e.name]}var yn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((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 u={key:"",value:ue(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((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 u={key:""},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=vi.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ue((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),xi.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new yr('Decode error - map field "addresses" had too many elements');a.addresses.push(xi.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new yr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new $n('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new $n('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Me(o,r.codec()),r.decode=(o,s)=>De(o,r.codec(),s)})(yn||(yn={}));var xi;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:ue(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(xi||(xi={}));var vi;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(vi||(vi={}));function wn(r,e){let t=yn.decode(e);if(t.publicKey!=null&&r.publicKey==null){let s=sn(t.publicKey);r=cl(s)}let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:se(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Mt="/",tp=new TextEncoder().encode(Mt),Ei=tp[0],Br=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=P(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]!==Ei)throw new Error("Invalid key")}toString(e="utf8"){return H(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Mt))}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=tp),this._buf[0]!==Ei){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ei,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ei;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>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(Mt).slice(1)}type(){return iw(this.baseNamespace())}name(){return aw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Mt)||(e+=Mt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Mt):new r(e.slice(0,-1).join(Mt))}child(e){return this.toString()===Mt?e:e.toString()===Mt?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(),...cw(e.map(t=>t.namespaces()))])}};function iw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function aw(r){let e=r.split(":");return e[e.length-1]}function cw(r){return[].concat(...r)}var Wl="/peers/";function bn(r){if(!No(r)||r.type==null)throw new D("Invalid PeerId");let e=r.toCID().toString();return new Br(`${Wl}${e}`)}async function rp(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=se(o.multiaddr)),!rr(o.multiaddr))throw new D("Multiaddr was invalid");if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Si(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 o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new D("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.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=Ai(d,{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ai(d,{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.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[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Ai([...a.entries()],{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Ai([...h.entries()],{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=ht(o.id.publicKey):e.publicKey!=null?f=ht(e.publicKey):r.publicKey!=null&&(f=ht(r.publicKey));let l={addresses:await rp(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:f,peerRecordEnvelope:u};return r.type!=="RSA"&&delete l.publicKey,l}function Ai(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);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 op(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 sp(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 _i(r,e,t){let n=r.toString().split("/")[2],o=ge.parse(n,We),s=Qs(o),i=t.get(s);if(i!=null)return i;let a=wn(s,e);return t.set(s,a),a}function lw(r,e){return r==null?{}:{prefix:Wl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(_i(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(_i(n.key,n.value,e),_i(o.key,o.value,e)))}}var Bi=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Gl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(bn(e))}async delete(e){if(this.peerId.equals(e))throw new D("Cannot delete self peer");await this.datastore.delete(bn(e))}async load(e){let t=await this.datastore.get(bn(e));return wn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Si(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Si(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Si(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new lt;for await(let{key:n,value:o}of this.datastore.query(lw(e??{},t))){let s=_i(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(bn(e)),n=wn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.name!=="NotFoundError")throw t}return{}}async#t(e,t,n,o){let s=yn.encode(t);return n!=null&&ce(s,n)?{peer:wn(e,s),previous:o,updated:!1}:(await this.datastore.put(bn(e),s),{peer:wn(e,s),previous:o,updated:!0})}};var jl=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 Bi(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 o of this.store.all(t))e(o)}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 yo(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 o=await this.store.save(e,t);return this.#e(e,o),o.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 o=await this.store.patch(e,t);return this.#e(e,o),o.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 o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mn.openAndCertify(e,Sr.DOMAIN),o=Qs(n.publicKey.toCID());if(t?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;let s=Sr.createFromProtobuf(n.payload),i;try{i=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await mn.createFromProtobuf(i.peerRecordEnvelope),c=Sr.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:e,addresses:s.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 ip(r,e={}){return new jl(r,e)}var Ii=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 uw(r){return r[Symbol.asyncIterator]!=null}function fw(r){if(uw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Zl=fw;function hw(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var ap=hw;function dw(r){return r[Symbol.asyncIterator]!=null}function pw(r,e){let t=0;if(dw(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=ap(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var Ir=pw;function mw(r){return r[Symbol.asyncIterator]!=null}function gw(r,e){return mw(r)?async function*(){yield*(await yo(r)).sort(e)}():function*(){yield*yo(r).sort(e)}()}var Xl=gw;function yw(r){return r[Symbol.asyncIterator]!=null}function ww(r,e){return yw(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 Yl=ww;var Ci=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:o}of e)await this.put(n,o,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,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Zl(this.putMany(e,n)),e=[],await Zl(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 o=e.prefix;n=Ir(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Ir(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Ir(n,()=>o++>=s)}return e.limit!=null&&(n=Yl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Ir(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Ir(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Ir(n,()=>s++>=o)}return e.limit!=null&&(n=Yl(n,e.limit)),n}};var ki=class extends Ci{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 Ii;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 Br(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Br(e)}};function cp(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var bw=r=>r;function Jl(r,e){let t=r.getPeerId();return t!=null&&yt(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var Ti=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??bw,this._updatePeerStoreAddresses=cp(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.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>se(t))).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=>se(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>se(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>se(e))}addObservedAddr(e){e=Jl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=Jl(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=Jl(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>se(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var lp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(lp||(lp={}));var Li=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Ni=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},wo=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},bo=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Pi=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Ri=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Di=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},xo=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Cr=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Mi=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Ui=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},kr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Tr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Oi=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var Ql=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=pi())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Ho(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")}},vw=["metrics","connectionProtector","dns"],Ew=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function up(r={}){let e=new Ql(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Ew.includes(o)){let i=e.components[o];if(i==null&&!vw.includes(o))throw new Li(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function fp(r){let e={};for(let t of Object.values(r.components))for(let n of Aw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Sw(t))if(e[n]!==!0)throw new Ni(`Service "${_w(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Aw(r){return Array.isArray(r?.[Cn])?r[Cn]:[]}function Sw(r){return Array.isArray(r?.[Oa])?r[Oa]:[]}function _w(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var dp=ar(hp(),1),Bw=["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"],Iw=Bw.map(r=>new dp.Netmask(r));function eu(r){for(let e of Iw)if(e.contains(r))return!0;return!1}function Cw(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function kw(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"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return eu(o)}function Tw(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Lw(r){let e=r.split(":"),t=e[e.length-1];return eu(t)}function Nw(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 Fi(r){return ln(r)?eu(r):Cw(r)?kw(r):Tw(r)?Lw(r):un(r)?Nw(r):void 0}function pp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Fi(`${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 mp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Pw=new WeakMap;function Rw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(mp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(mp())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Pw.set(l,()=>{c(s),s=null,i()}),l}}var Dw=Rw(),gp=Dw;var Vi=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}},Hi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var $i=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 tu}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);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(o,i.consumedPoints,this.blockDuration)),new Vi("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 gp(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,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)}},tu=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,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 Ki(r){if(No(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:yt(t),r.forEach(n=>{if(!rr(n))throw new Vt("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let s=yt(o);if(e?.equals(s)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Mw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function yp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Mw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var wp="last-dial-failure",bp="last-dial-success";var qi=100,zi=50;var xp={maxConnections:qi,allow:[]},Gi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??xp.maxConnections,this.allow=t.allow??xp.allow,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 lt;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await yp(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Wi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)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}},xn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Wi(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 Wi(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 ru=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ji(r={}){return Uw(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 Uw(r,e){e=e??{};let t=e.onEnd,n=new xn,o,s,i,a=fe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fe()})}},u=g=>s!=null?s(g):(n.push(g),o),f=g=>(n=new xn,s!=null?s({error:g}):(n.push({error:g}),o)),l=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new xn,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,A)=>{w=()=>{A(new ru)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return m.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var nu=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 vn(r,e,t,n){let o=new nu(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var Zi=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 sr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Zi(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Zi(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Xi=class{deferred;signal;constructor(e){this.signal=e,this.deferred=fe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new et)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ow(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Yi=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Ow(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ee(1/0,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 et),this.cleanup())}async join(e={}){let t=new Xi(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 sr(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 En=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 Hi;let n=new Yi(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new et)}),this.clear()}async onEmpty(e){this.size!==0&&await vn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await vn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await vn(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=ji({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new et("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ji=class extends En{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Fw=r=>r.toString().split("/").slice(1),Eo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),G=r=>({match:e=>Eo(t=>t===r).match(e),pattern:r}),ta=()=>({match:r=>Eo(e=>typeof e=="string").match(r),pattern:"{string}"}),ra=()=>({match:r=>Eo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),ie=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{W.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Qi=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{kc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),te=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Ge=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Z=(...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 de(...r){function e(o){let s=Fw(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var na=Z(G("dns4"),ta()),oa=Z(G("dns6"),ta()),sa=Z(G("dnsaddr"),ta()),su=Z(G("dns"),ta()),SB=de(na,te(ie())),_B=de(oa,te(ie())),BB=de(sa,te(ie())),IB=de(Ge(su,sa,na,oa),te(ie())),vp=Z(G("ip4"),Eo(ln)),Ep=Z(G("ip6"),Eo(un)),iu=Ge(vp,Ep),Ut=Ge(iu,su,na,oa,sa),CB=de(Ge(iu,Z(Ge(su,sa,na,oa),te(ie())))),kB=de(vp),TB=de(Ep),LB=de(iu),au=Z(Ut,G("tcp"),ra()),Ao=Z(Ut,G("udp"),ra()),cu=de(Z(au,te(ie()))),NB=de(Ao),lu=Z(Ao,G("quic")),ia=Z(Ao,G("quic-v1")),Vw=Ge(lu,ia),PB=de(lu),RB=de(ia),ou=Ge(Ut,au,Ao,lu,ia),Ap=Ge(Z(ou,G("ws"),te(ie()))),uu=de(Ap),Sp=Ge(Z(ou,G("wss"),te(ie())),Z(ou,G("tls"),G("ws"),te(ie()))),fu=de(Sp),_p=Z(Ao,G("webrtc-direct"),te(Qi()),te(Qi()),te(ie())),hu=de(_p),Bp=Z(ia,G("webtransport"),te(Qi()),te(Qi()),te(ie())),du=de(Bp),ea=Ge(Ap,Sp,Z(au,te(ie())),Z(Vw,te(ie())),Z(Ut,te(ie())),_p,Bp,ie()),DB=de(ea),Hw=Z(ea,G("p2p-circuit"),ie()),So=de(Hw),$w=Ge(Z(ea,G("p2p-circuit"),G("webrtc"),te(ie())),Z(ea,G("webrtc"),te(ie())),G("webrtc")),pu=de($w),Kw=Ge(Z(Ut,G("tcp"),ra(),G("http"),te(ie())),Z(Ut,G("http"),te(ie()))),MB=de(Kw),qw=Ge(Z(Ut,G("tcp"),Ge(Z(G("443"),G("http")),Z(ra(),G("https"))),te(ie())),Z(Ut,G("tls"),G("http"),te(ie())),Z(Ut,G("https"),te(ie()))),UB=de(qw);function Ot(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}function mu(r){try{let{address:e}=r.nodeAddress();return!!Fi(e)}catch{return!0}}function zw(r,e){let t=cu.exactMatch(r.multiaddr),n=cu.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=fu.exactMatch(r.multiaddr),s=fu.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=uu.exactMatch(r.multiaddr),a=uu.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=pu.exactMatch(r.multiaddr),u=pu.exactMatch(e.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let f=hu.exactMatch(r.multiaddr),l=hu.exactMatch(e.multiaddr);if(f&&!l)return-1;if(!f&&l)return 1;let d=du.exactMatch(r.multiaddr),h=du.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function Gw(r,e){let t=mu(r.multiaddr),n=mu(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Ww(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function jw(r,e){let t=So.exactMatch(r.multiaddr),n=So.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Ip(r){return r.sort(zw).sort(Ww).sort(jw).sort(Gw)}async function Cp(r,e){let t=!1;for(let o of hn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var aa={maxParallelDials:zi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:br}},ca=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??aa.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??aa.maxDialQueueLength,this.dialTimeout=t.dialTimeout??aa.dialTimeout,this.connections=t.connections??new lt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ee(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))hn.set(n,o);this.queue=new Ji({concurrency:t.maxParallelDials??aa.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==et.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,ee(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Ki(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new he("dial-queue:already-connected")),s;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 u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new he("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Ur("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new he("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new he("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new he("dial-queue:calculated-addresses",u)),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let d of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new Ur("Peer had more than maxPeerAddrsToDial");f++;try{let h=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",d.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[bp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return h}catch(h){if(this.log.error("dial failed to %a",d.multiaddr,h),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[wp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new Oo(h.message);l.push(h)}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??bu,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Ot([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ee(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:se(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Ur("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new xo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await Cp(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(l.multiaddr)?l:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new Cr("The dial request has no valid addresses");let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=this.addressSorter==null?Ip(u):u.sort(this.addressSorter);if(f.length===0)throw new xo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!So.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var la=class extends En{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Dp=ar(Pp(),1);var Xw=Object.prototype.toString,Yw=r=>Xw.call(r)==="[object Error]",Jw=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 xu(r){return r&&Yw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Jw.has(r.message):!1}var vu=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}},Rp=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Eu(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...e};let o=Dp.default.operation(e),s=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",s,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",s),o.stop()};o.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 vu)throw c.originalError;if(c instanceof TypeError&&!xu(c))throw c;if(Rp(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){Rp(u,a,e),i(),n(u)}}})})}var ua=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new la({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,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p",n.detail,o)})})}async maybeReconnect(e){!this.started||!(await this.peerStore.get(e)).tags.has(Ua)||this.queue.has(e)||this.queue.add(async n=>{await Eu(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(n=>{this.log.error("failed to reconnect to %p",e,n)})}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Ua)]});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()}};var bu=50,Au={maxConnections:qi,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},fa=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??Au.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new lt,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=>se(n)),this.deny=(t.deny??[]).map(n=>se(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Au.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new $i({points:t.inboundConnectionThreshold??Au.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Gi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new ca(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??zi,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:br},connections:this.connections}),this.reconnectQueue=new ua({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 o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??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 o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await qu(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 zu(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(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}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,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.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}=Ki(e);if(this.peerId.equals(n))throw new Mr("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 he("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??bu});if(o.status!=="open")throw new Dr("Remote closed connection during opening");let s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)if(a.id===o.id&&(i=!0),t.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new Vt("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))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 o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!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=>se(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var An=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),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var tb=1.2,rb=2,nb=2e3,ha=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new An(e.interval??5e3),this.failure=new An(e.interval??5e3),this.next=new An(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??rb,this.timeoutMultiplier=e.timeoutMultiplier??tb,this.minTimeout=e.minTimeout??nb,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),o=Ot([e.signal,n]);return ee(1/0,o,n),o.start=Date.now(),o.timeout=t,o}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 Su=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=fe(),this.haveNext=fe()}[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=fe(),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=fe(),await sr(this.readNext.promise,t?.signal,t)}};function Mp(){return new Su}var da=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var _u=class extends Error{code;constructor(e,t){super(e),this.code=t}},Bu=class extends _u{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function pa(r,e){let t=Mp();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 o=new be;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Bu("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new be:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new da("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}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(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var ob=1e4,sb="1.0.0",ib="ping",ab="ipfs",Up=32,cb=!0,ma=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??ab}/${ib}/${sb}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??ob,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??cb,this.timeout=new ha({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Cn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,ee(1/0,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}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=pa(o);t=Date.now(),await Promise.all([s.write(nn(Up),{signal:n}),s.read(Up,{signal:n})]),e.rtt=Date.now()-t,await s.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 lb(r){return r[Symbol.asyncIterator]!=null}function ub(...r){let e=[];for(let t of r)lb(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=ji({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var _o=ub;var ga=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[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 wo("No content routers available");let n=this,o=new vr;for await(let s of _o(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new wo("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new bt;await Promise.all(this.routers.map(async o=>{await o.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 ya=globalThis.CustomEvent??Event;async function*Iu(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=fe(),a=fe(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=fe(),await i.promise),f)break;let m={done:!1};s.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,o.dispatchEvent(new ya("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new ya("task-complete"))})}c=!0,o.dispatchEvent(new ya("task-complete"))}catch(p){u=p,o.dispatchEvent(new ya("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;l();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=fe(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var wa=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??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new bo("No peer routers available");if(e.toString()===this.peerId.toString())throw new Pi("Should not try to find self");let n=this,o=_o(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new Ro}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new bo("No peer routers available");let n=this,o=Ul(1024);for await(let s of Iu(async function*(){let i=_o(...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}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ba=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,ee(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ee(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ot([this.shutdownController.signal,e?.signal]);ee(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=fe(),yield(await vn(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,ee(1/0,this.walkController.signal);let e=Ot([this.walkController.signal,this.shutdownController.signal]);ee(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=nn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await sr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Cu=32,ku=64,xa=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 Ri(`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))throw new Di(`Handler already registered for protocol ${e}`);let o=ui.bind({ignoreUndefined:!0})({maxInboundStreams:Cu,maxOutboundStreams:ku},n);this.handlers.set(e,{handler:t,options:o}),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()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.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 o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.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,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);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,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Tu=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 Op(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Tu({name:e,metrics:t}):n=new Map,n}var va=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=Op({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ft.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 o=n.pop();o!=null&&e.push(o.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 Oi(`No transport available for address ${String(e)}`);return t?.onProgress?.(new he("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=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Ft.NO_FATAL)throw new Cr(`Transport (${n}) could not listen on any available address`)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ft.FATAL_ALL)throw new Cr(n);this.log(`libp2p in dial mode only: ${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 o=t.pop();o!=null&&n.push(o.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 Be="/multistream/1.0.0";var Ea=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Aa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Sa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Bo(r,e={}){let t=pa(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=pe(e.maxDataLength));let n=e?.lengthDecoder??it,o=e?.lengthEncoder??ke;return{read:async i=>{let a=-1,c=new be;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Ea("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Sa("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Aa("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new be(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new be(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var fb=P(`
6
+ `)}`:`${t} :`}};th=Qt;k.Constructed=th;Qt.NAME="CONSTRUCTED";var ms=class extends Le{fromBER(e,t,n){return t}toBER(e){return ct}};ms.override="EndOfContentValueBlock";var rh,gs=class extends Se{constructor(e={}){super(e,ms),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};rh=gs;k.EndOfContent=rh;gs.NAME=zn;var nh,Qr=class extends Se{constructor(e={}){super(e,Le),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 o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};nh=Qr;k.Null=nh;Qr.NAME="NULL";var ys=class extends Pt(Le){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=q.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 o=q.BufferSourceConverter.toUint8Array(e);return Nt(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,jc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ys.NAME="BooleanValueBlock";var oh,ws=class extends Se{constructor(e={}){super(e,ys),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}`}};oh=ws;k.Boolean=oh;ws.NAME="BOOLEAN";var bs=class extends Pt(pt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=pt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===zn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Yf)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?pt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};bs.NAME="OctetStringValueBlock";var sh,xs=class r extends Se{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},bs),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 s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=js(s,0,s.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} : ${q.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 q.BufferSourceConverter.concat(e)}};sh=xs;k.OctetString=sh;xs.NAME=Yf;var vs=class extends Pt(pt){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 o=-1;if(this.isConstructed){if(o=pt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===zn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Jf)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=q.BufferSourceConverter.toUint8Array(e);if(!Nt(this,s,t,n))return-1;let i=s.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=js(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 pt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ct;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}}};vs.NAME="BitStringValueBlock";var ih,en=class extends Se{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},vs),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 o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};ih=en;k.BitString=ih;en.NAME=Jf;var ah;function M0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=cs(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=cs(t,s)),s}function Xf(r){if(r>=Kn.length)for(let e=Kn.length;e<=r;e++){let t=new Uint8Array([0]),n=Kn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=cs(t,n)),Kn.push(n)}return Kn[r]}function U0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Gn=class extends Pt(Le){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=jc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Wf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}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 o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}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,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=U0(Xf(n),t),i="-";break;default:t=M0(t,Xf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Zf.charAt(t[c]));return a===!1&&(i+=Zf.charAt(0)),i}};ah=Gn;Gn.NAME="IntegerValueBlock";Object.defineProperty(ah.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var ch,_e=class r extends Se{constructor(e={}){super(e,Gn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return ls(),BigInt(this.valueBlock.toString())}static fromBigInt(e){ls();let t=BigInt(e),n=new qn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+t,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);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()}`}};ch=_e;k.Integer=ch;_e.NAME="INTEGER";var lh,Es=class extends _e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};lh=Es;k.Enumerated=lh;Es.NAME="ENUMERATED";var Wn=class extends Pt(Le){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 o=q.BufferSourceConverter.toUint8Array(e);if(!Nt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(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=wr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){ls();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+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 o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ct;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=q.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}}};Wn.NAME="sidBlock";var As=class extends Le{constructor({value:e=rn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ct;t.push(o)}return Zc(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){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(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Wn;if(o>Number.MAX_SAFE_INTEGER){ls();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!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 o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}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}};As.NAME="ObjectIdentifierValueBlock";var uh,tn=class extends Se{constructor(e={}){super(e,As),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()}}};uh=tn;k.ObjectIdentifier=uh;tn.NAME="OBJECT IDENTIFIER";var jn=class extends Pt(kt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Nt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(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=wr(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 o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ct;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};jn.NAME="relativeSidBlock";var Ss=class extends Le{constructor({value:e=rn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new jn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,ct;n.push(s)}return Zc(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new jn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}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 o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}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}};Ss.NAME="RelativeObjectIdentifierValueBlock";var fh,_s=class extends Se{constructor(e={}){super(e,Ss),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()}}};fh=_s;k.RelativeObjectIdentifier=fh;_s.NAME="RelativeObjectIdentifier";var hh,Tt=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};hh=Tt;k.Sequence=hh;Tt.NAME="SEQUENCE";var dh,Bs=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};dh=Bs;k.Set=dh;Bs.NAME="SET";var Is=class extends Pt(Le){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=rn}toJSON(){return{...super.toJSON(),value:this.value}}};Is.NAME="StringValueBlock";var Cs=class extends Is{};Cs.NAME="SimpleStringValueBlock";var Oe=class extends hs{constructor({...e}={}){super(e,Cs)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Oe.NAME="SIMPLE STRING";var ks=class extends Oe{fromBuffer(e){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=q.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(e)),this.valueBlock.value=e}};ks.NAME="Utf8StringValueBlock";var ph,Lt=class extends ks{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};ph=Lt;k.Utf8String=ph;Lt.NAME="UTF8String";var Ts=class extends Oe{fromBuffer(e){this.valueBlock.value=q.Convert.ToUtf16String(e),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(e))}};Ts.NAME="BmpStringValueBlock";var mh,Ls=class extends Ts{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};mh=Ls;k.BmpString=mh;Ls.NAME="BMPString";var Ns=class extends Oe{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+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 o=0;o<t;o++){let s=Jt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};Ns.NAME="UniversalStringValueBlock";var gh,Ps=class extends Ns{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};gh=Ps;k.UniversalString=gh;Ps.NAME="UniversalString";var yh,Rs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};yh=Rs;k.NumericString=yh;Rs.NAME="NumericString";var wh,Ds=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};wh=Ds;k.PrintableString=wh;Ds.NAME="PrintableString";var bh,Ms=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};bh=Ms;k.TeletexString=bh;Ms.NAME="TeletexString";var xh,Us=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};xh=Us;k.VideotexString=xh;Us.NAME="VideotexString";var vh,Os=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};vh=Os;k.IA5String=vh;Os.NAME="IA5String";var Eh,Fs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Eh=Fs;k.GraphicString=Eh;Fs.NAME="GraphicString";var Ah,Zn=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Ah=Zn;k.VisibleString=Ah;Zn.NAME="VisibleString";var Sh,Vs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Sh=Vs;k.GeneralString=Sh;Vs.NAME="GeneralString";var _h,Hs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};_h=Hs;k.CharacterString=_h;Hs.NAME="CharacterString";var Bh,Xn=class extends Zn{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 o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}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,q.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);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 o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,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}}};Bh=Xn;k.UTCTime=Bh;Xn.NAME="UTCTime";var Ih,$s=class extends Xn{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="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.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 l=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.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}}};Ih=$s;k.GeneralizedTime=Ih;$s.NAME="GeneralizedTime";var Ch,Ks=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Ch=Ks;k.DATE=Ch;Ks.NAME="DATE";var kh,qs=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};kh=qs;k.TimeOfDay=kh;qs.NAME="TimeOfDay";var Th,zs=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Th=zs;k.DateTime=Th;zs.NAME="DateTime";var Lh,Gs=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Lh=Gs;k.Duration=Lh;Gs.NAME="Duration";var Nh,Ws=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Nh=Ws;k.TIME=Nh;Ws.NAME="TIME";function H(r,e="utf8"){let t=ns[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function nn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return Gr(r)}var Yn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Jn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Zs=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ph={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Zs("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=Ph;async function Rh(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 F0(e);return{privateKey:t[0],publicKey:t[1]}}async function Dh(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 Mh(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 F0(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 Jc(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return P(r.n,"base64url").length*8}var on=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Qn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return ge.createV1(114,this._multihash)}toString(){return W.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 Mh(this._key,t,e)}},eo=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Qn.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return Dh(this._key,e)}};var Xs=8192,Qc=18;function Uh(r){let{result:e}=Yc(r),t=e.valueBlock.value;return{n:H(mt(t[1].toBigInt()),"base64url"),e:H(mt(t[2].toBigInt()),"base64url"),d:H(mt(t[3].toBigInt()),"base64url"),p:H(mt(t[4].toBigInt()),"base64url"),q:H(mt(t[5].toBigInt()),"base64url"),dp:H(mt(t[6].toBigInt()),"base64url"),dq:H(mt(t[7].toBigInt()),"base64url"),qi:H(mt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function V0(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 _e({value:0}),_e.fromBigInt(gt(P(r.n,"base64url"))),_e.fromBigInt(gt(P(r.e,"base64url"))),_e.fromBigInt(gt(P(r.d,"base64url"))),_e.fromBigInt(gt(P(r.p,"base64url"))),_e.fromBigInt(gt(P(r.q,"base64url"))),_e.fromBigInt(gt(P(r.dp,"base64url"))),_e.fromBigInt(gt(P(r.dq,"base64url"))),_e.fromBigInt(gt(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Oh(r){let{result:e}=Yc(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:H(mt(t[0].toBigInt()),"base64url"),e:H(mt(t[1].toBigInt()),"base64url")}}function el(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let t=new Tt({value:[new Tt({value:[new tn({value:"1.2.840.113549.1.1.1"}),new Qr]}),new en({valueHex:new Tt({value:[_e.fromBigInt(gt(P(r.n,"base64url"))),_e.fromBigInt(gt(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function mt(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function gt(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 Fh(r){let e=Uh(r);return Vh(e)}function tl(r){let e=Oh(r);if(Jc(e)>Xs)throw new Rr("Key size is too large");let t=Yr(dt.encode({Type:we.RSA,Data:r})),n=tt(Qc,t);return new on(e,n)}function Vh(r){if(Jc(r)>Xs)throw new D("Key size is too large");let e=Hh(r),t=Yr(dt.encode({Type:we.RSA,Data:el(e.publicKey)})),n=tt(Qc,t);return new eo(e.privateKey,new on(e.publicKey,n))}async function rl(r){if(r>Xs)throw new D("Key size is too large");let e=await Rh(r),t=Yr(dt.encode({Type:we.RSA,Data:el(e.publicKey)})),n=tt(Qc,t);return new eo(e.privateKey,new on(e.publicKey,n))}function Hh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Ys=class extends zr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,lf(e);let n=Pn(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return qr(this),this.iHash.update(e),this}digestInto(e){qr(this),Kr(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:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,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()}},nl=(r,e,t)=>new Ys(r,e).update(t).digest();nl.create=(r,e)=>new Ys(r,e);function $h(r){r.lowS!==void 0&&ot("lowS",r.lowS),r.prehash!==void 0&&ot("prehash",r.prehash)}function H0(r){let e=Mn(r);ft(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:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("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("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:$0,hexToBytes:K0}=Wo,Rt={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Rt;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,o=lr(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?lr(o.length/2|128):"";return`${lr(r)}${s}${o}${e}`},decode(r,e){let{Err:t}=Rt,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 o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&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 u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;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}=Rt;if(r<Dt)throw new e("integer: negative integers are not allowed");let t=lr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected assertion");return t},decode(r){let{Err:e}=Rt;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 $0(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Rt,o=typeof r=="string"?K0(r):r;jr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("Invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Rt,n=`${e.encode(2,t.encode(r.r))}${e.encode(2,t.encode(r.s))}`;return e.encode(48,n)}},Dt=BigInt(0),Ee=BigInt(1),u2=BigInt(2),Kh=BigInt(3),f2=BigInt(4);function q0(r){let e=H0(r),{Fp:t}=e,n=jt(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return It(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),s=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function i(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Rn(m,Ee,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(zt(m)&&(m=_t(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:Bt(le("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(x=J(x,w)),$e("private key",x,Ee,w),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=hr((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(w));let A=t.mul(y,g),_=t.mul(b,g),v=t.mul(w,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),l=hr(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=i(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(b)?d.ZERO:new d(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(d.fromAffine)}static fromHex(g){let y=d.fromAffine(s(le("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,y){return Xo(d,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){l(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.eql(t.mul(y,_),t.mul(x,w)),B=t.eql(t.mul(b,_),t.mul(A,w));return v&&B}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,Kh),{px:w,py:x,pz:A}=this,_=t.ZERO,v=t.ZERO,B=t.ZERO,T=t.mul(w,w),re=t.mul(x,x),V=t.mul(A,A),F=t.mul(w,x);return F=t.add(F,F),B=t.mul(w,A),B=t.add(B,B),_=t.mul(g,B),v=t.mul(b,V),v=t.add(_,v),_=t.sub(re,v),v=t.add(re,v),v=t.mul(_,v),_=t.mul(F,_),B=t.mul(b,B),V=t.mul(g,V),F=t.sub(T,V),F=t.mul(g,F),F=t.add(F,B),B=t.add(T,T),T=t.add(B,T),T=t.add(T,V),T=t.mul(T,F),v=t.add(v,T),V=t.mul(x,A),V=t.add(V,V),T=t.mul(V,F),_=t.sub(_,T),B=t.mul(V,re),B=t.add(B,B),B=t.add(B,B),new d(_,v,B)}add(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.ZERO,B=t.ZERO,T=t.ZERO,re=e.a,V=t.mul(e.b,Kh),F=t.mul(y,x),R=t.mul(b,A),C=t.mul(w,_),L=t.add(y,b),S=t.add(x,A);L=t.mul(L,S),S=t.add(F,R),L=t.sub(L,S),S=t.add(y,w);let E=t.add(x,_);return S=t.mul(S,E),E=t.add(F,C),S=t.sub(S,E),E=t.add(b,w),v=t.add(A,_),E=t.mul(E,v),v=t.add(R,C),E=t.sub(E,v),T=t.mul(re,S),v=t.mul(V,C),T=t.add(v,T),v=t.sub(R,T),T=t.add(R,T),B=t.mul(v,T),R=t.add(F,F),R=t.add(R,F),C=t.mul(re,C),S=t.mul(V,S),R=t.add(R,C),C=t.sub(F,C),C=t.mul(re,C),S=t.add(S,C),F=t.mul(R,S),B=t.add(B,F),F=t.mul(E,S),v=t.mul(L,v),v=t.sub(v,F),F=t.mul(L,R),T=t.mul(E,T),T=t.add(T,F),new d(v,B,T)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){$e("scalar",g,Dt,e.n);let y=d.ZERO;if(g===Dt)return y;if(g===Ee)return this;let{endo:b}=e;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:x,k2neg:A,k2:_}=b.splitScalar(g),v=y,B=y,T=this;for(;x>Dt||_>Dt;)x&Ee&&(v=v.add(T)),_&Ee&&(B=B.add(T)),T=T.double(),x>>=Ee,_>>=Ee;return w&&(v=v.negate()),A&&(B=B.negate()),B=new d(t.mul(B.px,b.beta),B.py,B.pz),v.add(B)}multiply(g){let{endo:y,n:b}=e;$e("scalar",g,Ee,b);let w,x;if(y){let{k1neg:A,k1:_,k2neg:v,k2:B}=y.splitScalar(g),{p:T,f:re}=this.wNAF(_),{p:V,f:F}=this.wNAF(B);T=p.constTimeNegate(A,T),V=p.constTimeNegate(v,V),V=new d(t.mul(V.px,y.beta),V.py,V.pz),w=T.add(V),x=re.add(F)}else{let{p:A,f:_}=this.wNAF(g);w=A,x=_}return d.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=d.BASE,x=(_,v)=>v===Dt||v===Ee||!_.equals(w)?_.multiplyUnsafe(v):_.multiply(v),A=x(this,y).add(x(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===Ee)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===Ee?this:y?y(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return ot("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return ot("isCompressed",g),_t(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,p=Zo(d,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function z0(r){let e=Mn(r);return ft(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function qh(r){let e=z0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(C){return J(C,n)}function a(C){return jo(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=q0({...e,toBytes(C,L,S){let E=L.toAffine(),I=t.toBytes(E.x),N=It;return ot("isCompressed",S),S?N(Uint8Array.from([L.hasEvenY()?2:3]),I):N(Uint8Array.from([4]),I,t.toBytes(E.y))},fromBytes(C){let L=C.length,S=C[0],E=C.subarray(1);if(L===o&&(S===2||S===3)){let I=Bt(E);if(!Rn(I,Ee,t.ORDER))throw new Error("Point is not on curve");let N=f(I),M;try{M=t.sqrt(N)}catch(z){let K=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+K)}let U=(M&Ee)===Ee;return(S&1)===1!==U&&(M=t.neg(M)),{x:I,y:M}}else if(L===s&&S===4){let I=t.fromBytes(E.subarray(0,t.BYTES)),N=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:I,y:N}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=C=>_t(Wt(C,e.nByteLength));function h(C){let L=n>>Ee;return C>L}function p(C){return h(C)?i(-C):C}let m=(C,L,S)=>Bt(C.slice(L,S));class g{constructor(L,S,E){this.r=L,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(L){let S=e.nByteLength;return L=le("compactSignature",L,S*2),new g(m(L,0,S),m(L,S,2*S))}static fromDER(L){let{r:S,s:E}=Rt.toSig(le("DER",L));return new g(S,E)}assertValidity(){$e("r",this.r,Ee,n),$e("s",this.s,Ee,n)}addRecoveryBit(L){return new g(this.r,this.s,L)}recoverPublicKey(L){let{r:S,s:E,recovery:I}=this,N=_(le("msgHash",L));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");let M=I===2||I===3?S+e.n:S;if(M>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=I&1?"03":"02",$=c.fromHex(U+d(M)),z=a(M),K=i(-N*z),Y=i(E*z),Q=c.BASE.multiplyAndAddUnsafe($,K,Y);if(!Q)throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return ur(this.toDERHex())}toDERHex(){return Rt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ur(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(C){try{return u(C),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let C=ac(e.n);return Ef(e.randomBytes(C),e.n)},precompute(C=8,L=c.BASE){return L._setWindowSize(C),L.multiply(BigInt(3)),L}};function b(C,L=!0){return c.fromPrivateKey(C).toRawBytes(L)}function w(C){let L=zt(C),S=typeof C=="string",E=(L||S)&&C.length;return L?E===o||E===s:S?E===2*o||E===2*s:C instanceof c}function x(C,L,S=!0){if(w(C))throw new Error("first arg must be private key");if(!w(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(u(C)).toRawBytes(S)}let A=e.bits2int||function(C){let L=Bt(C),S=C.length*8-e.nBitLength;return S>0?L>>BigInt(S):L},_=e.bits2int_modN||function(C){return i(A(C))},v=Dn(e.nBitLength);function B(C){return $e(`num < 2^${e.nBitLength}`,C,Dt,v),Wt(C,e.nByteLength)}function T(C,L,S=re){if(["recovered","canonical"].some(ve=>ve in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:I}=e,{lowS:N,prehash:M,extraEntropy:U}=S;N==null&&(N=!0),C=le("msgHash",C),$h(S),M&&(C=le("prehashed msgHash",E(C)));let $=_(C),z=u(L),K=[B(z),B($)];if(U!=null&&U!==!1){let ve=U===!0?I(t.BYTES):U;K.push(le("extraEntropy",ve))}let Y=It(...K),Q=$;function xe(ve){let Ae=A(ve);if(!l(Ae))return;let Pe=a(Ae),me=c.BASE.multiply(Ae).toAffine(),He=i(me.x);if(He===Dt)return;let wt=i(Pe*i(Q+He*z));if(wt===Dt)return;let Sn=(me.x===He?0:2)|Number(me.y&Ee),_n=wt;return N&&h(wt)&&(_n=p(wt),Sn^=1),new g(He,_n,Sn)}return{seed:Y,k2sig:xe}}let re={lowS:e.lowS,prehash:!1},V={lowS:e.lowS,prehash:!1};function F(C,L,S=re){let{seed:E,k2sig:I}=T(C,L,S),N=e;return nc(N.hash.outputLen,N.nByteLength,N.hmac)(E,I)}c.BASE._setWindowSize(8);function R(C,L,S,E=V){let I=C;if(L=le("msgHash",L),S=le("publicKey",S),"strict"in E)throw new Error("options.strict was renamed to lowS");$h(E);let{lowS:N,prehash:M}=E,U,$;try{if(typeof I=="string"||zt(I))try{U=g.fromDER(I)}catch(me){if(!(me instanceof Rt.Err))throw me;U=g.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){let{r:me,s:He}=I;U=new g(me,He)}else throw new Error("PARSE");$=c.fromHex(S)}catch(me){if(me.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(N&&U.hasHighS())return!1;M&&(L=e.hash(L));let{r:z,s:K}=U,Y=_(L),Q=a(K),xe=i(Y*Q),ve=i(z*Q),Ae=c.BASE.multiplyAndAddUnsafe($,xe,ve)?.toAffine();return Ae?i(Ae.x)===z:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:F,verify:R,ProjectivePoint:c,Signature:g,utils:y}}function G0(r){return{hash:r,hmac:(e,...t)=>nl(r,e,Za(...t)),randomBytes:Gr}}function zh(r,e){let t=n=>qh({...r,...G0(n)});return Object.freeze({...t(e),create:t})}var jh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Gh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),W0=BigInt(1),ol=BigInt(2),Wh=(r,e)=>(r+e/ol)/e;function j0(r){let e=jh,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=oe(f,t,e)*f%e,d=oe(l,t,e)*f%e,h=oe(d,ol,e)*u%e,p=oe(h,o,e)*h%e,m=oe(p,s,e)*p%e,g=oe(m,a,e)*m%e,y=oe(g,c,e)*g%e,b=oe(y,a,e)*m%e,w=oe(b,t,e)*f%e,x=oe(w,i,e)*p%e,A=oe(x,n,e)*u%e,_=oe(A,ol,e);if(!sl.eql(sl.sqr(_),r))throw new Error("Cannot find square root");return _}var sl=jt(jh,void 0,void 0,{sqrt:j0}),Ye=zh({a:BigInt(0),b:BigInt(7),Fp:sl,n:Gh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Gh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-W0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Wh(s*r,e),c=Wh(-n*r,e),u=J(r-a*t-c*o,e),f=J(-a*n-c*s,e),l=u>i,d=f>i;if(l&&(u=e-u),d&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},Yr),x2=BigInt(0);var v2=Ye.ProjectivePoint;function Fe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ie(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function il(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Zh(r,e){let t=Zr.digest(e instanceof Uint8Array?e:e.subarray());if(il(t))return t.then(({digest:n})=>Ye.sign(n,r).toDERRawBytes()).catch(n=>{throw new Yn(String(n))});try{return Ye.sign(t.digest,r).toDERRawBytes()}catch(n){throw new Yn(String(n))}}function Xh(r,e,t){let n=Zr.digest(t instanceof Uint8Array?t:t.subarray());if(il(n))return n.then(({digest:o})=>Ye.verify(e,o,r)).catch(o=>{throw new Jn(String(o))});try{return Ye.verify(e,n.digest,r)}catch(o){throw new Jn(String(o))}}var to=class{type="secp256k1";raw;_key;constructor(e){this._key=Qh(e),this.raw=Yh(this._key)}toMultihash(){return At.digest(ht(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return W.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 Xh(this._key,t,e)}},Js=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Jh(e),this.publicKey=new to(t??ed(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return Zh(this.raw,e)}};function al(r){return new to(r)}async function td(){let r=Z0();return new Js(r)}function Yh(r){return Ye.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Jh(r){try{return Ye.getPublicKey(r,!0),r}catch(e){throw new Bn(String(e))}}function Qh(r){try{return Ye.ProjectivePoint.fromHex(r),r}catch(e){throw new Rr(String(e))}}function ed(r){try{return Ye.getPublicKey(r,!0)}catch(e){throw new Bn(String(e))}}function Z0(){return Ye.utils.randomPrivateKey()}async function rd(r,e){if(r==="Ed25519")return Lf();if(r==="secp256k1")return td();if(r==="RSA")return rl(e??2048);throw new Ht}function sn(r){let{Type:e,Data:t}=dt.decode(r),n=t??new Uint8Array;switch(e){case we.RSA:return tl(n);case we.Ed25519:return hc(n);case we.secp256k1:return al(n);default:throw new Ht}}function nd(r){let{Type:e,Data:t}=dt.decode(r.digest),n=t??new Uint8Array;switch(e){case we.Ed25519:return hc(n);case we.secp256k1:return al(n);default:throw new Ht}}function ht(r){return dt.encode({Type:we[r.type],Data:r.raw})}var od=Symbol.for("nodejs.util.inspect.custom"),X0=114,ro=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()})`}[Lo]=!0;toString(){return this.string==null&&(this.string=W.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ge.createV1(X0,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")}[od](){return`PeerId(${this.toString()})`}},no=class extends ro{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},oo=class extends ro{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},so=class extends ro{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Y0=2336,io=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=At.digest(P(this.url))}[od](){return`PeerId(${this.url})`}[Lo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ge.createV1(Y0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};var J0=114,sd=2336;function yt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=rt(W.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=rt(e.decode(r))}return an(t)}function cl(r){if(r.type==="Ed25519")return new oo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new so({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new no({multihash:r.toCID().multihash,publicKey:r});throw new Ht}function id(r){return cl(r.publicKey)}function an(r){if(ey(r))return new no({multihash:r});if(Q0(r))try{let e=nd(r);if(e.type==="Ed25519")return new oo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new so({multihash:r,publicKey:e})}catch{let t=H(r.digest);return new io(new URL(t))}throw new Mo("Supplied PeerID Multihash is invalid")}function Qs(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==J0&&r.code!==sd)throw new Do("Supplied PeerID CID is invalid");if(r.code===sd){let e=H(r.multihash.digest);return new io(new URL(e))}return an(r.multihash)}function Q0(r){return r.code===At.code}function ey(r){return r.code===Zr.code}var he=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var ul=ar(cd(),1);var co=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},fl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ld=r=>globalThis.DOMException===void 0?new fl(r):new DOMException(r),ud=r=>{let e=r.reason===void 0?ld("This operation was aborted."):r.reason;return e instanceof Error?e:ld(e)};function lo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=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:d}=e;d.aborted&&f(ud(d)),d.addEventListener("abort",()=>{f(ud(d))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new co;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function hl(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var uo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=hl(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}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 ul.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:uo,...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#b(){return this.#t||this.#s<this.#a}get#x(){return this.#o<this.#u}#v(){this.#o--,this.#f(),this.emit("next")}#E(){this.#w(),this.#y(),this.#l=void 0}get#A(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#E()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#A;if(this.#b&&this.#x){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.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){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.#h()}async#S(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=lo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#S(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof co&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},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.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};function ti(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var dl=60;function ri(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:Ze[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ze[e.type],TTL:e.TTL??e.ttl??dl,data:e.data instanceof Uint8Array?H(e.data):e.data}))}}var ny=4;function pl(r,e={}){let t=new tr({concurrency:e.queryConcurrency??ny});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ti(o.types).forEach(a=>{s.append("type",Ze[a])}),o.onProgress?.(new he("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=ri(await a.json());return o.onProgress?.(new he("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function fd(){return[pl("https://cloudflare-dns.com/dns-query"),pl("https://dns.google/resolve")]}var pd=ar(dd(),1);var ml=class{lru;constructor(e){this.lru=(0,pd.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return ri({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ze[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??dl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function md(r){return new ml(r)}var oy=1e3,ni=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=md(e.cacheSize??oy),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["."]=fd())}async query(e,t={}){let n=ti(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new he("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new he("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));function gd(r={}){return new ni(r)}var oi=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}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 o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var yd=45,sy=15,cn=new oi;function gl(r){if(!(r.length>sy))return cn.new(r).parseWith(()=>cn.readIPv4Addr())}function yl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>yd))return cn.new(r).parseWith(()=>cn.readIPv6Addr())}function si(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>yd))return cn.new(r).parseWith(()=>cn.readIPAddr())}var lA=parseInt("0xFFFF",16),uA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ln(r){return!!gl(r)}function un(r){return!!yl(r)}function ii(r){return!!si(r)}var xd=ln,uy=un,wl=function(r){let e=0;if(r=r.toString().trim(),xd(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(uy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=xd(t[n]),i;s&&(i=wl(t[n]),t[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,H(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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},vd=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var fn={},bl={},hy=[[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"]];hy.forEach(r=>{let e=dy(...r);bl[e.code]=e,fn[e.name]=e});function dy(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function X(r){if(typeof r=="number"){if(bl[r]!=null)return bl[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(fn[r]!=null)return fn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var WA=X("ip4"),jA=X("ip6"),ZA=X("ipcidr");function Al(r,e){switch(X(r).code){case 4:case 41:return my(e);case 42:return El(e);case 6:case 273:case 33:case 132:return Sd(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return El(e);case 421:return by(e);case 444:return Ad(e);case 445:return Ad(e);case 466:return wy(e);case 481:return globalThis.encodeURIComponent(El(e));default:return H(e,"base16")}}function Sl(r,e){switch(X(r).code){case 4:return Ed(e);case 41:return Ed(e);case 42:return vl(e);case 6:case 273:case 33:case 132:return _l(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return vl(e);case 421:return gy(e);case 444:return xy(e);case 445:return vy(e);case 466:return yy(e);case 481:return vl(globalThis.decodeURIComponent(e));default:return P(e,"base16")}}var xl=Object.values(Fn).map(r=>r.decoder),py=function(){let r=xl[0].or(xl[1]);return xl.slice(2).forEach(e=>r=r.or(e)),r}();function Ed(r){if(!ii(r))throw new Error("invalid ip address");return wl(r)}function my(r){let e=vd(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ii(e))throw new Error("invalid ip address");return e}function _l(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Sd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function vl(r){let e=P(r),t=Uint8Array.from(ke(e.length));return Fe([t,e],t.length+e.length)}function El(r){let e=it(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return H(r)}function gy(r){let e;r[0]==="Q"||r[0]==="1"?e=rt(W.decode(`z${r}`)).bytes:e=ge.parse(r).multihash.bytes;let t=Uint8Array.from(ke(e.length));return Fe([t,e],t.length+e.length)}function yy(r){let e=py.decode(r),t=Uint8Array.from(ke(e.length));return Fe([t,e],t.length+e.length)}function wy(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+H(t,"base64url")}function by(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return H(t,"base58btc")}function xy(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=We.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 o=_l(n);return Fe([t,o],t.length+o.length)}function vy(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=We.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 o=_l(n);return Fe([t,o],t.length+o.length)}function Ad(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=H(e,"base32"),o=Sd(t);return`${n}:${o}`}function _d(r){r=Bl(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=X(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Id("invalid address: "+r);if(a.path===!0){n=Bl(o.slice(s).join("/")),e.push([a.code,Sl(a.code,n)]),t.push([a.code,n]);break}let c=Sl(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Al(a.code,c)])}return{string:Bd(t),bytes:Cl(e),tuples:e,stringTuples:t,path:n}}function Il(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=it(r,o),i=pe(s),a=X(s),c=Ey(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Id("Invalid address Uint8Array: "+H(r,"base16"));e.push([s,u]);let f=Al(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Bd(t),tuples:e,stringTuples:t,path:n}}function Bd(r){let e=[];return r.map(t=>{let n=X(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Bl(e.join("/"))}function Cl(r){return Fe(r.map(e=>{let t=X(e[0]),n=Uint8Array.from(ke(t.code));return e.length>1&&e[1]!=null&&(n=Fe([n,e[1]])),n}))}function Ey(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=it(e instanceof Uint8Array?e:Uint8Array.from(e));return t+pe(t)}}function Bl(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Id(r){return new Error("Error parsing address: "+r)}var Ay=Symbol.for("nodejs.util.inspect.custom"),Tl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Sy=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],kl=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},ai=class r{bytes;#e;#t;#s;#a;[Tl]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Il(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=_d(e)}else if(rr(e))t=Il(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.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=X("tcp"),a=X("udp"),c=X("ip4"),u=X("ip6"),f=X("dns6"),l=X("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),Sy.includes(h)&&(t=i.name,o=443,n=`${p??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=X(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(t=X(h).name,n=`${p??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==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:o}}protos(){return this.#t.map(([e])=>Object.assign({},X(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>X(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Cl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===fn.p2p.code&&e.push([n,o]),n===fn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?H(W.decode(`z${n}`),"base58btc"):H(ge.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(s=>s.resolvable);if(t==null)return[this];let n=hn.get(t.name);if(n==null)throw new kl(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>se(s))}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)}[Ay](){return`Multiaddr(${this.#e})`}};var hn=new Map;function rr(r){return!!r?.[Tl]}function se(r){return new ai(r)}var _y=32,{code:By}=X("dnsaddr"),Ll=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},br=async function(e,t={}){let n=t.maxRecursiveDepth??_y;if(n===0)throw new Ll("Max recursive depth reached");let[,o]=e.stringTuples().find(([u])=>u===By)??[],i=await(t?.dns??gd()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Ze.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=se(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var Md=ar(Dd(),1),ui=Md.default;var Ny={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:br}},transportManager:{faultTolerance:Ft.FATAL_ALL}};async function Ud(r){let e=ui(Ny,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 Py(r,e){try{if(typeof r=="string"&&r.length>0)return Ry(r);if(typeof r=="number"&&isFinite(r))return e?.long?My(r):Dy(r);throw new Error("Value is not a string or number.")}catch(t){let n=Uy(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function Ry(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 hi=Py;function Dy(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 My(r){let e=Math.abs(r);return e>=864e5?fi(r,e,864e5,"day"):e>=36e5?fi(r,e,36e5,"hour"):e>=6e4?fi(r,e,6e4,"minute"):e>=1e3?fi(r,e,1e3,"second"):`${r} ms`}function fi(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Uy(r){return typeof r=="object"&&r!==null&&"message"in r}function Pl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=hi,t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(l||b);y.diff=w,y.prev=l,y.curr=b,l=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,v)=>{if(_==="%%")return"%";x++;let B=t.formatters[v];if(typeof B=="function"){let T=g[x];_=B.call(y,T),g.splice(x,1),x--}return _}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(f)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let d=t(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(f))return!1;for(l=0,d=t.names.length;l<d;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){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 di=qy(),Oy=["#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 Fy(){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 Vy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+hi(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,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var Hy=console.debug??console.log??(()=>{});function $y(r){try{r?di?.setItem("debug",r):di?.removeItem("debug")}catch{}}function Ky(){let r;try{r=di?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function qy(){try{return localStorage}catch{}}function zy(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Od=Pl({formatArgs:Vy,save:$y,load:Ky,useColors:Fy,setupFormatters:zy,colors:Oy,storage:di,log:Hy});var ze=Od;ze.formatters.b=r=>r==null?"undefined":W.baseEncode(r);ze.formatters.t=r=>r==null?"undefined":We.baseEncode(r);ze.formatters.m=r=>r==null?"undefined":Cc.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":r.stack??r.message;function Gy(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 pi(){return{forComponent(r){return Wy(r)}}}function Wy(r){let e=Gy(`${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 xr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function mi(r){let e=rt(W.decode(`z${r}`));return an(e)}var lt=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 xr(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 xr(this.map.values(),e=>e.key)}values(){return xr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var vr=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 xr(this.set.entries(),e=>{let t=mi(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=mi(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return xr(this.set.values(),e=>mi(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 Kd=Symbol.for("@achingbrain/uint8arraylist");function $d(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function yi(r){return!!r?.[Kd]}var be=class r{bufs;length;[Kd]=!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(yi(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(yi(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=$d(this.bufs,e);return t.buf[t.index]}set(e,t){let n=$d(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(yi(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:o}=this._subList(e,t);return Fe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Fe(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){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(!yi(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}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=Ie(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 o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,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 o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,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 o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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=Ie(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 o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,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 o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,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 o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,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 o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,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 o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Rl=64,ut=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Rl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ue(o);for(let a=0;a<i.length;a++)i[a]=s[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 Er(r,e){return Math.floor(Math.random()*(e-r))+r}var Ar=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ut))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ut))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 ut))throw new TypeError("Invalid Fingerprint");let t=Er(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ut))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Dl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},qd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},zd=new globalThis.TextEncoder;function jy(r,e){let t=Dl[e],n=qd[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Zy(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Dl[e],o=qd[e],s=r;for(;s.length>0;){let i=zd.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Ml(r,{size:e=32,utf8Buffer:t}={}){if(!Dl[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 Zy(r,e,t);r=zd.encode(r)}return jy(r,e)}var Xy=ar(Hd(),1);var ho={hash:r=>Number(Ml(r,{size:32})),hashV:(r,e)=>Yy(ho.hash(r,e))};function Yy(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),P(e,"base16")}var Jy=500,po=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??ho,this.seed=e.seed??Er(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=P(e));let t=new ut(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ar(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ar(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Er(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ar(this.bucketSize));for(let a=0;a<Jy;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 Ar(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=P(e));let t=new ut(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=P(e));let t=new ut(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Qy={1:.5,2:.84,4:.95,8:.98};function ew(r=.001){return r>.002?2:r>1e-5?4:8}function Gd(r,e=.001){let t=ew(e),n=Qy[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Rl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var wi=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??ho,this.seed=e.seed??Er(0,Math.pow(2,10)),this.filterSeries=[new po({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=P(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 po({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=P(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=P(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 Ul(r,e=.001,t){return new wi({...Gd(r,e),...t??{}})}var mo;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:ue(0),payloadType:ue(0),payload:ue(0),signature:ue(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(mo||(mo={}));var bi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var mn=class r{static createFromProtobuf=async e=>{let t=mo.decode(e),n=sn(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,o=e.codec,s=e.marshal(),i=Wd(n,o,s),a=await t.sign(i.subarray());return new r({publicKey:t.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new bi("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=mo.encode({publicKey:ht(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=Wd(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},Wd=(r,e,t)=>{let n=P(r),o=ke(n.byteLength),s=ke(e.length),i=ke(t.length);return new be(o,n,s,e,i,t)};function jd(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Zd="libp2p-peer-record",Xd=Uint8Array.from([3,1]);var go;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ue((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>Me(s,n.codec()),n.decode=(s,i)=>De(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ue((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ue(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;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(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new yr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Me(n,r.codec()),r.decode=(n,o)=>De(n,r.codec(),o)})(go||(go={}));var Sr=class r{static createFromProtobuf=e=>{let t=go.decode(e),n=an(rt(t.peerId)),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Zd;static CODEC=Xd;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=go.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||!jd(this.multiaddrs,e.multiaddrs))}};function tw(r){return r[Symbol.asyncIterator]!=null}function rw(r){if(tw(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 yo=rw;var nr={},gn=r=>{r.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)})};gn.addEventListener=(r,e)=>{nr[r]==null&&(nr[r]=[]),nr[r].push(e)};gn.removeEventListener=(r,e)=>{nr[r]!=null&&(nr[r]=nr[r].filter(t=>t===e))};gn.dispatchEvent=function(r,e,t){nr[r]!=null&&nr[r].forEach(n=>n(e,t))};var Ol=gn;var Fl="lock:worker:request-read",Vl="lock:worker:release-read",Hl="lock:master:grant-read",$l="lock:worker:request-write",Kl="lock:worker:release-write",ql="lock:master:grant-write";var Yd=(r=21)=>Math.random().toString().substring(2);var Jd=(r,e,t,n,o)=>(s,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()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},Qd=(r,e,t,n)=>async()=>{let o=Yd();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},nw={singleProcess:!1},ep=r=>{if(r=Object.assign({},nw,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Ol.addEventListener("message",Jd(t,"requestReadLock",Fl,Vl,Hl)),Ol.addEventListener("message",Jd(t,"requestWriteLock",$l,Kl,ql)),t}return{isWorker:!0,readLock:t=>Qd(t,Fl,Hl,Vl),writeLock:t=>Qd(t,$l,ql,Kl)}};var _r={},or;async function zl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>lo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var ow=(r,e)=>{if(or.isWorker===!0)return{readLock:or.readLock(r,e),writeLock:or.writeLock(r,e)};let t=new tr({concurrency:1}),n;return{async readLock(){if(n!=null)return zl(n,e);n=new tr({concurrency:e.concurrency,autoStart:!1});let o=n,s=zl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,zl(t,e)}}},sw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Gl(r){let e=Object.assign({},sw,r);return or==null&&(or=ep(e),or.isWorker!==!0&&(or.addEventListener("requestReadLock",t=>{_r[t.data.name]!=null&&_r[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),or.addEventListener("requestWriteLock",async t=>{_r[t.data.name]!=null&&_r[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),_r[e.name]==null&&(_r[e.name]=ow(e.name,e)),_r[e.name]}var yn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((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 u={key:"",value:ue(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((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 u={key:""},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=vi.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ue((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),xi.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new yr('Decode error - map field "addresses" had too many elements');a.addresses.push(xi.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new yr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new $n('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new $n('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Me(o,r.codec()),r.decode=(o,s)=>De(o,r.codec(),s)})(yn||(yn={}));var xi;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:ue(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(xi||(xi={}));var vi;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(vi||(vi={}));function wn(r,e){let t=yn.decode(e);if(t.publicKey!=null&&r.publicKey==null){let s=sn(t.publicKey);r=cl(s)}let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:se(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Mt="/",tp=new TextEncoder().encode(Mt),Ei=tp[0],Br=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=P(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]!==Ei)throw new Error("Invalid key")}toString(e="utf8"){return H(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Mt))}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=tp),this._buf[0]!==Ei){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ei,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ei;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>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(Mt).slice(1)}type(){return iw(this.baseNamespace())}name(){return aw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Mt)||(e+=Mt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Mt):new r(e.slice(0,-1).join(Mt))}child(e){return this.toString()===Mt?e:e.toString()===Mt?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(),...cw(e.map(t=>t.namespaces()))])}};function iw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function aw(r){let e=r.split(":");return e[e.length-1]}function cw(r){return[].concat(...r)}var Wl="/peers/";function bn(r){if(!No(r)||r.type==null)throw new D("Invalid PeerId");let e=r.toCID().toString();return new Br(`${Wl}${e}`)}async function rp(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=se(o.multiaddr)),!rr(o.multiaddr))throw new D("Multiaddr was invalid");if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Si(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 o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new D("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.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=Ai(d,{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ai(d,{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.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[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Ai([...a.entries()],{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Ai([...h.entries()],{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=ht(o.id.publicKey):e.publicKey!=null?f=ht(e.publicKey):r.publicKey!=null&&(f=ht(r.publicKey));let l={addresses:await rp(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:f,peerRecordEnvelope:u};return r.type!=="RSA"&&delete l.publicKey,l}function Ai(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);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 op(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 sp(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 _i(r,e,t){let n=r.toString().split("/")[2],o=ge.parse(n,We),s=Qs(o),i=t.get(s);if(i!=null)return i;let a=wn(s,e);return t.set(s,a),a}function lw(r,e){return r==null?{}:{prefix:Wl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(_i(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(_i(n.key,n.value,e),_i(o.key,o.value,e)))}}var Bi=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Gl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(bn(e))}async delete(e){if(this.peerId.equals(e))throw new D("Cannot delete self peer");await this.datastore.delete(bn(e))}async load(e){let t=await this.datastore.get(bn(e));return wn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Si(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Si(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Si(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new lt;for await(let{key:n,value:o}of this.datastore.query(lw(e??{},t))){let s=_i(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(bn(e)),n=wn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.name!=="NotFoundError")throw t}return{}}async#t(e,t,n,o){let s=yn.encode(t);return n!=null&&ce(s,n)?{peer:wn(e,s),previous:o,updated:!1}:(await this.datastore.put(bn(e),s),{peer:wn(e,s),previous:o,updated:!0})}};var jl=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 Bi(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 o of this.store.all(t))e(o)}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 yo(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 o=await this.store.save(e,t);return this.#e(e,o),o.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 o=await this.store.patch(e,t);return this.#e(e,o),o.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 o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mn.openAndCertify(e,Sr.DOMAIN),o=Qs(n.publicKey.toCID());if(t?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;let s=Sr.createFromProtobuf(n.payload),i;try{i=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await mn.createFromProtobuf(i.peerRecordEnvelope),c=Sr.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:e,addresses:s.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 ip(r,e={}){return new jl(r,e)}var Ii=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 uw(r){return r[Symbol.asyncIterator]!=null}function fw(r){if(uw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Zl=fw;function hw(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var ap=hw;function dw(r){return r[Symbol.asyncIterator]!=null}function pw(r,e){let t=0;if(dw(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=ap(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var Ir=pw;function mw(r){return r[Symbol.asyncIterator]!=null}function gw(r,e){return mw(r)?async function*(){yield*(await yo(r)).sort(e)}():function*(){yield*yo(r).sort(e)}()}var Xl=gw;function yw(r){return r[Symbol.asyncIterator]!=null}function ww(r,e){return yw(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 Yl=ww;var Ci=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:o}of e)await this.put(n,o,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,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Zl(this.putMany(e,n)),e=[],await Zl(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 o=e.prefix;n=Ir(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Ir(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Ir(n,()=>o++>=s)}return e.limit!=null&&(n=Yl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Ir(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Ir(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Ir(n,()=>s++>=o)}return e.limit!=null&&(n=Yl(n,e.limit)),n}};var ki=class extends Ci{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 Ii;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 Br(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Br(e)}};function cp(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var bw=r=>r;function Jl(r,e){let t=r.getPeerId();return t!=null&&yt(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var Ti=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??bw,this._updatePeerStoreAddresses=cp(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.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>se(t))).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=>se(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>se(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>se(e))}addObservedAddr(e){e=Jl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=Jl(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=Jl(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>se(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var lp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(lp||(lp={}));var Li=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Ni=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},wo=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},bo=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Pi=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Ri=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Di=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},xo=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Cr=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Mi=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Ui=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},kr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Tr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Oi=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var Ql=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=pi())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Ho(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")}},vw=["metrics","connectionProtector","dns"],Ew=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function up(r={}){let e=new Ql(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Ew.includes(o)){let i=e.components[o];if(i==null&&!vw.includes(o))throw new Li(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function fp(r){let e={};for(let t of Object.values(r.components))for(let n of Aw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Sw(t))if(e[n]!==!0)throw new Ni(`Service "${_w(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Aw(r){return Array.isArray(r?.[Cn])?r[Cn]:[]}function Sw(r){return Array.isArray(r?.[Oa])?r[Oa]:[]}function _w(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var dp=ar(hp(),1),Bw=["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"],Iw=Bw.map(r=>new dp.Netmask(r));function eu(r){for(let e of Iw)if(e.contains(r))return!0;return!1}function Cw(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function kw(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"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return eu(o)}function Tw(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Lw(r){let e=r.split(":"),t=e[e.length-1];return eu(t)}function Nw(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 Fi(r){return ln(r)?eu(r):Cw(r)?kw(r):Tw(r)?Lw(r):un(r)?Nw(r):void 0}function pp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Fi(`${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 mp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Pw=new WeakMap;function Rw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(mp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(mp())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Pw.set(l,()=>{c(s),s=null,i()}),l}}var Dw=Rw(),gp=Dw;var Vi=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}},Hi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var $i=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 tu}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);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(o,i.consumedPoints,this.blockDuration)),new Vi("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 gp(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,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)}},tu=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,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 Ki(r){if(No(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:yt(t),r.forEach(n=>{if(!rr(n))throw new Vt("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let s=yt(o);if(e?.equals(s)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Mw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function yp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Mw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var wp="last-dial-failure",bp="last-dial-success";var qi=100,zi=50;var xp={maxConnections:qi,allow:[]},Gi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??xp.maxConnections,this.allow=t.allow??xp.allow,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 lt;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await yp(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Wi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)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}},xn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Wi(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 Wi(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 ru=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ji(r={}){return Uw(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 Uw(r,e){e=e??{};let t=e.onEnd,n=new xn,o,s,i,a=fe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fe()})}},u=g=>s!=null?s(g):(n.push(g),o),f=g=>(n=new xn,s!=null?s({error:g}):(n.push({error:g}),o)),l=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new xn,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,A)=>{w=()=>{A(new ru)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return m.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var nu=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 vn(r,e,t,n){let o=new nu(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var Zi=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 sr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Zi(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Zi(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Xi=class{deferred;signal;constructor(e){this.signal=e,this.deferred=fe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new et)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ow(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Yi=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Ow(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ee(1/0,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 et),this.cleanup())}async join(e={}){let t=new Xi(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 sr(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 En=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 Hi;let n=new Yi(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new et)}),this.clear()}async onEmpty(e){this.size!==0&&await vn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await vn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await vn(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=ji({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new et("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ji=class extends En{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Fw=r=>r.toString().split("/").slice(1),Eo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),G=r=>({match:e=>Eo(t=>t===r).match(e),pattern:r}),ta=()=>({match:r=>Eo(e=>typeof e=="string").match(r),pattern:"{string}"}),ra=()=>({match:r=>Eo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),ie=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{W.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Qi=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{kc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),te=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Ge=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Z=(...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 de(...r){function e(o){let s=Fw(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var na=Z(G("dns4"),ta()),oa=Z(G("dns6"),ta()),sa=Z(G("dnsaddr"),ta()),su=Z(G("dns"),ta()),SB=de(na,te(ie())),_B=de(oa,te(ie())),BB=de(sa,te(ie())),IB=de(Ge(su,sa,na,oa),te(ie())),vp=Z(G("ip4"),Eo(ln)),Ep=Z(G("ip6"),Eo(un)),iu=Ge(vp,Ep),Ut=Ge(iu,su,na,oa,sa),CB=de(Ge(iu,Z(Ge(su,sa,na,oa),te(ie())))),kB=de(vp),TB=de(Ep),LB=de(iu),au=Z(Ut,G("tcp"),ra()),Ao=Z(Ut,G("udp"),ra()),cu=de(Z(au,te(ie()))),NB=de(Ao),lu=Z(Ao,G("quic")),ia=Z(Ao,G("quic-v1")),Vw=Ge(lu,ia),PB=de(lu),RB=de(ia),ou=Ge(Ut,au,Ao,lu,ia),Ap=Ge(Z(ou,G("ws"),te(ie()))),uu=de(Ap),Sp=Ge(Z(ou,G("wss"),te(ie())),Z(ou,G("tls"),G("ws"),te(ie()))),fu=de(Sp),_p=Z(Ao,G("webrtc-direct"),te(Qi()),te(Qi()),te(ie())),hu=de(_p),Bp=Z(ia,G("webtransport"),te(Qi()),te(Qi()),te(ie())),du=de(Bp),ea=Ge(Ap,Sp,Z(au,te(ie())),Z(Vw,te(ie())),Z(Ut,te(ie())),_p,Bp,ie()),DB=de(ea),Hw=Z(ea,G("p2p-circuit"),ie()),So=de(Hw),$w=Ge(Z(ea,G("p2p-circuit"),G("webrtc"),te(ie())),Z(ea,G("webrtc"),te(ie())),G("webrtc")),pu=de($w),Kw=Ge(Z(Ut,G("tcp"),ra(),G("http"),te(ie())),Z(Ut,G("http"),te(ie()))),MB=de(Kw),qw=Ge(Z(Ut,G("tcp"),Ge(Z(G("443"),G("http")),Z(ra(),G("https"))),te(ie())),Z(Ut,G("tls"),G("http"),te(ie())),Z(Ut,G("https"),te(ie()))),UB=de(qw);function Ot(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}function mu(r){try{let{address:e}=r.nodeAddress();return!!Fi(e)}catch{return!0}}function zw(r,e){let t=cu.exactMatch(r.multiaddr),n=cu.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=fu.exactMatch(r.multiaddr),s=fu.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=uu.exactMatch(r.multiaddr),a=uu.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=pu.exactMatch(r.multiaddr),u=pu.exactMatch(e.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let f=hu.exactMatch(r.multiaddr),l=hu.exactMatch(e.multiaddr);if(f&&!l)return-1;if(!f&&l)return 1;let d=du.exactMatch(r.multiaddr),h=du.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function Gw(r,e){let t=mu(r.multiaddr),n=mu(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Ww(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function jw(r,e){let t=So.exactMatch(r.multiaddr),n=So.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Ip(r){return r.sort(zw).sort(Ww).sort(jw).sort(Gw)}async function Cp(r,e){let t=!1;for(let o of hn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var aa={maxParallelDials:zi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:br}},ca=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??aa.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??aa.maxDialQueueLength,this.dialTimeout=t.dialTimeout??aa.dialTimeout,this.connections=t.connections??new lt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ee(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))hn.set(n,o);this.queue=new Ji({concurrency:t.maxParallelDials??aa.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==et.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,ee(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Ki(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new he("dial-queue:already-connected")),s;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 u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new he("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Ur("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new he("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new he("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new he("dial-queue:calculated-addresses",u)),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let d of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new Ur("Peer had more than maxPeerAddrsToDial");f++;try{let h=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",d.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[bp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return h}catch(h){if(this.log.error("dial failed to %a",d.multiaddr,h),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[wp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new Oo(h.message);l.push(h)}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??bu,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Ot([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ee(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:se(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Ur("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new xo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await Cp(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(l.multiaddr)?l:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new Cr("The dial request has no valid addresses");let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=this.addressSorter==null?Ip(u):u.sort(this.addressSorter);if(f.length===0)throw new xo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!So.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var la=class extends En{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Dp=ar(Pp(),1);var Xw=Object.prototype.toString,Yw=r=>Xw.call(r)==="[object Error]",Jw=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 xu(r){return r&&Yw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Jw.has(r.message):!1}var vu=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}},Rp=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Eu(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...e};let o=Dp.default.operation(e),s=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",s,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",s),o.stop()};o.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 vu)throw c.originalError;if(c instanceof TypeError&&!xu(c))throw c;if(Rp(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){Rp(u,a,e),i(),n(u)}}})})}var ua=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new la({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,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p",n.detail,o)})})}async maybeReconnect(e){!this.started||!(await this.peerStore.get(e)).tags.has(Ua)||this.queue.has(e)||this.queue.add(async n=>{await Eu(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(n=>{this.log.error("failed to reconnect to %p",e,n)})}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Ua)]});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()}};var bu=50,Au={maxConnections:qi,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},fa=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??Au.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new lt,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=>se(n)),this.deny=(t.deny??[]).map(n=>se(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Au.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new $i({points:t.inboundConnectionThreshold??Au.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Gi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new ca(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??zi,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:br},connections:this.connections}),this.reconnectQueue=new ua({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 o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??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 o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await qu(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 zu(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(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}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,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.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}=Ki(e);if(this.peerId.equals(n))throw new Mr("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 he("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??bu});if(o.status!=="open")throw new Dr("Remote closed connection during opening");let s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)if(a.id===o.id&&(i=!0),t.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new Vt("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))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 o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!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=>se(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var An=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),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var tb=1.2,rb=2,nb=2e3,ha=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new An(e.interval??5e3),this.failure=new An(e.interval??5e3),this.next=new An(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??rb,this.timeoutMultiplier=e.timeoutMultiplier??tb,this.minTimeout=e.minTimeout??nb,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),o=Ot([e.signal,n]);return ee(1/0,o,n),o.start=Date.now(),o.timeout=t,o}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 Su=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=fe(),this.haveNext=fe()}[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=fe(),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=fe(),await sr(this.readNext.promise,t?.signal,t)}};function Mp(){return new Su}var da=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var _u=class extends Error{code;constructor(e,t){super(e),this.code=t}},Bu=class extends _u{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function pa(r,e){let t=Mp();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 o=new be;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Bu("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new be:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new da("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}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(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var ob=1e4,sb="1.0.0",ib="ping",ab="ipfs",Up=32,cb=!0,ma=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??ab}/${ib}/${sb}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??ob,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??cb,this.timeout=new ha({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Cn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,ee(1/0,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}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=pa(o);t=Date.now(),await Promise.all([s.write(nn(Up),{signal:n}),s.read(Up,{signal:n})]),e.rtt=Date.now()-t,await s.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 lb(r){return r[Symbol.asyncIterator]!=null}function ub(...r){let e=[];for(let t of r)lb(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=ji({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var _o=ub;var ga=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[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 wo("No content routers available");let n=this,o=new vr;for await(let s of _o(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new wo("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new bt;await Promise.all(this.routers.map(async o=>{await o.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 ya=globalThis.CustomEvent??Event;async function*Iu(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=fe(),a=fe(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=fe(),await i.promise),f)break;let m={done:!1};s.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,o.dispatchEvent(new ya("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new ya("task-complete"))})}c=!0,o.dispatchEvent(new ya("task-complete"))}catch(p){u=p,o.dispatchEvent(new ya("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;l();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=fe(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var wa=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??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new bo("No peer routers available");if(e.toString()===this.peerId.toString())throw new Pi("Should not try to find self");let n=this,o=_o(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new Ro}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new bo("No peer routers available");let n=this,o=Ul(1024);for await(let s of Iu(async function*(){let i=_o(...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}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ba=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,ee(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ee(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ot([this.shutdownController.signal,e?.signal]);ee(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=fe(),yield(await vn(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,ee(1/0,this.walkController.signal);let e=Ot([this.walkController.signal,this.shutdownController.signal]);ee(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=nn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await sr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Cu=32,ku=64,xa=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 Ri(`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))throw new Di(`Handler already registered for protocol ${e}`);let o=ui.bind({ignoreUndefined:!0})({maxInboundStreams:Cu,maxOutboundStreams:ku},n);this.handlers.set(e,{handler:t,options:o}),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()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.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 o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.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,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);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,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Tu=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 Op(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Tu({name:e,metrics:t}):n=new Map,n}var va=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=Op({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ft.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 o=n.pop();o!=null&&e.push(o.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 Oi(`No transport available for address ${String(e)}`);return t?.onProgress?.(new he("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=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Ft.NO_FATAL)throw new Cr(`Transport (${n}) could not listen on any available address`)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ft.FATAL_ALL)throw new Cr(n);this.log(`libp2p in dial mode only: ${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 o=t.pop();o!=null&&n.push(o.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 Be="/multistream/1.0.0";var Ea=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Aa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Sa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Bo(r,e={}){let t=pa(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=pe(e.maxDataLength));let n=e?.lengthDecoder??it,o=e?.lengthEncoder??ke;return{read:async i=>{let a=-1,c=new be;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Ea("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Sa("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Aa("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new be(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new be(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var fb=P(`
7
7
  `);async function Nr(r,e,t){await r.write(e,t)}async function Fp(r,e,t){await r.writeV(e,t)}async function hb(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==fb[0])throw e.log.error("Invalid mss message - missing newline",t),new Uo("Missing newline");return t.sublist(0,-1)}async function ir(r,e){let t=await hb(r,e);return H(t.subarray())}async function Io(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return db(r,e[0],t);let n=Bo(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Be,o);let s=P(`${Be}
8
8
  `),i=P(`${o}
9
9
  `);await Fp(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await ir(n,t);if(t.log.trace('select: read "%s"',a),a===Be&&(t.log.trace("select: reading protocol response"),a=await ir(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Nr(n,P(`${c}
@@ -16,7 +16,7 @@ ${e.join(`
16
16
  `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new be(...e.map(i=>Ia.single(P(`${i}
17
17
  `))),P(`
18
18
  `));t.log.trace('handle: respond with "%s" for %s',e,o),await Nr(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log.trace('handle: respond with "na" for "%s"',o),await Nr(n,P(`na
19
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var yb=500,Ru=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,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=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Ku]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Po("the connection is being closed");if(this.status==="closed")throw new Dr("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Or("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(yb);ee(1/0,t),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 Hp(r){return new Ru(r)}function xb(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Cu}function vb(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??ku}function $p(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var La=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;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??3e3,this.outboundUpgradeTimeout=t.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??2e3,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 Mi(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){try{if(this.metrics.dials?.increment({inbound:!0}),!await this.components.connectionManager.acceptIncomingConnection(e))throw new Ui("connection denied");return await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(n){throw this.metrics.errors?.increment({inbound:!0}),n}finally{this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),o;return n!=null&&(o=yt(n),await this.shouldBlockConnection("denyOutboundConnection",o,e)),await this._performUpgrade(e,"outbound",t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let o,s,i,a,c,u=AbortSignal.timeout(t==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),f=Ot([u,n.signal]);ee(1/0,u,f),n.signal=f,this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),l=await d.protect(e,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new he(`upgrader:encrypt-${t}-connection`)),{conn:o,remotePeer:s,protocol:c}=await(t==="inbound"?this._encryptInbound(l,{...n,signal:f}):this._encryptOutbound(l,{...n,signal:f}));let d={...l,...o};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new Vt(`${t} connection that skipped encryption must have a peer id`);let h=yt(d);c="native",s=h}if(s.equals(this.components.peerId)){let d=new Mr("Can not dial self");throw e.abort(d),d}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new he(`upgrader:multiplex-${t}-connection`));let d=await(t==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,d),d}finally{f.clear()}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);ee(1/0,g);let{stream:y,protocol:b}=await ko(p,m,{signal:g,log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",b);let w=xb(b,this.components.registrar);if($p(b,"inbound",l)===w){let A=new Fo(`Too many inbound protocol streams for protocol "${b}" - limit ${w}`);throw p.abort(A),A}p.source=y.source,p.sink=y.sink,p.protocol=b,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(i,{protocols:[b]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:b})}).catch(async m=>{l.log.error("error handling incoming stream id %s - %e",p.id,m),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new kr("Connection is not multiplexed");l.log.trace("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);ee(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await Io(g,p,{...m,log:g.log,yieldBytes:!0});g.log.trace("selected protocol %s",b);let w=vb(b,this.components.registrar,m),x=$p(b,"outbound",l);if(x>=w){let A=new Vo(`Too many outbound protocol streams for protocol "${b}" - ${x}/${w}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(y){throw l.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer - %e",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new kr("Connection is not multiplexed")};return l=Hp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u?.streams??[],close:async p=>{await u?.close(p),await o.close(p)},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l.__maConnTimeline=d,l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new Or("Cannot open protocol stream on limited connection");s({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await ko(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Tr(`no crypto module found for ${s}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,s),{...await i.secureInbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,o),new Tr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Io(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Tr(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,s),{...await i.secureOutbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,o),new Tr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await Io(e,o,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:s,muxerFactory:a}}catch(s){throw e.log.error("error multiplexing outbound connection",s),new kr(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await ko(e,o,{...n,log:e.log}),a=t.get(i);return{stream:s,muxerFactory:a}}catch(s){throw e.log.error("error multiplexing inbound connection",s),new kr(String(s))}}};var Kp="2.1.6",qp="libp2p";var Na=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=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},ee(1/0,t),this.peerId=e.peerId,this.logger=e.logger??pi(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=up({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:qp,version:Kp},logger:this.logger,events:t,datastore:e.datastore??new ki,connectionGater:pp(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",ip(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new La(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:e.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new va(this.components,e.transportManager)),this.configureComponent("connectionManager",new fa(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ma(this.components,e.connectionMonitor)),this.configureComponent("registrar",new xa(this.components)),this.configureComponent("addressManager",new Ti(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new wa(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ga(this.components,{routers:i})),this.configureComponent("randomWalk",new ba(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[Ra]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Ra])),u[Ma]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Ma])),u[Da]!=null&&(this.log("registering service %s for peer discovery",a),u[Da].addEventListener?.("peer",f=>{this.#e(f)}))}fp(o)}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 vr;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=yt(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([P("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=sn(o);return await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,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 Ab(r={}){r.privateKey??=await rd("Ed25519");let e=new Na({...await Ud(r),peerId:id(r.privateKey)});return r.start!==!1&&await e.start(),e}return om(Sb);})();
19
+ `),t),t.log('handle: responded with "na" for "%s"',o)}}var yb=500,Ru=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,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=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Ku]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Po("the connection is being closed");if(this.status==="closed")throw new Dr("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Or("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(yb);ee(1/0,t),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 Hp(r){return new Ru(r)}function xb(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Cu}function vb(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??ku}function $p(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var La=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;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??3e3,this.outboundUpgradeTimeout=t.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??2e3,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 Mi(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){try{if(this.metrics.dials?.increment({inbound:!0}),!await this.components.connectionManager.acceptIncomingConnection(e))throw new Ui("connection denied");return await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(n){throw this.metrics.errors?.increment({inbound:!0}),n}finally{this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),o;return n!=null&&(o=yt(n),await this.shouldBlockConnection("denyOutboundConnection",o,e)),await this._performUpgrade(e,"outbound",t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let o,s,i,a,c,u=AbortSignal.timeout(t==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),f=Ot([u,n.signal]);ee(1/0,u,f),n.signal=f,this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),l=await d.protect(e,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new he(`upgrader:encrypt-${t}-connection`)),{conn:o,remotePeer:s,protocol:c}=await(t==="inbound"?this._encryptInbound(l,{...n,signal:f}):this._encryptOutbound(l,{...n,signal:f}));let d={...l,...o};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new Vt(`${t} connection that skipped encryption must have a peer id`);let h=yt(d);c="native",s=h}if(s.equals(this.components.peerId)){let d=new Mr("Can not dial self");throw e.abort(d),d}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new he(`upgrader:multiplex-${t}-connection`));let d=await(t==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,d),d}finally{f.clear()}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);ee(1/0,g);let{stream:y,protocol:b}=await ko(p,m,{signal:g,log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",b);let w=xb(b,this.components.registrar);if($p(b,"inbound",l)===w){let A=new Fo(`Too many inbound protocol streams for protocol "${b}" - limit ${w}`);throw p.abort(A),A}p.source=y.source,p.sink=y.sink,p.protocol=b,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(i,{protocols:[b]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:b})}).catch(async m=>{l.log.error("error handling incoming stream id %s - %e",p.id,m),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new kr("Connection is not multiplexed");l.log.trace("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);ee(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await Io(g,p,{...m,log:g.log,yieldBytes:!0});g.log.trace("selected protocol %s",b);let w=vb(b,this.components.registrar,m),x=$p(b,"outbound",l);if(x>=w){let A=new Vo(`Too many outbound protocol streams for protocol "${b}" - ${x}/${w}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(y){throw l.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer - %e",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new kr("Connection is not multiplexed")};return l=Hp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u?.streams??[],close:async p=>{await u?.close(p),await o.close(p)},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l.__maConnTimeline=d,l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new Or("Cannot open protocol stream on limited connection");s({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await ko(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Tr(`no crypto module found for ${s}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,s),{...await i.secureInbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,o),new Tr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Io(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Tr(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,s),{...await i.secureOutbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,o),new Tr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await Io(e,o,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:s,muxerFactory:a}}catch(s){throw e.log.error("error multiplexing outbound connection",s),new kr(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await ko(e,o,{...n,log:e.log}),a=t.get(i);return{stream:s,muxerFactory:a}}catch(s){throw e.log.error("error multiplexing inbound connection",s),new kr(String(s))}}};var Kp="2.1.7",qp="libp2p";var Na=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=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},ee(1/0,t),this.peerId=e.peerId,this.logger=e.logger??pi(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=up({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:qp,version:Kp},logger:this.logger,events:t,datastore:e.datastore??new ki,connectionGater:pp(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",ip(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new La(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:e.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new va(this.components,e.transportManager)),this.configureComponent("connectionManager",new fa(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ma(this.components,e.connectionMonitor)),this.configureComponent("registrar",new xa(this.components)),this.configureComponent("addressManager",new Ti(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new wa(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ga(this.components,{routers:i})),this.configureComponent("randomWalk",new ba(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[Ra]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Ra])),u[Ma]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Ma])),u[Da]!=null&&(this.log("registering service %s for peer discovery",a),u[Da].addEventListener?.("peer",f=>{this.#e(f)}))}fp(o)}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 vr;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=yt(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([P("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=sn(o);return await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,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 Ab(r={}){r.privateKey??=await rd("Ed25519");let e=new Na({...await Ud(r),peerId:id(r.privateKey)});return r.start!==!1&&await e.start(),e}return om(Sb);})();
20
20
  /*! Bundled license information:
21
21
 
22
22
  pvtsutils/build/index.js:
@@ -1,3 +1,3 @@
1
- export declare const version = "2.1.6";
1
+ export declare const version = "2.1.7";
2
2
  export declare const name = "libp2p";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1,3 +1,3 @@
1
- export const version = '2.1.6';
1
+ export const version = '2.1.7';
2
2
  export const name = 'libp2p';
3
3
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2p",
3
- "version": "2.1.6",
3
+ "version": "2.1.7",
4
4
  "description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/libp2p#readme",
@@ -114,7 +114,7 @@
114
114
  },
115
115
  "devDependencies": {
116
116
  "@chainsafe/libp2p-yamux": "^7.0.0",
117
- "@libp2p/circuit-relay-v2": "^2.1.2",
117
+ "@libp2p/circuit-relay-v2": "^2.1.3",
118
118
  "@libp2p/identify": "^3.0.7",
119
119
  "@libp2p/interface-compliance-tests": "^6.1.5",
120
120
  "@libp2p/mplex": "^11.0.7",
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.1.6'
1
+ export const version = '2.1.7'
2
2
  export const name = 'libp2p'