libp2p 3.5.2-15cea7995 → 3.5.2-19dc7bbd4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -9,7 +9,7 @@ ${e}`)}`:n!=null?`${n.split(`
9
9
  ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function z0(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Uh(r,e=""){if(z0(r)){let t=Bh(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
10
  ${e}${r.errors.map(n=>`${Uh(n,`${e}`)}`).join(`
11
11
  ${e}`)}`):t+=`
12
- ${e}[Error list was empty]`,t.trim()}return Bh(r,e)}We.formatters.e=r=>r==null?"undefined":Uh(r);function V0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Us(r){return{forComponent(e){return Kh(e,r)}}}function Kh(r,e){let t=V0(`${r}:trace`);return We.enabled(`${r}:trace`)&&We.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=We(`${r}:trace`,e)),Object.assign(We(r,e),{error:We(`${r}:error`,e),trace:t,newScope:n=>Kh(`${r}:${n}`,e)})}function Fh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function yr(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 Ks(r){let e=At(ie.decode(`z${r}`));return en(e)}var it=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 yr(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 yr(this.map.values(),e=>e.key)}values(){return yr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var br=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 yr(this.set.entries(),e=>{let t=Ks(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Ks(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return yr(this.set.values(),e=>Ks(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 Tu={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},qh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},$h=new TextEncoder;function H0(r,e){let t=Tu[e],n=qh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function W0(r,e,t){if(t.length<4)throw new RangeError("The `utf8Buffer` option must have a length of at least 4");let n=Tu[e],o=qh[e],s=r;for(;s.length>0;){let i=$h.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 Iu(r,{size:e=32,utf8Buffer:t}={}){if(!Object.hasOwn(Tu,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 W0(r,e,t);r=$h.encode(r)}return H0(r,e)}var ho={hash:r=>Number(Iu(r,{size:32})),hashV:(r,e)=>G0(ho.hash(r,e))};function G0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),I(e,"base16")}var Lu=64,dt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Lu)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=pe(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?Q(this.fp,e.fp):!1}};function wr(r,e){return Math.floor(Math.random()*(e-r))+r}var xr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof dt))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 dt))throw new TypeError("Invalid Fingerprint");let t=wr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var j0=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??wr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=I(e));let t=new dt(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 xr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new xr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[wr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new xr(this.bucketSize));for(let a=0;a<j0;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 xr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=I(e));let t=new dt(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=I(e));let t=new dt(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}},Y0={1:.5,2:.84,4:.95,8:.98};function X0(r=.001){return r>.002?2:r>1e-5?4:8}function zh(r,e=.001){let t=X0(e),n=Y0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Lu);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var qs=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??wr(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=I(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=I(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=I(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 mo(r,e=.001,t){return new qs({...zh(r,e),...t??{}})}function Pu(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function Y(r){let e=Pu(r);if(e==null)throw new T(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var $s=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 l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,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 Vh=45,Z0=15,tn=new $s;function zs(r){if(!(r.length>Z0))return tn.new(r).parseWith(()=>tn.readIPv4Addr())}function Vs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vh))return tn.new(r).parseWith(()=>tn.readIPv6Addr())}function Zt(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Vh)return;let t=tn.new(r).parseWith(()=>tn.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function Hh(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function Du(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function Ru(r){switch(r.length){case Er:return r.join(".");case vr:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Wh(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function Gh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Er=4,vr=16,RA=parseInt("0xFFFF",16),jh=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function go(r,e){e.length===vr&&r.length===Er&&Hh(e,0,11)&&(e=e.slice(12)),e.length===Er&&r.length===vr&&Du(r,jh,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function Yh(r,e){if(typeof e=="string"&&(e=Zt(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Ou(r){if(!Hs(r))throw new Error("Must have 0xffff prefix");return r.slice(12)}function Hs(r){return Du(r,jh,0,11)}function ku(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Er,o=zs(e);if(o==null&&(n=vr,o=Vs(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Nu(s,8*n);return{network:go(o,i),mask:i}}function Nu(r,e){if(e!==8*Er&&e!==8*vr)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Qt=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=ku(e));else{let n=Zt(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=Zt(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Nu(o,8*n.length);this.network=go(n,this.mask)}}contains(e){return Yh({network:this.network,mask:this.mask},e)}toString(){let e=Wh(this.mask),t=e!==-1?String(e):Gh(this.mask);return Ru(this.network)+"/"+t}};function Xh(r){try{let e=Y(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Zh(r){if(typeof r!="string"||!/^[0-9a-fA-FxX.:]+$/.test(r))return!1;let e=r.includes(":")?`[${r}]`:r,t;try{t=new URL(`http://${e}`)}catch{return!1}if(t.href!==`http://${t.hostname}/`)return!1;let n=t.hostname;if(n.startsWith("["))return n==="[::1]";let o=n.split(".");return o.length===4&&o[0]==="127"&&o.every(s=>/^\d{1,3}$/.test(s))}function yo(r){try{let e=Y(r);switch(e.type){case"ip4":case"ip6":return Zh(e.host);default:return!1}}catch{return!1}}function Ie(r){return Pu(r)!==null}function ht(r){return!!zs(r)}function Ws(r){return!!Vs(r)}var Q0=["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","::/128","::1/128","64:ff9b::/96","100::/64","2001::/32","2001:20::/28","2001:db8::/32","2002::/16","fc00::/7","fe80::/10","ff00::/8"].map(r=>new Qt(r));function rn(r){if(!ht(r)&&!Ws(r))return;let e=Zt(r);if(e==null)return;let t=e.length===16&&Hs(e)?Ou(e):e;return Q0.some(n=>n.contains(t))}function Pt(r){try{let e=Y(r);switch(e.type){case"ip4":case"ip6":return rn(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}var Le=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Dt=class extends Error{static name="ValidationError";name="ValidationError"},Gs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},js=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Bu(r){return e=>F(e,r)}function Fu(r){return e=>I(e,r)}function nn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Sr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Qh(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=I(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Sr(n);return tt([t,o],t.length+o.length)}function Jh(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=et.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=Sr(n);return tt([t,o],t.length+o.length)}function Uu(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=F(e,"base32"),o=nn(t);return`${n}:${o}`}var Ku=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Le("Invalid byte value in IP address");e[n]=o}),e},ep=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ht(t[n]),i;s&&(i=Ku(t[n]),t[n]=F(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,F(i.subarray(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++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Le("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},tp=function(r){if(r.byteLength!==4)throw new Le("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},rp=function(r){if(r.byteLength!==16)throw new Le("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Le(`Invalid IPv6 address "${t}"`)}};function np(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Le(`Invalid IPv6 address "${r}"`)}}var Mu=Object.values(On).map(r=>r.decoder),J0=(function(){let r=Mu[0].or(Mu[1]);return Mu.slice(2).forEach(e=>r=r.or(e)),r})();function op(r){return J0.decode(r)}function sp(r){return e=>r.encoder.encode(e)}function eb(r){if(parseInt(r).toString()!==r)throw new Dt("Value must be an integer")}function tb(r){if(r<0)throw new Dt("Value must be a positive integer, or zero")}function rb(r){return e=>{if(e>r)throw new Dt(`Value must be smaller than or equal to ${r}`)}}function nb(...r){return e=>{for(let t of r)t(e)}}var bo=nb(eb,tb,rb(65535));var _e=-1,qu=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new js(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Ot=new qu,yb=[{code:4,name:"ip4",size:32,valueToBytes:Ku,bytesToValue:tp,validate:r=>{if(!ht(r))throw new Dt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Sr,bytesToValue:nn,validate:bo},{code:273,name:"udp",size:16,valueToBytes:Sr,bytesToValue:nn,validate:bo},{code:33,name:"dccp",size:16,valueToBytes:Sr,bytesToValue:nn,validate:bo},{code:41,name:"ip6",size:128,valueToBytes:ep,bytesToValue:rp,stringToValue:np,validate:r=>{if(!Ws(r))throw new Dt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:_e},{code:43,name:"ipcidr",size:8,bytesToValue:Bu("base10"),valueToBytes:Fu("base10")},{code:53,name:"dns",size:_e},{code:54,name:"dns4",size:_e},{code:55,name:"dns6",size:_e},{code:56,name:"dnsaddr",size:_e},{code:132,name:"sctp",size:16,valueToBytes:Sr,bytesToValue:nn,validate:bo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:_e,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:_e,bytesToValue:Bu("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Fu("base58btc")(r):xe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Uu,valueToBytes:Qh},{code:445,name:"onion3",size:296,bytesToValue:Uu,valueToBytes:Jh},{code:446,name:"garlic64",size:_e},{code:447,name:"garlic32",size:_e},{code:448,name:"tls"},{code:449,name:"sni",size:_e},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:_e,bytesToValue:sp(sc),valueToBytes:op},{code:480,name:"http"},{code:481,name:"http-path",size:_e,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:_e}];yb.forEach(r=>{Ot.addProtocol(r)});function ip(r){let e=[],t=0;for(;t<r.length;){let n=dr(r,t),o=Ot.getProtocol(n),s=Ae(n),i=bb(o,r,t+s),a=0;i>0&&o.size===_e&&(a=Ae(i));let c=s+a+i,u={code:n,name:o.name,bytes:Te(r.subarray(t,t+c))};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??F(f)}e.push(u),t+=c}return e}function ap(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ot.getProtocol(n.code),s=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??I(n.value),a=i.byteLength,o.size===_e&&(c=Ae(a)));let u=new Uint8Array(s+c+a),l=0;Qr(n.code,u,l),l+=s,i!=null&&(o.size===_e&&(Qr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return tt(t,e)}function cp(r){if(r.charAt(0)!=="/")throw new Le('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Ot.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Le(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Le(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Le("Incomplete multiaddr");return e}function up(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ot.getProtocol(e.code);if(t==null)throw new Le(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function bb(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:dr(e,t)}var wb=Symbol.for("nodejs.util.inspect.custom"),tl=Symbol.for("@multiformats/multiaddr");function xb(r){if(r==null&&(r="/"),er(r))return r.getComponents();if(r instanceof Uint8Array)return ip(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),cp(r);if(Array.isArray(r))return r;throw new Le("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ei=class r{[tl]=!0;#e;#t;#n;constructor(e="/",t={}){this.#e=xb(e),t.validate!==!1&&Eb(this)}get bytes(){return this.#n==null&&(this.#n=ap(this.#e)),this.#n}toString(){return this.#t==null&&(this.#t=up(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Gs(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Q(this.bytes,e.bytes)}[wb](){return`Multiaddr(${this.toString()})`}};function Eb(r){r.getComponents().forEach(e=>{let t=Ot.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function er(r){return!!r?.[tl]}function re(r){return new ei(r)}var ae=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),O=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),lp=r=>({match:e=>r.match(e)===!1?e:!1}),G=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Re=(...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}}),X=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ce(...r){function e(o){if(o==null)return!1;let s=o.getComponents();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{matchers:r,matches:t,exactMatch:n}}var vb=O(421),fp=ce(vb),ri=O(54),ni=O(55),oi=O(56),nl=O(53),mC=ce(ri,G(O(421))),gC=ce(ni,G(O(421))),yC=ce(oi,G(O(421))),bC=ce(Re(nl,oi,ri,ni),G(O(421))),dp=X(O(4),G(O(43))),hp=X(G(O(42)),O(41),G(O(43))),ol=Re(dp,hp),ln=Re(ol,nl,ri,ni,oi),wC=ce(Re(ol,X(Re(nl,oi,ri,ni),G(O(421))))),sl=ce(dp),il=ce(hp),xC=ce(ol),al=X(ln,O(6)),wo=X(ln,O(273)),xo=ce(X(al,G(O(421)))),EC=ce(wo),cl=X(wo,ae(460),G(O(421))),si=X(wo,ae(461),G(O(421))),Sb=Re(cl,si),vC=ce(cl),pp=ce(si),rl=Re(ln,al,wo,cl,si),mp=Re(X(rl,ae(477),G(O(421)))),_r=ce(mp),gp=Re(X(rl,ae(478),G(O(421))),X(rl,ae(448),G(O(449)),ae(477),G(O(421)))),Eo=ce(gp),yp=X(wo,ae(280),G(O(466)),G(O(466)),G(O(421))),ul=ce(yp),bp=X(si,ae(465),G(O(466)),G(O(466)),G(O(421))),ll=ce(bp),ti=Re(mp,gp,X(al,G(O(421))),X(Sb,G(O(421))),X(ln,G(O(421))),yp,bp,O(421)),SC=ce(ti),Ab=X(G(ti),ae(290),lp(ae(281)),G(O(421))),Cr=ce(Ab),_b=Re(X(ti,ae(290),ae(281),G(O(421))),X(ti,ae(281),G(O(421))),X(ae(281),G(O(421)))),fl=ce(_b),Cb=X(ln,Re(X(O(6,"80")),X(O(6),ae(480)),ae(480)),G(O(481)),G(O(421))),AC=ce(Cb),Tb=X(ln,Re(X(O(6,"443")),X(O(6,"443"),ae(480)),X(O(6),ae(443)),X(O(6),ae(448),ae(480)),X(ae(448),ae(480)),ae(448),ae(443)),G(O(481)),G(O(421))),_C=ce(Tb),Ib=Re(X(O(777),G(O(421)))),CC=ce(Ib),Lb=Re(X(O(400),G(O(421)))),TC=ce(Lb);function wp(r,e){let t=xo.exactMatch(r),n=xo.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=Eo.exactMatch(r),s=Eo.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=_r.exactMatch(r),a=_r.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=fl.exactMatch(r),u=fl.exactMatch(e);if(c&&!u)return-1;if(!c&&u)return 1;let l=ul.exactMatch(r),f=ul.exactMatch(e);if(l&&!f)return-1;if(!l&&f)return 1;let d=ll.exactMatch(r),h=ll.exactMatch(e);return d&&!h?-1:!d&&h?1:0}function xp(r,e){let t=yo(r),n=yo(e);return t&&!n?1:!t&&n?-1:0}function Ep(r,e){let t=Pt(r),n=Pt(e);return t&&!n?1:!t&&n?-1:0}function vp(r,e){let t=Cr.exactMatch(r),n=Cr.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function Ce(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ii=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},fn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ii(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 ii(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 dl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function dn(r={}){return Pb(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 Pb(r,e){e=e??{};let t=e.onEnd,n=new fn,o,s,i,a=Ce(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,b)=>{s=S=>{s=null,n.push(S);try{g(r(n))}catch(w){b(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ce()})}},u=g=>s!=null?s(g):(n.push(g),o),l=g=>(n=new fn,s!=null?s({error:g}):(n.push({error:g}),o)),f=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?l(g):u({done:!0})),h=()=>(n=new fn,d(),{done:!0}),y=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async g=>{let b=g?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let S,w;b!=null&&(S=new Promise((v,A)=>{w=()=>{A(new dl)},b.addEventListener("abort",w)}));try{await Promise.race([a.promise,S])}finally{w!=null&&b!=null&&b?.removeEventListener("abort",w)}}},t==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(g){return p.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(g){return p.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return p.readableLength},onEmpty:g=>p.onEmpty(g)},o}var hl=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Db=r=>"reason"in r?r.reason:new DOMException("This operation was aborted.","AbortError"),Rb=2**31-1,Ob=(r,e)=>{if(typeof r!="number"||Math.sign(r)!==1)return new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(typeof e?.setTimeout!="function"||typeof e?.clearTimeout!="function")return new TypeError("Expected `customTimers` to have a `setTimeout` and a `clearTimeout` function")};function pl(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=()=>{try{r.cancel?.()}catch{}},f=new Promise((d,h)=>{let y=()=>{h(Db(i)),u()},p=Ob(t,s);try{p?h(p):i?.aborted?y():i&&(c=y,i.addEventListener("abort",c,{once:!0}))}finally{r.then(d,h)}if(p||i?.aborted||t>Rb)return;let g=n||o===!1||o instanceof Error?void 0:new hl(o??`Promise timed out after ${t} milliseconds`);a=s.setTimeout.call(void 0,()=>{if(n)try{d(n())}catch(b){h(b)}else o===!1?d():h(o instanceof Error?o:g);u()},t)}).finally(()=>{try{f.clear()}catch{}try{c&&i.removeEventListener("abort",c)}catch{}});return f.clear=()=>{a!==void 0&&(s.clearTimeout.call(void 0,a),a=void 0)},f}var Sp=r=>typeof r=="function"?{filter:r}:{...r},kb=r=>r===1/0||Number.isSafeInteger(r)&&r>=0,Nb=[["addEventListener","removeEventListener"],["on","off"],["addListener","removeListener"]],Mb=r=>{for(let[e,t]of Nb){let n=r?.[e],o=r?.[t];if(typeof n=="function"&&typeof o=="function")return{addListener:n.bind(r),removeListener:o.bind(r)}}throw new TypeError("Emitter is not compatible")},Bb=r=>{let e=new Map;for(let[t,n]of r)for(let o of Array.isArray(t)?t:[t])e.has(o)||e.set(o,n);return e},Fb=({addListener:r,removeListener:e,handlers:t,signal:n,abortHandler:o,isDone:s})=>{n?.addEventListener("abort",o,{once:!0});for(let[i,a]of t)if(r(i,a),s()){e(i,a);return}},Ub=({removeListener:r,handlers:e,signal:t,abortHandler:n})=>{for(let[o,s]of e)r(o,s);t?.removeEventListener("abort",n)},Kb=(r,e,t)=>{let n=Promise.resolve();return(o,s)=>{n=n.then(async()=>{if(e())return;let i;try{i=r?await r(o):!0}catch(a){e()||t(a);return}e()||s(i)})}};function qb(r,e,t){let n=()=>{},o=!1,s,i=new Promise((a,c)=>{t=Sp(t);let{filter:u}=t;if(!kb(t.count))throw new TypeError("The `count` option should be at least 0 or more");if(typeof t.timeout=="number"&&!(t.timeout>0))throw new TypeError(`Expected the \`timeout\` option to be a positive number, got \`${t.timeout}\``);t.signal?.throwIfAborted();let{addListener:l,removeListener:f}=Mb(r);if(t.count===0){a([]);return}let d=[],h=v=>{n(),c(v)},y=Kb(u,()=>o,h),p=v=>{d.push(v),t.count===d.length&&(n(),a(d))},g=(...v)=>{if(o)return;let A=t.multiArgs?v:v[0];if(!u){p(A);return}y(A,M=>{M&&p(A)})},b=(...v)=>{h(t.rejectionMultiArgs?v:v[0])},S=()=>{h(t.signal.reason)},w={addListener:l,removeListener:f,handlers:Bb([[e,g],[t.rejectionEvents??["error"],b]]),signal:t.signal,abortHandler:S,isDone:()=>o};n=()=>{o=!0,clearTimeout(s),Ub(w)},Fb(w),!(o||!t.resolveImmediately)&&(Number.isFinite(t.timeout)&&t.timeout<=2**31-1&&(s=setTimeout(n,t.timeout)),a(d))});if(i.cancel=n,typeof t.timeout=="number"&&t.timeout>0&&!t.resolveImmediately){let a=pl(i,{milliseconds:t.timeout});return a.cancel=()=>{n(),a.clear()},a}return i}function pt(r,e,t){let n=qb(r,e,{...Sp(t),count:1,resolveImmediately:!1}),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function vo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var ai=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}},ci=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Tr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function $b(r){return r.reason}function je(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??$b;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var ui=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ce(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Qe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function zb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ap=new WeakMap,li=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=zb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 Qe),this.cleanup())}async join(e){let t=new ui(e);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 je(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof t=="object"&&t!==null){let n=Ap.get(t);if(n==null&&(n=new WeakSet,Ap.set(t,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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.deferred.reject(e.signal?.reason??new Qe),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var hn=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=[],this.emitEmpty=vo(this.emitEmpty.bind(this),1),this.emitIdle=vo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!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 ci;let n=new li(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Qe)}),this.clear()}async onEmpty(e){this.size!==0&&await pt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await pt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await pt(this,"idle",e)}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=dn({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.error)},i=()=>{n()},a=()=>{n(new Qe("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function Et(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.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}var pn=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 Vb=1.2,Hb=2,Wb=5e3,Gb=6e4,jb=5e3,fi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??jb;this.success=new pn(t),this.failure=new pn(t),this.next=new pn(t),this.failureMultiplier=e.failureMultiplier??Hb,this.timeoutMultiplier=e.timeoutMultiplier??Vb,this.minTimeout=e.minTimeout??Wb,this.maxTimeout=e.maxTimeout??Gb,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=Et([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();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 ml=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ce(),this.haveNext=Ce()}[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=Ce(),e}async throw(e){return this.ended=!0,this.error=e,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 this.ended=!0,this.nextResult=e,this.haveNext.resolve(),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 this.error??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=Ce(),await je(this.readNext.promise,t?.signal,t)}};function _p(){return new ml}function Cp(r){return r[Symbol.asyncIterator]!=null}async function Yb(r,e,t){try{await Promise.all(r.map(async n=>{for(;;){let{value:o,done:s}=await n.next();if(s===!0)break;await e.push(o,{signal:t}),t.throwIfAborted()}})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Xb(r){let e=new AbortController,t=_p(),n=r.map(o=>Cp(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());Yb(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let o of n)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*Zb(r){for(let e of r)yield*e}function Qb(...r){let e=[];for(let t of r)Cp(t)||e.push(t);return e.length===r.length?Zb(e):Xb(r)}var mn=Qb;var Jb=4194304,di=class extends Error{static name="UnwrappedError";name="UnwrappedError"},yl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},wl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ew(r){return typeof r?.closeRead=="function"}function tw(r){return typeof r?.close=="function"}function gl(r){return ew(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:tw(r)?r.status!=="open":!1}function rw(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function xl(r,e){let t=e?.maxBufferSize??Jb,n=new ne,o,s=!1,i;if(!rw(r))throw new T("Argument should be a Stream or a Multiaddr");let a=f=>{if(!s&&i==null){if(n.append(f.data),n.byteLength>t){let d=n.byteLength;n.consume(d);let h=new $o(`Read buffer overflow - ${d} > ${t}`);i=h,o?.reject(h),queueMicrotask(()=>{r.abort(h)});return}o?.resolve()}};r.addEventListener("message",a);let c=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",c);let u=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",u);let l={readBuffer:n,async read(f){if(s===!0)throw new di("Stream was unwrapped");if(i!=null)throw i;if(gl(r)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new Tr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let d=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await je(o.promise,f?.signal),gl(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let h=f?.bytes??n.byteLength;if(n.byteLength<h){if(gl(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Tr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(f)}let y=n.sublist(0,h);return n.consume(h),y},async write(f,d){if(s===!0)throw new di("Stream was unwrapped");r.send(f)||await pt(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",a),r.removeEventListener("close",c),r.removeEventListener("remoteCloseWrite",u),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n),n.consume(n.byteLength))),r}};return l}function hi(r,e={}){let t=xl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ae(e.maxDataLength));let n=e?.lengthDecoder??dr,o=e?.lengthEncoder??Yt;return{async read(i){let a=-1,c=new ne;for(;;){let l=await t.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new yl("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new wl(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new bl(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await t.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Tr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new Tr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new ne(o(i.byteLength),i),a)},async writeV(i,a){let c=new ne(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var pi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},gn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},mi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},So=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function gi(r){return r[Symbol.asyncIterator]!=null}function Tp(r,e){if(r.byteLength>e)throw new gn("Message length too long")}var bi=r=>{let e=Ae(r),t=Se(e);return Yt(r,t),bi.bytes=e,t};bi.bytes=0;function wi(r,e){e=e??{};let t=e.lengthEncoder??bi,n=e?.maxDataLength??4194304;function*o(s){Tp(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return gi(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}wi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??bi,n=e?.maxDataLength??4194304;return Tp(r,n),new ne(t(r.byteLength),r)};var Ir;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ir||(Ir={}));var vl=r=>{let e=dr(r);return vl.bytes=Ae(e),e};vl.bytes=0;function El(r,e){let t=new ne,n=Ir.LENGTH,o=-1,s=e?.lengthDecoder??vl,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ir.LENGTH)try{if(o=s(t),o<0)throw new pi("Invalid message length");if(o>a)throw new gn("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Ir.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new mi("Message length length too long");break}throw u}if(n===Ir.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Ir.LENGTH}}}return gi(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new So("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new So("Unexpected end of input")})()}El.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return El(n,{...e??{},onLength:s=>{t=s}})};var xi=class extends hn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ei=class extends hn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var vi=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Sl}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 ai("Rate limit exceeded",i);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)}},Sl=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}};var Al=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 Oe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Al({name:e,metrics:t}):n=new Map,n}var _l=class extends it{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 Cl(r){let{name:e,metrics:t}=r,n;return t!=null?n=new _l({name:e,metrics:t}):n=new it,n}var Ao;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:pe(0),payloadType:pe(0),payload:pe(0),signature:pe(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Ao||(Ao={}));var Si=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var yn=class r{static createFromProtobuf=e=>{let t=Ao.decode(e),n=so(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=Ip(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new Si("Envelope signature is not valid for the given domain");return o};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=Ao.encode({publicKey:rt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Q(this.marshal(),e.marshal())}async validate(e,t){let n=Ip(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Ip=(r,e,t)=>{let n=I(r),o=Yt(n.byteLength),s=Yt(e.length),i=Yt(t.length);return new ne(o,n,s,e,i,t)};var Lp="libp2p-peer-record",Pp=Uint8Array.from([3,1]);var _o;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ke((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let y={multiaddr:pe(0)},p=d==null?f.len:f.pos+d;for(;f.pos<p;){let g=f.uint32();g>>>3===1?y.multiaddr=f.bytes():f.skipType(g&7)}return y},function*(f,d,h,y={}){let p=d==null?f.len:f.pos+d;for(;f.pos<p;){let g=f.uint32();g>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(g&7)}})),a);function c(f){return Fe(f,i.codec())}i.encode=c;function u(f,d){return Be(f,i.codec(),d)}i.decode=u;function l(f,d){return Ue(f,i.codec(),d)}i.stream=l})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ke((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let u of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(u,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={peerId:pe(0),seq:0n,addresses:[]},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.peerId=i.bytes();break}case 2:{u.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&u.addresses.length===c.limits.addresses)throw new st('Decode error - repeated field "addresses" had too many elements');u.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(f&7);break}}}return u},function*(i,a,c,u={}){let l={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(u.limits?.addresses!=null&&l.addresses===u.limits.addresses)throw new st('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:u.limits?.addresses$}))yield{...h,index:l.addresses};l.addresses++;break}default:{i.skipType(d&7);break}}}})),t);function n(i){return Fe(i,r.codec())}r.encode=n;function o(i,a){return Be(i,r.codec(),a)}r.decode=o;function s(i,a){return Ue(i,r.codec(),a)}r.stream=s})(_o||(_o={}));function Dp(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 Lr=class r{static createFromProtobuf=e=>{let t=_o.decode(e),n=en(At(t.peerId)),o=(t.addresses??[]).map(i=>re(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Lp;static CODEC=Pp;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=_o.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||!Dp(this.multiaddrs,e.multiaddrs))}};function ow(r){return r[Symbol.asyncIterator]!=null}function sw(r){if(ow(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Co=sw;var Ye=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Ai(r,e,t,n){let o=new Ye(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){Il(t,"abort",f),Il(r,e,u),Il(r,s,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Tl(t,"abort",f),Tl(r,e,u),Tl(r,s,l)})}function Tl(r,e,t){r!=null&&(Rp(r)?r.addEventListener(e,t):r.addListener(e,t))}function Il(r,e,t){r!=null&&(Rp(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Rp(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var _i=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Ci=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ye)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function iw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ti=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=iw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ye),this.cleanup())}async join(e={}){let t=new Ci(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 je(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)})}};function Ll(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var To=class extends Ne{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Ll(this.emitEmpty.bind(this),1),this.emitIdle=Ll(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let 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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new _i;let n=new Ti(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(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("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ye)}),this.clear()}async onEmpty(e){this.size!==0&&await Ai(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ai(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ai(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=dn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ye("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ii="lock:worker:request-read",Li="lock:worker:abort-read-request",Pi="lock:worker:release-read",Di="lock:master:grant-read",Ri="lock:master:error-read",Oi="lock:worker:request-write",ki="lock:worker:abort-write-request",Ni="lock:worker:release-write",Mi="lock:master:grant-write",Bi="lock:master:error-write",Fi="lock:worker:finalize",Ui="mortice",Op={singleProcess:!1};var Pl=(r,e,t,n,o,s,i,a,c)=>u=>{if(u.data==null)return;let l={type:u.data.type,name:u.data.name,identifier:u.data.identifier};l.type===o&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let y={type:h.data.type,name:h.data.name,identifier:h.data.identifier};y.type===a&&y.identifier===l.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===s&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===Fi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var kp=(r=10)=>Math.random().toString().substring(2,r+2);var Ki=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Ui)}readLock(e){return this.sendRequest(Ii,Li,Di,Ri,Pi,e)}writeLock(e){return this.sendRequest(Oi,ki,Mi,Bi,Ni,e)}finalize(){this.channel.postMessage({type:Fi,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=kp();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",l,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),u(h)}};this.channel.addEventListener("message",f)})}};var Np=r=>{if(r=Object.assign({},Op,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Ui),n=new Ne;return t.addEventListener("message",Pl(n,t,"requestReadLock","abortReadLockRequest",Ii,Li,Ri,Pi,Di)),t.addEventListener("message",Pl(n,t,"requestWriteLock","abortWriteLockRequest",Oi,ki,Bi,Ni,Mi)),n}return new Ki(r.name)};var Pr=new Map,Io;function Mp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function aw(r){if(Io==null&&(Io=Np(r),!Mp(Io))){let e=Io;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Pr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Pr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Pr.get(n);o?.finalize()})}return Io}async function Dl(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ye)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var Bp=(r,e)=>{let t=Pr.get(r);if(t!=null)return t;let n=aw(e);if(Mp(n))return t=n,Pr.set(r,t),t;let o=new To({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Dl(s,i);s=new To({concurrency:e.concurrency,autoStart:!1});let a=s,c=Dl(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Dl(o,i)},finalize:()=>{Pr.delete(r)},queue:o},Pr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var cw={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Rl(r){let e=Object.assign({},cw,r);return Bp(e.name,e)}var kt;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ke((d,h,y={})=>{y.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),y.lengthDelimited!==!1&&h.ldelim()},(d,h,y={})=>{let p={key:"",value:pe(0)},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let b=d.uint32();switch(b>>>3){case 1:{p.key=d.string();break}case 2:{p.value=d.bytes();break}default:{d.skipType(b&7);break}}}return p},function*(d,h,y,p={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let b=d.uint32();switch(b>>>3){case 1:{yield{field:`${y}.key`,value:d.string()};break}case 2:{yield{field:`${y}.value`,value:d.bytes()};break}default:{d.skipType(b&7);break}}}})),c);function u(d){return Fe(d,a.codec())}a.encode=u;function l(d,h){return Be(d,a.codec(),h)}a.decode=l;function f(d,h){return Ue(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=Ke((d,h,y={})=>{y.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Po.codec().encode(d.value,h)),y.lengthDelimited!==!1&&h.ldelim()},(d,h,y={})=>{let p={key:""},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let b=d.uint32();switch(b>>>3){case 1:{p.key=d.string();break}case 2:{p.value=Po.codec().decode(d,d.uint32(),{limits:y.limits?.value});break}default:{d.skipType(b&7);break}}}return p},function*(d,h,y,p={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let b=d.uint32();switch(b>>>3){case 1:{yield{field:`${y}.key`,value:d.string()};break}case 2:{yield*Po.codec().stream(d,d.uint32(),`${y}.value`,{limits:p.limits?.value});break}default:{d.skipType(b&7);break}}}})),c);function u(d){return Fe(d,a.codec())}a.encode=u;function l(d,h){return Be(d,a.codec(),h)}a.decode=l;function f(d,h){return Ue(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ke((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let l of a.addresses)c.uint32(10),Lo.codec().encode(l,c);if(a.protocols!=null&&a.protocols.length>0)for(let l of a.protocols)c.uint32(18),c.string(l);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[l,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:l,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[l,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:l,value:f},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={addresses:[],protocols:[],metadata:new Map,tags:new Map},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(u.limits?.addresses!=null&&l.addresses.length===u.limits.addresses)throw new st('Decode error - repeated field "addresses" had too many elements');l.addresses.push(Lo.codec().decode(a,a.uint32(),{limits:u.limits?.addresses$}));break}case 2:{if(u.limits?.protocols!=null&&l.protocols.length===u.limits.protocols)throw new st('Decode error - repeated field "protocols" had too many elements');l.protocols.push(a.string());break}case 4:{l.publicKey=a.bytes();break}case 5:{l.peerRecordEnvelope=a.bytes();break}case 6:{if(u.limits?.metadata!=null&&l.metadata.size===u.limits.metadata)throw new to('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.metadata$value}});l.metadata.set(h.key,h.value);break}case 7:{if(u.limits?.tags!=null&&l.tags.size===u.limits.tags)throw new to('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.tags$value}});l.tags.set(h.key,h.value);break}case 8:{l.updated=a.uint64Number();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,u,l={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(l.limits?.addresses!=null&&f.addresses===l.limits.addresses)throw new st('Streaming decode error - repeated field "addresses" had too many elements');for(let y of Lo.codec().stream(a,a.uint32(),`${u}.addresses[]`,{limits:l.limits?.addresses$}))yield{...y,index:f.addresses};f.addresses++;break}case 2:{if(l.limits?.protocols!=null&&f.protocols===l.limits.protocols)throw new st('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${u}.protocols[]`,index:f.protocols,value:a.string()},f.protocols++;break}case 4:{yield{field:`${u}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${u}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(l.limits?.metadata!=null&&f.metadata===l.limits.metadata)throw new st('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${u}.metadata{}`,{limits:{value:l.limits?.metadata$value}}),f.metadata++;break}case 7:{if(l.limits?.tags!=null&&f.tags===l.limits.tags)throw new st('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${u}.tags{}`,{limits:{value:l.limits?.tags$value}}),f.tags++;break}case 8:{yield{field:`${u}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Fe(a,r.codec())}r.encode=o;function s(a,c){return Be(a,r.codec(),c)}r.decode=s;function i(a,c){return Ue(a,r.codec(),c)}r.stream=i})(kt||(kt={}));var Lo;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:pe(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Lo||(Lo={}));var Po;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Po||(Po={}));function uw(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=so(e.publicKey,t);return fo(n)}function Fp(r,e,t){let n=kt.decode(e);return bn(r,n,t)}function bn(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:uw(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:re(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Up(r,e){return lw(r.addresses,e.addresses)&&fw(r.protocols,e.protocols)&&dw(r.publicKey,e.publicKey)&&hw(r.peerRecordEnvelope,e.peerRecordEnvelope)&&pw(r.metadata,e.metadata)&&mw(r.tags,e.tags)}function lw(r,e){return qp(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Q(t.multiaddr,n.multiaddr)))}function fw(r,e){return qp(r,e,(t,n)=>t===n)}function dw(r,e){return Kp(r,e)}function hw(r,e){return Kp(r,e)}function pw(r,e){return $p(r,e,(t,n)=>Q(t,n))}function mw(r,e){return $p(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Kp(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Q(r,e):!1}function qp(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function $p(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Nt="/",zp=new TextEncoder().encode(Nt),qi=zp[0],Dr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=I(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]!==qi)throw new Error("Invalid key")}toString(e="utf8"){return F(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Nt))}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=zp),this._buf[0]!==qi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(qi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===qi;)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(Nt).slice(1)}type(){return gw(this.baseNamespace())}name(){return yw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Nt)||(e+=Nt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Nt):new r(e.slice(0,-1).join(Nt))}child(e){return this.toString()===Nt?e:e.toString()===Nt?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(),...bw(e.map(t=>t.namespaces()))])}};function gw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function yw(r){let e=r.split(":");return e[e.length-1]}function bw(r){return[].concat(...r)}var Ol="/peers/";function Do(r){if(!Ft(r)||r.type==null)throw new T("Invalid PeerId");let e=r.toCID().toString();return new Dr(`${Ol}${e}`)}async function Vp(r,e,t,n,o){let s=o?.maxAddresses??1/0,i=new Map;for(let c of t){if(c==null)continue;if(c.multiaddr instanceof Uint8Array&&(c.multiaddr=re(c.multiaddr)),!er(c.multiaddr))throw new T("Multiaddr was invalid");if(!await e(r,c.multiaddr,o))continue;let u=c.isCertified??!1,l=c.multiaddr.toString(),f=i.get(l);f!=null?c.isCertified=f.isCertified||u:i.set(l,{multiaddr:c.multiaddr,isCertified:u})}let a=[...i.entries()];return a.length>s&&(o?.log?.("%p has %d addresses, only storing %d",r,a.length,s),a=[...a.filter(([,c])=>c.isCertified),...a.filter(([,c])=>!c.isCertified)].slice(0,s)),a.sort(([c],[u])=>c.localeCompare(u)).map(([,{isCertified:c,multiaddr:u}])=>{let l=u.getComponents().find(f=>f.code===421)?.value;return r.equals(l)&&(u=u.decapsulate(re(`/p2p/${r}`))),{isCertified:c,multiaddr:u.bytes}})}async function zi(r,e,t,n){if(e==null)throw new T("Invalid PeerData");if(e.publicKey!=null&&!r.equals(e.publicKey.toMultihash().bytes))throw new T("publicKey does not match peer id");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new T("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(y=>({isCertified:!1,multiaddr:y}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let y=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=$i(y,{validate:Hp})}if(e.tags!=null){let y=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=$i(y,{validate:Wp,map:Gp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(y=>({isCertified:!1,multiaddr:y}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let y=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[p,g]of y)g==null?a.delete(p):a.set(p,g);a=$i([...a.entries()],{validate:Hp})}if(e.tags!=null){let y=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),p=new Map(c);for(let[g,b]of y)b==null?p.delete(g):p.set(g,b);c=$i([...p.entries()],{validate:Wp,map:Gp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=rt(o.id.publicKey):e.publicKey!=null?l=rt(e.publicKey):r.publicKey!=null&&(l=rt(r.publicKey));let f={addresses:await Vp(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((y,p)=>y.localeCompare(p)),metadata:a,tags:c,publicKey:l,peerRecordEnvelope:u},d=new Map;for(let y of n.existingPeer?.peerPB.addresses??[]){let p=F(y.multiaddr,"base64");y.observed!=null&&!d.has(p)&&d.set(p,y.observed)}let h=Date.now();return f.addresses.forEach(y=>{y.observed=d.get(F(y.multiaddr,"base64"))??h}),r.type!=="RSA"&&delete f.publicKey,f}function $i(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 Hp(r,e){if(typeof r!="string")throw new T("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new T("Metadata value must be a Uint8Array")}function Wp(r,e){if(typeof r!="string")throw new T("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new T("Tag value must be an integer");if(e.value<0||e.value>100)throw new T("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new T("Tag ttl must be an integer");if(e.ttl<0)throw new T("Tag ttl must be between greater than 0")}}function Gp(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function jp(r){let e=r.toString().split("/")[2],t=xe.parse(e,et);return _u(t)}function kl(r,e,t){let n=jp(r);return Fp(n,e,t)}function ww(r,e){return{prefix:Ol,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(kl(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(kl(n.key,n.value,e),kl(o.key,o.value,e)))}}var Vi=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;maxAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Cl({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5,this.maxAddresses=t.maxAddresses??100}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:Rl({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Do(e),t)}async load(e,t){let n=Do(e),o=await this.datastore.get(n,t),s=kt.decode(o);if(this.#a(e,s))throw await this.datastore.delete(n,t),new nr;return bn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await zi(e,t,"patch",{...n,addressFilter:this.addressFilter,maxAddresses:this.#n(e),log:this.log});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await zi(e,t,"patch",{...n,addressFilter:this.addressFilter,maxAddresses:this.#n(e),log:this.log,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await zi(e,t,"merge",{addressFilter:this.addressFilter,maxAddresses:this.#n(e),log:this.log,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(ww(e??{},this.maxAddressAge),e)){let o=jp(t);if(o.equals(this.peerId))continue;let s=kt.decode(n);if(this.#a(o,s)){await this.datastore.delete(t,e);continue}yield bn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Do(e),o=await this.datastore.get(n,t),s=kt.decode(o);if(this.#a(e,s))throw await this.datastore.delete(n,t),new nr;return{peerPB:s,peer:bn(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=kt.encode(t);return await this.datastore.put(Do(e),s,o),{peer:bn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Up(t,n.peerPB)}}#n(e){return this.peerId.equals(e)?1/0:this.maxAddresses}#a(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Nl=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 Vi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Co(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Ft(t)?t:Ft(t?.expectedPeer)?t.expectedPeer:void 0,s=Ft(t)||t===void 0?n:t,i=await yn.openAndCertify(e,Lr.DOMAIN,s),a=fo(i.publicKey);if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=Lr.createFromProtobuf(i.payload);if(!c.peerId.equals(a))return this.log("signing key did not match peer id in the peer record - signer: %p record: %p",a,c.peerId),!1;let u;try{u=await this.get(a,s)}catch(l){if(l.name!=="NotFoundError")throw l}if(u?.peerRecordEnvelope!=null){let l=yn.createFromProtobuf(u.peerRecordEnvelope),f=Lr.createFromProtobuf(l.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))},s),!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 Yp(r,e={}){return new Nl(r,e)}var Hi=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function xw(r){return r[Symbol.asyncIterator]!=null}function Ew(r){if(xw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ml=Ew;function vw(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 Xp=vw;function Sw(r){return r[Symbol.asyncIterator]!=null}function Aw(r,e){let t=0;if(Sw(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Xp(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(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 Rr=Aw;function _w(r){return r[Symbol.asyncIterator]!=null}function Cw(r,e){return _w(r)?(async function*(){yield*(await Co(r)).sort(e)})():(function*(){yield*Co(r).sort(e)})()}var Bl=Cw;function Tw(r){return r[Symbol.asyncIterator]!=null}function Iw(r,e){return Tw(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 Fl=Iw;var Wi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value: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 Ml(this.putMany(e,n)),e=[],await Ml(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=Rr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Rr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Bl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Rr(n,()=>o++>=s)}return e.limit!=null&&(n=Fl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Rr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Rr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Bl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Rr(n,()=>s++>=o)}return e.limit!=null&&(n=Fl(n,e.limit)),n}};var Gi=class extends Wi{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Hi;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new Dr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Dr(n),t?.signal?.throwIfAborted()}};var Zp=864e13;var ji=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Oe({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=Y(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=rn(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?Zp-Date.now():0,lastVerified:o?Zp-Date.now():void 0})})}remove(e){let t=Y(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!Ie(o))continue;let s=Y(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),re(n)}confirm(e,t){let n=Y(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=Y(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Yi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Oe({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=Y(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:ht(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=Y(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!Ie(n))continue;let o=Y(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(u=>u.code===4||u.code===41),c=i.findIndex(u=>u.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,re(i)):e}confirm(e,t){if(!Ie(e))return!1;let n=Y(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!Ie(e))return!1;let n=Y(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var Lw={maxObservedAddresses:10},Xi=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Oe({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Lw.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Pt(e)||Xh(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:re(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var Pw={maxObservedAddresses:10},Zi=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Oe({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Pw.maxObservedAddresses}get(e,t){if(Pt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!Ie(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!Ie(e))return e.toString();let t=Y(e);return`${t.host}-${t.port}-${t.protocol}`}};var Qp=6e4,Jp={maxObservedAddresses:10,addressVerificationTTL:Qp*10,addressVerificationRetry:Qp*5},Dw=r=>r;function Ul(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&xt(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var Qi=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Xi(e,t),this.dnsMappings=new ji(e,t),this.ipMappings=new Yi(e,t),this.transportAddresses=new Zi(e,t),this.announceFilter=t.announceFilter??Dw,this.observedAddressFilter=mo(1024),this.addressVerificationTTL=t.addressVerificationTTL??Jp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Jp.addressVerificationRetry,this._updatePeerStoreAddresses=vo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===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 - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>re(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=Y(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Ul(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Ul(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Ul(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=re(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(re(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${ht(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(re(`/ip${ht(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Ie(e))return!1;let t=Y(e);if(t.type!=="ip4"||rn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>_r.exactMatch(s)||Eo.exactMatch(s),s=>xo.exactMatch(s),s=>pp.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(u=>u.getAddrs().filter(l=>Y(l).type==="ip4"&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>!yo(u)).pop();if(a==null)continue;let c=Y(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var em;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(em||(em={}));var Ji=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},ea=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},wn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ro=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},ta=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},ra=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},na=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Oo=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},oa=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},sa=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},ia=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},aa=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},ca=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},tr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Or=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ua=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},la=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Kl=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=Us())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Qo(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")}},Rw=["metrics","connectionProtector","dns"],Ow=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function tm(r={}){let e=new Kl(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Ow.includes(o)){let i=e.components[o];if(i==null&&!Rw.includes(o))throw new Ji(`${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 rm(r){let e={};for(let t of Object.values(r.components))for(let n of kw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Nw(t))if(e[n]!==!0)throw new ea(`Service "${Mw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function kw(r){return Array.isArray(r?.[In])?r[In]:[]}function Nw(r){return Array.isArray(r?.[$a])?r[$a]:[]}function Mw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function nm(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>_r.matches(e)?!0:Pt(e)),r}var se=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function fa(r){if(Ft(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:xt(n),e.forEach(o=>{if(!er(o))throw new Mt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new T("Multiaddrs must all have the same peer id or have no peer id")}else{let i=xt(s);if(t?.equals(i)!==!0)throw new T("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!fp.exactMatch(n)),{peerId:t,multiaddrs:e}}var Bw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function om(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Bw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function ko(r){let e=Y(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new T(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new T(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Qt(e.host,t)}function ql(r){return!Cr.exactMatch(r)}function da(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>ql(s)))return n}var ha=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>ko(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new it;for(let c of e){let u=c.remotePeer;if(!o.has(u)){o.set(u,0);try{let l=await this.peerStore.get(u);o.set(u,[...l.tags.values()].reduce((f,d)=>f+d.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",l)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(l=>{if(Ie(c.remoteAddr)){let f=Y(c.remoteAddr);return l.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await om(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}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})}};var sm="last-dial-failure",im="last-dial-success";var am=100,pa=50;function Fw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function cm(r){return r.sort((e,t)=>xp(e.multiaddr,t.multiaddr)||Ep(e.multiaddr,t.multiaddr)||vp(e.multiaddr,t.multiaddr)||Fw(e,t)||wp(e.multiaddr,t.multiaddr))}var ma=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"},ga=class extends AggregateError{static name="EmptyDNSAnswerError";name="EmptyDNSAnswerError"};var zl=gf(lm(),1);var Vl=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},fm=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Hl(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(fm(i)),r.then(f,d);return}if(i&&(c=()=>{d(fm(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new Vl;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(y){d(y)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}function Wl(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 qw=100,xn=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:s}=this,i={priority:n,id:o,run:e};if(s===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#n();let a=Wl(this.#e,i,(c,u)=>u.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((s,i)=>i>=this.#t&&s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>qw&&this.#t>this.#e.length/2&&this.#n(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#n(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var Mo=class extends zl.default{#e;#t;#n=0;#a;#m=!1;#w=!1;#l;#x=0;#u;#f;#c;#i=[];#s=0;#r;#C;#o=0;#g;#d;#R=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:xn,strict:!1,...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})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#l=e.interval,this.#c=e.strict,this.#r=new e.queueClass,this.#C=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#d=e.autoStart===!1,this.#K()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#l)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#O(e){this.#c?this.#i.push(e):this.#n++}#k(){this.#c?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#S(){return this.#i.length-this.#s}get#N(){return this.#t?!0:this.#c?this.#S()<this.#a:this.#n<this.#a}get#M(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#F(){this.#f=void 0,this.#P(),this.#L()}#U(e){if(this.#c){if(this.#v(e),this.#S()>=this.#a){let n=this.#i[this.#s],o=this.#l-(e-n);return this.#T(o),!0}return!1}if(this.#u===void 0){let t=this.#x-e;if(t<0)this.#n=this.#e?this.#o:0;else return this.#T(t),!0}return!1}#T(e){this.#f===void 0&&(this.#f=setTimeout(()=>{this.#F()},e))}#A(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#I(){this.#f&&(clearTimeout(this.#f),this.#f=void 0)}#b(){if(this.#r.size===0){if(this.#A(),this.emit("empty"),this.#o===0){if(this.#I(),this.#c&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#d){let t=Date.now(),n=!this.#U(t);if(this.#N&&this.#M){let o=this.#r.dequeue();this.#t||(this.#O(t),this.#p()),n&&this.#L(),o(),this.emit("active"),e=!0}}return e}#L(){this.#t||this.#u!==void 0||this.#c||(this.#u=setInterval(()=>{this.#P()},this.#l),this.#x=Date.now()+this.#l)}#P(){this.#c||(this.#u!==void 0&&(this.#n===0&&this.#o===0?this.#A():this.#x=Date.now()+this.#l),this.#n=this.#e?this.#o:0),this.#_(),this.#p()}#_(){for(;this.#b(););}get concurrency(){return this.#g}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.#g=e,this.#_()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#r.setPriority(e,t)}async add(e,t={}){if(t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);return new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let u;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#q(),this.#y.delete(s),d}let l=e({signal:t.signal});if(t.timeout!==void 0&&(l=Hl(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#r.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((h,y)=>{u=()=>{y(d.reason)},d.addEventListener("abort",u,{once:!0}),d.aborted&&u()})])}let f=await l;n(f),this.emit("completed",f)}catch(l){o(l),this.emit("error",l)}finally{u&&t.signal?.removeEventListener("abort",u),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof xn){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:u}=t,l=()=>{i(),c(),o(u.reason),this.#b(),this.emit("next")};if(i=()=>{u.removeEventListener("abort",l),this.#E.delete(i)},u.aborted){l();return}u.addEventListener("abort",l,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#d?(this.#d=!1,this.#_(),this):this}pause(){this.#d=!0}clear(){for(let e of this.#E)e();this.#r=new this.#C,this.#A(),this.#D(),this.emit("empty"),this.#o===0&&(this.#I(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#h(["next","active"],()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#h("idle")}async onPendingZero(){this.#o!==0&&await this.#h("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#h("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#h("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#h(e,t){let n=Array.isArray(e)?e:[e];return new Promise(o=>{let s=()=>{if(!(t&&!t())){for(let i of n)this.off(i,s);o()}};for(let i of n)this.on(i,s)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#d}#K(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#D()}))}#q(){this.#t||(this.#k(),this.#p())}#D(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#c){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#n;let n=t>=this.#a;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function ba(r){let e=[Xe.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Gl=60;function wa(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:Xe[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Xe[e.type],TTL:e.TTL??e.ttl??Gl,data:e.data instanceof Uint8Array?F(e.data):e.data}))}}var $w=4;function jl(r,e={}){let t=new Mo({concurrency:e.queryConcurrency??$w});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),ba(o.types).forEach(c=>{i.append("type",Xe[c])}),o.onProgress?.(new se("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let u=wa(await c.json());return o.onProgress?.(new se("dns:response",u)),u},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function dm(){return[jl("https://cloudflare-dns.com/dns-query"),jl("https://dns.google/resolve")]}var mm=gf(pm(),1);var Yl=class{lru;constructor(e){this.lru=(0,mm.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 wa({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:Xe[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??Gl)*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 gm(r){return new Yl(r)}var zw=1e3,Vw=()=>Math.random()>.5?-1:1,xa=class{resolvers;cache;logger;sorter;constructor(e){this.resolvers={},this.cache=gm(e.cacheSize??zw),this.logger=e.logger,this.sorter=e.sorter??Vw,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["."]=dm())}async query(e,t={}){let n=ba(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new se("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(this.sorter),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,logger:this.logger,types:n});if(u.Answer.length===0)throw new ga("Query result had no answers");for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new se("dns:error",u))}}throw new ma(a,`DNS lookup of ${e} ${n} failed`)}};var Xe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Xe||(Xe={}));function ym(r={}){return new xa(r)}var Xl=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let o=this.getDNS(t),s;try{s=await o.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[Xe.TXT]})}catch(c){if(c.name==="DNSQueryFailedError"&&Array.isArray(c.errors)&&c.errors.length>0&&c.errors.every(l=>l.name==="EmptyDNSAnswerError"))return[];throw c}let i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let u=c.data.replace(/["']/g,"").trim().split("=")[1];u!=null&&(i!=null&&!u.includes(i)||a.push(re(u)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=ym()),this.dns)}},kr=new Xl;async function Zl(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new la("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Zl(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var En={maxParallelDials:pa,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:kr}},Ea=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??En.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??En.maxDialQueueLength,this.dialTimeout=t.dialTimeout??En.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??En.addressDialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??En.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Ei({concurrency:t.maxParallelDials??En.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Qe.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=fa(e);if(n!=null&&t.force!==!0){let i=da(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new se("dial-queue:already-connected",i)),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new se("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Mr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new se("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new se("dial-queue:start-dial"));let a=Et([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??rf,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}l.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(h=>h.multiaddr.toString())),e?.onProgress?.(new se("dial-queue:calculated-addresses",l));for(let h of l){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Mr("Peer had more than maxPeerAddrsToDial");a++;let y=Et([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:y});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[im]:I(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}return p}catch(p){if(this.log.error("dial failed to %a - %e",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[sm]:I(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}if(t.aborted)throw new Go(p.message);u.push(p)}finally{y.clear()}}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:re(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Mr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Oo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await Zl(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new ia(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=this.addressSorter==null?cm(u):u.sort(this.addressSorter);if(l.length===0)throw new Oo(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}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=>!Cr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var Hw=Object.prototype.toString,Ww=r=>Hw.call(r)==="[object Error]",Gw=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function nf(r){if(!(r&&Ww(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:Gw.has(t)}function jw(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");if(Number.isFinite(r)&&!Number.isInteger(r))throw new TypeError("Expected `retries` to be a non-negative integer or Infinity.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function va(r,e,{allowInfinity:t=!1}={}){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${t?" or Infinity":""}.`);if(!t&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<0)throw new TypeError(`Expected \`${r}\` to be \u2265 0.`)}function Bo(r,e,t){if(e!=null&&typeof e!==t)throw new TypeError(`Expected \`${r}\` to be a ${t}.`)}function Yw(r){if(r!=null&&(typeof r.throwIfAborted!="function"||typeof r.addEventListener!="function"||typeof r.removeEventListener!="function"))throw new TypeError("Expected `signal` to be an AbortSignal.")}var Sa=class r extends Error{constructor(e){super(typeof e=="string"?e:void 0),this.name="AbortError",e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),{message:e}=this.originalError,Error.captureStackTrace?.(this.originalError,r)),this.message=e}},Xw=2**31-1;function Zw(r,e){if(e.minTimeout===0)return 0;let t=r+1,n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return Math.min(o,Math.ceil(e.maxTimeout),Xw)}function of(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function Qw(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}function Jw(r){try{return String(r)}catch{return Object.prototype.toString.call(r)}}function ex(r){let e=r;for(;e instanceof Sa&&e.originalError instanceof Error;)e=e.originalError;return e}async function tx({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=()=>{o.signal?.throwIfAborted()},i=r instanceof Error?r:new TypeError(`Non-error was thrown: "${Jw(r)}". You should only throw errors.`);if(s(),i instanceof Sa)throw ex(i);let a=o.retries-t,c=!(i instanceof TypeError)||nf(i),u=of(n,o.maxRetryTime),l=c&&u>0&&a>0?Zw(t,o):0,f=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:t,retryDelay:l}),d=await o.shouldConsumeRetry(f)??!0;s();let h=d?l:0,y=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:t,retryDelay:h});await o.onFailedAttempt(y),s();let p=of(n,o.maxRetryTime);if(!c||p<=0||a<=0)throw i;let g=await o.shouldRetry(y);if(s(),!g)throw i;let b=of(n,o.maxRetryTime);if(b<=0)throw i;return d?(await Qw(Math.min(h,b),o),!0):!1}async function sf(r,e={}){if(e={...e},e.retries??=10,jw(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=1/0,e.maxRetryTime??=1/0,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Bo("onFailedAttempt",e.onFailedAttempt,"function"),Bo("shouldRetry",e.shouldRetry,"function"),Bo("shouldConsumeRetry",e.shouldConsumeRetry,"function"),Bo("randomize",e.randomize,"boolean"),Bo("unref",e.unref,"boolean"),Yw(e.signal),va("factor",e.factor),va("minTimeout",e.minTimeout),va("maxTimeout",e.maxTimeout,{allowInfinity:!0}),va("maxRetryTime",e.maxRetryTime,{allowInfinity:!0}),e.factor===0&&(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await tx({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Aa=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new xi({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);bm(t)&&(this.queue.has(e)||this.queue.add(async n=>{await sf(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",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(Ka)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>bm(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function bm(r){for(let e of r.tags.keys())if(e.startsWith(Ka))return!0;return!1}var rf=50,af={maxConnections:am,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},_a=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??af.maxConnections,this.maxConnections<1)throw new T("Connection Manager maxConnections must be greater than 0");this.connections=new it,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=>ko(re(n))),this.deny=(t.deny??[]).map(n=>ko(re(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??af.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new vi({points:t.inboundConnectionThreshold??af.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ha({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>re(n))}),this.dialQueue=new Ea(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??pa,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:kr},connections:this.connections}),this.reconnectQueue=new Aa({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 bf(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await wf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([pt(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new T("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",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.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}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 St("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new se("connection:open",e));let{peerId:n,multiaddrs:o}=fa(e);if(this.peerId.equals(n))throw new Nr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=da(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new se("dial-queue:already-connected")),t.onProgress?.(new se("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??rf});if(s.status!=="open")throw new rr("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Mt("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new se("connection:opened",s)),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([pt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Ie(e.remoteAddr)){let s=Y(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(Ie(e.remoteAddr)){let s=Y(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(Ie(e.remoteAddr)){let o=Y(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!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=>re(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var ox=1e4,sx="1.0.0",ix="ping",ax="ipfs",wm=32,cx=!0,Ca=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??ax}/${ix}/${sx}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??ox,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??cx,this.timeout=new fi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[In]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o;try{o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let s=xl(o);t=Date.now(),await Promise.all([s.write(crypto.getRandomValues(new Uint8Array(wm)),{signal:n}),s.read({bytes:wm,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(s){if(o?.abort(s),s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",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)}};var Ta=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:F(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:F(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new wn("No content routers available");let n=this,o=new br;for await(let s of mn(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new wn("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new wn("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new St;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new St;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Ia=globalThis.CustomEvent??Event;async function*cf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=Ce(),a=Ce(),c=!1,u,l=!1,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=Ce(),await i.promise),l||f)break;let g={done:!1};s.push(g),p().then(b=>{g.done=!0,g.ok=!0,g.value=b,o.dispatchEvent(new Ia("task-complete"))},b=>{g.done=!0,g.err=b,o.dispatchEvent(new Ia("task-complete"))})}c=!0,o.dispatchEvent(new Ia("task-complete"))}catch(p){u=p,o.dispatchEvent(new Ia("task-complete"))}});function d(){return n?s[0]?.done:!!s.find(p=>p.done)}function*h(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw l=!0,i.resolve(),p.err;i.resolve()}}function*y(){for(;d();)for(let p=0;p<s.length;p++)if(s[p].done){let g=s[p];if(s.splice(p,1),p--,g.ok)yield g.value;else throw l=!0,i.resolve(),g.err;i.resolve()}}try{for(;;){if(d()||(a=Ce(),await a.promise),u!=null||(n?yield*h():yield*y(),u!=null))throw u;if(c&&s.length===0)break}}finally{f=!0,i.resolve()}}var La=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:F(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Ro("No peer routers available");if(e.toString()===this.peerId.toString())throw new ta("Should not try to find self");let n=this,o=mn(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new nr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ro("No peer routers available");let n=this,o=mo(1024);for await(let s of cf((async function*(){let i=mn(...n.routers.filter(a=>a.getClosestPeers instanceof Function).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 - %e",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Pa=class extends Ne{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Et([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Ce(),yield(await pt(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Et([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=crypto.getRandomValues(new Uint8Array(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 je(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("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var uf=32,lf=64,Da=class{log;topologies;handlers;components;middleware;globalMiddleware=[];constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Oe({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[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 ra(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new na(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:uf,maxOutboundStreams:lf,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new T("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))}use(e,t){if(typeof e=="function"){this.globalMiddleware.push(e);return}if(t==null)throw new T("Protocol middleware is required");this.middleware.set(e,t)}unuse(e){typeof e=="function"?this.globalMiddleware=this.globalMiddleware.filter(t=>t!==e):this.middleware.delete(e)}getMiddleware(e){return[...this.globalMiddleware,...this.middleware.get(e)??[]]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var Ra=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=Oe({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Oe({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Tn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new T("Transport must have a valid tag");if(this.transports.has(t))throw new T(`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 ua(`No transport available for address ${String(e)}`);return t?.onProgress?.(new se("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 St("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new oa)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let u=i.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(s)??[];l==null&&(l=[],this.listeners.set(s,l)),l.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let f=l.findIndex(d=>d===u);l.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),sl.matches(c)?t.ipv4.attempts++:il.matches(c)&&t.ipv6.attempts++,n.push(u.listen(c).then(()=>{t.errors.delete(c.toString()),sl.matches(c)&&t.ipv4.success++,il.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Tn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new sa(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
12
+ ${e}[Error list was empty]`,t.trim()}return Bh(r,e)}We.formatters.e=r=>r==null?"undefined":Uh(r);function V0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Us(r){return{forComponent(e){return Kh(e,r)}}}function Kh(r,e){let t=V0(`${r}:trace`);return We.enabled(`${r}:trace`)&&We.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=We(`${r}:trace`,e)),Object.assign(We(r,e),{error:We(`${r}:error`,e),trace:t,newScope:n=>Kh(`${r}:${n}`,e)})}function Fh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function yr(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 Ks(r){let e=At(ie.decode(`z${r}`));return en(e)}var it=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 yr(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 yr(this.map.values(),e=>e.key)}values(){return yr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var br=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 yr(this.set.entries(),e=>{let t=Ks(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Ks(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return yr(this.set.values(),e=>Ks(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 Tu={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},qh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},$h=new TextEncoder;function H0(r,e){let t=Tu[e],n=qh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function W0(r,e,t){if(t.length<4)throw new RangeError("The `utf8Buffer` option must have a length of at least 4");let n=Tu[e],o=qh[e],s=r;for(;s.length>0;){let i=$h.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 Iu(r,{size:e=32,utf8Buffer:t}={}){if(!Object.hasOwn(Tu,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 W0(r,e,t);r=$h.encode(r)}return H0(r,e)}var ho={hash:r=>Number(Iu(r,{size:32})),hashV:(r,e)=>G0(ho.hash(r,e))};function G0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),I(e,"base16")}var Lu=64,dt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Lu)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=pe(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?Q(this.fp,e.fp):!1}};function wr(r,e){return Math.floor(Math.random()*(e-r))+r}var xr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof dt))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 dt))throw new TypeError("Invalid Fingerprint");let t=wr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof dt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var j0=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??wr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=I(e));let t=new dt(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 xr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new xr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[wr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new xr(this.bucketSize));for(let a=0;a<j0;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 xr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=I(e));let t=new dt(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=I(e));let t=new dt(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}},Y0={1:.5,2:.84,4:.95,8:.98};function X0(r=.001){return r>.002?2:r>1e-5?4:8}function zh(r,e=.001){let t=X0(e),n=Y0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Lu);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var qs=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??wr(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=I(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=I(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=I(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 mo(r,e=.001,t){return new qs({...zh(r,e),...t??{}})}function Pu(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function Y(r){let e=Pu(r);if(e==null)throw new T(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var $s=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 l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,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 Vh=45,Z0=15,tn=new $s;function zs(r){if(!(r.length>Z0))return tn.new(r).parseWith(()=>tn.readIPv4Addr())}function Vs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vh))return tn.new(r).parseWith(()=>tn.readIPv6Addr())}function Zt(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Vh)return;let t=tn.new(r).parseWith(()=>tn.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function Hh(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function Du(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function Ru(r){switch(r.length){case Er:return r.join(".");case vr:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Wh(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function Gh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Er=4,vr=16,RA=parseInt("0xFFFF",16),jh=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function go(r,e){e.length===vr&&r.length===Er&&Hh(e,0,11)&&(e=e.slice(12)),e.length===Er&&r.length===vr&&Du(r,jh,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function Yh(r,e){if(typeof e=="string"&&(e=Zt(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Ou(r){if(!Hs(r))throw new Error("Must have 0xffff prefix");return r.slice(12)}function Hs(r){return Du(r,jh,0,11)}function ku(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Er,o=zs(e);if(o==null&&(n=vr,o=Vs(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Nu(s,8*n);return{network:go(o,i),mask:i}}function Nu(r,e){if(e!==8*Er&&e!==8*vr)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Qt=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=ku(e));else{let n=Zt(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=Zt(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Nu(o,8*n.length);this.network=go(n,this.mask)}}contains(e){return Yh({network:this.network,mask:this.mask},e)}toString(){let e=Wh(this.mask),t=e!==-1?String(e):Gh(this.mask);return Ru(this.network)+"/"+t}};function Xh(r){try{let e=Y(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Zh(r){if(typeof r!="string"||!/^[0-9a-fA-FxX.:]+$/.test(r))return!1;let e=r.includes(":")?`[${r}]`:r,t;try{t=new URL(`http://${e}`)}catch{return!1}if(t.href!==`http://${t.hostname}/`)return!1;let n=t.hostname;if(n.startsWith("["))return n==="[::1]";let o=n.split(".");return o.length===4&&o[0]==="127"&&o.every(s=>/^\d{1,3}$/.test(s))}function yo(r){try{let e=Y(r);switch(e.type){case"ip4":case"ip6":return Zh(e.host);default:return!1}}catch{return!1}}function Ie(r){return Pu(r)!==null}function ht(r){return!!zs(r)}function Ws(r){return!!Vs(r)}var Q0=["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","::/128","::1/128","64:ff9b::/96","100::/64","2001::/32","2001:20::/28","2001:db8::/32","2002::/16","fc00::/7","fe80::/10","ff00::/8"].map(r=>new Qt(r));function rn(r){if(!ht(r)&&!Ws(r))return;let e=Zt(r);if(e==null)return;let t=e.length===16&&Hs(e)?Ou(e):e;return Q0.some(n=>n.contains(t))}function Pt(r){try{let e=Y(r);switch(e.type){case"ip4":case"ip6":return rn(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}var Le=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Dt=class extends Error{static name="ValidationError";name="ValidationError"},Gs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},js=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Bu(r){return e=>F(e,r)}function Fu(r){return e=>I(e,r)}function nn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Sr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Qh(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=I(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Sr(n);return tt([t,o],t.length+o.length)}function Jh(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=et.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=Sr(n);return tt([t,o],t.length+o.length)}function Uu(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=F(e,"base32"),o=nn(t);return`${n}:${o}`}var Ku=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Le("Invalid byte value in IP address");e[n]=o}),e},ep=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ht(t[n]),i;s&&(i=Ku(t[n]),t[n]=F(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,F(i.subarray(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++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Le("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},tp=function(r){if(r.byteLength!==4)throw new Le("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},rp=function(r){if(r.byteLength!==16)throw new Le("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Le(`Invalid IPv6 address "${t}"`)}};function np(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Le(`Invalid IPv6 address "${r}"`)}}var Mu=Object.values(On).map(r=>r.decoder),J0=(function(){let r=Mu[0].or(Mu[1]);return Mu.slice(2).forEach(e=>r=r.or(e)),r})();function op(r){return J0.decode(r)}function sp(r){return e=>r.encoder.encode(e)}function eb(r){if(parseInt(r).toString()!==r)throw new Dt("Value must be an integer")}function tb(r){if(r<0)throw new Dt("Value must be a positive integer, or zero")}function rb(r){return e=>{if(e>r)throw new Dt(`Value must be smaller than or equal to ${r}`)}}function nb(...r){return e=>{for(let t of r)t(e)}}var bo=nb(eb,tb,rb(65535));var _e=-1,qu=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new js(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Ot=new qu,yb=[{code:4,name:"ip4",size:32,valueToBytes:Ku,bytesToValue:tp,validate:r=>{if(!ht(r))throw new Dt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Sr,bytesToValue:nn,validate:bo},{code:273,name:"udp",size:16,valueToBytes:Sr,bytesToValue:nn,validate:bo},{code:33,name:"dccp",size:16,valueToBytes:Sr,bytesToValue:nn,validate:bo},{code:41,name:"ip6",size:128,valueToBytes:ep,bytesToValue:rp,stringToValue:np,validate:r=>{if(!Ws(r))throw new Dt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:_e},{code:43,name:"ipcidr",size:8,bytesToValue:Bu("base10"),valueToBytes:Fu("base10")},{code:53,name:"dns",size:_e},{code:54,name:"dns4",size:_e},{code:55,name:"dns6",size:_e},{code:56,name:"dnsaddr",size:_e},{code:132,name:"sctp",size:16,valueToBytes:Sr,bytesToValue:nn,validate:bo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:_e,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:_e,bytesToValue:Bu("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Fu("base58btc")(r):xe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Uu,valueToBytes:Qh},{code:445,name:"onion3",size:296,bytesToValue:Uu,valueToBytes:Jh},{code:446,name:"garlic64",size:_e},{code:447,name:"garlic32",size:_e},{code:448,name:"tls"},{code:449,name:"sni",size:_e},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:_e,bytesToValue:sp(sc),valueToBytes:op},{code:480,name:"http"},{code:481,name:"http-path",size:_e,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:_e}];yb.forEach(r=>{Ot.addProtocol(r)});function ip(r){let e=[],t=0;for(;t<r.length;){let n=dr(r,t),o=Ot.getProtocol(n),s=Ae(n),i=bb(o,r,t+s),a=0;i>0&&o.size===_e&&(a=Ae(i));let c=s+a+i,u={code:n,name:o.name,bytes:Te(r.subarray(t,t+c))};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??F(f)}e.push(u),t+=c}return e}function ap(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ot.getProtocol(n.code),s=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??I(n.value),a=i.byteLength,o.size===_e&&(c=Ae(a)));let u=new Uint8Array(s+c+a),l=0;Qr(n.code,u,l),l+=s,i!=null&&(o.size===_e&&(Qr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return tt(t,e)}function cp(r){if(r.charAt(0)!=="/")throw new Le('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Ot.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Le(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Le(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Le("Incomplete multiaddr");return e}function up(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ot.getProtocol(e.code);if(t==null)throw new Le(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function bb(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:dr(e,t)}var wb=Symbol.for("nodejs.util.inspect.custom"),tl=Symbol.for("@multiformats/multiaddr");function xb(r){if(r==null&&(r="/"),er(r))return r.getComponents();if(r instanceof Uint8Array)return ip(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),cp(r);if(Array.isArray(r))return r;throw new Le("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ei=class r{[tl]=!0;#e;#t;#n;constructor(e="/",t={}){this.#e=xb(e),t.validate!==!1&&Eb(this)}get bytes(){return this.#n==null&&(this.#n=ap(this.#e)),this.#n}toString(){return this.#t==null&&(this.#t=up(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Gs(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Q(this.bytes,e.bytes)}[wb](){return`Multiaddr(${this.toString()})`}};function Eb(r){r.getComponents().forEach(e=>{let t=Ot.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function er(r){return!!r?.[tl]}function re(r){return new ei(r)}var ae=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),O=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),lp=r=>({match:e=>r.match(e)===!1?e:!1}),G=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Re=(...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}}),X=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ce(...r){function e(o){if(o==null)return!1;let s=o.getComponents();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{matchers:r,matches:t,exactMatch:n}}var vb=O(421),fp=ce(vb),ri=O(54),ni=O(55),oi=O(56),nl=O(53),mC=ce(ri,G(O(421))),gC=ce(ni,G(O(421))),yC=ce(oi,G(O(421))),bC=ce(Re(nl,oi,ri,ni),G(O(421))),dp=X(O(4),G(O(43))),hp=X(G(O(42)),O(41),G(O(43))),ol=Re(dp,hp),ln=Re(ol,nl,ri,ni,oi),wC=ce(Re(ol,X(Re(nl,oi,ri,ni),G(O(421))))),sl=ce(dp),il=ce(hp),xC=ce(ol),al=X(ln,O(6)),wo=X(ln,O(273)),xo=ce(X(al,G(O(421)))),EC=ce(wo),cl=X(wo,ae(460),G(O(421))),si=X(wo,ae(461),G(O(421))),Sb=Re(cl,si),vC=ce(cl),pp=ce(si),rl=Re(ln,al,wo,cl,si),mp=Re(X(rl,ae(477),G(O(421)))),_r=ce(mp),gp=Re(X(rl,ae(478),G(O(421))),X(rl,ae(448),G(O(449)),ae(477),G(O(421)))),Eo=ce(gp),yp=X(wo,ae(280),G(O(466)),G(O(466)),G(O(421))),ul=ce(yp),bp=X(si,ae(465),G(O(466)),G(O(466)),G(O(421))),ll=ce(bp),ti=Re(mp,gp,X(al,G(O(421))),X(Sb,G(O(421))),X(ln,G(O(421))),yp,bp,O(421)),SC=ce(ti),Ab=X(G(ti),ae(290),lp(ae(281)),G(O(421))),Cr=ce(Ab),_b=Re(X(ti,ae(290),ae(281),G(O(421))),X(ti,ae(281),G(O(421))),X(ae(281),G(O(421)))),fl=ce(_b),Cb=X(ln,Re(X(O(6,"80")),X(O(6),ae(480)),ae(480)),G(O(481)),G(O(421))),AC=ce(Cb),Tb=X(ln,Re(X(O(6,"443")),X(O(6,"443"),ae(480)),X(O(6),ae(443)),X(O(6),ae(448),ae(480)),X(ae(448),ae(480)),ae(448),ae(443)),G(O(481)),G(O(421))),_C=ce(Tb),Ib=Re(X(O(777),G(O(421)))),CC=ce(Ib),Lb=Re(X(O(400),G(O(421)))),TC=ce(Lb);function wp(r,e){let t=xo.exactMatch(r),n=xo.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=Eo.exactMatch(r),s=Eo.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=_r.exactMatch(r),a=_r.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=fl.exactMatch(r),u=fl.exactMatch(e);if(c&&!u)return-1;if(!c&&u)return 1;let l=ul.exactMatch(r),f=ul.exactMatch(e);if(l&&!f)return-1;if(!l&&f)return 1;let d=ll.exactMatch(r),h=ll.exactMatch(e);return d&&!h?-1:!d&&h?1:0}function xp(r,e){let t=yo(r),n=yo(e);return t&&!n?1:!t&&n?-1:0}function Ep(r,e){let t=Pt(r),n=Pt(e);return t&&!n?1:!t&&n?-1:0}function vp(r,e){let t=Cr.exactMatch(r),n=Cr.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function Ce(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ii=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},fn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ii(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 ii(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 dl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function dn(r={}){return Pb(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 Pb(r,e){e=e??{};let t=e.onEnd,n=new fn,o,s,i,a=Ce(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,b)=>{s=S=>{s=null,n.push(S);try{g(r(n))}catch(w){b(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ce()})}},u=g=>s!=null?s(g):(n.push(g),o),l=g=>(n=new fn,s!=null?s({error:g}):(n.push({error:g}),o)),f=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?l(g):u({done:!0})),h=()=>(n=new fn,d(),{done:!0}),y=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async g=>{let b=g?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let S,w;b!=null&&(S=new Promise((v,A)=>{w=()=>{A(new dl)},b.addEventListener("abort",w)}));try{await Promise.race([a.promise,S])}finally{w!=null&&b!=null&&b?.removeEventListener("abort",w)}}},t==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(g){return p.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(g){return p.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return p.readableLength},onEmpty:g=>p.onEmpty(g)},o}var hl=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Db=r=>"reason"in r?r.reason:new DOMException("This operation was aborted.","AbortError"),Rb=2**31-1,Ob=(r,e)=>{if(typeof r!="number"||Math.sign(r)!==1)return new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(typeof e?.setTimeout!="function"||typeof e?.clearTimeout!="function")return new TypeError("Expected `customTimers` to have a `setTimeout` and a `clearTimeout` function")};function pl(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=()=>{try{r.cancel?.()}catch{}},f=new Promise((d,h)=>{let y=()=>{h(Db(i)),u()},p=Ob(t,s);try{p?h(p):i?.aborted?y():i&&(c=y,i.addEventListener("abort",c,{once:!0}))}finally{r.then(d,h)}if(p||i?.aborted||t>Rb)return;let g=n||o===!1||o instanceof Error?void 0:new hl(o??`Promise timed out after ${t} milliseconds`);a=s.setTimeout.call(void 0,()=>{if(n)try{d(n())}catch(b){h(b)}else o===!1?d():h(o instanceof Error?o:g);u()},t)}).finally(()=>{try{f.clear()}catch{}try{c&&i.removeEventListener("abort",c)}catch{}});return f.clear=()=>{a!==void 0&&(s.clearTimeout.call(void 0,a),a=void 0)},f}var Sp=r=>typeof r=="function"?{filter:r}:{...r},kb=r=>r===1/0||Number.isSafeInteger(r)&&r>=0,Nb=[["addEventListener","removeEventListener"],["on","off"],["addListener","removeListener"]],Mb=r=>{for(let[e,t]of Nb){let n=r?.[e],o=r?.[t];if(typeof n=="function"&&typeof o=="function")return{addListener:n.bind(r),removeListener:o.bind(r)}}throw new TypeError("Emitter is not compatible")},Bb=r=>{let e=new Map;for(let[t,n]of r)for(let o of Array.isArray(t)?t:[t])e.has(o)||e.set(o,n);return e},Fb=({addListener:r,removeListener:e,handlers:t,signal:n,abortHandler:o,isDone:s})=>{n?.addEventListener("abort",o,{once:!0});for(let[i,a]of t)if(r(i,a),s()){e(i,a);return}},Ub=({removeListener:r,handlers:e,signal:t,abortHandler:n})=>{for(let[o,s]of e)r(o,s);t?.removeEventListener("abort",n)},Kb=(r,e,t)=>{let n=Promise.resolve();return(o,s)=>{n=n.then(async()=>{if(e())return;let i;try{i=r?await r(o):!0}catch(a){e()||t(a);return}e()||s(i)})}};function qb(r,e,t){let n=()=>{},o=!1,s,i=new Promise((a,c)=>{t=Sp(t);let{filter:u}=t;if(!kb(t.count))throw new TypeError("The `count` option should be at least 0 or more");if(typeof t.timeout=="number"&&!(t.timeout>0))throw new TypeError(`Expected the \`timeout\` option to be a positive number, got \`${t.timeout}\``);t.signal?.throwIfAborted();let{addListener:l,removeListener:f}=Mb(r);if(t.count===0){a([]);return}let d=[],h=v=>{n(),c(v)},y=Kb(u,()=>o,h),p=v=>{d.push(v),t.count===d.length&&(n(),a(d))},g=(...v)=>{if(o)return;let A=t.multiArgs?v:v[0];if(!u){p(A);return}y(A,M=>{M&&p(A)})},b=(...v)=>{h(t.rejectionMultiArgs?v:v[0])},S=()=>{h(t.signal.reason)},w={addListener:l,removeListener:f,handlers:Bb([[e,g],[t.rejectionEvents??["error"],b]]),signal:t.signal,abortHandler:S,isDone:()=>o};n=()=>{o=!0,clearTimeout(s),Ub(w)},Fb(w),!(o||!t.resolveImmediately)&&(Number.isFinite(t.timeout)&&t.timeout<=2**31-1&&(s=setTimeout(n,t.timeout)),a(d))});if(i.cancel=n,typeof t.timeout=="number"&&t.timeout>0&&!t.resolveImmediately){let a=pl(i,{milliseconds:t.timeout});return a.cancel=()=>{n(),a.clear()},a}return i}function pt(r,e,t){let n=qb(r,e,{...Sp(t),count:1,resolveImmediately:!1}),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function vo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var ai=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}},ci=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Tr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function $b(r){return r.reason}function je(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??$b;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var ui=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ce(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Qe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function zb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ap=new WeakMap,li=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=zb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 Qe),this.cleanup())}async join(e){let t=new ui(e);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 je(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof t=="object"&&t!==null){let n=Ap.get(t);if(n==null&&(n=new WeakSet,Ap.set(t,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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.deferred.reject(e.signal?.reason??new Qe),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var hn=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=[],this.emitEmpty=vo(this.emitEmpty.bind(this),1),this.emitIdle=vo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!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 ci;let n=new li(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Qe)}),this.clear()}async onEmpty(e){this.size!==0&&await pt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await pt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await pt(this,"idle",e)}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=dn({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.error)},i=()=>{n()},a=()=>{n(new Qe("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function Et(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.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}var pn=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 Vb=1.2,Hb=2,Wb=5e3,Gb=6e4,jb=5e3,fi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??jb;this.success=new pn(t),this.failure=new pn(t),this.next=new pn(t),this.failureMultiplier=e.failureMultiplier??Hb,this.timeoutMultiplier=e.timeoutMultiplier??Vb,this.minTimeout=e.minTimeout??Wb,this.maxTimeout=e.maxTimeout??Gb,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=Et([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();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 ml=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ce(),this.haveNext=Ce()}[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=Ce(),e}async throw(e){return this.ended=!0,this.error=e,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 this.ended=!0,this.nextResult=e,this.haveNext.resolve(),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 this.error??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=Ce(),await je(this.readNext.promise,t?.signal,t)}};function _p(){return new ml}function Cp(r){return r[Symbol.asyncIterator]!=null}async function Yb(r,e,t){try{await Promise.all(r.map(async n=>{for(;;){let{value:o,done:s}=await n.next();if(s===!0)break;await e.push(o,{signal:t}),t.throwIfAborted()}})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Xb(r){let e=new AbortController,t=_p(),n=r.map(o=>Cp(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());Yb(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let o of n)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*Zb(r){for(let e of r)yield*e}function Qb(...r){let e=[];for(let t of r)Cp(t)||e.push(t);return e.length===r.length?Zb(e):Xb(r)}var mn=Qb;var Jb=4194304,di=class extends Error{static name="UnwrappedError";name="UnwrappedError"},yl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},wl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ew(r){return typeof r?.closeRead=="function"}function tw(r){return typeof r?.close=="function"}function gl(r){return ew(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:tw(r)?r.status!=="open":!1}function rw(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function xl(r,e){let t=e?.maxBufferSize??Jb,n=new ne,o,s=!1,i;if(!rw(r))throw new T("Argument should be a Stream or a Multiaddr");let a=f=>{if(!s&&i==null){if(n.append(f.data),n.byteLength>t){let d=n.byteLength;n.consume(d);let h=new $o(`Read buffer overflow - ${d} > ${t}`);i=h,o?.reject(h),queueMicrotask(()=>{r.abort(h)});return}o?.resolve()}};r.addEventListener("message",a);let c=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",c);let u=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",u);let l={readBuffer:n,async read(f){if(s===!0)throw new di("Stream was unwrapped");if(i!=null)throw i;if(gl(r)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new Tr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let d=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await je(o.promise,f?.signal),gl(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let h=f?.bytes??n.byteLength;if(n.byteLength<h){if(gl(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Tr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(f)}let y=n.sublist(0,h);return n.consume(h),y},async write(f,d){if(s===!0)throw new di("Stream was unwrapped");r.send(f)||await pt(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",a),r.removeEventListener("close",c),r.removeEventListener("remoteCloseWrite",u),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n),n.consume(n.byteLength))),r}};return l}function hi(r,e={}){let t=xl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ae(e.maxDataLength));let n=e?.lengthDecoder??dr,o=e?.lengthEncoder??Yt;return{async read(i){let a=-1,c=new ne;for(;;){let l=await t.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new yl("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new wl(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new bl(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await t.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Tr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new Tr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new ne(o(i.byteLength),i),a)},async writeV(i,a){let c=new ne(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var pi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},gn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},mi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},So=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function gi(r){return r[Symbol.asyncIterator]!=null}function Tp(r,e){if(r.byteLength>e)throw new gn("Message length too long")}var bi=r=>{let e=Ae(r),t=Se(e);return Yt(r,t),bi.bytes=e,t};bi.bytes=0;function wi(r,e){e=e??{};let t=e.lengthEncoder??bi,n=e?.maxDataLength??4194304;function*o(s){Tp(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return gi(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}wi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??bi,n=e?.maxDataLength??4194304;return Tp(r,n),new ne(t(r.byteLength),r)};var Ir;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ir||(Ir={}));var vl=r=>{let e=dr(r);return vl.bytes=Ae(e),e};vl.bytes=0;function El(r,e){let t=new ne,n=Ir.LENGTH,o=-1,s=e?.lengthDecoder??vl,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ir.LENGTH)try{if(o=s(t),o<0)throw new pi("Invalid message length");if(o>a)throw new gn("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Ir.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new mi("Message length length too long");break}throw u}if(n===Ir.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Ir.LENGTH}}}return gi(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new So("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new So("Unexpected end of input")})()}El.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return El(n,{...e??{},onLength:s=>{t=s}})};var xi=class extends hn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ei=class extends hn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var vi=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Sl}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 ai("Rate limit exceeded",i);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)}},Sl=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}};var Al=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 Oe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Al({name:e,metrics:t}):n=new Map,n}var _l=class extends it{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 Cl(r){let{name:e,metrics:t}=r,n;return t!=null?n=new _l({name:e,metrics:t}):n=new it,n}var Ao;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:pe(0),payloadType:pe(0),payload:pe(0),signature:pe(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Ao||(Ao={}));var Si=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var yn=class r{static createFromProtobuf=e=>{let t=Ao.decode(e),n=so(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=Ip(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new Si("Envelope signature is not valid for the given domain");return o};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=Ao.encode({publicKey:rt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Q(this.marshal(),e.marshal())}async validate(e,t){let n=Ip(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Ip=(r,e,t)=>{let n=I(r),o=Yt(n.byteLength),s=Yt(e.length),i=Yt(t.length);return new ne(o,n,s,e,i,t)};var Lp="libp2p-peer-record",Pp=Uint8Array.from([3,1]);var _o;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ke((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let y={multiaddr:pe(0)},p=d==null?f.len:f.pos+d;for(;f.pos<p;){let g=f.uint32();g>>>3===1?y.multiaddr=f.bytes():f.skipType(g&7)}return y},function*(f,d,h,y={}){let p=d==null?f.len:f.pos+d;for(;f.pos<p;){let g=f.uint32();g>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(g&7)}})),a);function c(f){return Fe(f,i.codec())}i.encode=c;function u(f,d){return Be(f,i.codec(),d)}i.decode=u;function l(f,d){return Ue(f,i.codec(),d)}i.stream=l})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ke((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let u of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(u,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={peerId:pe(0),seq:0n,addresses:[]},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.peerId=i.bytes();break}case 2:{u.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&u.addresses.length===c.limits.addresses)throw new st('Decode error - repeated field "addresses" had too many elements');u.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(f&7);break}}}return u},function*(i,a,c,u={}){let l={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(u.limits?.addresses!=null&&l.addresses===u.limits.addresses)throw new st('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:u.limits?.addresses$}))yield{...h,index:l.addresses};l.addresses++;break}default:{i.skipType(d&7);break}}}})),t);function n(i){return Fe(i,r.codec())}r.encode=n;function o(i,a){return Be(i,r.codec(),a)}r.decode=o;function s(i,a){return Ue(i,r.codec(),a)}r.stream=s})(_o||(_o={}));function Dp(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 Lr=class r{static createFromProtobuf=e=>{let t=_o.decode(e),n=en(At(t.peerId)),o=(t.addresses??[]).map(i=>re(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Lp;static CODEC=Pp;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=_o.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||!Dp(this.multiaddrs,e.multiaddrs))}};function ow(r){return r[Symbol.asyncIterator]!=null}function sw(r){if(ow(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Co=sw;var Ye=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Ai(r,e,t,n){let o=new Ye(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){Il(t,"abort",f),Il(r,e,u),Il(r,s,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Tl(t,"abort",f),Tl(r,e,u),Tl(r,s,l)})}function Tl(r,e,t){r!=null&&(Rp(r)?r.addEventListener(e,t):r.addListener(e,t))}function Il(r,e,t){r!=null&&(Rp(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Rp(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var _i=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Ci=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ye)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function iw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ti=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=iw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ye),this.cleanup())}async join(e={}){let t=new Ci(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 je(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)})}};function Ll(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var To=class extends Ne{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Ll(this.emitEmpty.bind(this),1),this.emitIdle=Ll(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let 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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new _i;let n=new Ti(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(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("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ye)}),this.clear()}async onEmpty(e){this.size!==0&&await Ai(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ai(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ai(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=dn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ye("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ii="lock:worker:request-read",Li="lock:worker:abort-read-request",Pi="lock:worker:release-read",Di="lock:master:grant-read",Ri="lock:master:error-read",Oi="lock:worker:request-write",ki="lock:worker:abort-write-request",Ni="lock:worker:release-write",Mi="lock:master:grant-write",Bi="lock:master:error-write",Fi="lock:worker:finalize",Ui="mortice",Op={singleProcess:!1};var Pl=(r,e,t,n,o,s,i,a,c)=>u=>{if(u.data==null)return;let l={type:u.data.type,name:u.data.name,identifier:u.data.identifier};l.type===o&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let y={type:h.data.type,name:h.data.name,identifier:h.data.identifier};y.type===a&&y.identifier===l.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===s&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===Fi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var kp=(r=10)=>Math.random().toString().substring(2,r+2);var Ki=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Ui)}readLock(e){return this.sendRequest(Ii,Li,Di,Ri,Pi,e)}writeLock(e){return this.sendRequest(Oi,ki,Mi,Bi,Ni,e)}finalize(){this.channel.postMessage({type:Fi,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=kp();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",l,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),u(h)}};this.channel.addEventListener("message",f)})}};var Np=r=>{if(r=Object.assign({},Op,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Ui),n=new Ne;return t.addEventListener("message",Pl(n,t,"requestReadLock","abortReadLockRequest",Ii,Li,Ri,Pi,Di)),t.addEventListener("message",Pl(n,t,"requestWriteLock","abortWriteLockRequest",Oi,ki,Bi,Ni,Mi)),n}return new Ki(r.name)};var Pr=new Map,Io;function Mp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function aw(r){if(Io==null&&(Io=Np(r),!Mp(Io))){let e=Io;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Pr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Pr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Pr.get(n);o?.finalize()})}return Io}async function Dl(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ye)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var Bp=(r,e)=>{let t=Pr.get(r);if(t!=null)return t;let n=aw(e);if(Mp(n))return t=n,Pr.set(r,t),t;let o=new To({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Dl(s,i);s=new To({concurrency:e.concurrency,autoStart:!1});let a=s,c=Dl(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Dl(o,i)},finalize:()=>{Pr.delete(r)},queue:o},Pr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var cw={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Rl(r){let e=Object.assign({},cw,r);return Bp(e.name,e)}var kt;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ke((d,h,y={})=>{y.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),y.lengthDelimited!==!1&&h.ldelim()},(d,h,y={})=>{let p={key:"",value:pe(0)},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let b=d.uint32();switch(b>>>3){case 1:{p.key=d.string();break}case 2:{p.value=d.bytes();break}default:{d.skipType(b&7);break}}}return p},function*(d,h,y,p={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let b=d.uint32();switch(b>>>3){case 1:{yield{field:`${y}.key`,value:d.string()};break}case 2:{yield{field:`${y}.value`,value:d.bytes()};break}default:{d.skipType(b&7);break}}}})),c);function u(d){return Fe(d,a.codec())}a.encode=u;function l(d,h){return Be(d,a.codec(),h)}a.decode=l;function f(d,h){return Ue(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=Ke((d,h,y={})=>{y.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Po.codec().encode(d.value,h)),y.lengthDelimited!==!1&&h.ldelim()},(d,h,y={})=>{let p={key:""},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let b=d.uint32();switch(b>>>3){case 1:{p.key=d.string();break}case 2:{p.value=Po.codec().decode(d,d.uint32(),{limits:y.limits?.value});break}default:{d.skipType(b&7);break}}}return p},function*(d,h,y,p={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let b=d.uint32();switch(b>>>3){case 1:{yield{field:`${y}.key`,value:d.string()};break}case 2:{yield*Po.codec().stream(d,d.uint32(),`${y}.value`,{limits:p.limits?.value});break}default:{d.skipType(b&7);break}}}})),c);function u(d){return Fe(d,a.codec())}a.encode=u;function l(d,h){return Be(d,a.codec(),h)}a.decode=l;function f(d,h){return Ue(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ke((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let l of a.addresses)c.uint32(10),Lo.codec().encode(l,c);if(a.protocols!=null&&a.protocols.length>0)for(let l of a.protocols)c.uint32(18),c.string(l);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[l,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:l,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[l,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:l,value:f},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={addresses:[],protocols:[],metadata:new Map,tags:new Map},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(u.limits?.addresses!=null&&l.addresses.length===u.limits.addresses)throw new st('Decode error - repeated field "addresses" had too many elements');l.addresses.push(Lo.codec().decode(a,a.uint32(),{limits:u.limits?.addresses$}));break}case 2:{if(u.limits?.protocols!=null&&l.protocols.length===u.limits.protocols)throw new st('Decode error - repeated field "protocols" had too many elements');l.protocols.push(a.string());break}case 4:{l.publicKey=a.bytes();break}case 5:{l.peerRecordEnvelope=a.bytes();break}case 6:{if(u.limits?.metadata!=null&&l.metadata.size===u.limits.metadata)throw new to('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.metadata$value}});l.metadata.set(h.key,h.value);break}case 7:{if(u.limits?.tags!=null&&l.tags.size===u.limits.tags)throw new to('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.tags$value}});l.tags.set(h.key,h.value);break}case 8:{l.updated=a.uint64Number();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,u,l={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(l.limits?.addresses!=null&&f.addresses===l.limits.addresses)throw new st('Streaming decode error - repeated field "addresses" had too many elements');for(let y of Lo.codec().stream(a,a.uint32(),`${u}.addresses[]`,{limits:l.limits?.addresses$}))yield{...y,index:f.addresses};f.addresses++;break}case 2:{if(l.limits?.protocols!=null&&f.protocols===l.limits.protocols)throw new st('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${u}.protocols[]`,index:f.protocols,value:a.string()},f.protocols++;break}case 4:{yield{field:`${u}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${u}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(l.limits?.metadata!=null&&f.metadata===l.limits.metadata)throw new st('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${u}.metadata{}`,{limits:{value:l.limits?.metadata$value}}),f.metadata++;break}case 7:{if(l.limits?.tags!=null&&f.tags===l.limits.tags)throw new st('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${u}.tags{}`,{limits:{value:l.limits?.tags$value}}),f.tags++;break}case 8:{yield{field:`${u}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Fe(a,r.codec())}r.encode=o;function s(a,c){return Be(a,r.codec(),c)}r.decode=s;function i(a,c){return Ue(a,r.codec(),c)}r.stream=i})(kt||(kt={}));var Lo;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:pe(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Lo||(Lo={}));var Po;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Be(s,r.codec(),i)}r.decode=n;function o(s,i){return Ue(s,r.codec(),i)}r.stream=o})(Po||(Po={}));function uw(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=so(e.publicKey,t);return fo(n)}function Fp(r,e,t){let n=kt.decode(e);return bn(r,n,t)}function bn(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:uw(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:re(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Up(r,e){return lw(r.addresses,e.addresses)&&fw(r.protocols,e.protocols)&&dw(r.publicKey,e.publicKey)&&hw(r.peerRecordEnvelope,e.peerRecordEnvelope)&&pw(r.metadata,e.metadata)&&mw(r.tags,e.tags)}function lw(r,e){return qp(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Q(t.multiaddr,n.multiaddr)))}function fw(r,e){return qp(r,e,(t,n)=>t===n)}function dw(r,e){return Kp(r,e)}function hw(r,e){return Kp(r,e)}function pw(r,e){return $p(r,e,(t,n)=>Q(t,n))}function mw(r,e){return $p(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Kp(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Q(r,e):!1}function qp(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function $p(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Nt="/",zp=new TextEncoder().encode(Nt),qi=zp[0],Dr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=I(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]!==qi)throw new Error("Invalid key")}toString(e="utf8"){return F(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Nt))}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=zp),this._buf[0]!==qi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(qi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===qi;)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(Nt).slice(1)}type(){return gw(this.baseNamespace())}name(){return yw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Nt)||(e+=Nt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Nt):new r(e.slice(0,-1).join(Nt))}child(e){return this.toString()===Nt?e:e.toString()===Nt?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(),...bw(e.map(t=>t.namespaces()))])}};function gw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function yw(r){let e=r.split(":");return e[e.length-1]}function bw(r){return[].concat(...r)}var Ol="/peers/";function Do(r){if(!Ft(r)||r.type==null)throw new T("Invalid PeerId");let e=r.toCID().toString();return new Dr(`${Ol}${e}`)}async function Vp(r,e,t,n,o){let s=o?.maxAddresses??1/0,i=new Map;for(let c of t){if(c==null)continue;if(c.multiaddr instanceof Uint8Array&&(c.multiaddr=re(c.multiaddr)),!er(c.multiaddr))throw new T("Multiaddr was invalid");if(!await e(r,c.multiaddr,o))continue;let u=c.isCertified??!1,l=c.multiaddr.toString(),f=i.get(l);f!=null?c.isCertified=f.isCertified||u:i.set(l,{multiaddr:c.multiaddr,isCertified:u})}let a=[...i.entries()];return a.length>s&&(o?.log?.("%p has %d addresses, only storing %d",r,a.length,s),a=[...a.filter(([,c])=>c.isCertified),...a.filter(([,c])=>!c.isCertified)].slice(0,s)),a.sort(([c],[u])=>c.localeCompare(u)).map(([,{isCertified:c,multiaddr:u}])=>{let l=u.getComponents().find(f=>f.code===421)?.value;return r.equals(l)&&(u=u.decapsulate(re(`/p2p/${r}`))),{isCertified:c,multiaddr:u.bytes}})}async function zi(r,e,t,n){if(e==null)throw new T("Invalid PeerData");if(e.publicKey!=null&&!r.equals(e.publicKey.toMultihash().bytes))throw new T("publicKey does not match peer id");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new T("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(y=>({isCertified:!1,multiaddr:y}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let y=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=$i(y,{validate:Hp})}if(e.tags!=null){let y=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=$i(y,{validate:Wp,map:Gp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(y=>({isCertified:!1,multiaddr:y}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let y=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[p,g]of y)g==null?a.delete(p):a.set(p,g);a=$i([...a.entries()],{validate:Hp})}if(e.tags!=null){let y=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),p=new Map(c);for(let[g,b]of y)b==null?p.delete(g):p.set(g,b);c=$i([...p.entries()],{validate:Wp,map:Gp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=rt(o.id.publicKey):e.publicKey!=null?l=rt(e.publicKey):r.publicKey!=null&&(l=rt(r.publicKey));let f={addresses:await Vp(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((y,p)=>y.localeCompare(p)),metadata:a,tags:c,publicKey:l,peerRecordEnvelope:u},d=new Map;for(let y of n.existingPeer?.peerPB.addresses??[]){let p=F(y.multiaddr,"base64");y.observed!=null&&!d.has(p)&&d.set(p,y.observed)}let h=Date.now();return f.addresses.forEach(y=>{y.observed=d.get(F(y.multiaddr,"base64"))??h}),r.type!=="RSA"&&delete f.publicKey,f}function $i(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 Hp(r,e){if(typeof r!="string")throw new T("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new T("Metadata value must be a Uint8Array")}function Wp(r,e){if(typeof r!="string")throw new T("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new T("Tag value must be an integer");if(e.value<0||e.value>100)throw new T("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new T("Tag ttl must be an integer");if(e.ttl<0)throw new T("Tag ttl must be between greater than 0")}}function Gp(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function jp(r){let e=r.toString().split("/")[2],t=xe.parse(e,et);return _u(t)}function kl(r,e,t){let n=jp(r);return Fp(n,e,t)}function ww(r,e){return{prefix:Ol,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(kl(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(kl(n.key,n.value,e),kl(o.key,o.value,e)))}}var Vi=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;maxAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Cl({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5,this.maxAddresses=t.maxAddresses??100}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:Rl({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Do(e),t)}async load(e,t){let n=Do(e),o=await this.datastore.get(n,t),s=kt.decode(o);if(this.#a(e,s))throw await this.datastore.delete(n,t),new nr;return bn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await zi(e,t,"patch",{...n,addressFilter:this.addressFilter,maxAddresses:this.#n(e),log:this.log});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await zi(e,t,"patch",{...n,addressFilter:this.addressFilter,maxAddresses:this.#n(e),log:this.log,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await zi(e,t,"merge",{addressFilter:this.addressFilter,maxAddresses:this.#n(e),log:this.log,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(ww(e??{},this.maxAddressAge),e)){let o=jp(t);if(o.equals(this.peerId))continue;let s=kt.decode(n);if(this.#a(o,s)){await this.datastore.delete(t,e);continue}yield bn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Do(e),o=await this.datastore.get(n,t),s=kt.decode(o);if(this.#a(e,s))throw await this.datastore.delete(n,t),new nr;return{peerPB:s,peer:bn(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=kt.encode(t);return await this.datastore.put(Do(e),s,o),{peer:bn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Up(t,n.peerPB)}}#n(e){return this.peerId.equals(e)?1/0:this.maxAddresses}#a(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Nl=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 Vi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Co(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Ft(t)?t:Ft(t?.expectedPeer)?t.expectedPeer:void 0,s=Ft(t)||t===void 0?n:t,i=await yn.openAndCertify(e,Lr.DOMAIN,s),a=fo(i.publicKey);if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=Lr.createFromProtobuf(i.payload);if(!c.peerId.equals(a))return this.log("signing key did not match peer id in the peer record - signer: %p record: %p",a,c.peerId),!1;let u;try{u=await this.get(a,s)}catch(l){if(l.name!=="NotFoundError")throw l}if(u?.peerRecordEnvelope!=null){let l=yn.createFromProtobuf(u.peerRecordEnvelope),f=Lr.createFromProtobuf(l.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))},s),!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 Yp(r,e={}){return new Nl(r,e)}var Hi=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function xw(r){return r[Symbol.asyncIterator]!=null}function Ew(r){if(xw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ml=Ew;function vw(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 Xp=vw;function Sw(r){return r[Symbol.asyncIterator]!=null}function Aw(r,e){let t=0;if(Sw(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Xp(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(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 Rr=Aw;function _w(r){return r[Symbol.asyncIterator]!=null}function Cw(r,e){return _w(r)?(async function*(){yield*(await Co(r)).sort(e)})():(function*(){yield*Co(r).sort(e)})()}var Bl=Cw;function Tw(r){return r[Symbol.asyncIterator]!=null}function Iw(r,e){return Tw(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 Fl=Iw;var Wi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value: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 Ml(this.putMany(e,n)),e=[],await Ml(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=Rr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Rr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Bl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Rr(n,()=>o++>=s)}return e.limit!=null&&(n=Fl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Rr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Rr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Bl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Rr(n,()=>s++>=o)}return e.limit!=null&&(n=Fl(n,e.limit)),n}};var Gi=class extends Wi{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Hi;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new Dr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Dr(n),t?.signal?.throwIfAborted()}};var Zp=864e13;var ji=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Oe({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=Y(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=rn(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?Zp-Date.now():0,lastVerified:o?Zp-Date.now():void 0})})}remove(e){let t=Y(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!Ie(o))continue;let s=Y(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),re(n)}confirm(e,t){let n=Y(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=Y(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Yi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Oe({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=Y(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:ht(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=Y(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!Ie(n))continue;let o=Y(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(u=>u.code===4||u.code===41),c=i.findIndex(u=>u.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,re(i)):e}confirm(e,t){if(!Ie(e))return!1;let n=Y(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!Ie(e))return!1;let n=Y(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var Lw={maxObservedAddresses:10},Xi=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Oe({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Lw.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Pt(e)||Xh(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:re(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var Pw={maxObservedAddresses:10},Zi=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Oe({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Pw.maxObservedAddresses}get(e,t){if(Pt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!Ie(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!Ie(e))return e.toString();let t=Y(e);return`${t.host}-${t.port}-${t.protocol}`}};var Qp=6e4,Jp={maxObservedAddresses:10,addressVerificationTTL:Qp*10,addressVerificationRetry:Qp*5},Dw=r=>r;function Ul(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&xt(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var Qi=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Xi(e,t),this.dnsMappings=new ji(e,t),this.ipMappings=new Yi(e,t),this.transportAddresses=new Zi(e,t),this.announceFilter=t.announceFilter??Dw,this.observedAddressFilter=mo(1024),this.addressVerificationTTL=t.addressVerificationTTL??Jp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Jp.addressVerificationRetry,this._updatePeerStoreAddresses=vo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===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 - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>re(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=Y(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Ul(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Ul(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Ul(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=re(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(re(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${ht(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(re(`/ip${ht(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Ie(e))return!1;let t=Y(e);if(t.type!=="ip4"||rn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>_r.exactMatch(s)||Eo.exactMatch(s),s=>xo.exactMatch(s),s=>pp.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(u=>u.getAddrs().filter(l=>Y(l).type==="ip4"&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>!yo(u)).pop();if(a==null)continue;let c=Y(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var em;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(em||(em={}));var Ji=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},ea=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},wn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ro=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},ta=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},ra=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},na=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Oo=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},oa=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},sa=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},ia=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},aa=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},ca=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},tr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Or=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ua=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},la=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Kl=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=Us())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Qo(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")}},Rw=["metrics","connectionProtector","dns"],Ow=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function tm(r={}){let e=new Kl(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Ow.includes(o)){let i=e.components[o];if(i==null&&!Rw.includes(o))throw new Ji(`${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 rm(r){let e={};for(let t of Object.values(r.components))for(let n of kw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Nw(t))if(e[n]!==!0)throw new ea(`Service "${Mw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function kw(r){return Array.isArray(r?.[In])?r[In]:[]}function Nw(r){return Array.isArray(r?.[$a])?r[$a]:[]}function Mw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function nm(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>_r.matches(e)?!0:Pt(e)),r}var se=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function fa(r){if(Ft(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:xt(n),e.forEach(o=>{if(!er(o))throw new Mt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new T("Multiaddrs must all have the same peer id or have no peer id")}else{let i=xt(s);if(t?.equals(i)!==!0)throw new T("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!fp.exactMatch(n)),{peerId:t,multiaddrs:e}}var Bw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function om(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Bw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function ko(r){let e=Y(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new T(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new T(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Qt(e.host,t)}function ql(r){return!Cr.exactMatch(r)}function da(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>ql(s)))return n}var ha=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>ko(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new it;for(let c of e){let u=c.remotePeer;if(!o.has(u)){o.set(u,0);try{let l=await this.peerStore.get(u);o.set(u,[...l.tags.values()].reduce((f,d)=>f+d.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",l)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(l=>{if(Ie(c.remoteAddr)){let f=Y(c.remoteAddr);return l.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await om(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}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})}};var sm="last-dial-failure",im="last-dial-success";var am=100,pa=50;function Fw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function cm(r){return r.sort((e,t)=>xp(e.multiaddr,t.multiaddr)||Ep(e.multiaddr,t.multiaddr)||vp(e.multiaddr,t.multiaddr)||Fw(e,t)||wp(e.multiaddr,t.multiaddr))}var ma=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"},ga=class extends AggregateError{static name="EmptyDNSAnswerError";name="EmptyDNSAnswerError"};var zl=gf(lm(),1);var Vl=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},fm=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Hl(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(fm(i)),r.then(f,d);return}if(i&&(c=()=>{d(fm(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new Vl;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(y){d(y)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}function Wl(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 qw=100,xn=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:s}=this,i={priority:n,id:o,run:e};if(s===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#n();let a=Wl(this.#e,i,(c,u)=>u.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((s,i)=>i>=this.#t&&s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>qw&&this.#t>this.#e.length/2&&this.#n(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#n(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var Mo=class extends zl.default{#e;#t;#n=0;#a;#m=!1;#w=!1;#l;#x=0;#u;#f;#c;#i=[];#s=0;#r;#C;#o=0;#g;#d;#R=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:xn,strict:!1,...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})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#l=e.interval,this.#c=e.strict,this.#r=new e.queueClass,this.#C=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#d=e.autoStart===!1,this.#K()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#l)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#O(e){this.#c?this.#i.push(e):this.#n++}#k(){this.#c?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#S(){return this.#i.length-this.#s}get#N(){return this.#t?!0:this.#c?this.#S()<this.#a:this.#n<this.#a}get#M(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#F(){this.#f=void 0,this.#P(),this.#L()}#U(e){if(this.#c){if(this.#v(e),this.#S()>=this.#a){let n=this.#i[this.#s],o=this.#l-(e-n);return this.#T(o),!0}return!1}if(this.#u===void 0){let t=this.#x-e;if(t<0)this.#n=this.#e?this.#o:0;else return this.#T(t),!0}return!1}#T(e){this.#f===void 0&&(this.#f=setTimeout(()=>{this.#F()},e))}#A(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#I(){this.#f&&(clearTimeout(this.#f),this.#f=void 0)}#b(){if(this.#r.size===0){if(this.#A(),this.emit("empty"),this.#o===0){if(this.#I(),this.#c&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#d){let t=Date.now(),n=!this.#U(t);if(this.#N&&this.#M){let o=this.#r.dequeue();this.#t||(this.#O(t),this.#p()),n&&this.#L(),o(),this.emit("active"),e=!0}}return e}#L(){this.#t||this.#u!==void 0||this.#c||(this.#u=setInterval(()=>{this.#P()},this.#l),this.#x=Date.now()+this.#l)}#P(){this.#c||(this.#u!==void 0&&(this.#n===0&&this.#o===0?this.#A():this.#x=Date.now()+this.#l),this.#n=this.#e?this.#o:0),this.#_(),this.#p()}#_(){for(;this.#b(););}get concurrency(){return this.#g}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.#g=e,this.#_()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#r.setPriority(e,t)}async add(e,t={}){if(t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);return new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let u;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#q(),this.#y.delete(s),d}let l=e({signal:t.signal});if(t.timeout!==void 0&&(l=Hl(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#r.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((h,y)=>{u=()=>{y(d.reason)},d.addEventListener("abort",u,{once:!0}),d.aborted&&u()})])}let f=await l;n(f),this.emit("completed",f)}catch(l){o(l),this.emit("error",l)}finally{u&&t.signal?.removeEventListener("abort",u),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof xn){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:u}=t,l=()=>{i(),c(),o(u.reason),this.#b(),this.emit("next")};if(i=()=>{u.removeEventListener("abort",l),this.#E.delete(i)},u.aborted){l();return}u.addEventListener("abort",l,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#d?(this.#d=!1,this.#_(),this):this}pause(){this.#d=!0}clear(){for(let e of this.#E)e();this.#r=new this.#C,this.#A(),this.#D(),this.emit("empty"),this.#o===0&&(this.#I(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#h(["next","active"],()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#h("idle")}async onPendingZero(){this.#o!==0&&await this.#h("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#h("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#h("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#h(e,t){let n=Array.isArray(e)?e:[e];return new Promise(o=>{let s=()=>{if(!(t&&!t())){for(let i of n)this.off(i,s);o()}};for(let i of n)this.on(i,s)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#d}#K(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#D()}))}#q(){this.#t||(this.#k(),this.#p())}#D(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#c){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#n;let n=t>=this.#a;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function ba(r){let e=[Xe.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Gl=60;function wa(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:Xe[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Xe[e.type],TTL:e.TTL??e.ttl??Gl,data:e.data instanceof Uint8Array?F(e.data):e.data}))}}var $w=4;function jl(r,e={}){let t=new Mo({concurrency:e.queryConcurrency??$w});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),ba(o.types).forEach(c=>{i.append("type",Xe[c])}),o.onProgress?.(new se("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let u=wa(await c.json());return o.onProgress?.(new se("dns:response",u)),u},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function dm(){return[jl("https://cloudflare-dns.com/dns-query"),jl("https://dns.google/resolve")]}var mm=gf(pm(),1);var Yl=class{lru;constructor(e){this.lru=(0,mm.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 wa({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:Xe[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??Gl)*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 gm(r){return new Yl(r)}var zw=1e3,Vw=()=>Math.random()>.5?-1:1,xa=class{resolvers;cache;logger;sorter;constructor(e){this.resolvers={},this.cache=gm(e.cacheSize??zw),this.logger=e.logger,this.sorter=e.sorter??Vw,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["."]=dm())}async query(e,t={}){let n=ba(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new se("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(this.sorter),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,logger:this.logger,types:n});if(u.Answer.length===0)throw new ga("Query result had no answers");for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new se("dns:error",u))}}throw new ma(a,`DNS lookup of ${e} ${n} failed`)}};var Xe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Xe||(Xe={}));function ym(r={}){return new xa(r)}var Xl=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let o=this.getDNS(t),s;try{s=await o.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[Xe.TXT]})}catch(c){if(c.name==="DNSQueryFailedError"&&Array.isArray(c.errors)&&c.errors.length>0&&c.errors.every(l=>l.name==="EmptyDNSAnswerError"))return[];throw c}let i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let u=c.data.replace(/["']/g,"").trim().split("=")[1];u!=null&&(i!=null&&!u.includes(i)||a.push(re(u)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=ym()),this.dns)}},kr=new Xl;async function Zl(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new la("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Zl(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var En={maxParallelDials:pa,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:kr}},Ea=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??En.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??En.maxDialQueueLength,this.dialTimeout=t.dialTimeout??En.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??En.addressDialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??En.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Ei({concurrency:t.maxParallelDials??En.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Qe.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=fa(e);if(n!=null&&t.force!==!0){let i=da(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new se("dial-queue:already-connected",i)),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new se("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Mr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new se("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new se("dial-queue:start-dial"));let a=Et([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??rf,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}l.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(h=>h.multiaddr.toString())),e?.onProgress?.(new se("dial-queue:calculated-addresses",l));for(let h of l){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Mr("Peer had more than maxPeerAddrsToDial");a++;let y=Et([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:y});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[im]:I(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}return p}catch(p){if(this.log.error("dial failed to %a - %e",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[sm]:I(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}if(t.aborted)throw new Go(p.message);u.push(p)}finally{y.clear()}}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:re(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Mr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Oo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await Zl(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new ia(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=this.addressSorter==null?cm(u):u.sort(this.addressSorter);if(l.length===0)throw new Oo(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}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=>!Cr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var Hw=Object.prototype.toString,Ww=r=>Hw.call(r)==="[object Error]",Gw=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function nf(r){if(!(r&&Ww(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:Gw.has(t)}function jw(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");if(Number.isFinite(r)&&!Number.isInteger(r))throw new TypeError("Expected `retries` to be a non-negative integer or Infinity.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function va(r,e,{allowInfinity:t=!1}={}){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${t?" or Infinity":""}.`);if(!t&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<0)throw new TypeError(`Expected \`${r}\` to be \u2265 0.`)}function Bo(r,e,t){if(e!=null&&typeof e!==t)throw new TypeError(`Expected \`${r}\` to be a ${t}.`)}function Yw(r){if(r!=null&&(typeof r.throwIfAborted!="function"||typeof r.addEventListener!="function"||typeof r.removeEventListener!="function"))throw new TypeError("Expected `signal` to be an AbortSignal.")}var Sa=class r extends Error{constructor(e){super(typeof e=="string"?e:void 0),this.name="AbortError",e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),{message:e}=this.originalError,Error.captureStackTrace?.(this.originalError,r)),this.message=e}},Xw=2**31-1;function Zw(r,e){if(e.minTimeout===0)return 0;let t=r+1,n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return Math.min(o,Math.ceil(e.maxTimeout),Xw)}function of(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function Qw(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}function Jw(r){try{return String(r)}catch{return Object.prototype.toString.call(r)}}function ex(r){let e=r;for(;e instanceof Sa&&e.originalError instanceof Error;)e=e.originalError;return e}async function tx({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=()=>{o.signal?.throwIfAborted()},i=r instanceof Error?r:new TypeError(`Non-error was thrown: "${Jw(r)}". You should only throw errors.`);if(s(),i instanceof Sa)throw ex(i);let a=o.retries-t,c=!(i instanceof TypeError)||nf(i),u=of(n,o.maxRetryTime),l=c&&u>0&&a>0?Zw(t,o):0,f=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:t,retryDelay:l}),d=await o.shouldConsumeRetry(f)??!0;s();let h=d?l:0,y=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:t,retryDelay:h});await o.onFailedAttempt(y),s();let p=of(n,o.maxRetryTime);if(!c||p<=0||a<=0)throw i;let g=await o.shouldRetry(y);if(s(),!g)throw i;let b=of(n,o.maxRetryTime);if(b<=0)throw i;return d?(await Qw(Math.min(h,b),o),!0):!1}async function sf(r,e={}){if(e={...e},e.retries??=10,jw(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=1/0,e.maxRetryTime??=1/0,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Bo("onFailedAttempt",e.onFailedAttempt,"function"),Bo("shouldRetry",e.shouldRetry,"function"),Bo("shouldConsumeRetry",e.shouldConsumeRetry,"function"),Bo("randomize",e.randomize,"boolean"),Bo("unref",e.unref,"boolean"),Yw(e.signal),va("factor",e.factor),va("minTimeout",e.minTimeout),va("maxTimeout",e.maxTimeout,{allowInfinity:!0}),va("maxRetryTime",e.maxRetryTime,{allowInfinity:!0}),e.factor===0&&(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await tx({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Aa=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new xi({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);bm(t)&&(this.queue.has(e)||this.queue.add(async n=>{await sf(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",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(Ka)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>bm(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function bm(r){for(let e of r.tags.keys())if(e.startsWith(Ka))return!0;return!1}var rf=50,af={maxConnections:am,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},_a=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??af.maxConnections,this.maxConnections<1)throw new T("Connection Manager maxConnections must be greater than 0");this.connections=new it,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=>ko(re(n))),this.deny=(t.deny??[]).map(n=>ko(re(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??af.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new vi({points:t.inboundConnectionThreshold??af.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ha({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>re(n))}),this.dialQueue=new Ea(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??pa,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:kr},connections:this.connections}),this.reconnectQueue=new Aa({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 bf(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await wf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([pt(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new T("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",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.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}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 St("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new se("connection:open",e));let{peerId:n,multiaddrs:o}=fa(e);if(this.peerId.equals(n))throw new Nr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=da(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new se("dial-queue:already-connected")),t.onProgress?.(new se("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??rf});if(s.status!=="open")throw new rr("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Mt("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new se("connection:opened",s)),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([pt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Ie(e.remoteAddr)){let s=Y(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(Ie(e.remoteAddr)){let s=Y(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(Ie(e.remoteAddr)){let o=Y(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!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=>re(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var ox=1e4,sx="1.0.0",ix="ping",ax="ipfs",wm=32,cx=!0,Ca=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??ax}/${ix}/${sx}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??ox,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??cx,this.timeout=new fi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[In]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o;try{o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let s=xl(o);t=Date.now(),await Promise.all([s.write(crypto.getRandomValues(new Uint8Array(wm)),{signal:n}),s.read({bytes:wm,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(s){if(o?.abort(s),s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",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)}};var Ta=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:F(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:F(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new wn("No content routers available");let n=this,o=new br;for await(let s of mn(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new wn("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new wn("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new St;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new St;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Ia=globalThis.CustomEvent??Event;async function*cf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=Ce(),a=Ce(),c=!1,u,l=!1,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=Ce(),await i.promise),l||f)break;let g={done:!1};s.push(g),p().then(b=>{g.done=!0,g.ok=!0,g.value=b,o.dispatchEvent(new Ia("task-complete"))},b=>{g.done=!0,g.err=b,o.dispatchEvent(new Ia("task-complete"))})}c=!0,o.dispatchEvent(new Ia("task-complete"))}catch(p){u=p,o.dispatchEvent(new Ia("task-complete"))}});function d(){return n?s[0]?.done:!!s.find(p=>p.done)}function*h(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw l=!0,i.resolve(),p.err;i.resolve()}}function*y(){for(;d();)for(let p=0;p<s.length;p++)if(s[p].done){let g=s[p];if(s.splice(p,1),p--,g.ok)yield g.value;else throw l=!0,i.resolve(),g.err;i.resolve()}}try{for(;;){if(d()||(a=Ce(),await a.promise),u!=null||(n?yield*h():yield*y(),u!=null))throw u;if(c&&s.length===0)break}}finally{f=!0,i.resolve()}}var La=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:F(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Ro("No peer routers available");if(e.toString()===this.peerId.toString())throw new ta("Should not try to find self");let n=this,o=mn(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new nr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ro("No peer routers available");let n=this,o=mo(1024);for await(let s of cf((async function*(){let i=mn(...n.routers.filter(a=>a.getClosestPeers instanceof Function).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 - %e",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Pa=class extends Ne{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Et([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Ce(),yield(await pt(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Et([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0&&!e.aborted;)try{let o=crypto.getRandomValues(new Uint8Array(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 je(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("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var uf=32,lf=64,Da=class{log;topologies;handlers;components;middleware;globalMiddleware=[];constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Oe({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[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 ra(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new na(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:uf,maxOutboundStreams:lf,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new T("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))}use(e,t){if(typeof e=="function"){this.globalMiddleware.push(e);return}if(t==null)throw new T("Protocol middleware is required");this.middleware.set(e,t)}unuse(e){typeof e=="function"?this.globalMiddleware=this.globalMiddleware.filter(t=>t!==e):this.middleware.delete(e)}getMiddleware(e){return[...this.globalMiddleware,...this.middleware.get(e)??[]]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var Ra=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=Oe({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Oe({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Tn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new T("Transport must have a valid tag");if(this.transports.has(t))throw new T(`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 ua(`No transport available for address ${String(e)}`);return t?.onProgress?.(new se("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 St("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new oa)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let u=i.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(s)??[];l==null&&(l=[],this.listeners.set(s,l)),l.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let f=l.findIndex(d=>d===u);l.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),sl.matches(c)?t.ipv4.attempts++:il.matches(c)&&t.ipv6.attempts++,n.push(u.listen(c).then(()=>{t.errors.delete(c.toString()),sl.matches(c)&&t.ipv4.success++,il.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Tn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new sa(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
13
13
  ${[...t.errors.entries()].map(([s,i])=>`
14
14
  ${s}: ${`${ux(i)}`.split(`
15
15
  `).join(`
@@ -23,7 +23,7 @@ ${[...t.errors.entries()].map(([s,i])=>`
23
23
  `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new ne(...e.map(a=>wi.single(I(`${a}
24
24
  `))),I(`
25
25
  `));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(I(`na
26
- `),t),n('responded with "na" for "%s"',s)}}var df=class extends Ne{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=ql(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new Xo(n.local,n.error))})}[Symbol.toStringTag]="Connection";[yf]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new tr("Connection is not multiplexed");if(this.muxer.status!=="open")throw new rr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new rr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Cn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new se("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await vn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=hx(n.protocol,this.components.registrar,t),s=Sm(n.protocol,"outbound",this);if(s>o){let c=new Yo(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new se("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let u=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",u),t.protocol=await Sn(t,u,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=dx(t.protocol,this.components.registrar);if(Sm(t.protocol,"inbound",this)>o)throw new jo(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Cn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(u,l,f)=>{await i(u,l),f(u,l)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(u,l)=>{e=u,t=l,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function Am(r,e){return new df(r,e)}function dx(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return uf}function hx(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??lf}function Sm(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Oa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Oe({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Oe({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,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"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_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 aa(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Et([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new ca("Connection denied");await je(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=xt(n),await je(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,u=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${u}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(px(n)){if(n.remotePeer==null)throw new Mt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;if(f!=null&&(d=xt(f)),n?.onProgress?.(new se(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d})),d!=null&&!d.equals(s)){let h=new qo(`Expected remote peer ${d} but connected to ${s}`);throw e.abort(h),h}}if(s.equals(this.components.peerId)){let f=new Nr("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new se(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let l=this._createConnection({id:u,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return l.log("successfully upgraded connection"),l}_createConnection(e){let t=Am(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Sn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Or(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Or(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await vn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Or(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Or(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 s=await vn(e,o,n),i=t.get(s);if(i==null)throw new tr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new tr(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Sn(e,o,n),i=t.get(s);if(i==null)throw new tr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function px(r){return r.skipEncryption===!0}var ka="3.5.2-15cea7995",Na="js-libp2p";function Cm(r,e){return`${r??Na}/${e??ka} browser/${globalThis.navigator.userAgent}`}var Uo=class extends Ne{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Ne,n=t.dispatchEvent.bind(t);t.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||f},this.peerId=e.peerId,this.logger=e.logger??Us(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??Na,s=e.nodeInfo?.version??ka,i=this.components=tm({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Cm(o,s)},logger:this.logger,events:t,datastore:e.datastore??new Gi,connectionGater:nm(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Yp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let l={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:l})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Oa(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(e.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Ra(this.components,e.transportManager)),this.configureComponent("connectionManager",new _a(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Ca(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Da(this.components)),this.configureComponent("addressManager",new Qi(this.components,e.addresses));let a=(e.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new La(this.components,{routers:a}));let c=(e.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ta(this.components,{routers:c})),this.configureComponent("randomWalk",new Pa(this.components)),(e.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),e.services!=null)for(let u of Object.keys(e.services)){let l=e.services[u],f=l(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=f,this.configureComponent(u,f),f[Ba]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Ba])),f[Ua]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[Ua])),f[Fa]!=null&&(this.log("registering service %s for peer discovery",u),f[Fa].addEventListener?.("peer",d=>{this.#e(d)}))}rm(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",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 br;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 T("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new T("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){er(e)&&(e=xt(e.getComponents().findLast(n=>n.code===421)?.value??"")),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,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=tt([I("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=await Dh(e,o,t);return await this.peerStore.patch(e,{publicKey:s},t),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,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){if(typeof e=="function"){this.components.registrar.use(e);return}if(t==null)throw new T("Protocol middleware is required");this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){if(typeof e=="function"){this.components.registrar.unuse(e);return}this.components.registrar.unuse(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("could not update multiaddrs of discovered peer - %e",n)})}};async function mx(r={}){r.privateKey??=await Lh("Ed25519");let e=new Uo({...await Nh(r),peerId:kh(r.privateKey)});return r.start!==!1&&await e.start(),e}var gx=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function yx(r){return r==null?!1:r instanceof Uo?!0:gx.every(e=>typeof r[e]=="function")}return Nm(bx);})();
26
+ `),t),n('responded with "na" for "%s"',s)}}var df=class extends Ne{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=ql(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new Xo(n.local,n.error))})}[Symbol.toStringTag]="Connection";[yf]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new tr("Connection is not multiplexed");if(this.muxer.status!=="open")throw new rr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new rr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Cn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new se("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await vn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=hx(n.protocol,this.components.registrar,t),s=Sm(n.protocol,"outbound",this);if(s>o){let c=new Yo(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new se("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let u=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",u),t.protocol=await Sn(t,u,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=dx(t.protocol,this.components.registrar);if(Sm(t.protocol,"inbound",this)>o)throw new jo(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Cn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(u,l,f)=>{await i(u,l),f(u,l)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(u,l)=>{e=u,t=l,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function Am(r,e){return new df(r,e)}function dx(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return uf}function hx(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??lf}function Sm(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Oa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Oe({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Oe({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,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"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_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 aa(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Et([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new ca("Connection denied");await je(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=xt(n),await je(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,u=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${u}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(px(n)){if(n.remotePeer==null)throw new Mt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;if(f!=null&&(d=xt(f)),n?.onProgress?.(new se(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d})),d!=null&&!d.equals(s)){let h=new qo(`Expected remote peer ${d} but connected to ${s}`);throw e.abort(h),h}}if(s.equals(this.components.peerId)){let f=new Nr("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new se(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let l=this._createConnection({id:u,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return l.log("successfully upgraded connection"),l}_createConnection(e){let t=Am(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Sn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Or(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Or(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await vn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Or(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Or(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 s=await vn(e,o,n),i=t.get(s);if(i==null)throw new tr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new tr(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Sn(e,o,n),i=t.get(s);if(i==null)throw new tr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function px(r){return r.skipEncryption===!0}var ka="3.5.2-19dc7bbd4",Na="js-libp2p";function Cm(r,e){return`${r??Na}/${e??ka} browser/${globalThis.navigator.userAgent}`}var Uo=class extends Ne{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Ne,n=t.dispatchEvent.bind(t);t.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||f},this.peerId=e.peerId,this.logger=e.logger??Us(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??Na,s=e.nodeInfo?.version??ka,i=this.components=tm({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Cm(o,s)},logger:this.logger,events:t,datastore:e.datastore??new Gi,connectionGater:nm(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Yp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let l={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:l})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Oa(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(e.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Ra(this.components,e.transportManager)),this.configureComponent("connectionManager",new _a(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Ca(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Da(this.components)),this.configureComponent("addressManager",new Qi(this.components,e.addresses));let a=(e.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new La(this.components,{routers:a}));let c=(e.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ta(this.components,{routers:c})),this.configureComponent("randomWalk",new Pa(this.components)),(e.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),e.services!=null)for(let u of Object.keys(e.services)){let l=e.services[u],f=l(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=f,this.configureComponent(u,f),f[Ba]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Ba])),f[Ua]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[Ua])),f[Fa]!=null&&(this.log("registering service %s for peer discovery",u),f[Fa].addEventListener?.("peer",d=>{this.#e(d)}))}rm(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",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 br;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 T("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new T("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){er(e)&&(e=xt(e.getComponents().findLast(n=>n.code===421)?.value??"")),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,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=tt([I("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=await Dh(e,o,t);return await this.peerStore.patch(e,{publicKey:s},t),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,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){if(typeof e=="function"){this.components.registrar.use(e);return}if(t==null)throw new T("Protocol middleware is required");this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){if(typeof e=="function"){this.components.registrar.unuse(e);return}this.components.registrar.unuse(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("could not update multiaddrs of discovered peer - %e",n)})}};async function mx(r={}){r.privateKey??=await Lh("Ed25519");let e=new Uo({...await Nh(r),peerId:kh(r.privateKey)});return r.start!==!1&&await e.start(),e}var gx=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function yx(r){return r==null?!1:r instanceof Uo?!0:gx.every(e=>typeof r[e]=="function")}return Nm(bx);})();
27
27
  /*! Bundled license information:
28
28
 
29
29
  @noble/curves/utils.js: