libp2p 0.36.1 → 0.36.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -37,12 +37,12 @@ if (cid) {
37
37
  (?:${mt}:){1}(?:(?::${mt}){0,4}:${qr}|(?::${mt}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
38
38
  (?::(?:(?::${mt}){0,5}:${qr}|(?::${mt}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
39
39
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
40
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),fP=new RegExp(`(?:^${qr}$)|(?:^${Hc}$)`),dP=new RegExp(`^${qr}$`),hP=new RegExp(`^${Hc}$`),Lf=t=>t&&t.exact?fP:new RegExp(`(?:${ri(t)}${qr}${ri(t)})|(?:${ri(t)}${Hc}${ri(t)})`,"g");Lf.v4=t=>t&&t.exact?dP:new RegExp(`${ri(t)}${qr}${ri(t)}`,"g");Lf.v6=t=>t&&t.exact?hP:new RegExp(`${ri(t)}${Hc}${ri(t)}`,"g");lv.exports=Lf});var Uf=w((mM,fv)=>{"use strict";var qf=kf(),Us=t=>qf({exact:!0}).test(t);Us.v4=t=>qf.v4({exact:!0}).test(t);Us.v6=t=>qf.v6({exact:!0}).test(t);Us.version=t=>Us(t)?Us.v4(t)?4:6:void 0;fv.exports=Us});var gv=w((vM,yv)=>{"use strict";var Mf=Uf(),{toString:dv}=(Tt(),Ot),pP=Mf,Ff=Mf.v4,hv=Mf.v6,pv=function(t,e,r){r=~~r;let n;if(Ff(t))n=e||new Uint8Array(r+4),t.split(/\./g).map(function(i){n[r++]=parseInt(i,10)&255});else if(hv(t)){let i=t.split(":",8),s;for(s=0;s<i.length;s++){let o=Ff(i[s]),a;o&&(a=pv(i[s]),i[s]=dv(a.slice(0,2),"base16")),a&&++s<8&&i.splice(s,0,dv(a.slice(2,4),"base16"))}if(i[0]==="")for(;i.length<8;)i.unshift("0");else if(i[i.length-1]==="")for(;i.length<8;)i.push("0");else if(i.length<8){for(s=0;s<i.length&&i[s]!=="";s++);let o=[s,"1"];for(s=9-i.length;s>0;s--)o.push("0");i.splice.apply(i,o)}for(n=e||new Uint8Array(r+16),s=0;s<i.length;s++){let o=parseInt(i[s],16);n[r++]=o>>8&255,n[r++]=o&255}}if(!n)throw Error("Invalid ip address: "+t);return n},yP=function(t,e,r){e=~~e,r=r||t.length-e;let n=[],i,s=new DataView(t.buffer);if(r===4){for(let o=0;o<r;o++)n.push(t[e+o]);i=n.join(".")}else if(r===16){for(let o=0;o<r;o+=2)n.push(s.getUint16(e+o).toString(16));i=n.join(":"),i=i.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3"),i=i.replace(/:{3,4}/,"::")}return i};yv.exports={isIP:pP,isV4:Ff,isV6:hv,toBytes:pv,toString:yP}});var ha=w((bM,vv)=>{"use strict";function Jt(t){if(typeof t=="number"){if(Jt.codes[t])return Jt.codes[t];throw new Error("no protocol with code: "+t)}else if(typeof t=="string"){if(Jt.names[t])return Jt.names[t];throw new Error("no protocol with name: "+t)}throw new Error("invalid protocol id type: "+t)}var _r=-1;Jt.lengthPrefixedVarSize=_r;Jt.V=_r;Jt.table=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,_r,"ip6zone"],[53,_r,"dns","resolvable"],[54,_r,"dns4","resolvable"],[55,_r,"dns6","resolvable"],[56,_r,"dnsaddr","resolvable"],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,_r,"unix",!1,"path"],[421,_r,"ipfs"],[421,_r,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,_r,"garlic64"],[460,0,"quic"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,_r,"memory"]];Jt.names={};Jt.codes={};Jt.table.map(t=>{let e=mv.apply(null,t);return Jt.codes[e.code]=e,Jt.names[e.name]=e,null});Jt.object=mv;function mv(t,e,r,n,i){return{code:t,size:e,name:r,resolvable:Boolean(n),path:Boolean(i)}}vv.exports=Jt});var wv=w((EM,Ev)=>{Ev.exports=Kf;var bv=128,gP=127,mP=~gP,vP=Math.pow(2,31);function Kf(t,e,r){if(Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw Kf.bytes=0,new RangeError("Could not encode varint");e=e||[],r=r||0;for(var n=r;t>=vP;)e[r++]=t&255|bv,t/=128;for(;t&mP;)e[r++]=t&255|bv,t>>>=7;return e[r]=t|0,Kf.bytes=r-n+1,e}});var xv=w((wM,Sv)=>{Sv.exports=Vf;var bP=128,_v=127;function Vf(t,e){var r=0,e=e||0,n=0,i=e,s,o=t.length;do{if(i>=o||n>49)throw Vf.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=n<28?(s&_v)<<n:(s&_v)*Math.pow(2,n),n+=7}while(s>=bP);return Vf.bytes=i-e,r}});var Cv=w((_M,Av)=>{var EP=Math.pow(2,7),wP=Math.pow(2,14),_P=Math.pow(2,21),SP=Math.pow(2,28),xP=Math.pow(2,35),AP=Math.pow(2,42),CP=Math.pow(2,49),IP=Math.pow(2,56),TP=Math.pow(2,63);Av.exports=function(t){return t<EP?1:t<wP?2:t<_P?3:t<SP?4:t<xP?5:t<AP?6:t<CP?7:t<IP?8:t<TP?9:10}});var Ui=w((SM,Iv)=>{Iv.exports={encode:wv(),decode:xv(),encodingLength:Cv()}});var Lv=w((xM,Dv)=>{"use strict";var zc=gv(),Tv=ha(),{CID:RP}=(ws(),ko),{base32:Rv}=(wi(),Ei),{base58btc:BP}=(qn(),kn),PP=(bi(),Do),Ms=Ui(),{toString:Gc}=(Tt(),Ot),{fromString:Bv}=(It(),Nt),{concat:Wc}=(Yn(),Wn);Dv.exports=pa;function pa(t,e){return e instanceof Uint8Array?pa.toString(t,e):pa.toBytes(t,e)}pa.toString=function(e,r){switch(Tv(e).code){case 4:case 41:return NP(r);case 6:case 273:case 33:case 132:return Nv(r).toString();case 53:case 54:case 55:case 56:case 400:case 777:return DP(r);case 421:return kP(r);case 444:return Ov(r);case 445:return Ov(r);default:return Gc(r,"base16")}};pa.toBytes=function(e,r){switch(Tv(e).code){case 4:return Pv(r);case 41:return Pv(r);case 6:case 273:case 33:case 132:return jf(parseInt(r,10));case 53:case 54:case 55:case 56:case 400:case 777:return OP(r);case 421:return LP(r);case 444:return qP(r);case 445:return UP(r);default:return Bv(r,"base16")}};function Pv(t){if(!zc.isIP(t))throw new Error("invalid ip address");return zc.toBytes(t)}function NP(t){let e=zc.toString(t);if(!e||!zc.isIP(e))throw new Error("invalid ip address");return e}function jf(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function Nv(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function OP(t){let e=Bv(t),r=Uint8Array.from(Ms.encode(e.length));return Wc([r,e],r.length+e.length)}function DP(t){let e=Ms.decode(t);if(t=t.slice(Ms.decode.bytes),t.length!==e)throw new Error("inconsistent lengths");return Gc(t)}function LP(t){let e;t[0]==="Q"||t[0]==="1"?e=PP.decode(BP.decode(`z${t}`)).bytes:e=RP.parse(t).multihash.bytes;let r=Uint8Array.from(Ms.encode(e.length));return Wc([r,e],r.length+e.length)}function kP(t){let e=Ms.decode(t),r=t.slice(Ms.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return Gc(r,"base58btc")}function qP(t){let e=t.split(":");if(e.length!==2)throw new Error("failed to parse onion addr: "+e+" 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 r=Rv.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 i=jf(n);return Wc([r,i],r.length+i.length)}function UP(t){let e=t.split(":");if(e.length!==2)throw new Error("failed to parse onion addr: "+e+" 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 r=Rv.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 i=jf(n);return Wc([r,i],r.length+i.length)}function Ov(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=Gc(e,"base32"),i=Nv(r);return n+":"+i}});var Gv=w((AM,zv)=>{"use strict";var kv=Lv(),$f=ha(),ya=Ui(),{concat:qv}=(Yn(),Wn),{toString:MP}=(Tt(),Ot);zv.exports={stringToStringTuples:Uv,stringTuplesToString:Mv,tuplesToStringTuples:Kv,stringTuplesToTuples:Fv,bytesToTuples:Hf,tuplesToBytes:Vv,bytesToString:FP,stringToBytes:$v,fromString:KP,fromBytes:Hv,validateBytes:zf,isValidBytes:VP,cleanPath:Yc,ParseError:Gf,protoFromTuple:ga,sizeForAddr:jv};function Uv(t){let e=[],r=t.split("/").slice(1);if(r.length===1&&r[0]==="")return[];for(let n=0;n<r.length;n++){let i=r[n],s=$f(i);if(s.size===0){e.push([i]);continue}if(n++,n>=r.length)throw Gf("invalid address: "+t);if(s.path){e.push([i,Yc(r.slice(n).join("/"))]);break}e.push([i,r[n]])}return e}function Mv(t){let e=[];return t.map(r=>{let n=ga(r);return e.push(n.name),r.length>1&&e.push(r[1]),null}),Yc(e.join("/"))}function Fv(t){return t.map(e=>{Array.isArray(e)||(e=[e]);let r=ga(e);return e.length>1?[r.code,kv.toBytes(r.code,e[1])]:[r.code]})}function Kv(t){return t.map(e=>{let r=ga(e);return e[1]?[r.code,kv.toString(r.code,e[1])]:[r.code]})}function Vv(t){return Hv(qv(t.map(e=>{let r=ga(e),n=Uint8Array.from(ya.encode(r.code));return e.length>1&&(n=qv([n,e[1]])),n})))}function jv(t,e){return t.size>0?t.size/8:t.size===0?0:ya.decode(e)+ya.decode.bytes}function Hf(t){let e=[],r=0;for(;r<t.length;){let n=ya.decode(t,r),i=ya.decode.bytes,s=$f(n),o=jv(s,t.slice(r+i));if(o===0){e.push([n]),r+=i;continue}let a=t.slice(r+i,r+i+o);if(r+=o+i,r>t.length)throw Gf("Invalid address Uint8Array: "+MP(t,"base16"));e.push([n,a])}return e}function FP(t){let e=Hf(t),r=Kv(e);return Mv(r)}function $v(t){t=Yc(t);let e=Uv(t),r=Fv(e);return Vv(r)}function KP(t){return $v(t)}function Hv(t){let e=zf(t);if(e)throw e;return Uint8Array.from(t)}function zf(t){try{Hf(t)}catch(e){return e}}function VP(t){return zf(t)===void 0}function Yc(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}function Gf(t){return new Error("Error parsing address: "+t)}function ga(t){return $f(t[0])}});var qt=w((CM,Qv)=>{"use strict";var Ur=Gv(),Fs=ha(),Wv=Ui(),{CID:jP}=(ws(),ko),{base58btc:$P}=(qn(),kn),HP=de(),zP=Symbol.for("nodejs.util.inspect.custom"),{toString:Qc}=(Tt(),Ot),{equals:GP}=(mr(),gr),Wf=new Map,Yv=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Ht=class{constructor(e){if(e==null&&(e=""),Object.defineProperty(this,Yv,{value:!0}),e instanceof Uint8Array)this.bytes=Ur.fromBytes(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=Ur.fromString(e)}else if(Ht.isMultiaddr(e))this.bytes=Ur.fromBytes(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return Ur.bytesToString(this.bytes)}toJSON(){return this.toString()}toOptions(){let e={},r=this.toString().split("/");return e.family=r[1]==="ip4"?4:6,e.host=r[2],e.transport=r[3],e.port=parseInt(r[4]),e}protos(){return this.protoCodes().map(e=>Object.assign({},Fs(e)))}protoCodes(){let e=[],r=this.bytes,n=0;for(;n<r.length;){let i=Wv.decode(r,n),s=Wv.decode.bytes,o=Fs(i);n+=Ur.sizeForAddr(o,r.slice(n+s))+s,e.push(i)}return e}protoNames(){return this.protos().map(e=>e.name)}tuples(){return Ur.bytesToTuples(this.bytes)}stringTuples(){let e=Ur.bytesToTuples(this.bytes);return Ur.tuplesToStringTuples(e)}encapsulate(e){return e=new Ht(e),new Ht(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error("Address "+this+" does not contain subaddress: "+e);return new Ht(n.slice(0,i))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new Ht(Ur.tuplesToBytes(r.slice(0,n)));return this}getPeerId(){try{let r=this.stringTuples().filter(n=>n[0]===Fs.names.ipfs.code).pop();if(r&&r[1]){let n=r[1];return n[0]==="Q"||n[0]==="1"?Qc($P.decode(`z${n}`),"base58btc"):Qc(jP.parse(n).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){let e=null;try{e=this.stringTuples().filter(r=>!!Fs(r[0]).path)[0][1],e||(e=null)}catch(r){e=null}return e}equals(e){return GP(this.bytes,e.bytes)}async resolve(){let e=this.protos().find(i=>i.resolvable);if(!e)return[this];let r=Wf.get(e.name);if(!r)throw HP(new Error(`no available resolver for ${e.name}`),"ERR_NO_AVAILABLE_RESOLVER");return(await r(this)).map(i=>new Ht(i))}nodeAddress(){let e=this.protoCodes(),r=this.protoNames(),n=this.toString().split("/").slice(1);if(n.length<4)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6}/{address}/{tcp, udp}/{port}".');if(e[0]!==4&&e[0]!==41&&e[0]!==54&&e[0]!==55)throw new Error(`no protocol with name: "'${r[0]}'". Must have a valid family name: "{ip4, ip6, dns4, dns6}".`);if(n[2]!=="tcp"&&n[2]!=="udp")throw new Error(`no protocol with name: "'${r[1]}'". Must have a valid transport protocol: "{tcp, udp}".`);return{family:e[0]===41||e[0]===55?6:4,address:n[1],port:parseInt(n[3])}}isThinWaistAddress(e){let r=(e||this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}static fromNodeAddress(e,r){if(!e)throw new Error("requires node address object");if(!r)throw new Error("requires transport protocol");let n;switch(e.family){case 4:n="ip4";break;case 6:n="ip6";break;default:throw Error(`Invalid addr family. Got '${e.family}' instead of 4 or 6`)}return new Ht("/"+[n,e.address,r,e.port].join("/"))}static isName(e){return Ht.isMultiaddr(e)?e.protos().some(r=>r.resolvable):!1}static isMultiaddr(e){return e instanceof Ht||Boolean(e&&e[Yv])}[zP](){return"<Multiaddr "+Qc(this.bytes,"base16")+" - "+Ur.bytesToString(this.bytes)+">"}inspect(){return"<Multiaddr "+Qc(this.bytes,"base16")+" - "+Ur.bytesToString(this.bytes)+">"}};Ht.protocols=Fs;Ht.resolvers=Wf;function WP(t){return new Ht(t)}Qv.exports={Multiaddr:Ht,multiaddr:WP,protocols:Fs,resolvers:Wf}});var Mi=w((IM,Xv)=>{"use strict";var YP=async t=>{let e=[];for await(let r of t)e.push(r);return e};Xv.exports=YP});var Zv,Yf,Jv=Se(()=>{Zv=Po(Mi()),Yf=(t,e)=>async function*(){yield*(await(0,Zv.default)(t)).sort(e)}()});var ma=w((RM,e1)=>{"use strict";var QP=async t=>{for await(let e of t);};e1.exports=QP});var Fi=w((BM,t1)=>{"use strict";var XP=async function*(t,e){for await(let r of t)await e(r)&&(yield r)};t1.exports=XP});var Qf=w((PM,r1)=>{"use strict";var ZP=async function*(t,e){let r=0;if(!(e<1)){for await(let n of t)if(yield n,r++,r===e)return}};r1.exports=ZP});var Xf,Ki,Zf,Jf,n1=Se(()=>{Jv();Xf=Po(ma()),Ki=Po(Fi()),Zf=Po(Qf()),Jf=class{open(){return Promise.reject(new Error(".open is not implemented"))}close(){return Promise.reject(new Error(".close is not implemented"))}put(e,r,n){return Promise.reject(new Error(".put is not implemented"))}get(e,r){return Promise.reject(new Error(".get is not implemented"))}has(e,r){return Promise.reject(new Error(".has is not implemented"))}delete(e,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,r={}){for await(let{key:n,value:i}of e)await this.put(n,i,r),yield{key:n,value:i}}async*getMany(e,r={}){for await(let n of e)yield this.get(n,r)}async*deleteMany(e,r={}){for await(let n of e)await this.delete(n,r),yield n}batch(){let e=[],r=[];return{put(n,i){e.push({key:n,value:i})},delete(n){r.push(n)},commit:async n=>{await(0,Xf.default)(this.putMany(e,n)),e=[],await(0,Xf.default)(this.deleteMany(r,n)),r=[]}}}async*_all(e,r){throw new Error("._all is not implemented")}async*_allKeys(e,r){throw new Error("._allKeys is not implemented")}query(e,r){let n=this._all(e,r);if(e.prefix!=null&&(n=(0,Ki.default)(n,i=>i.key.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>(0,Ki.default)(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>Yf(i,s),n)),e.offset!=null){let i=0;n=(0,Ki.default)(n,()=>i++>=e.offset)}return e.limit!=null&&(n=(0,Zf.default)(n,e.limit)),n}queryKeys(e,r){let n=this._allKeys(e,r);if(e.prefix!=null&&(n=(0,Ki.default)(n,i=>i.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>(0,Ki.default)(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>Yf(i,s),n)),e.offset!=null){let i=0;n=(0,Ki.default)(n,()=>i++>=e.offset)}return e.limit!=null&&(n=(0,Zf.default)(n,e.limit)),n}}});var i1,s1=Se(()=>{i1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"});var td={};gt(td,{customAlphabet:()=>JP,customRandom:()=>a1,nanoid:()=>ed,random:()=>o1,urlAlphabet:()=>i1});var o1,a1,JP,ed,Xc=Se(()=>{s1();o1=t=>crypto.getRandomValues(new Uint8Array(t)),a1=(t,e,r)=>{let n=(2<<Math.log(t.length-1)/Math.LN2)-1,i=-~(1.6*n*e/t.length);return()=>{let s="";for(;;){let o=r(i),a=i;for(;a--;)if(s+=t[o[a]&n]||"",s.length===e)return s}}},JP=(t,e)=>a1(t,e,o1),ed=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t));for(;t--;){let n=r[t]&63;n<36?e+=n.toString(36):n<62?e+=(n-26).toString(36).toUpperCase():n<63?e+="_":e+="-"}return e}});var rd={};gt(rd,{Key:()=>Bt});function eN(t){let e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function tN(t){let e=t.split(":");return e[e.length-1]}function rN(t){return[].concat(...t)}var An,c1,Zc,Bt,Jc=Se(()=>{Xc();Tt();It();An="/",c1=new TextEncoder().encode(An),Zc=c1[0],Bt=class{constructor(e,r){if(typeof e=="string")this._buf=cf(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(r==null&&(r=!0),r&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Zc)throw new Error("Invalid key")}toString(e="utf8"){return lf(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Bt(e.join(An))}static random(){return new Bt(ed().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new Bt(e):e.uint8Array?new Bt(e.uint8Array()):null}clean(){if((!this._buf||this._buf.byteLength===0)&&(this._buf=c1),this._buf[0]!==Zc){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Zc,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Zc;)this._buf=this._buf.subarray(0,-1)}less(e){let r=this.list(),n=e.list();for(let i=0;i<r.length;i++){if(n.length<i+1)return!1;let s=r[i],o=n[i];if(s<o)return!0;if(s>o)return!1}return r.length<n.length}reverse(){return Bt.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(An).slice(1)}type(){return eN(this.baseNamespace())}name(){return tN(this.baseNamespace())}instance(e){return new Bt(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(An)||(e+=An),e+=this.type(),new Bt(e)}parent(){let e=this.list();return e.length===1?new Bt(An):new Bt(e.slice(0,-1).join(An))}child(e){return this.toString()===An?e:e.toString()===An?this:new Bt(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 Bt.withNamespaces([...this.namespaces(),...rN(e.map(r=>r.namespaces()))])}}});function l1(t){return t=t||new Error("Not Found"),(0,u1.default)(t,"ERR_NOT_FOUND")}var u1,f1=Se(()=>{u1=Po(de())});var h1={};gt(h1,{MemoryDatastore:()=>d1});var d1,p1=Se(()=>{n1();Jc();f1();d1=class extends Jf{constructor(){super();this.data={}}open(){return Promise.resolve()}close(){return Promise.resolve()}async put(e,r){this.data[e.toString()]=r}async get(e){if(!await this.has(e))throw l1();return this.data[e.toString()]}async has(e){return this.data[e.toString()]!==void 0}async delete(e){delete this.data[e.toString()]}async*_all(){yield*Object.entries(this.data).map(([e,r])=>({key:new Bt(e),value:r}))}async*_allKeys(){yield*Object.entries(this.data).map(([e])=>new Bt(e))}}});var je=w(nd=>{"use strict";nd.messages={NOT_STARTED_YET:"The libp2p node is not started yet",DHT_DISABLED:"DHT is not available",CONN_ENCRYPTION_REQUIRED:"At least one connection encryption module is required",NOT_FOUND:"Not found"};nd.codes={DHT_DISABLED:"ERR_DHT_DISABLED",PUBSUB_NOT_STARTED:"ERR_PUBSUB_NOT_STARTED",DHT_NOT_STARTED:"ERR_DHT_NOT_STARTED",CONN_ENCRYPTION_REQUIRED:"ERR_CONN_ENCRYPTION_REQUIRED",ERR_PEER_DIAL_INTERCEPTED:"ERR_PEER_DIAL_INTERCEPTED",ERR_CONNECTION_INTERCEPTED:"ERR_CONNECTION_INTERCEPTED",ERR_INVALID_PROTOCOLS_FOR_STREAM:"ERR_INVALID_PROTOCOLS_FOR_STREAM",ERR_CONNECTION_ENDED:"ERR_CONNECTION_ENDED",ERR_CONNECTION_FAILED:"ERR_CONNECTION_FAILED",ERR_NODE_NOT_STARTED:"ERR_NODE_NOT_STARTED",ERR_ALREADY_ABORTED:"ERR_ALREADY_ABORTED",ERR_TOO_MANY_ADDRESSES:"ERR_TOO_MANY_ADDRESSES",ERR_NO_VALID_ADDRESSES:"ERR_NO_VALID_ADDRESSES",ERR_RELAYED_DIAL:"ERR_RELAYED_DIAL",ERR_DIALED_SELF:"ERR_DIALED_SELF",ERR_DISCOVERED_SELF:"ERR_DISCOVERED_SELF",ERR_DUPLICATE_TRANSPORT:"ERR_DUPLICATE_TRANSPORT",ERR_ENCRYPTION_FAILED:"ERR_ENCRYPTION_FAILED",ERR_HOP_REQUEST_FAILED:"ERR_HOP_REQUEST_FAILED",ERR_INVALID_KEY:"ERR_INVALID_KEY",ERR_INVALID_MESSAGE:"ERR_INVALID_MESSAGE",ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS",ERR_INVALID_PEER:"ERR_INVALID_PEER",ERR_MUXER_UNAVAILABLE:"ERR_MUXER_UNAVAILABLE",ERR_NOT_FOUND:"ERR_NOT_FOUND",ERR_TIMEOUT:"ERR_TIMEOUT",ERR_TRANSPORT_UNAVAILABLE:"ERR_TRANSPORT_UNAVAILABLE",ERR_TRANSPORT_DIAL_FAILED:"ERR_TRANSPORT_DIAL_FAILED",ERR_UNSUPPORTED_PROTOCOL:"ERR_UNSUPPORTED_PROTOCOL",ERR_INVALID_MULTIADDR:"ERR_INVALID_MULTIADDR",ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID",ERR_FIND_SELF:"ERR_FIND_SELF",ERR_NO_ROUTERS_AVAILABLE:"ERR_NO_ROUTERS_AVAILABLE",ERR_CONNECTION_NOT_MULTIPLEXED:"ERR_CONNECTION_NOT_MULTIPLEXED",ERR_NO_DIAL_TOKENS:"ERR_NO_DIAL_TOKENS",ERR_KEYCHAIN_REQUIRED:"ERR_KEYCHAIN_REQUIRED",ERR_INVALID_CMS:"ERR_INVALID_CMS",ERR_MISSING_KEYS:"ERR_MISSING_KEYS",ERR_NO_KEY:"ERR_NO_KEY",ERR_INVALID_KEY_NAME:"ERR_INVALID_KEY_NAME",ERR_INVALID_KEY_TYPE:"ERR_INVALID_KEY_TYPE",ERR_KEY_ALREADY_EXISTS:"ERR_KEY_ALREADY_EXISTS",ERR_INVALID_KEY_SIZE:"ERR_INVALID_KEY_SIZE",ERR_KEY_NOT_FOUND:"ERR_KEY_NOT_FOUND",ERR_OLD_KEY_NAME_INVALID:"ERR_OLD_KEY_NAME_INVALID",ERR_NEW_KEY_NAME_INVALID:"ERR_NEW_KEY_NAME_INVALID",ERR_PASSWORD_REQUIRED:"ERR_PASSWORD_REQUIRED",ERR_PEM_REQUIRED:"ERR_PEM_REQUIRED",ERR_CANNOT_READ_KEY:"ERR_CANNOT_READ_KEY",ERR_MISSING_PRIVATE_KEY:"ERR_MISSING_PRIVATE_KEY",ERR_INVALID_OLD_PASS_TYPE:"ERR_INVALID_OLD_PASS_TYPE",ERR_INVALID_NEW_PASS_TYPE:"ERR_INVALID_NEW_PASS_TYPE",ERR_INVALID_PASS_LENGTH:"ERR_INVALID_PASS_LENGTH",ERR_NOT_IMPLEMENTED:"ERR_NOT_IMPLEMENTED",ERR_WRONG_PING_ACK:"ERR_WRONG_PING_ACK"}});var id=w(($M,y1)=>{"use strict";var nN=async function*(t,e){for await(let r of t)yield e(r)};y1.exports=nN});var sd=w((HM,g1)=>{"use strict";var iN=de(),sN=Fi(),oN=id(),aN=Qf();async function*cN(t,e){yield*oN(t,async r=>(await e.addressBook.add(r.id,r.multiaddrs),r))}function uN(t){let e=new Set;return sN(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*lN(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw iN(new Error("not found"),"NOT_FOUND")}function fN(t,e){return e?aN(t,e):t}g1.exports={storeAddresses:cN,uniquePeers:uN,requirePeers:lN,maybeLimitSource:fN}});var v1=w((zM,m1)=>{"use strict";m1.exports=function(){return Date.now()}});var va=w((GM,E1)=>{"use strict";var eu=v1(),b1=class{constructor(e,r,n){let i=this;this._started=eu(),this._rescheduled=0,this._scheduled=r,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(eu()-i._started),i._schedule(i._scheduled)):(i._triggered=!0,e.apply(null,i._args))},this._timer=setTimeout(this._timerWrapper,r)}reschedule(e){e||(e=this._scheduled);let r=eu();r+e-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(e)):this._triggered?this._schedule(e):(this._started=r,this._rescheduled=e)}_schedule(e){this._triggered=!1,this._started=eu(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function dN(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let t;if(arguments.length>0){t=new Array(arguments.length-2);for(var e=0;e<t.length;e++)t[e]=arguments[e+2]}return new b1(arguments[0],arguments[1],t)}E1.exports=dN});var od=w((WM,_1)=>{"use strict";var{AbortController:hN}=globalThis,w1=va(),tu=class extends hN{constructor(e){super();this._ms=e,this._timer=w1(()=>this.abort(),e),Object.setPrototypeOf(this,tu.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=w1(()=>this.abort(),this._ms)}};_1.exports={TimeoutController:tu}});var x1=w((QM,S1)=>{S1.exports=class{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}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var ad=w((ZM,C1)=>{var A1=x1();C1.exports=class{constructor(e){this.hwm=e||16,this.head=new A1(this.hwm),this.tail=this.head}push(e){if(!this.head.push(e)){let r=this.head;this.head=r.next=new A1(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next){let r=this.tail.next;return this.tail.next=null,this.tail=r,this.tail.shift()}return e}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}});var ud=w((JM,I1)=>{var cd=ad();I1.exports=t=>{t=t||{};let e;typeof t=="function"?(e=t,t={}):e=t.onEnd;let r=new cd,n,i,s,o=()=>{if(!r.isEmpty()){if(t.writev){let g,m=[];for(;!r.isEmpty();){if(g=r.shift(),g.error)throw g.error;m.push(g.value)}return{done:g.done,value:m}}let h=r.shift();if(h.error)throw h.error;return h}return s?{done:!0}:new Promise((h,g)=>{i=m=>(i=null,m.error?g(m.error):t.writev&&!m.done?h({done:m.done,value:[m.value]}):h(m),n)})},a=h=>i?i(h):(r.push(h),n),c=h=>(r=new cd,i?i({error:h}):(r.push({error:h}),n)),u=h=>s?n:a({done:!1,value:h}),l=h=>s?n:(s=!0,h?c(h):a({done:!0})),f=()=>(r=new cd,l(),{done:!0}),d=h=>(l(h),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:o,return:f,throw:d,push:u,end:l},!e)return n;let p=n;return n={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(h){return p.throw(h),e&&(e(h),e=null),{done:!0}},return(){return p.return(),e&&(e(),e=null),{done:!0}},push:u,end(h){return p.end(h),e&&(e(h),e=null),n}},n}});var ld=w((eF,T1)=>{"use strict";var pN=ud(),yN=async function*(...t){let e=pN();setTimeout(async()=>{try{await Promise.all(t.map(async r=>{for await(let n of r)e.push(n)})),e.end()}catch(r){e.end(r)}},0),yield*e};T1.exports=yN});var ir=w((tF,Ks)=>{var R1=(...t)=>{let e;for(;t.length;)e=t.shift()(e);return e},fd=t=>t&&(typeof t[Symbol.asyncIterator]=="function"||typeof t[Symbol.iterator]=="function"||typeof t.next=="function"),ru=t=>t&&typeof t.sink=="function"&&fd(t.source),gN=t=>e=>(t.sink(e),t.source),B1=(...t)=>{if(ru(t[0])){let e=t[0];t[0]=()=>e.source}else if(fd(t[0])){let e=t[0];t[0]=()=>e}if(t.length>1&&ru(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let e=1;e<t.length-1;e++)ru(t[e])&&(t[e]=gN(t[e]));return R1(...t)};Ks.exports=B1;Ks.exports.pipe=B1;Ks.exports.rawPipe=R1;Ks.exports.isIterable=fd;Ks.exports.isDuplex=ru});var dd=w((rF,P1)=>{"use strict";var mN=async t=>{for await(let e of t)return e};P1.exports=mN});var hd=w((nF,N1)=>{"use strict";var Vs=new Map,vN=()=>`${Date.now()}:${Math.floor(Math.random()*1e6)}`;async function bN(t,e,r){for(;Vs.get(r);){try{await t()}catch(n){setTimeout(()=>{throw n},1);break}if(!Vs.get(r))break;await new Promise(n=>{let i=setTimeout(n,e);Vs.set(r,i)})}}function EN(t,e,r){r=r||e;let n=vN(),i=setTimeout(()=>{bN(t,e,n)},r);return Vs.set(n,i),n}function wN(t){let e=Vs.get(t);e&&(clearTimeout(e),Vs.delete(t))}N1.exports={setDelayedInterval:EN,clearDelayedInterval:wN}});var L1=w((iF,D1)=>{"use strict";var _N=de(),{messages:SN,codes:xN}=je(),O1=class{constructor(e){this._dht=e}async findPeer(e,r={}){for await(let n of this._dht.findPeer(e,r))if(n.name==="FINAL_PEER")return n.peer;throw _N(new Error(SN.NOT_FOUND),xN.ERR_NOT_FOUND)}async*getClosestPeers(e,r={}){for await(let n of this._dht.getClosestPeers(e,r))n.name==="PEER_RESPONSE"&&(yield*n.closer)}};D1.exports={DHTPeerRouting:O1}});var $1=w((sF,j1)=>{"use strict";var k1=Te(),q1=Object.assign(k1("libp2p:peer-routing"),{error:k1("libp2p:peer-routing:err")}),nu=de(),ba=je(),{storeAddresses:U1,uniquePeers:AN,requirePeers:CN}=sd(),{TimeoutController:IN}=od(),M1=ld(),{pipe:F1}=ir(),TN=dd(),RN=ma(),BN=Fi(),{setDelayedInterval:PN,clearDelayedInterval:NN}=hd(),{DHTPeerRouting:ON}=L1(),{setMaxListeners:K1}=Qt(),V1=class{constructor(e){this._peerId=e.peerId,this._peerStore=e.peerStore,this._routers=e._modules.peerRouting||[],e._dht&&e._config.dht.enabled&&this._routers.push(new ON(e._dht)),this._refreshManagerOptions=e._options.peerRouting.refreshManager,this._findClosestPeersTask=this._findClosestPeersTask.bind(this)}start(){!this._routers.length||this._timeoutId||!this._refreshManagerOptions.enabled||(this._timeoutId=PN(this._findClosestPeersTask,this._refreshManagerOptions.interval,this._refreshManagerOptions.bootDelay))}async _findClosestPeersTask(){try{await RN(this.getClosestPeers(this._peerId.id,{timeout:this._refreshManagerOptions.timeout||1e4}))}catch(e){q1.error(e)}}stop(){NN(this._timeoutId)}async findPeer(e,r){if(!this._routers.length)throw nu(new Error("No peer routers available"),ba.codes.ERR_NO_ROUTERS_AVAILABLE);if(e.toB58String()===this._peerId.toB58String())throw nu(new Error("Should not try to find self"),ba.codes.ERR_FIND_SELF);let n=await F1(M1(...this._routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(s){q1.error(s)}}())),i=>BN(i,Boolean),i=>U1(i,this._peerStore),i=>TN(i));if(n)return n;throw nu(new Error(ba.messages.NOT_FOUND),ba.codes.ERR_NOT_FOUND)}async*getClosestPeers(e,r={timeout:3e4}){if(!this._routers.length)throw nu(new Error("No peer routers available"),ba.codes.ERR_NO_ROUTERS_AVAILABLE);if(r.timeout){let n=new IN(r.timeout);try{K1&&K1(1/0,n.signal)}catch{}r.signal=n.signal}yield*F1(M1(...this._routers.map(n=>n.getClosestPeers(e,r))),n=>U1(n,this._peerStore),n=>AN(n),n=>CN(n))}};j1.exports=V1});var G1=w((oF,z1)=>{"use strict";var DN=ma(),H1=class{constructor(e){this._dht=e}async provide(e){await DN(this._dht.provide(e))}async*findProviders(e,r){for await(let n of this._dht.findProviders(e,r))n.name==="PROVIDER"&&(yield*n.providers)}};z1.exports={DHTContentRouting:H1}});var Q1=w((aF,Y1)=>{"use strict";var Vi=de(),{messages:Ea,codes:ji}=je(),{storeAddresses:LN,uniquePeers:kN,requirePeers:qN,maybeLimitSource:UN}=sd(),MN=ma(),FN=ld(),{pipe:KN}=ir(),{DHTContentRouting:VN}=G1(),W1=class{constructor(e){this.libp2p=e,this.routers=e._modules.contentRouting||[],this.dht=e._dht,this.dht&&e._config.dht.enabled&&this.routers.push(new VN(this.dht))}async*findProviders(e,r={}){if(!this.routers.length)throw Vi(new Error("No content this.routers available"),ji.ERR_NO_ROUTERS_AVAILABLE);yield*KN(FN(...this.routers.map(n=>n.findProviders(e,r))),n=>LN(n,this.libp2p.peerStore),n=>kN(n),n=>UN(n,r.maxNumProviders),n=>qN(n))}async provide(e){if(!this.routers.length)throw Vi(new Error("No content routers available"),ji.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(r=>r.provide(e)))}async put(e,r,n){if(!this.libp2p.isStarted()||!this.dht.isStarted)throw Vi(new Error(Ea.NOT_STARTED_YET),ji.DHT_NOT_STARTED);await MN(this.dht.put(e,r,n))}async get(e,r){if(!this.libp2p.isStarted()||!this.dht.isStarted)throw Vi(new Error(Ea.NOT_STARTED_YET),ji.DHT_NOT_STARTED);for await(let n of this.dht.get(e,r))if(n.name==="VALUE")return{from:n.peerId,val:n.value};throw Vi(new Error(Ea.NOT_FOUND),ji.ERR_NOT_FOUND)}async*getMany(e,r,n){if(!this.libp2p.isStarted()||!this.dht.isStarted)throw Vi(new Error(Ea.NOT_STARTED_YET),ji.DHT_NOT_STARTED);if(!r)return;let i=0;for await(let s of this.dht.get(e,n))if(s.name==="VALUE"&&(yield{from:s.peerId,val:s.value},i++,i===r))break;if(i===0)throw Vi(new Error(Ea.NOT_FOUND),ji.ERR_NOT_FOUND)}};Y1.exports=W1});var pd=w((cF,eb)=>{"use strict";var jN=Rt(),{Multiaddr:X1}=qt(),Z1=de(),{codes:J1}=je();function $N(t){typeof t=="string"&&(t=new X1(t));let e;if(X1.isMultiaddr(t)){e=t;let r=t.getPeerId();if(!r)throw Z1(new Error(`${t} does not have a valid peer type`),J1.ERR_INVALID_MULTIADDR);try{t=jN.createFromB58String(r)}catch(n){throw Z1(new Error(`${t} is not a valid peer type`),J1.ERR_INVALID_MULTIADDR)}}return{id:t,multiaddrs:e?[e]:void 0}}eb.exports=$N});var rb=w((uF,tb)=>{"use strict";tb.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var Hs=w((ob,ab)=>{"use strict";var iu=rb(),{hasOwnProperty:nb}=Object.prototype,{propertyIsEnumerable:HN}=Object,js=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),zN=ob,ib={concatArrays:!1,ignoreUndefined:!1},su=t=>{let e=[];for(let r in t)nb.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let n of r)HN.call(t,n)&&e.push(n)}return e};function $s(t){return Array.isArray(t)?GN(t):iu(t)?WN(t):t}function GN(t){let e=t.slice(0,0);return su(t).forEach(r=>{js(e,r,$s(t[r]))}),e}function WN(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return su(t).forEach(r=>{js(e,r,$s(t[r]))}),e}var sb=(t,e,r,n)=>(r.forEach(i=>{typeof e[i]=="undefined"&&n.ignoreUndefined||(i in t&&t[i]!==Object.getPrototypeOf(t)?js(t,i,yd(t[i],e[i],n)):js(t,i,$s(e[i])))}),t),YN=(t,e,r)=>{let n=t.slice(0,0),i=0;return[t,e].forEach(s=>{let o=[];for(let a=0;a<s.length;a++)!nb.call(s,a)||(o.push(String(a)),s===t?js(n,i++,s[a]):js(n,i++,$s(s[a])));n=sb(n,s,su(s).filter(a=>!o.includes(a)),r)}),n};function yd(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?YN(t,e,r):!iu(e)||!iu(t)?$s(e):sb(t,e,su(e),r)}ab.exports=function(...t){let e=yd($s(ib),this!==zN&&this||{},ib),r={_:{}};for(let n of t)if(n!==void 0){if(!iu(n))throw new TypeError("`"+n+"` is not an Option Object");r=yd(r,{_:n},e)}return r._}});var lb=w((lF,ub)=>{"use strict";ub.exports=cb;var QN=ul(),ni=cb.prototype,XN=new Date%1e9;function ZN(){return(Math.random()*1e9>>>0)+XN++}function cb(t){t=t||{},this.id=t.id||ZN(),this.max=t.max||1/0,this.items=t.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(t.lastModified||new Date);for(var e,r,n=this.items.length;n--;)e=this.items[n],r=new Date(e.expires)-new Date,this._lookup[e.key]=e,r>0?this.expire(e.key,r):r<=0&&this.delete(e.key)}ni.has=function(t){return t in this._lookup};ni.get=function(t){if(!this.has(t))return null;var e=this._lookup[t];return e.refresh&&this.expire(t,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};ni.meta=function(t){if(!this.has(t))return null;var e=this._lookup[t];return"meta"in e?e.meta:null};ni.set=function(t,e,r){var n=this._lookup[t],i=this._lookup[t]={key:t,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,i)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(i),this.size++),r&&("ttl"in r&&this.expire(t,r.ttl),"meta"in r&&(i.meta=r.meta),r.refresh&&(i.refresh=r.ttl)),this};ni.delete=function(t){var e=this._lookup[t];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[t],this.size--,this):!1};ni.expire=function(t,e){var r=e||0,n=this._lookup[t];if(!n)return this;if(typeof r=="string"&&(r=QN(e)),typeof r!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),r),n.expires=Number(new Date)+r,this};ni.clear=function(){for(var t=this.items.length;t--;)this.delete(this.items[t].key);return this};ni.toJSON=function(){for(var t=new Array(this.items.length),e,r=t.length;r--;)e=this.items[r],t[r]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:t}}});var wa=w((zs,fb)=>{"use strict";var JN=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof Cn!="undefined")return Cn;throw new Error("unable to locate global object")},Cn=JN();fb.exports=zs=Cn.fetch;Cn.fetch&&(zs.default=Cn.fetch.bind(Cn));zs.Headers=Cn.Headers;zs.Request=Cn.Request;zs.Response=Cn.Response});var db=w((fF,gd)=>{"use strict";globalThis.fetch&&globalThis.Headers&&globalThis.Request&&globalThis.Response?gd.exports={default:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response}:gd.exports={default:wa().default,Headers:wa().Headers,Request:wa().Request,Response:wa().Response}});var pb=w((dF,hb)=>{"use strict";var{default:e3,Headers:t3}=db();function r3({serverResolver:t,hostname:e,recordType:r}){return`${t}?name=${e}&type=${r}`}function n3(t){return e3(t,{headers:new t3({accept:"application/dns-json"})})}function i3(t,e){return`${e}_${t}`}hb.exports={buildResource:r3,fetch:n3,getCacheKey:i3}});var mb=w((hF,gb)=>{"use strict";var yb=Te(),ou=yb("dns-over-http-resolver");ou.error=yb("dns-over-http-resolver:error");var s3=lb(),Sr=pb(),au=class{constructor({maxCache:e=100}={}){this._cache=new s3({max:e}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"]}getServers(){return this._servers}_getShuffledServers(){let e=[].concat(this._servers);for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}resolve(e,r="A"){switch(r){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(Sr.getCacheKey(e,r));if(n)return n;for(let i of this._getShuffledServers())try{let o=await(await Sr.fetch(Sr.buildResource({serverResolver:i,hostname:e,recordType:r}))).json(),a=o.Answer.map(u=>u.data),c=Math.min(o.Answer.map(u=>u.TTL));return this._cache.set(Sr.getCacheKey(e,r),a,{ttl:c}),a}catch(s){ou.error(`${i} could not resolve ${e} record ${r}`)}throw new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(Sr.getCacheKey(e,r));if(n)return n;for(let i of this._getShuffledServers())try{let o=await(await Sr.fetch(Sr.buildResource({serverResolver:i,hostname:e,recordType:r}))).json(),a=o.Answer.map(u=>u.data),c=Math.min(o.Answer.map(u=>u.TTL));return this._cache.set(Sr.getCacheKey(e,r),a,{ttl:c}),a}catch(s){ou.error(`${i} could not resolve ${e} record ${r}`)}throw new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._cache.get(Sr.getCacheKey(e,r));if(n)return n;for(let i of this._getShuffledServers())try{let o=await(await Sr.fetch(Sr.buildResource({serverResolver:i,hostname:e,recordType:r}))).json(),a=o.Answer.map(u=>[u.data.replace(/['"]+/g,"")]),c=Math.min(o.Answer.map(u=>u.TTL));return this._cache.set(Sr.getCacheKey(e,r),a,{ttl:c}),a}catch(s){ou.error(`${i} could not resolve ${e} record ${r}`)}throw new Error(`Could not resolve ${e} record ${r}`)}};au.Resolver=au;gb.exports=au});var bb=w((pF,vb)=>{"use strict";var o3=mb();vb.exports=o3});var wb=w((yF,Eb)=>{"use strict";var a3=ha(),{code:c3}=a3("dnsaddr");async function u3(t){let e=bb(),r=new e,n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===c3)||[],o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]);return n&&(o=o.filter(a=>a.includes(n))),o}Eb.exports={dnsaddrResolver:u3}});var cu=w((gF,_b)=>{"use strict";_b.exports={DIAL_TIMEOUT:3e4,MAX_PARALLEL_DIALS:100,MAX_PER_PEER_DIALS:4,MAX_ADDRS_TO_DIAL:25,METRICS:{computeThrottleMaxQueueSize:1e3,computeThrottleTimeout:2e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3],maxOldPeersRetention:50}}});var md=w((mF,l3)=>{l3.exports={name:"libp2p",version:"0.36.1",description:"JavaScript implementation of libp2p, a modular peer to peer network stack",leadMaintainer:"Jacob Heun <jacobheun@gmail.com>",main:"src/index.js",types:"dist/src/index.d.ts",typesVersions:{"*":{"src/*":["dist/src/*","dist/src/*/index"]}},files:["dist","src"],scripts:{lint:"aegir lint",build:"aegir build","build:proto":"npm run build:proto:circuit && npm run build:proto:fetch && npm run build:proto:identify && npm run build:proto:plaintext && npm run build:proto:address-book && npm run build:proto:proto-book && npm run build:proto:peer && npm run build:proto:peer-record && npm run build:proto:envelope","build:proto:circuit":"pbjs -t static-module -w commonjs -r libp2p-circuit --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/circuit/protocol/index.js ./src/circuit/protocol/index.proto","build:proto:fetch":"pbjs -t static-module -w commonjs -r libp2p-fetch --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/fetch/proto.js ./src/fetch/proto.proto","build:proto:identify":"pbjs -t static-module -w commonjs -r libp2p-identify --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/identify/message.js ./src/identify/message.proto","build:proto:plaintext":"pbjs -t static-module -w commonjs -r libp2p-plaintext --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/insecure/proto.js ./src/insecure/proto.proto","build:proto:peer":"pbjs -t static-module -w commonjs -r libp2p-peer --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/peer-store/pb/peer.js ./src/peer-store/pb/peer.proto","build:proto:peer-record":"pbjs -t static-module -w commonjs -r libp2p-peer-record --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/record/peer-record/peer-record.js ./src/record/peer-record/peer-record.proto","build:proto:envelope":"pbjs -t static-module -w commonjs -r libp2p-envelope --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/record/envelope/envelope.js ./src/record/envelope/envelope.proto","build:proto-types":"npm run build:proto-types:circuit && npm run build:proto-types:fetch && npm run build:proto-types:identify && npm run build:proto-types:plaintext && npm run build:proto-types:address-book && npm run build:proto-types:proto-book && npm run build:proto-types:peer && npm run build:proto-types:peer-record && npm run build:proto-types:envelope","build:proto-types:circuit":"pbts -o src/circuit/protocol/index.d.ts src/circuit/protocol/index.js","build:proto-types:fetch":"pbts -o src/fetch/proto.d.ts src/fetch/proto.js","build:proto-types:identify":"pbts -o src/identify/message.d.ts src/identify/message.js","build:proto-types:plaintext":"pbts -o src/insecure/proto.d.ts src/insecure/proto.js","build:proto-types:peer":"pbts -o src/peer-store/pb/peer.d.ts src/peer-store/pb/peer.js","build:proto-types:peer-record":"pbts -o src/record/peer-record/peer-record.d.ts src/record/peer-record/peer-record.js","build:proto-types:envelope":"pbts -o src/record/envelope/envelope.d.ts src/record/envelope/envelope.js",test:"aegir test","test:ts":"aegir build --no-bundle && npm run test --prefix test/ts-use","test:node":'aegir test -t node -f "./test/**/*.{node,spec}.js"',"test:browser":"aegir test -t browser","test:examples":"cd examples && npm run test:all","test:interop":"LIBP2P_JS=$PWD npx aegir test -t node -f ./node_modules/libp2p-interop/test/*",prepare:"npm run build",coverage:"nyc --reporter=text --reporter=lcov npm run test:node"},repository:{type:"git",url:"https://github.com/libp2p/js-libp2p.git"},keywords:["libp2p","network","p2p","peer","peer-to-peer","IPFS"],bugs:{url:"https://github.com/libp2p/js-libp2p/issues"},homepage:"https://libp2p.io",license:"MIT",engines:{node:">=15.0.0"},browser:{"nat-api":!1},eslintConfig:{extends:"ipfs",ignorePatterns:["!.aegir.js","test/ts-use","*.d.ts"]},dependencies:{"@vascosantos/moving-average":"^1.1.0","abortable-iterator":"^3.0.0","aggregate-error":"^3.1.0","any-signal":"^3.0.0","bignumber.js":"^9.0.1","class-is":"^1.1.0","datastore-core":"^7.0.0",debug:"^4.3.1","err-code":"^3.0.0","es6-promisify":"^7.0.0",events:"^3.3.0",hashlru:"^2.3.0","interface-datastore":"^6.0.2","it-all":"^1.0.4","it-buffer":"^0.1.2","it-drain":"^1.0.3","it-filter":"^1.0.1","it-first":"^1.0.4","it-foreach":"^0.1.1","it-handshake":"^2.0.0","it-length-prefixed":"^5.0.2","it-map":"^1.0.4","it-merge":"^1.0.0","it-pipe":"^1.1.0","it-sort":"^1.0.1","it-take":"^1.0.0","libp2p-crypto":"^0.21.2","libp2p-interfaces":"^4.0.0","libp2p-utils":"^0.4.0",mafmt:"^10.0.0","merge-options":"^3.0.4",mortice:"^2.0.1",multiaddr:"^10.0.0",multiformats:"^9.0.0","multistream-select":"^3.0.0","mutable-proxy":"^1.0.0","nat-api":"^0.3.1","node-forge":"^1.2.1","p-any":"^3.0.0","p-fifo":"^1.0.0","p-retry":"^4.4.0","p-settle":"^4.1.1","peer-id":"^0.16.0","private-ip":"^2.1.0",protobufjs:"^6.10.2",retimer:"^3.0.0","sanitize-filename":"^1.6.3","set-delayed-interval":"^1.0.0","streaming-iterables":"^6.0.0","timeout-abort-controller":"^3.0.0",uint8arrays:"^3.0.0",varint:"^6.0.0",wherearewe:"^1.0.0",xsalsa20:"^1.1.0"},devDependencies:{"@chainsafe/libp2p-noise":"^5.0.0","@nodeutils/defaults-deep":"^1.1.0","@types/es6-promisify":"^6.0.0","@types/node":"^16.0.1","@types/node-forge":"^1.0.0","@types/varint":"^6.0.0",aegir:"^36.0.0",buffer:"^6.0.3",delay:"^5.0.0","into-stream":"^6.0.0","ipfs-http-client":"^54.0.2","it-concat":"^2.0.0","it-pair":"^1.0.0","it-pushable":"^1.4.0",libp2p:".","libp2p-bootstrap":"^0.14.0","libp2p-delegated-content-routing":"^0.11.0","libp2p-delegated-peer-routing":"^0.11.1","libp2p-interfaces-compliance-tests":"^4.0.8","libp2p-interop":"^0.7.1","libp2p-kad-dht":"^0.28.6","libp2p-mdns":"^0.18.0","libp2p-mplex":"^0.10.4","libp2p-tcp":"^0.17.0","libp2p-webrtc-star":"^0.25.0","libp2p-websockets":"^0.16.0",nock:"^13.0.3","p-defer":"^3.0.0","p-times":"^3.0.0","p-wait-for":"^3.2.0",rimraf:"^3.0.2",sinon:"^12.0.1",util:"^0.12.3"},contributors:["Vasco Santos <vasco.santos@moxy.studio>","David Dias <daviddias.p@gmail.com>","Jacob Heun <jacobheun@gmail.com>","Alex Potsides <alex@achingbrain.net>","Alan Shaw <alan@tableflip.io>","Cayman <caymannava@gmail.com>","Pedro Teixeira <i@pgte.me>","Friedel Ziegelmayer <dignifiedquire@gmail.com>","Maciej Kr\xFCger <mkg20001@gmail.com>","Hugo Dias <mail@hugodias.me>","dirkmc <dirkmdev@gmail.com>","Volker Mische <volker.mische@gmail.com>","Chris Dostert <chrisdostert@users.noreply.github.com>","zeim839 <50573884+zeim839@users.noreply.github.com>","Robert Kiel <robert.kiel@hoprnet.org>","Richard Littauer <richard.littauer@gmail.com>","a1300 <matthias-knopp@gmx.net>","Ryan Bell <ryan@piing.net>","\u1D20\u026A\u1D04\u1D1B\u1D0F\u0280 \u0299\u1D0A\u1D07\u029F\u1D0B\u029C\u1D0F\u029F\u1D0D <victorbjelkholm@gmail.com>","Andrew Nesbitt <andrewnez@gmail.com>","Franck Royer <franck@royer.one>","Thomas Eizinger <thomas@eizinger.io>","V\xEDt Habada <vithabada93@gmail.com>","Giovanni T. Parra <fiatjaf@gmail.com>","acolytec3 <17355484+acolytec3@users.noreply.github.com>","Alan Smithee <ggnore.alan.smithee@gmail.com>","Elven <mon.samuel@qq.com>","Samlior <samlior@foxmail.com>","Didrik Nordstr\xF6m <didrik.nordstrom@gmail.com>","Aditya Bose <13054902+adbose@users.noreply.github.com>","TJKoury <TJKoury@gmail.com>","TheStarBoys <41286328+TheStarBoys@users.noreply.github.com>","Tiago Alves <alvesjtiago@gmail.com>","Tim Daubensch\xFCtz <tim@daubenschuetz.de>","XiaoZhang <zxinmyth@gmail.com>","Yusef Napora <yusef@napora.org>","Zane Starr <zcstarr@gmail.com>","ebinks <elizabethjbinks@gmail.com>","greenSnot <greenSnot@users.noreply.github.com>","isan_rivkin <isanrivkin@gmail.com>","mayerwin <mayerwin@users.noreply.github.com>","mcclure <andi.m.mcclure@gmail.com>","patrickwoodhead <91056047+patrickwoodhead@users.noreply.github.com>","phillmac <phillmac@users.noreply.github.com>","robertkiel <robert.kiel@validitylabs.org>","shresthagrawal <34920931+shresthagrawal@users.noreply.github.com>","swedneck <40505480+swedneck@users.noreply.github.com>","tuyennhv <vutuyen2636@gmail.com>","S\xF6nke Hahn <soenkehahn@gmail.com>","Aleksei <vozhdb@gmail.com>","Bernd Strehl <bernd.strehl@gmail.com>","Chris Bratlien <chrisbratlien@gmail.com>","Cindy Wu <ciindy.wu@gmail.com>","Daijiro Wachi <daijiro.wachi@gmail.com>","Diogo Silva <fsdiogo@gmail.com>","Dmitriy Ryajov <dryajov@gmail.com>","Ethan Lam <elmemphis2000@gmail.com>","Fei Liu <liu.feiwood@gmail.com>","Felipe Martins <felipebrasil93@gmail.com>","Florian-Merle <florian.david.merle@gmail.com>","Francis Gulotta <wizard@roborooter.com>","Guy Sviry <32539816+guysv@users.noreply.github.com>","Henrique Dias <hacdias@gmail.com>","Irakli Gozalishvili <rfobic@gmail.com>","Joel Gustafson <joelg@mit.edu>","John Rees <johnrees@users.noreply.github.com>","Jo\xE3o Santos <joaosantos15@users.noreply.github.com>","Julien Bouquillon <contact@revolunet.com>","Kevin Kwok <antimatter15@gmail.com>","Kevin Lacker <lacker@gmail.com>","Lars Gierth <lgierth@users.noreply.github.com>","Leask Wong <i@leaskh.com>","Marcin Tojek <mtojek@users.noreply.github.com>","Marston Connell <34043723+TheMarstonConnell@users.noreply.github.com>","Michael Burns <5170+mburns@users.noreply.github.com>","Miguel Mota <miguelmota2@gmail.com>","Nuno Nogueira <nunofmn@gmail.com>","Philipp Muens <raute1337@gmx.de>","RasmusErik Voel Jensen <github@solsort.com>","Smite Chow <xiaopengyou@live.com>","Soeren <nikorpoulsen@gmail.com>"]}});var vd=w((vF,cn)=>{"use strict";var f3=md().version;cn.exports.PROTOCOL_VERSION="ipfs/0.1.0";cn.exports.AGENT_VERSION=`js-libp2p/${f3}`;cn.exports.MULTICODEC_IDENTIFY="/ipfs/id/1.0.0";cn.exports.MULTICODEC_IDENTIFY_PUSH="/ipfs/id/push/1.0.0";cn.exports.IDENTIFY_PROTOCOL_VERSION="0.1.0";cn.exports.MULTICODEC_IDENTIFY_PROTOCOL_NAME="id";cn.exports.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME="id/push";cn.exports.MULTICODEC_IDENTIFY_PROTOCOL_VERSION="1.0.0";cn.exports.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION="1.0.0"});var uu=w((bF,xb)=>{"use strict";var Sb=60*1e3;xb.exports={ADVERTISE_BOOT_DELAY:15*Sb,ADVERTISE_TTL:30*Sb,CIRCUIT_PROTO_CODE:290,HOP_METADATA_KEY:"hop_relay",HOP_METADATA_VALUE:"true",RELAY_RENDEZVOUS_NS:"/libp2p/relay"}});var Ab=w(_a=>{(function(){var t,e,r,n,i,s,o,a;a=function(c){var u,l,f,d;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&255<<8)>>>8,d=c&255,[u,l,f,d].join(".")},o=function(c){var u,l,f,d,p,h;for(u=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}h=e(c),p=h[0],l=h[1],c=c.substring(l),u.push(p)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},r=function(c){return c.charCodeAt(0)},n=r("0"),s=r("a"),i=r("A"),e=function(c){var u,l,f,d,p;for(d=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),p=f;f<c.length;){if("0"<=c[f]&&c[f]<=l)d=d*u+(r(c[f])-n)>>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")d=d*u+(10+r(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*u+(10+r(c[f])-i)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===p)throw new Error("empty octet");return[d,f]},t=function(){function c(u,l){var f,d,p,h;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(h=u.split("/",2),u=h[0],l=h[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=o(l)}catch(g){throw f=g,new Error("Invalid mask: "+l)}for(d=p=32;p>=0;d=--p)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(u)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(o(u)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,d;for(d=o(this.first),f=o(this.last),l=0;d<=f;)u(a(d),d,l),l++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),_a.ip2long=o,_a.long2ip=a,_a.Netmask=t}).call(_a)});var Ib=w((Cb,lu)=>{(function(t){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",r={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",o="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${o})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${o})|(?:::)(?:${o})?)${e}\\.${e}\\.${e}\\.${e}(${s})?$`,"i")};function c(p,h){if(p.indexOf("::")!==p.lastIndexOf("::"))return null;let g=0,m=-1,S=(p.match(a.zoneIndex)||[])[0],R,L;for(S&&(S=S.substring(1),p=p.replace(/%.+$/,""));(m=p.indexOf(":",m+1))>=0;)g++;if(p.substr(0,2)==="::"&&g--,p.substr(-2,2)==="::"&&g--,g>h)return null;for(L=h-g,R=":";L--;)R+="0:";return p=p.replace("::",R),p[0]===":"&&(p=p.slice(1)),p[p.length-1]===":"&&(p=p.slice(0,-1)),h=function(){let H=p.split(":"),q=[];for(let k=0;k<H.length;k++)q.push(parseInt(H[k],16));return q}(),{parts:h,zoneId:S}}function u(p,h,g,m){if(p.length!==h.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let S=0,R;for(;m>0;){if(R=g-m,R<0&&(R=0),p[S]>>R!=h[S]>>R)return!1;m-=g,S+=1}return!0}function l(p){if(i.test(p))return parseInt(p,16);if(p[0]==="0"&&!isNaN(parseInt(p[1],10))){if(n.test(p))return parseInt(p,8);throw new Error(`ipaddr: cannot parse ${p} as octal`)}return parseInt(p,10)}function f(p,h){for(;p.length<h;)p=`0${p}`;return p}let d={};d.IPv4=function(){function p(h){if(h.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let g,m;for(g=0;g<h.length;g++)if(m=h[g],!(0<=m&&m<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=h}return p.prototype.SpecialRanges={unspecified:[[new p([0,0,0,0]),8]],broadcast:[[new p([255,255,255,255]),32]],multicast:[[new p([224,0,0,0]),4]],linkLocal:[[new p([169,254,0,0]),16]],loopback:[[new p([127,0,0,0]),8]],carrierGradeNat:[[new p([100,64,0,0]),10]],private:[[new p([10,0,0,0]),8],[new p([172,16,0,0]),12],[new p([192,168,0,0]),16]],reserved:[[new p([192,0,0,0]),24],[new p([192,0,2,0]),24],[new p([192,88,99,0]),24],[new p([198,51,100,0]),24],[new p([203,0,113,0]),24],[new p([240,0,0,0]),4]]},p.prototype.kind=function(){return"ipv4"},p.prototype.match=function(h,g){let m;if(g===void 0&&(m=h,h=m[0],g=m[1]),h.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return u(this.octets,h.octets,8,g)},p.prototype.prefixLengthFromSubnetMask=function(){let h=0,g=!1,m={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},S,R,L;for(S=3;S>=0;S-=1)if(R=this.octets[S],R in m){if(L=m[R],g&&L!==0)return null;L!==8&&(g=!0),h+=L}else return null;return 32-h},p.prototype.range=function(){return d.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){return this.octets.slice(0)},p.prototype.toIPv4MappedAddress=function(){return d.IPv6.parse(`::ffff:${this.toString()}`)},p.prototype.toNormalizedString=function(){return this.toString()},p.prototype.toString=function(){return this.octets.join(".")},p}(),d.IPv4.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),g=h[0].toByteArray(),m=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),S=[],R=0;for(;R<4;)S.push(parseInt(g[R],10)|parseInt(m[R],10)^255),R++;return new this(S)}catch(h){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},d.IPv4.isIPv4=function(p){return this.parser(p)!==null},d.IPv4.isValid=function(p){try{return new this(this.parser(p)),!0}catch(h){return!1}},d.IPv4.isValidFourPartDecimal=function(p){return!!(d.IPv4.isValid(p)&&p.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},d.IPv4.networkAddressFromCIDR=function(p){let h,g,m,S,R;try{for(h=this.parseCIDR(p),m=h[0].toByteArray(),R=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),S=[],g=0;g<4;)S.push(parseInt(m[g],10)&parseInt(R[g],10)),g++;return new this(S)}catch(L){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},d.IPv4.parse=function(p){let h=this.parser(p);if(h===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(h)},d.IPv4.parseCIDR=function(p){let h;if(h=p.match(/^(.+)\/(\d+)$/)){let g=parseInt(h[2]);if(g>=0&&g<=32){let m=[this.parse(h[1]),g];return Object.defineProperty(m,"toString",{value:function(){return this.join("/")}}),m}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},d.IPv4.parser=function(p){let h,g,m;if(h=p.match(r.fourOctet))return function(){let S=h.slice(1,6),R=[];for(let L=0;L<S.length;L++)g=S[L],R.push(l(g));return R}();if(h=p.match(r.longValue)){if(m=l(h[1]),m>4294967295||m<0)throw new Error("ipaddr: address outside defined range");return function(){let S=[],R;for(R=0;R<=24;R+=8)S.push(m>>R&255);return S}().reverse()}else return(h=p.match(r.twoOctet))?function(){let S=h.slice(1,4),R=[];if(m=l(S[1]),m>16777215||m<0)throw new Error("ipaddr: address outside defined range");return R.push(l(S[0])),R.push(m>>16&255),R.push(m>>8&255),R.push(m&255),R}():(h=p.match(r.threeOctet))?function(){let S=h.slice(1,5),R=[];if(m=l(S[2]),m>65535||m<0)throw new Error("ipaddr: address outside defined range");return R.push(l(S[0])),R.push(l(S[1])),R.push(m>>8&255),R.push(m&255),R}():null},d.IPv4.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>32)throw new Error("ipaddr: invalid IPv4 prefix length");let h=[0,0,0,0],g=0,m=Math.floor(p/8);for(;g<m;)h[g]=255,g++;return m<4&&(h[m]=Math.pow(2,p%8)-1<<8-p%8),new this(h)},d.IPv6=function(){function p(h,g){let m,S;if(h.length===16)for(this.parts=[],m=0;m<=14;m+=2)this.parts.push(h[m]<<8|h[m+1]);else if(h.length===8)this.parts=h;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(m=0;m<this.parts.length;m++)if(S=this.parts[m],!(0<=S&&S<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");g&&(this.zoneId=g)}return p.prototype.SpecialRanges={unspecified:[new p([0,0,0,0,0,0,0,0]),128],linkLocal:[new p([65152,0,0,0,0,0,0,0]),10],multicast:[new p([65280,0,0,0,0,0,0,0]),8],loopback:[new p([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new p([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new p([0,0,0,0,0,65535,0,0]),96],rfc6145:[new p([0,0,0,0,65535,0,0,0]),96],rfc6052:[new p([100,65435,0,0,0,0,0,0]),96],"6to4":[new p([8194,0,0,0,0,0,0,0]),16],teredo:[new p([8193,0,0,0,0,0,0,0]),32],reserved:[[new p([8193,3512,0,0,0,0,0,0]),32]]},p.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},p.prototype.kind=function(){return"ipv6"},p.prototype.match=function(h,g){let m;if(g===void 0&&(m=h,h=m[0],g=m[1]),h.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return u(this.parts,h.parts,16,g)},p.prototype.prefixLengthFromSubnetMask=function(){let h=0,g=!1,m={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},S,R;for(let L=7;L>=0;L-=1)if(S=this.parts[L],S in m){if(R=m[S],g&&R!==0)return null;R!==16&&(g=!0),h+=R}else return null;return 128-h},p.prototype.range=function(){return d.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){let h,g=[],m=this.parts;for(let S=0;S<m.length;S++)h=m[S],g.push(h>>8),g.push(h&255);return g},p.prototype.toFixedLengthString=function(){let h=function(){let m=[];for(let S=0;S<this.parts.length;S++)m.push(f(this.parts[S].toString(16),4));return m}.call(this).join(":"),g="";return this.zoneId&&(g=`%${this.zoneId}`),h+g},p.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let h=this.parts.slice(-2),g=h[0],m=h[1];return new d.IPv4([g>>8,g&255,m>>8,m&255])},p.prototype.toNormalizedString=function(){let h=function(){let m=[];for(let S=0;S<this.parts.length;S++)m.push(this.parts[S].toString(16));return m}.call(this).join(":"),g="";return this.zoneId&&(g=`%${this.zoneId}`),h+g},p.prototype.toRFC5952String=function(){let h=/((^|:)(0(:|$)){2,})/g,g=this.toNormalizedString(),m=0,S=-1,R;for(;R=h.exec(g);)R[0].length>S&&(m=R.index,S=R[0].length);return S<0?g:`${g.substring(0,m)}::${g.substring(m+S)}`},p.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},p}(),d.IPv6.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),g=h[0].toByteArray(),m=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),S=[],R=0;for(;R<16;)S.push(parseInt(g[R],10)|parseInt(m[R],10)^255),R++;return new this(S)}catch(h){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${h})`)}},d.IPv6.isIPv6=function(p){return this.parser(p)!==null},d.IPv6.isValid=function(p){if(typeof p=="string"&&p.indexOf(":")===-1)return!1;try{let h=this.parser(p);return new this(h.parts,h.zoneId),!0}catch(h){return!1}},d.IPv6.networkAddressFromCIDR=function(p){let h,g,m,S,R;try{for(h=this.parseCIDR(p),m=h[0].toByteArray(),R=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),S=[],g=0;g<16;)S.push(parseInt(m[g],10)&parseInt(R[g],10)),g++;return new this(S)}catch(L){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${L})`)}},d.IPv6.parse=function(p){let h=this.parser(p);if(h.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(h.parts,h.zoneId)},d.IPv6.parseCIDR=function(p){let h,g,m;if((g=p.match(/^(.+)\/(\d+)$/))&&(h=parseInt(g[2]),h>=0&&h<=128))return m=[this.parse(g[1]),h],Object.defineProperty(m,"toString",{value:function(){return this.join("/")}}),m;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},d.IPv6.parser=function(p){let h,g,m,S,R,L;if(m=p.match(a.deprecatedTransitional))return this.parser(`::ffff:${m[1]}`);if(a.native.test(p))return c(p,8);if((m=p.match(a.transitional))&&(L=m[6]||"",h=c(m[1].slice(0,-1)+L,6),h.parts)){for(R=[parseInt(m[2]),parseInt(m[3]),parseInt(m[4]),parseInt(m[5])],g=0;g<R.length;g++)if(S=R[g],!(0<=S&&S<=255))return null;return h.parts.push(R[0]<<8|R[1]),h.parts.push(R[2]<<8|R[3]),{parts:h.parts,zoneId:h.zoneId}}return null},d.IPv6.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>128)throw new Error("ipaddr: invalid IPv6 prefix length");let h=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],g=0,m=Math.floor(p/8);for(;g<m;)h[g]=255,g++;return m<16&&(h[m]=Math.pow(2,p%8)-1<<8-p%8),new this(h)},d.fromByteArray=function(p){let h=p.length;if(h===4)return new d.IPv4(p);if(h===16)return new d.IPv6(p);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},d.isValid=function(p){return d.IPv6.isValid(p)||d.IPv4.isValid(p)},d.parse=function(p){if(d.IPv6.isValid(p))return d.IPv6.parse(p);if(d.IPv4.isValid(p))return d.IPv4.parse(p);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},d.parseCIDR=function(p){try{return d.IPv6.parseCIDR(p)}catch(h){try{return d.IPv4.parseCIDR(p)}catch(g){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},d.process=function(p){let h=this.parse(p);return h.kind()==="ipv6"&&h.isIPv4MappedAddress()?h.toIPv4Address():h},d.subnetMatch=function(p,h,g){let m,S,R,L;g==null&&(g="unicast");for(S in h)if(Object.prototype.hasOwnProperty.call(h,S)){for(R=h[S],R[0]&&!(R[0]instanceof Array)&&(R=[R]),m=0;m<R.length;m++)if(L=R[m],p.kind()===L[0].kind()&&p.match.apply(p,L))return S}return g},typeof lu!="undefined"&&lu.exports?lu.exports=d:t.ipaddr=d})(Cb)});var Pb=w(Sa=>{"use strict";var Tb=Sa&&Sa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Sa,"__esModule",{value:!0});var d3=Ab(),h3=Tb(kf()),p3=Tb(Uf()),Rb=Ib(),y3=["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"],g3=y3.map(t=>new d3.Netmask(t));function m3(t){for(let e of g3)if(e.contains(t))return!0;return!1}function Bb(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}Sa.default=t=>{if(Rb.isValid(t)){let e=Rb.parse(t);if(e.kind()==="ipv4")return m3(e.toNormalizedString());if(e.kind()==="ipv6")return Bb(t)}else if(p3.default(t)&&h3.default.v6().test(t))return Bb(t)}});var bd=w((_F,Nb)=>{"use strict";Nb.exports=Pb().default});var Db=w((SF,Ob)=>{"use strict";var v3=bd();function b3(t){let{address:e}=t.nodeAddress();return v3(e)}Ob.exports=b3});var Ed=w((xF,kb)=>{"use strict";var Lb=Db();function E3(t,e){let r=Lb(t.multiaddr),n=Lb(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function w3(t){return[...t].sort(E3)}kb.exports.publicAddressesFirst=w3});var Ub=w((AF,wd)=>{"use strict";var qb=async t=>{try{let e=await t;return{isFulfilled:!0,isRejected:!1,value:e}}catch(e){return{isFulfilled:!1,isRejected:!0,reason:e}}};wd.exports=qb;wd.exports.default=qb});var Fb=w((CF,_d)=>{"use strict";var Mb=(t,...e)=>new Promise(r=>{r(t(...e))});_d.exports=Mb;_d.exports.default=Mb});var Vb=w((IF,Sd)=>{"use strict";var _3=Fb(),Kb=t=>{if(!((Number.isInteger(t)||t===1/0)&&t>0))return Promise.reject(new TypeError("Expected `concurrency` to be a number from 1 and up"));let e=[],r=0,n=()=>{r--,e.length>0&&e.shift()()},i=(a,c,...u)=>{r++;let l=_3(a,...u);c(l),l.then(n,n)},s=(a,c,...u)=>{r<t?i(a,c,...u):e.push(i.bind(null,a,c,...u))},o=(a,...c)=>new Promise(u=>s(a,u,...c));return Object.defineProperties(o,{activeCount:{get:()=>r},pendingCount:{get:()=>e.length},clearQueue:{value:()=>{e.length=0}}}),o};Sd.exports=Kb;Sd.exports.default=Kb});var $b=w((TF,jb)=>{"use strict";var xd=Ub(),S3=Vb();jb.exports=async(t,e={})=>{let{concurrency:r=1/0}=e,n=S3(r);return Promise.all(t.map(i=>i&&typeof i.then=="function"?xd(i):xd(typeof i=="function"?n(()=>i()):Promise.resolve(i))))}});var Gb=w((RF,zb)=>{"use strict";var Gs=gn(),Hb=Gs.Reader,x3=Gs.Writer,Je=Gs.util,xa=Gs.roots["libp2p-envelope"]||(Gs.roots["libp2p-envelope"]={});xa.Envelope=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.publicKey=Je.newBuffer([]),t.prototype.payloadType=Je.newBuffer([]),t.prototype.payload=Je.newBuffer([]),t.prototype.signature=Je.newBuffer([]),t.encode=function(r,n){return n||(n=x3.create()),r.publicKey!=null&&Object.hasOwnProperty.call(r,"publicKey")&&n.uint32(10).bytes(r.publicKey),r.payloadType!=null&&Object.hasOwnProperty.call(r,"payloadType")&&n.uint32(18).bytes(r.payloadType),r.payload!=null&&Object.hasOwnProperty.call(r,"payload")&&n.uint32(26).bytes(r.payload),r.signature!=null&&Object.hasOwnProperty.call(r,"signature")&&n.uint32(42).bytes(r.signature),n},t.decode=function(r,n){r instanceof Hb||(r=Hb.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new xa.Envelope;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.publicKey=r.bytes();break;case 2:s.payloadType=r.bytes();break;case 3:s.payload=r.bytes();break;case 5:s.signature=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof xa.Envelope)return r;var n=new xa.Envelope;return r.publicKey!=null&&(typeof r.publicKey=="string"?Je.base64.decode(r.publicKey,n.publicKey=Je.newBuffer(Je.base64.length(r.publicKey)),0):r.publicKey.length&&(n.publicKey=r.publicKey)),r.payloadType!=null&&(typeof r.payloadType=="string"?Je.base64.decode(r.payloadType,n.payloadType=Je.newBuffer(Je.base64.length(r.payloadType)),0):r.payloadType.length&&(n.payloadType=r.payloadType)),r.payload!=null&&(typeof r.payload=="string"?Je.base64.decode(r.payload,n.payload=Je.newBuffer(Je.base64.length(r.payload)),0):r.payload.length&&(n.payload=r.payload)),r.signature!=null&&(typeof r.signature=="string"?Je.base64.decode(r.signature,n.signature=Je.newBuffer(Je.base64.length(r.signature)),0):r.signature.length&&(n.signature=r.signature)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(n.bytes===String?i.publicKey="":(i.publicKey=[],n.bytes!==Array&&(i.publicKey=Je.newBuffer(i.publicKey))),n.bytes===String?i.payloadType="":(i.payloadType=[],n.bytes!==Array&&(i.payloadType=Je.newBuffer(i.payloadType))),n.bytes===String?i.payload="":(i.payload=[],n.bytes!==Array&&(i.payload=Je.newBuffer(i.payload))),n.bytes===String?i.signature="":(i.signature=[],n.bytes!==Array&&(i.signature=Je.newBuffer(i.signature)))),r.publicKey!=null&&r.hasOwnProperty("publicKey")&&(i.publicKey=n.bytes===String?Je.base64.encode(r.publicKey,0,r.publicKey.length):n.bytes===Array?Array.prototype.slice.call(r.publicKey):r.publicKey),r.payloadType!=null&&r.hasOwnProperty("payloadType")&&(i.payloadType=n.bytes===String?Je.base64.encode(r.payloadType,0,r.payloadType.length):n.bytes===Array?Array.prototype.slice.call(r.payloadType):r.payloadType),r.payload!=null&&r.hasOwnProperty("payload")&&(i.payload=n.bytes===String?Je.base64.encode(r.payload,0,r.payload.length):n.bytes===Array?Array.prototype.slice.call(r.payload):r.payload),r.signature!=null&&r.hasOwnProperty("signature")&&(i.signature=n.bytes===String?Je.base64.encode(r.signature,0,r.signature.length):n.bytes===Array?Array.prototype.slice.call(r.signature):r.signature),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Gs.util.toJSONOptions)},t}();zb.exports=xa});var du=w((BF,Qb)=>{"use strict";var A3=de(),{concat:C3}=(Yn(),Wn),{fromString:I3}=(It(),Nt),T3=jc(),R3=Rt(),Ad=Ui(),{equals:fu}=(mr(),gr),{codes:B3}=je(),{Envelope:Wb}=Gb(),ii=class{constructor({peerId:e,payloadType:r,payload:n,signature:i}){this.peerId=e,this.payloadType=r,this.payload=n,this.signature=i,this._marshal=void 0}marshal(){if(this._marshal)return this._marshal;let e=T3.marshalPublicKey(this.peerId.pubKey);return this._marshal=Wb.encode({publicKey:e,payloadType:this.payloadType,payload:this.payload,signature:this.signature}).finish(),this._marshal}equals(e){return fu(this.peerId.pubKey.bytes,e.peerId.pubKey.bytes)&&fu(this.payloadType,e.payloadType)&&fu(this.payload,e.payload)&&fu(this.signature,e.signature)}validate(e){let r=Yb(e,this.payloadType,this.payload);return this.peerId.pubKey.verify(r,this.signature)}},Yb=(t,e,r)=>{let n=I3(t),i=Ad.encode(n.byteLength),s=Ad.encode(e.length),o=Ad.encode(r.length);return C3([new Uint8Array(i),n,new Uint8Array(s),e,new Uint8Array(o),r])};ii.createFromProtobuf=async t=>{let e=Wb.decode(t),r=await R3.createFromPubKey(e.publicKey);return new ii({peerId:r,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};ii.seal=async(t,e)=>{let r=t.domain,n=t.codec,i=t.marshal(),s=Yb(r,n,i),o=await e.privKey.sign(s);return new ii({peerId:e,payloadType:n,payload:i,signature:o})};ii.openAndCertify=async(t,e)=>{let r=await ii.createFromProtobuf(t);if(!await r.validate(e))throw A3(new Error("envelope signature is not valid for the given domain"),B3.ERR_SIGNATURE_NOT_VALID);return r};Qb.exports=ii});var Zb=w((PF,Xb)=>{"use strict";function P3(t,e){return t.length===e.length&&e.sort()&&t.sort().every((r,n)=>e[n].equals(r))}Xb.exports=P3});var tE=w((NF,eE)=>{"use strict";var $i=gn(),hu=$i.Reader,Jb=$i.Writer,lt=$i.util,xr=$i.roots["libp2p-peer-record"]||($i.roots["libp2p-peer-record"]={});xr.PeerRecord=function(){function t(e){if(this.addresses=[],e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.peerId=lt.newBuffer([]),t.prototype.seq=lt.Long?lt.Long.fromBits(0,0,!0):0,t.prototype.addresses=lt.emptyArray,t.encode=function(r,n){if(n||(n=Jb.create()),r.peerId!=null&&Object.hasOwnProperty.call(r,"peerId")&&n.uint32(10).bytes(r.peerId),r.seq!=null&&Object.hasOwnProperty.call(r,"seq")&&n.uint32(16).uint64(r.seq),r.addresses!=null&&r.addresses.length)for(var i=0;i<r.addresses.length;++i)xr.PeerRecord.AddressInfo.encode(r.addresses[i],n.uint32(26).fork()).ldelim();return n},t.decode=function(r,n){r instanceof hu||(r=hu.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new xr.PeerRecord;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.peerId=r.bytes();break;case 2:s.seq=r.uint64();break;case 3:s.addresses&&s.addresses.length||(s.addresses=[]),s.addresses.push(xr.PeerRecord.AddressInfo.decode(r,r.uint32()));break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof xr.PeerRecord)return r;var n=new xr.PeerRecord;if(r.peerId!=null&&(typeof r.peerId=="string"?lt.base64.decode(r.peerId,n.peerId=lt.newBuffer(lt.base64.length(r.peerId)),0):r.peerId.length&&(n.peerId=r.peerId)),r.seq!=null&&(lt.Long?(n.seq=lt.Long.fromValue(r.seq)).unsigned=!0:typeof r.seq=="string"?n.seq=parseInt(r.seq,10):typeof r.seq=="number"?n.seq=r.seq:typeof r.seq=="object"&&(n.seq=new lt.LongBits(r.seq.low>>>0,r.seq.high>>>0).toNumber(!0))),r.addresses){if(!Array.isArray(r.addresses))throw TypeError(".PeerRecord.addresses: array expected");n.addresses=[];for(var i=0;i<r.addresses.length;++i){if(typeof r.addresses[i]!="object")throw TypeError(".PeerRecord.addresses: object expected");n.addresses[i]=xr.PeerRecord.AddressInfo.fromObject(r.addresses[i])}}return n},t.toObject=function(r,n){n||(n={});var i={};if((n.arrays||n.defaults)&&(i.addresses=[]),n.defaults)if(n.bytes===String?i.peerId="":(i.peerId=[],n.bytes!==Array&&(i.peerId=lt.newBuffer(i.peerId))),lt.Long){var s=new lt.Long(0,0,!0);i.seq=n.longs===String?s.toString():n.longs===Number?s.toNumber():s}else i.seq=n.longs===String?"0":0;if(r.peerId!=null&&r.hasOwnProperty("peerId")&&(i.peerId=n.bytes===String?lt.base64.encode(r.peerId,0,r.peerId.length):n.bytes===Array?Array.prototype.slice.call(r.peerId):r.peerId),r.seq!=null&&r.hasOwnProperty("seq")&&(typeof r.seq=="number"?i.seq=n.longs===String?String(r.seq):r.seq:i.seq=n.longs===String?lt.Long.prototype.toString.call(r.seq):n.longs===Number?new lt.LongBits(r.seq.low>>>0,r.seq.high>>>0).toNumber(!0):r.seq),r.addresses&&r.addresses.length){i.addresses=[];for(var o=0;o<r.addresses.length;++o)i.addresses[o]=xr.PeerRecord.AddressInfo.toObject(r.addresses[o],n)}return i},t.prototype.toJSON=function(){return this.constructor.toObject(this,$i.util.toJSONOptions)},t.AddressInfo=function(){function e(r){if(r)for(var n=Object.keys(r),i=0;i<n.length;++i)r[n[i]]!=null&&(this[n[i]]=r[n[i]])}return e.prototype.multiaddr=lt.newBuffer([]),e.encode=function(n,i){return i||(i=Jb.create()),n.multiaddr!=null&&Object.hasOwnProperty.call(n,"multiaddr")&&i.uint32(10).bytes(n.multiaddr),i},e.decode=function(n,i){n instanceof hu||(n=hu.create(n));for(var s=i===void 0?n.len:n.pos+i,o=new xr.PeerRecord.AddressInfo;n.pos<s;){var a=n.uint32();switch(a>>>3){case 1:o.multiaddr=n.bytes();break;default:n.skipType(a&7);break}}return o},e.fromObject=function(n){if(n instanceof xr.PeerRecord.AddressInfo)return n;var i=new xr.PeerRecord.AddressInfo;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?lt.base64.decode(n.multiaddr,i.multiaddr=lt.newBuffer(lt.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),i},e.toObject=function(n,i){i||(i={});var s={};return i.defaults&&(i.bytes===String?s.multiaddr="":(s.multiaddr=[],i.bytes!==Array&&(s.multiaddr=lt.newBuffer(s.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(s.multiaddr=i.bytes===String?lt.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,$i.util.toJSONOptions)},e}(),t}();eE.exports=xr});var nE=w((OF,rE)=>{"use strict";var N3="libp2p-peer-record",O3=Uint8Array.from([3,1]);rE.exports={ENVELOPE_DOMAIN_PEER_RECORD:N3,ENVELOPE_PAYLOAD_TYPE_PEER_RECORD:O3}});var pu=w((DF,oE)=>{"use strict";var{Multiaddr:D3}=qt(),L3=Rt(),k3=Zb(),{PeerRecord:iE}=tE(),{ENVELOPE_DOMAIN_PEER_RECORD:sE,ENVELOPE_PAYLOAD_TYPE_PEER_RECORD:q3}=nE(),Hi=class{constructor({peerId:e,multiaddrs:r=[],seqNumber:n=Date.now()}){this.domain=sE,this.codec=q3,this.peerId=e,this.multiaddrs=r,this.seqNumber=n,this._marshal=void 0}marshal(){return this._marshal?this._marshal:(this._marshal=iE.encode({peerId:this.peerId.toBytes(),seq:this.seqNumber,addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))}).finish(),this._marshal)}equals(e){return!(!(e instanceof Hi)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!k3(this.multiaddrs,e.multiaddrs))}};Hi.createFromProtobuf=t=>{let e=iE.decode(t),r=L3.createFromBytes(e.peerId),n=(e.addresses||[]).map(s=>new D3(s.multiaddr)),i=Number(e.seq);return new Hi({peerId:r,multiaddrs:n,seqNumber:i})};Hi.DOMAIN=sE;oE.exports=Hi});var Cd=w((LF,aE)=>{"use strict";var U3=du(),M3=pu();async function F3(t){let e=new M3({peerId:t.peerId,multiaddrs:t.multiaddrs}),r=await U3.seal(e,t.peerId);await t.peerStore.addressBook.consumePeerRecord(r)}aE.exports.updateSelfPeerRecord=F3});var Td=w((kF,lE)=>{"use strict";var cE=Te(),zi=Object.assign(cE("libp2p:transports"),{error:cE("libp2p:transports:err")}),K3=$b(),{codes:Ws}=je(),Aa=de(),{updateSelfPeerRecord:uE}=Cd(),Id=class{constructor({libp2p:e,upgrader:r,faultTolerance:n=yu.FATAL_ALL}){this.libp2p=e,this.upgrader=r,this._transports=new Map,this._listeners=new Map,this._listenerOptions=new Map,this.faultTolerance=n}add(e,r,n={}){if(zi("adding %s",e),!e)throw Aa(new Error(`Transport must have a valid key, was given '${e}'`),Ws.ERR_INVALID_KEY);if(this._transports.has(e))throw Aa(new Error("There is already a transport with this key"),Ws.ERR_DUPLICATE_TRANSPORT);let i=new r({...n,libp2p:this.libp2p,upgrader:this.upgrader});this._transports.set(e,i),this._listenerOptions.set(e,n.listenerOptions||{}),this._listeners.has(e)||this._listeners.set(e,[])}async close(){let e=[];for(let[r,n]of this._listeners)for(zi("closing listeners for %s",r);n.length;){let i=n.pop();i.removeAllListeners("listening"),i.removeAllListeners("close"),e.push(i.close())}await Promise.all(e),zi("all listeners closed");for(let r of this._listeners.keys())this._listeners.set(r,[])}async dial(e,r){let n=this.transportForMultiaddr(e);if(!n)throw Aa(new Error(`No transport available for address ${String(e)}`),Ws.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,r)}catch(i){throw i.code||(i.code=Ws.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this._listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return this._transports.values()}transportForMultiaddr(e){for(let r of this._transports.values())if(r.filter([e]).length)return r;return null}async listen(e){if(!e||e.length===0){zi("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this._transports.entries()){let s=i.filter(e),o=[];for(let u of s){zi("creating listener for %s on %s",n,u);let l=i.createListener(this._listenerOptions.get(n));this._listeners.get(n).push(l),l.on("listening",()=>uE(this.libp2p)),l.on("close",()=>uE(this.libp2p)),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if(!(await K3(o)).find(u=>u.isFulfilled===!0)&&this.faultTolerance!==yu.NO_FATAL)throw Aa(new Error(`Transport (${n}) could not listen on any available address`),Ws.ERR_NO_VALID_ADDRESSES)}if(r.length===this._transports.size){let n=`no valid addresses were provided for transports [${r}]`;if(this.faultTolerance===yu.FATAL_ALL)throw Aa(new Error(n),Ws.ERR_NO_VALID_ADDRESSES);zi(`libp2p in dial mode only: ${n}`)}}async remove(e){if(zi("removing %s",e),this._listeners.has(e))for(let r of this._listeners.get(e))r.removeAllListeners("listening"),r.removeAllListeners("close"),await r.close();this._transports.delete(e),this._listeners.delete(e)}async removeAll(){let e=[];for(let r of this._transports.keys())e.push(this.remove(r));await Promise.all(e)}},yu={FATAL_ALL:0,NO_FATAL:1};Id.FaultTolerance=yu;lE.exports=Id});var hE=w((qF,dE)=>{"use strict";var V3=Hs(),{dnsaddrResolver:j3}=wb(),Rd=cu(),{AGENT_VERSION:$3}=vd(),fE=uu(),{publicAddressesFirst:H3}=Ed(),{FaultTolerance:z3}=Td(),G3={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{minConnections:25},connectionGater:{},transportManager:{faultTolerance:z3.FATAL_ALL},dialer:{maxParallelDials:Rd.MAX_PARALLEL_DIALS,maxDialsPerPeer:Rd.MAX_PER_PEER_DIALS,dialTimeout:Rd.DIAL_TIMEOUT,resolvers:{dnsaddr:j3},addressSorter:H3},host:{agentVersion:$3},metrics:{enabled:!1},peerStore:{persistence:!1,threshold:5},peerRouting:{refreshManager:{enabled:!0,interval:6e5,bootDelay:1e4}},config:{protocolPrefix:"ipfs",dht:{enabled:!1,kBucketSize:20},nat:{enabled:!0,ttl:7200,keepAlive:!0,gateway:null,externalIp:null,pmp:{enabled:!1}},peerDiscovery:{autoDial:!0},pubsub:{enabled:!0},relay:{enabled:!0,advertise:{bootDelay:fE.ADVERTISE_BOOT_DELAY,enabled:!1,ttl:fE.ADVERTISE_TTL},hop:{enabled:!1,active:!1},autoRelay:{enabled:!1,maxListeners:2}},transport:{}}};dE.exports.validate=t=>{let e=V3(G3,t);if(e.modules.transport.length<1)throw new Error("'options.modules.transport' must contain at least 1 transport");return e}});var gE=w((UF,yE)=>{"use strict";var{EventEmitter:W3}=Qt(),{Multiaddr:Ca}=qt(),Y3=Rt(),pE=class extends W3{constructor(e,{listen:r=[],announce:n=[]}={}){super();this.peerId=e,this.listen=new Set(r.map(i=>i.toString())),this.announce=new Set(n.map(i=>i.toString())),this.observed=new Set}getListenAddrs(){return Array.from(this.listen).map(e=>new Ca(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>new Ca(e))}getObservedAddrs(){return Array.from(this.observed).map(e=>new Ca(e))}addObservedAddr(e){let r=new Ca(e),n=r.getPeerId();n&&Y3.createFromB58String(n).equals(this.peerId)&&(r=r.decapsulate(new Ca(`/p2p/${this.peerId}`)));let i=r.toString();this.observed.has(i)||(this.observed.add(i),this.emit("change:addresses"))}};yE.exports=pE});var bE=w((MF,vE)=>{"use strict";var{EventEmitter:Q3}=Qt(),Bd=Te()("latency-monitor:VisibilityChangeEmitter"),mE=class extends Q3{constructor(){super();if(typeof document=="undefined"){Bd('This is not a browser, no "document" found. Stopping.');return}this._initializeVisibilityVarNames(),this._addVisibilityChangeListener()}_initializeVisibilityVarNames(){let e,r;typeof document.hidden!="undefined"?(e="hidden",r="visibilitychange"):typeof document.mozHidden!="undefined"?(e="mozHidden",r="mozvisibilitychange"):typeof document.msHidden!="undefined"?(e="msHidden",r="msvisibilitychange"):typeof document.webkitHidden!="undefined"&&(e="webkitHidden",r="webkitvisibilitychange"),this._hidden=e,this._visibilityChange=r}_addVisibilityChangeListener(){typeof document.addEventListener=="undefined"||typeof document[this._hidden]=="undefined"?Bd("Checking page visibility requires a browser that supports the Page Visibility API."):document.addEventListener(this._visibilityChange,this._handleVisibilityChange.bind(this),!1)}isVisible(){if(!(this._hidden===void 0||document[this._hidden]===void 0))return!document[this._hidden]}_handleVisibilityChange(){let e=!document[this._hidden];Bd(e?"Page Visible":"Page Hidden"),this.emit("visibilityChange",e)}};vE.exports=mE});var _E=w((FF,wE)=>{"use strict";var{EventEmitter:X3}=Qt(),Z3=bE(),In=Te()("latency-monitor:LatencyMonitor"),EE=class extends X3{constructor({latencyCheckIntervalMs:e,dataEmitIntervalMs:r,asyncTestFn:n,latencyRandomPercentage:i}={}){super();let s=this;s.latencyCheckIntervalMs=e||500,s.latencyRandomPercentage=i||10,s._latecyCheckMultiply=2*(s.latencyRandomPercentage/100)*s.latencyCheckIntervalMs,s._latecyCheckSubtract=s._latecyCheckMultiply/2,s.dataEmitIntervalMs=r===null||r===0?void 0:r||5*1e3,In("latencyCheckIntervalMs: %s dataEmitIntervalMs: %s",s.latencyCheckIntervalMs,s.dataEmitIntervalMs),s.dataEmitIntervalMs?In("Expecting ~%s events per summary",s.latencyCheckIntervalMs/s.dataEmitIntervalMs):In("Not emitting summaries"),s.asyncTestFn=n}start(){globalThis.process&&globalThis.process.hrtime?(In("Using process.hrtime for timing"),this.now=globalThis.process.hrtime,this.getDeltaMS=e=>{let r=this.now(e);return r[0]*1e3+r[1]/1e6}):typeof window!="undefined"&&window.performance&&window.performance.now?(In("Using performance.now for timing"),this.now=window.performance.now.bind(window.performance),this.getDeltaMS=e=>Math.round(this.now()-e)):(In("Using Date.now for timing"),this.now=Date.now,this.getDeltaMS=e=>this.now()-e),this._latencyData=this._initLatencyData(),J3()&&(this._visibilityChangeEmitter=new Z3,this._visibilityChangeEmitter.on("visibilityChange",e=>{e?this._startTimers():(this._emitSummary(),this._stopTimers())})),(!this._visibilityChangeEmitter||this._visibilityChangeEmitter.isVisible())&&this._startTimers()}stop(){this._stopTimers()}_startTimers(){this._checkLatencyID||(this._checkLatency(),this.dataEmitIntervalMs&&(this._emitIntervalID=setInterval(()=>this._emitSummary(),this.dataEmitIntervalMs),typeof this._emitIntervalID.unref=="function"&&this._emitIntervalID.unref()))}_stopTimers(){this._checkLatencyID&&(clearTimeout(this._checkLatencyID),this._checkLatencyID=void 0),this._emitIntervalID&&(clearInterval(this._emitIntervalID),this._emitIntervalID=void 0)}_emitSummary(){let e=this.getSummary();e.events>0&&this.emit("data",e)}getSummary(){let e={events:this._latencyData.events,minMs:this._latencyData.minMs,maxMs:this._latencyData.maxMs,avgMs:this._latencyData.events?this._latencyData.totalMs/this._latencyData.events:Number.POSITIVE_INFINITY,lengthMs:this.getDeltaMS(this._latencyData.startTime)};return this._latencyData=this._initLatencyData(),In("Summary: %O",e),e}_checkLatency(){let e=this,r=Math.random()*e._latecyCheckMultiply-e._latecyCheckSubtract,n={deltaOffset:Math.ceil(e.latencyCheckIntervalMs+r),startTime:e.now()},i=()=>{if(!this._checkLatencyID)return;let s=e.getDeltaMS(n.startTime)-n.deltaOffset;e._checkLatency(),e._latencyData.events++,e._latencyData.minMs=Math.min(e._latencyData.minMs,s),e._latencyData.maxMs=Math.max(e._latencyData.maxMs,s),e._latencyData.totalMs+=s,In("MS: %s Data: %O",s,e._latencyData)};In("localData: %O",n),this._checkLatencyID=setTimeout(()=>{e.asyncTestFn?(n.deltaOffset=0,n.startTime=e.now(),e.asyncTestFn(i)):(n.deltaOffset-=1,i())},n.deltaOffset),typeof this._checkLatencyID.unref=="function"&&this._checkLatencyID.unref()}_initLatencyData(){return{startTime:this.now(),minMs:Number.POSITIVE_INFINITY,maxMs:Number.NEGATIVE_INFINITY,events:0,totalMs:0}}};function J3(){return typeof window!="undefined"}wE.exports=EE});var Pd=w((KF,xE)=>{"use strict";var SE=class extends Map{constructor(e){super();let{system:r,component:n,metric:i,metrics:s}=e;this._system=r,this._component=n,this._metric=i,this._metrics=s,this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size})}set(e,r){return super.set(e,r),this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size}),this}delete(e){let r=super.delete(e);return this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size}),r}clear(){super.clear(),this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size})}};xE.exports=({system:t="libp2p",component:e,metric:r,metrics:n})=>{let i;return n?i=new SE({system:t,component:e,metric:r,metrics:n}):i=new Map,i}});var OE=w((VF,NE)=>{"use strict";var AE=Te(),Mr=Object.assign(AE("libp2p:connection-manager"),{error:AE("libp2p:connection-manager:err")}),CE=de(),eO=Hs(),tO=_E(),IE=va(),{EventEmitter:rO}=Qt(),TE=Pd(),nO=Rt(),{codes:{ERR_INVALID_PARAMETERS:RE}}=je(),iO={maxConnections:1/0,minConnections:0,maxData:1/0,maxSentData:1/0,maxReceivedData:1/0,maxEventLoopDelay:1/0,pollInterval:2e3,autoDialInterval:1e4,movingAverageInterval:6e4,defaultPeerValue:1},BE="connection-manager",sO="peer-connections",oO="peer-values",PE=class extends rO{constructor(e,r={}){super();if(this._libp2p=e,this._peerId=e.peerId.toB58String(),this._options=eO.call({ignoreUndefined:!0},iO,r),this._options.maxConnections<this._options.minConnections)throw CE(new Error("Connection Manager maxConnections must be greater than minConnections"),RE);Mr("options: %j",this._options),this._peerValues=TE({component:BE,metric:oO,metrics:this._libp2p.metrics}),this.connections=TE({component:BE,metric:sO,metrics:this._libp2p.metrics}),this._started=!1,this._timer=null,this._checkMetrics=this._checkMetrics.bind(this),this._latencyMonitor=new tO({latencyCheckIntervalMs:this._options.pollInterval,dataEmitIntervalMs:this._options.pollInterval}),this.setMaxListeners(1/0)}get size(){return Array.from(this.connections.values()).reduce((e,r)=>e+r.length,0)}start(){this._libp2p.metrics&&(this._timer=this._timer||IE(this._checkMetrics,this._options.pollInterval)),this._latencyMonitor.start(),this._onLatencyMeasure=this._onLatencyMeasure.bind(this),this._latencyMonitor.on("data",this._onLatencyMeasure),this._started=!0,Mr("started")}async stop(){this._timer&&this._timer.clear(),this._latencyMonitor.removeListener("data",this._onLatencyMeasure),this._latencyMonitor.stop(),this._started=!1,await this._close(),Mr("stopped")}async _close(){let e=[];for(let r of this.connections.values())for(let n of r)e.push(n.close());await Promise.all(e),this.connections.clear()}setPeerValue(e,r){if(r<0||r>1)throw new Error("value should be a number between 0 and 1");this._peerValues.set(e.toB58String(),r)}async _checkMetrics(){if(this._libp2p.metrics)try{let e=this._libp2p.metrics.global.movingAverages,r=e.dataReceived[this._options.movingAverageInterval].movingAverage();await this._checkMaxLimit("maxReceivedData",r);let n=e.dataSent[this._options.movingAverageInterval].movingAverage();await this._checkMaxLimit("maxSentData",n);let i=r+n;await this._checkMaxLimit("maxData",i),Mr("metrics update",i)}finally{this._timer=IE(this._checkMetrics,this._options.pollInterval)}}async onConnect(e){let r=e.remotePeer,n=r.toB58String(),i=this.connections.get(n);this.emit("peer:connect",e),i?i.push(e):this.connections.set(n,[e]),await this._libp2p.peerStore.keyBook.set(r,r.pubKey),this._peerValues.has(n)||this._peerValues.set(n,this._options.defaultPeerValue),await this._checkMaxLimit("maxConnections",this.size)}onDisconnect(e){let r=e.remotePeer.toB58String(),n=this.connections.get(r);n&&n.length>1?(n=n.filter(i=>i.id!==e.id),this.connections.set(r,n)):n&&(this.connections.delete(r),this._peerValues.delete(e.remotePeer.toB58String()),this.emit("peer:disconnect",e),this._libp2p.metrics&&this._libp2p.metrics.onPeerDisconnected(e.remotePeer))}get(e){let r=this.getAll(e);return r.length?r[0]:null}getAll(e){if(!nO.isPeerId(e))throw CE(new Error("peerId must be an instance of peer-id"),RE);let r=e.toB58String(),n=this.connections.get(r);return n?n.filter(i=>i.stat.status==="open"):[]}_onLatencyMeasure(e){this._checkMaxLimit("maxEventLoopDelay",e.avgMs).catch(r=>{Mr.error(r)})}async _checkMaxLimit(e,r){let n=this._options[e];Mr("checking limit of %s. current value: %d of %d",e,r,n),r>n&&(Mr("%s: limit exceeded: %s, %d",this._peerId,e,r),await this._maybeDisconnectOne())}async _maybeDisconnectOne(){if(this._options.minConnections<this.connections.size){let e=Array.from(new Map([...this._peerValues.entries()].sort((n,i)=>n[1]-i[1])));Mr("%s: sorted peer values: %j",this._peerId,e);let r=e[0];if(r){let n=r[0];Mr("%s: lowest value peer is %s",this._peerId,n),Mr("%s: closing a connection to %j",this._peerId,n);for(let i of this.connections.values())if(i[0].remotePeer.toB58String()===n){i[0].close().catch(s=>{Mr.error(s)}),this.onDisconnect(i[0]);break}}}}};NE.exports=PE});var LE=w((jF,DE)=>{"use strict";var aO=Mi(),cO=async function*(t,e){yield*(await aO(t)).sort(e)};DE.exports=cO});var FE=w(($F,ME)=>{"use strict";var kE=Te(),uO=Hs(),qE=va(),lO=Mi(),{pipe:fO}=ir(),dO=Fi(),hO=LE(),si=Object.assign(kE("libp2p:connection-manager:auto-dialler"),{error:kE("libp2p:connection-manager:auto-dialler:err")}),pO={enabled:!0,minConnections:0,autoDialInterval:1e4},UE=class{constructor(e,r={}){this._options=uO.call({ignoreUndefined:!0},pO,r),this._libp2p=e,this._running=!1,this._autoDialTimeout=null,this._autoDial=this._autoDial.bind(this),si("options: %j",this._options)}async start(){if(!this._options.enabled){si("not enabled");return}this._running=!0,this._autoDial().catch(e=>{si.error("could start autodial",e)}),si("started")}async stop(){if(!this._options.enabled){si("not enabled");return}this._running=!1,this._autoDialTimeout&&this._autoDialTimeout.clear(),si("stopped")}async _autoDial(){let e=this._options.minConnections;if(this._libp2p.connections.size>=e){this._autoDialTimeout=qE(this._autoDial,this._options.autoDialInterval);return}let r=await fO(this._libp2p.peerStore.getPeers(),n=>dO(n,i=>!i.id.equals(this._libp2p.peerId)),n=>hO(n,(i,s)=>s.protocols&&s.protocols.length&&(!i.protocols||!i.protocols.length)||s.id.pubKey&&!i.id.pubKey?1:-1),n=>lO(n));for(let n=0;this._running&&n<r.length&&this._libp2p.connections.size<e;n++){let i=r[n];if(!this._libp2p.connectionManager.get(i.id)){si("connecting to a peerStore stored peer %s",i.id.toB58String());try{await this._libp2p.dialer.connectToPeer(i.id)}catch(s){si.error("could not connect to peerStore stored peer",s)}}}!this._running||(this._autoDialTimeout=qE(this._autoDial,this._options.autoDialInterval))}};ME.exports=UE});var XE=w((HF,QE)=>{"use strict";var{Multiaddr:Nd}=qt(),KE=ce("dns4"),VE=ce("dns6"),jE=ce("dnsaddr"),Gi=Ut(ce("dns"),jE,KE,VE),Ia=Ut(ce("ip4"),ce("ip6")),Ys=Ut(ve(Ia,ce("tcp")),ve(Gi,ce("tcp"))),Od=ve(Ia,ce("udp")),$E=ve(Od,ce("utp")),HE=ve(Od,ce("quic")),Qs=Ut(ve(Ys,ce("ws")),ve(Gi,ce("ws"))),Xs=Ut(ve(Ys,ce("wss")),ve(Gi,ce("wss"))),gu=Ut(ve(Ys,ce("http")),ve(Ia,ce("http")),ve(Gi,ce("http"))),mu=Ut(ve(Ys,ce("https")),ve(Ia,ce("https")),ve(Gi,ce("https"))),Dd=Ut(ve(Qs,ce("p2p-webrtc-star"),ce("p2p")),ve(Xs,ce("p2p-webrtc-star"),ce("p2p")),ve(Qs,ce("p2p-webrtc-star")),ve(Xs,ce("p2p-webrtc-star"))),yO=Ut(ve(Qs,ce("p2p-websocket-star"),ce("p2p")),ve(Xs,ce("p2p-websocket-star"),ce("p2p")),ve(Qs,ce("p2p-websocket-star")),ve(Xs,ce("p2p-websocket-star"))),Ld=Ut(ve(gu,ce("p2p-webrtc-direct"),ce("p2p")),ve(mu,ce("p2p-webrtc-direct"),ce("p2p")),ve(gu,ce("p2p-webrtc-direct")),ve(mu,ce("p2p-webrtc-direct"))),Zs=Ut(Qs,Xs,gu,mu,Dd,Ld,Ys,$E,HE,Gi),gO=Ut(ve(Zs,ce("p2p-stardust"),ce("p2p")),ve(Zs,ce("p2p-stardust"))),oi=Ut(ve(Zs,ce("p2p")),Dd,Ld,ce("p2p")),zE=Ut(ve(oi,ce("p2p-circuit"),oi),ve(oi,ce("p2p-circuit")),ve(ce("p2p-circuit"),oi),ve(Zs,ce("p2p-circuit")),ve(ce("p2p-circuit"),Zs),ce("p2p-circuit")),GE=()=>Ut(ve(zE,GE),zE),Js=GE(),WE=Ut(ve(Js,oi,Js),ve(oi,Js),ve(Js,oi),Js,oi);QE.exports={DNS:Gi,DNS4:KE,DNS6:VE,DNSADDR:jE,IP:Ia,TCP:Ys,UDP:Od,QUIC:HE,UTP:$E,HTTP:gu,HTTPS:mu,WebSockets:Qs,WebSocketsSecure:Xs,WebSocketStar:yO,WebRTCStar:Dd,WebRTCDirect:Ld,Reliable:Zs,Stardust:gO,Circuit:Js,P2P:WE,IPFS:WE};function YE(t){function e(r){if(!Nd.isMultiaddr(r))try{r=new Nd(r)}catch(i){return!1}let n=t(r.protoNames());return n===null?!1:n===!0||n===!1?n:n.length===0}return e}function ve(...t){function e(r){if(r.length<t.length)return null;let n=r;return t.some(i=>(n=typeof i=="function"?i().partialMatch(r):i.partialMatch(r),Array.isArray(n)&&(r=n),n===null)),n}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:YE(e),partialMatch:e}}function Ut(...t){function e(n){let i=null;return t.some(s=>{let o=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return o?(i=o,!0):!1}),i}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:YE(e),partialMatch:e}}function ce(t){let e=t;function r(i){let s;if(typeof i=="string"||i instanceof Uint8Array)try{s=new Nd(i)}catch(a){return!1}else s=i;let o=s.protoNames();return o.length===1&&o[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:r,partialMatch:n}}});var eo=w((zF,JE)=>{"use strict";var Wi=gn(),vu=Wi.Reader,ZE=Wi.Writer,Ar=Wi.util,At=Wi.roots["libp2p-circuit"]||(Wi.roots["libp2p-circuit"]={});At.CircuitRelay=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.type=1,t.prototype.srcPeer=null,t.prototype.dstPeer=null,t.prototype.code=100,t.encode=function(r,n){return n||(n=ZE.create()),r.type!=null&&Object.hasOwnProperty.call(r,"type")&&n.uint32(8).int32(r.type),r.srcPeer!=null&&Object.hasOwnProperty.call(r,"srcPeer")&&At.CircuitRelay.Peer.encode(r.srcPeer,n.uint32(18).fork()).ldelim(),r.dstPeer!=null&&Object.hasOwnProperty.call(r,"dstPeer")&&At.CircuitRelay.Peer.encode(r.dstPeer,n.uint32(26).fork()).ldelim(),r.code!=null&&Object.hasOwnProperty.call(r,"code")&&n.uint32(32).int32(r.code),n},t.decode=function(r,n){r instanceof vu||(r=vu.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new At.CircuitRelay;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.type=r.int32();break;case 2:s.srcPeer=At.CircuitRelay.Peer.decode(r,r.uint32());break;case 3:s.dstPeer=At.CircuitRelay.Peer.decode(r,r.uint32());break;case 4:s.code=r.int32();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof At.CircuitRelay)return r;var n=new At.CircuitRelay;switch(r.type){case"HOP":case 1:n.type=1;break;case"STOP":case 2:n.type=2;break;case"STATUS":case 3:n.type=3;break;case"CAN_HOP":case 4:n.type=4;break}if(r.srcPeer!=null){if(typeof r.srcPeer!="object")throw TypeError(".CircuitRelay.srcPeer: object expected");n.srcPeer=At.CircuitRelay.Peer.fromObject(r.srcPeer)}if(r.dstPeer!=null){if(typeof r.dstPeer!="object")throw TypeError(".CircuitRelay.dstPeer: object expected");n.dstPeer=At.CircuitRelay.Peer.fromObject(r.dstPeer)}switch(r.code){case"SUCCESS":case 100:n.code=100;break;case"HOP_SRC_ADDR_TOO_LONG":case 220:n.code=220;break;case"HOP_DST_ADDR_TOO_LONG":case 221:n.code=221;break;case"HOP_SRC_MULTIADDR_INVALID":case 250:n.code=250;break;case"HOP_DST_MULTIADDR_INVALID":case 251:n.code=251;break;case"HOP_NO_CONN_TO_DST":case 260:n.code=260;break;case"HOP_CANT_DIAL_DST":case 261:n.code=261;break;case"HOP_CANT_OPEN_DST_STREAM":case 262:n.code=262;break;case"HOP_CANT_SPEAK_RELAY":case 270:n.code=270;break;case"HOP_CANT_RELAY_TO_SELF":case 280:n.code=280;break;case"STOP_SRC_ADDR_TOO_LONG":case 320:n.code=320;break;case"STOP_DST_ADDR_TOO_LONG":case 321:n.code=321;break;case"STOP_SRC_MULTIADDR_INVALID":case 350:n.code=350;break;case"STOP_DST_MULTIADDR_INVALID":case 351:n.code=351;break;case"STOP_RELAY_REFUSED":case 390:n.code=390;break;case"MALFORMED_MESSAGE":case 400:n.code=400;break}return n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.type=n.enums===String?"HOP":1,i.srcPeer=null,i.dstPeer=null,i.code=n.enums===String?"SUCCESS":100),r.type!=null&&r.hasOwnProperty("type")&&(i.type=n.enums===String?At.CircuitRelay.Type[r.type]:r.type),r.srcPeer!=null&&r.hasOwnProperty("srcPeer")&&(i.srcPeer=At.CircuitRelay.Peer.toObject(r.srcPeer,n)),r.dstPeer!=null&&r.hasOwnProperty("dstPeer")&&(i.dstPeer=At.CircuitRelay.Peer.toObject(r.dstPeer,n)),r.code!=null&&r.hasOwnProperty("code")&&(i.code=n.enums===String?At.CircuitRelay.Status[r.code]:r.code),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Wi.util.toJSONOptions)},t.Status=function(){var e={},r=Object.create(e);return r[e[100]="SUCCESS"]=100,r[e[220]="HOP_SRC_ADDR_TOO_LONG"]=220,r[e[221]="HOP_DST_ADDR_TOO_LONG"]=221,r[e[250]="HOP_SRC_MULTIADDR_INVALID"]=250,r[e[251]="HOP_DST_MULTIADDR_INVALID"]=251,r[e[260]="HOP_NO_CONN_TO_DST"]=260,r[e[261]="HOP_CANT_DIAL_DST"]=261,r[e[262]="HOP_CANT_OPEN_DST_STREAM"]=262,r[e[270]="HOP_CANT_SPEAK_RELAY"]=270,r[e[280]="HOP_CANT_RELAY_TO_SELF"]=280,r[e[320]="STOP_SRC_ADDR_TOO_LONG"]=320,r[e[321]="STOP_DST_ADDR_TOO_LONG"]=321,r[e[350]="STOP_SRC_MULTIADDR_INVALID"]=350,r[e[351]="STOP_DST_MULTIADDR_INVALID"]=351,r[e[390]="STOP_RELAY_REFUSED"]=390,r[e[400]="MALFORMED_MESSAGE"]=400,r}(),t.Type=function(){var e={},r=Object.create(e);return r[e[1]="HOP"]=1,r[e[2]="STOP"]=2,r[e[3]="STATUS"]=3,r[e[4]="CAN_HOP"]=4,r}(),t.Peer=function(){function e(r){if(this.addrs=[],r)for(var n=Object.keys(r),i=0;i<n.length;++i)r[n[i]]!=null&&(this[n[i]]=r[n[i]])}return e.prototype.id=Ar.newBuffer([]),e.prototype.addrs=Ar.emptyArray,e.encode=function(n,i){if(i||(i=ZE.create()),i.uint32(10).bytes(n.id),n.addrs!=null&&n.addrs.length)for(var s=0;s<n.addrs.length;++s)i.uint32(18).bytes(n.addrs[s]);return i},e.decode=function(n,i){n instanceof vu||(n=vu.create(n));for(var s=i===void 0?n.len:n.pos+i,o=new At.CircuitRelay.Peer;n.pos<s;){var a=n.uint32();switch(a>>>3){case 1:o.id=n.bytes();break;case 2:o.addrs&&o.addrs.length||(o.addrs=[]),o.addrs.push(n.bytes());break;default:n.skipType(a&7);break}}if(!o.hasOwnProperty("id"))throw Ar.ProtocolError("missing required 'id'",{instance:o});return o},e.fromObject=function(n){if(n instanceof At.CircuitRelay.Peer)return n;var i=new At.CircuitRelay.Peer;if(n.id!=null&&(typeof n.id=="string"?Ar.base64.decode(n.id,i.id=Ar.newBuffer(Ar.base64.length(n.id)),0):n.id.length&&(i.id=n.id)),n.addrs){if(!Array.isArray(n.addrs))throw TypeError(".CircuitRelay.Peer.addrs: array expected");i.addrs=[];for(var s=0;s<n.addrs.length;++s)typeof n.addrs[s]=="string"?Ar.base64.decode(n.addrs[s],i.addrs[s]=Ar.newBuffer(Ar.base64.length(n.addrs[s])),0):n.addrs[s].length&&(i.addrs[s]=n.addrs[s])}return i},e.toObject=function(n,i){i||(i={});var s={};if((i.arrays||i.defaults)&&(s.addrs=[]),i.defaults&&(i.bytes===String?s.id="":(s.id=[],i.bytes!==Array&&(s.id=Ar.newBuffer(s.id)))),n.id!=null&&n.hasOwnProperty("id")&&(s.id=i.bytes===String?Ar.base64.encode(n.id,0,n.id.length):i.bytes===Array?Array.prototype.slice.call(n.id):n.id),n.addrs&&n.addrs.length){s.addrs=[];for(var o=0;o<n.addrs.length;++o)s.addrs[o]=i.bytes===String?Ar.base64.encode(n.addrs[o],0,n.addrs[o].length):i.bytes===Array?Array.prototype.slice.call(n.addrs[o]):n.addrs[o]}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,Wi.util.toJSONOptions)},e}(),t}();JE.exports=At});var tw=w((GF,ew)=>{ew.exports=function(e){if(e){if(typeof e[Symbol.iterator]=="function")return e[Symbol.iterator]();if(typeof e[Symbol.asyncIterator]=="function")return e[Symbol.asyncIterator]();if(typeof e.next=="function")return e}throw new Error("argument is not an iterator or iterable")}});var nw=w((YF,rw)=>{rw.exports=class extends Error{constructor(e,r){super(e||"The operation was aborted");this.type="aborted",this.code=r||"ABORT_ERR"}}});var bu=w((QF,Yi)=>{var mO=tw(),kd=nw(),iw=(t,e,r)=>qd(t,Array.isArray(e)?e:[{signal:e,options:r}]),qd=(t,e)=>{t=mO(t),e=e.map(({signal:n,options:i})=>({signal:n,options:i||{}}));async function*r(){let n,i=()=>{n&&n()};for(let{signal:s}of e)s.addEventListener("abort",i);for(;;){let s;try{for(let{signal:a,options:c}of e)if(a.aborted){let{abortMessage:u,abortCode:l}=c;throw new kd(u,l)}let o=new Promise((a,c)=>{n=()=>{let{options:u}=e.find(({signal:d})=>d.aborted),{abortMessage:l,abortCode:f}=u;c(new kd(l,f))}});s=await Promise.race([o,t.next()]),n=null}catch(o){for(let{signal:u}of e)u.removeEventListener("abort",i);let a=e.find(({signal:u})=>u.aborted),c=o.type==="aborted"&&a;if(c&&a.options.onAbort&&await a.options.onAbort(t),typeof t.return=="function")try{let u=t.return();u instanceof Promise&&u.catch(l=>{a.options.onReturnError!=null&&a.options.onReturnError(l)})}catch(u){a.options.onReturnError!=null&&a.options.onReturnError(u)}if(c&&a.options.returnOnAbort)return;throw o}if(s.done)break;yield s.value}for(let{signal:s}of e)s.removeEventListener("abort",i)}return r()},sw=(t,e,r)=>ow(t,Array.isArray(e)?e:[{signal:e,options:r}]),ow=(t,e)=>r=>t(qd(r,e)),vO=(t,e,r)=>bO(t,Array.isArray(e)?e:[{signal:e,options:r}]),bO=(t,e)=>({sink:ow(t.sink,e),source:qd(t.source,e)});Yi.exports=iw;Yi.exports.AbortError=kd;Yi.exports.source=iw;Yi.exports.sink=sw;Yi.exports.transform=sw;Yi.exports.duplex=vO});var uw=w((XF,cw)=>{"use strict";var{source:aw}=bu(),EO=Te(),wO=EO("libp2p:stream:converter");function _O({stream:t,remoteAddr:e,localAddr:r},n={}){let{sink:i,source:s}=t,o={async sink(c){n.signal&&(c=aw(c,n.signal));try{await i(c)}catch(u){u.type!=="aborted"&&wO(u)}a()},source:n.signal?aw(s,n.signal):s,conn:t,localAddr:r,remoteAddr:e,timeline:{open:Date.now(),close:void 0},close(){return i(new Uint8Array(0)),a()}};function a(){return o.timeline.close||(o.timeline.close=Date.now()),Promise.resolve()}return o}cw.exports=_O});var Ta=w((ZF,lw)=>{"use strict";lw.exports={relay:"/libp2p/circuit/relay/0.1.0"}});var dw=w((JF,fw)=>{"use strict";var{EventEmitter:SO}=Qt(),{Multiaddr:xO}=qt();fw.exports=t=>{let e=new Map;async function r(s){let o=String(s).split("/p2p-circuit").find(u=>u!==""),a=await t.dial(new xO(o)),c=a.remoteAddr.encapsulate("/p2p-circuit");e.set(a.remotePeer.toB58String(),c),i.emit("listening")}function n(){let s=[];for(let o of e.values())s.push(o);return s}let i=Object.assign(new SO,{close:()=>Promise.resolve(),listen:r,getAddrs:n});return t.connectionManager.on("peer:disconnect",s=>{e.delete(s.remotePeer.toB58String())&&i.emit("close")}),i}});var Ud=w((eK,yw)=>{"use strict";var{Multiaddr:hw}=qt(),{CircuitRelay:Qi}=eo();function pw(t,e){t.write({type:Qi.Type.STATUS,code:e})}function AO(t,e){try{t.dstPeer&&t.dstPeer.addrs&&t.dstPeer.addrs.forEach(r=>new hw(r))}catch(r){throw pw(e,t.type===Qi.Type.HOP?Qi.Status.HOP_DST_MULTIADDR_INVALID:Qi.Status.STOP_DST_MULTIADDR_INVALID),r}try{t.srcPeer&&t.srcPeer.addrs&&t.srcPeer.addrs.forEach(r=>new hw(r))}catch(r){throw pw(e,t.type===Qi.Type.HOP?Qi.Status.HOP_SRC_MULTIADDR_INVALID:Qi.Status.STOP_SRC_MULTIADDR_INVALID),r}}yw.exports={validateAddrs:AO}});var vw=w(Eu=>{"use strict";Eu.byteLength=IO;Eu.toByteArray=RO;Eu.fromByteArray=NO;var un=[],Cr=[],CO=typeof Uint8Array!="undefined"?Uint8Array:Array,Md="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Xi=0,gw=Md.length;Xi<gw;++Xi)un[Xi]=Md[Xi],Cr[Md.charCodeAt(Xi)]=Xi;var Xi,gw;Cr["-".charCodeAt(0)]=62;Cr["_".charCodeAt(0)]=63;function mw(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function IO(t){var e=mw(t),r=e[0],n=e[1];return(r+n)*3/4-n}function TO(t,e,r){return(e+r)*3/4-r}function RO(t){var e,r=mw(t),n=r[0],i=r[1],s=new CO(TO(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)e=Cr[t.charCodeAt(c)]<<18|Cr[t.charCodeAt(c+1)]<<12|Cr[t.charCodeAt(c+2)]<<6|Cr[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Cr[t.charCodeAt(c)]<<2|Cr[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=Cr[t.charCodeAt(c)]<<10|Cr[t.charCodeAt(c+1)]<<4|Cr[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function BO(t){return un[t>>18&63]+un[t>>12&63]+un[t>>6&63]+un[t&63]}function PO(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(BO(n));return i.join("")}function NO(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(PO(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(un[e>>2]+un[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(un[e>>10]+un[e>>4&63]+un[e<<2&63]+"=")),i.join("")}});var bw=w(Fd=>{Fd.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,u=c>>1,l=-7,f=r?i-1:0,d=r?-1:1,p=t[e+f];for(f+=d,s=p&(1<<-l)-1,p>>=-l,l+=a;l>0;s=s*256+t[e+f],f+=d,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=n;l>0;o=o*256+t[e+f],f+=d,l-=8);if(s===0)s=1-u;else{if(s===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-u}return(p?-1:1)*o*Math.pow(2,s-n)};Fd.write=function(t,e,r,n,i,s){var o,a,c,u=s*8-i-1,l=(1<<u)-1,f=l>>1,d=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,h=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=l):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+f>=1?e+=d/c:e+=d*Math.pow(2,1-f),e*c>=2&&(o++,c/=2),o+f>=l?(a=0,o=l):o+f>=1?(a=(e*c-1)*Math.pow(2,i),o=o+f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=a&255,p+=h,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;t[r+p]=o&255,p+=h,o/=256,u-=8);t[r+p-h]|=g*128}});var ci=w(io=>{"use strict";var Kd=vw(),to=bw(),Ew=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;io.Buffer=F;io.SlowBuffer=UO;io.INSPECT_MAX_BYTES=50;var wu=2147483647;io.kMaxLength=wu;F.TYPED_ARRAY_SUPPORT=OO();!F.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function OO(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch(t){return!1}}Object.defineProperty(F.prototype,"parent",{enumerable:!0,get:function(){if(!!F.isBuffer(this))return this.buffer}});Object.defineProperty(F.prototype,"offset",{enumerable:!0,get:function(){if(!!F.isBuffer(this))return this.byteOffset}});function Tn(t){if(t>wu)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,F.prototype),e}function F(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Vd(t)}return ww(t,e,r)}F.poolSize=8192;function ww(t,e,r){if(typeof t=="string")return LO(t,e);if(ArrayBuffer.isView(t))return kO(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(ln(t,ArrayBuffer)||t&&ln(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer!="undefined"&&(ln(t,SharedArrayBuffer)||t&&ln(t.buffer,SharedArrayBuffer)))return $d(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return F.from(n,e,r);let i=qO(t);if(i)return i;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return F.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}F.from=function(t,e,r){return ww(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function _w(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function DO(t,e,r){return _w(t),t<=0?Tn(t):e!==void 0?typeof r=="string"?Tn(t).fill(e,r):Tn(t).fill(e):Tn(t)}F.alloc=function(t,e,r){return DO(t,e,r)};function Vd(t){return _w(t),Tn(t<0?0:Hd(t)|0)}F.allocUnsafe=function(t){return Vd(t)};F.allocUnsafeSlow=function(t){return Vd(t)};function LO(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let r=Sw(t,e)|0,n=Tn(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function jd(t){let e=t.length<0?0:Hd(t.length)|0,r=Tn(e);for(let n=0;n<e;n+=1)r[n]=t[n]&255;return r}function kO(t){if(ln(t,Uint8Array)){let e=new Uint8Array(t);return $d(e.buffer,e.byteOffset,e.byteLength)}return jd(t)}function $d(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return e===void 0&&r===void 0?n=new Uint8Array(t):r===void 0?n=new Uint8Array(t,e):n=new Uint8Array(t,e,r),Object.setPrototypeOf(n,F.prototype),n}function qO(t){if(F.isBuffer(t)){let e=Hd(t.length)|0,r=Tn(e);return r.length===0||t.copy(r,0,0,e),r}if(t.length!==void 0)return typeof t.length!="number"||Wd(t.length)?Tn(0):jd(t);if(t.type==="Buffer"&&Array.isArray(t.data))return jd(t.data)}function Hd(t){if(t>=wu)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+wu.toString(16)+" bytes");return t|0}function UO(t){return+t!=t&&(t=0),F.alloc(+t)}F.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==F.prototype};F.compare=function(e,r){if(ln(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),ln(r,Uint8Array)&&(r=F.from(r,r.offset,r.byteLength)),!F.isBuffer(e)||!F.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;let n=e.length,i=r.length;for(let s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==r[s]){n=e[s],i=r[s];break}return n<i?-1:i<n?1:0};F.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};F.concat=function(e,r){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return F.alloc(0);let n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;let i=F.allocUnsafe(r),s=0;for(n=0;n<e.length;++n){let o=e[n];if(ln(o,Uint8Array))s+o.length>i.length?(F.isBuffer(o)||(o=F.from(o)),o.copy(i,s)):Uint8Array.prototype.set.call(i,o,s);else if(F.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function Sw(t,e){if(F.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||ln(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);let r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Gd(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Lw(t).length;default:if(i)return n?-1:Gd(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=Sw;function MO(t,e,r){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return YO(this,e,r);case"utf8":case"utf-8":return Cw(this,e,r);case"ascii":return GO(this,e,r);case"latin1":case"binary":return WO(this,e,r);case"base64":return HO(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return QO(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function Zi(t,e,r){let n=t[e];t[e]=t[r],t[r]=n}F.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<e;r+=2)Zi(this,r,r+1);return this};F.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<e;r+=4)Zi(this,r,r+3),Zi(this,r+1,r+2);return this};F.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<e;r+=8)Zi(this,r,r+7),Zi(this,r+1,r+6),Zi(this,r+2,r+5),Zi(this,r+3,r+4);return this};F.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?Cw(this,0,e):MO.apply(this,arguments)};F.prototype.toLocaleString=F.prototype.toString;F.prototype.equals=function(e){if(!F.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:F.compare(this,e)===0};F.prototype.inspect=function(){let e="",r=io.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};Ew&&(F.prototype[Ew]=F.prototype.inspect);F.prototype.compare=function(e,r,n,i,s){if(ln(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),!F.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;let o=s-i,a=n-r,c=Math.min(o,a),u=this.slice(i,s),l=e.slice(r,n);for(let f=0;f<c;++f)if(u[f]!==l[f]){o=u[f],a=l[f];break}return o<a?-1:a<o?1:0};function xw(t,e,r,n,i){if(t.length===0)return-1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Wd(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=F.from(e,n)),F.isBuffer(e))return e.length===0?-1:Aw(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Aw(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Aw(t,e,r,n,i){let s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,a/=2,r/=2}function c(l,f){return s===1?l[f]:l.readUInt16BE(f*s)}let u;if(i){let l=-1;for(u=r;u<o;u++)if(c(t,u)===c(e,l===-1?0:u-l)){if(l===-1&&(l=u),u-l+1===a)return l*s}else l!==-1&&(u-=u-l),l=-1}else for(r+a>o&&(r=o-a),u=r;u>=0;u--){let l=!0;for(let f=0;f<a;f++)if(c(t,u+f)!==c(e,f)){l=!1;break}if(l)return u}return-1}F.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};F.prototype.indexOf=function(e,r,n){return xw(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return xw(this,e,r,n,!1)};function FO(t,e,r,n){r=Number(r)||0;let i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;let s=e.length;n>s/2&&(n=s/2);let o;for(o=0;o<n;++o){let a=parseInt(e.substr(o*2,2),16);if(Wd(a))return o;t[r+o]=a}return o}function KO(t,e,r,n){return _u(Gd(e,t.length-r),t,r,n)}function VO(t,e,r,n){return _u(eD(e),t,r,n)}function jO(t,e,r,n){return _u(Lw(e),t,r,n)}function $O(t,e,r,n){return _u(tD(e,t.length-r),t,r,n)}F.prototype.write=function(e,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return FO(this,e,r,n);case"utf8":case"utf-8":return KO(this,e,r,n);case"ascii":case"latin1":case"binary":return VO(this,e,r,n);case"base64":return jO(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return $O(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};F.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function HO(t,e,r){return e===0&&r===t.length?Kd.fromByteArray(t):Kd.fromByteArray(t.slice(e,r))}function Cw(t,e,r){r=Math.min(t.length,r);let n=[],i=e;for(;i<r;){let s=t[i],o=null,a=s>239?4:s>223?3:s>191?2:1;if(i+a<=r){let c,u,l,f;switch(a){case 1:s<128&&(o=s);break;case 2:c=t[i+1],(c&192)==128&&(f=(s&31)<<6|c&63,f>127&&(o=f));break;case 3:c=t[i+1],u=t[i+2],(c&192)==128&&(u&192)==128&&(f=(s&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:c=t[i+1],u=t[i+2],l=t[i+3],(c&192)==128&&(u&192)==128&&(l&192)==128&&(f=(s&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a}return zO(n)}var Iw=4096;function zO(t){let e=t.length;if(e<=Iw)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Iw));return r}function GO(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]&127);return n}function WO(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function YO(t,e,r){let n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let i="";for(let s=e;s<r;++s)i+=rD[t[s]];return i}function QO(t,e,r){let n=t.slice(e,r),i="";for(let s=0;s<n.length-1;s+=2)i+=String.fromCharCode(n[s]+n[s+1]*256);return i}F.prototype.slice=function(e,r){let n=this.length;e=~~e,r=r===void 0?n:~~r,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<e&&(r=e);let i=this.subarray(e,r);return Object.setPrototypeOf(i,F.prototype),i};function Ct(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}F.prototype.readUintLE=F.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ct(e,r,this.length);let i=this[e],s=1,o=0;for(;++o<r&&(s*=256);)i+=this[e+o]*s;return i};F.prototype.readUintBE=F.prototype.readUIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ct(e,r,this.length);let i=this[e+--r],s=1;for(;r>0&&(s*=256);)i+=this[e+--r]*s;return i};F.prototype.readUint8=F.prototype.readUInt8=function(e,r){return e=e>>>0,r||Ct(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Ct(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Ct(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};F.prototype.readUint32BE=F.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};F.prototype.readBigUInt64LE=ai(function(e){e=e>>>0,no(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Ra(e,this.length-8);let i=r+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,s=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(i)+(BigInt(s)<<BigInt(32))});F.prototype.readBigUInt64BE=ai(function(e){e=e>>>0,no(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Ra(e,this.length-8);let i=r*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],s=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(i)<<BigInt(32))+BigInt(s)});F.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ct(e,r,this.length);let i=this[e],s=1,o=0;for(;++o<r&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*r)),i};F.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ct(e,r,this.length);let i=r,s=1,o=this[e+--i];for(;i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};F.prototype.readInt8=function(e,r){return e=e>>>0,r||Ct(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Ct(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};F.prototype.readInt16BE=function(e,r){e=e>>>0,r||Ct(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};F.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};F.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};F.prototype.readBigInt64LE=ai(function(e){e=e>>>0,no(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Ra(e,this.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(i)<<BigInt(32))+BigInt(r+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)});F.prototype.readBigInt64BE=ai(function(e){e=e>>>0,no(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Ra(e,this.length-8);let i=(r<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n)});F.prototype.readFloatLE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),to.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),to.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ct(e,8,this.length),to.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ct(e,8,this.length),to.read(this,e,!1,52,8)};function er(t,e,r,n,i,s){if(!F.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}F.prototype.writeUintLE=F.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;er(this,e,r,n,a,0)}let s=1,o=0;for(this[r]=e&255;++o<n&&(s*=256);)this[r+o]=e/s&255;return r+n};F.prototype.writeUintBE=F.prototype.writeUIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;er(this,e,r,n,a,0)}let s=n-1,o=1;for(this[r+s]=e&255;--s>=0&&(o*=256);)this[r+s]=e/o&255;return r+n};F.prototype.writeUint8=F.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,1,255,0),this[r]=e&255,r+1};F.prototype.writeUint16LE=F.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeUint16BE=F.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeUint32LE=F.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};F.prototype.writeUint32BE=F.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function Tw(t,e,r,n,i){Dw(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,r}function Rw(t,e,r,n,i){Dw(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s=s>>8,t[r+6]=s,s=s>>8,t[r+5]=s,s=s>>8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o=o>>8,t[r+2]=o,o=o>>8,t[r+1]=o,o=o>>8,t[r]=o,r+8}F.prototype.writeBigUInt64LE=ai(function(e,r=0){return Tw(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});F.prototype.writeBigUInt64BE=ai(function(e,r=0){return Rw(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});F.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let c=Math.pow(2,8*n-1);er(this,e,r,n,c-1,-c)}let s=0,o=1,a=0;for(this[r]=e&255;++s<n&&(o*=256);)e<0&&a===0&&this[r+s-1]!==0&&(a=1),this[r+s]=(e/o>>0)-a&255;return r+n};F.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let c=Math.pow(2,8*n-1);er(this,e,r,n,c-1,-c)}let s=n-1,o=1,a=0;for(this[r+s]=e&255;--s>=0&&(o*=256);)e<0&&a===0&&this[r+s+1]!==0&&(a=1),this[r+s]=(e/o>>0)-a&255;return r+n};F.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};F.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};F.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};F.prototype.writeBigInt64LE=ai(function(e,r=0){return Tw(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});F.prototype.writeBigInt64BE=ai(function(e,r=0){return Rw(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Bw(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Pw(t,e,r,n,i){return e=+e,r=r>>>0,i||Bw(t,e,r,4,34028234663852886e22,-34028234663852886e22),to.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return Pw(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return Pw(this,e,r,!1,n)};function Nw(t,e,r,n,i){return e=+e,r=r>>>0,i||Bw(t,e,r,8,17976931348623157e292,-17976931348623157e292),to.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return Nw(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return Nw(this,e,r,!1,n)};F.prototype.copy=function(e,r,n,i){if(!F.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r<i-n&&(i=e.length-r+n);let s=i-n;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),r),s};F.prototype.fill=function(e,r,n,i){if(typeof e=="string"){if(typeof r=="string"?(i=r,r=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!F.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(e.length===1){let o=e.charCodeAt(0);(i==="utf8"&&o<128||i==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);let s;if(typeof e=="number")for(s=r;s<n;++s)this[s]=e;else{let o=F.isBuffer(e)?e:F.from(e,i),a=o.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-r;++s)this[s+r]=o[s%a]}return this};var ro={};function zd(t,e,r){ro[t]=class extends r{constructor(){super();Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(i){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:i,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}zd("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);zd("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError);zd("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=Ow(String(r)):typeof r=="bigint"&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=Ow(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);function Ow(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function XO(t,e,r){no(e,"offset"),(t[e]===void 0||t[e+r]===void 0)&&Ra(e,t.length-(r+1))}function Dw(t,e,r,n,i,s){if(t>r||t<e){let o=typeof e=="bigint"?"n":"",a;throw s>3?e===0||e===BigInt(0)?a=`>= 0${o} and < 2${o} ** ${(s+1)*8}${o}`:a=`>= -(2${o} ** ${(s+1)*8-1}${o}) and < 2 ** ${(s+1)*8-1}${o}`:a=`>= ${e}${o} and <= ${r}${o}`,new ro.ERR_OUT_OF_RANGE("value",a,t)}XO(n,i,s)}function no(t,e){if(typeof t!="number")throw new ro.ERR_INVALID_ARG_TYPE(e,"number",t)}function Ra(t,e,r){throw Math.floor(t)!==t?(no(t,r),new ro.ERR_OUT_OF_RANGE(r||"offset","an integer",t)):e<0?new ro.ERR_BUFFER_OUT_OF_BOUNDS:new ro.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}var ZO=/[^+/0-9A-Za-z-_]/g;function JO(t){if(t=t.split("=")[0],t=t.trim().replace(ZO,""),t.length<2)return"";for(;t.length%4!=0;)t=t+"=";return t}function Gd(t,e){e=e||1/0;let r,n=t.length,i=null,s=[];for(let o=0;o<n;++o){if(r=t.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function eD(t){let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function tD(t,e){let r,n,i,s=[];for(let o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}function Lw(t){return Kd.toByteArray(JO(t))}function _u(t,e,r,n){let i;for(i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ln(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function Wd(t){return t!==t}var rD=function(){let t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){let n=r*16;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function ai(t){return typeof BigInt=="undefined"?nD:t}function nD(){throw new Error("BigInt not supported")}});var Ji=w((sK,qw)=>{"use strict";var{Buffer:Fr}=ci(),kw=Symbol.for("BufferList");function Ge(t){if(!(this instanceof Ge))return new Ge(t);Ge._init.call(this,t)}Ge._init=function(e){Object.defineProperty(this,kw,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)};Ge.prototype._new=function(e){return new Ge(e)};Ge.prototype._offset=function(e){if(e===0)return[0,0];let r=0;for(let n=0;n<this._bufs.length;n++){let i=r+this._bufs[n].length;if(e<i||n===this._bufs.length-1)return[n,e-r];r=i}};Ge.prototype._reverseOffset=function(t){let e=t[0],r=t[1];for(let n=0;n<e;n++)r+=this._bufs[n].length;return r};Ge.prototype.get=function(e){if(e>this.length||e<0)return;let r=this._offset(e);return this._bufs[r[0]][r[1]]};Ge.prototype.slice=function(e,r){return typeof e=="number"&&e<0&&(e+=this.length),typeof r=="number"&&r<0&&(r+=this.length),this.copy(null,0,e,r)};Ge.prototype.copy=function(e,r,n,i){if((typeof n!="number"||n<0)&&(n=0),(typeof i!="number"||i>this.length)&&(i=this.length),n>=this.length||i<=0)return e||Fr.alloc(0);let s=!!e,o=this._offset(n),a=i-n,c=a,u=s&&r||0,l=o[1];if(n===0&&i===this.length){if(!s)return this._bufs.length===1?this._bufs[0]:Fr.concat(this._bufs,this.length);for(let f=0;f<this._bufs.length;f++)this._bufs[f].copy(e,u),u+=this._bufs[f].length;return e}if(c<=this._bufs[o[0]].length-l)return s?this._bufs[o[0]].copy(e,r,l,l+c):this._bufs[o[0]].slice(l,l+c);s||(e=Fr.allocUnsafe(a));for(let f=o[0];f<this._bufs.length;f++){let d=this._bufs[f].length-l;if(c>d)this._bufs[f].copy(e,u,l),u+=d;else{this._bufs[f].copy(e,u,l,l+c),u+=d;break}c-=d,l&&(l=0)}return e.length>u?e.slice(0,u):e};Ge.prototype.shallowSlice=function(e,r){if(e=e||0,r=typeof r!="number"?this.length:r,e<0&&(e+=this.length),r<0&&(r+=this.length),e===r)return this._new();let n=this._offset(e),i=this._offset(r),s=this._bufs.slice(n[0],i[0]+1);return i[1]===0?s.pop():s[s.length-1]=s[s.length-1].slice(0,i[1]),n[1]!==0&&(s[0]=s[0].slice(n[1])),this._new(s)};Ge.prototype.toString=function(e,r,n){return this.slice(r,n).toString(e)};Ge.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;)if(e>=this._bufs[0].length)e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}return this};Ge.prototype.duplicate=function(){let e=this._new();for(let r=0;r<this._bufs.length;r++)e.append(this._bufs[r]);return e};Ge.prototype.append=function(e){if(e==null)return this;if(e.buffer)this._appendBuffer(Fr.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let r=0;r<e.length;r++)this.append(e[r]);else if(this._isBufferList(e))for(let r=0;r<e._bufs.length;r++)this.append(e._bufs[r]);else typeof e=="number"&&(e=e.toString()),this._appendBuffer(Fr.from(e));return this};Ge.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length};Ge.prototype.indexOf=function(t,e,r){if(r===void 0&&typeof e=="string"&&(r=e,e=void 0),typeof t=="function"||Array.isArray(t))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof t=="number"?t=Fr.from([t]):typeof t=="string"?t=Fr.from(t,r):this._isBufferList(t)?t=t.slice():Array.isArray(t.buffer)?t=Fr.from(t.buffer,t.byteOffset,t.byteLength):Fr.isBuffer(t)||(t=Fr.from(t)),e=Number(e||0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let n=this._offset(e),i=n[0],s=n[1];for(;i<this._bufs.length;i++){let o=this._bufs[i];for(;s<o.length;)if(o.length-s>=t.length){let c=o.indexOf(t,s);if(c!==-1)return this._reverseOffset([i,c]);s=o.length-t.length+1}else{let c=this._reverseOffset([i,s]);if(this._match(c,t))return c;s++}s=0}return-1};Ge.prototype._match=function(t,e){if(this.length-t<e.length)return!1;for(let r=0;r<e.length;r++)if(this.get(t+r)!==e[r])return!1;return!0};(function(){let t={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let e in t)(function(r){t[r]===null?Ge.prototype[r]=function(n,i){return this.slice(n,n+i)[r](0,i)}:Ge.prototype[r]=function(n=0){return this.slice(n,n+t[r])[r](0)}})(e)})();Ge.prototype._isBufferList=function(e){return e instanceof Ge||Ge.isBufferList(e)};Ge.isBufferList=function(e){return e!=null&&e[kw]};qw.exports=Ge});var Yd=w((oK,Fw)=>{"use strict";var Uw=Ui(),{Buffer:iD}=ci(),Mw=(t,e,r)=>{let n=Uw.encode(t,e,r);return Mw.bytes=Uw.encode.bytes,e||iD.from(n)};Fw.exports=Mw});var zw=w((aK,Su)=>{"use strict";var{Buffer:Kw}=ci(),Vw=Ji(),jw=Yd(),Qd=8,$w=10*1024;function Hw(t){t=t||{};let e=Math.max(t.poolSize||$w,t.minPoolSize||Qd),r=t.lengthEncoder||jw;return async function*(i){let s=Kw.alloc(e),o=0;for await(let a of i){r(a.length,s,o);let c=s.slice(o,o+r.bytes);o+=r.bytes,s.length-o<Qd&&(s=Kw.alloc(e),o=0),yield new Vw().append(c).append(a)}}}Hw.single=(t,e)=>{e=e||{};let r=e.lengthEncoder||jw;return new Vw([r(t.length),t.slice()])};Su.exports=Hw;Su.exports.MIN_POOL_SIZE=Qd;Su.exports.DEFAULT_POOL_SIZE=$w});var Xd=w((cK,Yw)=>{"use strict";var Gw=Ui(),{Buffer:sD}=ci(),oD=t=>new Proxy({},{get:(e,r)=>r[0]==="l"?t[r]:t.get(parseInt(r))}),Ww=t=>{let e=Gw.decode(sD.isBuffer(t)?t:oD(t));return Ww.bytes=Gw.decode.bytes,e};Yw.exports=Ww});var Jw=w((uK,xu)=>{"use strict";var{Buffer:aD}=ci(),Zd=Ji(),cD=Xd(),Qw=8,Xw=1024*1024*4,Zw=aD.alloc(0),ui={LENGTH:"readLength",DATA:"readData"},uD={[ui.LENGTH]:(t,e,r,n)=>{e=e.append(t);let i;try{i=n.lengthDecoder(e)}catch(s){if(e.length>n.maxLengthLength)throw Object.assign(s,{message:"message length too long",code:"ERR_MSG_LENGTH_TOO_LONG"});if(s instanceof RangeError)return{mode:ui.LENGTH,buffer:e,chunk:void 0,state:void 0,data:void 0};throw s}if(i>n.maxDataLength)throw Object.assign(new Error("message data too long"),{code:"ERR_MSG_DATA_TOO_LONG"});return t=e.shallowSlice(n.lengthDecoder.bytes),e=new Zd,n.onLength&&n.onLength(i),i<=0?(n.onData&&n.onData(Zw),{mode:ui.LENGTH,chunk:t,buffer:e,data:Zw}):{mode:ui.DATA,chunk:t,buffer:e,state:{dataLength:i},data:void 0}},[ui.DATA]:(t,e,r,n)=>{if(e=e.append(t),!r)throw new Error("state is required");if(e.length<r.dataLength)return{mode:ui.DATA,buffer:e,state:r,chunk:void 0,data:void 0};let{dataLength:i}=r,s=e.shallowSlice(0,i),o=e.length>i?e.shallowSlice(i):void 0;return e=new Zd,n.onData&&n.onData(s),{mode:ui.LENGTH,chunk:o,buffer:e,state:void 0,data:s}}};function Jd(t){t=t||{};let e={lengthDecoder:t.lengthDecoder||cD,maxLengthLength:t.maxLengthLength||Qw,maxDataLength:t.maxDataLength||Xw,onLength:t.onLength,onData:t.onData};return async function*(n){let i=new Zd,s=ui.LENGTH,o;for await(let a of n){let c=a;for(;c;){let u=uD[s](c,i,o,e);s=u.mode,c=u.chunk,i=u.buffer,o=u.state,u.data&&(yield u.data)}}if(i.length)throw Object.assign(new Error("unexpected end of input"),{code:"ERR_UNEXPECTED_EOF"})}}Jd.fromReader=(t,e)=>{let r=1,n={[Symbol.asyncIterator](){return this},next:async()=>{try{return await t.next(r)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}};return Jd({...e||{},onLength:s=>{r=s}})(n)};xu.exports=Jd;xu.exports.MAX_LENGTH_LENGTH=Qw;xu.exports.MAX_DATA_LENGTH=Xw});var r2=w((lK,t2)=>{"use strict";var{Buffer:lD}=ci(),e2=(t,e,r)=>(e=e||lD.allocUnsafe(4),e.writeInt32BE(t,r),e);e2.bytes=4;t2.exports=e2});var s2=w((fK,i2)=>{"use strict";var n2=t=>{if(t.length<4)throw RangeError("Could not decode int32BE");return t.readInt32BE(0)};n2.bytes=4;i2.exports=n2});var so=w(es=>{"use strict";es.encode=zw();es.decode=Jw();es.varintEncode=Yd();es.varintDecode=Xd();es.int32BEEncode=r2();es.int32BEDecode=s2()});var th=w((hK,o2)=>{var eh=Ji();o2.exports=t=>{let e=async function*(){let r=yield,n=new eh;for await(let i of t){if(!r){r=yield n.append(i),n=new eh;continue}for(n.append(i);n.length>=r;){let s=n.shallowSlice(0,r);if(n.consume(r),r=yield s,!r){n.length&&(r=yield n,n=new eh);break}}}if(r)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}});var rh=w((pK,a2)=>{"use strict";var fD=()=>{let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t};a2.exports=fD});var oo=w((yK,c2)=>{"use strict";var dD=th(),hD=ud(),pD=rh();c2.exports=t=>{let e=hD(),r=dD(t.source),n=pD(),i,s=t.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:a=>i?Promise.reject(i):(n.resolve(a),s),source:r},rest:()=>e.end(),write:e.push,read:async()=>(await r.next()).value}}});var Cu=w((gK,h2)=>{"use strict";var u2=Te(),Au=Object.assign(u2("libp2p:circuit:stream-handler"),{error:u2("libp2p:circuit:stream-handler:err")}),l2=so(),yD=oo(),{CircuitRelay:f2}=eo(),d2=class{constructor({stream:e,maxLength:r=4096}){this.stream=e,this.shake=yD(this.stream),this.decoder=l2.decode.fromReader(this.shake.reader,{maxDataLength:r})}async read(){let e=await this.decoder.next();if(e.value){let r=f2.decode(e.value.slice());return Au("read message type",r.type),r}Au("read received no value, closing stream"),this.close()}write(e){Au("write message type %s",e.type),this.shake.write(l2.encode.single(f2.encode(e).finish()))}rest(){return this.shake.rest(),this.shake.stream}end(e){this.write(e),this.close()}close(){Au("closing the stream"),this.rest().sink([])}};h2.exports=d2});var sh=w((mK,ih)=>{"use strict";var p2=Te(),Ba=Object.assign(p2("libp2p:circuit:stop"),{error:p2("libp2p:circuit:stop:err")}),{CircuitRelay:nh}=eo(),gD=Ta(),mD=Cu(),{validateAddrs:vD}=Ud();ih.exports.handleStop=function({connection:e,request:r,streamHandler:n}){try{vD(r,n)}catch(i){return Ba.error("invalid stop request via peer %s",e.remotePeer.toB58String(),i)}return Ba("stop request is valid"),n.write({type:nh.Type.STATUS,code:nh.Status.SUCCESS}),n.rest()};ih.exports.stop=async function({connection:e,request:r}){let{stream:n}=await e.newStream([gD.relay]);Ba("starting stop request to %s",e.remotePeer.toB58String());let i=new mD({stream:n});i.write(r);let s=await i.read();if(!s)return i.close();if(s.code===nh.Status.SUCCESS)return Ba("stop request to %s was successful",e.remotePeer.toB58String()),i.rest();Ba("stop request failed with code %d",s.code),i.close()}});var oh=w((vK,E2)=>{"use strict";var y2=Te(),Rn=Object.assign(y2("libp2p:circuit:hop"),{error:y2("libp2p:circuit:hop:err")}),g2=de(),bD=Rt(),{validateAddrs:ED}=Ud(),m2=Cu(),{CircuitRelay:sr}=eo(),{pipe:wD}=ir(),{codes:v2}=je(),{stop:_D}=sh(),b2=Ta();async function SD({connection:t,request:e,streamHandler:r,circuit:n}){if(!n._options.hop.enabled)return Rn("HOP request received but we are not acting as a relay"),r.end({type:sr.Type.STATUS,code:sr.Status.HOP_CANT_SPEAK_RELAY});try{ED(e,r)}catch(u){return Rn.error("invalid hop request via peer %s",t.remotePeer.toB58String(),u)}if(!e.dstPeer){Rn("HOP request received but we do not receive a dstPeer");return}let i=new bD(e.dstPeer.id),s=n._connectionManager.get(i);if(!s&&!n._options.hop.active)return Rn("HOP request received but we are not connected to the destination peer"),r.end({type:sr.Type.STATUS,code:sr.Status.HOP_NO_CONN_TO_DST});if(!s)return;let o={type:sr.Type.STOP,dstPeer:e.dstPeer,srcPeer:e.srcPeer},a;try{a=await _D({connection:s,request:o})}catch(u){return Rn.error(u)}Rn("hop request from %s is valid",t.remotePeer.toB58String()),r.write({type:sr.Type.STATUS,code:sr.Status.SUCCESS});let c=r.rest();return wD(c,a,c)}async function xD({connection:t,request:e}){let{stream:r}=await t.newStream([b2.relay]),n=new m2({stream:r});n.write(e);let i=await n.read();if(!i)throw g2(new Error("HOP request had no response"),v2.ERR_HOP_REQUEST_FAILED);if(i.code===sr.Status.SUCCESS)return Rn("hop request was successful"),n.rest();throw Rn("hop request failed with code %d, closing stream",i.code),n.close(),g2(new Error(`HOP request failed with code ${i.code}`),v2.ERR_HOP_REQUEST_FAILED)}async function AD({connection:t}){let{stream:e}=await t.newStream([b2.relay]),r=new m2({stream:e});r.write({type:sr.Type.CAN_HOP});let n=await r.read();return await r.close(),!(!n||n.code!==sr.Status.SUCCESS)}function CD({connection:t,streamHandler:e,circuit:r}){let n=r._options.hop.enabled;Rn("can hop (%s) request from %s",n,t.remotePeer.toB58String()),e.end({type:sr.Type.STATUS,code:n?sr.Status.SUCCESS:sr.Status.HOP_CANT_SPEAK_RELAY})}E2.exports={handleHop:SD,hop:xD,canHop:AD,handleCanHop:CD}});var C2=w((bK,A2)=>{"use strict";var w2=Te(),Bn=Object.assign(w2("libp2p:circuit"),{error:w2("libp2p:circuit:err")}),ID=de(),TD=XE(),{Multiaddr:Pa}=qt(),_2=Rt(),{CircuitRelay:Na}=eo(),{codes:RD}=je(),S2=uw(),{relay:BD}=Ta(),PD=dw(),{handleCanHop:ND,handleHop:OD,hop:DD}=oh(),{handleStop:LD}=sh(),kD=Cu(),qD=Symbol.for("@libp2p/js-libp2p-circuit/circuit"),x2=class{constructor({libp2p:e,upgrader:r}){this._dialer=e.dialer,this._registrar=e.registrar,this._connectionManager=e.connectionManager,this._upgrader=r,this._options=e._config.relay,this._libp2p=e,this.peerId=e.peerId,this._registrar.handle(BD,this._onProtocol.bind(this))}async _onProtocol({connection:e,stream:r}){let n=new kD({stream:r}),i=await n.read();if(!i)return;let s=this,o;switch(i.type){case Na.Type.CAN_HOP:{Bn("received CAN_HOP request from %s",e.remotePeer.toB58String()),await ND({circuit:s,connection:e,streamHandler:n});break}case Na.Type.HOP:{Bn("received HOP request from %s",e.remotePeer.toB58String()),o=await OD({connection:e,request:i,streamHandler:n,circuit:s});break}case Na.Type.STOP:{Bn("received STOP request from %s",e.remotePeer.toB58String()),o=await LD({connection:e,request:i,streamHandler:n});break}default:Bn("Request of type %s not supported",i.type)}if(o){let a=new Pa(i.dstPeer.addrs[0]),c=new Pa(i.srcPeer.addrs[0]),u=S2({stream:o,remoteAddr:a,localAddr:c}),l=i.type===Na.Type.HOP?"relay":"inbound";Bn("new %s connection %s",l,u.remoteAddr);let f=await this._upgrader.upgradeInbound(u);Bn("%s connection %s upgraded",l,u.remoteAddr),this.handler&&this.handler(f)}}async dial(e,r){let n=e.toString().split("/p2p-circuit"),i=new Pa(n[0]),s=new Pa(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(!o||!a){let d="Circuit relay dial failed as addresses did not have peer id";throw Bn.error(d),ID(new Error(d),RD.ERR_RELAYED_DIAL)}let c=_2.createFromB58String(o),u=_2.createFromB58String(a),l=!1,f=this._connectionManager.get(c);f||(f=await this._dialer.connectToPeer(i,r),l=!0);try{let d=await DD({connection:f,request:{type:Na.Type.HOP,srcPeer:{id:this.peerId.toBytes(),addrs:this._libp2p.multiaddrs.map(g=>g.bytes)},dstPeer:{id:u.toBytes(),addrs:[new Pa(s).bytes]}}}),p=i.encapsulate(`/p2p-circuit/p2p/${this.peerId.toB58String()}`),h=S2({stream:d,remoteAddr:e,localAddr:p});return Bn("new outbound connection %s",h.remoteAddr),this._upgrader.upgradeOutbound(h)}catch(d){throw Bn.error("Circuit relay dial failed",d),l&&await f.close(),d}}createListener(e,r){return typeof e=="function"&&(r=e,e={}),this.handler=r,PD(this._libp2p)}filter(e){return e=Array.isArray(e)?e:[e],e.filter(r=>TD.Circuit.matches(r))}get[Symbol.toStringTag](){return"Circuit"}static isTransport(e){return Boolean(e&&e[qD])}};A2.exports=x2});var ah=w((EK,I2)=>{"use strict";var{CID:UD}=(ws(),ko),{sha256:MD}=(Bi(),Gn);I2.exports.namespaceToCid=async t=>{let e=new TextEncoder().encode(t),r=await MD.digest(e);return UD.createV0(r)}});var O2=w((wK,N2)=>{"use strict";var T2=Te(),ch=Object.assign(T2("libp2p:auto-relay"),{error:T2("libp2p:auto-relay:err")}),{fromString:FD}=(It(),Nt),{toString:KD}=(Tt(),Ot),{Multiaddr:VD}=qt(),jD=Mi(),{relay:$D}=Ta(),{canHop:HD}=oh(),{namespaceToCid:zD}=ah(),{CIRCUIT_PROTO_CODE:GD,HOP_METADATA_KEY:R2,HOP_METADATA_VALUE:B2,RELAY_RENDEZVOUS_NS:WD}=uu(),P2=class{constructor({libp2p:e,maxListeners:r=1,onError:n}){this._libp2p=e,this._peerId=e.peerId,this._peerStore=e.peerStore,this._connectionManager=e.connectionManager,this._transportManager=e.transportManager,this._addressSorter=e.dialer.addressSorter,this.maxListeners=r,this._listenRelays=new Set,this._onProtocolChange=this._onProtocolChange.bind(this),this._onPeerDisconnected=this._onPeerDisconnected.bind(this),this._peerStore.on("change:protocols",this._onProtocolChange),this._connectionManager.on("peer:disconnect",this._onPeerDisconnected),this._onError=(i,s)=>{ch.error(s||i),n&&n(i,s)}}async _onProtocolChange({peerId:e,protocols:r}){let n=e.toB58String(),i=r.find(s=>s===$D);if(!i&&this._listenRelays.has(n)){await this._removeListenRelay(n);return}else if(!i||this._listenRelays.has(n))return;try{let s=this._connectionManager.get(e);if(!s)return;if(s.remoteAddr.protoCodes().includes(GD)){ch(`relayed connection to ${n} will not be used to hop on`);return}await HD({connection:s})&&(await this._peerStore.metadataBook.setValue(e,R2,FD(B2)),await this._addListenRelay(s,n))}catch(s){this._onError(s)}}_onPeerDisconnected(e){let n=e.remotePeer.toB58String();!this._listenRelays.has(n)||this._removeListenRelay(n).catch(i=>{ch.error(i)})}async _addListenRelay(e,r){try{if(this._listenRelays.size>=this.maxListeners)return;let n=await this._peerStore.addressBook.getMultiaddrsForPeer(e.remotePeer,this._addressSorter);(await Promise.all(n.map(async s=>{try{return await this._transportManager.listen([new VD(`${s.toString()}/p2p-circuit`)]),!0}catch(o){this._onError(o)}return!1}))).includes(!0)&&this._listenRelays.add(r)}catch(n){this._onError(n),this._listenRelays.delete(r)}}async _removeListenRelay(e){this._listenRelays.delete(e)&&await this._listenOnAvailableHopRelays([e])}async _listenOnAvailableHopRelays(e=[]){if(this._listenRelays.size>=this.maxListeners)return;let r=[],n=await jD(this._peerStore.getPeers());for await(let{id:i,metadata:s}of n){let o=i.toB58String();if(this._listenRelays.has(o)||e.includes(o))continue;let a=s.get(R2);if(!a||KD(a)!==B2)continue;let c=this._connectionManager.get(i);if(!c){r.push(i);continue}if(await this._addListenRelay(c,o),this._listenRelays.size>=this.maxListeners)return}for(let i of r)if(await this._tryToListenOnRelay(i),this._listenRelays.size>=this.maxListeners)return;try{let i=await zD(WD);for await(let s of this._libp2p.contentRouting.findProviders(i)){if(!s.multiaddrs.length)continue;let o=s.id;if(await this._peerStore.addressBook.add(o,s.multiaddrs),await this._tryToListenOnRelay(o),this._listenRelays.size>=this.maxListeners)return}}catch(i){this._onError(i)}}async _tryToListenOnRelay(e){try{let r=await this._libp2p.dial(e);await this._addListenRelay(r,e.toB58String())}catch(r){this._onError(r,`could not connect and listen on known hop relay ${e.toB58String()}`)}}};N2.exports=P2});var U2=w((_K,q2)=>{"use strict";var D2=Te(),L2=Object.assign(D2("libp2p:relay"),{error:D2("libp2p:relay:err")}),{codes:YD}=je(),{setDelayedInterval:QD,clearDelayedInterval:XD}=hd(),ZD=O2(),{namespaceToCid:JD}=ah(),{RELAY_RENDEZVOUS_NS:eL}=uu(),k2=class{constructor(e){this._libp2p=e,this._options={...e._config.relay},this._autoRelay=this._options.autoRelay.enabled&&new ZD({libp2p:e,...this._options.autoRelay}),this._advertiseService=this._advertiseService.bind(this)}start(){this._options.hop.enabled&&this._options.advertise.enabled&&(this._timeout=QD(this._advertiseService,this._options.advertise.ttl,this._options.advertise.bootDelay))}stop(){XD(this._timeout)}async _advertiseService(){try{let e=await JD(eL);await this._libp2p.contentRouting.provide(e)}catch(e){e.code===YD.ERR_NO_ROUTERS_AVAILABLE?(L2.error("a content router, such as a DHT, must be provided in order to advertise the relay service",e),this.stop()):L2.error(e)}}};q2.exports=k2});var lh=w((SK,uh)=>{var{AbortController:tL}=globalThis;function M2(t){let e=new tL;function r(){e.abort();for(let n of t)!n||!n.removeEventListener||n.removeEventListener("abort",r)}for(let n of t)if(!(!n||!n.addEventListener)){if(n.aborted){r();break}n.addEventListener("abort",r)}return e.signal}uh.exports=M2;uh.exports.anySignal=M2});var j2=w((AK,V2)=>{var F2=ad(),K2=rh();V2.exports=class{constructor(){this._buffer=new F2,this._waitingConsumers=new F2}push(e){let{promise:r,resolve:n}=K2();return this._buffer.push({chunk:e,resolve:n}),this._consume(),r}_consume(){for(;!this._waitingConsumers.isEmpty()&&!this._buffer.isEmpty();){let e=this._waitingConsumers.shift(),r=this._buffer.shift();e.resolve(r.chunk),r.resolve()}}shift(){let{promise:e,resolve:r}=K2();return this._waitingConsumers.push({resolve:r}),this._consume(),e}isEmpty(){return this._buffer.isEmpty()}}});var H2=w((CK,$2)=>{"use strict";$2.exports=(t,e=1,r)=>{if(r={indent:" ",includeEmptyLines:!1,...r},typeof t!="string")throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof t}\``);if(typeof e!="number")throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof e}\``);if(typeof r.indent!="string")throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof r.indent}\``);if(e===0)return t;let n=r.includeEmptyLines?/^/gm:/^(?!\s*$)/gm;return t.replace(n,r.indent.repeat(e))}});var z2=w(()=>{});var Q2=w((RK,Y2)=>{"use strict";var G2=z2(),W2=/\s+at.*(?:\(|\s)(.*)\)?/,rL=/^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/,nL=typeof G2.homedir=="undefined"?"":G2.homedir();Y2.exports=(t,e)=>(e=Object.assign({pretty:!1},e),t.replace(/\\/g,"/").split(`
40
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),fP=new RegExp(`(?:^${qr}$)|(?:^${Hc}$)`),dP=new RegExp(`^${qr}$`),hP=new RegExp(`^${Hc}$`),Lf=t=>t&&t.exact?fP:new RegExp(`(?:${ri(t)}${qr}${ri(t)})|(?:${ri(t)}${Hc}${ri(t)})`,"g");Lf.v4=t=>t&&t.exact?dP:new RegExp(`${ri(t)}${qr}${ri(t)}`,"g");Lf.v6=t=>t&&t.exact?hP:new RegExp(`${ri(t)}${Hc}${ri(t)}`,"g");lv.exports=Lf});var Uf=w((mM,fv)=>{"use strict";var qf=kf(),Us=t=>qf({exact:!0}).test(t);Us.v4=t=>qf.v4({exact:!0}).test(t);Us.v6=t=>qf.v6({exact:!0}).test(t);Us.version=t=>Us(t)?Us.v4(t)?4:6:void 0;fv.exports=Us});var gv=w((vM,yv)=>{"use strict";var Mf=Uf(),{toString:dv}=(Tt(),Ot),pP=Mf,Ff=Mf.v4,hv=Mf.v6,pv=function(t,e,r){r=~~r;let n;if(Ff(t))n=e||new Uint8Array(r+4),t.split(/\./g).map(function(i){n[r++]=parseInt(i,10)&255});else if(hv(t)){let i=t.split(":",8),s;for(s=0;s<i.length;s++){let o=Ff(i[s]),a;o&&(a=pv(i[s]),i[s]=dv(a.slice(0,2),"base16")),a&&++s<8&&i.splice(s,0,dv(a.slice(2,4),"base16"))}if(i[0]==="")for(;i.length<8;)i.unshift("0");else if(i[i.length-1]==="")for(;i.length<8;)i.push("0");else if(i.length<8){for(s=0;s<i.length&&i[s]!=="";s++);let o=[s,"1"];for(s=9-i.length;s>0;s--)o.push("0");i.splice.apply(i,o)}for(n=e||new Uint8Array(r+16),s=0;s<i.length;s++){let o=parseInt(i[s],16);n[r++]=o>>8&255,n[r++]=o&255}}if(!n)throw Error("Invalid ip address: "+t);return n},yP=function(t,e,r){e=~~e,r=r||t.length-e;let n=[],i,s=new DataView(t.buffer);if(r===4){for(let o=0;o<r;o++)n.push(t[e+o]);i=n.join(".")}else if(r===16){for(let o=0;o<r;o+=2)n.push(s.getUint16(e+o).toString(16));i=n.join(":"),i=i.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3"),i=i.replace(/:{3,4}/,"::")}return i};yv.exports={isIP:pP,isV4:Ff,isV6:hv,toBytes:pv,toString:yP}});var ha=w((bM,vv)=>{"use strict";function Jt(t){if(typeof t=="number"){if(Jt.codes[t])return Jt.codes[t];throw new Error("no protocol with code: "+t)}else if(typeof t=="string"){if(Jt.names[t])return Jt.names[t];throw new Error("no protocol with name: "+t)}throw new Error("invalid protocol id type: "+t)}var _r=-1;Jt.lengthPrefixedVarSize=_r;Jt.V=_r;Jt.table=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,_r,"ip6zone"],[53,_r,"dns","resolvable"],[54,_r,"dns4","resolvable"],[55,_r,"dns6","resolvable"],[56,_r,"dnsaddr","resolvable"],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,_r,"unix",!1,"path"],[421,_r,"ipfs"],[421,_r,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,_r,"garlic64"],[460,0,"quic"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,_r,"memory"]];Jt.names={};Jt.codes={};Jt.table.map(t=>{let e=mv.apply(null,t);return Jt.codes[e.code]=e,Jt.names[e.name]=e,null});Jt.object=mv;function mv(t,e,r,n,i){return{code:t,size:e,name:r,resolvable:Boolean(n),path:Boolean(i)}}vv.exports=Jt});var wv=w((EM,Ev)=>{Ev.exports=Kf;var bv=128,gP=127,mP=~gP,vP=Math.pow(2,31);function Kf(t,e,r){if(Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw Kf.bytes=0,new RangeError("Could not encode varint");e=e||[],r=r||0;for(var n=r;t>=vP;)e[r++]=t&255|bv,t/=128;for(;t&mP;)e[r++]=t&255|bv,t>>>=7;return e[r]=t|0,Kf.bytes=r-n+1,e}});var xv=w((wM,Sv)=>{Sv.exports=Vf;var bP=128,_v=127;function Vf(t,e){var r=0,e=e||0,n=0,i=e,s,o=t.length;do{if(i>=o||n>49)throw Vf.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=n<28?(s&_v)<<n:(s&_v)*Math.pow(2,n),n+=7}while(s>=bP);return Vf.bytes=i-e,r}});var Cv=w((_M,Av)=>{var EP=Math.pow(2,7),wP=Math.pow(2,14),_P=Math.pow(2,21),SP=Math.pow(2,28),xP=Math.pow(2,35),AP=Math.pow(2,42),CP=Math.pow(2,49),IP=Math.pow(2,56),TP=Math.pow(2,63);Av.exports=function(t){return t<EP?1:t<wP?2:t<_P?3:t<SP?4:t<xP?5:t<AP?6:t<CP?7:t<IP?8:t<TP?9:10}});var Ui=w((SM,Iv)=>{Iv.exports={encode:wv(),decode:xv(),encodingLength:Cv()}});var Lv=w((xM,Dv)=>{"use strict";var zc=gv(),Tv=ha(),{CID:RP}=(ws(),ko),{base32:Rv}=(wi(),Ei),{base58btc:BP}=(qn(),kn),PP=(bi(),Do),Ms=Ui(),{toString:Gc}=(Tt(),Ot),{fromString:Bv}=(It(),Nt),{concat:Wc}=(Yn(),Wn);Dv.exports=pa;function pa(t,e){return e instanceof Uint8Array?pa.toString(t,e):pa.toBytes(t,e)}pa.toString=function(e,r){switch(Tv(e).code){case 4:case 41:return NP(r);case 6:case 273:case 33:case 132:return Nv(r).toString();case 53:case 54:case 55:case 56:case 400:case 777:return DP(r);case 421:return kP(r);case 444:return Ov(r);case 445:return Ov(r);default:return Gc(r,"base16")}};pa.toBytes=function(e,r){switch(Tv(e).code){case 4:return Pv(r);case 41:return Pv(r);case 6:case 273:case 33:case 132:return jf(parseInt(r,10));case 53:case 54:case 55:case 56:case 400:case 777:return OP(r);case 421:return LP(r);case 444:return qP(r);case 445:return UP(r);default:return Bv(r,"base16")}};function Pv(t){if(!zc.isIP(t))throw new Error("invalid ip address");return zc.toBytes(t)}function NP(t){let e=zc.toString(t);if(!e||!zc.isIP(e))throw new Error("invalid ip address");return e}function jf(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function Nv(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function OP(t){let e=Bv(t),r=Uint8Array.from(Ms.encode(e.length));return Wc([r,e],r.length+e.length)}function DP(t){let e=Ms.decode(t);if(t=t.slice(Ms.decode.bytes),t.length!==e)throw new Error("inconsistent lengths");return Gc(t)}function LP(t){let e;t[0]==="Q"||t[0]==="1"?e=PP.decode(BP.decode(`z${t}`)).bytes:e=RP.parse(t).multihash.bytes;let r=Uint8Array.from(Ms.encode(e.length));return Wc([r,e],r.length+e.length)}function kP(t){let e=Ms.decode(t),r=t.slice(Ms.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return Gc(r,"base58btc")}function qP(t){let e=t.split(":");if(e.length!==2)throw new Error("failed to parse onion addr: "+e+" 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 r=Rv.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 i=jf(n);return Wc([r,i],r.length+i.length)}function UP(t){let e=t.split(":");if(e.length!==2)throw new Error("failed to parse onion addr: "+e+" 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 r=Rv.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 i=jf(n);return Wc([r,i],r.length+i.length)}function Ov(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=Gc(e,"base32"),i=Nv(r);return n+":"+i}});var Gv=w((AM,zv)=>{"use strict";var kv=Lv(),$f=ha(),ya=Ui(),{concat:qv}=(Yn(),Wn),{toString:MP}=(Tt(),Ot);zv.exports={stringToStringTuples:Uv,stringTuplesToString:Mv,tuplesToStringTuples:Kv,stringTuplesToTuples:Fv,bytesToTuples:Hf,tuplesToBytes:Vv,bytesToString:FP,stringToBytes:$v,fromString:KP,fromBytes:Hv,validateBytes:zf,isValidBytes:VP,cleanPath:Yc,ParseError:Gf,protoFromTuple:ga,sizeForAddr:jv};function Uv(t){let e=[],r=t.split("/").slice(1);if(r.length===1&&r[0]==="")return[];for(let n=0;n<r.length;n++){let i=r[n],s=$f(i);if(s.size===0){e.push([i]);continue}if(n++,n>=r.length)throw Gf("invalid address: "+t);if(s.path){e.push([i,Yc(r.slice(n).join("/"))]);break}e.push([i,r[n]])}return e}function Mv(t){let e=[];return t.map(r=>{let n=ga(r);return e.push(n.name),r.length>1&&e.push(r[1]),null}),Yc(e.join("/"))}function Fv(t){return t.map(e=>{Array.isArray(e)||(e=[e]);let r=ga(e);return e.length>1?[r.code,kv.toBytes(r.code,e[1])]:[r.code]})}function Kv(t){return t.map(e=>{let r=ga(e);return e[1]?[r.code,kv.toString(r.code,e[1])]:[r.code]})}function Vv(t){return Hv(qv(t.map(e=>{let r=ga(e),n=Uint8Array.from(ya.encode(r.code));return e.length>1&&(n=qv([n,e[1]])),n})))}function jv(t,e){return t.size>0?t.size/8:t.size===0?0:ya.decode(e)+ya.decode.bytes}function Hf(t){let e=[],r=0;for(;r<t.length;){let n=ya.decode(t,r),i=ya.decode.bytes,s=$f(n),o=jv(s,t.slice(r+i));if(o===0){e.push([n]),r+=i;continue}let a=t.slice(r+i,r+i+o);if(r+=o+i,r>t.length)throw Gf("Invalid address Uint8Array: "+MP(t,"base16"));e.push([n,a])}return e}function FP(t){let e=Hf(t),r=Kv(e);return Mv(r)}function $v(t){t=Yc(t);let e=Uv(t),r=Fv(e);return Vv(r)}function KP(t){return $v(t)}function Hv(t){let e=zf(t);if(e)throw e;return Uint8Array.from(t)}function zf(t){try{Hf(t)}catch(e){return e}}function VP(t){return zf(t)===void 0}function Yc(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}function Gf(t){return new Error("Error parsing address: "+t)}function ga(t){return $f(t[0])}});var qt=w((CM,Qv)=>{"use strict";var Ur=Gv(),Fs=ha(),Wv=Ui(),{CID:jP}=(ws(),ko),{base58btc:$P}=(qn(),kn),HP=de(),zP=Symbol.for("nodejs.util.inspect.custom"),{toString:Qc}=(Tt(),Ot),{equals:GP}=(mr(),gr),Wf=new Map,Yv=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Ht=class{constructor(e){if(e==null&&(e=""),Object.defineProperty(this,Yv,{value:!0}),e instanceof Uint8Array)this.bytes=Ur.fromBytes(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=Ur.fromString(e)}else if(Ht.isMultiaddr(e))this.bytes=Ur.fromBytes(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return Ur.bytesToString(this.bytes)}toJSON(){return this.toString()}toOptions(){let e={},r=this.toString().split("/");return e.family=r[1]==="ip4"?4:6,e.host=r[2],e.transport=r[3],e.port=parseInt(r[4]),e}protos(){return this.protoCodes().map(e=>Object.assign({},Fs(e)))}protoCodes(){let e=[],r=this.bytes,n=0;for(;n<r.length;){let i=Wv.decode(r,n),s=Wv.decode.bytes,o=Fs(i);n+=Ur.sizeForAddr(o,r.slice(n+s))+s,e.push(i)}return e}protoNames(){return this.protos().map(e=>e.name)}tuples(){return Ur.bytesToTuples(this.bytes)}stringTuples(){let e=Ur.bytesToTuples(this.bytes);return Ur.tuplesToStringTuples(e)}encapsulate(e){return e=new Ht(e),new Ht(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error("Address "+this+" does not contain subaddress: "+e);return new Ht(n.slice(0,i))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new Ht(Ur.tuplesToBytes(r.slice(0,n)));return this}getPeerId(){try{let r=this.stringTuples().filter(n=>n[0]===Fs.names.ipfs.code).pop();if(r&&r[1]){let n=r[1];return n[0]==="Q"||n[0]==="1"?Qc($P.decode(`z${n}`),"base58btc"):Qc(jP.parse(n).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){let e=null;try{e=this.stringTuples().filter(r=>!!Fs(r[0]).path)[0][1],e||(e=null)}catch(r){e=null}return e}equals(e){return GP(this.bytes,e.bytes)}async resolve(){let e=this.protos().find(i=>i.resolvable);if(!e)return[this];let r=Wf.get(e.name);if(!r)throw HP(new Error(`no available resolver for ${e.name}`),"ERR_NO_AVAILABLE_RESOLVER");return(await r(this)).map(i=>new Ht(i))}nodeAddress(){let e=this.protoCodes(),r=this.protoNames(),n=this.toString().split("/").slice(1);if(n.length<4)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6}/{address}/{tcp, udp}/{port}".');if(e[0]!==4&&e[0]!==41&&e[0]!==54&&e[0]!==55)throw new Error(`no protocol with name: "'${r[0]}'". Must have a valid family name: "{ip4, ip6, dns4, dns6}".`);if(n[2]!=="tcp"&&n[2]!=="udp")throw new Error(`no protocol with name: "'${r[1]}'". Must have a valid transport protocol: "{tcp, udp}".`);return{family:e[0]===41||e[0]===55?6:4,address:n[1],port:parseInt(n[3])}}isThinWaistAddress(e){let r=(e||this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}static fromNodeAddress(e,r){if(!e)throw new Error("requires node address object");if(!r)throw new Error("requires transport protocol");let n;switch(e.family){case 4:n="ip4";break;case 6:n="ip6";break;default:throw Error(`Invalid addr family. Got '${e.family}' instead of 4 or 6`)}return new Ht("/"+[n,e.address,r,e.port].join("/"))}static isName(e){return Ht.isMultiaddr(e)?e.protos().some(r=>r.resolvable):!1}static isMultiaddr(e){return e instanceof Ht||Boolean(e&&e[Yv])}[zP](){return"<Multiaddr "+Qc(this.bytes,"base16")+" - "+Ur.bytesToString(this.bytes)+">"}inspect(){return"<Multiaddr "+Qc(this.bytes,"base16")+" - "+Ur.bytesToString(this.bytes)+">"}};Ht.protocols=Fs;Ht.resolvers=Wf;function WP(t){return new Ht(t)}Qv.exports={Multiaddr:Ht,multiaddr:WP,protocols:Fs,resolvers:Wf}});var Mi=w((IM,Xv)=>{"use strict";var YP=async t=>{let e=[];for await(let r of t)e.push(r);return e};Xv.exports=YP});var Zv,Yf,Jv=Se(()=>{Zv=Po(Mi()),Yf=(t,e)=>async function*(){yield*(await(0,Zv.default)(t)).sort(e)}()});var ma=w((RM,e1)=>{"use strict";var QP=async t=>{for await(let e of t);};e1.exports=QP});var Fi=w((BM,t1)=>{"use strict";var XP=async function*(t,e){for await(let r of t)await e(r)&&(yield r)};t1.exports=XP});var Qf=w((PM,r1)=>{"use strict";var ZP=async function*(t,e){let r=0;if(!(e<1)){for await(let n of t)if(yield n,r++,r===e)return}};r1.exports=ZP});var Xf,Ki,Zf,Jf,n1=Se(()=>{Jv();Xf=Po(ma()),Ki=Po(Fi()),Zf=Po(Qf()),Jf=class{open(){return Promise.reject(new Error(".open is not implemented"))}close(){return Promise.reject(new Error(".close is not implemented"))}put(e,r,n){return Promise.reject(new Error(".put is not implemented"))}get(e,r){return Promise.reject(new Error(".get is not implemented"))}has(e,r){return Promise.reject(new Error(".has is not implemented"))}delete(e,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,r={}){for await(let{key:n,value:i}of e)await this.put(n,i,r),yield{key:n,value:i}}async*getMany(e,r={}){for await(let n of e)yield this.get(n,r)}async*deleteMany(e,r={}){for await(let n of e)await this.delete(n,r),yield n}batch(){let e=[],r=[];return{put(n,i){e.push({key:n,value:i})},delete(n){r.push(n)},commit:async n=>{await(0,Xf.default)(this.putMany(e,n)),e=[],await(0,Xf.default)(this.deleteMany(r,n)),r=[]}}}async*_all(e,r){throw new Error("._all is not implemented")}async*_allKeys(e,r){throw new Error("._allKeys is not implemented")}query(e,r){let n=this._all(e,r);if(e.prefix!=null&&(n=(0,Ki.default)(n,i=>i.key.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>(0,Ki.default)(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>Yf(i,s),n)),e.offset!=null){let i=0;n=(0,Ki.default)(n,()=>i++>=e.offset)}return e.limit!=null&&(n=(0,Zf.default)(n,e.limit)),n}queryKeys(e,r){let n=this._allKeys(e,r);if(e.prefix!=null&&(n=(0,Ki.default)(n,i=>i.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>(0,Ki.default)(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>Yf(i,s),n)),e.offset!=null){let i=0;n=(0,Ki.default)(n,()=>i++>=e.offset)}return e.limit!=null&&(n=(0,Zf.default)(n,e.limit)),n}}});var i1,s1=Se(()=>{i1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"});var td={};gt(td,{customAlphabet:()=>JP,customRandom:()=>a1,nanoid:()=>ed,random:()=>o1,urlAlphabet:()=>i1});var o1,a1,JP,ed,Xc=Se(()=>{s1();o1=t=>crypto.getRandomValues(new Uint8Array(t)),a1=(t,e,r)=>{let n=(2<<Math.log(t.length-1)/Math.LN2)-1,i=-~(1.6*n*e/t.length);return()=>{let s="";for(;;){let o=r(i),a=i;for(;a--;)if(s+=t[o[a]&n]||"",s.length===e)return s}}},JP=(t,e)=>a1(t,e,o1),ed=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t));for(;t--;){let n=r[t]&63;n<36?e+=n.toString(36):n<62?e+=(n-26).toString(36).toUpperCase():n<63?e+="_":e+="-"}return e}});var rd={};gt(rd,{Key:()=>Bt});function eN(t){let e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function tN(t){let e=t.split(":");return e[e.length-1]}function rN(t){return[].concat(...t)}var An,c1,Zc,Bt,Jc=Se(()=>{Xc();Tt();It();An="/",c1=new TextEncoder().encode(An),Zc=c1[0],Bt=class{constructor(e,r){if(typeof e=="string")this._buf=cf(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(r==null&&(r=!0),r&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Zc)throw new Error("Invalid key")}toString(e="utf8"){return lf(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Bt(e.join(An))}static random(){return new Bt(ed().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new Bt(e):e.uint8Array?new Bt(e.uint8Array()):null}clean(){if((!this._buf||this._buf.byteLength===0)&&(this._buf=c1),this._buf[0]!==Zc){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Zc,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Zc;)this._buf=this._buf.subarray(0,-1)}less(e){let r=this.list(),n=e.list();for(let i=0;i<r.length;i++){if(n.length<i+1)return!1;let s=r[i],o=n[i];if(s<o)return!0;if(s>o)return!1}return r.length<n.length}reverse(){return Bt.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(An).slice(1)}type(){return eN(this.baseNamespace())}name(){return tN(this.baseNamespace())}instance(e){return new Bt(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(An)||(e+=An),e+=this.type(),new Bt(e)}parent(){let e=this.list();return e.length===1?new Bt(An):new Bt(e.slice(0,-1).join(An))}child(e){return this.toString()===An?e:e.toString()===An?this:new Bt(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 Bt.withNamespaces([...this.namespaces(),...rN(e.map(r=>r.namespaces()))])}}});function l1(t){return t=t||new Error("Not Found"),(0,u1.default)(t,"ERR_NOT_FOUND")}var u1,f1=Se(()=>{u1=Po(de())});var h1={};gt(h1,{MemoryDatastore:()=>d1});var d1,p1=Se(()=>{n1();Jc();f1();d1=class extends Jf{constructor(){super();this.data={}}open(){return Promise.resolve()}close(){return Promise.resolve()}async put(e,r){this.data[e.toString()]=r}async get(e){if(!await this.has(e))throw l1();return this.data[e.toString()]}async has(e){return this.data[e.toString()]!==void 0}async delete(e){delete this.data[e.toString()]}async*_all(){yield*Object.entries(this.data).map(([e,r])=>({key:new Bt(e),value:r}))}async*_allKeys(){yield*Object.entries(this.data).map(([e])=>new Bt(e))}}});var je=w(nd=>{"use strict";nd.messages={NOT_STARTED_YET:"The libp2p node is not started yet",DHT_DISABLED:"DHT is not available",CONN_ENCRYPTION_REQUIRED:"At least one connection encryption module is required",NOT_FOUND:"Not found"};nd.codes={DHT_DISABLED:"ERR_DHT_DISABLED",PUBSUB_NOT_STARTED:"ERR_PUBSUB_NOT_STARTED",DHT_NOT_STARTED:"ERR_DHT_NOT_STARTED",CONN_ENCRYPTION_REQUIRED:"ERR_CONN_ENCRYPTION_REQUIRED",ERR_PEER_DIAL_INTERCEPTED:"ERR_PEER_DIAL_INTERCEPTED",ERR_CONNECTION_INTERCEPTED:"ERR_CONNECTION_INTERCEPTED",ERR_INVALID_PROTOCOLS_FOR_STREAM:"ERR_INVALID_PROTOCOLS_FOR_STREAM",ERR_CONNECTION_ENDED:"ERR_CONNECTION_ENDED",ERR_CONNECTION_FAILED:"ERR_CONNECTION_FAILED",ERR_NODE_NOT_STARTED:"ERR_NODE_NOT_STARTED",ERR_ALREADY_ABORTED:"ERR_ALREADY_ABORTED",ERR_TOO_MANY_ADDRESSES:"ERR_TOO_MANY_ADDRESSES",ERR_NO_VALID_ADDRESSES:"ERR_NO_VALID_ADDRESSES",ERR_RELAYED_DIAL:"ERR_RELAYED_DIAL",ERR_DIALED_SELF:"ERR_DIALED_SELF",ERR_DISCOVERED_SELF:"ERR_DISCOVERED_SELF",ERR_DUPLICATE_TRANSPORT:"ERR_DUPLICATE_TRANSPORT",ERR_ENCRYPTION_FAILED:"ERR_ENCRYPTION_FAILED",ERR_HOP_REQUEST_FAILED:"ERR_HOP_REQUEST_FAILED",ERR_INVALID_KEY:"ERR_INVALID_KEY",ERR_INVALID_MESSAGE:"ERR_INVALID_MESSAGE",ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS",ERR_INVALID_PEER:"ERR_INVALID_PEER",ERR_MUXER_UNAVAILABLE:"ERR_MUXER_UNAVAILABLE",ERR_NOT_FOUND:"ERR_NOT_FOUND",ERR_TIMEOUT:"ERR_TIMEOUT",ERR_TRANSPORT_UNAVAILABLE:"ERR_TRANSPORT_UNAVAILABLE",ERR_TRANSPORT_DIAL_FAILED:"ERR_TRANSPORT_DIAL_FAILED",ERR_UNSUPPORTED_PROTOCOL:"ERR_UNSUPPORTED_PROTOCOL",ERR_INVALID_MULTIADDR:"ERR_INVALID_MULTIADDR",ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID",ERR_FIND_SELF:"ERR_FIND_SELF",ERR_NO_ROUTERS_AVAILABLE:"ERR_NO_ROUTERS_AVAILABLE",ERR_CONNECTION_NOT_MULTIPLEXED:"ERR_CONNECTION_NOT_MULTIPLEXED",ERR_NO_DIAL_TOKENS:"ERR_NO_DIAL_TOKENS",ERR_KEYCHAIN_REQUIRED:"ERR_KEYCHAIN_REQUIRED",ERR_INVALID_CMS:"ERR_INVALID_CMS",ERR_MISSING_KEYS:"ERR_MISSING_KEYS",ERR_NO_KEY:"ERR_NO_KEY",ERR_INVALID_KEY_NAME:"ERR_INVALID_KEY_NAME",ERR_INVALID_KEY_TYPE:"ERR_INVALID_KEY_TYPE",ERR_KEY_ALREADY_EXISTS:"ERR_KEY_ALREADY_EXISTS",ERR_INVALID_KEY_SIZE:"ERR_INVALID_KEY_SIZE",ERR_KEY_NOT_FOUND:"ERR_KEY_NOT_FOUND",ERR_OLD_KEY_NAME_INVALID:"ERR_OLD_KEY_NAME_INVALID",ERR_NEW_KEY_NAME_INVALID:"ERR_NEW_KEY_NAME_INVALID",ERR_PASSWORD_REQUIRED:"ERR_PASSWORD_REQUIRED",ERR_PEM_REQUIRED:"ERR_PEM_REQUIRED",ERR_CANNOT_READ_KEY:"ERR_CANNOT_READ_KEY",ERR_MISSING_PRIVATE_KEY:"ERR_MISSING_PRIVATE_KEY",ERR_INVALID_OLD_PASS_TYPE:"ERR_INVALID_OLD_PASS_TYPE",ERR_INVALID_NEW_PASS_TYPE:"ERR_INVALID_NEW_PASS_TYPE",ERR_INVALID_PASS_LENGTH:"ERR_INVALID_PASS_LENGTH",ERR_NOT_IMPLEMENTED:"ERR_NOT_IMPLEMENTED",ERR_WRONG_PING_ACK:"ERR_WRONG_PING_ACK"}});var id=w(($M,y1)=>{"use strict";var nN=async function*(t,e){for await(let r of t)yield e(r)};y1.exports=nN});var sd=w((HM,g1)=>{"use strict";var iN=de(),sN=Fi(),oN=id(),aN=Qf();async function*cN(t,e){yield*oN(t,async r=>(await e.addressBook.add(r.id,r.multiaddrs),r))}function uN(t){let e=new Set;return sN(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*lN(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw iN(new Error("not found"),"NOT_FOUND")}function fN(t,e){return e?aN(t,e):t}g1.exports={storeAddresses:cN,uniquePeers:uN,requirePeers:lN,maybeLimitSource:fN}});var v1=w((zM,m1)=>{"use strict";m1.exports=function(){return Date.now()}});var va=w((GM,E1)=>{"use strict";var eu=v1(),b1=class{constructor(e,r,n){let i=this;this._started=eu(),this._rescheduled=0,this._scheduled=r,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(eu()-i._started),i._schedule(i._scheduled)):(i._triggered=!0,e.apply(null,i._args))},this._timer=setTimeout(this._timerWrapper,r)}reschedule(e){e||(e=this._scheduled);let r=eu();r+e-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(e)):this._triggered?this._schedule(e):(this._started=r,this._rescheduled=e)}_schedule(e){this._triggered=!1,this._started=eu(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function dN(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let t;if(arguments.length>0){t=new Array(arguments.length-2);for(var e=0;e<t.length;e++)t[e]=arguments[e+2]}return new b1(arguments[0],arguments[1],t)}E1.exports=dN});var od=w((WM,_1)=>{"use strict";var{AbortController:hN}=globalThis,w1=va(),tu=class extends hN{constructor(e){super();this._ms=e,this._timer=w1(()=>this.abort(),e),Object.setPrototypeOf(this,tu.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=w1(()=>this.abort(),this._ms)}};_1.exports={TimeoutController:tu}});var x1=w((QM,S1)=>{S1.exports=class{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}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var ad=w((ZM,C1)=>{var A1=x1();C1.exports=class{constructor(e){this.hwm=e||16,this.head=new A1(this.hwm),this.tail=this.head}push(e){if(!this.head.push(e)){let r=this.head;this.head=r.next=new A1(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next){let r=this.tail.next;return this.tail.next=null,this.tail=r,this.tail.shift()}return e}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}});var ud=w((JM,I1)=>{var cd=ad();I1.exports=t=>{t=t||{};let e;typeof t=="function"?(e=t,t={}):e=t.onEnd;let r=new cd,n,i,s,o=()=>{if(!r.isEmpty()){if(t.writev){let g,m=[];for(;!r.isEmpty();){if(g=r.shift(),g.error)throw g.error;m.push(g.value)}return{done:g.done,value:m}}let h=r.shift();if(h.error)throw h.error;return h}return s?{done:!0}:new Promise((h,g)=>{i=m=>(i=null,m.error?g(m.error):t.writev&&!m.done?h({done:m.done,value:[m.value]}):h(m),n)})},a=h=>i?i(h):(r.push(h),n),c=h=>(r=new cd,i?i({error:h}):(r.push({error:h}),n)),u=h=>s?n:a({done:!1,value:h}),l=h=>s?n:(s=!0,h?c(h):a({done:!0})),f=()=>(r=new cd,l(),{done:!0}),d=h=>(l(h),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:o,return:f,throw:d,push:u,end:l},!e)return n;let p=n;return n={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(h){return p.throw(h),e&&(e(h),e=null),{done:!0}},return(){return p.return(),e&&(e(),e=null),{done:!0}},push:u,end(h){return p.end(h),e&&(e(h),e=null),n}},n}});var ld=w((eF,T1)=>{"use strict";var pN=ud(),yN=async function*(...t){let e=pN();setTimeout(async()=>{try{await Promise.all(t.map(async r=>{for await(let n of r)e.push(n)})),e.end()}catch(r){e.end(r)}},0),yield*e};T1.exports=yN});var ir=w((tF,Ks)=>{var R1=(...t)=>{let e;for(;t.length;)e=t.shift()(e);return e},fd=t=>t&&(typeof t[Symbol.asyncIterator]=="function"||typeof t[Symbol.iterator]=="function"||typeof t.next=="function"),ru=t=>t&&typeof t.sink=="function"&&fd(t.source),gN=t=>e=>(t.sink(e),t.source),B1=(...t)=>{if(ru(t[0])){let e=t[0];t[0]=()=>e.source}else if(fd(t[0])){let e=t[0];t[0]=()=>e}if(t.length>1&&ru(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let e=1;e<t.length-1;e++)ru(t[e])&&(t[e]=gN(t[e]));return R1(...t)};Ks.exports=B1;Ks.exports.pipe=B1;Ks.exports.rawPipe=R1;Ks.exports.isIterable=fd;Ks.exports.isDuplex=ru});var dd=w((rF,P1)=>{"use strict";var mN=async t=>{for await(let e of t)return e};P1.exports=mN});var hd=w((nF,N1)=>{"use strict";var Vs=new Map,vN=()=>`${Date.now()}:${Math.floor(Math.random()*1e6)}`;async function bN(t,e,r){for(;Vs.get(r);){try{await t()}catch(n){setTimeout(()=>{throw n},1);break}if(!Vs.get(r))break;await new Promise(n=>{let i=setTimeout(n,e);Vs.set(r,i)})}}function EN(t,e,r){r=r||e;let n=vN(),i=setTimeout(()=>{bN(t,e,n)},r);return Vs.set(n,i),n}function wN(t){let e=Vs.get(t);e&&(clearTimeout(e),Vs.delete(t))}N1.exports={setDelayedInterval:EN,clearDelayedInterval:wN}});var L1=w((iF,D1)=>{"use strict";var _N=de(),{messages:SN,codes:xN}=je(),O1=class{constructor(e){this._dht=e}async findPeer(e,r={}){for await(let n of this._dht.findPeer(e,r))if(n.name==="FINAL_PEER")return n.peer;throw _N(new Error(SN.NOT_FOUND),xN.ERR_NOT_FOUND)}async*getClosestPeers(e,r={}){for await(let n of this._dht.getClosestPeers(e,r))n.name==="PEER_RESPONSE"&&(yield*n.closer)}};D1.exports={DHTPeerRouting:O1}});var $1=w((sF,j1)=>{"use strict";var k1=Te(),q1=Object.assign(k1("libp2p:peer-routing"),{error:k1("libp2p:peer-routing:err")}),nu=de(),ba=je(),{storeAddresses:U1,uniquePeers:AN,requirePeers:CN}=sd(),{TimeoutController:IN}=od(),M1=ld(),{pipe:F1}=ir(),TN=dd(),RN=ma(),BN=Fi(),{setDelayedInterval:PN,clearDelayedInterval:NN}=hd(),{DHTPeerRouting:ON}=L1(),{setMaxListeners:K1}=Qt(),V1=class{constructor(e){this._peerId=e.peerId,this._peerStore=e.peerStore,this._routers=e._modules.peerRouting||[],e._dht&&e._config.dht.enabled&&this._routers.push(new ON(e._dht)),this._refreshManagerOptions=e._options.peerRouting.refreshManager,this._findClosestPeersTask=this._findClosestPeersTask.bind(this)}start(){!this._routers.length||this._timeoutId||!this._refreshManagerOptions.enabled||(this._timeoutId=PN(this._findClosestPeersTask,this._refreshManagerOptions.interval,this._refreshManagerOptions.bootDelay))}async _findClosestPeersTask(){try{await RN(this.getClosestPeers(this._peerId.id,{timeout:this._refreshManagerOptions.timeout||1e4}))}catch(e){q1.error(e)}}stop(){NN(this._timeoutId)}async findPeer(e,r){if(!this._routers.length)throw nu(new Error("No peer routers available"),ba.codes.ERR_NO_ROUTERS_AVAILABLE);if(e.toB58String()===this._peerId.toB58String())throw nu(new Error("Should not try to find self"),ba.codes.ERR_FIND_SELF);let n=await F1(M1(...this._routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(s){q1.error(s)}}())),i=>BN(i,Boolean),i=>U1(i,this._peerStore),i=>TN(i));if(n)return n;throw nu(new Error(ba.messages.NOT_FOUND),ba.codes.ERR_NOT_FOUND)}async*getClosestPeers(e,r={timeout:3e4}){if(!this._routers.length)throw nu(new Error("No peer routers available"),ba.codes.ERR_NO_ROUTERS_AVAILABLE);if(r.timeout){let n=new IN(r.timeout);try{K1&&K1(1/0,n.signal)}catch{}r.signal=n.signal}yield*F1(M1(...this._routers.map(n=>n.getClosestPeers(e,r))),n=>U1(n,this._peerStore),n=>AN(n),n=>CN(n))}};j1.exports=V1});var G1=w((oF,z1)=>{"use strict";var DN=ma(),H1=class{constructor(e){this._dht=e}async provide(e){await DN(this._dht.provide(e))}async*findProviders(e,r){for await(let n of this._dht.findProviders(e,r))n.name==="PROVIDER"&&(yield*n.providers)}};z1.exports={DHTContentRouting:H1}});var Q1=w((aF,Y1)=>{"use strict";var Vi=de(),{messages:Ea,codes:ji}=je(),{storeAddresses:LN,uniquePeers:kN,requirePeers:qN,maybeLimitSource:UN}=sd(),MN=ma(),FN=ld(),{pipe:KN}=ir(),{DHTContentRouting:VN}=G1(),W1=class{constructor(e){this.libp2p=e,this.routers=e._modules.contentRouting||[],this.dht=e._dht,this.dht&&e._config.dht.enabled&&this.routers.push(new VN(this.dht))}async*findProviders(e,r={}){if(!this.routers.length)throw Vi(new Error("No content this.routers available"),ji.ERR_NO_ROUTERS_AVAILABLE);yield*KN(FN(...this.routers.map(n=>n.findProviders(e,r))),n=>LN(n,this.libp2p.peerStore),n=>kN(n),n=>UN(n,r.maxNumProviders),n=>qN(n))}async provide(e){if(!this.routers.length)throw Vi(new Error("No content routers available"),ji.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(r=>r.provide(e)))}async put(e,r,n){if(!this.libp2p.isStarted()||!this.dht.isStarted)throw Vi(new Error(Ea.NOT_STARTED_YET),ji.DHT_NOT_STARTED);await MN(this.dht.put(e,r,n))}async get(e,r){if(!this.libp2p.isStarted()||!this.dht.isStarted)throw Vi(new Error(Ea.NOT_STARTED_YET),ji.DHT_NOT_STARTED);for await(let n of this.dht.get(e,r))if(n.name==="VALUE")return{from:n.peerId,val:n.value};throw Vi(new Error(Ea.NOT_FOUND),ji.ERR_NOT_FOUND)}async*getMany(e,r,n){if(!this.libp2p.isStarted()||!this.dht.isStarted)throw Vi(new Error(Ea.NOT_STARTED_YET),ji.DHT_NOT_STARTED);if(!r)return;let i=0;for await(let s of this.dht.get(e,n))if(s.name==="VALUE"&&(yield{from:s.peerId,val:s.value},i++,i===r))break;if(i===0)throw Vi(new Error(Ea.NOT_FOUND),ji.ERR_NOT_FOUND)}};Y1.exports=W1});var pd=w((cF,eb)=>{"use strict";var jN=Rt(),{Multiaddr:X1}=qt(),Z1=de(),{codes:J1}=je();function $N(t){typeof t=="string"&&(t=new X1(t));let e;if(X1.isMultiaddr(t)){e=t;let r=t.getPeerId();if(!r)throw Z1(new Error(`${t} does not have a valid peer type`),J1.ERR_INVALID_MULTIADDR);try{t=jN.createFromB58String(r)}catch(n){throw Z1(new Error(`${t} is not a valid peer type`),J1.ERR_INVALID_MULTIADDR)}}return{id:t,multiaddrs:e?[e]:void 0}}eb.exports=$N});var rb=w((uF,tb)=>{"use strict";tb.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var Hs=w((ob,ab)=>{"use strict";var iu=rb(),{hasOwnProperty:nb}=Object.prototype,{propertyIsEnumerable:HN}=Object,js=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),zN=ob,ib={concatArrays:!1,ignoreUndefined:!1},su=t=>{let e=[];for(let r in t)nb.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let n of r)HN.call(t,n)&&e.push(n)}return e};function $s(t){return Array.isArray(t)?GN(t):iu(t)?WN(t):t}function GN(t){let e=t.slice(0,0);return su(t).forEach(r=>{js(e,r,$s(t[r]))}),e}function WN(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return su(t).forEach(r=>{js(e,r,$s(t[r]))}),e}var sb=(t,e,r,n)=>(r.forEach(i=>{typeof e[i]=="undefined"&&n.ignoreUndefined||(i in t&&t[i]!==Object.getPrototypeOf(t)?js(t,i,yd(t[i],e[i],n)):js(t,i,$s(e[i])))}),t),YN=(t,e,r)=>{let n=t.slice(0,0),i=0;return[t,e].forEach(s=>{let o=[];for(let a=0;a<s.length;a++)!nb.call(s,a)||(o.push(String(a)),s===t?js(n,i++,s[a]):js(n,i++,$s(s[a])));n=sb(n,s,su(s).filter(a=>!o.includes(a)),r)}),n};function yd(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?YN(t,e,r):!iu(e)||!iu(t)?$s(e):sb(t,e,su(e),r)}ab.exports=function(...t){let e=yd($s(ib),this!==zN&&this||{},ib),r={_:{}};for(let n of t)if(n!==void 0){if(!iu(n))throw new TypeError("`"+n+"` is not an Option Object");r=yd(r,{_:n},e)}return r._}});var lb=w((lF,ub)=>{"use strict";ub.exports=cb;var QN=ul(),ni=cb.prototype,XN=new Date%1e9;function ZN(){return(Math.random()*1e9>>>0)+XN++}function cb(t){t=t||{},this.id=t.id||ZN(),this.max=t.max||1/0,this.items=t.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(t.lastModified||new Date);for(var e,r,n=this.items.length;n--;)e=this.items[n],r=new Date(e.expires)-new Date,this._lookup[e.key]=e,r>0?this.expire(e.key,r):r<=0&&this.delete(e.key)}ni.has=function(t){return t in this._lookup};ni.get=function(t){if(!this.has(t))return null;var e=this._lookup[t];return e.refresh&&this.expire(t,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};ni.meta=function(t){if(!this.has(t))return null;var e=this._lookup[t];return"meta"in e?e.meta:null};ni.set=function(t,e,r){var n=this._lookup[t],i=this._lookup[t]={key:t,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,i)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(i),this.size++),r&&("ttl"in r&&this.expire(t,r.ttl),"meta"in r&&(i.meta=r.meta),r.refresh&&(i.refresh=r.ttl)),this};ni.delete=function(t){var e=this._lookup[t];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[t],this.size--,this):!1};ni.expire=function(t,e){var r=e||0,n=this._lookup[t];if(!n)return this;if(typeof r=="string"&&(r=QN(e)),typeof r!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),r),n.expires=Number(new Date)+r,this};ni.clear=function(){for(var t=this.items.length;t--;)this.delete(this.items[t].key);return this};ni.toJSON=function(){for(var t=new Array(this.items.length),e,r=t.length;r--;)e=this.items[r],t[r]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:t}}});var wa=w((zs,fb)=>{"use strict";var JN=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof Cn!="undefined")return Cn;throw new Error("unable to locate global object")},Cn=JN();fb.exports=zs=Cn.fetch;Cn.fetch&&(zs.default=Cn.fetch.bind(Cn));zs.Headers=Cn.Headers;zs.Request=Cn.Request;zs.Response=Cn.Response});var db=w((fF,gd)=>{"use strict";globalThis.fetch&&globalThis.Headers&&globalThis.Request&&globalThis.Response?gd.exports={default:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response}:gd.exports={default:wa().default,Headers:wa().Headers,Request:wa().Request,Response:wa().Response}});var pb=w((dF,hb)=>{"use strict";var{default:e3,Headers:t3}=db();function r3({serverResolver:t,hostname:e,recordType:r}){return`${t}?name=${e}&type=${r}`}function n3(t){return e3(t,{headers:new t3({accept:"application/dns-json"})})}function i3(t,e){return`${e}_${t}`}hb.exports={buildResource:r3,fetch:n3,getCacheKey:i3}});var mb=w((hF,gb)=>{"use strict";var yb=Te(),ou=yb("dns-over-http-resolver");ou.error=yb("dns-over-http-resolver:error");var s3=lb(),Sr=pb(),au=class{constructor({maxCache:e=100}={}){this._cache=new s3({max:e}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"]}getServers(){return this._servers}_getShuffledServers(){let e=[].concat(this._servers);for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}resolve(e,r="A"){switch(r){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(Sr.getCacheKey(e,r));if(n)return n;for(let i of this._getShuffledServers())try{let o=await(await Sr.fetch(Sr.buildResource({serverResolver:i,hostname:e,recordType:r}))).json(),a=o.Answer.map(u=>u.data),c=Math.min(o.Answer.map(u=>u.TTL));return this._cache.set(Sr.getCacheKey(e,r),a,{ttl:c}),a}catch(s){ou.error(`${i} could not resolve ${e} record ${r}`)}throw new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(Sr.getCacheKey(e,r));if(n)return n;for(let i of this._getShuffledServers())try{let o=await(await Sr.fetch(Sr.buildResource({serverResolver:i,hostname:e,recordType:r}))).json(),a=o.Answer.map(u=>u.data),c=Math.min(o.Answer.map(u=>u.TTL));return this._cache.set(Sr.getCacheKey(e,r),a,{ttl:c}),a}catch(s){ou.error(`${i} could not resolve ${e} record ${r}`)}throw new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._cache.get(Sr.getCacheKey(e,r));if(n)return n;for(let i of this._getShuffledServers())try{let o=await(await Sr.fetch(Sr.buildResource({serverResolver:i,hostname:e,recordType:r}))).json(),a=o.Answer.map(u=>[u.data.replace(/['"]+/g,"")]),c=Math.min(o.Answer.map(u=>u.TTL));return this._cache.set(Sr.getCacheKey(e,r),a,{ttl:c}),a}catch(s){ou.error(`${i} could not resolve ${e} record ${r}`)}throw new Error(`Could not resolve ${e} record ${r}`)}};au.Resolver=au;gb.exports=au});var bb=w((pF,vb)=>{"use strict";var o3=mb();vb.exports=o3});var wb=w((yF,Eb)=>{"use strict";var a3=ha(),{code:c3}=a3("dnsaddr");async function u3(t){let e=bb(),r=new e,n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===c3)||[],o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]);return n&&(o=o.filter(a=>a.includes(n))),o}Eb.exports={dnsaddrResolver:u3}});var cu=w((gF,_b)=>{"use strict";_b.exports={DIAL_TIMEOUT:3e4,MAX_PARALLEL_DIALS:100,MAX_PER_PEER_DIALS:4,MAX_ADDRS_TO_DIAL:25,METRICS:{computeThrottleMaxQueueSize:1e3,computeThrottleTimeout:2e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3],maxOldPeersRetention:50}}});var md=w((mF,l3)=>{l3.exports={name:"libp2p",version:"0.36.2",description:"JavaScript implementation of libp2p, a modular peer to peer network stack",leadMaintainer:"Jacob Heun <jacobheun@gmail.com>",main:"src/index.js",types:"dist/src/index.d.ts",typesVersions:{"*":{"src/*":["dist/src/*","dist/src/*/index"]}},files:["dist","src"],scripts:{lint:"aegir lint",build:"aegir build","build:proto":"npm run build:proto:circuit && npm run build:proto:fetch && npm run build:proto:identify && npm run build:proto:plaintext && npm run build:proto:address-book && npm run build:proto:proto-book && npm run build:proto:peer && npm run build:proto:peer-record && npm run build:proto:envelope","build:proto:circuit":"pbjs -t static-module -w commonjs -r libp2p-circuit --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/circuit/protocol/index.js ./src/circuit/protocol/index.proto","build:proto:fetch":"pbjs -t static-module -w commonjs -r libp2p-fetch --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/fetch/proto.js ./src/fetch/proto.proto","build:proto:identify":"pbjs -t static-module -w commonjs -r libp2p-identify --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/identify/message.js ./src/identify/message.proto","build:proto:plaintext":"pbjs -t static-module -w commonjs -r libp2p-plaintext --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/insecure/proto.js ./src/insecure/proto.proto","build:proto:peer":"pbjs -t static-module -w commonjs -r libp2p-peer --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/peer-store/pb/peer.js ./src/peer-store/pb/peer.proto","build:proto:peer-record":"pbjs -t static-module -w commonjs -r libp2p-peer-record --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/record/peer-record/peer-record.js ./src/record/peer-record/peer-record.proto","build:proto:envelope":"pbjs -t static-module -w commonjs -r libp2p-envelope --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/record/envelope/envelope.js ./src/record/envelope/envelope.proto","build:proto-types":"npm run build:proto-types:circuit && npm run build:proto-types:fetch && npm run build:proto-types:identify && npm run build:proto-types:plaintext && npm run build:proto-types:address-book && npm run build:proto-types:proto-book && npm run build:proto-types:peer && npm run build:proto-types:peer-record && npm run build:proto-types:envelope","build:proto-types:circuit":"pbts -o src/circuit/protocol/index.d.ts src/circuit/protocol/index.js","build:proto-types:fetch":"pbts -o src/fetch/proto.d.ts src/fetch/proto.js","build:proto-types:identify":"pbts -o src/identify/message.d.ts src/identify/message.js","build:proto-types:plaintext":"pbts -o src/insecure/proto.d.ts src/insecure/proto.js","build:proto-types:peer":"pbts -o src/peer-store/pb/peer.d.ts src/peer-store/pb/peer.js","build:proto-types:peer-record":"pbts -o src/record/peer-record/peer-record.d.ts src/record/peer-record/peer-record.js","build:proto-types:envelope":"pbts -o src/record/envelope/envelope.d.ts src/record/envelope/envelope.js",test:"aegir test","test:ts":"aegir build --no-bundle && npm run test --prefix test/ts-use","test:node":'aegir test -t node -f "./test/**/*.{node,spec}.js"',"test:browser":"aegir test -t browser","test:examples":"cd examples && npm run test:all","test:interop":"LIBP2P_JS=$PWD npx aegir test -t node -f ./node_modules/libp2p-interop/test/*",prepare:"npm run build",coverage:"nyc --reporter=text --reporter=lcov npm run test:node"},repository:{type:"git",url:"https://github.com/libp2p/js-libp2p.git"},keywords:["libp2p","network","p2p","peer","peer-to-peer","IPFS"],bugs:{url:"https://github.com/libp2p/js-libp2p/issues"},homepage:"https://libp2p.io",license:"MIT",engines:{node:">=15.0.0"},browser:{"nat-api":!1},eslintConfig:{extends:"ipfs",ignorePatterns:["!.aegir.js","test/ts-use","*.d.ts"]},dependencies:{"@vascosantos/moving-average":"^1.1.0","abortable-iterator":"^3.0.0","aggregate-error":"^3.1.0","any-signal":"^3.0.0","bignumber.js":"^9.0.1","class-is":"^1.1.0","datastore-core":"^7.0.0",debug:"^4.3.1","err-code":"^3.0.0","es6-promisify":"^7.0.0",events:"^3.3.0",hashlru:"^2.3.0","interface-datastore":"^6.0.2","it-all":"^1.0.4","it-buffer":"^0.1.2","it-drain":"^1.0.3","it-filter":"^1.0.1","it-first":"^1.0.4","it-foreach":"^0.1.1","it-handshake":"^2.0.0","it-length-prefixed":"^5.0.2","it-map":"^1.0.4","it-merge":"^1.0.0","it-pipe":"^1.1.0","it-sort":"^1.0.1","it-take":"^1.0.0","libp2p-crypto":"^0.21.2","libp2p-interfaces":"^4.0.0","libp2p-utils":"^0.4.0",mafmt:"^10.0.0","merge-options":"^3.0.4",mortice:"^2.0.1",multiaddr:"^10.0.0",multiformats:"^9.0.0","multistream-select":"^3.0.0","mutable-proxy":"^1.0.0","nat-api":"^0.3.1","node-forge":"^1.2.1","p-any":"^3.0.0","p-fifo":"^1.0.0","p-retry":"^4.4.0","p-settle":"^4.1.1","peer-id":"^0.16.0","private-ip":"^2.1.0",protobufjs:"^6.10.2",retimer:"^3.0.0","sanitize-filename":"^1.6.3","set-delayed-interval":"^1.0.0","streaming-iterables":"^6.0.0","timeout-abort-controller":"^3.0.0",uint8arrays:"^3.0.0",varint:"^6.0.0",wherearewe:"^1.0.0",xsalsa20:"^1.1.0"},devDependencies:{"@chainsafe/libp2p-noise":"^5.0.0","@nodeutils/defaults-deep":"^1.1.0","@types/es6-promisify":"^6.0.0","@types/node":"^16.0.1","@types/node-forge":"^1.0.0","@types/varint":"^6.0.0",aegir:"^36.0.0",buffer:"^6.0.3",delay:"^5.0.0","into-stream":"^6.0.0","ipfs-http-client":"^54.0.2","it-concat":"^2.0.0","it-pair":"^1.0.0","it-pushable":"^1.4.0",libp2p:".","libp2p-bootstrap":"^0.14.0","libp2p-delegated-content-routing":"^0.11.0","libp2p-delegated-peer-routing":"^0.11.1","libp2p-interfaces-compliance-tests":"^4.0.8","libp2p-interop":"^0.7.1","libp2p-kad-dht":"^0.28.6","libp2p-mdns":"^0.18.0","libp2p-mplex":"^0.10.4","libp2p-tcp":"^0.17.0","libp2p-webrtc-star":"^0.25.0","libp2p-websockets":"^0.16.0",nock:"^13.0.3","p-defer":"^3.0.0","p-times":"^3.0.0","p-wait-for":"^3.2.0",rimraf:"^3.0.2",sinon:"^12.0.1",util:"^0.12.3"},contributors:["Vasco Santos <vasco.santos@moxy.studio>","David Dias <daviddias.p@gmail.com>","Jacob Heun <jacobheun@gmail.com>","Alex Potsides <alex@achingbrain.net>","Alan Shaw <alan@tableflip.io>","Cayman <caymannava@gmail.com>","Pedro Teixeira <i@pgte.me>","Friedel Ziegelmayer <dignifiedquire@gmail.com>","Maciej Kr\xFCger <mkg20001@gmail.com>","Hugo Dias <mail@hugodias.me>","dirkmc <dirkmdev@gmail.com>","Volker Mische <volker.mische@gmail.com>","Chris Dostert <chrisdostert@users.noreply.github.com>","zeim839 <50573884+zeim839@users.noreply.github.com>","Robert Kiel <robert.kiel@hoprnet.org>","Richard Littauer <richard.littauer@gmail.com>","a1300 <matthias-knopp@gmx.net>","Ryan Bell <ryan@piing.net>","\u1D20\u026A\u1D04\u1D1B\u1D0F\u0280 \u0299\u1D0A\u1D07\u029F\u1D0B\u029C\u1D0F\u029F\u1D0D <victorbjelkholm@gmail.com>","Andrew Nesbitt <andrewnez@gmail.com>","Franck Royer <franck@royer.one>","Thomas Eizinger <thomas@eizinger.io>","V\xEDt Habada <vithabada93@gmail.com>","Giovanni T. Parra <fiatjaf@gmail.com>","acolytec3 <17355484+acolytec3@users.noreply.github.com>","Alan Smithee <ggnore.alan.smithee@gmail.com>","Elven <mon.samuel@qq.com>","Samlior <samlior@foxmail.com>","Didrik Nordstr\xF6m <didrik.nordstrom@gmail.com>","Aditya Bose <13054902+adbose@users.noreply.github.com>","TJKoury <TJKoury@gmail.com>","TheStarBoys <41286328+TheStarBoys@users.noreply.github.com>","Tiago Alves <alvesjtiago@gmail.com>","Tim Daubensch\xFCtz <tim@daubenschuetz.de>","XiaoZhang <zxinmyth@gmail.com>","Yusef Napora <yusef@napora.org>","Zane Starr <zcstarr@gmail.com>","ebinks <elizabethjbinks@gmail.com>","greenSnot <greenSnot@users.noreply.github.com>","isan_rivkin <isanrivkin@gmail.com>","mayerwin <mayerwin@users.noreply.github.com>","mcclure <andi.m.mcclure@gmail.com>","patrickwoodhead <91056047+patrickwoodhead@users.noreply.github.com>","phillmac <phillmac@users.noreply.github.com>","robertkiel <robert.kiel@validitylabs.org>","shresthagrawal <34920931+shresthagrawal@users.noreply.github.com>","swedneck <40505480+swedneck@users.noreply.github.com>","tuyennhv <vutuyen2636@gmail.com>","S\xF6nke Hahn <soenkehahn@gmail.com>","Aleksei <vozhdb@gmail.com>","Bernd Strehl <bernd.strehl@gmail.com>","Chris Bratlien <chrisbratlien@gmail.com>","Cindy Wu <ciindy.wu@gmail.com>","Daijiro Wachi <daijiro.wachi@gmail.com>","Diogo Silva <fsdiogo@gmail.com>","Dmitriy Ryajov <dryajov@gmail.com>","Ethan Lam <elmemphis2000@gmail.com>","Fei Liu <liu.feiwood@gmail.com>","Felipe Martins <felipebrasil93@gmail.com>","Florian-Merle <florian.david.merle@gmail.com>","Francis Gulotta <wizard@roborooter.com>","Guy Sviry <32539816+guysv@users.noreply.github.com>","Henrique Dias <hacdias@gmail.com>","Irakli Gozalishvili <rfobic@gmail.com>","Joel Gustafson <joelg@mit.edu>","John Rees <johnrees@users.noreply.github.com>","Jo\xE3o Santos <joaosantos15@users.noreply.github.com>","Julien Bouquillon <contact@revolunet.com>","Kevin Kwok <antimatter15@gmail.com>","Kevin Lacker <lacker@gmail.com>","Lars Gierth <lgierth@users.noreply.github.com>","Leask Wong <i@leaskh.com>","Marcin Tojek <mtojek@users.noreply.github.com>","Marston Connell <34043723+TheMarstonConnell@users.noreply.github.com>","Michael Burns <5170+mburns@users.noreply.github.com>","Miguel Mota <miguelmota2@gmail.com>","Nuno Nogueira <nunofmn@gmail.com>","Philipp Muens <raute1337@gmx.de>","RasmusErik Voel Jensen <github@solsort.com>","Smite Chow <xiaopengyou@live.com>","Soeren <nikorpoulsen@gmail.com>"]}});var vd=w((vF,cn)=>{"use strict";var f3=md().version;cn.exports.PROTOCOL_VERSION="ipfs/0.1.0";cn.exports.AGENT_VERSION=`js-libp2p/${f3}`;cn.exports.MULTICODEC_IDENTIFY="/ipfs/id/1.0.0";cn.exports.MULTICODEC_IDENTIFY_PUSH="/ipfs/id/push/1.0.0";cn.exports.IDENTIFY_PROTOCOL_VERSION="0.1.0";cn.exports.MULTICODEC_IDENTIFY_PROTOCOL_NAME="id";cn.exports.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME="id/push";cn.exports.MULTICODEC_IDENTIFY_PROTOCOL_VERSION="1.0.0";cn.exports.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION="1.0.0"});var uu=w((bF,xb)=>{"use strict";var Sb=60*1e3;xb.exports={ADVERTISE_BOOT_DELAY:15*Sb,ADVERTISE_TTL:30*Sb,CIRCUIT_PROTO_CODE:290,HOP_METADATA_KEY:"hop_relay",HOP_METADATA_VALUE:"true",RELAY_RENDEZVOUS_NS:"/libp2p/relay"}});var Ab=w(_a=>{(function(){var t,e,r,n,i,s,o,a;a=function(c){var u,l,f,d;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&255<<8)>>>8,d=c&255,[u,l,f,d].join(".")},o=function(c){var u,l,f,d,p,h;for(u=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}h=e(c),p=h[0],l=h[1],c=c.substring(l),u.push(p)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},r=function(c){return c.charCodeAt(0)},n=r("0"),s=r("a"),i=r("A"),e=function(c){var u,l,f,d,p;for(d=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),p=f;f<c.length;){if("0"<=c[f]&&c[f]<=l)d=d*u+(r(c[f])-n)>>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")d=d*u+(10+r(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*u+(10+r(c[f])-i)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===p)throw new Error("empty octet");return[d,f]},t=function(){function c(u,l){var f,d,p,h;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(h=u.split("/",2),u=h[0],l=h[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=o(l)}catch(g){throw f=g,new Error("Invalid mask: "+l)}for(d=p=32;p>=0;d=--p)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(u)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(o(u)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,d;for(d=o(this.first),f=o(this.last),l=0;d<=f;)u(a(d),d,l),l++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),_a.ip2long=o,_a.long2ip=a,_a.Netmask=t}).call(_a)});var Ib=w((Cb,lu)=>{(function(t){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",r={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",o="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${o})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${o})|(?:::)(?:${o})?)${e}\\.${e}\\.${e}\\.${e}(${s})?$`,"i")};function c(p,h){if(p.indexOf("::")!==p.lastIndexOf("::"))return null;let g=0,m=-1,S=(p.match(a.zoneIndex)||[])[0],R,L;for(S&&(S=S.substring(1),p=p.replace(/%.+$/,""));(m=p.indexOf(":",m+1))>=0;)g++;if(p.substr(0,2)==="::"&&g--,p.substr(-2,2)==="::"&&g--,g>h)return null;for(L=h-g,R=":";L--;)R+="0:";return p=p.replace("::",R),p[0]===":"&&(p=p.slice(1)),p[p.length-1]===":"&&(p=p.slice(0,-1)),h=function(){let H=p.split(":"),q=[];for(let k=0;k<H.length;k++)q.push(parseInt(H[k],16));return q}(),{parts:h,zoneId:S}}function u(p,h,g,m){if(p.length!==h.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let S=0,R;for(;m>0;){if(R=g-m,R<0&&(R=0),p[S]>>R!=h[S]>>R)return!1;m-=g,S+=1}return!0}function l(p){if(i.test(p))return parseInt(p,16);if(p[0]==="0"&&!isNaN(parseInt(p[1],10))){if(n.test(p))return parseInt(p,8);throw new Error(`ipaddr: cannot parse ${p} as octal`)}return parseInt(p,10)}function f(p,h){for(;p.length<h;)p=`0${p}`;return p}let d={};d.IPv4=function(){function p(h){if(h.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let g,m;for(g=0;g<h.length;g++)if(m=h[g],!(0<=m&&m<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=h}return p.prototype.SpecialRanges={unspecified:[[new p([0,0,0,0]),8]],broadcast:[[new p([255,255,255,255]),32]],multicast:[[new p([224,0,0,0]),4]],linkLocal:[[new p([169,254,0,0]),16]],loopback:[[new p([127,0,0,0]),8]],carrierGradeNat:[[new p([100,64,0,0]),10]],private:[[new p([10,0,0,0]),8],[new p([172,16,0,0]),12],[new p([192,168,0,0]),16]],reserved:[[new p([192,0,0,0]),24],[new p([192,0,2,0]),24],[new p([192,88,99,0]),24],[new p([198,51,100,0]),24],[new p([203,0,113,0]),24],[new p([240,0,0,0]),4]]},p.prototype.kind=function(){return"ipv4"},p.prototype.match=function(h,g){let m;if(g===void 0&&(m=h,h=m[0],g=m[1]),h.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return u(this.octets,h.octets,8,g)},p.prototype.prefixLengthFromSubnetMask=function(){let h=0,g=!1,m={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},S,R,L;for(S=3;S>=0;S-=1)if(R=this.octets[S],R in m){if(L=m[R],g&&L!==0)return null;L!==8&&(g=!0),h+=L}else return null;return 32-h},p.prototype.range=function(){return d.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){return this.octets.slice(0)},p.prototype.toIPv4MappedAddress=function(){return d.IPv6.parse(`::ffff:${this.toString()}`)},p.prototype.toNormalizedString=function(){return this.toString()},p.prototype.toString=function(){return this.octets.join(".")},p}(),d.IPv4.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),g=h[0].toByteArray(),m=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),S=[],R=0;for(;R<4;)S.push(parseInt(g[R],10)|parseInt(m[R],10)^255),R++;return new this(S)}catch(h){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},d.IPv4.isIPv4=function(p){return this.parser(p)!==null},d.IPv4.isValid=function(p){try{return new this(this.parser(p)),!0}catch(h){return!1}},d.IPv4.isValidFourPartDecimal=function(p){return!!(d.IPv4.isValid(p)&&p.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},d.IPv4.networkAddressFromCIDR=function(p){let h,g,m,S,R;try{for(h=this.parseCIDR(p),m=h[0].toByteArray(),R=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),S=[],g=0;g<4;)S.push(parseInt(m[g],10)&parseInt(R[g],10)),g++;return new this(S)}catch(L){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},d.IPv4.parse=function(p){let h=this.parser(p);if(h===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(h)},d.IPv4.parseCIDR=function(p){let h;if(h=p.match(/^(.+)\/(\d+)$/)){let g=parseInt(h[2]);if(g>=0&&g<=32){let m=[this.parse(h[1]),g];return Object.defineProperty(m,"toString",{value:function(){return this.join("/")}}),m}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},d.IPv4.parser=function(p){let h,g,m;if(h=p.match(r.fourOctet))return function(){let S=h.slice(1,6),R=[];for(let L=0;L<S.length;L++)g=S[L],R.push(l(g));return R}();if(h=p.match(r.longValue)){if(m=l(h[1]),m>4294967295||m<0)throw new Error("ipaddr: address outside defined range");return function(){let S=[],R;for(R=0;R<=24;R+=8)S.push(m>>R&255);return S}().reverse()}else return(h=p.match(r.twoOctet))?function(){let S=h.slice(1,4),R=[];if(m=l(S[1]),m>16777215||m<0)throw new Error("ipaddr: address outside defined range");return R.push(l(S[0])),R.push(m>>16&255),R.push(m>>8&255),R.push(m&255),R}():(h=p.match(r.threeOctet))?function(){let S=h.slice(1,5),R=[];if(m=l(S[2]),m>65535||m<0)throw new Error("ipaddr: address outside defined range");return R.push(l(S[0])),R.push(l(S[1])),R.push(m>>8&255),R.push(m&255),R}():null},d.IPv4.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>32)throw new Error("ipaddr: invalid IPv4 prefix length");let h=[0,0,0,0],g=0,m=Math.floor(p/8);for(;g<m;)h[g]=255,g++;return m<4&&(h[m]=Math.pow(2,p%8)-1<<8-p%8),new this(h)},d.IPv6=function(){function p(h,g){let m,S;if(h.length===16)for(this.parts=[],m=0;m<=14;m+=2)this.parts.push(h[m]<<8|h[m+1]);else if(h.length===8)this.parts=h;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(m=0;m<this.parts.length;m++)if(S=this.parts[m],!(0<=S&&S<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");g&&(this.zoneId=g)}return p.prototype.SpecialRanges={unspecified:[new p([0,0,0,0,0,0,0,0]),128],linkLocal:[new p([65152,0,0,0,0,0,0,0]),10],multicast:[new p([65280,0,0,0,0,0,0,0]),8],loopback:[new p([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new p([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new p([0,0,0,0,0,65535,0,0]),96],rfc6145:[new p([0,0,0,0,65535,0,0,0]),96],rfc6052:[new p([100,65435,0,0,0,0,0,0]),96],"6to4":[new p([8194,0,0,0,0,0,0,0]),16],teredo:[new p([8193,0,0,0,0,0,0,0]),32],reserved:[[new p([8193,3512,0,0,0,0,0,0]),32]]},p.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},p.prototype.kind=function(){return"ipv6"},p.prototype.match=function(h,g){let m;if(g===void 0&&(m=h,h=m[0],g=m[1]),h.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return u(this.parts,h.parts,16,g)},p.prototype.prefixLengthFromSubnetMask=function(){let h=0,g=!1,m={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},S,R;for(let L=7;L>=0;L-=1)if(S=this.parts[L],S in m){if(R=m[S],g&&R!==0)return null;R!==16&&(g=!0),h+=R}else return null;return 128-h},p.prototype.range=function(){return d.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){let h,g=[],m=this.parts;for(let S=0;S<m.length;S++)h=m[S],g.push(h>>8),g.push(h&255);return g},p.prototype.toFixedLengthString=function(){let h=function(){let m=[];for(let S=0;S<this.parts.length;S++)m.push(f(this.parts[S].toString(16),4));return m}.call(this).join(":"),g="";return this.zoneId&&(g=`%${this.zoneId}`),h+g},p.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let h=this.parts.slice(-2),g=h[0],m=h[1];return new d.IPv4([g>>8,g&255,m>>8,m&255])},p.prototype.toNormalizedString=function(){let h=function(){let m=[];for(let S=0;S<this.parts.length;S++)m.push(this.parts[S].toString(16));return m}.call(this).join(":"),g="";return this.zoneId&&(g=`%${this.zoneId}`),h+g},p.prototype.toRFC5952String=function(){let h=/((^|:)(0(:|$)){2,})/g,g=this.toNormalizedString(),m=0,S=-1,R;for(;R=h.exec(g);)R[0].length>S&&(m=R.index,S=R[0].length);return S<0?g:`${g.substring(0,m)}::${g.substring(m+S)}`},p.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},p}(),d.IPv6.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),g=h[0].toByteArray(),m=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),S=[],R=0;for(;R<16;)S.push(parseInt(g[R],10)|parseInt(m[R],10)^255),R++;return new this(S)}catch(h){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${h})`)}},d.IPv6.isIPv6=function(p){return this.parser(p)!==null},d.IPv6.isValid=function(p){if(typeof p=="string"&&p.indexOf(":")===-1)return!1;try{let h=this.parser(p);return new this(h.parts,h.zoneId),!0}catch(h){return!1}},d.IPv6.networkAddressFromCIDR=function(p){let h,g,m,S,R;try{for(h=this.parseCIDR(p),m=h[0].toByteArray(),R=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),S=[],g=0;g<16;)S.push(parseInt(m[g],10)&parseInt(R[g],10)),g++;return new this(S)}catch(L){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${L})`)}},d.IPv6.parse=function(p){let h=this.parser(p);if(h.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(h.parts,h.zoneId)},d.IPv6.parseCIDR=function(p){let h,g,m;if((g=p.match(/^(.+)\/(\d+)$/))&&(h=parseInt(g[2]),h>=0&&h<=128))return m=[this.parse(g[1]),h],Object.defineProperty(m,"toString",{value:function(){return this.join("/")}}),m;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},d.IPv6.parser=function(p){let h,g,m,S,R,L;if(m=p.match(a.deprecatedTransitional))return this.parser(`::ffff:${m[1]}`);if(a.native.test(p))return c(p,8);if((m=p.match(a.transitional))&&(L=m[6]||"",h=c(m[1].slice(0,-1)+L,6),h.parts)){for(R=[parseInt(m[2]),parseInt(m[3]),parseInt(m[4]),parseInt(m[5])],g=0;g<R.length;g++)if(S=R[g],!(0<=S&&S<=255))return null;return h.parts.push(R[0]<<8|R[1]),h.parts.push(R[2]<<8|R[3]),{parts:h.parts,zoneId:h.zoneId}}return null},d.IPv6.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>128)throw new Error("ipaddr: invalid IPv6 prefix length");let h=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],g=0,m=Math.floor(p/8);for(;g<m;)h[g]=255,g++;return m<16&&(h[m]=Math.pow(2,p%8)-1<<8-p%8),new this(h)},d.fromByteArray=function(p){let h=p.length;if(h===4)return new d.IPv4(p);if(h===16)return new d.IPv6(p);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},d.isValid=function(p){return d.IPv6.isValid(p)||d.IPv4.isValid(p)},d.parse=function(p){if(d.IPv6.isValid(p))return d.IPv6.parse(p);if(d.IPv4.isValid(p))return d.IPv4.parse(p);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},d.parseCIDR=function(p){try{return d.IPv6.parseCIDR(p)}catch(h){try{return d.IPv4.parseCIDR(p)}catch(g){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},d.process=function(p){let h=this.parse(p);return h.kind()==="ipv6"&&h.isIPv4MappedAddress()?h.toIPv4Address():h},d.subnetMatch=function(p,h,g){let m,S,R,L;g==null&&(g="unicast");for(S in h)if(Object.prototype.hasOwnProperty.call(h,S)){for(R=h[S],R[0]&&!(R[0]instanceof Array)&&(R=[R]),m=0;m<R.length;m++)if(L=R[m],p.kind()===L[0].kind()&&p.match.apply(p,L))return S}return g},typeof lu!="undefined"&&lu.exports?lu.exports=d:t.ipaddr=d})(Cb)});var Pb=w(Sa=>{"use strict";var Tb=Sa&&Sa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Sa,"__esModule",{value:!0});var d3=Ab(),h3=Tb(kf()),p3=Tb(Uf()),Rb=Ib(),y3=["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"],g3=y3.map(t=>new d3.Netmask(t));function m3(t){for(let e of g3)if(e.contains(t))return!0;return!1}function Bb(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}Sa.default=t=>{if(Rb.isValid(t)){let e=Rb.parse(t);if(e.kind()==="ipv4")return m3(e.toNormalizedString());if(e.kind()==="ipv6")return Bb(t)}else if(p3.default(t)&&h3.default.v6().test(t))return Bb(t)}});var bd=w((_F,Nb)=>{"use strict";Nb.exports=Pb().default});var Db=w((SF,Ob)=>{"use strict";var v3=bd();function b3(t){let{address:e}=t.nodeAddress();return v3(e)}Ob.exports=b3});var Ed=w((xF,kb)=>{"use strict";var Lb=Db();function E3(t,e){let r=Lb(t.multiaddr),n=Lb(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function w3(t){return[...t].sort(E3)}kb.exports.publicAddressesFirst=w3});var Ub=w((AF,wd)=>{"use strict";var qb=async t=>{try{let e=await t;return{isFulfilled:!0,isRejected:!1,value:e}}catch(e){return{isFulfilled:!1,isRejected:!0,reason:e}}};wd.exports=qb;wd.exports.default=qb});var Fb=w((CF,_d)=>{"use strict";var Mb=(t,...e)=>new Promise(r=>{r(t(...e))});_d.exports=Mb;_d.exports.default=Mb});var Vb=w((IF,Sd)=>{"use strict";var _3=Fb(),Kb=t=>{if(!((Number.isInteger(t)||t===1/0)&&t>0))return Promise.reject(new TypeError("Expected `concurrency` to be a number from 1 and up"));let e=[],r=0,n=()=>{r--,e.length>0&&e.shift()()},i=(a,c,...u)=>{r++;let l=_3(a,...u);c(l),l.then(n,n)},s=(a,c,...u)=>{r<t?i(a,c,...u):e.push(i.bind(null,a,c,...u))},o=(a,...c)=>new Promise(u=>s(a,u,...c));return Object.defineProperties(o,{activeCount:{get:()=>r},pendingCount:{get:()=>e.length},clearQueue:{value:()=>{e.length=0}}}),o};Sd.exports=Kb;Sd.exports.default=Kb});var $b=w((TF,jb)=>{"use strict";var xd=Ub(),S3=Vb();jb.exports=async(t,e={})=>{let{concurrency:r=1/0}=e,n=S3(r);return Promise.all(t.map(i=>i&&typeof i.then=="function"?xd(i):xd(typeof i=="function"?n(()=>i()):Promise.resolve(i))))}});var Gb=w((RF,zb)=>{"use strict";var Gs=gn(),Hb=Gs.Reader,x3=Gs.Writer,Je=Gs.util,xa=Gs.roots["libp2p-envelope"]||(Gs.roots["libp2p-envelope"]={});xa.Envelope=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.publicKey=Je.newBuffer([]),t.prototype.payloadType=Je.newBuffer([]),t.prototype.payload=Je.newBuffer([]),t.prototype.signature=Je.newBuffer([]),t.encode=function(r,n){return n||(n=x3.create()),r.publicKey!=null&&Object.hasOwnProperty.call(r,"publicKey")&&n.uint32(10).bytes(r.publicKey),r.payloadType!=null&&Object.hasOwnProperty.call(r,"payloadType")&&n.uint32(18).bytes(r.payloadType),r.payload!=null&&Object.hasOwnProperty.call(r,"payload")&&n.uint32(26).bytes(r.payload),r.signature!=null&&Object.hasOwnProperty.call(r,"signature")&&n.uint32(42).bytes(r.signature),n},t.decode=function(r,n){r instanceof Hb||(r=Hb.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new xa.Envelope;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.publicKey=r.bytes();break;case 2:s.payloadType=r.bytes();break;case 3:s.payload=r.bytes();break;case 5:s.signature=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof xa.Envelope)return r;var n=new xa.Envelope;return r.publicKey!=null&&(typeof r.publicKey=="string"?Je.base64.decode(r.publicKey,n.publicKey=Je.newBuffer(Je.base64.length(r.publicKey)),0):r.publicKey.length&&(n.publicKey=r.publicKey)),r.payloadType!=null&&(typeof r.payloadType=="string"?Je.base64.decode(r.payloadType,n.payloadType=Je.newBuffer(Je.base64.length(r.payloadType)),0):r.payloadType.length&&(n.payloadType=r.payloadType)),r.payload!=null&&(typeof r.payload=="string"?Je.base64.decode(r.payload,n.payload=Je.newBuffer(Je.base64.length(r.payload)),0):r.payload.length&&(n.payload=r.payload)),r.signature!=null&&(typeof r.signature=="string"?Je.base64.decode(r.signature,n.signature=Je.newBuffer(Je.base64.length(r.signature)),0):r.signature.length&&(n.signature=r.signature)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(n.bytes===String?i.publicKey="":(i.publicKey=[],n.bytes!==Array&&(i.publicKey=Je.newBuffer(i.publicKey))),n.bytes===String?i.payloadType="":(i.payloadType=[],n.bytes!==Array&&(i.payloadType=Je.newBuffer(i.payloadType))),n.bytes===String?i.payload="":(i.payload=[],n.bytes!==Array&&(i.payload=Je.newBuffer(i.payload))),n.bytes===String?i.signature="":(i.signature=[],n.bytes!==Array&&(i.signature=Je.newBuffer(i.signature)))),r.publicKey!=null&&r.hasOwnProperty("publicKey")&&(i.publicKey=n.bytes===String?Je.base64.encode(r.publicKey,0,r.publicKey.length):n.bytes===Array?Array.prototype.slice.call(r.publicKey):r.publicKey),r.payloadType!=null&&r.hasOwnProperty("payloadType")&&(i.payloadType=n.bytes===String?Je.base64.encode(r.payloadType,0,r.payloadType.length):n.bytes===Array?Array.prototype.slice.call(r.payloadType):r.payloadType),r.payload!=null&&r.hasOwnProperty("payload")&&(i.payload=n.bytes===String?Je.base64.encode(r.payload,0,r.payload.length):n.bytes===Array?Array.prototype.slice.call(r.payload):r.payload),r.signature!=null&&r.hasOwnProperty("signature")&&(i.signature=n.bytes===String?Je.base64.encode(r.signature,0,r.signature.length):n.bytes===Array?Array.prototype.slice.call(r.signature):r.signature),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Gs.util.toJSONOptions)},t}();zb.exports=xa});var du=w((BF,Qb)=>{"use strict";var A3=de(),{concat:C3}=(Yn(),Wn),{fromString:I3}=(It(),Nt),T3=jc(),R3=Rt(),Ad=Ui(),{equals:fu}=(mr(),gr),{codes:B3}=je(),{Envelope:Wb}=Gb(),ii=class{constructor({peerId:e,payloadType:r,payload:n,signature:i}){this.peerId=e,this.payloadType=r,this.payload=n,this.signature=i,this._marshal=void 0}marshal(){if(this._marshal)return this._marshal;let e=T3.marshalPublicKey(this.peerId.pubKey);return this._marshal=Wb.encode({publicKey:e,payloadType:this.payloadType,payload:this.payload,signature:this.signature}).finish(),this._marshal}equals(e){return fu(this.peerId.pubKey.bytes,e.peerId.pubKey.bytes)&&fu(this.payloadType,e.payloadType)&&fu(this.payload,e.payload)&&fu(this.signature,e.signature)}validate(e){let r=Yb(e,this.payloadType,this.payload);return this.peerId.pubKey.verify(r,this.signature)}},Yb=(t,e,r)=>{let n=I3(t),i=Ad.encode(n.byteLength),s=Ad.encode(e.length),o=Ad.encode(r.length);return C3([new Uint8Array(i),n,new Uint8Array(s),e,new Uint8Array(o),r])};ii.createFromProtobuf=async t=>{let e=Wb.decode(t),r=await R3.createFromPubKey(e.publicKey);return new ii({peerId:r,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};ii.seal=async(t,e)=>{let r=t.domain,n=t.codec,i=t.marshal(),s=Yb(r,n,i),o=await e.privKey.sign(s);return new ii({peerId:e,payloadType:n,payload:i,signature:o})};ii.openAndCertify=async(t,e)=>{let r=await ii.createFromProtobuf(t);if(!await r.validate(e))throw A3(new Error("envelope signature is not valid for the given domain"),B3.ERR_SIGNATURE_NOT_VALID);return r};Qb.exports=ii});var Zb=w((PF,Xb)=>{"use strict";function P3(t,e){return t.length===e.length&&e.sort()&&t.sort().every((r,n)=>e[n].equals(r))}Xb.exports=P3});var tE=w((NF,eE)=>{"use strict";var $i=gn(),hu=$i.Reader,Jb=$i.Writer,lt=$i.util,xr=$i.roots["libp2p-peer-record"]||($i.roots["libp2p-peer-record"]={});xr.PeerRecord=function(){function t(e){if(this.addresses=[],e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.peerId=lt.newBuffer([]),t.prototype.seq=lt.Long?lt.Long.fromBits(0,0,!0):0,t.prototype.addresses=lt.emptyArray,t.encode=function(r,n){if(n||(n=Jb.create()),r.peerId!=null&&Object.hasOwnProperty.call(r,"peerId")&&n.uint32(10).bytes(r.peerId),r.seq!=null&&Object.hasOwnProperty.call(r,"seq")&&n.uint32(16).uint64(r.seq),r.addresses!=null&&r.addresses.length)for(var i=0;i<r.addresses.length;++i)xr.PeerRecord.AddressInfo.encode(r.addresses[i],n.uint32(26).fork()).ldelim();return n},t.decode=function(r,n){r instanceof hu||(r=hu.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new xr.PeerRecord;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.peerId=r.bytes();break;case 2:s.seq=r.uint64();break;case 3:s.addresses&&s.addresses.length||(s.addresses=[]),s.addresses.push(xr.PeerRecord.AddressInfo.decode(r,r.uint32()));break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof xr.PeerRecord)return r;var n=new xr.PeerRecord;if(r.peerId!=null&&(typeof r.peerId=="string"?lt.base64.decode(r.peerId,n.peerId=lt.newBuffer(lt.base64.length(r.peerId)),0):r.peerId.length&&(n.peerId=r.peerId)),r.seq!=null&&(lt.Long?(n.seq=lt.Long.fromValue(r.seq)).unsigned=!0:typeof r.seq=="string"?n.seq=parseInt(r.seq,10):typeof r.seq=="number"?n.seq=r.seq:typeof r.seq=="object"&&(n.seq=new lt.LongBits(r.seq.low>>>0,r.seq.high>>>0).toNumber(!0))),r.addresses){if(!Array.isArray(r.addresses))throw TypeError(".PeerRecord.addresses: array expected");n.addresses=[];for(var i=0;i<r.addresses.length;++i){if(typeof r.addresses[i]!="object")throw TypeError(".PeerRecord.addresses: object expected");n.addresses[i]=xr.PeerRecord.AddressInfo.fromObject(r.addresses[i])}}return n},t.toObject=function(r,n){n||(n={});var i={};if((n.arrays||n.defaults)&&(i.addresses=[]),n.defaults)if(n.bytes===String?i.peerId="":(i.peerId=[],n.bytes!==Array&&(i.peerId=lt.newBuffer(i.peerId))),lt.Long){var s=new lt.Long(0,0,!0);i.seq=n.longs===String?s.toString():n.longs===Number?s.toNumber():s}else i.seq=n.longs===String?"0":0;if(r.peerId!=null&&r.hasOwnProperty("peerId")&&(i.peerId=n.bytes===String?lt.base64.encode(r.peerId,0,r.peerId.length):n.bytes===Array?Array.prototype.slice.call(r.peerId):r.peerId),r.seq!=null&&r.hasOwnProperty("seq")&&(typeof r.seq=="number"?i.seq=n.longs===String?String(r.seq):r.seq:i.seq=n.longs===String?lt.Long.prototype.toString.call(r.seq):n.longs===Number?new lt.LongBits(r.seq.low>>>0,r.seq.high>>>0).toNumber(!0):r.seq),r.addresses&&r.addresses.length){i.addresses=[];for(var o=0;o<r.addresses.length;++o)i.addresses[o]=xr.PeerRecord.AddressInfo.toObject(r.addresses[o],n)}return i},t.prototype.toJSON=function(){return this.constructor.toObject(this,$i.util.toJSONOptions)},t.AddressInfo=function(){function e(r){if(r)for(var n=Object.keys(r),i=0;i<n.length;++i)r[n[i]]!=null&&(this[n[i]]=r[n[i]])}return e.prototype.multiaddr=lt.newBuffer([]),e.encode=function(n,i){return i||(i=Jb.create()),n.multiaddr!=null&&Object.hasOwnProperty.call(n,"multiaddr")&&i.uint32(10).bytes(n.multiaddr),i},e.decode=function(n,i){n instanceof hu||(n=hu.create(n));for(var s=i===void 0?n.len:n.pos+i,o=new xr.PeerRecord.AddressInfo;n.pos<s;){var a=n.uint32();switch(a>>>3){case 1:o.multiaddr=n.bytes();break;default:n.skipType(a&7);break}}return o},e.fromObject=function(n){if(n instanceof xr.PeerRecord.AddressInfo)return n;var i=new xr.PeerRecord.AddressInfo;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?lt.base64.decode(n.multiaddr,i.multiaddr=lt.newBuffer(lt.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),i},e.toObject=function(n,i){i||(i={});var s={};return i.defaults&&(i.bytes===String?s.multiaddr="":(s.multiaddr=[],i.bytes!==Array&&(s.multiaddr=lt.newBuffer(s.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(s.multiaddr=i.bytes===String?lt.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,$i.util.toJSONOptions)},e}(),t}();eE.exports=xr});var nE=w((OF,rE)=>{"use strict";var N3="libp2p-peer-record",O3=Uint8Array.from([3,1]);rE.exports={ENVELOPE_DOMAIN_PEER_RECORD:N3,ENVELOPE_PAYLOAD_TYPE_PEER_RECORD:O3}});var pu=w((DF,oE)=>{"use strict";var{Multiaddr:D3}=qt(),L3=Rt(),k3=Zb(),{PeerRecord:iE}=tE(),{ENVELOPE_DOMAIN_PEER_RECORD:sE,ENVELOPE_PAYLOAD_TYPE_PEER_RECORD:q3}=nE(),Hi=class{constructor({peerId:e,multiaddrs:r=[],seqNumber:n=Date.now()}){this.domain=sE,this.codec=q3,this.peerId=e,this.multiaddrs=r,this.seqNumber=n,this._marshal=void 0}marshal(){return this._marshal?this._marshal:(this._marshal=iE.encode({peerId:this.peerId.toBytes(),seq:this.seqNumber,addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))}).finish(),this._marshal)}equals(e){return!(!(e instanceof Hi)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!k3(this.multiaddrs,e.multiaddrs))}};Hi.createFromProtobuf=t=>{let e=iE.decode(t),r=L3.createFromBytes(e.peerId),n=(e.addresses||[]).map(s=>new D3(s.multiaddr)),i=Number(e.seq);return new Hi({peerId:r,multiaddrs:n,seqNumber:i})};Hi.DOMAIN=sE;oE.exports=Hi});var Cd=w((LF,aE)=>{"use strict";var U3=du(),M3=pu();async function F3(t){let e=new M3({peerId:t.peerId,multiaddrs:t.multiaddrs}),r=await U3.seal(e,t.peerId);await t.peerStore.addressBook.consumePeerRecord(r)}aE.exports.updateSelfPeerRecord=F3});var Td=w((kF,lE)=>{"use strict";var cE=Te(),zi=Object.assign(cE("libp2p:transports"),{error:cE("libp2p:transports:err")}),K3=$b(),{codes:Ws}=je(),Aa=de(),{updateSelfPeerRecord:uE}=Cd(),Id=class{constructor({libp2p:e,upgrader:r,faultTolerance:n=yu.FATAL_ALL}){this.libp2p=e,this.upgrader=r,this._transports=new Map,this._listeners=new Map,this._listenerOptions=new Map,this.faultTolerance=n}add(e,r,n={}){if(zi("adding %s",e),!e)throw Aa(new Error(`Transport must have a valid key, was given '${e}'`),Ws.ERR_INVALID_KEY);if(this._transports.has(e))throw Aa(new Error("There is already a transport with this key"),Ws.ERR_DUPLICATE_TRANSPORT);let i=new r({...n,libp2p:this.libp2p,upgrader:this.upgrader});this._transports.set(e,i),this._listenerOptions.set(e,n.listenerOptions||{}),this._listeners.has(e)||this._listeners.set(e,[])}async close(){let e=[];for(let[r,n]of this._listeners)for(zi("closing listeners for %s",r);n.length;){let i=n.pop();i.removeAllListeners("listening"),i.removeAllListeners("close"),e.push(i.close())}await Promise.all(e),zi("all listeners closed");for(let r of this._listeners.keys())this._listeners.set(r,[])}async dial(e,r){let n=this.transportForMultiaddr(e);if(!n)throw Aa(new Error(`No transport available for address ${String(e)}`),Ws.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,r)}catch(i){throw i.code||(i.code=Ws.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this._listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return this._transports.values()}transportForMultiaddr(e){for(let r of this._transports.values())if(r.filter([e]).length)return r;return null}async listen(e){if(!e||e.length===0){zi("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this._transports.entries()){let s=i.filter(e),o=[];for(let u of s){zi("creating listener for %s on %s",n,u);let l=i.createListener(this._listenerOptions.get(n));this._listeners.get(n).push(l),l.on("listening",()=>uE(this.libp2p)),l.on("close",()=>uE(this.libp2p)),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if(!(await K3(o)).find(u=>u.isFulfilled===!0)&&this.faultTolerance!==yu.NO_FATAL)throw Aa(new Error(`Transport (${n}) could not listen on any available address`),Ws.ERR_NO_VALID_ADDRESSES)}if(r.length===this._transports.size){let n=`no valid addresses were provided for transports [${r}]`;if(this.faultTolerance===yu.FATAL_ALL)throw Aa(new Error(n),Ws.ERR_NO_VALID_ADDRESSES);zi(`libp2p in dial mode only: ${n}`)}}async remove(e){if(zi("removing %s",e),this._listeners.has(e))for(let r of this._listeners.get(e))r.removeAllListeners("listening"),r.removeAllListeners("close"),await r.close();this._transports.delete(e),this._listeners.delete(e)}async removeAll(){let e=[];for(let r of this._transports.keys())e.push(this.remove(r));await Promise.all(e)}},yu={FATAL_ALL:0,NO_FATAL:1};Id.FaultTolerance=yu;lE.exports=Id});var hE=w((qF,dE)=>{"use strict";var V3=Hs(),{dnsaddrResolver:j3}=wb(),Rd=cu(),{AGENT_VERSION:$3}=vd(),fE=uu(),{publicAddressesFirst:H3}=Ed(),{FaultTolerance:z3}=Td(),G3={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{minConnections:25},connectionGater:{},transportManager:{faultTolerance:z3.FATAL_ALL},dialer:{maxParallelDials:Rd.MAX_PARALLEL_DIALS,maxDialsPerPeer:Rd.MAX_PER_PEER_DIALS,dialTimeout:Rd.DIAL_TIMEOUT,resolvers:{dnsaddr:j3},addressSorter:H3},host:{agentVersion:$3},metrics:{enabled:!1},peerStore:{persistence:!1,threshold:5},peerRouting:{refreshManager:{enabled:!0,interval:6e5,bootDelay:1e4}},config:{protocolPrefix:"ipfs",dht:{enabled:!1,kBucketSize:20},nat:{enabled:!0,ttl:7200,keepAlive:!0,gateway:null,externalIp:null,pmp:{enabled:!1}},peerDiscovery:{autoDial:!0},pubsub:{enabled:!0},relay:{enabled:!0,advertise:{bootDelay:fE.ADVERTISE_BOOT_DELAY,enabled:!1,ttl:fE.ADVERTISE_TTL},hop:{enabled:!1,active:!1},autoRelay:{enabled:!1,maxListeners:2}},transport:{}}};dE.exports.validate=t=>{let e=V3(G3,t);if(e.modules.transport.length<1)throw new Error("'options.modules.transport' must contain at least 1 transport");return e}});var gE=w((UF,yE)=>{"use strict";var{EventEmitter:W3}=Qt(),{Multiaddr:Ca}=qt(),Y3=Rt(),pE=class extends W3{constructor(e,{listen:r=[],announce:n=[]}={}){super();this.peerId=e,this.listen=new Set(r.map(i=>i.toString())),this.announce=new Set(n.map(i=>i.toString())),this.observed=new Set}getListenAddrs(){return Array.from(this.listen).map(e=>new Ca(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>new Ca(e))}getObservedAddrs(){return Array.from(this.observed).map(e=>new Ca(e))}addObservedAddr(e){let r=new Ca(e),n=r.getPeerId();n&&Y3.createFromB58String(n).equals(this.peerId)&&(r=r.decapsulate(new Ca(`/p2p/${this.peerId}`)));let i=r.toString();this.observed.has(i)||(this.observed.add(i),this.emit("change:addresses"))}};yE.exports=pE});var bE=w((MF,vE)=>{"use strict";var{EventEmitter:Q3}=Qt(),Bd=Te()("latency-monitor:VisibilityChangeEmitter"),mE=class extends Q3{constructor(){super();if(typeof document=="undefined"){Bd('This is not a browser, no "document" found. Stopping.');return}this._initializeVisibilityVarNames(),this._addVisibilityChangeListener()}_initializeVisibilityVarNames(){let e,r;typeof document.hidden!="undefined"?(e="hidden",r="visibilitychange"):typeof document.mozHidden!="undefined"?(e="mozHidden",r="mozvisibilitychange"):typeof document.msHidden!="undefined"?(e="msHidden",r="msvisibilitychange"):typeof document.webkitHidden!="undefined"&&(e="webkitHidden",r="webkitvisibilitychange"),this._hidden=e,this._visibilityChange=r}_addVisibilityChangeListener(){typeof document.addEventListener=="undefined"||typeof document[this._hidden]=="undefined"?Bd("Checking page visibility requires a browser that supports the Page Visibility API."):document.addEventListener(this._visibilityChange,this._handleVisibilityChange.bind(this),!1)}isVisible(){if(!(this._hidden===void 0||document[this._hidden]===void 0))return!document[this._hidden]}_handleVisibilityChange(){let e=!document[this._hidden];Bd(e?"Page Visible":"Page Hidden"),this.emit("visibilityChange",e)}};vE.exports=mE});var _E=w((FF,wE)=>{"use strict";var{EventEmitter:X3}=Qt(),Z3=bE(),In=Te()("latency-monitor:LatencyMonitor"),EE=class extends X3{constructor({latencyCheckIntervalMs:e,dataEmitIntervalMs:r,asyncTestFn:n,latencyRandomPercentage:i}={}){super();let s=this;s.latencyCheckIntervalMs=e||500,s.latencyRandomPercentage=i||10,s._latecyCheckMultiply=2*(s.latencyRandomPercentage/100)*s.latencyCheckIntervalMs,s._latecyCheckSubtract=s._latecyCheckMultiply/2,s.dataEmitIntervalMs=r===null||r===0?void 0:r||5*1e3,In("latencyCheckIntervalMs: %s dataEmitIntervalMs: %s",s.latencyCheckIntervalMs,s.dataEmitIntervalMs),s.dataEmitIntervalMs?In("Expecting ~%s events per summary",s.latencyCheckIntervalMs/s.dataEmitIntervalMs):In("Not emitting summaries"),s.asyncTestFn=n}start(){globalThis.process&&globalThis.process.hrtime?(In("Using process.hrtime for timing"),this.now=globalThis.process.hrtime,this.getDeltaMS=e=>{let r=this.now(e);return r[0]*1e3+r[1]/1e6}):typeof window!="undefined"&&window.performance&&window.performance.now?(In("Using performance.now for timing"),this.now=window.performance.now.bind(window.performance),this.getDeltaMS=e=>Math.round(this.now()-e)):(In("Using Date.now for timing"),this.now=Date.now,this.getDeltaMS=e=>this.now()-e),this._latencyData=this._initLatencyData(),J3()&&(this._visibilityChangeEmitter=new Z3,this._visibilityChangeEmitter.on("visibilityChange",e=>{e?this._startTimers():(this._emitSummary(),this._stopTimers())})),(!this._visibilityChangeEmitter||this._visibilityChangeEmitter.isVisible())&&this._startTimers()}stop(){this._stopTimers()}_startTimers(){this._checkLatencyID||(this._checkLatency(),this.dataEmitIntervalMs&&(this._emitIntervalID=setInterval(()=>this._emitSummary(),this.dataEmitIntervalMs),typeof this._emitIntervalID.unref=="function"&&this._emitIntervalID.unref()))}_stopTimers(){this._checkLatencyID&&(clearTimeout(this._checkLatencyID),this._checkLatencyID=void 0),this._emitIntervalID&&(clearInterval(this._emitIntervalID),this._emitIntervalID=void 0)}_emitSummary(){let e=this.getSummary();e.events>0&&this.emit("data",e)}getSummary(){let e={events:this._latencyData.events,minMs:this._latencyData.minMs,maxMs:this._latencyData.maxMs,avgMs:this._latencyData.events?this._latencyData.totalMs/this._latencyData.events:Number.POSITIVE_INFINITY,lengthMs:this.getDeltaMS(this._latencyData.startTime)};return this._latencyData=this._initLatencyData(),In("Summary: %O",e),e}_checkLatency(){let e=this,r=Math.random()*e._latecyCheckMultiply-e._latecyCheckSubtract,n={deltaOffset:Math.ceil(e.latencyCheckIntervalMs+r),startTime:e.now()},i=()=>{if(!this._checkLatencyID)return;let s=e.getDeltaMS(n.startTime)-n.deltaOffset;e._checkLatency(),e._latencyData.events++,e._latencyData.minMs=Math.min(e._latencyData.minMs,s),e._latencyData.maxMs=Math.max(e._latencyData.maxMs,s),e._latencyData.totalMs+=s,In("MS: %s Data: %O",s,e._latencyData)};In("localData: %O",n),this._checkLatencyID=setTimeout(()=>{e.asyncTestFn?(n.deltaOffset=0,n.startTime=e.now(),e.asyncTestFn(i)):(n.deltaOffset-=1,i())},n.deltaOffset),typeof this._checkLatencyID.unref=="function"&&this._checkLatencyID.unref()}_initLatencyData(){return{startTime:this.now(),minMs:Number.POSITIVE_INFINITY,maxMs:Number.NEGATIVE_INFINITY,events:0,totalMs:0}}};function J3(){return typeof window!="undefined"}wE.exports=EE});var Pd=w((KF,xE)=>{"use strict";var SE=class extends Map{constructor(e){super();let{system:r,component:n,metric:i,metrics:s}=e;this._system=r,this._component=n,this._metric=i,this._metrics=s,this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size})}set(e,r){return super.set(e,r),this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size}),this}delete(e){let r=super.delete(e);return this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size}),r}clear(){super.clear(),this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size})}};xE.exports=({system:t="libp2p",component:e,metric:r,metrics:n})=>{let i;return n?i=new SE({system:t,component:e,metric:r,metrics:n}):i=new Map,i}});var OE=w((VF,NE)=>{"use strict";var AE=Te(),Mr=Object.assign(AE("libp2p:connection-manager"),{error:AE("libp2p:connection-manager:err")}),CE=de(),eO=Hs(),tO=_E(),IE=va(),{EventEmitter:rO}=Qt(),TE=Pd(),nO=Rt(),{codes:{ERR_INVALID_PARAMETERS:RE}}=je(),iO={maxConnections:1/0,minConnections:0,maxData:1/0,maxSentData:1/0,maxReceivedData:1/0,maxEventLoopDelay:1/0,pollInterval:2e3,autoDialInterval:1e4,movingAverageInterval:6e4,defaultPeerValue:1},BE="connection-manager",sO="peer-connections",oO="peer-values",PE=class extends rO{constructor(e,r={}){super();if(this._libp2p=e,this._peerId=e.peerId.toB58String(),this._options=eO.call({ignoreUndefined:!0},iO,r),this._options.maxConnections<this._options.minConnections)throw CE(new Error("Connection Manager maxConnections must be greater than minConnections"),RE);Mr("options: %j",this._options),this._peerValues=TE({component:BE,metric:oO,metrics:this._libp2p.metrics}),this.connections=TE({component:BE,metric:sO,metrics:this._libp2p.metrics}),this._started=!1,this._timer=null,this._checkMetrics=this._checkMetrics.bind(this),this._latencyMonitor=new tO({latencyCheckIntervalMs:this._options.pollInterval,dataEmitIntervalMs:this._options.pollInterval}),this.setMaxListeners(1/0)}get size(){return Array.from(this.connections.values()).reduce((e,r)=>e+r.length,0)}start(){this._libp2p.metrics&&(this._timer=this._timer||IE(this._checkMetrics,this._options.pollInterval)),this._latencyMonitor.start(),this._onLatencyMeasure=this._onLatencyMeasure.bind(this),this._latencyMonitor.on("data",this._onLatencyMeasure),this._started=!0,Mr("started")}async stop(){this._timer&&this._timer.clear(),this._latencyMonitor.removeListener("data",this._onLatencyMeasure),this._latencyMonitor.stop(),this._started=!1,await this._close(),Mr("stopped")}async _close(){let e=[];for(let r of this.connections.values())for(let n of r)e.push(n.close());await Promise.all(e),this.connections.clear()}setPeerValue(e,r){if(r<0||r>1)throw new Error("value should be a number between 0 and 1");this._peerValues.set(e.toB58String(),r)}async _checkMetrics(){if(this._libp2p.metrics)try{let e=this._libp2p.metrics.global.movingAverages,r=e.dataReceived[this._options.movingAverageInterval].movingAverage();await this._checkMaxLimit("maxReceivedData",r);let n=e.dataSent[this._options.movingAverageInterval].movingAverage();await this._checkMaxLimit("maxSentData",n);let i=r+n;await this._checkMaxLimit("maxData",i),Mr("metrics update",i)}finally{this._timer=IE(this._checkMetrics,this._options.pollInterval)}}async onConnect(e){if(!this._started){await e.close();return}let r=e.remotePeer,n=r.toB58String(),i=this.connections.get(n);this.emit("peer:connect",e),i?i.push(e):this.connections.set(n,[e]),await this._libp2p.peerStore.keyBook.set(r,r.pubKey),this._peerValues.has(n)||this._peerValues.set(n,this._options.defaultPeerValue),await this._checkMaxLimit("maxConnections",this.size)}onDisconnect(e){if(!this._started)return;let r=e.remotePeer.toB58String(),n=this.connections.get(r);n&&n.length>1?(n=n.filter(i=>i.id!==e.id),this.connections.set(r,n)):n&&(this.connections.delete(r),this._peerValues.delete(e.remotePeer.toB58String()),this.emit("peer:disconnect",e),this._libp2p.metrics&&this._libp2p.metrics.onPeerDisconnected(e.remotePeer))}get(e){let r=this.getAll(e);return r.length?r[0]:null}getAll(e){if(!nO.isPeerId(e))throw CE(new Error("peerId must be an instance of peer-id"),RE);let r=e.toB58String(),n=this.connections.get(r);return n?n.filter(i=>i.stat.status==="open"):[]}_onLatencyMeasure(e){this._checkMaxLimit("maxEventLoopDelay",e.avgMs).catch(r=>{Mr.error(r)})}async _checkMaxLimit(e,r){let n=this._options[e];Mr("checking limit of %s. current value: %d of %d",e,r,n),r>n&&(Mr("%s: limit exceeded: %s, %d",this._peerId,e,r),await this._maybeDisconnectOne())}async _maybeDisconnectOne(){if(this._options.minConnections<this.connections.size){let e=Array.from(new Map([...this._peerValues.entries()].sort((n,i)=>n[1]-i[1])));Mr("%s: sorted peer values: %j",this._peerId,e);let r=e[0];if(r){let n=r[0];Mr("%s: lowest value peer is %s",this._peerId,n),Mr("%s: closing a connection to %j",this._peerId,n);for(let i of this.connections.values())if(i[0].remotePeer.toB58String()===n){i[0].close().catch(s=>{Mr.error(s)}),this.onDisconnect(i[0]);break}}}}};NE.exports=PE});var LE=w((jF,DE)=>{"use strict";var aO=Mi(),cO=async function*(t,e){yield*(await aO(t)).sort(e)};DE.exports=cO});var FE=w(($F,ME)=>{"use strict";var kE=Te(),uO=Hs(),qE=va(),lO=Mi(),{pipe:fO}=ir(),dO=Fi(),hO=LE(),si=Object.assign(kE("libp2p:connection-manager:auto-dialler"),{error:kE("libp2p:connection-manager:auto-dialler:err")}),pO={enabled:!0,minConnections:0,autoDialInterval:1e4},UE=class{constructor(e,r={}){this._options=uO.call({ignoreUndefined:!0},pO,r),this._libp2p=e,this._running=!1,this._autoDialTimeout=null,this._autoDial=this._autoDial.bind(this),si("options: %j",this._options)}async start(){if(!this._options.enabled){si("not enabled");return}this._running=!0,this._autoDial().catch(e=>{si.error("could start autodial",e)}),si("started")}async stop(){if(!this._options.enabled){si("not enabled");return}this._running=!1,this._autoDialTimeout&&this._autoDialTimeout.clear(),si("stopped")}async _autoDial(){let e=this._options.minConnections;if(this._libp2p.connections.size>=e){this._autoDialTimeout=qE(this._autoDial,this._options.autoDialInterval);return}let r=await fO(this._libp2p.peerStore.getPeers(),n=>dO(n,i=>!i.id.equals(this._libp2p.peerId)),n=>hO(n,(i,s)=>s.protocols&&s.protocols.length&&(!i.protocols||!i.protocols.length)||s.id.pubKey&&!i.id.pubKey?1:-1),n=>lO(n));for(let n=0;this._running&&n<r.length&&this._libp2p.connections.size<e;n++){let i=r[n];if(!this._libp2p.connectionManager.get(i.id)){si("connecting to a peerStore stored peer %s",i.id.toB58String());try{await this._libp2p.dialer.connectToPeer(i.id)}catch(s){si.error("could not connect to peerStore stored peer",s)}}}!this._running||(this._autoDialTimeout=qE(this._autoDial,this._options.autoDialInterval))}};ME.exports=UE});var XE=w((HF,QE)=>{"use strict";var{Multiaddr:Nd}=qt(),KE=ce("dns4"),VE=ce("dns6"),jE=ce("dnsaddr"),Gi=Ut(ce("dns"),jE,KE,VE),Ia=Ut(ce("ip4"),ce("ip6")),Ys=Ut(ve(Ia,ce("tcp")),ve(Gi,ce("tcp"))),Od=ve(Ia,ce("udp")),$E=ve(Od,ce("utp")),HE=ve(Od,ce("quic")),Qs=Ut(ve(Ys,ce("ws")),ve(Gi,ce("ws"))),Xs=Ut(ve(Ys,ce("wss")),ve(Gi,ce("wss"))),gu=Ut(ve(Ys,ce("http")),ve(Ia,ce("http")),ve(Gi,ce("http"))),mu=Ut(ve(Ys,ce("https")),ve(Ia,ce("https")),ve(Gi,ce("https"))),Dd=Ut(ve(Qs,ce("p2p-webrtc-star"),ce("p2p")),ve(Xs,ce("p2p-webrtc-star"),ce("p2p")),ve(Qs,ce("p2p-webrtc-star")),ve(Xs,ce("p2p-webrtc-star"))),yO=Ut(ve(Qs,ce("p2p-websocket-star"),ce("p2p")),ve(Xs,ce("p2p-websocket-star"),ce("p2p")),ve(Qs,ce("p2p-websocket-star")),ve(Xs,ce("p2p-websocket-star"))),Ld=Ut(ve(gu,ce("p2p-webrtc-direct"),ce("p2p")),ve(mu,ce("p2p-webrtc-direct"),ce("p2p")),ve(gu,ce("p2p-webrtc-direct")),ve(mu,ce("p2p-webrtc-direct"))),Zs=Ut(Qs,Xs,gu,mu,Dd,Ld,Ys,$E,HE,Gi),gO=Ut(ve(Zs,ce("p2p-stardust"),ce("p2p")),ve(Zs,ce("p2p-stardust"))),oi=Ut(ve(Zs,ce("p2p")),Dd,Ld,ce("p2p")),zE=Ut(ve(oi,ce("p2p-circuit"),oi),ve(oi,ce("p2p-circuit")),ve(ce("p2p-circuit"),oi),ve(Zs,ce("p2p-circuit")),ve(ce("p2p-circuit"),Zs),ce("p2p-circuit")),GE=()=>Ut(ve(zE,GE),zE),Js=GE(),WE=Ut(ve(Js,oi,Js),ve(oi,Js),ve(Js,oi),Js,oi);QE.exports={DNS:Gi,DNS4:KE,DNS6:VE,DNSADDR:jE,IP:Ia,TCP:Ys,UDP:Od,QUIC:HE,UTP:$E,HTTP:gu,HTTPS:mu,WebSockets:Qs,WebSocketsSecure:Xs,WebSocketStar:yO,WebRTCStar:Dd,WebRTCDirect:Ld,Reliable:Zs,Stardust:gO,Circuit:Js,P2P:WE,IPFS:WE};function YE(t){function e(r){if(!Nd.isMultiaddr(r))try{r=new Nd(r)}catch(i){return!1}let n=t(r.protoNames());return n===null?!1:n===!0||n===!1?n:n.length===0}return e}function ve(...t){function e(r){if(r.length<t.length)return null;let n=r;return t.some(i=>(n=typeof i=="function"?i().partialMatch(r):i.partialMatch(r),Array.isArray(n)&&(r=n),n===null)),n}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:YE(e),partialMatch:e}}function Ut(...t){function e(n){let i=null;return t.some(s=>{let o=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return o?(i=o,!0):!1}),i}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:YE(e),partialMatch:e}}function ce(t){let e=t;function r(i){let s;if(typeof i=="string"||i instanceof Uint8Array)try{s=new Nd(i)}catch(a){return!1}else s=i;let o=s.protoNames();return o.length===1&&o[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:r,partialMatch:n}}});var eo=w((zF,JE)=>{"use strict";var Wi=gn(),vu=Wi.Reader,ZE=Wi.Writer,Ar=Wi.util,At=Wi.roots["libp2p-circuit"]||(Wi.roots["libp2p-circuit"]={});At.CircuitRelay=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.type=1,t.prototype.srcPeer=null,t.prototype.dstPeer=null,t.prototype.code=100,t.encode=function(r,n){return n||(n=ZE.create()),r.type!=null&&Object.hasOwnProperty.call(r,"type")&&n.uint32(8).int32(r.type),r.srcPeer!=null&&Object.hasOwnProperty.call(r,"srcPeer")&&At.CircuitRelay.Peer.encode(r.srcPeer,n.uint32(18).fork()).ldelim(),r.dstPeer!=null&&Object.hasOwnProperty.call(r,"dstPeer")&&At.CircuitRelay.Peer.encode(r.dstPeer,n.uint32(26).fork()).ldelim(),r.code!=null&&Object.hasOwnProperty.call(r,"code")&&n.uint32(32).int32(r.code),n},t.decode=function(r,n){r instanceof vu||(r=vu.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new At.CircuitRelay;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.type=r.int32();break;case 2:s.srcPeer=At.CircuitRelay.Peer.decode(r,r.uint32());break;case 3:s.dstPeer=At.CircuitRelay.Peer.decode(r,r.uint32());break;case 4:s.code=r.int32();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof At.CircuitRelay)return r;var n=new At.CircuitRelay;switch(r.type){case"HOP":case 1:n.type=1;break;case"STOP":case 2:n.type=2;break;case"STATUS":case 3:n.type=3;break;case"CAN_HOP":case 4:n.type=4;break}if(r.srcPeer!=null){if(typeof r.srcPeer!="object")throw TypeError(".CircuitRelay.srcPeer: object expected");n.srcPeer=At.CircuitRelay.Peer.fromObject(r.srcPeer)}if(r.dstPeer!=null){if(typeof r.dstPeer!="object")throw TypeError(".CircuitRelay.dstPeer: object expected");n.dstPeer=At.CircuitRelay.Peer.fromObject(r.dstPeer)}switch(r.code){case"SUCCESS":case 100:n.code=100;break;case"HOP_SRC_ADDR_TOO_LONG":case 220:n.code=220;break;case"HOP_DST_ADDR_TOO_LONG":case 221:n.code=221;break;case"HOP_SRC_MULTIADDR_INVALID":case 250:n.code=250;break;case"HOP_DST_MULTIADDR_INVALID":case 251:n.code=251;break;case"HOP_NO_CONN_TO_DST":case 260:n.code=260;break;case"HOP_CANT_DIAL_DST":case 261:n.code=261;break;case"HOP_CANT_OPEN_DST_STREAM":case 262:n.code=262;break;case"HOP_CANT_SPEAK_RELAY":case 270:n.code=270;break;case"HOP_CANT_RELAY_TO_SELF":case 280:n.code=280;break;case"STOP_SRC_ADDR_TOO_LONG":case 320:n.code=320;break;case"STOP_DST_ADDR_TOO_LONG":case 321:n.code=321;break;case"STOP_SRC_MULTIADDR_INVALID":case 350:n.code=350;break;case"STOP_DST_MULTIADDR_INVALID":case 351:n.code=351;break;case"STOP_RELAY_REFUSED":case 390:n.code=390;break;case"MALFORMED_MESSAGE":case 400:n.code=400;break}return n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.type=n.enums===String?"HOP":1,i.srcPeer=null,i.dstPeer=null,i.code=n.enums===String?"SUCCESS":100),r.type!=null&&r.hasOwnProperty("type")&&(i.type=n.enums===String?At.CircuitRelay.Type[r.type]:r.type),r.srcPeer!=null&&r.hasOwnProperty("srcPeer")&&(i.srcPeer=At.CircuitRelay.Peer.toObject(r.srcPeer,n)),r.dstPeer!=null&&r.hasOwnProperty("dstPeer")&&(i.dstPeer=At.CircuitRelay.Peer.toObject(r.dstPeer,n)),r.code!=null&&r.hasOwnProperty("code")&&(i.code=n.enums===String?At.CircuitRelay.Status[r.code]:r.code),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Wi.util.toJSONOptions)},t.Status=function(){var e={},r=Object.create(e);return r[e[100]="SUCCESS"]=100,r[e[220]="HOP_SRC_ADDR_TOO_LONG"]=220,r[e[221]="HOP_DST_ADDR_TOO_LONG"]=221,r[e[250]="HOP_SRC_MULTIADDR_INVALID"]=250,r[e[251]="HOP_DST_MULTIADDR_INVALID"]=251,r[e[260]="HOP_NO_CONN_TO_DST"]=260,r[e[261]="HOP_CANT_DIAL_DST"]=261,r[e[262]="HOP_CANT_OPEN_DST_STREAM"]=262,r[e[270]="HOP_CANT_SPEAK_RELAY"]=270,r[e[280]="HOP_CANT_RELAY_TO_SELF"]=280,r[e[320]="STOP_SRC_ADDR_TOO_LONG"]=320,r[e[321]="STOP_DST_ADDR_TOO_LONG"]=321,r[e[350]="STOP_SRC_MULTIADDR_INVALID"]=350,r[e[351]="STOP_DST_MULTIADDR_INVALID"]=351,r[e[390]="STOP_RELAY_REFUSED"]=390,r[e[400]="MALFORMED_MESSAGE"]=400,r}(),t.Type=function(){var e={},r=Object.create(e);return r[e[1]="HOP"]=1,r[e[2]="STOP"]=2,r[e[3]="STATUS"]=3,r[e[4]="CAN_HOP"]=4,r}(),t.Peer=function(){function e(r){if(this.addrs=[],r)for(var n=Object.keys(r),i=0;i<n.length;++i)r[n[i]]!=null&&(this[n[i]]=r[n[i]])}return e.prototype.id=Ar.newBuffer([]),e.prototype.addrs=Ar.emptyArray,e.encode=function(n,i){if(i||(i=ZE.create()),i.uint32(10).bytes(n.id),n.addrs!=null&&n.addrs.length)for(var s=0;s<n.addrs.length;++s)i.uint32(18).bytes(n.addrs[s]);return i},e.decode=function(n,i){n instanceof vu||(n=vu.create(n));for(var s=i===void 0?n.len:n.pos+i,o=new At.CircuitRelay.Peer;n.pos<s;){var a=n.uint32();switch(a>>>3){case 1:o.id=n.bytes();break;case 2:o.addrs&&o.addrs.length||(o.addrs=[]),o.addrs.push(n.bytes());break;default:n.skipType(a&7);break}}if(!o.hasOwnProperty("id"))throw Ar.ProtocolError("missing required 'id'",{instance:o});return o},e.fromObject=function(n){if(n instanceof At.CircuitRelay.Peer)return n;var i=new At.CircuitRelay.Peer;if(n.id!=null&&(typeof n.id=="string"?Ar.base64.decode(n.id,i.id=Ar.newBuffer(Ar.base64.length(n.id)),0):n.id.length&&(i.id=n.id)),n.addrs){if(!Array.isArray(n.addrs))throw TypeError(".CircuitRelay.Peer.addrs: array expected");i.addrs=[];for(var s=0;s<n.addrs.length;++s)typeof n.addrs[s]=="string"?Ar.base64.decode(n.addrs[s],i.addrs[s]=Ar.newBuffer(Ar.base64.length(n.addrs[s])),0):n.addrs[s].length&&(i.addrs[s]=n.addrs[s])}return i},e.toObject=function(n,i){i||(i={});var s={};if((i.arrays||i.defaults)&&(s.addrs=[]),i.defaults&&(i.bytes===String?s.id="":(s.id=[],i.bytes!==Array&&(s.id=Ar.newBuffer(s.id)))),n.id!=null&&n.hasOwnProperty("id")&&(s.id=i.bytes===String?Ar.base64.encode(n.id,0,n.id.length):i.bytes===Array?Array.prototype.slice.call(n.id):n.id),n.addrs&&n.addrs.length){s.addrs=[];for(var o=0;o<n.addrs.length;++o)s.addrs[o]=i.bytes===String?Ar.base64.encode(n.addrs[o],0,n.addrs[o].length):i.bytes===Array?Array.prototype.slice.call(n.addrs[o]):n.addrs[o]}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,Wi.util.toJSONOptions)},e}(),t}();JE.exports=At});var tw=w((GF,ew)=>{ew.exports=function(e){if(e){if(typeof e[Symbol.iterator]=="function")return e[Symbol.iterator]();if(typeof e[Symbol.asyncIterator]=="function")return e[Symbol.asyncIterator]();if(typeof e.next=="function")return e}throw new Error("argument is not an iterator or iterable")}});var nw=w((YF,rw)=>{rw.exports=class extends Error{constructor(e,r){super(e||"The operation was aborted");this.type="aborted",this.code=r||"ABORT_ERR"}}});var bu=w((QF,Yi)=>{var mO=tw(),kd=nw(),iw=(t,e,r)=>qd(t,Array.isArray(e)?e:[{signal:e,options:r}]),qd=(t,e)=>{t=mO(t),e=e.map(({signal:n,options:i})=>({signal:n,options:i||{}}));async function*r(){let n,i=()=>{n&&n()};for(let{signal:s}of e)s.addEventListener("abort",i);for(;;){let s;try{for(let{signal:a,options:c}of e)if(a.aborted){let{abortMessage:u,abortCode:l}=c;throw new kd(u,l)}let o=new Promise((a,c)=>{n=()=>{let{options:u}=e.find(({signal:d})=>d.aborted),{abortMessage:l,abortCode:f}=u;c(new kd(l,f))}});s=await Promise.race([o,t.next()]),n=null}catch(o){for(let{signal:u}of e)u.removeEventListener("abort",i);let a=e.find(({signal:u})=>u.aborted),c=o.type==="aborted"&&a;if(c&&a.options.onAbort&&await a.options.onAbort(t),typeof t.return=="function")try{let u=t.return();u instanceof Promise&&u.catch(l=>{a.options.onReturnError!=null&&a.options.onReturnError(l)})}catch(u){a.options.onReturnError!=null&&a.options.onReturnError(u)}if(c&&a.options.returnOnAbort)return;throw o}if(s.done)break;yield s.value}for(let{signal:s}of e)s.removeEventListener("abort",i)}return r()},sw=(t,e,r)=>ow(t,Array.isArray(e)?e:[{signal:e,options:r}]),ow=(t,e)=>r=>t(qd(r,e)),vO=(t,e,r)=>bO(t,Array.isArray(e)?e:[{signal:e,options:r}]),bO=(t,e)=>({sink:ow(t.sink,e),source:qd(t.source,e)});Yi.exports=iw;Yi.exports.AbortError=kd;Yi.exports.source=iw;Yi.exports.sink=sw;Yi.exports.transform=sw;Yi.exports.duplex=vO});var uw=w((XF,cw)=>{"use strict";var{source:aw}=bu(),EO=Te(),wO=EO("libp2p:stream:converter");function _O({stream:t,remoteAddr:e,localAddr:r},n={}){let{sink:i,source:s}=t,o={async sink(c){n.signal&&(c=aw(c,n.signal));try{await i(c)}catch(u){u.type!=="aborted"&&wO(u)}a()},source:n.signal?aw(s,n.signal):s,conn:t,localAddr:r,remoteAddr:e,timeline:{open:Date.now(),close:void 0},close(){return i(new Uint8Array(0)),a()}};function a(){return o.timeline.close||(o.timeline.close=Date.now()),Promise.resolve()}return o}cw.exports=_O});var Ta=w((ZF,lw)=>{"use strict";lw.exports={relay:"/libp2p/circuit/relay/0.1.0"}});var dw=w((JF,fw)=>{"use strict";var{EventEmitter:SO}=Qt(),{Multiaddr:xO}=qt();fw.exports=t=>{let e=new Map;async function r(s){let o=String(s).split("/p2p-circuit").find(u=>u!==""),a=await t.dial(new xO(o)),c=a.remoteAddr.encapsulate("/p2p-circuit");e.set(a.remotePeer.toB58String(),c),i.emit("listening")}function n(){let s=[];for(let o of e.values())s.push(o);return s}let i=Object.assign(new SO,{close:()=>Promise.resolve(),listen:r,getAddrs:n});return t.connectionManager.on("peer:disconnect",s=>{e.delete(s.remotePeer.toB58String())&&i.emit("close")}),i}});var Ud=w((eK,yw)=>{"use strict";var{Multiaddr:hw}=qt(),{CircuitRelay:Qi}=eo();function pw(t,e){t.write({type:Qi.Type.STATUS,code:e})}function AO(t,e){try{t.dstPeer&&t.dstPeer.addrs&&t.dstPeer.addrs.forEach(r=>new hw(r))}catch(r){throw pw(e,t.type===Qi.Type.HOP?Qi.Status.HOP_DST_MULTIADDR_INVALID:Qi.Status.STOP_DST_MULTIADDR_INVALID),r}try{t.srcPeer&&t.srcPeer.addrs&&t.srcPeer.addrs.forEach(r=>new hw(r))}catch(r){throw pw(e,t.type===Qi.Type.HOP?Qi.Status.HOP_SRC_MULTIADDR_INVALID:Qi.Status.STOP_SRC_MULTIADDR_INVALID),r}}yw.exports={validateAddrs:AO}});var vw=w(Eu=>{"use strict";Eu.byteLength=IO;Eu.toByteArray=RO;Eu.fromByteArray=NO;var un=[],Cr=[],CO=typeof Uint8Array!="undefined"?Uint8Array:Array,Md="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Xi=0,gw=Md.length;Xi<gw;++Xi)un[Xi]=Md[Xi],Cr[Md.charCodeAt(Xi)]=Xi;var Xi,gw;Cr["-".charCodeAt(0)]=62;Cr["_".charCodeAt(0)]=63;function mw(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function IO(t){var e=mw(t),r=e[0],n=e[1];return(r+n)*3/4-n}function TO(t,e,r){return(e+r)*3/4-r}function RO(t){var e,r=mw(t),n=r[0],i=r[1],s=new CO(TO(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)e=Cr[t.charCodeAt(c)]<<18|Cr[t.charCodeAt(c+1)]<<12|Cr[t.charCodeAt(c+2)]<<6|Cr[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Cr[t.charCodeAt(c)]<<2|Cr[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=Cr[t.charCodeAt(c)]<<10|Cr[t.charCodeAt(c+1)]<<4|Cr[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function BO(t){return un[t>>18&63]+un[t>>12&63]+un[t>>6&63]+un[t&63]}function PO(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(BO(n));return i.join("")}function NO(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(PO(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(un[e>>2]+un[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(un[e>>10]+un[e>>4&63]+un[e<<2&63]+"=")),i.join("")}});var bw=w(Fd=>{Fd.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,u=c>>1,l=-7,f=r?i-1:0,d=r?-1:1,p=t[e+f];for(f+=d,s=p&(1<<-l)-1,p>>=-l,l+=a;l>0;s=s*256+t[e+f],f+=d,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=n;l>0;o=o*256+t[e+f],f+=d,l-=8);if(s===0)s=1-u;else{if(s===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-u}return(p?-1:1)*o*Math.pow(2,s-n)};Fd.write=function(t,e,r,n,i,s){var o,a,c,u=s*8-i-1,l=(1<<u)-1,f=l>>1,d=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,h=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=l):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+f>=1?e+=d/c:e+=d*Math.pow(2,1-f),e*c>=2&&(o++,c/=2),o+f>=l?(a=0,o=l):o+f>=1?(a=(e*c-1)*Math.pow(2,i),o=o+f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=a&255,p+=h,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;t[r+p]=o&255,p+=h,o/=256,u-=8);t[r+p-h]|=g*128}});var ci=w(io=>{"use strict";var Kd=vw(),to=bw(),Ew=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;io.Buffer=F;io.SlowBuffer=UO;io.INSPECT_MAX_BYTES=50;var wu=2147483647;io.kMaxLength=wu;F.TYPED_ARRAY_SUPPORT=OO();!F.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function OO(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch(t){return!1}}Object.defineProperty(F.prototype,"parent",{enumerable:!0,get:function(){if(!!F.isBuffer(this))return this.buffer}});Object.defineProperty(F.prototype,"offset",{enumerable:!0,get:function(){if(!!F.isBuffer(this))return this.byteOffset}});function Tn(t){if(t>wu)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,F.prototype),e}function F(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Vd(t)}return ww(t,e,r)}F.poolSize=8192;function ww(t,e,r){if(typeof t=="string")return LO(t,e);if(ArrayBuffer.isView(t))return kO(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(ln(t,ArrayBuffer)||t&&ln(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer!="undefined"&&(ln(t,SharedArrayBuffer)||t&&ln(t.buffer,SharedArrayBuffer)))return $d(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return F.from(n,e,r);let i=qO(t);if(i)return i;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return F.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}F.from=function(t,e,r){return ww(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function _w(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function DO(t,e,r){return _w(t),t<=0?Tn(t):e!==void 0?typeof r=="string"?Tn(t).fill(e,r):Tn(t).fill(e):Tn(t)}F.alloc=function(t,e,r){return DO(t,e,r)};function Vd(t){return _w(t),Tn(t<0?0:Hd(t)|0)}F.allocUnsafe=function(t){return Vd(t)};F.allocUnsafeSlow=function(t){return Vd(t)};function LO(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let r=Sw(t,e)|0,n=Tn(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function jd(t){let e=t.length<0?0:Hd(t.length)|0,r=Tn(e);for(let n=0;n<e;n+=1)r[n]=t[n]&255;return r}function kO(t){if(ln(t,Uint8Array)){let e=new Uint8Array(t);return $d(e.buffer,e.byteOffset,e.byteLength)}return jd(t)}function $d(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return e===void 0&&r===void 0?n=new Uint8Array(t):r===void 0?n=new Uint8Array(t,e):n=new Uint8Array(t,e,r),Object.setPrototypeOf(n,F.prototype),n}function qO(t){if(F.isBuffer(t)){let e=Hd(t.length)|0,r=Tn(e);return r.length===0||t.copy(r,0,0,e),r}if(t.length!==void 0)return typeof t.length!="number"||Wd(t.length)?Tn(0):jd(t);if(t.type==="Buffer"&&Array.isArray(t.data))return jd(t.data)}function Hd(t){if(t>=wu)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+wu.toString(16)+" bytes");return t|0}function UO(t){return+t!=t&&(t=0),F.alloc(+t)}F.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==F.prototype};F.compare=function(e,r){if(ln(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),ln(r,Uint8Array)&&(r=F.from(r,r.offset,r.byteLength)),!F.isBuffer(e)||!F.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;let n=e.length,i=r.length;for(let s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==r[s]){n=e[s],i=r[s];break}return n<i?-1:i<n?1:0};F.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};F.concat=function(e,r){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return F.alloc(0);let n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;let i=F.allocUnsafe(r),s=0;for(n=0;n<e.length;++n){let o=e[n];if(ln(o,Uint8Array))s+o.length>i.length?(F.isBuffer(o)||(o=F.from(o)),o.copy(i,s)):Uint8Array.prototype.set.call(i,o,s);else if(F.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function Sw(t,e){if(F.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||ln(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);let r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Gd(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Lw(t).length;default:if(i)return n?-1:Gd(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=Sw;function MO(t,e,r){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return YO(this,e,r);case"utf8":case"utf-8":return Cw(this,e,r);case"ascii":return GO(this,e,r);case"latin1":case"binary":return WO(this,e,r);case"base64":return HO(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return QO(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function Zi(t,e,r){let n=t[e];t[e]=t[r],t[r]=n}F.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<e;r+=2)Zi(this,r,r+1);return this};F.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<e;r+=4)Zi(this,r,r+3),Zi(this,r+1,r+2);return this};F.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<e;r+=8)Zi(this,r,r+7),Zi(this,r+1,r+6),Zi(this,r+2,r+5),Zi(this,r+3,r+4);return this};F.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?Cw(this,0,e):MO.apply(this,arguments)};F.prototype.toLocaleString=F.prototype.toString;F.prototype.equals=function(e){if(!F.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:F.compare(this,e)===0};F.prototype.inspect=function(){let e="",r=io.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};Ew&&(F.prototype[Ew]=F.prototype.inspect);F.prototype.compare=function(e,r,n,i,s){if(ln(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),!F.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;let o=s-i,a=n-r,c=Math.min(o,a),u=this.slice(i,s),l=e.slice(r,n);for(let f=0;f<c;++f)if(u[f]!==l[f]){o=u[f],a=l[f];break}return o<a?-1:a<o?1:0};function xw(t,e,r,n,i){if(t.length===0)return-1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Wd(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=F.from(e,n)),F.isBuffer(e))return e.length===0?-1:Aw(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Aw(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Aw(t,e,r,n,i){let s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,a/=2,r/=2}function c(l,f){return s===1?l[f]:l.readUInt16BE(f*s)}let u;if(i){let l=-1;for(u=r;u<o;u++)if(c(t,u)===c(e,l===-1?0:u-l)){if(l===-1&&(l=u),u-l+1===a)return l*s}else l!==-1&&(u-=u-l),l=-1}else for(r+a>o&&(r=o-a),u=r;u>=0;u--){let l=!0;for(let f=0;f<a;f++)if(c(t,u+f)!==c(e,f)){l=!1;break}if(l)return u}return-1}F.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};F.prototype.indexOf=function(e,r,n){return xw(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return xw(this,e,r,n,!1)};function FO(t,e,r,n){r=Number(r)||0;let i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;let s=e.length;n>s/2&&(n=s/2);let o;for(o=0;o<n;++o){let a=parseInt(e.substr(o*2,2),16);if(Wd(a))return o;t[r+o]=a}return o}function KO(t,e,r,n){return _u(Gd(e,t.length-r),t,r,n)}function VO(t,e,r,n){return _u(eD(e),t,r,n)}function jO(t,e,r,n){return _u(Lw(e),t,r,n)}function $O(t,e,r,n){return _u(tD(e,t.length-r),t,r,n)}F.prototype.write=function(e,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return FO(this,e,r,n);case"utf8":case"utf-8":return KO(this,e,r,n);case"ascii":case"latin1":case"binary":return VO(this,e,r,n);case"base64":return jO(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return $O(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};F.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function HO(t,e,r){return e===0&&r===t.length?Kd.fromByteArray(t):Kd.fromByteArray(t.slice(e,r))}function Cw(t,e,r){r=Math.min(t.length,r);let n=[],i=e;for(;i<r;){let s=t[i],o=null,a=s>239?4:s>223?3:s>191?2:1;if(i+a<=r){let c,u,l,f;switch(a){case 1:s<128&&(o=s);break;case 2:c=t[i+1],(c&192)==128&&(f=(s&31)<<6|c&63,f>127&&(o=f));break;case 3:c=t[i+1],u=t[i+2],(c&192)==128&&(u&192)==128&&(f=(s&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:c=t[i+1],u=t[i+2],l=t[i+3],(c&192)==128&&(u&192)==128&&(l&192)==128&&(f=(s&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a}return zO(n)}var Iw=4096;function zO(t){let e=t.length;if(e<=Iw)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Iw));return r}function GO(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]&127);return n}function WO(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function YO(t,e,r){let n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let i="";for(let s=e;s<r;++s)i+=rD[t[s]];return i}function QO(t,e,r){let n=t.slice(e,r),i="";for(let s=0;s<n.length-1;s+=2)i+=String.fromCharCode(n[s]+n[s+1]*256);return i}F.prototype.slice=function(e,r){let n=this.length;e=~~e,r=r===void 0?n:~~r,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<e&&(r=e);let i=this.subarray(e,r);return Object.setPrototypeOf(i,F.prototype),i};function Ct(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}F.prototype.readUintLE=F.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ct(e,r,this.length);let i=this[e],s=1,o=0;for(;++o<r&&(s*=256);)i+=this[e+o]*s;return i};F.prototype.readUintBE=F.prototype.readUIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ct(e,r,this.length);let i=this[e+--r],s=1;for(;r>0&&(s*=256);)i+=this[e+--r]*s;return i};F.prototype.readUint8=F.prototype.readUInt8=function(e,r){return e=e>>>0,r||Ct(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Ct(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Ct(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};F.prototype.readUint32BE=F.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};F.prototype.readBigUInt64LE=ai(function(e){e=e>>>0,no(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Ra(e,this.length-8);let i=r+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,s=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(i)+(BigInt(s)<<BigInt(32))});F.prototype.readBigUInt64BE=ai(function(e){e=e>>>0,no(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Ra(e,this.length-8);let i=r*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],s=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(i)<<BigInt(32))+BigInt(s)});F.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ct(e,r,this.length);let i=this[e],s=1,o=0;for(;++o<r&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*r)),i};F.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ct(e,r,this.length);let i=r,s=1,o=this[e+--i];for(;i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};F.prototype.readInt8=function(e,r){return e=e>>>0,r||Ct(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Ct(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};F.prototype.readInt16BE=function(e,r){e=e>>>0,r||Ct(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};F.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};F.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};F.prototype.readBigInt64LE=ai(function(e){e=e>>>0,no(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Ra(e,this.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(i)<<BigInt(32))+BigInt(r+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)});F.prototype.readBigInt64BE=ai(function(e){e=e>>>0,no(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Ra(e,this.length-8);let i=(r<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n)});F.prototype.readFloatLE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),to.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ct(e,4,this.length),to.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ct(e,8,this.length),to.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ct(e,8,this.length),to.read(this,e,!1,52,8)};function er(t,e,r,n,i,s){if(!F.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}F.prototype.writeUintLE=F.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;er(this,e,r,n,a,0)}let s=1,o=0;for(this[r]=e&255;++o<n&&(s*=256);)this[r+o]=e/s&255;return r+n};F.prototype.writeUintBE=F.prototype.writeUIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;er(this,e,r,n,a,0)}let s=n-1,o=1;for(this[r+s]=e&255;--s>=0&&(o*=256);)this[r+s]=e/o&255;return r+n};F.prototype.writeUint8=F.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,1,255,0),this[r]=e&255,r+1};F.prototype.writeUint16LE=F.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeUint16BE=F.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeUint32LE=F.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};F.prototype.writeUint32BE=F.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function Tw(t,e,r,n,i){Dw(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,r}function Rw(t,e,r,n,i){Dw(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s=s>>8,t[r+6]=s,s=s>>8,t[r+5]=s,s=s>>8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o=o>>8,t[r+2]=o,o=o>>8,t[r+1]=o,o=o>>8,t[r]=o,r+8}F.prototype.writeBigUInt64LE=ai(function(e,r=0){return Tw(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});F.prototype.writeBigUInt64BE=ai(function(e,r=0){return Rw(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});F.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let c=Math.pow(2,8*n-1);er(this,e,r,n,c-1,-c)}let s=0,o=1,a=0;for(this[r]=e&255;++s<n&&(o*=256);)e<0&&a===0&&this[r+s-1]!==0&&(a=1),this[r+s]=(e/o>>0)-a&255;return r+n};F.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let c=Math.pow(2,8*n-1);er(this,e,r,n,c-1,-c)}let s=n-1,o=1,a=0;for(this[r+s]=e&255;--s>=0&&(o*=256);)e<0&&a===0&&this[r+s+1]!==0&&(a=1),this[r+s]=(e/o>>0)-a&255;return r+n};F.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};F.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};F.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||er(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};F.prototype.writeBigInt64LE=ai(function(e,r=0){return Tw(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});F.prototype.writeBigInt64BE=ai(function(e,r=0){return Rw(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Bw(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Pw(t,e,r,n,i){return e=+e,r=r>>>0,i||Bw(t,e,r,4,34028234663852886e22,-34028234663852886e22),to.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return Pw(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return Pw(this,e,r,!1,n)};function Nw(t,e,r,n,i){return e=+e,r=r>>>0,i||Bw(t,e,r,8,17976931348623157e292,-17976931348623157e292),to.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return Nw(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return Nw(this,e,r,!1,n)};F.prototype.copy=function(e,r,n,i){if(!F.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r<i-n&&(i=e.length-r+n);let s=i-n;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),r),s};F.prototype.fill=function(e,r,n,i){if(typeof e=="string"){if(typeof r=="string"?(i=r,r=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!F.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(e.length===1){let o=e.charCodeAt(0);(i==="utf8"&&o<128||i==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);let s;if(typeof e=="number")for(s=r;s<n;++s)this[s]=e;else{let o=F.isBuffer(e)?e:F.from(e,i),a=o.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-r;++s)this[s+r]=o[s%a]}return this};var ro={};function zd(t,e,r){ro[t]=class extends r{constructor(){super();Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(i){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:i,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}zd("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);zd("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError);zd("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=Ow(String(r)):typeof r=="bigint"&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=Ow(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);function Ow(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function XO(t,e,r){no(e,"offset"),(t[e]===void 0||t[e+r]===void 0)&&Ra(e,t.length-(r+1))}function Dw(t,e,r,n,i,s){if(t>r||t<e){let o=typeof e=="bigint"?"n":"",a;throw s>3?e===0||e===BigInt(0)?a=`>= 0${o} and < 2${o} ** ${(s+1)*8}${o}`:a=`>= -(2${o} ** ${(s+1)*8-1}${o}) and < 2 ** ${(s+1)*8-1}${o}`:a=`>= ${e}${o} and <= ${r}${o}`,new ro.ERR_OUT_OF_RANGE("value",a,t)}XO(n,i,s)}function no(t,e){if(typeof t!="number")throw new ro.ERR_INVALID_ARG_TYPE(e,"number",t)}function Ra(t,e,r){throw Math.floor(t)!==t?(no(t,r),new ro.ERR_OUT_OF_RANGE(r||"offset","an integer",t)):e<0?new ro.ERR_BUFFER_OUT_OF_BOUNDS:new ro.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}var ZO=/[^+/0-9A-Za-z-_]/g;function JO(t){if(t=t.split("=")[0],t=t.trim().replace(ZO,""),t.length<2)return"";for(;t.length%4!=0;)t=t+"=";return t}function Gd(t,e){e=e||1/0;let r,n=t.length,i=null,s=[];for(let o=0;o<n;++o){if(r=t.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function eD(t){let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function tD(t,e){let r,n,i,s=[];for(let o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}function Lw(t){return Kd.toByteArray(JO(t))}function _u(t,e,r,n){let i;for(i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ln(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function Wd(t){return t!==t}var rD=function(){let t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){let n=r*16;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function ai(t){return typeof BigInt=="undefined"?nD:t}function nD(){throw new Error("BigInt not supported")}});var Ji=w((sK,qw)=>{"use strict";var{Buffer:Fr}=ci(),kw=Symbol.for("BufferList");function Ge(t){if(!(this instanceof Ge))return new Ge(t);Ge._init.call(this,t)}Ge._init=function(e){Object.defineProperty(this,kw,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)};Ge.prototype._new=function(e){return new Ge(e)};Ge.prototype._offset=function(e){if(e===0)return[0,0];let r=0;for(let n=0;n<this._bufs.length;n++){let i=r+this._bufs[n].length;if(e<i||n===this._bufs.length-1)return[n,e-r];r=i}};Ge.prototype._reverseOffset=function(t){let e=t[0],r=t[1];for(let n=0;n<e;n++)r+=this._bufs[n].length;return r};Ge.prototype.get=function(e){if(e>this.length||e<0)return;let r=this._offset(e);return this._bufs[r[0]][r[1]]};Ge.prototype.slice=function(e,r){return typeof e=="number"&&e<0&&(e+=this.length),typeof r=="number"&&r<0&&(r+=this.length),this.copy(null,0,e,r)};Ge.prototype.copy=function(e,r,n,i){if((typeof n!="number"||n<0)&&(n=0),(typeof i!="number"||i>this.length)&&(i=this.length),n>=this.length||i<=0)return e||Fr.alloc(0);let s=!!e,o=this._offset(n),a=i-n,c=a,u=s&&r||0,l=o[1];if(n===0&&i===this.length){if(!s)return this._bufs.length===1?this._bufs[0]:Fr.concat(this._bufs,this.length);for(let f=0;f<this._bufs.length;f++)this._bufs[f].copy(e,u),u+=this._bufs[f].length;return e}if(c<=this._bufs[o[0]].length-l)return s?this._bufs[o[0]].copy(e,r,l,l+c):this._bufs[o[0]].slice(l,l+c);s||(e=Fr.allocUnsafe(a));for(let f=o[0];f<this._bufs.length;f++){let d=this._bufs[f].length-l;if(c>d)this._bufs[f].copy(e,u,l),u+=d;else{this._bufs[f].copy(e,u,l,l+c),u+=d;break}c-=d,l&&(l=0)}return e.length>u?e.slice(0,u):e};Ge.prototype.shallowSlice=function(e,r){if(e=e||0,r=typeof r!="number"?this.length:r,e<0&&(e+=this.length),r<0&&(r+=this.length),e===r)return this._new();let n=this._offset(e),i=this._offset(r),s=this._bufs.slice(n[0],i[0]+1);return i[1]===0?s.pop():s[s.length-1]=s[s.length-1].slice(0,i[1]),n[1]!==0&&(s[0]=s[0].slice(n[1])),this._new(s)};Ge.prototype.toString=function(e,r,n){return this.slice(r,n).toString(e)};Ge.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;)if(e>=this._bufs[0].length)e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}return this};Ge.prototype.duplicate=function(){let e=this._new();for(let r=0;r<this._bufs.length;r++)e.append(this._bufs[r]);return e};Ge.prototype.append=function(e){if(e==null)return this;if(e.buffer)this._appendBuffer(Fr.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let r=0;r<e.length;r++)this.append(e[r]);else if(this._isBufferList(e))for(let r=0;r<e._bufs.length;r++)this.append(e._bufs[r]);else typeof e=="number"&&(e=e.toString()),this._appendBuffer(Fr.from(e));return this};Ge.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length};Ge.prototype.indexOf=function(t,e,r){if(r===void 0&&typeof e=="string"&&(r=e,e=void 0),typeof t=="function"||Array.isArray(t))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof t=="number"?t=Fr.from([t]):typeof t=="string"?t=Fr.from(t,r):this._isBufferList(t)?t=t.slice():Array.isArray(t.buffer)?t=Fr.from(t.buffer,t.byteOffset,t.byteLength):Fr.isBuffer(t)||(t=Fr.from(t)),e=Number(e||0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let n=this._offset(e),i=n[0],s=n[1];for(;i<this._bufs.length;i++){let o=this._bufs[i];for(;s<o.length;)if(o.length-s>=t.length){let c=o.indexOf(t,s);if(c!==-1)return this._reverseOffset([i,c]);s=o.length-t.length+1}else{let c=this._reverseOffset([i,s]);if(this._match(c,t))return c;s++}s=0}return-1};Ge.prototype._match=function(t,e){if(this.length-t<e.length)return!1;for(let r=0;r<e.length;r++)if(this.get(t+r)!==e[r])return!1;return!0};(function(){let t={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let e in t)(function(r){t[r]===null?Ge.prototype[r]=function(n,i){return this.slice(n,n+i)[r](0,i)}:Ge.prototype[r]=function(n=0){return this.slice(n,n+t[r])[r](0)}})(e)})();Ge.prototype._isBufferList=function(e){return e instanceof Ge||Ge.isBufferList(e)};Ge.isBufferList=function(e){return e!=null&&e[kw]};qw.exports=Ge});var Yd=w((oK,Fw)=>{"use strict";var Uw=Ui(),{Buffer:iD}=ci(),Mw=(t,e,r)=>{let n=Uw.encode(t,e,r);return Mw.bytes=Uw.encode.bytes,e||iD.from(n)};Fw.exports=Mw});var zw=w((aK,Su)=>{"use strict";var{Buffer:Kw}=ci(),Vw=Ji(),jw=Yd(),Qd=8,$w=10*1024;function Hw(t){t=t||{};let e=Math.max(t.poolSize||$w,t.minPoolSize||Qd),r=t.lengthEncoder||jw;return async function*(i){let s=Kw.alloc(e),o=0;for await(let a of i){r(a.length,s,o);let c=s.slice(o,o+r.bytes);o+=r.bytes,s.length-o<Qd&&(s=Kw.alloc(e),o=0),yield new Vw().append(c).append(a)}}}Hw.single=(t,e)=>{e=e||{};let r=e.lengthEncoder||jw;return new Vw([r(t.length),t.slice()])};Su.exports=Hw;Su.exports.MIN_POOL_SIZE=Qd;Su.exports.DEFAULT_POOL_SIZE=$w});var Xd=w((cK,Yw)=>{"use strict";var Gw=Ui(),{Buffer:sD}=ci(),oD=t=>new Proxy({},{get:(e,r)=>r[0]==="l"?t[r]:t.get(parseInt(r))}),Ww=t=>{let e=Gw.decode(sD.isBuffer(t)?t:oD(t));return Ww.bytes=Gw.decode.bytes,e};Yw.exports=Ww});var Jw=w((uK,xu)=>{"use strict";var{Buffer:aD}=ci(),Zd=Ji(),cD=Xd(),Qw=8,Xw=1024*1024*4,Zw=aD.alloc(0),ui={LENGTH:"readLength",DATA:"readData"},uD={[ui.LENGTH]:(t,e,r,n)=>{e=e.append(t);let i;try{i=n.lengthDecoder(e)}catch(s){if(e.length>n.maxLengthLength)throw Object.assign(s,{message:"message length too long",code:"ERR_MSG_LENGTH_TOO_LONG"});if(s instanceof RangeError)return{mode:ui.LENGTH,buffer:e,chunk:void 0,state:void 0,data:void 0};throw s}if(i>n.maxDataLength)throw Object.assign(new Error("message data too long"),{code:"ERR_MSG_DATA_TOO_LONG"});return t=e.shallowSlice(n.lengthDecoder.bytes),e=new Zd,n.onLength&&n.onLength(i),i<=0?(n.onData&&n.onData(Zw),{mode:ui.LENGTH,chunk:t,buffer:e,data:Zw}):{mode:ui.DATA,chunk:t,buffer:e,state:{dataLength:i},data:void 0}},[ui.DATA]:(t,e,r,n)=>{if(e=e.append(t),!r)throw new Error("state is required");if(e.length<r.dataLength)return{mode:ui.DATA,buffer:e,state:r,chunk:void 0,data:void 0};let{dataLength:i}=r,s=e.shallowSlice(0,i),o=e.length>i?e.shallowSlice(i):void 0;return e=new Zd,n.onData&&n.onData(s),{mode:ui.LENGTH,chunk:o,buffer:e,state:void 0,data:s}}};function Jd(t){t=t||{};let e={lengthDecoder:t.lengthDecoder||cD,maxLengthLength:t.maxLengthLength||Qw,maxDataLength:t.maxDataLength||Xw,onLength:t.onLength,onData:t.onData};return async function*(n){let i=new Zd,s=ui.LENGTH,o;for await(let a of n){let c=a;for(;c;){let u=uD[s](c,i,o,e);s=u.mode,c=u.chunk,i=u.buffer,o=u.state,u.data&&(yield u.data)}}if(i.length)throw Object.assign(new Error("unexpected end of input"),{code:"ERR_UNEXPECTED_EOF"})}}Jd.fromReader=(t,e)=>{let r=1,n={[Symbol.asyncIterator](){return this},next:async()=>{try{return await t.next(r)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}};return Jd({...e||{},onLength:s=>{r=s}})(n)};xu.exports=Jd;xu.exports.MAX_LENGTH_LENGTH=Qw;xu.exports.MAX_DATA_LENGTH=Xw});var r2=w((lK,t2)=>{"use strict";var{Buffer:lD}=ci(),e2=(t,e,r)=>(e=e||lD.allocUnsafe(4),e.writeInt32BE(t,r),e);e2.bytes=4;t2.exports=e2});var s2=w((fK,i2)=>{"use strict";var n2=t=>{if(t.length<4)throw RangeError("Could not decode int32BE");return t.readInt32BE(0)};n2.bytes=4;i2.exports=n2});var so=w(es=>{"use strict";es.encode=zw();es.decode=Jw();es.varintEncode=Yd();es.varintDecode=Xd();es.int32BEEncode=r2();es.int32BEDecode=s2()});var th=w((hK,o2)=>{var eh=Ji();o2.exports=t=>{let e=async function*(){let r=yield,n=new eh;for await(let i of t){if(!r){r=yield n.append(i),n=new eh;continue}for(n.append(i);n.length>=r;){let s=n.shallowSlice(0,r);if(n.consume(r),r=yield s,!r){n.length&&(r=yield n,n=new eh);break}}}if(r)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}});var rh=w((pK,a2)=>{"use strict";var fD=()=>{let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t};a2.exports=fD});var oo=w((yK,c2)=>{"use strict";var dD=th(),hD=ud(),pD=rh();c2.exports=t=>{let e=hD(),r=dD(t.source),n=pD(),i,s=t.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:a=>i?Promise.reject(i):(n.resolve(a),s),source:r},rest:()=>e.end(),write:e.push,read:async()=>(await r.next()).value}}});var Cu=w((gK,h2)=>{"use strict";var u2=Te(),Au=Object.assign(u2("libp2p:circuit:stream-handler"),{error:u2("libp2p:circuit:stream-handler:err")}),l2=so(),yD=oo(),{CircuitRelay:f2}=eo(),d2=class{constructor({stream:e,maxLength:r=4096}){this.stream=e,this.shake=yD(this.stream),this.decoder=l2.decode.fromReader(this.shake.reader,{maxDataLength:r})}async read(){let e=await this.decoder.next();if(e.value){let r=f2.decode(e.value.slice());return Au("read message type",r.type),r}Au("read received no value, closing stream"),this.close()}write(e){Au("write message type %s",e.type),this.shake.write(l2.encode.single(f2.encode(e).finish()))}rest(){return this.shake.rest(),this.shake.stream}end(e){this.write(e),this.close()}close(){Au("closing the stream"),this.rest().sink([])}};h2.exports=d2});var sh=w((mK,ih)=>{"use strict";var p2=Te(),Ba=Object.assign(p2("libp2p:circuit:stop"),{error:p2("libp2p:circuit:stop:err")}),{CircuitRelay:nh}=eo(),gD=Ta(),mD=Cu(),{validateAddrs:vD}=Ud();ih.exports.handleStop=function({connection:e,request:r,streamHandler:n}){try{vD(r,n)}catch(i){return Ba.error("invalid stop request via peer %s",e.remotePeer.toB58String(),i)}return Ba("stop request is valid"),n.write({type:nh.Type.STATUS,code:nh.Status.SUCCESS}),n.rest()};ih.exports.stop=async function({connection:e,request:r}){let{stream:n}=await e.newStream([gD.relay]);Ba("starting stop request to %s",e.remotePeer.toB58String());let i=new mD({stream:n});i.write(r);let s=await i.read();if(!s)return i.close();if(s.code===nh.Status.SUCCESS)return Ba("stop request to %s was successful",e.remotePeer.toB58String()),i.rest();Ba("stop request failed with code %d",s.code),i.close()}});var oh=w((vK,E2)=>{"use strict";var y2=Te(),Rn=Object.assign(y2("libp2p:circuit:hop"),{error:y2("libp2p:circuit:hop:err")}),g2=de(),bD=Rt(),{validateAddrs:ED}=Ud(),m2=Cu(),{CircuitRelay:sr}=eo(),{pipe:wD}=ir(),{codes:v2}=je(),{stop:_D}=sh(),b2=Ta();async function SD({connection:t,request:e,streamHandler:r,circuit:n}){if(!n._options.hop.enabled)return Rn("HOP request received but we are not acting as a relay"),r.end({type:sr.Type.STATUS,code:sr.Status.HOP_CANT_SPEAK_RELAY});try{ED(e,r)}catch(u){return Rn.error("invalid hop request via peer %s",t.remotePeer.toB58String(),u)}if(!e.dstPeer){Rn("HOP request received but we do not receive a dstPeer");return}let i=new bD(e.dstPeer.id),s=n._connectionManager.get(i);if(!s&&!n._options.hop.active)return Rn("HOP request received but we are not connected to the destination peer"),r.end({type:sr.Type.STATUS,code:sr.Status.HOP_NO_CONN_TO_DST});if(!s)return;let o={type:sr.Type.STOP,dstPeer:e.dstPeer,srcPeer:e.srcPeer},a;try{a=await _D({connection:s,request:o})}catch(u){return Rn.error(u)}Rn("hop request from %s is valid",t.remotePeer.toB58String()),r.write({type:sr.Type.STATUS,code:sr.Status.SUCCESS});let c=r.rest();return wD(c,a,c)}async function xD({connection:t,request:e}){let{stream:r}=await t.newStream([b2.relay]),n=new m2({stream:r});n.write(e);let i=await n.read();if(!i)throw g2(new Error("HOP request had no response"),v2.ERR_HOP_REQUEST_FAILED);if(i.code===sr.Status.SUCCESS)return Rn("hop request was successful"),n.rest();throw Rn("hop request failed with code %d, closing stream",i.code),n.close(),g2(new Error(`HOP request failed with code ${i.code}`),v2.ERR_HOP_REQUEST_FAILED)}async function AD({connection:t}){let{stream:e}=await t.newStream([b2.relay]),r=new m2({stream:e});r.write({type:sr.Type.CAN_HOP});let n=await r.read();return await r.close(),!(!n||n.code!==sr.Status.SUCCESS)}function CD({connection:t,streamHandler:e,circuit:r}){let n=r._options.hop.enabled;Rn("can hop (%s) request from %s",n,t.remotePeer.toB58String()),e.end({type:sr.Type.STATUS,code:n?sr.Status.SUCCESS:sr.Status.HOP_CANT_SPEAK_RELAY})}E2.exports={handleHop:SD,hop:xD,canHop:AD,handleCanHop:CD}});var C2=w((bK,A2)=>{"use strict";var w2=Te(),Bn=Object.assign(w2("libp2p:circuit"),{error:w2("libp2p:circuit:err")}),ID=de(),TD=XE(),{Multiaddr:Pa}=qt(),_2=Rt(),{CircuitRelay:Na}=eo(),{codes:RD}=je(),S2=uw(),{relay:BD}=Ta(),PD=dw(),{handleCanHop:ND,handleHop:OD,hop:DD}=oh(),{handleStop:LD}=sh(),kD=Cu(),qD=Symbol.for("@libp2p/js-libp2p-circuit/circuit"),x2=class{constructor({libp2p:e,upgrader:r}){this._dialer=e.dialer,this._registrar=e.registrar,this._connectionManager=e.connectionManager,this._upgrader=r,this._options=e._config.relay,this._libp2p=e,this.peerId=e.peerId,this._registrar.handle(BD,this._onProtocol.bind(this))}async _onProtocol({connection:e,stream:r}){let n=new kD({stream:r}),i=await n.read();if(!i)return;let s=this,o;switch(i.type){case Na.Type.CAN_HOP:{Bn("received CAN_HOP request from %s",e.remotePeer.toB58String()),await ND({circuit:s,connection:e,streamHandler:n});break}case Na.Type.HOP:{Bn("received HOP request from %s",e.remotePeer.toB58String()),o=await OD({connection:e,request:i,streamHandler:n,circuit:s});break}case Na.Type.STOP:{Bn("received STOP request from %s",e.remotePeer.toB58String()),o=await LD({connection:e,request:i,streamHandler:n});break}default:Bn("Request of type %s not supported",i.type)}if(o){let a=new Pa(i.dstPeer.addrs[0]),c=new Pa(i.srcPeer.addrs[0]),u=S2({stream:o,remoteAddr:a,localAddr:c}),l=i.type===Na.Type.HOP?"relay":"inbound";Bn("new %s connection %s",l,u.remoteAddr);let f=await this._upgrader.upgradeInbound(u);Bn("%s connection %s upgraded",l,u.remoteAddr),this.handler&&this.handler(f)}}async dial(e,r){let n=e.toString().split("/p2p-circuit"),i=new Pa(n[0]),s=new Pa(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(!o||!a){let d="Circuit relay dial failed as addresses did not have peer id";throw Bn.error(d),ID(new Error(d),RD.ERR_RELAYED_DIAL)}let c=_2.createFromB58String(o),u=_2.createFromB58String(a),l=!1,f=this._connectionManager.get(c);f||(f=await this._dialer.connectToPeer(i,r),l=!0);try{let d=await DD({connection:f,request:{type:Na.Type.HOP,srcPeer:{id:this.peerId.toBytes(),addrs:this._libp2p.multiaddrs.map(g=>g.bytes)},dstPeer:{id:u.toBytes(),addrs:[new Pa(s).bytes]}}}),p=i.encapsulate(`/p2p-circuit/p2p/${this.peerId.toB58String()}`),h=S2({stream:d,remoteAddr:e,localAddr:p});return Bn("new outbound connection %s",h.remoteAddr),this._upgrader.upgradeOutbound(h)}catch(d){throw Bn.error("Circuit relay dial failed",d),l&&await f.close(),d}}createListener(e,r){return typeof e=="function"&&(r=e,e={}),this.handler=r,PD(this._libp2p)}filter(e){return e=Array.isArray(e)?e:[e],e.filter(r=>TD.Circuit.matches(r))}get[Symbol.toStringTag](){return"Circuit"}static isTransport(e){return Boolean(e&&e[qD])}};A2.exports=x2});var ah=w((EK,I2)=>{"use strict";var{CID:UD}=(ws(),ko),{sha256:MD}=(Bi(),Gn);I2.exports.namespaceToCid=async t=>{let e=new TextEncoder().encode(t),r=await MD.digest(e);return UD.createV0(r)}});var O2=w((wK,N2)=>{"use strict";var T2=Te(),ch=Object.assign(T2("libp2p:auto-relay"),{error:T2("libp2p:auto-relay:err")}),{fromString:FD}=(It(),Nt),{toString:KD}=(Tt(),Ot),{Multiaddr:VD}=qt(),jD=Mi(),{relay:$D}=Ta(),{canHop:HD}=oh(),{namespaceToCid:zD}=ah(),{CIRCUIT_PROTO_CODE:GD,HOP_METADATA_KEY:R2,HOP_METADATA_VALUE:B2,RELAY_RENDEZVOUS_NS:WD}=uu(),P2=class{constructor({libp2p:e,maxListeners:r=1,onError:n}){this._libp2p=e,this._peerId=e.peerId,this._peerStore=e.peerStore,this._connectionManager=e.connectionManager,this._transportManager=e.transportManager,this._addressSorter=e.dialer.addressSorter,this.maxListeners=r,this._listenRelays=new Set,this._onProtocolChange=this._onProtocolChange.bind(this),this._onPeerDisconnected=this._onPeerDisconnected.bind(this),this._peerStore.on("change:protocols",this._onProtocolChange),this._connectionManager.on("peer:disconnect",this._onPeerDisconnected),this._onError=(i,s)=>{ch.error(s||i),n&&n(i,s)}}async _onProtocolChange({peerId:e,protocols:r}){let n=e.toB58String(),i=r.find(s=>s===$D);if(!i&&this._listenRelays.has(n)){await this._removeListenRelay(n);return}else if(!i||this._listenRelays.has(n))return;try{let s=this._connectionManager.get(e);if(!s)return;if(s.remoteAddr.protoCodes().includes(GD)){ch(`relayed connection to ${n} will not be used to hop on`);return}await HD({connection:s})&&(await this._peerStore.metadataBook.setValue(e,R2,FD(B2)),await this._addListenRelay(s,n))}catch(s){this._onError(s)}}_onPeerDisconnected(e){let n=e.remotePeer.toB58String();!this._listenRelays.has(n)||this._removeListenRelay(n).catch(i=>{ch.error(i)})}async _addListenRelay(e,r){try{if(this._listenRelays.size>=this.maxListeners)return;let n=await this._peerStore.addressBook.getMultiaddrsForPeer(e.remotePeer,this._addressSorter);(await Promise.all(n.map(async s=>{try{return await this._transportManager.listen([new VD(`${s.toString()}/p2p-circuit`)]),!0}catch(o){this._onError(o)}return!1}))).includes(!0)&&this._listenRelays.add(r)}catch(n){this._onError(n),this._listenRelays.delete(r)}}async _removeListenRelay(e){this._listenRelays.delete(e)&&await this._listenOnAvailableHopRelays([e])}async _listenOnAvailableHopRelays(e=[]){if(this._listenRelays.size>=this.maxListeners)return;let r=[],n=await jD(this._peerStore.getPeers());for await(let{id:i,metadata:s}of n){let o=i.toB58String();if(this._listenRelays.has(o)||e.includes(o))continue;let a=s.get(R2);if(!a||KD(a)!==B2)continue;let c=this._connectionManager.get(i);if(!c){r.push(i);continue}if(await this._addListenRelay(c,o),this._listenRelays.size>=this.maxListeners)return}for(let i of r)if(await this._tryToListenOnRelay(i),this._listenRelays.size>=this.maxListeners)return;try{let i=await zD(WD);for await(let s of this._libp2p.contentRouting.findProviders(i)){if(!s.multiaddrs.length)continue;let o=s.id;if(await this._peerStore.addressBook.add(o,s.multiaddrs),await this._tryToListenOnRelay(o),this._listenRelays.size>=this.maxListeners)return}}catch(i){this._onError(i)}}async _tryToListenOnRelay(e){try{let r=await this._libp2p.dial(e);await this._addListenRelay(r,e.toB58String())}catch(r){this._onError(r,`could not connect and listen on known hop relay ${e.toB58String()}`)}}};N2.exports=P2});var U2=w((_K,q2)=>{"use strict";var D2=Te(),L2=Object.assign(D2("libp2p:relay"),{error:D2("libp2p:relay:err")}),{codes:YD}=je(),{setDelayedInterval:QD,clearDelayedInterval:XD}=hd(),ZD=O2(),{namespaceToCid:JD}=ah(),{RELAY_RENDEZVOUS_NS:eL}=uu(),k2=class{constructor(e){this._libp2p=e,this._options={...e._config.relay},this._autoRelay=this._options.autoRelay.enabled&&new ZD({libp2p:e,...this._options.autoRelay}),this._advertiseService=this._advertiseService.bind(this)}start(){this._options.hop.enabled&&this._options.advertise.enabled&&(this._timeout=QD(this._advertiseService,this._options.advertise.ttl,this._options.advertise.bootDelay))}stop(){XD(this._timeout)}async _advertiseService(){try{let e=await JD(eL);await this._libp2p.contentRouting.provide(e)}catch(e){e.code===YD.ERR_NO_ROUTERS_AVAILABLE?(L2.error("a content router, such as a DHT, must be provided in order to advertise the relay service",e),this.stop()):L2.error(e)}}};q2.exports=k2});var lh=w((SK,uh)=>{var{AbortController:tL}=globalThis;function M2(t){let e=new tL;function r(){e.abort();for(let n of t)!n||!n.removeEventListener||n.removeEventListener("abort",r)}for(let n of t)if(!(!n||!n.addEventListener)){if(n.aborted){r();break}n.addEventListener("abort",r)}return e.signal}uh.exports=M2;uh.exports.anySignal=M2});var j2=w((AK,V2)=>{var F2=ad(),K2=rh();V2.exports=class{constructor(){this._buffer=new F2,this._waitingConsumers=new F2}push(e){let{promise:r,resolve:n}=K2();return this._buffer.push({chunk:e,resolve:n}),this._consume(),r}_consume(){for(;!this._waitingConsumers.isEmpty()&&!this._buffer.isEmpty();){let e=this._waitingConsumers.shift(),r=this._buffer.shift();e.resolve(r.chunk),r.resolve()}}shift(){let{promise:e,resolve:r}=K2();return this._waitingConsumers.push({resolve:r}),this._consume(),e}isEmpty(){return this._buffer.isEmpty()}}});var H2=w((CK,$2)=>{"use strict";$2.exports=(t,e=1,r)=>{if(r={indent:" ",includeEmptyLines:!1,...r},typeof t!="string")throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof t}\``);if(typeof e!="number")throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof e}\``);if(typeof r.indent!="string")throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof r.indent}\``);if(e===0)return t;let n=r.includeEmptyLines?/^/gm:/^(?!\s*$)/gm;return t.replace(n,r.indent.repeat(e))}});var z2=w(()=>{});var Q2=w((RK,Y2)=>{"use strict";var G2=z2(),W2=/\s+at.*(?:\(|\s)(.*)\)?/,rL=/^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/,nL=typeof G2.homedir=="undefined"?"":G2.homedir();Y2.exports=(t,e)=>(e=Object.assign({pretty:!1},e),t.replace(/\\/g,"/").split(`
41
41
  `).filter(r=>{let n=r.match(W2);if(n===null||!n[1])return!0;let i=n[1];return i.includes(".app/Contents/Resources/electron.asar")||i.includes(".app/Contents/Resources/default_app.asar")?!1:!rL.test(i)}).filter(r=>r.trim()!=="").map(r=>e.pretty?r.replace(W2,(n,i)=>n.replace(i,i.replace(nL,"~"))):r).join(`
42
42
  `))});var J2=w((BK,Z2)=>{"use strict";var iL=H2(),sL=Q2(),oL=t=>t.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g,""),X2=class extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError(`Expected input to be an Array, got ${typeof e}`);e=[...e].map(n=>n instanceof Error?n:n!==null&&typeof n=="object"?Object.assign(new Error(n.message),n):new Error(n));let r=e.map(n=>typeof n.stack=="string"?oL(sL(n.stack)):String(n)).join(`
43
43
  `);r=`
44
44
  `+iL(r,4);super(r);this.name="AggregateError",Object.defineProperty(this,"_errors",{value:e})}*[Symbol.iterator](){for(let e of this._errors)yield e}};Z2.exports=X2});var e_=w((PK,dh)=>{"use strict";var fh=class extends Error{constructor(e){super(e||"Promise was canceled");this.name="CancelError"}get isCanceled(){return!0}},Oa=class{static fn(e){return(...r)=>new Oa((n,i,s)=>{r.push(s),e(...r).then(n,i)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((r,n)=>{this._reject=n;let i=a=>{(!this._isCanceled||!o.shouldReject)&&(this._isPending=!1,r(a))},s=a=>{this._isPending=!1,n(a)},o=a=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(a)};return Object.defineProperties(o,{shouldReject:{get:()=>this._rejectOnCancel,set:a=>{this._rejectOnCancel=a}}}),e(i,s,o)})}then(e,r){return this._promise.then(e,r)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(!(!this._isPending||this._isCanceled)){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let r of this._cancelHandlers)r()}catch(r){this._reject(r);return}this._rejectOnCancel&&this._reject(new fh(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(Oa.prototype,Promise.prototype);dh.exports=Oa;dh.exports.CancelError=fh});var r_=w((NK,Iu)=>{"use strict";var t_=J2(),aL=e_(),hh=class extends Error{},cL=(t,e)=>new aL((r,n,i)=>{let{count:s,filter:o=()=>!0}=e;if(!Number.isFinite(s)){n(new TypeError(`Expected a finite number, got ${typeof e.count}`));return}let a=[],c=[],u=0,l=!1,f=new Set,d=()=>(a.length===s&&(r(a),l=!0),u-c.length<s&&(n(new t_(c)),l=!0),l),p=()=>{for(let h of t)!f.has(h)&&typeof h.cancel=="function"&&h.cancel()};i(p);for(let h of t)u++,(async()=>{try{let g=await h;if(l)return;if(!o(g))throw new hh("Value does not satisfy filter");a.push(g)}catch(g){c.push(g)}finally{f.add(h),!l&&d()&&p()}})();s>u&&(n(new RangeError(`Expected input to contain at least ${e.count} items, but contains ${u} items`)),p())});Iu.exports=cL;Iu.exports.AggregateError=t_;Iu.exports.FilterError=hh});var n_=w((OK,yh)=>{"use strict";var ph=class extends Error{constructor(e){super(e||"Promise was canceled");this.name="CancelError"}get isCanceled(){return!0}},Da=class{static fn(e){return(...r)=>new Da((n,i,s)=>{r.push(s),e(...r).then(n,i)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((r,n)=>{this._reject=n;let i=a=>{(!this._isCanceled||!o.shouldReject)&&(this._isPending=!1,r(a))},s=a=>{this._isPending=!1,n(a)},o=a=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(a)};return Object.defineProperties(o,{shouldReject:{get:()=>this._rejectOnCancel,set:a=>{this._rejectOnCancel=a}}}),e(i,s,o)})}then(e,r){return this._promise.then(e,r)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(!(!this._isPending||this._isCanceled)){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let r of this._cancelHandlers)r()}catch(r){this._reject(r);return}this._rejectOnCancel&&this._reject(new ph(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(Da.prototype,Promise.prototype);yh.exports=Da;yh.exports.CancelError=ph});var s_=w((DK,gh)=>{"use strict";var i_=r_(),uL=n_();gh.exports=(t,e)=>{let r=i_(t,{...e,count:1});return uL.fn(async n=>{n(()=>{r.cancel()});let[i]=await r;return i})()};gh.exports.AggregateError=i_.AggregateError});var u_=w((LK,c_)=>{"use strict";var lL=de(),{anySignal:fL}=lh(),dL=j2(),hL=s_(),{setMaxListeners:o_}=Qt(),{codes:pL}=je(),a_=class{constructor({addrs:e,dialAction:r,dialer:n}){this.addrs=e,this.dialer=n,this.dialAction=r}async run(e={}){let r=this.dialer.getTokens(this.addrs.length);if(r.length<1)throw lL(new Error("No dial tokens available"),pL.ERR_NO_DIAL_TOKENS);let n=new dL;r.forEach(o=>n.push(o));let i=this.addrs.map(()=>{let o=new AbortController;try{o_&&o_(1/0,o.signal)}catch{}return o}),s=0;try{return await hL(this.addrs.map(async(o,a)=>{let c=await n.shift(),u;try{let l=i[a].signal;u=await this.dialAction(o,{...e,signal:e.signal?fL([l,e.signal]):l}),i.splice(a,1)}finally{s++,this.addrs.length-s>=r.length?n.push(c):this.dialer.releaseToken(r.splice(r.indexOf(c),1)[0])}return u}))}finally{i.map(o=>o.abort()),r.forEach(o=>this.dialer.releaseToken(o))}}};c_.exports=a_});var m_=w((kK,g_)=>{"use strict";var l_=Te(),yL=Mi(),gL=Fi(),{pipe:mL}=ir(),ao=Object.assign(l_("libp2p:dialer"),{error:l_("libp2p:dialer:err")}),Tu=de(),{Multiaddr:mh}=qt(),{TimeoutController:vL}=od(),{AbortError:bL}=bu(),{anySignal:EL}=lh(),{setMaxListeners:f_}=Qt(),wL=u_(),{publicAddressesFirst:_L}=Ed(),d_=pd(),h_=Pd(),{codes:La}=je(),{DIAL_TIMEOUT:SL,MAX_PARALLEL_DIALS:xL,MAX_PER_PEER_DIALS:AL,MAX_ADDRS_TO_DIAL:CL}=cu(),p_="dialler",IL="pending-dials",TL="pending-dial-targets",y_=class{constructor({transportManager:e,peerStore:r,connectionGater:n,addressSorter:i=_L,maxParallelDials:s=xL,maxAddrsToDial:o=CL,dialTimeout:a=SL,maxDialsPerPeer:c=AL,resolvers:u={},metrics:l}){this.connectionGater=n,this.transportManager=e,this.peerStore=r,this.addressSorter=i,this.maxParallelDials=s,this.maxAddrsToDial=o,this.timeout=a,this.maxDialsPerPeer=c,this.tokens=[...new Array(s)].map((f,d)=>d),this._pendingDials=h_({component:p_,metric:IL,metrics:l}),this._pendingDialTargets=h_({component:p_,metric:TL,metrics:l});for(let[f,d]of Object.entries(u))mh.resolvers.set(f,d)}destroy(){for(let e of this._pendingDials.values())try{e.controller.abort()}catch(r){ao.error(r)}this._pendingDials.clear();for(let e of this._pendingDialTargets.values())e.reject(new bL("Dialer was destroyed"));this._pendingDialTargets.clear()}async connectToPeer(e,r={}){let{id:n}=d_(e);if(await this.connectionGater.denyDialPeer(n))throw Tu(new Error("The dial request is blocked by gater.allowDialPeer"),La.ERR_PEER_DIAL_INTERCEPTED);let i=await this._createCancellableDialTarget(e);if(!i.addrs.length)throw Tu(new Error("The dial request has no valid addresses"),La.ERR_NO_VALID_ADDRESSES);let s=this._pendingDials.get(i.id)||this._createPendingDial(i,r);try{let o=await s.promise;return ao("dial succeeded to %s",i.id),o}catch(o){throw s.controller.signal.aborted&&(o.code=La.ERR_TIMEOUT),ao.error(o),o}finally{s.destroy()}}async _createCancellableDialTarget(e){let r=`${parseInt(String(Math.random()*1e9),10).toString()+Date.now()}`,n=new Promise((i,s)=>{this._pendingDialTargets.set(r,{resolve:i,reject:s})});try{return await Promise.race([this._createDialTarget(e),n])}finally{this._pendingDialTargets.delete(r)}}async _createDialTarget(e){let{id:r,multiaddrs:n}=d_(e);n&&await this.peerStore.addressBook.add(r,n);let i=await mL(await this.peerStore.addressBook.getMultiaddrsForPeer(r,this.addressSorter),a=>gL(a,async c=>!await this.connectionGater.denyDialMultiaddr(r,c)),a=>yL(a));mh.isMultiaddr(e)&&(i=i.filter(a=>!e.equals(a)),i.unshift(e));let s=[];for(let a of i)(await this._resolve(a)).forEach(u=>s.push(u));let o=s.filter(a=>this.transportManager.transportForMultiaddr(a));if(o.length>this.maxAddrsToDial)throw await this.peerStore.delete(r),Tu(new Error("dial with more addresses than allowed"),La.ERR_TOO_MANY_ADDRESSES);return{id:r.toB58String(),addrs:o}}_createPendingDial(e,r={}){let n=(u,l)=>{if(l.signal.aborted)throw Tu(new Error("already aborted"),La.ERR_ALREADY_ABORTED);return this.transportManager.dial(u,l)},i=new wL({addrs:e.addrs,dialAction:n,dialer:this}),s=new vL(this.timeout),o=[s.signal];r.signal&&o.push(r.signal);let a=EL(o);try{f_&&f_(1/0,a)}catch{}let c={dialRequest:i,controller:s,promise:i.run({...r,signal:a}),destroy:()=>{s.clear(),this._pendingDials.delete(e.id)}};return this._pendingDials.set(e.id,c),c}getTokens(e){let r=Math.min(e,this.maxDialsPerPeer,this.tokens.length),n=this.tokens.splice(0,r);return ao("%d tokens request, returning %d, %d remaining",e,r,this.tokens.length),n}releaseToken(e){this.tokens.indexOf(e)>-1||(ao("token %d released",e),this.tokens.push(e))}async _resolve(e){if(!e.protoNames().includes("dnsaddr"))return[e];let n=await this._resolveRecord(e);return(await Promise.all(n.map(o=>this._resolve(o)))).flat().reduce((o,a)=>(o.find(c=>c.equals(a))||o.push(a),o),[])}async _resolveRecord(e){try{return e=new mh(e.toString()),await e.resolve()}catch(r){return ao.error(`multiaddr ${e} could not be resolved`),[]}}};g_.exports=y_});var b_=w((qK,v_)=>{"use strict";function RL(t){return t>=55296&&t<=56319}function BL(t){return t>=56320&&t<=57343}v_.exports=function(e,r,n){if(typeof r!="string")throw new Error("Input must be string");for(var i=r.length,s=0,o,a,c=0;c<i;c+=1){if(o=r.charCodeAt(c),a=r[c],RL(o)&&BL(r.charCodeAt(c+1))&&(c+=1,a+=r[c]),s+=e(a),s===n)return r.slice(0,c+1);if(s>n)return r.slice(0,c-a.length+1)}return r}});var w_=w((UK,E_)=>{"use strict";function PL(t){return t>=55296&&t<=56319}function NL(t){return t>=56320&&t<=57343}E_.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var r=e.length,n=0,i=null,s=null,o=0;o<r;o++)i=e.charCodeAt(o),NL(i)?s!=null&&PL(s)?n+=1:n+=3:i<=127?n+=1:i>=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),s=i;return n}});var S_=w((MK,__)=>{"use strict";var OL=b_(),DL=w_();__.exports=OL.bind(null,DL)});var C_=w((FK,A_)=>{"use strict";var LL=S_(),kL=/[\/\?<>\\:\*\|"]/g,qL=/[\x00-\x1f\x80-\x9f]/g,UL=/^\.+$/,ML=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,FL=/[\. ]+$/;function x_(t,e){if(typeof t!="string")throw new Error("Input must be string");var r=t.replace(kL,e).replace(qL,e).replace(UL,e).replace(ML,e).replace(FL,e);return LL(r,255)}A_.exports=function(t,e){var r=e&&e.replacement||"",n=x_(t,r);return r===""?n:x_(n,"")}});var R_=w((KK,T_)=>{"use strict";Is();var Ru=be(),{toString:co}=(Tt(),Ot),{fromString:I_}=(It(),Nt);T_.exports={createCipheriv:(t,e,r)=>{let n=Ru.cipher.createCipher("AES-CTR",co(e,"ascii"));return n.start({iv:co(r,"ascii")}),{update:i=>(n.update(Ru.util.createBuffer(co(i,"ascii"))),I_(n.output.getBytes(),"ascii"))}},createDecipheriv:(t,e,r)=>{let n=Ru.cipher.createDecipher("AES-CTR",co(e,"ascii"));return n.start({iv:co(r,"ascii")}),{update:i=>(n.update(Ru.util.createBuffer(co(i,"ascii"))),I_(n.output.getBytes(),"ascii"))}}}});var N_=w((VK,P_)=>{"use strict";var KL=de(),B_={16:"aes-128-ctr",32:"aes-256-ctr"};P_.exports=function(t){let e=B_[t.length];if(!e){let r=Object.entries(B_).map(([n,i])=>`${n} (${i})`).join(" / ");throw KL(new Error(`Invalid key length ${t.length} bytes. Must be ${r}`),"ERR_INVALID_KEY_LENGTH")}return e}});var L_=w(D_=>{"use strict";var O_=R_(),VL=N_();D_.create=async function(t,e){let r=VL(t),n=O_.createCipheriv(r,t,e),i=O_.createDecipheriv(r,t,e);return{async encrypt(o){return n.update(o)},async decrypt(o){return i.update(o)}}}});var U_=w(($K,q_)=>{"use strict";var jL=Kl(),$L=$e(),HL=de(),k_={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function zL(t,e,r,n,i){let s=k_[i];if(!s){let a=Object.keys(k_).join(" / ");throw HL(new Error(`Hash '${i}' is unknown or not supported. Must be ${a}`),"ERR_UNSUPPORTED_HASH_TYPE")}let o=jL(t,e,r,n,s);return $L.encode64(o)}q_.exports=zL});var Bu=w(uo=>{"use strict";var GL=Tf(),WL=L_(),YL=jc();uo.aes=WL;uo.hmac=GL;uo.keys=YL;uo.randomBytes=Rc();uo.pbkdf2=U_()});var V_=w((zK,K_)=>{var lo=be();jn();$e();var Z=lo.asn1,fo=K_.exports=lo.pkcs7asn1=lo.pkcs7asn1||{};lo.pkcs7=lo.pkcs7||{};lo.pkcs7.asn1=fo;var M_={name:"ContentInfo",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:Z.Class.UNIVERSAL,type:Z.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:Z.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};fo.contentInfoValidator=M_;var F_={name:"EncryptedContentInfo",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:Z.Class.UNIVERSAL,type:Z.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:Z.Class.UNIVERSAL,type:Z.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:Z.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:Z.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};fo.envelopedDataValidator={name:"EnvelopedData",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:Z.Class.UNIVERSAL,type:Z.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(F_)};fo.encryptedDataValidator={name:"EncryptedData",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:Z.Class.UNIVERSAL,type:Z.Type.INTEGER,constructed:!1,capture:"version"}].concat(F_)};var QL={name:"SignerInfo",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:Z.Class.UNIVERSAL,type:Z.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:Z.Class.UNIVERSAL,type:Z.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:Z.Class.UNIVERSAL,type:Z.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:Z.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:Z.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:Z.Class.UNIVERSAL,type:Z.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:Z.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};fo.signedDataValidator={name:"SignedData",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:Z.Class.UNIVERSAL,type:Z.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},M_,{name:"SignedData.Certificates",tagClass:Z.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:Z.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SET,capture:"signerInfos",optional:!0,value:[QL]}]};fo.recipientInfoValidator={name:"RecipientInfo",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:Z.Class.UNIVERSAL,type:Z.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:Z.Class.UNIVERSAL,type:Z.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:Z.Class.UNIVERSAL,type:Z.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:Z.Class.UNIVERSAL,type:Z.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:Z.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:Z.Class.UNIVERSAL,type:Z.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var $_=w((GK,j_)=>{var ts=be();$e();ts.mgf=ts.mgf||{};var XL=j_.exports=ts.mgf.mgf1=ts.mgf1=ts.mgf1||{};XL.create=function(t){var e={generate:function(r,n){for(var i=new ts.util.ByteBuffer,s=Math.ceil(n/t.digestLength),o=0;o<s;o++){var a=new ts.util.ByteBuffer;a.putInt32(o),t.start(),t.update(r+a.getBytes()),i.putBuffer(t.digest())}return i.truncate(i.length()-n),i.getBytes()}};return e}});var z_=w((WK,H_)=>{var Pu=be();$_();H_.exports=Pu.mgf=Pu.mgf||{};Pu.mgf.mgf1=Pu.mgf1});var W_=w((YK,G_)=>{var rs=be();Ci();$e();var ZL=G_.exports=rs.pss=rs.pss||{};ZL.create=function(t){arguments.length===3&&(t={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var e=t.md,r=t.mgf,n=e.digestLength,i=t.salt||null;typeof i=="string"&&(i=rs.util.createBuffer(i));var s;if("saltLength"in t)s=t.saltLength;else if(i!==null)s=i.length();else throw new Error("Salt length not specified or specific salt not given.");if(i!==null&&i.length()!==s)throw new Error("Given salt length does not match length of given salt.");var o=t.prng||rs.random,a={};return a.encode=function(c,u){var l,f=u-1,d=Math.ceil(f/8),p=c.digest().getBytes();if(d<n+s+2)throw new Error("Message is too long to encrypt.");var h;i===null?h=o.getBytesSync(s):h=i.bytes();var g=new rs.util.ByteBuffer;g.fillWithByte(0,8),g.putBytes(p),g.putBytes(h),e.start(),e.update(g.getBytes());var m=e.digest().getBytes(),S=new rs.util.ByteBuffer;S.fillWithByte(0,d-s-n-2),S.putByte(1),S.putBytes(h);var R=S.getBytes(),L=d-n-1,H=r.generate(m,L),q="";for(l=0;l<L;l++)q+=String.fromCharCode(R.charCodeAt(l)^H.charCodeAt(l));var k=65280>>8*d-f&255;return q=String.fromCharCode(q.charCodeAt(0)&~k)+q.substr(1),q+m+String.fromCharCode(188)},a.verify=function(c,u,l){var f,d=l-1,p=Math.ceil(d/8);if(u=u.substr(-p),p<n+s+2)throw new Error("Inconsistent parameters to PSS signature verification.");if(u.charCodeAt(p-1)!==188)throw new Error("Encoded message does not end in 0xBC.");var h=p-n-1,g=u.substr(0,h),m=u.substr(h,n),S=65280>>8*p-d&255;if((g.charCodeAt(0)&S)!=0)throw new Error("Bits beyond keysize not zero as expected.");var R=r.generate(m,h),L="";for(f=0;f<h;f++)L+=String.fromCharCode(g.charCodeAt(f)^R.charCodeAt(f));L=String.fromCharCode(L.charCodeAt(0)&~S)+L.substr(1);var H=p-n-s-2;for(f=0;f<H;f++)if(L.charCodeAt(f)!==0)throw new Error("Leftmost octets not zero as expected");if(L.charCodeAt(H)!==1)throw new Error("Inconsistent PSS signature, 0x01 marker not found");var q=L.substr(-s),k=new rs.util.ByteBuffer;k.fillWithByte(0,8),k.putBytes(c),k.putBytes(q),e.start(),e.update(k.getBytes());var J=e.digest().getBytes();return m===J},a}});var bh=w((QK,J_)=>{var oe=be();Is();jn();yc();$n();z_();xs();bc();W_();Ho();$e();var y=oe.asn1,G=J_.exports=oe.pki=oe.pki||{},Ce=G.oids,ft={};ft.CN=Ce.commonName;ft.commonName="CN";ft.C=Ce.countryName;ft.countryName="C";ft.L=Ce.localityName;ft.localityName="L";ft.ST=Ce.stateOrProvinceName;ft.stateOrProvinceName="ST";ft.O=Ce.organizationName;ft.organizationName="O";ft.OU=Ce.organizationalUnitName;ft.organizationalUnitName="OU";ft.E=Ce.emailAddress;ft.emailAddress="E";var Y_=oe.pki.rsa.publicKeyValidator,JL={name:"Certificate",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:y.Class.UNIVERSAL,type:y.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:y.Class.UNIVERSAL,type:y.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:y.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:y.Class.UNIVERSAL,type:y.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:y.Class.UNIVERSAL,type:y.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:y.Class.UNIVERSAL,type:y.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:y.Class.UNIVERSAL,type:y.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},Y_,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:y.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:y.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:y.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:y.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},ek={name:"rsapss",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:y.Class.UNIVERSAL,type:y.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:y.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:y.Class.UNIVERSAL,type:y.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:y.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:y.Class.UNIVERSAL,type:y.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:y.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:y.Class.UNIVERSAL,type:y.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},tk={name:"CertificationRequestInfo",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:y.Class.UNIVERSAL,type:y.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},Y_,{name:"CertificationRequestInfo.attributes",tagClass:y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:y.Class.UNIVERSAL,type:y.Type.SET,constructed:!0}]}]}]},rk={name:"CertificationRequest",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[tk,{name:"CertificationRequest.signatureAlgorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:y.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};G.RDNAttributesAsArray=function(t,e){for(var r=[],n,i,s,o=0;o<t.value.length;++o){n=t.value[o];for(var a=0;a<n.value.length;++a)s={},i=n.value[a],s.type=y.derToOid(i.value[0].value),s.value=i.value[1].value,s.valueTagClass=i.value[1].type,s.type in Ce&&(s.name=Ce[s.type],s.name in ft&&(s.shortName=ft[s.name])),e&&(e.update(s.type),e.update(s.value)),r.push(s)}return r};G.CRIAttributesAsArray=function(t){for(var e=[],r=0;r<t.length;++r)for(var n=t[r],i=y.derToOid(n.value[0].value),s=n.value[1].value,o=0;o<s.length;++o){var a={};if(a.type=i,a.value=s[o].value,a.valueTagClass=s[o].type,a.type in Ce&&(a.name=Ce[a.type],a.name in ft&&(a.shortName=ft[a.name])),a.type===Ce.extensionRequest){a.extensions=[];for(var c=0;c<a.value.length;++c)a.extensions.push(G.certificateExtensionFromAsn1(a.value[c]))}e.push(a)}return e};function li(t,e){typeof e=="string"&&(e={shortName:e});for(var r=null,n,i=0;r===null&&i<t.attributes.length;++i)n=t.attributes[i],(e.type&&e.type===n.type||e.name&&e.name===n.name||e.shortName&&e.shortName===n.shortName)&&(r=n);return r}var Nu=function(t,e,r){var n={};if(t!==Ce["RSASSA-PSS"])return n;r&&(n={hash:{algorithmOid:Ce.sha1},mgf:{algorithmOid:Ce.mgf1,hash:{algorithmOid:Ce.sha1}},saltLength:20});var i={},s=[];if(!y.validate(e,ek,i,s)){var o=new Error("Cannot read RSASSA-PSS parameter block.");throw o.errors=s,o}return i.hashOid!==void 0&&(n.hash=n.hash||{},n.hash.algorithmOid=y.derToOid(i.hashOid)),i.maskGenOid!==void 0&&(n.mgf=n.mgf||{},n.mgf.algorithmOid=y.derToOid(i.maskGenOid),n.mgf.hash=n.mgf.hash||{},n.mgf.hash.algorithmOid=y.derToOid(i.maskGenHashOid)),i.saltLength!==void 0&&(n.saltLength=i.saltLength.charCodeAt(0)),n},Ou=function(t){switch(Ce[t.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return oe.md.sha1.create();case"md5WithRSAEncryption":return oe.md.md5.create();case"sha256WithRSAEncryption":return oe.md.sha256.create();case"sha384WithRSAEncryption":return oe.md.sha384.create();case"sha512WithRSAEncryption":return oe.md.sha512.create();case"RSASSA-PSS":return oe.md.sha256.create();default:var e=new Error("Could not compute "+t.type+" digest. Unknown signature OID.");throw e.signatureOid=t.signatureOid,e}},Q_=function(t){var e=t.certificate,r;switch(e.signatureOid){case Ce.sha1WithRSAEncryption:case Ce.sha1WithRSASignature:break;case Ce["RSASSA-PSS"]:var n,i;if(n=Ce[e.signatureParameters.mgf.hash.algorithmOid],n===void 0||oe.md[n]===void 0){var s=new Error("Unsupported MGF hash function.");throw s.oid=e.signatureParameters.mgf.hash.algorithmOid,s.name=n,s}if(i=Ce[e.signatureParameters.mgf.algorithmOid],i===void 0||oe.mgf[i]===void 0){var s=new Error("Unsupported MGF function.");throw s.oid=e.signatureParameters.mgf.algorithmOid,s.name=i,s}if(i=oe.mgf[i].create(oe.md[n].create()),n=Ce[e.signatureParameters.hash.algorithmOid],n===void 0||oe.md[n]===void 0){var s=new Error("Unsupported RSASSA-PSS hash function.");throw s.oid=e.signatureParameters.hash.algorithmOid,s.name=n,s}r=oe.pss.create(oe.md[n].create(),i,e.signatureParameters.saltLength);break}return e.publicKey.verify(t.md.digest().getBytes(),t.signature,r)};G.certificateFromPem=function(t,e,r){var n=oe.pem.decode(t)[0];if(n.type!=="CERTIFICATE"&&n.type!=="X509 CERTIFICATE"&&n.type!=="TRUSTED CERTIFICATE"){var i=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw i.headerType=n.type,i}if(n.procType&&n.procType.type==="ENCRYPTED")throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var s=y.fromDer(n.body,r);return G.certificateFromAsn1(s,e)};G.certificateToPem=function(t,e){var r={type:"CERTIFICATE",body:y.toDer(G.certificateToAsn1(t)).getBytes()};return oe.pem.encode(r,{maxline:e})};G.publicKeyFromPem=function(t){var e=oe.pem.decode(t)[0];if(e.type!=="PUBLIC KEY"&&e.type!=="RSA PUBLIC KEY"){var r=new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw r.headerType=e.type,r}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert public key from PEM; PEM is encrypted.");var n=y.fromDer(e.body);return G.publicKeyFromAsn1(n)};G.publicKeyToPem=function(t,e){var r={type:"PUBLIC KEY",body:y.toDer(G.publicKeyToAsn1(t)).getBytes()};return oe.pem.encode(r,{maxline:e})};G.publicKeyToRSAPublicKeyPem=function(t,e){var r={type:"RSA PUBLIC KEY",body:y.toDer(G.publicKeyToRSAPublicKey(t)).getBytes()};return oe.pem.encode(r,{maxline:e})};G.getPublicKeyFingerprint=function(t,e){e=e||{};var r=e.md||oe.md.sha1.create(),n=e.type||"RSAPublicKey",i;switch(n){case"RSAPublicKey":i=y.toDer(G.publicKeyToRSAPublicKey(t)).getBytes();break;case"SubjectPublicKeyInfo":i=y.toDer(G.publicKeyToAsn1(t)).getBytes();break;default:throw new Error('Unknown fingerprint type "'+e.type+'".')}r.start(),r.update(i);var s=r.digest();if(e.encoding==="hex"){var o=s.toHex();return e.delimiter?o.match(/.{2}/g).join(e.delimiter):o}else{if(e.encoding==="binary")return s.getBytes();if(e.encoding)throw new Error('Unknown encoding "'+e.encoding+'".')}return s};G.certificationRequestFromPem=function(t,e,r){var n=oe.pem.decode(t)[0];if(n.type!=="CERTIFICATE REQUEST"){var i=new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw i.headerType=n.type,i}if(n.procType&&n.procType.type==="ENCRYPTED")throw new Error("Could not convert certification request from PEM; PEM is encrypted.");var s=y.fromDer(n.body,r);return G.certificationRequestFromAsn1(s,e)};G.certificationRequestToPem=function(t,e){var r={type:"CERTIFICATE REQUEST",body:y.toDer(G.certificationRequestToAsn1(t)).getBytes()};return oe.pem.encode(r,{maxline:e})};G.createCertificate=function(){var t={};return t.version=2,t.serialNumber="00",t.signatureOid=null,t.signature=null,t.siginfo={},t.siginfo.algorithmOid=null,t.validity={},t.validity.notBefore=new Date,t.validity.notAfter=new Date,t.issuer={},t.issuer.getField=function(e){return li(t.issuer,e)},t.issuer.addField=function(e){Ir([e]),t.issuer.attributes.push(e)},t.issuer.attributes=[],t.issuer.hash=null,t.subject={},t.subject.getField=function(e){return li(t.subject,e)},t.subject.addField=function(e){Ir([e]),t.subject.attributes.push(e)},t.subject.attributes=[],t.subject.hash=null,t.extensions=[],t.publicKey=null,t.md=null,t.setSubject=function(e,r){Ir(e),t.subject.attributes=e,delete t.subject.uniqueId,r&&(t.subject.uniqueId=r),t.subject.hash=null},t.setIssuer=function(e,r){Ir(e),t.issuer.attributes=e,delete t.issuer.uniqueId,r&&(t.issuer.uniqueId=r),t.issuer.hash=null},t.setExtensions=function(e){for(var r=0;r<e.length;++r)X_(e[r],{cert:t});t.extensions=e},t.getExtension=function(e){typeof e=="string"&&(e={name:e});for(var r=null,n,i=0;r===null&&i<t.extensions.length;++i)n=t.extensions[i],(e.id&&n.id===e.id||e.name&&n.name===e.name)&&(r=n);return r},t.sign=function(e,r){t.md=r||oe.md.sha1.create();var n=Ce[t.md.algorithm+"WithRSAEncryption"];if(!n){var i=new Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw i.algorithm=t.md.algorithm,i}t.signatureOid=t.siginfo.algorithmOid=n,t.tbsCertificate=G.getTBSCertificate(t);var s=y.toDer(t.tbsCertificate);t.md.update(s.getBytes()),t.signature=e.sign(t.md)},t.verify=function(e){var r=!1;if(!t.issued(e)){var n=e.issuer,i=t.subject,s=new Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw s.expectedIssuer=i.attributes,s.actualIssuer=n.attributes,s}var o=e.md;if(o===null){o=Ou({signatureOid:e.signatureOid,type:"certificate"});var a=e.tbsCertificate||G.getTBSCertificate(e),c=y.toDer(a);o.update(c.getBytes())}return o!==null&&(r=Q_({certificate:t,md:o,signature:e.signature})),r},t.isIssuer=function(e){var r=!1,n=t.issuer,i=e.subject;if(n.hash&&i.hash)r=n.hash===i.hash;else if(n.attributes.length===i.attributes.length){r=!0;for(var s,o,a=0;r&&a<n.attributes.length;++a)s=n.attributes[a],o=i.attributes[a],(s.type!==o.type||s.value!==o.value)&&(r=!1)}return r},t.issued=function(e){return e.isIssuer(t)},t.generateSubjectKeyIdentifier=function(){return G.getPublicKeyFingerprint(t.publicKey,{type:"RSAPublicKey"})},t.verifySubjectKeyIdentifier=function(){for(var e=Ce.subjectKeyIdentifier,r=0;r<t.extensions.length;++r){var n=t.extensions[r];if(n.id===e){var i=t.generateSubjectKeyIdentifier().getBytes();return oe.util.hexToBytes(n.subjectKeyIdentifier)===i}}return!1},t};G.certificateFromAsn1=function(t,e){var r={},n=[];if(!y.validate(t,JL,r,n)){var i=new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw i.errors=n,i}var s=y.derToOid(r.publicKeyOid);if(s!==G.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var o=G.createCertificate();o.version=r.certVersion?r.certVersion.charCodeAt(0):0;var a=oe.util.createBuffer(r.certSerialNumber);o.serialNumber=a.toHex(),o.signatureOid=oe.asn1.derToOid(r.certSignatureOid),o.signatureParameters=Nu(o.signatureOid,r.certSignatureParams,!0),o.siginfo.algorithmOid=oe.asn1.derToOid(r.certinfoSignatureOid),o.siginfo.parameters=Nu(o.siginfo.algorithmOid,r.certinfoSignatureParams,!1),o.signature=r.certSignature;var c=[];if(r.certValidity1UTCTime!==void 0&&c.push(y.utcTimeToDate(r.certValidity1UTCTime)),r.certValidity2GeneralizedTime!==void 0&&c.push(y.generalizedTimeToDate(r.certValidity2GeneralizedTime)),r.certValidity3UTCTime!==void 0&&c.push(y.utcTimeToDate(r.certValidity3UTCTime)),r.certValidity4GeneralizedTime!==void 0&&c.push(y.generalizedTimeToDate(r.certValidity4GeneralizedTime)),c.length>2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(c.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(o.validity.notBefore=c[0],o.validity.notAfter=c[1],o.tbsCertificate=r.tbsCertificate,e){o.md=Ou({signatureOid:o.signatureOid,type:"certificate"});var u=y.toDer(o.tbsCertificate);o.md.update(u.getBytes())}var l=oe.md.sha1.create(),f=y.toDer(r.certIssuer);l.update(f.getBytes()),o.issuer.getField=function(h){return li(o.issuer,h)},o.issuer.addField=function(h){Ir([h]),o.issuer.attributes.push(h)},o.issuer.attributes=G.RDNAttributesAsArray(r.certIssuer),r.certIssuerUniqueId&&(o.issuer.uniqueId=r.certIssuerUniqueId),o.issuer.hash=l.digest().toHex();var d=oe.md.sha1.create(),p=y.toDer(r.certSubject);return d.update(p.getBytes()),o.subject.getField=function(h){return li(o.subject,h)},o.subject.addField=function(h){Ir([h]),o.subject.attributes.push(h)},o.subject.attributes=G.RDNAttributesAsArray(r.certSubject),r.certSubjectUniqueId&&(o.subject.uniqueId=r.certSubjectUniqueId),o.subject.hash=d.digest().toHex(),r.certExtensions?o.extensions=G.certificateExtensionsFromAsn1(r.certExtensions):o.extensions=[],o.publicKey=G.publicKeyFromAsn1(r.subjectPublicKeyInfo),o};G.certificateExtensionsFromAsn1=function(t){for(var e=[],r=0;r<t.value.length;++r)for(var n=t.value[r],i=0;i<n.value.length;++i)e.push(G.certificateExtensionFromAsn1(n.value[i]));return e};G.certificateExtensionFromAsn1=function(t){var e={};if(e.id=y.derToOid(t.value[0].value),e.critical=!1,t.value[1].type===y.Type.BOOLEAN?(e.critical=t.value[1].value.charCodeAt(0)!==0,e.value=t.value[2].value):e.value=t.value[1].value,e.id in Ce){if(e.name=Ce[e.id],e.name==="keyUsage"){var r=y.fromDer(e.value),n=0,i=0;r.value.length>1&&(n=r.value.charCodeAt(1),i=r.value.length>2?r.value.charCodeAt(2):0),e.digitalSignature=(n&128)==128,e.nonRepudiation=(n&64)==64,e.keyEncipherment=(n&32)==32,e.dataEncipherment=(n&16)==16,e.keyAgreement=(n&8)==8,e.keyCertSign=(n&4)==4,e.cRLSign=(n&2)==2,e.encipherOnly=(n&1)==1,e.decipherOnly=(i&128)==128}else if(e.name==="basicConstraints"){var r=y.fromDer(e.value);r.value.length>0&&r.value[0].type===y.Type.BOOLEAN?e.cA=r.value[0].value.charCodeAt(0)!==0:e.cA=!1;var s=null;r.value.length>0&&r.value[0].type===y.Type.INTEGER?s=r.value[0].value:r.value.length>1&&(s=r.value[1].value),s!==null&&(e.pathLenConstraint=y.derToInteger(s))}else if(e.name==="extKeyUsage")for(var r=y.fromDer(e.value),o=0;o<r.value.length;++o){var a=y.derToOid(r.value[o].value);a in Ce?e[Ce[a]]=!0:e[a]=!0}else if(e.name==="nsCertType"){var r=y.fromDer(e.value),n=0;r.value.length>1&&(n=r.value.charCodeAt(1)),e.client=(n&128)==128,e.server=(n&64)==64,e.email=(n&32)==32,e.objsign=(n&16)==16,e.reserved=(n&8)==8,e.sslCA=(n&4)==4,e.emailCA=(n&2)==2,e.objCA=(n&1)==1}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.altNames=[];for(var c,r=y.fromDer(e.value),u=0;u<r.value.length;++u){c=r.value[u];var l={type:c.type,value:c.value};switch(e.altNames.push(l),c.type){case 1:case 2:case 6:break;case 7:l.ip=oe.util.bytesToIP(c.value);break;case 8:l.oid=y.derToOid(c.value);break;default:}}}else if(e.name==="subjectKeyIdentifier"){var r=y.fromDer(e.value);e.subjectKeyIdentifier=oe.util.bytesToHex(r.value)}}return e};G.certificationRequestFromAsn1=function(t,e){var r={},n=[];if(!y.validate(t,rk,r,n)){var i=new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw i.errors=n,i}var s=y.derToOid(r.publicKeyOid);if(s!==G.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var o=G.createCertificationRequest();if(o.version=r.csrVersion?r.csrVersion.charCodeAt(0):0,o.signatureOid=oe.asn1.derToOid(r.csrSignatureOid),o.signatureParameters=Nu(o.signatureOid,r.csrSignatureParams,!0),o.siginfo.algorithmOid=oe.asn1.derToOid(r.csrSignatureOid),o.siginfo.parameters=Nu(o.siginfo.algorithmOid,r.csrSignatureParams,!1),o.signature=r.csrSignature,o.certificationRequestInfo=r.certificationRequestInfo,e){o.md=Ou({signatureOid:o.signatureOid,type:"certification request"});var a=y.toDer(o.certificationRequestInfo);o.md.update(a.getBytes())}var c=oe.md.sha1.create();return o.subject.getField=function(u){return li(o.subject,u)},o.subject.addField=function(u){Ir([u]),o.subject.attributes.push(u)},o.subject.attributes=G.RDNAttributesAsArray(r.certificationRequestInfoSubject,c),o.subject.hash=c.digest().toHex(),o.publicKey=G.publicKeyFromAsn1(r.subjectPublicKeyInfo),o.getAttribute=function(u){return li(o,u)},o.addAttribute=function(u){Ir([u]),o.attributes.push(u)},o.attributes=G.CRIAttributesAsArray(r.certificationRequestInfoAttributes||[]),o};G.createCertificationRequest=function(){var t={};return t.version=0,t.signatureOid=null,t.signature=null,t.siginfo={},t.siginfo.algorithmOid=null,t.subject={},t.subject.getField=function(e){return li(t.subject,e)},t.subject.addField=function(e){Ir([e]),t.subject.attributes.push(e)},t.subject.attributes=[],t.subject.hash=null,t.publicKey=null,t.attributes=[],t.getAttribute=function(e){return li(t,e)},t.addAttribute=function(e){Ir([e]),t.attributes.push(e)},t.md=null,t.setSubject=function(e){Ir(e),t.subject.attributes=e,t.subject.hash=null},t.setAttributes=function(e){Ir(e),t.attributes=e},t.sign=function(e,r){t.md=r||oe.md.sha1.create();var n=Ce[t.md.algorithm+"WithRSAEncryption"];if(!n){var i=new Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw i.algorithm=t.md.algorithm,i}t.signatureOid=t.siginfo.algorithmOid=n,t.certificationRequestInfo=G.getCertificationRequestInfo(t);var s=y.toDer(t.certificationRequestInfo);t.md.update(s.getBytes()),t.signature=e.sign(t.md)},t.verify=function(){var e=!1,r=t.md;if(r===null){r=Ou({signatureOid:t.signatureOid,type:"certification request"});var n=t.certificationRequestInfo||G.getCertificationRequestInfo(t),i=y.toDer(n);r.update(i.getBytes())}return r!==null&&(e=Q_({certificate:t,md:r,signature:t.signature})),e},t};function ho(t){for(var e=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]),r,n,i=t.attributes,s=0;s<i.length;++s){r=i[s];var o=r.value,a=y.Type.PRINTABLESTRING;"valueTagClass"in r&&(a=r.valueTagClass,a===y.Type.UTF8&&(o=oe.util.encodeUtf8(o))),n=y.create(y.Class.UNIVERSAL,y.Type.SET,!0,[y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(r.type).getBytes()),y.create(y.Class.UNIVERSAL,a,!1,o)])]),e.value.push(n)}return e}function Ir(t){for(var e,r=0;r<t.length;++r){if(e=t[r],typeof e.name=="undefined"&&(e.type&&e.type in G.oids?e.name=G.oids[e.type]:e.shortName&&e.shortName in ft&&(e.name=G.oids[ft[e.shortName]])),typeof e.type=="undefined")if(e.name&&e.name in G.oids)e.type=G.oids[e.name];else{var n=new Error("Attribute type not specified.");throw n.attribute=e,n}if(typeof e.shortName=="undefined"&&e.name&&e.name in ft&&(e.shortName=ft[e.name]),e.type===Ce.extensionRequest&&(e.valueConstructed=!0,e.valueTagClass=y.Type.SEQUENCE,!e.value&&e.extensions)){e.value=[];for(var i=0;i<e.extensions.length;++i)e.value.push(G.certificateExtensionToAsn1(X_(e.extensions[i])))}if(typeof e.value=="undefined"){var n=new Error("Attribute value not specified.");throw n.attribute=e,n}}}function X_(t,e){if(e=e||{},typeof t.name=="undefined"&&t.id&&t.id in G.oids&&(t.name=G.oids[t.id]),typeof t.id=="undefined")if(t.name&&t.name in G.oids)t.id=G.oids[t.name];else{var r=new Error("Extension ID not specified.");throw r.extension=t,r}if(typeof t.value!="undefined")return t;if(t.name==="keyUsage"){var n=0,i=0,s=0;t.digitalSignature&&(i|=128,n=7),t.nonRepudiation&&(i|=64,n=6),t.keyEncipherment&&(i|=32,n=5),t.dataEncipherment&&(i|=16,n=4),t.keyAgreement&&(i|=8,n=3),t.keyCertSign&&(i|=4,n=2),t.cRLSign&&(i|=2,n=1),t.encipherOnly&&(i|=1,n=0),t.decipherOnly&&(s|=128,n=7);var o=String.fromCharCode(n);s!==0?o+=String.fromCharCode(i)+String.fromCharCode(s):i!==0&&(o+=String.fromCharCode(i)),t.value=y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,o)}else if(t.name==="basicConstraints")t.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]),t.cA&&t.value.value.push(y.create(y.Class.UNIVERSAL,y.Type.BOOLEAN,!1,String.fromCharCode(255))),"pathLenConstraint"in t&&t.value.value.push(y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(t.pathLenConstraint).getBytes()));else if(t.name==="extKeyUsage"){t.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);var a=t.value.value;for(var c in t)t[c]===!0&&(c in Ce?a.push(y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(Ce[c]).getBytes())):c.indexOf(".")!==-1&&a.push(y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(c).getBytes())))}else if(t.name==="nsCertType"){var n=0,i=0;t.client&&(i|=128,n=7),t.server&&(i|=64,n=6),t.email&&(i|=32,n=5),t.objsign&&(i|=16,n=4),t.reserved&&(i|=8,n=3),t.sslCA&&(i|=4,n=2),t.emailCA&&(i|=2,n=1),t.objCA&&(i|=1,n=0);var o=String.fromCharCode(n);i!==0&&(o+=String.fromCharCode(i)),t.value=y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,o)}else if(t.name==="subjectAltName"||t.name==="issuerAltName"){t.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);for(var u,l=0;l<t.altNames.length;++l){u=t.altNames[l];var o=u.value;if(u.type===7&&u.ip){if(o=oe.util.bytesFromIP(u.ip),o===null){var r=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw r.extension=t,r}}else u.type===8&&(u.oid?o=y.oidToDer(y.oidToDer(u.oid)):o=y.oidToDer(o));t.value.value.push(y.create(y.Class.CONTEXT_SPECIFIC,u.type,!1,o))}}else if(t.name==="nsComment"&&e.cert){if(!/^[\x00-\x7F]*$/.test(t.comment)||t.comment.length<1||t.comment.length>128)throw new Error('Invalid "nsComment" content.');t.value=y.create(y.Class.UNIVERSAL,y.Type.IA5STRING,!1,t.comment)}else if(t.name==="subjectKeyIdentifier"&&e.cert){var f=e.cert.generateSubjectKeyIdentifier();t.subjectKeyIdentifier=f.toHex(),t.value=y.create(y.Class.UNIVERSAL,y.Type.OCTETSTRING,!1,f.getBytes())}else if(t.name==="authorityKeyIdentifier"&&e.cert){t.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);var a=t.value.value;if(t.keyIdentifier){var d=t.keyIdentifier===!0?e.cert.generateSubjectKeyIdentifier().getBytes():t.keyIdentifier;a.push(y.create(y.Class.CONTEXT_SPECIFIC,0,!1,d))}if(t.authorityCertIssuer){var p=[y.create(y.Class.CONTEXT_SPECIFIC,4,!0,[ho(t.authorityCertIssuer===!0?e.cert.issuer:t.authorityCertIssuer)])];a.push(y.create(y.Class.CONTEXT_SPECIFIC,1,!0,p))}if(t.serialNumber){var h=oe.util.hexToBytes(t.serialNumber===!0?e.cert.serialNumber:t.serialNumber);a.push(y.create(y.Class.CONTEXT_SPECIFIC,2,!1,h))}}else if(t.name==="cRLDistributionPoints"){t.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);for(var a=t.value.value,g=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]),m=y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[]),u,l=0;l<t.altNames.length;++l){u=t.altNames[l];var o=u.value;if(u.type===7&&u.ip){if(o=oe.util.bytesFromIP(u.ip),o===null){var r=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw r.extension=t,r}}else u.type===8&&(u.oid?o=y.oidToDer(y.oidToDer(u.oid)):o=y.oidToDer(o));m.value.push(y.create(y.Class.CONTEXT_SPECIFIC,u.type,!1,o))}g.value.push(y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[m])),a.push(g)}if(typeof t.value=="undefined"){var r=new Error("Extension value not specified.");throw r.extension=t,r}return t}function vh(t,e){switch(t){case Ce["RSASSA-PSS"]:var r=[];return e.hash.algorithmOid!==void 0&&r.push(y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(e.hash.algorithmOid).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")])])),e.mgf.algorithmOid!==void 0&&r.push(y.create(y.Class.CONTEXT_SPECIFIC,1,!0,[y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(e.mgf.algorithmOid).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(e.mgf.hash.algorithmOid).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")])])])),e.saltLength!==void 0&&r.push(y.create(y.Class.CONTEXT_SPECIFIC,2,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(e.saltLength).getBytes())])),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,r);default:return y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")}}function nk(t){var e=y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[]);if(t.attributes.length===0)return e;for(var r=t.attributes,n=0;n<r.length;++n){var i=r[n],s=i.value,o=y.Type.UTF8;"valueTagClass"in i&&(o=i.valueTagClass),o===y.Type.UTF8&&(s=oe.util.encodeUtf8(s));var a=!1;"valueConstructed"in i&&(a=i.valueConstructed);var c=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(i.type).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.SET,!0,[y.create(y.Class.UNIVERSAL,o,a,s)])]);e.value.push(c)}return e}var ik=new Date("1950-01-01T00:00:00Z"),sk=new Date("2050-01-01T00:00:00Z");function Z_(t){return t>=ik&&t<sk?y.create(y.Class.UNIVERSAL,y.Type.UTCTIME,!1,y.dateToUtcTime(t)):y.create(y.Class.UNIVERSAL,y.Type.GENERALIZEDTIME,!1,y.dateToGeneralizedTime(t))}G.getTBSCertificate=function(t){var e=Z_(t.validity.notBefore),r=Z_(t.validity.notAfter),n=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(t.version).getBytes())]),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,oe.util.hexToBytes(t.serialNumber)),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(t.siginfo.algorithmOid).getBytes()),vh(t.siginfo.algorithmOid,t.siginfo.parameters)]),ho(t.issuer),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[e,r]),ho(t.subject),G.publicKeyToAsn1(t.publicKey)]);return t.issuer.uniqueId&&n.value.push(y.create(y.Class.CONTEXT_SPECIFIC,1,!0,[y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,String.fromCharCode(0)+t.issuer.uniqueId)])),t.subject.uniqueId&&n.value.push(y.create(y.Class.CONTEXT_SPECIFIC,2,!0,[y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,String.fromCharCode(0)+t.subject.uniqueId)])),t.extensions.length>0&&n.value.push(G.certificateExtensionsToAsn1(t.extensions)),n};G.getCertificationRequestInfo=function(t){var e=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(t.version).getBytes()),ho(t.subject),G.publicKeyToAsn1(t.publicKey),nk(t)]);return e};G.distinguishedNameToAsn1=function(t){return ho(t)};G.certificateToAsn1=function(t){var e=t.tbsCertificate||G.getTBSCertificate(t);return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[e,y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(t.signatureOid).getBytes()),vh(t.signatureOid,t.signatureParameters)]),y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,String.fromCharCode(0)+t.signature)])};G.certificateExtensionsToAsn1=function(t){var e=y.create(y.Class.CONTEXT_SPECIFIC,3,!0,[]),r=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);e.value.push(r);for(var n=0;n<t.length;++n)r.value.push(G.certificateExtensionToAsn1(t[n]));return e};G.certificateExtensionToAsn1=function(t){var e=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);e.value.push(y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(t.id).getBytes())),t.critical&&e.value.push(y.create(y.Class.UNIVERSAL,y.Type.BOOLEAN,!1,String.fromCharCode(255)));var r=t.value;return typeof t.value!="string"&&(r=y.toDer(r).getBytes()),e.value.push(y.create(y.Class.UNIVERSAL,y.Type.OCTETSTRING,!1,r)),e};G.certificationRequestToAsn1=function(t){var e=t.certificationRequestInfo||G.getCertificationRequestInfo(t);return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[e,y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(t.signatureOid).getBytes()),vh(t.signatureOid,t.signatureParameters)]),y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,String.fromCharCode(0)+t.signature)])};G.createCaStore=function(t){var e={certs:{}};e.getIssuer=function(o){var a=r(o.issuer);return a},e.addCertificate=function(o){if(typeof o=="string"&&(o=oe.pki.certificateFromPem(o)),n(o.subject),!e.hasCertificate(o))if(o.subject.hash in e.certs){var a=e.certs[o.subject.hash];oe.util.isArray(a)||(a=[a]),a.push(o),e.certs[o.subject.hash]=a}else e.certs[o.subject.hash]=o},e.hasCertificate=function(o){typeof o=="string"&&(o=oe.pki.certificateFromPem(o));var a=r(o.subject);if(!a)return!1;oe.util.isArray(a)||(a=[a]);for(var c=y.toDer(G.certificateToAsn1(o)).getBytes(),u=0;u<a.length;++u){var l=y.toDer(G.certificateToAsn1(a[u])).getBytes();if(c===l)return!0}return!1},e.listAllCertificates=function(){var o=[];for(var a in e.certs)if(e.certs.hasOwnProperty(a)){var c=e.certs[a];if(!oe.util.isArray(c))o.push(c);else for(var u=0;u<c.length;++u)o.push(c[u])}return o},e.removeCertificate=function(o){var a;if(typeof o=="string"&&(o=oe.pki.certificateFromPem(o)),n(o.subject),!e.hasCertificate(o))return null;var c=r(o.subject);if(!oe.util.isArray(c))return a=e.certs[o.subject.hash],delete e.certs[o.subject.hash],a;for(var u=y.toDer(G.certificateToAsn1(o)).getBytes(),l=0;l<c.length;++l){var f=y.toDer(G.certificateToAsn1(c[l])).getBytes();u===f&&(a=c[l],c.splice(l,1))}return c.length===0&&delete e.certs[o.subject.hash],a};function r(o){return n(o),e.certs[o.hash]||null}function n(o){if(!o.hash){var a=oe.md.sha1.create();o.attributes=G.RDNAttributesAsArray(ho(o),a),o.hash=a.digest().toHex()}}if(t)for(var i=0;i<t.length;++i){var s=t[i];e.addCertificate(s)}return e};G.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"};G.verifyCertificateChain=function(t,e,r){typeof r=="function"&&(r={verify:r}),r=r||{},e=e.slice(0);var n=e.slice(0),i=r.validityCheckDate;typeof i=="undefined"&&(i=new Date);var s=!0,o=null,a=0;do{var c=e.shift(),u=null,l=!1;if(i&&(i<c.validity.notBefore||i>c.validity.notAfter)&&(o={message:"Certificate is not valid yet or has expired.",error:G.certificateError.certificate_expired,notBefore:c.validity.notBefore,notAfter:c.validity.notAfter,now:i}),o===null){if(u=e[0]||t.getIssuer(c),u===null&&c.isIssuer(c)&&(l=!0,u=c),u){var f=u;oe.util.isArray(f)||(f=[f]);for(var d=!1;!d&&f.length>0;){u=f.shift();try{d=u.verify(c)}catch(q){}}d||(o={message:"Certificate signature is invalid.",error:G.certificateError.bad_certificate})}o===null&&(!u||l)&&!t.hasCertificate(c)&&(o={message:"Certificate is not trusted.",error:G.certificateError.unknown_ca})}if(o===null&&u&&!c.isIssuer(u)&&(o={message:"Certificate issuer is invalid.",error:G.certificateError.bad_certificate}),o===null)for(var p={keyUsage:!0,basicConstraints:!0},h=0;o===null&&h<c.extensions.length;++h){var g=c.extensions[h];g.critical&&!(g.name in p)&&(o={message:"Certificate has an unsupported critical extension.",error:G.certificateError.unsupported_certificate})}if(o===null&&(!s||e.length===0&&(!u||l))){var m=c.getExtension("basicConstraints"),S=c.getExtension("keyUsage");if(S!==null&&(!S.keyCertSign||m===null)&&(o={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:G.certificateError.bad_certificate}),o===null&&m!==null&&!m.cA&&(o={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:G.certificateError.bad_certificate}),o===null&&S!==null&&"pathLenConstraint"in m){var R=a-1;R>m.pathLenConstraint&&(o={message:"Certificate basicConstraints pathLenConstraint violated.",error:G.certificateError.bad_certificate})}}var L=o===null?!0:o.error,H=r.verify?r.verify(L,a,n):L;if(H===!0)o=null;else throw L===!0&&(o={message:"The application rejected the certificate.",error:G.certificateError.bad_certificate}),(H||H===0)&&(typeof H=="object"&&!oe.util.isArray(H)?(H.message&&(o.message=H.message),H.error&&(o.error=H.error)):typeof H=="string"&&(o.error=H)),o;s=!1,++a}while(e.length>0);return!0}});var rS=w((XK,tS)=>{var Y=be();Is();jn();yc();xs();bc();V_();Ci();$e();bh();var T=Y.asn1,zt=tS.exports=Y.pkcs7=Y.pkcs7||{};zt.messageFromPem=function(t){var e=Y.pem.decode(t)[0];if(e.type!=="PKCS7"){var r=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw r.headerType=e.type,r}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var n=T.fromDer(e.body);return zt.messageFromAsn1(n)};zt.messageToPem=function(t,e){var r={type:"PKCS7",body:T.toDer(t.toAsn1()).getBytes()};return Y.pem.encode(r,{maxline:e})};zt.messageFromAsn1=function(t){var e={},r=[];if(!T.validate(t,zt.asn1.contentInfoValidator,e,r)){var n=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw n.errors=r,n}var i=T.derToOid(e.contentType),s;switch(i){case Y.pki.oids.envelopedData:s=zt.createEnvelopedData();break;case Y.pki.oids.encryptedData:s=zt.createEncryptedData();break;case Y.pki.oids.signedData:s=zt.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return s.fromAsn1(e.content.value[0]),s};zt.createSignedData=function(){var t=null;return t={type:Y.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(n){if(wh(t,n,zt.asn1.signedDataValidator),t.certificates=[],t.crls=[],t.digestAlgorithmIdentifiers=[],t.contentInfo=null,t.signerInfos=[],t.rawCapture.certificates)for(var i=t.rawCapture.certificates.value,s=0;s<i.length;++s)t.certificates.push(Y.pki.certificateFromAsn1(i[s]))},toAsn1:function(){t.contentInfo||t.sign();for(var n=[],i=0;i<t.certificates.length;++i)n.push(Y.pki.certificateToAsn1(t.certificates[i]));var s=[],o=T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(t.version).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.SET,!0,t.digestAlgorithmIdentifiers),t.contentInfo])]);return n.length>0&&o.value[0].value.push(T.create(T.Class.CONTEXT_SPECIFIC,0,!0,n)),s.length>0&&o.value[0].value.push(T.create(T.Class.CONTEXT_SPECIFIC,1,!0,s)),o.value[0].value.push(T.create(T.Class.UNIVERSAL,T.Type.SET,!0,t.signerInfos)),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(t.type).getBytes()),o])},addSigner:function(n){var i=n.issuer,s=n.serialNumber;if(n.certificate){var o=n.certificate;typeof o=="string"&&(o=Y.pki.certificateFromPem(o)),i=o.issuer.attributes,s=o.serialNumber}var a=n.key;if(!a)throw new Error("Could not add PKCS#7 signer; no private key specified.");typeof a=="string"&&(a=Y.pki.privateKeyFromPem(a));var c=n.digestAlgorithm||Y.pki.oids.sha1;switch(c){case Y.pki.oids.sha1:case Y.pki.oids.sha256:case Y.pki.oids.sha384:case Y.pki.oids.sha512:case Y.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+c)}var u=n.authenticatedAttributes||[];if(u.length>0){for(var l=!1,f=!1,d=0;d<u.length;++d){var p=u[d];if(!l&&p.type===Y.pki.oids.contentType){if(l=!0,f)break;continue}if(!f&&p.type===Y.pki.oids.messageDigest){if(f=!0,l)break;continue}}if(!l||!f)throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}t.signers.push({key:a,version:1,issuer:i,serialNumber:s,digestAlgorithm:c,signatureAlgorithm:Y.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:u,unauthenticatedAttributes:[]})},sign:function(n){if(n=n||{},(typeof t.content!="object"||t.contentInfo===null)&&(t.contentInfo=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(Y.pki.oids.data).getBytes())]),"content"in t)){var i;t.content instanceof Y.util.ByteBuffer?i=t.content.bytes():typeof t.content=="string"&&(i=Y.util.encodeUtf8(t.content)),n.detached?t.detachedContent=T.create(T.Class.UNIVERSAL,T.Type.OCTETSTRING,!1,i):t.contentInfo.value.push(T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[T.create(T.Class.UNIVERSAL,T.Type.OCTETSTRING,!1,i)]))}if(t.signers.length!==0){var s=e();r(s)}},verify:function(){throw new Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(n){typeof n=="string"&&(n=Y.pki.certificateFromPem(n)),t.certificates.push(n)},addCertificateRevokationList:function(n){throw new Error("PKCS#7 CRL support not yet implemented.")}},t;function e(){for(var n={},i=0;i<t.signers.length;++i){var s=t.signers[i],o=s.digestAlgorithm;o in n||(n[o]=Y.md[Y.pki.oids[o]].create()),s.authenticatedAttributes.length===0?s.md=n[o]:s.md=Y.md[Y.pki.oids[o]].create()}t.digestAlgorithmIdentifiers=[];for(var o in n)t.digestAlgorithmIdentifiers.push(T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(o).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")]));return n}function r(n){var i;if(t.detachedContent?i=t.detachedContent:(i=t.contentInfo.value[1],i=i.value[0]),!i)throw new Error("Could not sign PKCS#7 message; there is no content to sign.");var s=T.derToOid(t.contentInfo.value[0].value),o=T.toDer(i);o.getByte(),T.getBerValueLength(o),o=o.getBytes();for(var a in n)n[a].start().update(o);for(var c=new Date,u=0;u<t.signers.length;++u){var l=t.signers[u];if(l.authenticatedAttributes.length===0){if(s!==Y.pki.oids.data)throw new Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{l.authenticatedAttributesAsn1=T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[]);for(var f=T.create(T.Class.UNIVERSAL,T.Type.SET,!0,[]),d=0;d<l.authenticatedAttributes.length;++d){var p=l.authenticatedAttributes[d];p.type===Y.pki.oids.messageDigest?p.value=n[l.digestAlgorithm].digest():p.type===Y.pki.oids.signingTime&&(p.value||(p.value=c)),f.value.push(Eh(p)),l.authenticatedAttributesAsn1.value.push(Eh(p))}o=T.toDer(f).getBytes(),l.md.start().update(o)}l.signature=l.key.sign(l.md,"RSASSA-PKCS1-V1_5")}t.signerInfos=fk(t.signers)}};zt.createEncryptedData=function(){var t=null;return t={type:Y.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:Y.pki.oids["aes256-CBC"]},fromAsn1:function(e){wh(t,e,zt.asn1.encryptedDataValidator)},decrypt:function(e){e!==void 0&&(t.encryptedContent.key=e),eS(t)}},t};zt.createEnvelopedData=function(){var t=null;return t={type:Y.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:Y.pki.oids["aes256-CBC"]},fromAsn1:function(e){var r=wh(t,e,zt.asn1.envelopedDataValidator);t.recipients=ck(r.recipientInfos.value)},toAsn1:function(){return T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(t.type).getBytes()),T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(t.version).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.SET,!0,uk(t.recipients)),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,dk(t.encryptedContent))])])])},findRecipient:function(e){for(var r=e.issuer.attributes,n=0;n<t.recipients.length;++n){var i=t.recipients[n],s=i.issuer;if(i.serialNumber===e.serialNumber&&s.length===r.length){for(var o=!0,a=0;a<r.length;++a)if(s[a].type!==r[a].type||s[a].value!==r[a].value){o=!1;break}if(o)return i}}return null},decrypt:function(e,r){if(t.encryptedContent.key===void 0&&e!==void 0&&r!==void 0)switch(e.encryptedContent.algorithm){case Y.pki.oids.rsaEncryption:case Y.pki.oids.desCBC:var n=r.decrypt(e.encryptedContent.content);t.encryptedContent.key=Y.util.createBuffer(n);break;default:throw new Error("Unsupported asymmetric cipher, OID "+e.encryptedContent.algorithm)}eS(t)},addRecipient:function(e){t.recipients.push({version:0,issuer:e.issuer.attributes,serialNumber:e.serialNumber,encryptedContent:{algorithm:Y.pki.oids.rsaEncryption,key:e.publicKey}})},encrypt:function(e,r){if(t.encryptedContent.content===void 0){r=r||t.encryptedContent.algorithm,e=e||t.encryptedContent.key;var n,i,s;switch(r){case Y.pki.oids["aes128-CBC"]:n=16,i=16,s=Y.aes.createEncryptionCipher;break;case Y.pki.oids["aes192-CBC"]:n=24,i=16,s=Y.aes.createEncryptionCipher;break;case Y.pki.oids["aes256-CBC"]:n=32,i=16,s=Y.aes.createEncryptionCipher;break;case Y.pki.oids["des-EDE3-CBC"]:n=24,i=8,s=Y.des.createEncryptionCipher;break;default:throw new Error("Unsupported symmetric cipher, OID "+r)}if(e===void 0)e=Y.util.createBuffer(Y.random.getBytes(n));else if(e.length()!=n)throw new Error("Symmetric key has wrong length; got "+e.length()+" bytes, expected "+n+".");t.encryptedContent.algorithm=r,t.encryptedContent.key=e,t.encryptedContent.parameter=Y.util.createBuffer(Y.random.getBytes(i));var o=s(e);if(o.start(t.encryptedContent.parameter.copy()),o.update(t.content),!o.finish())throw new Error("Symmetric encryption failed.");t.encryptedContent.content=o.output}for(var a=0;a<t.recipients.length;++a){var c=t.recipients[a];if(c.encryptedContent.content===void 0)switch(c.encryptedContent.algorithm){case Y.pki.oids.rsaEncryption:c.encryptedContent.content=c.encryptedContent.key.encrypt(t.encryptedContent.key.data);break;default:throw new Error("Unsupported asymmetric cipher, OID "+c.encryptedContent.algorithm)}}}},t};function ok(t){var e={},r=[];if(!T.validate(t,zt.asn1.recipientInfoValidator,e,r)){var n=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw n.errors=r,n}return{version:e.version.charCodeAt(0),issuer:Y.pki.RDNAttributesAsArray(e.issuer),serialNumber:Y.util.createBuffer(e.serial).toHex(),encryptedContent:{algorithm:T.derToOid(e.encAlgorithm),parameter:e.encParameter?e.encParameter.value:void 0,content:e.encKey}}}function ak(t){return T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(t.version).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[Y.pki.distinguishedNameToAsn1({attributes:t.issuer}),T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,Y.util.hexToBytes(t.serialNumber))]),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(t.encryptedContent.algorithm).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")]),T.create(T.Class.UNIVERSAL,T.Type.OCTETSTRING,!1,t.encryptedContent.content)])}function ck(t){for(var e=[],r=0;r<t.length;++r)e.push(ok(t[r]));return e}function uk(t){for(var e=[],r=0;r<t.length;++r)e.push(ak(t[r]));return e}function lk(t){var e=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(t.version).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[Y.pki.distinguishedNameToAsn1({attributes:t.issuer}),T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,Y.util.hexToBytes(t.serialNumber))]),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(t.digestAlgorithm).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")])]);if(t.authenticatedAttributesAsn1&&e.value.push(t.authenticatedAttributesAsn1),e.value.push(T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(t.signatureAlgorithm).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")])),e.value.push(T.create(T.Class.UNIVERSAL,T.Type.OCTETSTRING,!1,t.signature)),t.unauthenticatedAttributes.length>0){for(var r=T.create(T.Class.CONTEXT_SPECIFIC,1,!0,[]),n=0;n<t.unauthenticatedAttributes.length;++n){var i=t.unauthenticatedAttributes[n];r.values.push(Eh(i))}e.value.push(r)}return e}function fk(t){for(var e=[],r=0;r<t.length;++r)e.push(lk(t[r]));return e}function Eh(t){var e;if(t.type===Y.pki.oids.contentType)e=T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(t.value).getBytes());else if(t.type===Y.pki.oids.messageDigest)e=T.create(T.Class.UNIVERSAL,T.Type.OCTETSTRING,!1,t.value.bytes());else if(t.type===Y.pki.oids.signingTime){var r=new Date("1950-01-01T00:00:00Z"),n=new Date("2050-01-01T00:00:00Z"),i=t.value;if(typeof i=="string"){var s=Date.parse(i);isNaN(s)?i.length===13?i=T.utcTimeToDate(i):i=T.generalizedTimeToDate(i):i=new Date(s)}i>=r&&i<n?e=T.create(T.Class.UNIVERSAL,T.Type.UTCTIME,!1,T.dateToUtcTime(i)):e=T.create(T.Class.UNIVERSAL,T.Type.GENERALIZEDTIME,!1,T.dateToGeneralizedTime(i))}return T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(t.type).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.SET,!0,[e])])}function dk(t){return[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(Y.pki.oids.data).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(t.algorithm).getBytes()),t.parameter?T.create(T.Class.UNIVERSAL,T.Type.OCTETSTRING,!1,t.parameter.getBytes()):void 0]),T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[T.create(T.Class.UNIVERSAL,T.Type.OCTETSTRING,!1,t.content.getBytes())])]}function wh(t,e,r){var n={},i=[];if(!T.validate(e,r,n,i)){var s=new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw s.errors=s,s}var o=T.derToOid(n.contentType);if(o!==Y.pki.oids.data)throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(n.encryptedContent){var a="";if(Y.util.isArray(n.encryptedContent))for(var c=0;c<n.encryptedContent.length;++c){if(n.encryptedContent[c].type!==T.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");a+=n.encryptedContent[c].value}else a=n.encryptedContent;t.encryptedContent={algorithm:T.derToOid(n.encAlgorithm),parameter:Y.util.createBuffer(n.encParameter.value),content:Y.util.createBuffer(a)}}if(n.content){var a="";if(Y.util.isArray(n.content))for(var c=0;c<n.content.length;++c){if(n.content[c].type!==T.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");a+=n.content[c].value}else a=n.content;t.content=Y.util.createBuffer(a)}return t.version=n.version.charCodeAt(0),t.rawCapture=n,n}function eS(t){if(t.encryptedContent.key===void 0)throw new Error("Symmetric key not available.");if(t.content===void 0){var e;switch(t.encryptedContent.algorithm){case Y.pki.oids["aes128-CBC"]:case Y.pki.oids["aes192-CBC"]:case Y.pki.oids["aes256-CBC"]:e=Y.aes.createDecryptionCipher(t.encryptedContent.key);break;case Y.pki.oids.desCBC:case Y.pki.oids["des-EDE3-CBC"]:e=Y.des.createDecryptionCipher(t.encryptedContent.key);break;default:throw new Error("Unsupported symmetric cipher, OID "+t.encryptedContent.algorithm)}if(e.start(t.encryptedContent.parameter),e.update(t.encryptedContent.content),!e.finish())throw new Error("Symmetric decryption failed.");t.content=e.output}}});var sS=w((ZK,iS)=>{"use strict";bh();var hk=be(),nS=hk.pki,pk=(t,e)=>{let r=nS.setRsaPublicKey(e.n,e.e),n=nS.createCertificate();n.publicKey=r,n.serialNumber="01",n.validity.notBefore=new Date,n.validity.notAfter=new Date,n.validity.notAfter.setFullYear(n.validity.notBefore.getFullYear()+10);let i=[{name:"organizationName",value:"ipfs"},{shortName:"OU",value:"keystore"},{name:"commonName",value:t.id}];return n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0,codeSigning:!0,emailProtection:!0,timeStamping:!0},{name:"nsCertType",client:!0,server:!0,email:!0,objsign:!0,sslCA:!0,emailCA:!0,objCA:!0}]),n.sign(e),n};async function yk(t,e){let r=t.map(e),i=(await Promise.all(r)).findIndex(s=>s);return t[i]}iS.exports={certificateForKey:pk,findAsync:yk}});var uS=w((JK,cS)=>{"use strict";rS();Xl();var fi=be(),{certificateForKey:gk,findAsync:mk}=sS(),po=de(),{fromString:oS}=(It(),Nt),{toString:vk}=(Tt(),Ot),{codes:yo}=je(),_h=new WeakMap,aS=class{constructor(e,r){if(!e)throw po(new Error("keychain is required"),yo.ERR_KEYCHAIN_REQUIRED);this.keychain=e,_h.set(this,{dek:r})}async encrypt(e,r){if(!(r instanceof Uint8Array))throw po(new Error("Plain data must be a Uint8Array"),yo.ERR_INVALID_PARAMETERS);let n=await this.keychain.findKeyByName(e),i=await this.keychain._getPrivateKey(e),s=_h.get(this).dek,o=fi.pki.decryptRsaPrivateKey(i,s),a=await gk(n,o),c=fi.pkcs7.createEnvelopedData();c.addRecipient(a),c.content=fi.util.createBuffer(r),c.encrypt();let u=fi.asn1.toDer(c.toAsn1()).getBytes();return oS(u,"ascii")}async decrypt(e){if(!(e instanceof Uint8Array))throw po(new Error("CMS data is required"),yo.ERR_INVALID_PARAMETERS);let r;try{let u=fi.util.createBuffer(vk(e,"ascii")),l=fi.asn1.fromDer(u);r=fi.pkcs7.messageFromAsn1(l)}catch(u){throw po(new Error("Invalid CMS: "+u.message),yo.ERR_INVALID_CMS)}let n=r.recipients.filter(u=>u.issuer.find(l=>l.shortName==="O"&&l.value==="ipfs")).filter(u=>u.issuer.find(l=>l.shortName==="CN")).map(u=>({recipient:u,keyId:u.issuer.find(l=>l.shortName==="CN").value})),i=await mk(n,async u=>{try{if(await this.keychain.findKeyById(u.keyId))return!0}catch(l){return!1}return!1});if(!i){let u=n.map(l=>l.keyId);throw po(new Error("Decryption needs one of the key(s): "+u.join(", ")),yo.ERR_MISSING_KEYS,{missingKeys:u})}let s=await this.keychain.findKeyById(i.keyId);if(!s)throw po(new Error("No key available to decrypto"),yo.ERR_NO_KEY);let o=await this.keychain._getPrivateKey(s.name),a=_h.get(this).dek,c=fi.pki.decryptRsaPrivateKey(o,a);return r.decrypt(i.recipient,c),oS(r.content.getBytes(),"ascii")}};cS.exports=aS});var gS=w((eV,yS)=>{"use strict";var lS=Te(),fS=Object.assign(lS("libp2p:keychain"),{error:lS("libp2p:keychain:err")}),bk=C_(),Ek=Hs(),ns=Bu(),{Key:dS}=(Jc(),rd),wk=uS(),et=de(),{codes:tt}=je(),{toString:is}=(Tt(),Ot),{fromString:Pn}=(It(),Nt);hf();var _k="/pkcs8/",hS="/info/",di=new WeakMap,ss={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},Sh={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function Nn(t){return!t||typeof t!="string"?!1:t===bk(t.trim())}async function Le(t){let e=200,r=1e3,n=Math.random()*(r-e)+e;throw await new Promise(i=>setTimeout(i,n)),t}function fn(t){return new dS(_k+t)}function hi(t){return new dS(hS+t)}var pS=class{constructor(e,r){if(!e)throw new Error("store is required");if(this.store=e,this.opts=Ek(Sh,r),this.opts.pass&&this.opts.pass.length<20)throw new Error("pass must be least 20 characters");if(this.opts.dek.keyLength<ss.minKeyLength)throw new Error(`dek.keyLength must be least ${ss.minKeyLength} bytes`);if(this.opts.dek.salt.length<ss.minSaltLength)throw new Error(`dek.saltLength must be least ${ss.minSaltLength} bytes`);if(this.opts.dek.iterationCount<ss.minIterationCount)throw new Error(`dek.iterationCount must be least ${ss.minIterationCount}`);let n=this.opts.pass?ns.pbkdf2(this.opts.pass,this.opts.dek.salt,this.opts.dek.iterationCount,this.opts.dek.keyLength,this.opts.dek.hash):"";di.set(this,{dek:n})}get cms(){return new wk(this,di.get(this).dek)}static generateOptions(){let e=Object.assign({},Sh),r=Math.ceil(ss.minSaltLength/3)*3;return e.dek.salt=is(ns.randomBytes(r),"base64"),e}static get options(){return Sh}async createKey(e,r,n=2048){let i=this;if(!Nn(e)||e==="self")return Le(et(new Error(`Invalid key name '${e}'`),tt.ERR_INVALID_KEY_NAME));if(typeof r!="string")return Le(et(new Error(`Invalid key type '${r}'`),tt.ERR_INVALID_KEY_TYPE));let s=fn(e);if(await i.store.has(s))return Le(et(new Error(`Key '${e}' already exists`),tt.ERR_KEY_ALREADY_EXISTS));switch(r.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)return Le(et(new Error(`Invalid RSA key size ${n}`),tt.ERR_INVALID_KEY_SIZE));break;default:break}let a;try{let c=await ns.keys.generateKeyPair(r,n),u=await c.id(),l=di.get(this).dek,f=await c.export(l);a={name:e,id:u};let d=i.store.batch();d.put(s,Pn(f)),d.put(hi(e),Pn(JSON.stringify(a))),await d.commit()}catch(c){return Le(c)}return a}async listKeys(){let e=this,r={prefix:hS},n=[];for await(let i of e.store.query(r))n.push(JSON.parse(is(i.value)));return n}async findKeyById(e){try{return(await this.listKeys()).find(n=>n.id===e)}catch(r){return Le(r)}}async findKeyByName(e){if(!Nn(e))return Le(et(new Error(`Invalid key name '${e}'`),tt.ERR_INVALID_KEY_NAME));let r=hi(e);try{let n=await this.store.get(r);return JSON.parse(is(n))}catch(n){return Le(et(new Error(`Key '${e}' does not exist. ${n.message}`),tt.ERR_KEY_NOT_FOUND))}}async removeKey(e){let r=this;if(!Nn(e)||e==="self")return Le(et(new Error(`Invalid key name '${e}'`),tt.ERR_INVALID_KEY_NAME));let n=fn(e),i=await r.findKeyByName(e),s=r.store.batch();return s.delete(n),s.delete(hi(e)),await s.commit(),i}async renameKey(e,r){let n=this;if(!Nn(e)||e==="self")return Le(et(new Error(`Invalid old key name '${e}'`),tt.ERR_OLD_KEY_NAME_INVALID));if(!Nn(r)||r==="self")return Le(et(new Error(`Invalid new key name '${r}'`),tt.ERR_NEW_KEY_NAME_INVALID));let i=fn(e),s=fn(r),o=hi(e),a=hi(r);if(await n.store.has(s))return Le(et(new Error(`Key '${r}' already exists`),tt.ERR_KEY_ALREADY_EXISTS));try{let u=await n.store.get(i),l=await n.store.get(o),f=JSON.parse(is(l));f.name=r;let d=n.store.batch();return d.put(s,u),d.put(a,Pn(JSON.stringify(f))),d.delete(i),d.delete(o),await d.commit(),f}catch(u){return Le(u)}}async exportKey(e,r){if(!Nn(e))return Le(et(new Error(`Invalid key name '${e}'`),tt.ERR_INVALID_KEY_NAME));if(!r)return Le(et(new Error("Password is required"),tt.ERR_PASSWORD_REQUIRED));let n=fn(e);try{let i=await this.store.get(n),s=is(i),o=di.get(this).dek;return(await ns.keys.import(s,o)).export(r)}catch(i){return Le(i)}}async importKey(e,r,n){let i=this;if(!Nn(e)||e==="self")return Le(et(new Error(`Invalid key name '${e}'`),tt.ERR_INVALID_KEY_NAME));if(!r)return Le(et(new Error("PEM encoded key is required"),tt.ERR_PEM_REQUIRED));let s=fn(e);if(await i.store.has(s))return Le(et(new Error(`Key '${e}' already exists`),tt.ERR_KEY_ALREADY_EXISTS));let a;try{a=await ns.keys.import(r,n)}catch(f){return Le(et(new Error("Cannot read the key, most likely the password is wrong"),tt.ERR_CANNOT_READ_KEY))}let c;try{c=await a.id();let f=di.get(this).dek;r=await a.export(f)}catch(f){return Le(f)}let u={name:e,id:c},l=i.store.batch();return l.put(s,Pn(r)),l.put(hi(e),Pn(JSON.stringify(u))),await l.commit(),u}async importPeer(e,r){let n=this;if(!Nn(e))return Le(et(new Error(`Invalid key name '${e}'`),tt.ERR_INVALID_KEY_NAME));if(!r||!r.privKey)return Le(et(new Error("Peer.privKey is required"),tt.ERR_MISSING_PRIVATE_KEY));let i=r.privKey,s=fn(e);if(await n.store.has(s))return Le(et(new Error(`Key '${e}' already exists`),tt.ERR_KEY_ALREADY_EXISTS));try{let a=await i.id(),c=di.get(this).dek,u=await i.export(c),l={name:e,id:a},f=n.store.batch();return f.put(s,Pn(u)),f.put(hi(e),Pn(JSON.stringify(l))),await f.commit(),l}catch(a){return Le(a)}}async _getPrivateKey(e){if(!Nn(e))return Le(et(new Error(`Invalid key name '${e}'`),tt.ERR_INVALID_KEY_NAME));try{let r=fn(e),n=await this.store.get(r);return is(n)}catch(r){return Le(et(new Error(`Key '${e}' does not exist. ${r.message}`),tt.ERR_KEY_NOT_FOUND))}}async rotateKeychainPass(e,r){if(typeof e!="string")return Le(et(new Error(`Invalid old pass type '${typeof e}'`),tt.ERR_INVALID_OLD_PASS_TYPE));if(typeof r!="string")return Le(et(new Error(`Invalid new pass type '${typeof r}'`),tt.ERR_INVALID_NEW_PASS_TYPE));if(r.length<20)return Le(et(new Error(`Invalid pass length ${r.length}`),tt.ERR_INVALID_PASS_LENGTH));fS("recreating keychain");let n=di.get(this).dek;this.opts.pass=r;let i=r?ns.pbkdf2(r,this.opts.dek.salt,this.opts.dek.iterationCount,this.opts.dek.keyLength,this.opts.dek.hash):"";di.set(this,{dek:i});let s=await this.listKeys();for(let o of s){let a=await this.store.get(fn(o.name)),c=is(a),u=await ns.keys.import(c,n),l=i.toString(),f=await u.export(l),d=this.store.batch(),p={name:o.name,id:o.id};d.put(fn(o.name),Pn(f)),d.put(hi(o.name),Pn(JSON.stringify(p))),await d.commit()}fS("keychain reconstructed")}};yS.exports=pS});var Lu=w((Du,mS)=>{(function(t,e){typeof Du=="object"&&typeof mS!="undefined"?e(Du):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis!="undefined"?globalThis:t||self,e(t.streamingIterables={}))})(Du,function(t){"use strict";async function*e(b,v){let _=[];for await(let C of v)_.push(C),_.length===b&&(yield _,_=[]);_.length>0&&(yield _)}function*r(b,v){let _=[];for(let C of v)_.push(C),_.length===b&&(yield _,_=[]);_.length>0&&(yield _)}function n(b,v){return v===void 0?_=>n(b,_):v[Symbol.asyncIterator]?e(b,v):r(b,v)}function i(b){if(typeof b.next=="function")return b;if(typeof b[Symbol.iterator]=="function")return b[Symbol.iterator]();if(typeof b[Symbol.asyncIterator]=="function")return b[Symbol.asyncIterator]();throw new TypeError('"values" does not to conform to any of the iterator or iterable protocols')}function s(){let b,v;return{promise:new Promise((C,A)=>{v=C,b=A}),reject:b,resolve:v}}function o(b,v){let _=i(v),C=[],A=[],B=!1,N=!1;function O(){for(;A.length>0&&C.length>0;){let ee=A.shift(),{error:fe,value:qe}=C.shift();fe?ee.reject(fe):ee.resolve({done:!1,value:qe})}for(;A.length>0&&N;){let{resolve:ee}=A.shift();ee({done:!0,value:void 0})}}async function U(){if(!N&&!B&&!(C.length>=b)){B=!0;try{let{done:ee,value:fe}=await _.next();ee?N=!0:C.push({value:fe})}catch(ee){N=!0,C.push({error:ee})}O(),B=!1,U()}}async function W(){if(C.length>0){let{error:fe,value:qe}=C.shift();if(fe)throw fe;return U(),{done:!1,value:qe}}if(N)return{done:!0,value:void 0};let ee=s();return A.push(ee),U(),ee.promise}let Q={next:W,[Symbol.asyncIterator]:()=>Q};return Q}function*a(b,v){let _=[],C;try{for(let A of v)_.push(A),!(_.length<=b)&&(yield _.shift())}catch(A){C=A}for(let A of _)yield A;if(C)throw C}function c(b,v){return v===void 0?_=>c(b,_):b===0?v:v[Symbol.asyncIterator]?o(b,v):a(b,v)}async function u(b){let v=[];for await(let _ of b)v.push(_);return v}function l(b){return b[Symbol.asyncIterator]?u(b):Array.from(b)}async function*f(b){for await(let v of b)yield*v}function*d(b){for(let v of b)yield*v}function p(...b){return b.find(_=>_[Symbol.asyncIterator]!==void 0)?f(b):d(b)}async function h(b){for await(let v of b);}function g(b){if(b[Symbol.asyncIterator])return h(b);for(let v of b);}async function*m(b,v){for await(let _ of v)await b(_)&&(yield _)}function S(b,v){return v===void 0?_=>m(b,_):m(b,v)}async function*R(b){for await(let v of b)v&&typeof v!="string"&&(v[Symbol.iterator]||v[Symbol.asyncIterator])?yield*R(v):yield v}async function*L(b,v){for await(let _ of v)yield await b(_)}function H(b,v){return v===void 0?_=>L(b,_):L(b,v)}function q(b,v){return v===void 0?_=>q(b,_):S(_=>_!=null,R(H(b,v)))}function k(b,v,_){let C=i(_),A=[],B=[],N=!1,O=!1,U=0,W=null;function Q(){for(;B.length>0&&A.length>0;){let{resolve:ae}=B.shift(),ue=A.shift();ae({done:!1,value:ue})}for(;B.length>0&&U===0&&N;){let{resolve:ae,reject:ue}=B.shift();W?(ue(W),W=null):ae({done:!0,value:void 0})}}async function ee(){if(N){Q();return}if(!O&&!(U+A.length>=b)){O=!0,U++;try{let{done:ae,value:ue}=await C.next();ae?(N=!0,U--,Q()):fe(ue)}catch(ae){N=!0,U--,W=ae,Q()}O=!1,ee()}}async function fe(ae){try{let ue=await v(ae);if(ue&&ue[Symbol.asyncIterator])for await(let ds of ue)A.push(ds);else A.push(ue)}catch(ue){N=!0,W=ue}U--,Q(),ee()}async function qe(){if(A.length===0){let ue=s();return B.push(ue),ee(),ue.promise}let ae=A.shift();return ee(),{done:!1,value:ae}}let ge={next:qe,[Symbol.asyncIterator]:()=>ge};return ge}function J(b,v,_){return v===void 0?(C,A)=>A?J(b,C,A):J(b,C):_===void 0?C=>J(b,v,C):S(C=>C!=null,R(k(b,v,_)))}async function ie(b){return new Promise(v=>{b.once("readable",()=>{v()})})}async function*j(b){for(;;){let v=b.read();if(v!==null){yield v;continue}if(b._readableState.ended)break;await ie(b)}}function we(b){return typeof b[Symbol.asyncIterator]=="function"?b:j(b)}async function*le(...b){let v=new Set(b.map(i));for(;v.size>0;)for(let _ of v){let C=await _.next();C.done?v.delete(_):yield C.value}}function ye(b,...v){let _=b();for(let C of v)_=C(_);return _}async function*nt(b,v,_){let C=null,A=U=>({value:v(U)}),B=async function*(U){for await(let W of U){if(C)return;yield W}},N=ye(()=>_,c(1),B,H(A),c(b-1)),O=i(N);for(;;){let{value:U,done:W}=await O.next();if(W)break;try{let Q=await U.value;C||(yield Q)}catch(Q){C=Q}}if(C)throw C}function it(b,v,_){return v===void 0?(C,A)=>it(b,C,A):_===void 0?C=>it(b,v,C):b===1?H(v,_):nt(b,v,_)}function Ie(b,v,_){return v===void 0?(C,A)=>A?Ie(b,C,A):Ie(b,C):_===void 0?C=>Ie(b,v,C):S(C=>C!=null,R(it(b,v,_)))}async function*Fe(...b){let v=b.map(i),_=new Set,C=new Map,A=null,B=null,N=null,O=ee=>{A=ee,B&&B(ee)},U=ee=>{N&&N(ee)},W=()=>new Promise((ee,fe)=>{if(A&&fe(A),C.size>0)return ee();N=ee,B=fe}),Q=ee=>{let fe=Promise.resolve(ee.next()).then(async({done:qe,value:ge})=>{qe||C.set(ee,ge),_.delete(fe)});_.add(fe),fe.then(U,O)};for(let ee of v)Q(ee);for(;;){if(_.size===0&&C.size===0)return;await W();for(let[ee,fe]of C)C.delete(ee),yield fe,Q(ee)}}async function ne(b,v,_){let C=v;for await(let A of _)C=await b(C,A);return C}function tr(b,v,_){return v===void 0?(C,A)=>A?ne(b,C,A):tr(b,C):_===void 0?C=>tr(b,v,C):ne(b,v,_)}async function*Wt(b,v){let _=0;for await(let C of v)if(yield await C,_++,_>=b)break}function*hn(b,v){let _=0;for(let C of v)if(yield C,_++,_>=b)break}function Yt(b,v){return v===void 0?_=>Yt(b,_):v[Symbol.asyncIterator]?Wt(b,v):hn(b,v)}async function*pn(b,v){for await(let _ of v)await b(_),yield _}function z(b,v){return v===void 0?_=>pn(b,_):pn(b,v)}function fs(b,v){let _=b[0]+v[0],C=b[1]+v[1];if(C>=1e9){let A=C%1e9;_+=(C-A)/1e9,C=A}return[_,C]}async function*Ha(b,v){let _=v[Symbol.asyncIterator](),C=[0,0];for(;;){let A=process.hrtime(),{value:B,done:N}=await _.next(),O=process.hrtime(A);if(C=fs(C,O),b.progress&&b.progress(O,C),N)return b.total&&b.total(C),B;yield B}}function*Ro(b,v){let _=v[Symbol.iterator](),C=[0,0];for(;;){let A=process.hrtime(),{value:B,done:N}=_.next(),O=process.hrtime(A);if(C=fs(C,O),b.progress&&b.progress(O,C),N)return b.total&&b.total(C),B;yield B}}function Kt(b={},v){return v===void 0?_=>Kt(b,_):v[Symbol.asyncIterator]!==void 0?Ha(b,v):Ro(b,v)}function Pr(b,v,_){let C=i(_),A=[],B=[],N=!1,O=!1,U=0,W=null;function Q(){for(;B.length>0&&A.length>0;){let{resolve:ae}=B.shift(),ue=A.shift();ae({done:!1,value:ue})}for(;B.length>0&&U===0&&N;){let{resolve:ae,reject:ue}=B.shift();W?(ue(W),W=null):ae({done:!0,value:void 0})}}async function ee(){if(N){Q();return}if(!O&&!(U+A.length>=b)){O=!0,U++;try{let{done:ae,value:ue}=await C.next();ae?(N=!0,U--,Q()):fe(ue)}catch(ae){N=!0,U--,W=ae,Q()}O=!1,ee()}}async function fe(ae){try{let ue=await v(ae);A.push(ue)}catch(ue){N=!0,W=ue}U--,Q(),ee()}async function qe(){if(A.length===0){let ue=s();return B.push(ue),ee(),ue.promise}let ae=A.shift();return ee(),{done:!1,value:ae}}let ge={next:qe,[Symbol.asyncIterator]:()=>ge};return ge}function E(b,v,_){return v===void 0?(C,A)=>A?E(b,C,A):E(b,C):_===void 0?C=>E(b,v,C):Pr(b,v,_)}async function x(b,v){let _=null,C=null,A=null,B=W=>{_=W,C&&C(W)},N=()=>{A&&A()},O=()=>{b.removeListener("error",B),b.removeListener("drain",N)};b.once("error",B);let U=()=>new Promise((W,Q)=>{if(_)return Q(_);b.once("drain",N),A=W,C=Q});for await(let W of v)if(b.write(W)===!1&&await U(),_)break;if(O(),_)throw _}function I(b,v){return v===void 0?_=>x(b,_):x(b,v)}t.batch=n,t.buffer=c,t.collect=l,t.concat=p,t.consume=g,t.filter=S,t.flatMap=q,t.flatTransform=J,t.flatten=R,t.fromStream=we,t.getIterator=i,t.map=H,t.merge=le,t.parallelFlatMap=Ie,t.parallelMap=it,t.parallelMerge=Fe,t.pipeline=ye,t.reduce=tr,t.take=Yt,t.tap=z,t.time=Kt,t.transform=E,t.writeToStream=I,Object.defineProperty(t,"__esModule",{value:!0})})});var bS=w((tV,vS)=>{vS.exports=function(t){if(!t)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,r=Object.create(null),n=Object.create(null);function i(s,o){r[s]=o,e++,e>=t&&(e=0,n=r,r=Object.create(null))}return{has:function(s){return r[s]!==void 0||n[s]!==void 0},remove:function(s){r[s]!==void 0&&(r[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var o=r[s];if(o!==void 0)return o;if((o=n[s])!==void 0)return i(s,o),o},set:function(s,o){r[s]!==void 0?r[s]=o:i(s,o)},clear:function(){r=Object.create(null),n=Object.create(null)}}}});var wS=w((rV,ES)=>{"use strict";var Sk=bS();ES.exports=t=>{let e=Sk(t);return e.delete=e.remove,e}});var SS=w((_S,ku)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,i=Math.floor,s="[BigNumber Error] ",o=s+"Number primitive has more than 15 significant digits: ",a=1e14,c=14,u=9007199254740991,l=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],f=1e7,d=1e9;function p(q){var k,J,ie,j=z.prototype={constructor:z,toString:null,valueOf:null},we=new z(1),le=20,ye=4,nt=-7,it=21,Ie=-1e7,Fe=1e7,ne=!1,tr=1,Wt=0,hn={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Yt="0123456789abcdefghijklmnopqrstuvwxyz",pn=!0;function z(E,x){var I,b,v,_,C,A,B,N,O=this;if(!(O instanceof z))return new z(E,x);if(x==null){if(E&&E._isBigNumber===!0){O.s=E.s,!E.c||E.e>Fe?O.c=O.e=null:E.e<Ie?O.c=[O.e=0]:(O.e=E.e,O.c=E.c.slice());return}if((A=typeof E=="number")&&E*0==0){if(O.s=1/E<0?(E=-E,-1):1,E===~~E){for(_=0,C=E;C>=10;C/=10,_++);_>Fe?O.c=O.e=null:(O.e=_,O.c=[E]);return}N=String(E)}else{if(!r.test(N=String(E)))return ie(O,N,A);O.s=N.charCodeAt(0)==45?(N=N.slice(1),-1):1}(_=N.indexOf("."))>-1&&(N=N.replace(".","")),(C=N.search(/e/i))>0?(_<0&&(_=C),_+=+N.slice(C+1),N=N.substring(0,C)):_<0&&(_=N.length)}else{if(S(x,2,Yt.length,"Base"),x==10&&pn)return O=new z(E),Kt(O,le+O.e+1,ye);if(N=String(E),A=typeof E=="number"){if(E*0!=0)return ie(O,N,A,x);if(O.s=1/E<0?(N=N.slice(1),-1):1,z.DEBUG&&N.replace(/^0\.0*|\./,"").length>15)throw Error(o+E)}else O.s=N.charCodeAt(0)===45?(N=N.slice(1),-1):1;for(I=Yt.slice(0,x),_=C=0,B=N.length;C<B;C++)if(I.indexOf(b=N.charAt(C))<0){if(b=="."){if(C>_){_=B;continue}}else if(!v&&(N==N.toUpperCase()&&(N=N.toLowerCase())||N==N.toLowerCase()&&(N=N.toUpperCase()))){v=!0,C=-1,_=0;continue}return ie(O,String(E),A,x)}A=!1,N=J(N,x,10,O.s),(_=N.indexOf("."))>-1?N=N.replace(".",""):_=N.length}for(C=0;N.charCodeAt(C)===48;C++);for(B=N.length;N.charCodeAt(--B)===48;);if(N=N.slice(C,++B)){if(B-=C,A&&z.DEBUG&&B>15&&(E>u||E!==i(E)))throw Error(o+O.s*E);if((_=_-C-1)>Fe)O.c=O.e=null;else if(_<Ie)O.c=[O.e=0];else{if(O.e=_,O.c=[],C=(_+1)%c,_<0&&(C+=c),C<B){for(C&&O.c.push(+N.slice(0,C)),B-=c;C<B;)O.c.push(+N.slice(C,C+=c));C=c-(N=N.slice(C)).length}else C-=B;for(;C--;N+="0");O.c.push(+N)}}else O.c=[O.e=0]}z.clone=p,z.ROUND_UP=0,z.ROUND_DOWN=1,z.ROUND_CEIL=2,z.ROUND_FLOOR=3,z.ROUND_HALF_UP=4,z.ROUND_HALF_DOWN=5,z.ROUND_HALF_EVEN=6,z.ROUND_HALF_CEIL=7,z.ROUND_HALF_FLOOR=8,z.EUCLID=9,z.config=z.set=function(E){var x,I;if(E!=null)if(typeof E=="object"){if(E.hasOwnProperty(x="DECIMAL_PLACES")&&(I=E[x],S(I,0,d,x),le=I),E.hasOwnProperty(x="ROUNDING_MODE")&&(I=E[x],S(I,0,8,x),ye=I),E.hasOwnProperty(x="EXPONENTIAL_AT")&&(I=E[x],I&&I.pop?(S(I[0],-d,0,x),S(I[1],0,d,x),nt=I[0],it=I[1]):(S(I,-d,d,x),nt=-(it=I<0?-I:I))),E.hasOwnProperty(x="RANGE"))if(I=E[x],I&&I.pop)S(I[0],-d,-1,x),S(I[1],1,d,x),Ie=I[0],Fe=I[1];else if(S(I,-d,d,x),I)Ie=-(Fe=I<0?-I:I);else throw Error(s+x+" cannot be zero: "+I);if(E.hasOwnProperty(x="CRYPTO"))if(I=E[x],I===!!I)if(I)if(typeof crypto!="undefined"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))ne=I;else throw ne=!I,Error(s+"crypto unavailable");else ne=I;else throw Error(s+x+" not true or false: "+I);if(E.hasOwnProperty(x="MODULO_MODE")&&(I=E[x],S(I,0,9,x),tr=I),E.hasOwnProperty(x="POW_PRECISION")&&(I=E[x],S(I,0,d,x),Wt=I),E.hasOwnProperty(x="FORMAT"))if(I=E[x],typeof I=="object")hn=I;else throw Error(s+x+" not an object: "+I);if(E.hasOwnProperty(x="ALPHABET"))if(I=E[x],typeof I=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(I))pn=I.slice(0,10)=="0123456789",Yt=I;else throw Error(s+x+" invalid: "+I)}else throw Error(s+"Object expected: "+E);return{DECIMAL_PLACES:le,ROUNDING_MODE:ye,EXPONENTIAL_AT:[nt,it],RANGE:[Ie,Fe],CRYPTO:ne,MODULO_MODE:tr,POW_PRECISION:Wt,FORMAT:hn,ALPHABET:Yt}},z.isBigNumber=function(E){if(!E||E._isBigNumber!==!0)return!1;if(!z.DEBUG)return!0;var x,I,b=E.c,v=E.e,_=E.s;e:if({}.toString.call(b)=="[object Array]"){if((_===1||_===-1)&&v>=-d&&v<=d&&v===i(v)){if(b[0]===0){if(v===0&&b.length===1)return!0;break e}if(x=(v+1)%c,x<1&&(x+=c),String(b[0]).length==x){for(x=0;x<b.length;x++)if(I=b[x],I<0||I>=a||I!==i(I))break e;if(I!==0)return!0}}}else if(b===null&&v===null&&(_===null||_===1||_===-1))return!0;throw Error(s+"Invalid BigNumber: "+E)},z.maximum=z.max=function(){return Ha(arguments,j.lt)},z.minimum=z.min=function(){return Ha(arguments,j.gt)},z.random=function(){var E=9007199254740992,x=Math.random()*E&2097151?function(){return i(Math.random()*E)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(I){var b,v,_,C,A,B=0,N=[],O=new z(we);if(I==null?I=le:S(I,0,d),C=n(I/c),ne)if(crypto.getRandomValues){for(b=crypto.getRandomValues(new Uint32Array(C*=2));B<C;)A=b[B]*131072+(b[B+1]>>>11),A>=9e15?(v=crypto.getRandomValues(new Uint32Array(2)),b[B]=v[0],b[B+1]=v[1]):(N.push(A%1e14),B+=2);B=C/2}else if(crypto.randomBytes){for(b=crypto.randomBytes(C*=7);B<C;)A=(b[B]&31)*281474976710656+b[B+1]*1099511627776+b[B+2]*4294967296+b[B+3]*16777216+(b[B+4]<<16)+(b[B+5]<<8)+b[B+6],A>=9e15?crypto.randomBytes(7).copy(b,B):(N.push(A%1e14),B+=7);B=C/7}else throw ne=!1,Error(s+"crypto unavailable");if(!ne)for(;B<C;)A=x(),A<9e15&&(N[B++]=A%1e14);for(C=N[--B],I%=c,C&&I&&(A=l[c-I],N[B]=i(C/A)*A);N[B]===0;N.pop(),B--);if(B<0)N=[_=0];else{for(_=-1;N[0]===0;N.splice(0,1),_-=c);for(B=1,A=N[0];A>=10;A/=10,B++);B<c&&(_-=c-B)}return O.e=_,O.c=N,O}}(),z.sum=function(){for(var E=1,x=arguments,I=new z(x[0]);E<x.length;)I=I.plus(x[E++]);return I},J=function(){var E="0123456789";function x(I,b,v,_){for(var C,A=[0],B,N=0,O=I.length;N<O;){for(B=A.length;B--;A[B]*=b);for(A[0]+=_.indexOf(I.charAt(N++)),C=0;C<A.length;C++)A[C]>v-1&&(A[C+1]==null&&(A[C+1]=0),A[C+1]+=A[C]/v|0,A[C]%=v)}return A.reverse()}return function(I,b,v,_,C){var A,B,N,O,U,W,Q,ee,fe=I.indexOf("."),qe=le,ge=ye;for(fe>=0&&(O=Wt,Wt=0,I=I.replace(".",""),ee=new z(b),W=ee.pow(I.length-fe),Wt=O,ee.c=x(H(g(W.c),W.e,"0"),10,v,E),ee.e=ee.c.length),Q=x(I,b,v,C?(A=Yt,E):(A=E,Yt)),N=O=Q.length;Q[--O]==0;Q.pop());if(!Q[0])return A.charAt(0);if(fe<0?--N:(W.c=Q,W.e=N,W.s=_,W=k(W,ee,qe,ge,v),Q=W.c,U=W.r,N=W.e),B=N+qe+1,fe=Q[B],O=v/2,U=U||B<0||Q[B+1]!=null,U=ge<4?(fe!=null||U)&&(ge==0||ge==(W.s<0?3:2)):fe>O||fe==O&&(ge==4||U||ge==6&&Q[B-1]&1||ge==(W.s<0?8:7)),B<1||!Q[0])I=U?H(A.charAt(1),-qe,A.charAt(0)):A.charAt(0);else{if(Q.length=B,U)for(--v;++Q[--B]>v;)Q[B]=0,B||(++N,Q=[1].concat(Q));for(O=Q.length;!Q[--O];);for(fe=0,I="";fe<=O;I+=A.charAt(Q[fe++]));I=H(I,N,A.charAt(0))}return I}}(),k=function(){function E(b,v,_){var C,A,B,N,O=0,U=b.length,W=v%f,Q=v/f|0;for(b=b.slice();U--;)B=b[U]%f,N=b[U]/f|0,C=Q*B+N*W,A=W*B+C%f*f+O,O=(A/_|0)+(C/f|0)+Q*N,b[U]=A%_;return O&&(b=[O].concat(b)),b}function x(b,v,_,C){var A,B;if(_!=C)B=_>C?1:-1;else for(A=B=0;A<_;A++)if(b[A]!=v[A]){B=b[A]>v[A]?1:-1;break}return B}function I(b,v,_,C){for(var A=0;_--;)b[_]-=A,A=b[_]<v[_]?1:0,b[_]=A*C+b[_]-v[_];for(;!b[0]&&b.length>1;b.splice(0,1));}return function(b,v,_,C,A){var B,N,O,U,W,Q,ee,fe,qe,ge,ae,ue,ds,al,cl,$r,Bo,fr=b.s==v.s?1:-1,Vt=b.c,at=v.c;if(!Vt||!Vt[0]||!at||!at[0])return new z(!b.s||!v.s||(Vt?at&&Vt[0]==at[0]:!at)?NaN:Vt&&Vt[0]==0||!at?fr*0:fr/0);for(fe=new z(fr),qe=fe.c=[],N=b.e-v.e,fr=_+N+1,A||(A=a,N=h(b.e/c)-h(v.e/c),fr=fr/c|0),O=0;at[O]==(Vt[O]||0);O++);if(at[O]>(Vt[O]||0)&&N--,fr<0)qe.push(1),U=!0;else{for(al=Vt.length,$r=at.length,O=0,fr+=2,W=i(A/(at[0]+1)),W>1&&(at=E(at,W,A),Vt=E(Vt,W,A),$r=at.length,al=Vt.length),ds=$r,ge=Vt.slice(0,$r),ae=ge.length;ae<$r;ge[ae++]=0);Bo=at.slice(),Bo=[0].concat(Bo),cl=at[0],at[1]>=A/2&&cl++;do{if(W=0,B=x(at,ge,$r,ae),B<0){if(ue=ge[0],$r!=ae&&(ue=ue*A+(ge[1]||0)),W=i(ue/cl),W>1)for(W>=A&&(W=A-1),Q=E(at,W,A),ee=Q.length,ae=ge.length;x(Q,ge,ee,ae)==1;)W--,I(Q,$r<ee?Bo:at,ee,A),ee=Q.length,B=1;else W==0&&(B=W=1),Q=at.slice(),ee=Q.length;if(ee<ae&&(Q=[0].concat(Q)),I(ge,Q,ae,A),ae=ge.length,B==-1)for(;x(at,ge,$r,ae)<1;)W++,I(ge,$r<ae?Bo:at,ae,A),ae=ge.length}else B===0&&(W++,ge=[0]);qe[O++]=W,ge[0]?ge[ae++]=Vt[ds]||0:(ge=[Vt[ds]],ae=1)}while((ds++<al||ge[0]!=null)&&fr--);U=ge[0]!=null,qe[0]||qe.splice(0,1)}if(A==a){for(O=1,fr=qe[0];fr>=10;fr/=10,O++);Kt(fe,_+(fe.e=O+N*c-1)+1,C,U)}else fe.e=N,fe.r=+U;return fe}}();function fs(E,x,I,b){var v,_,C,A,B;if(I==null?I=ye:S(I,0,8),!E.c)return E.toString();if(v=E.c[0],C=E.e,x==null)B=g(E.c),B=b==1||b==2&&(C<=nt||C>=it)?L(B,C):H(B,C,"0");else if(E=Kt(new z(E),x,I),_=E.e,B=g(E.c),A=B.length,b==1||b==2&&(x<=_||_<=nt)){for(;A<x;B+="0",A++);B=L(B,_)}else if(x-=C,B=H(B,_,"0"),_+1>A){if(--x>0)for(B+=".";x--;B+="0");}else if(x+=_-A,x>0)for(_+1==A&&(B+=".");x--;B+="0");return E.s<0&&v?"-"+B:B}function Ha(E,x){for(var I,b=1,v=new z(E[0]);b<E.length;b++)if(I=new z(E[b]),I.s)x.call(v,I)&&(v=I);else{v=I;break}return v}function Ro(E,x,I){for(var b=1,v=x.length;!x[--v];x.pop());for(v=x[0];v>=10;v/=10,b++);return(I=b+I*c-1)>Fe?E.c=E.e=null:I<Ie?E.c=[E.e=0]:(E.e=I,E.c=x),E}ie=function(){var E=/^(-?)0([xbo])(?=\w[\w.]*$)/i,x=/^([^.]+)\.$/,I=/^\.([^.]+)$/,b=/^-?(Infinity|NaN)$/,v=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(_,C,A,B){var N,O=A?C:C.replace(v,"");if(b.test(O))_.s=isNaN(O)?null:O<0?-1:1;else{if(!A&&(O=O.replace(E,function(U,W,Q){return N=(Q=Q.toLowerCase())=="x"?16:Q=="b"?2:8,!B||B==N?W:U}),B&&(N=B,O=O.replace(x,"$1").replace(I,"0.$1")),C!=O))return new z(O,N);if(z.DEBUG)throw Error(s+"Not a"+(B?" base "+B:"")+" number: "+C);_.s=null}_.c=_.e=null}}();function Kt(E,x,I,b){var v,_,C,A,B,N,O,U=E.c,W=l;if(U){e:{for(v=1,A=U[0];A>=10;A/=10,v++);if(_=x-v,_<0)_+=c,C=x,B=U[N=0],O=B/W[v-C-1]%10|0;else if(N=n((_+1)/c),N>=U.length)if(b){for(;U.length<=N;U.push(0));B=O=0,v=1,_%=c,C=_-c+1}else break e;else{for(B=A=U[N],v=1;A>=10;A/=10,v++);_%=c,C=_-c+v,O=C<0?0:B/W[v-C-1]%10|0}if(b=b||x<0||U[N+1]!=null||(C<0?B:B%W[v-C-1]),b=I<4?(O||b)&&(I==0||I==(E.s<0?3:2)):O>5||O==5&&(I==4||b||I==6&&(_>0?C>0?B/W[v-C]:0:U[N-1])%10&1||I==(E.s<0?8:7)),x<1||!U[0])return U.length=0,b?(x-=E.e+1,U[0]=W[(c-x%c)%c],E.e=-x||0):U[0]=E.e=0,E;if(_==0?(U.length=N,A=1,N--):(U.length=N+1,A=W[c-_],U[N]=C>0?i(B/W[v-C]%W[C])*A:0),b)for(;;)if(N==0){for(_=1,C=U[0];C>=10;C/=10,_++);for(C=U[0]+=A,A=1;C>=10;C/=10,A++);_!=A&&(E.e++,U[0]==a&&(U[0]=1));break}else{if(U[N]+=A,U[N]!=a)break;U[N--]=0,A=1}for(_=U.length;U[--_]===0;U.pop());}E.e>Fe?E.c=E.e=null:E.e<Ie&&(E.c=[E.e=0])}return E}function Pr(E){var x,I=E.e;return I===null?E.toString():(x=g(E.c),x=I<=nt||I>=it?L(x,I):H(x,I,"0"),E.s<0?"-"+x:x)}return j.absoluteValue=j.abs=function(){var E=new z(this);return E.s<0&&(E.s=1),E},j.comparedTo=function(E,x){return m(this,new z(E,x))},j.decimalPlaces=j.dp=function(E,x){var I,b,v,_=this;if(E!=null)return S(E,0,d),x==null?x=ye:S(x,0,8),Kt(new z(_),E+_.e+1,x);if(!(I=_.c))return null;if(b=((v=I.length-1)-h(this.e/c))*c,v=I[v])for(;v%10==0;v/=10,b--);return b<0&&(b=0),b},j.dividedBy=j.div=function(E,x){return k(this,new z(E,x),le,ye)},j.dividedToIntegerBy=j.idiv=function(E,x){return k(this,new z(E,x),0,1)},j.exponentiatedBy=j.pow=function(E,x){var I,b,v,_,C,A,B,N,O,U=this;if(E=new z(E),E.c&&!E.isInteger())throw Error(s+"Exponent not an integer: "+Pr(E));if(x!=null&&(x=new z(x)),A=E.e>14,!U.c||!U.c[0]||U.c[0]==1&&!U.e&&U.c.length==1||!E.c||!E.c[0])return O=new z(Math.pow(+Pr(U),A?2-R(E):+Pr(E))),x?O.mod(x):O;if(B=E.s<0,x){if(x.c?!x.c[0]:!x.s)return new z(NaN);b=!B&&U.isInteger()&&x.isInteger(),b&&(U=U.mod(x))}else{if(E.e>9&&(U.e>0||U.e<-1||(U.e==0?U.c[0]>1||A&&U.c[1]>=24e7:U.c[0]<8e13||A&&U.c[0]<=9999975e7)))return _=U.s<0&&R(E)?-0:0,U.e>-1&&(_=1/_),new z(B?1/_:_);Wt&&(_=n(Wt/c+2))}for(A?(I=new z(.5),B&&(E.s=1),N=R(E)):(v=Math.abs(+Pr(E)),N=v%2),O=new z(we);;){if(N){if(O=O.times(U),!O.c)break;_?O.c.length>_&&(O.c.length=_):b&&(O=O.mod(x))}if(v){if(v=i(v/2),v===0)break;N=v%2}else if(E=E.times(I),Kt(E,E.e+1,1),E.e>14)N=R(E);else{if(v=+Pr(E),v===0)break;N=v%2}U=U.times(U),_?U.c&&U.c.length>_&&(U.c.length=_):b&&(U=U.mod(x))}return b?O:(B&&(O=we.div(O)),x?O.mod(x):_?Kt(O,Wt,ye,C):O)},j.integerValue=function(E){var x=new z(this);return E==null?E=ye:S(E,0,8),Kt(x,x.e+1,E)},j.isEqualTo=j.eq=function(E,x){return m(this,new z(E,x))===0},j.isFinite=function(){return!!this.c},j.isGreaterThan=j.gt=function(E,x){return m(this,new z(E,x))>0},j.isGreaterThanOrEqualTo=j.gte=function(E,x){return(x=m(this,new z(E,x)))===1||x===0},j.isInteger=function(){return!!this.c&&h(this.e/c)>this.c.length-2},j.isLessThan=j.lt=function(E,x){return m(this,new z(E,x))<0},j.isLessThanOrEqualTo=j.lte=function(E,x){return(x=m(this,new z(E,x)))===-1||x===0},j.isNaN=function(){return!this.s},j.isNegative=function(){return this.s<0},j.isPositive=function(){return this.s>0},j.isZero=function(){return!!this.c&&this.c[0]==0},j.minus=function(E,x){var I,b,v,_,C=this,A=C.s;if(E=new z(E,x),x=E.s,!A||!x)return new z(NaN);if(A!=x)return E.s=-x,C.plus(E);var B=C.e/c,N=E.e/c,O=C.c,U=E.c;if(!B||!N){if(!O||!U)return O?(E.s=-x,E):new z(U?C:NaN);if(!O[0]||!U[0])return U[0]?(E.s=-x,E):new z(O[0]?C:ye==3?-0:0)}if(B=h(B),N=h(N),O=O.slice(),A=B-N){for((_=A<0)?(A=-A,v=O):(N=B,v=U),v.reverse(),x=A;x--;v.push(0));v.reverse()}else for(b=(_=(A=O.length)<(x=U.length))?A:x,A=x=0;x<b;x++)if(O[x]!=U[x]){_=O[x]<U[x];break}if(_&&(v=O,O=U,U=v,E.s=-E.s),x=(b=U.length)-(I=O.length),x>0)for(;x--;O[I++]=0);for(x=a-1;b>A;){if(O[--b]<U[b]){for(I=b;I&&!O[--I];O[I]=x);--O[I],O[b]+=a}O[b]-=U[b]}for(;O[0]==0;O.splice(0,1),--N);return O[0]?Ro(E,O,N):(E.s=ye==3?-1:1,E.c=[E.e=0],E)},j.modulo=j.mod=function(E,x){var I,b,v=this;return E=new z(E,x),!v.c||!E.s||E.c&&!E.c[0]?new z(NaN):!E.c||v.c&&!v.c[0]?new z(v):(tr==9?(b=E.s,E.s=1,I=k(v,E,0,3),E.s=b,I.s*=b):I=k(v,E,0,tr),E=v.minus(I.times(E)),!E.c[0]&&tr==1&&(E.s=v.s),E)},j.multipliedBy=j.times=function(E,x){var I,b,v,_,C,A,B,N,O,U,W,Q,ee,fe,qe,ge=this,ae=ge.c,ue=(E=new z(E,x)).c;if(!ae||!ue||!ae[0]||!ue[0])return!ge.s||!E.s||ae&&!ae[0]&&!ue||ue&&!ue[0]&&!ae?E.c=E.e=E.s=null:(E.s*=ge.s,!ae||!ue?E.c=E.e=null:(E.c=[0],E.e=0)),E;for(b=h(ge.e/c)+h(E.e/c),E.s*=ge.s,B=ae.length,U=ue.length,B<U&&(ee=ae,ae=ue,ue=ee,v=B,B=U,U=v),v=B+U,ee=[];v--;ee.push(0));for(fe=a,qe=f,v=U;--v>=0;){for(I=0,W=ue[v]%qe,Q=ue[v]/qe|0,C=B,_=v+C;_>v;)N=ae[--C]%qe,O=ae[C]/qe|0,A=Q*N+O*W,N=W*N+A%qe*qe+ee[_]+I,I=(N/fe|0)+(A/qe|0)+Q*O,ee[_--]=N%fe;ee[_]=I}return I?++b:ee.splice(0,1),Ro(E,ee,b)},j.negated=function(){var E=new z(this);return E.s=-E.s||null,E},j.plus=function(E,x){var I,b=this,v=b.s;if(E=new z(E,x),x=E.s,!v||!x)return new z(NaN);if(v!=x)return E.s=-x,b.minus(E);var _=b.e/c,C=E.e/c,A=b.c,B=E.c;if(!_||!C){if(!A||!B)return new z(v/0);if(!A[0]||!B[0])return B[0]?E:new z(A[0]?b:v*0)}if(_=h(_),C=h(C),A=A.slice(),v=_-C){for(v>0?(C=_,I=B):(v=-v,I=A),I.reverse();v--;I.push(0));I.reverse()}for(v=A.length,x=B.length,v-x<0&&(I=B,B=A,A=I,x=v),v=0;x;)v=(A[--x]=A[x]+B[x]+v)/a|0,A[x]=a===A[x]?0:A[x]%a;return v&&(A=[v].concat(A),++C),Ro(E,A,C)},j.precision=j.sd=function(E,x){var I,b,v,_=this;if(E!=null&&E!==!!E)return S(E,1,d),x==null?x=ye:S(x,0,8),Kt(new z(_),E,x);if(!(I=_.c))return null;if(v=I.length-1,b=v*c+1,v=I[v]){for(;v%10==0;v/=10,b--);for(v=I[0];v>=10;v/=10,b++);}return E&&_.e+1>b&&(b=_.e+1),b},j.shiftedBy=function(E){return S(E,-u,u),this.times("1e"+E)},j.squareRoot=j.sqrt=function(){var E,x,I,b,v,_=this,C=_.c,A=_.s,B=_.e,N=le+4,O=new z("0.5");if(A!==1||!C||!C[0])return new z(!A||A<0&&(!C||C[0])?NaN:C?_:1/0);if(A=Math.sqrt(+Pr(_)),A==0||A==1/0?(x=g(C),(x.length+B)%2==0&&(x+="0"),A=Math.sqrt(+x),B=h((B+1)/2)-(B<0||B%2),A==1/0?x="5e"+B:(x=A.toExponential(),x=x.slice(0,x.indexOf("e")+1)+B),I=new z(x)):I=new z(A+""),I.c[0]){for(B=I.e,A=B+N,A<3&&(A=0);;)if(v=I,I=O.times(v.plus(k(_,v,N,1))),g(v.c).slice(0,A)===(x=g(I.c)).slice(0,A))if(I.e<B&&--A,x=x.slice(A-3,A+1),x=="9999"||!b&&x=="4999"){if(!b&&(Kt(v,v.e+le+2,0),v.times(v).eq(_))){I=v;break}N+=4,A+=4,b=1}else{(!+x||!+x.slice(1)&&x.charAt(0)=="5")&&(Kt(I,I.e+le+2,1),E=!I.times(I).eq(_));break}}return Kt(I,I.e+le+1,ye,E)},j.toExponential=function(E,x){return E!=null&&(S(E,0,d),E++),fs(this,E,x,1)},j.toFixed=function(E,x){return E!=null&&(S(E,0,d),E=E+this.e+1),fs(this,E,x)},j.toFormat=function(E,x,I){var b,v=this;if(I==null)E!=null&&x&&typeof x=="object"?(I=x,x=null):E&&typeof E=="object"?(I=E,E=x=null):I=hn;else if(typeof I!="object")throw Error(s+"Argument not an object: "+I);if(b=v.toFixed(E,x),v.c){var _,C=b.split("."),A=+I.groupSize,B=+I.secondaryGroupSize,N=I.groupSeparator||"",O=C[0],U=C[1],W=v.s<0,Q=W?O.slice(1):O,ee=Q.length;if(B&&(_=A,A=B,B=_,ee-=_),A>0&&ee>0){for(_=ee%A||A,O=Q.substr(0,_);_<ee;_+=A)O+=N+Q.substr(_,A);B>0&&(O+=N+Q.slice(_)),W&&(O="-"+O)}b=U?O+(I.decimalSeparator||"")+((B=+I.fractionGroupSize)?U.replace(new RegExp("\\d{"+B+"}\\B","g"),"$&"+(I.fractionGroupSeparator||"")):U):O}return(I.prefix||"")+b+(I.suffix||"")},j.toFraction=function(E){var x,I,b,v,_,C,A,B,N,O,U,W,Q=this,ee=Q.c;if(E!=null&&(A=new z(E),!A.isInteger()&&(A.c||A.s!==1)||A.lt(we)))throw Error(s+"Argument "+(A.isInteger()?"out of range: ":"not an integer: ")+Pr(A));if(!ee)return new z(Q);for(x=new z(we),N=I=new z(we),b=B=new z(we),W=g(ee),_=x.e=W.length-Q.e-1,x.c[0]=l[(C=_%c)<0?c+C:C],E=!E||A.comparedTo(x)>0?_>0?x:N:A,C=Fe,Fe=1/0,A=new z(W),B.c[0]=0;O=k(A,x,0,1),v=I.plus(O.times(b)),v.comparedTo(E)!=1;)I=b,b=v,N=B.plus(O.times(v=N)),B=v,x=A.minus(O.times(v=x)),A=v;return v=k(E.minus(I),b,0,1),B=B.plus(v.times(N)),I=I.plus(v.times(b)),B.s=N.s=Q.s,_=_*2,U=k(N,b,_,ye).minus(Q).abs().comparedTo(k(B,I,_,ye).minus(Q).abs())<1?[N,b]:[B,I],Fe=C,U},j.toNumber=function(){return+Pr(this)},j.toPrecision=function(E,x){return E!=null&&S(E,1,d),fs(this,E,x,2)},j.toString=function(E){var x,I=this,b=I.s,v=I.e;return v===null?b?(x="Infinity",b<0&&(x="-"+x)):x="NaN":(E==null?x=v<=nt||v>=it?L(g(I.c),v):H(g(I.c),v,"0"):E===10&&pn?(I=Kt(new z(I),le+v+1,ye),x=H(g(I.c),I.e,"0")):(S(E,2,Yt.length,"Base"),x=J(H(g(I.c),v,"0"),10,E,b,!0)),b<0&&I.c[0]&&(x="-"+x)),x},j.valueOf=j.toJSON=function(){return Pr(this)},j._isBigNumber=!0,q!=null&&z.set(q),z}function h(q){var k=q|0;return q>0||q===k?k:k-1}function g(q){for(var k,J,ie=1,j=q.length,we=q[0]+"";ie<j;){for(k=q[ie++]+"",J=c-k.length;J--;k="0"+k);we+=k}for(j=we.length;we.charCodeAt(--j)===48;);return we.slice(0,j+1||1)}function m(q,k){var J,ie,j=q.c,we=k.c,le=q.s,ye=k.s,nt=q.e,it=k.e;if(!le||!ye)return null;if(J=j&&!j[0],ie=we&&!we[0],J||ie)return J?ie?0:-ye:le;if(le!=ye)return le;if(J=le<0,ie=nt==it,!j||!we)return ie?0:!j^J?1:-1;if(!ie)return nt>it^J?1:-1;for(ye=(nt=j.length)<(it=we.length)?nt:it,le=0;le<ye;le++)if(j[le]!=we[le])return j[le]>we[le]^J?1:-1;return nt==it?0:nt>it^J?1:-1}function S(q,k,J,ie){if(q<k||q>J||q!==i(q))throw Error(s+(ie||"Argument")+(typeof q=="number"?q<k||q>J?" out of range: ":" not an integer: ":" not a primitive number: ")+String(q))}function R(q){var k=q.c.length-1;return h(q.e/c)==k&&q.c[k]%2!=0}function L(q,k){return(q.length>1?q.charAt(0)+"."+q.slice(1):q)+(k<0?"e":"e+")+k}function H(q,k,J){var ie,j;if(k<0){for(j=J+".";++k;j+=J);q=j+q}else if(ie=q.length,++k>ie){for(j=J,k-=ie;--k;j+=J);q+=j}else k<ie&&(q=q.slice(0,k)+"."+q.slice(k));return q}e=p(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof ku!="undefined"&&ku.exports?ku.exports=e:(t||(t=typeof self!="undefined"&&self?self:window),t.BigNumber=e)})(_S)});var CS=w((xS,AS)=>{"use strict";var xk=Math.exp;xS=AS.exports=function(e){if(typeof e!="number")throw new Error("must provide a timespan to the moving average constructor");if(e<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let r,n=0,i=0,s=0,o,a={};function c(u,l){return 1-xk(-(u-l)/e)}return a.push=function(l,f){if(o){let d=c(l,o),p=f-r,h=d*p;r=d*f+(1-d)*r,n=(1-d)*(n+p*h),i=Math.sqrt(n),s=r+d*p}else r=f;o=l},a.movingAverage=function(){return r},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return s},a}});var BS=w((nV,RS)=>{"use strict";var{EventEmitter:Ak}=Qt(),{BigNumber:qu}=SS(),IS=CS(),Ck=va(),TS=class extends Ak{constructor(e,r){super();this._options=r,this._queue=[],this._stats={dataReceived:qu(0),dataSent:qu(0)},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this);let n=this._options.movingAverageIntervals;for(let i=0;i<e.length;i++){let s=e[i];this._stats[s]=qu(0),this._movingAverages[s]={};for(let o=0;o<n.length;o++){let a=n[o];(this._movingAverages[s][a]=IS(a)).push(this._frequencyLastTime,0)}}}start(){this._queue.length&&this._resetComputeTimeout()}stop(){this._timeout&&(this._timeout.clear(),this._timeout=null)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}toJSON(){let e=this.snapshot,r=this.movingAverages,n={dataReceived:e.dataReceived.toString(),dataSent:e.dataSent.toString(),movingAverages:{}},i=Object.keys(r);for(let s of i){n.movingAverages[s]={};for(let o of Object.keys(r[s]))n.movingAverages[s][o]=r[s][o].movingAverage()}return n}push(e,r){this._queue.push([e,r,Date.now()]),this._resetComputeTimeout()}_resetComputeTimeout(){this._timeout=Ck(this._update,this._nextTimeout())}_nextTimeout(){let e=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-e),0)}_update(){if(this._timeout=null,this._queue.length){let e;for(e of this._queue)this._applyOp(e);this._queue=[],this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let r=e-this._frequencyLastTime;Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,r,e)}),this._frequencyLastTime=e}_updateFrequencyFor(e,r,n){let i=this._frequencyAccumulators[e]||0;this._frequencyAccumulators[e]=0;let o=i/(r||1)*1e3,a=this._movingAverages[e];a||(a=this._movingAverages[e]={});let c=this._options.movingAverageIntervals;for(let u=0;u<c.length;u++){let l=c[u],f=a[l];f||(f=a[l]=IS(l)),f.push(n,o)}}_applyOp(e){let r=e[0],n=e[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);let i;Object.prototype.hasOwnProperty.call(this._stats,r)?i=this._stats[r]:i=this._stats[r]=qu(0),this._stats[r]=i.plus(n),this._frequencyAccumulators[r]||(this._frequencyAccumulators[r]=0),this._frequencyAccumulators[r]+=n}};RS.exports=TS});var OS=w((iV,NS)=>{"use strict";var Ik=Hs(),{pipe:Tk}=ir(),{tap:PS}=Lu(),Rk=wS(),{METRICS:Bk}=cu(),xh=BS(),Ah=["dataReceived","dataSent"],Pk={in:"dataReceived",out:"dataSent"},Uu=class{constructor(e){this._options=Ik(Bk,e),this._globalStats=new xh(Ah,this._options),this._peerStats=new Map,this._protocolStats=new Map,this._oldPeers=Rk(this._options.maxOldPeersRetention),this._running=!1,this._onMessage=this._onMessage.bind(this),this._systems=new Map}start(){this._running=!0}stop(){this._running=!1,this._globalStats.stop();for(let e of this._peerStats.values())e.stop();for(let e of this._protocolStats.values())e.stop()}get global(){return this._globalStats}get peers(){return Array.from(this._peerStats.keys())}getComponentMetrics(){return this._systems}updateComponentMetric({system:e="libp2p",component:r,metric:n,value:i}){this._systems.has(e)||this._systems.set(e,new Map);let s=this._systems.get(e);s.has(r)||s.set(r,new Map),s.get(r).set(n,i)}forPeer(e){let r=e.toB58String();return this._peerStats.get(r)||this._oldPeers.get(r)}get protocols(){return Array.from(this._protocolStats.keys())}forProtocol(e){return this._protocolStats.get(e)}onPeerDisconnected(e){let r=e.toB58String(),n=this._peerStats.get(r);n&&(n.stop(),this._peerStats.delete(r),this._oldPeers.set(r,n))}_onMessage({remotePeer:e,protocol:r,direction:n,dataLength:i}){if(!this._running)return;let s=Pk[n],o=this.forPeer(e);if(o||(o=new xh(Ah,this._options),this._peerStats.set(e.toB58String(),o)),o.push(s,i),this._globalStats.push(s,i),r){let a=this.forProtocol(r);a||(a=new xh(Ah,this._options),this._protocolStats.set(r,a)),a.push(s,i)}}updatePlaceholder(e,r){if(!this._running)return;let n=this.forPeer(e),i=r.toB58String(),s=this.forPeer(r),o=n;s&&(o=Uu.mergeStats(s,o),this._oldPeers.delete(i)),this._peerStats.delete(e.toB58String()),this._peerStats.set(i,o),o.start()}trackStream({stream:e,remotePeer:r,protocol:n}){let i=this,s=e.source;e.source=PS(a=>i._onMessage({remotePeer:r,protocol:n,direction:"in",dataLength:a.length}))(s);let o=e.sink;return e.sink=a=>Tk(a,PS(c=>i._onMessage({remotePeer:r,protocol:n,direction:"out",dataLength:c.length})),o),e}static mergeStats(e,r){return e.stop(),r.stop(),e._queue=[...e._queue,...r._queue],e}};NS.exports=Uu});var Mu=w((sV,qS)=>{"use strict";var DS=Ji(),LS=so(),{pipe:Nk}=ir(),Ok=de(),{fromString:Dk}=(It(),Nt),Lk=dd(),{source:kk}=bu(),kS=Dk(`
45
- `);function Ch(t){return LS.encode.single(new DS([t,kS]))}function qk(t,e){t.push(Ch(e))}async function Uk(t,e){t.push(e.reduce((r,n)=>r.append(Ch(n)),new DS))}async function Mk(t,e){let r=1,n={[Symbol.asyncIterator](){return this},next:()=>t.next(r)},i=n;e&&e.signal&&(i=kk(n,e.signal));let s=a=>{r=a},o=await Nk(i,LS.decode({onLength:s}),Lk);if(o.get(o.length-1)!==kS[0])throw Ok(new Error("missing newline"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.shallowSlice(0,-1)}qS.exports={encode:Ch,write:qk,writeAll:Uk,read:Mk}});var FS=w((oV,MS)=>{"use strict";var US=Te(),Fk=de(),go=Mu(),Kk=oo(),mo=Object.assign(US("mss:select"),{error:US("mss:select:error")});MS.exports=async function(e,r,n,i){r=Array.isArray(r)?[...r]:[r];let{reader:s,writer:o,rest:a,stream:c}=Kk(e),u=r.shift();if(!u)throw new Error("At least one protocol must be specified");n?(mo('select: write ["%s", "%s"]',n,u),go.writeAll(o,[n,u])):(mo('select: write "%s"',u),go.write(o,u));let l=(await go.read(s,i)).toString();if(mo('select: read "%s"',l),l===n&&(l=(await go.read(s,i)).toString(),mo('select: read "%s"',l)),l===u)return a(),{stream:c,protocol:u};for(let f of r){mo('select: write "%s"',f),go.write(o,f);let d=(await go.read(s,i)).toString();if(mo('select: read "%s" for "%s"',d,f),d===f)return a(),{stream:c,protocol:f}}throw a(),Fk(new Error("protocol selection failed"),"ERR_UNSUPPORTED_PROTOCOL")}});var Ih=w(KS=>{"use strict";KS.PROTOCOL_ID="/multistream/1.0.0"});var $S=w((cV,jS)=>{"use strict";var VS=Te(),Vk=Ji(),vo=Mu(),jk=oo(),{PROTOCOL_ID:Th}=Ih(),ka=Object.assign(VS("mss:handle"),{error:VS("mss:handle:error")});jS.exports=async function(e,r,n){r=Array.isArray(r)?r:[r];let{writer:i,reader:s,rest:o,stream:a}=jk(e);for(;;){let c=(await vo.read(s,n)).toString();if(ka('read "%s"',c),c===Th){ka('respond with "%s" for "%s"',Th,c),vo.write(i,Th);continue}if(r.includes(c))return vo.write(i,c),ka('respond with "%s" for "%s"',c,c),o(),{stream:a,protocol:c};if(c==="ls"){vo.write(i,new Vk(r.map(u=>vo.encode(u)))),ka('respond with "%s" for %s',r,c);continue}vo.write(i,"na"),ka('respond with "na" for "%s"',c)}}});var WS=w((uV,GS)=>{"use strict";var $k=th(),HS=Te(),zS=Mu(),Hk=oo(),zk=so(),{pipe:Gk}=ir(),Wk=Object.assign(HS("mss:ls"),{error:HS("mss:ls:error")});GS.exports=async function(e,r){let{reader:n,writer:i,rest:s,stream:o}=Hk(e);Wk('write "ls"'),zS.write(i,"ls"),s();let a=await zS.read(n,r),c=$k([a]),u=[];return await Gk(c,zk.decode(),async f=>{for await(let d of f)u.push(d.shallowSlice(0,-1).toString())}),{stream:o,protocols:u}}});var ZS=w(Fu=>{"use strict";var YS=FS(),Yk=$S(),Qk=WS(),{PROTOCOL_ID:Rh}=Ih();Fu.PROTOCOL_ID=Rh;var Bh=class{constructor(e){this._stream=e,this._shaken=!1}async _handshake(e){if(this._shaken)return;let{stream:r}=await YS(this._stream,Rh,void 0,e);this._stream=r,this._shaken=!0}},QS=class extends Bh{select(e,r){return YS(this._stream,e,this._shaken?void 0:Rh,r)}async ls(e){await this._handshake(e);let r=await Qk(this._stream,e),{stream:n,protocols:i}=r;return this._stream=n,i}};Fu.Dialer=QS;var XS=class extends Bh{handle(e,r){return Yk(this._stream,e,r)}};Fu.Listener=XS});var ex=w((fV,JS)=>{"use strict";var Xk={OPEN:"open",CLOSING:"closing",CLOSED:"closed"};JS.exports=Xk});var ox=w((dV,sx)=>{"use strict";var tx=Rt(),{Multiaddr:Zk}=qt(),or=de(),{OPEN:Jk,CLOSING:rx,CLOSED:Ph}=ex(),nx=Symbol.for("@libp2p/interface-connection/connection"),ix=class{constructor({localAddr:e,remoteAddr:r,localPeer:n,remotePeer:i,newStream:s,close:o,getStreams:a,stat:c}){e6(e,n,i,s,o,a,c),this.id=parseInt(String(Math.random()*1e9)).toString(36)+Date.now(),this.localAddr=e,this.remoteAddr=r,this.localPeer=n,this.remotePeer=i,this._stat={...c,status:Jk},this._newStream=s,this._close=o,this._getStreams=a,this.registry=new Map,this.tags=[]}get[Symbol.toStringTag](){return"Connection"}get[nx](){return!0}static isConnection(e){return Boolean(e&&e[nx])}get stat(){return this._stat}get streams(){return this._getStreams()}async newStream(e){if(this.stat.status===rx)throw or(new Error("the connection is being closed"),"ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===Ph)throw or(new Error("the connection is closed"),"ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let{stream:r,protocol:n}=await this._newStream(e);return this.addStream(r,{protocol:n}),{stream:r,protocol:n}}addStream(e,{protocol:r,metadata:n={}}){this.registry.set(e.id,{protocol:r,...n})}removeStream(e){this.registry.delete(e)}async close(){if(this.stat.status!==Ph){if(this._closing)return this._closing;this.stat.status=rx,this._closing=await this._close(),this._stat.timeline.close=Date.now(),this.stat.status=Ph}}};sx.exports=ix;function e6(t,e,r,n,i,s,o){if(t&&!Zk.isMultiaddr(t))throw or(new Error("localAddr must be an instance of multiaddr"),"ERR_INVALID_PARAMETERS");if(!tx.isPeerId(e))throw or(new Error("localPeer must be an instance of peer-id"),"ERR_INVALID_PARAMETERS");if(!tx.isPeerId(r))throw or(new Error("remotePeer must be an instance of peer-id"),"ERR_INVALID_PARAMETERS");if(typeof n!="function")throw or(new Error("new stream must be a function"),"ERR_INVALID_PARAMETERS");if(typeof i!="function")throw or(new Error("close must be a function"),"ERR_INVALID_PARAMETERS");if(typeof s!="function")throw or(new Error("getStreams must be a function"),"ERR_INVALID_PARAMETERS");if(!o)throw or(new Error("connection metadata object must be provided"),"ERR_INVALID_PARAMETERS");if(o.direction!=="inbound"&&o.direction!=="outbound")throw or(new Error('direction must be "inbound" or "outbound"'),"ERR_INVALID_PARAMETERS");if(!o.timeline)throw or(new Error("connection timeline object must be provided in the stat object"),"ERR_INVALID_PARAMETERS");if(!o.timeline.open)throw or(new Error("connection open timestamp must be provided"),"ERR_INVALID_PARAMETERS");if(!o.timeline.upgraded)throw or(new Error("connection upgraded timestamp must be provided"),"ERR_INVALID_PARAMETERS")}});var cx=w(ax=>{"use strict";ax.Connection=ox()});var lx=w((pV,ux)=>{"use strict";function t6(t){if(Array.isArray(t)){for(var e=0,r=Array(t.length);e<t.length;e++)r[e]=t[e];return r}else return Array.from(t)}ux.exports=function(e){var r=void 0,n=void 0;function i(a){if(!(a instanceof Object))throw new Error('Target "'+a+'" is not an object');n=a}function s(a){Object.keys(a).forEach(function(c){var u=a[c];if(typeof u!="function")throw new Error('Trap "'+c+": "+u+'" is not a function');if(!Reflect[c])throw new Error('Trap "'+c+": "+u+'" is not a valid trap')}),r=a}i(function(){}),e&&i(e),s(Reflect);var o=new Proxy({},{get:function(c,u){return function(){for(var l=arguments.length,f=Array(l),d=0;d<l;d++)f[d]=arguments[d];return r[u].apply(null,[n].concat(t6(f.slice(1))))}}});return{setTarget:i,setHandler:s,getTarget:function(){return n},getHandler:function(){return r},proxy:new Proxy(n,o)}}});var yx=w((yV,px)=>{"use strict";var fx=Te(),vt=Object.assign(fx("libp2p:upgrader"),{error:fx("libp2p:upgrader:err")}),ar=de(),bo=ZS(),{Connection:r6}=cx(),n6=Rt(),{pipe:i6}=ir(),dx=lx(),{codes:cr}=je(),hx=class{constructor({localPeer:e,metrics:r,connectionGater:n,cryptos:i=new Map,muxers:s=new Map,onConnectionEnd:o=()=>{},onConnection:a=()=>{}}){this.connectionGater=n,this.localPeer=e,this.metrics=r,this.cryptos=i,this.muxers=s,this.protector=null,this.protocols=new Map,this.onConnection=a,this.onConnectionEnd=o}async upgradeInbound(e){let r,n,i,s,o,a,c;if(await this.connectionGater.denyInboundConnection(e))throw ar(new Error("The multiaddr connection is blocked by gater.acceptConnection"),cr.ERR_CONNECTION_INTERCEPTED);if(this.metrics){({setTarget:a,proxy:c}=dx());let l=(Math.random()*1e9).toString(36)+Date.now();a({toB58String:()=>l}),e=this.metrics.trackStream({stream:e,remotePeer:c})}vt("Starting the inbound connection upgrade");let u=e;this.protector&&(u=await this.protector.protect(e));try{if({conn:r,remotePeer:n,protocol:o}=await this._encryptInbound(this.localPeer,u,this.cryptos),await this.connectionGater.denyInboundEncryptedConnection(n,r))throw ar(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),cr.ERR_CONNECTION_INTERCEPTED);this.muxers.size?{stream:i,Muxer:s}=await this._multiplexInbound(r,this.muxers):i=r}catch(l){throw vt.error("Failed to upgrade inbound connection",l),await e.close(l),l}if(await this.connectionGater.denyInboundUpgradedConnection(n,r))throw ar(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),cr.ERR_CONNECTION_INTERCEPTED);return this.metrics&&(this.metrics.updatePlaceholder(c,n),a(n)),vt("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:o,direction:"inbound",maConn:e,upgradedConn:i,Muxer:s,remotePeer:n})}async upgradeOutbound(e){let r=e.remoteAddr.getPeerId();if(!r)throw ar(new Error("outbound connection must have a peer id"),cr.ERR_INVALID_MULTIADDR);let n=n6.createFromB58String(r);if(await this.connectionGater.denyOutboundConnection(n,e))throw ar(new Error("The multiaddr connection is blocked by connectionGater.denyOutboundConnection"),cr.ERR_CONNECTION_INTERCEPTED);let i,s,o,a,c,u,l;if(this.metrics){({setTarget:u,proxy:l}=dx());let d=(Math.random()*1e9).toString(36)+Date.now();u({toB58String:()=>d}),e=this.metrics.trackStream({stream:e,remotePeer:l})}vt("Starting the outbound connection upgrade");let f=e;this.protector&&(f=await this.protector.protect(e));try{if({conn:i,remotePeer:s,protocol:a}=await this._encryptOutbound(this.localPeer,f,n,this.cryptos),await this.connectionGater.denyOutboundEncryptedConnection(s,i))throw ar(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),cr.ERR_CONNECTION_INTERCEPTED);this.muxers.size?{stream:o,Muxer:c}=await this._multiplexOutbound(i,this.muxers):o=i}catch(d){throw vt.error("Failed to upgrade outbound connection",d),await e.close(d),d}if(await this.connectionGater.denyOutboundUpgradedConnection(s,i))throw ar(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),cr.ERR_CONNECTION_INTERCEPTED);return this.metrics&&(this.metrics.updatePlaceholder(l,s),u(s)),vt("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:a,direction:"outbound",maConn:e,upgradedConn:o,Muxer:c,remotePeer:s})}_createConnection({cryptoProtocol:e,direction:r,maConn:n,upgradedConn:i,Muxer:s,remotePeer:o}){let a,c,u;s&&(a=new s({onStream:async d=>{if(!u)return;let p=new bo.Listener(d);try{let{stream:h,protocol:g}=await p.handle(Array.from(this.protocols.keys()));vt("%s: incoming stream opened on %s",r,g),this.metrics&&this.metrics.trackStream({stream:h,remotePeer:o,protocol:g}),u.addStream(d,{protocol:g}),this._onStream({connection:u,stream:{...d,...h},protocol:g})}catch(h){vt.error(h)}},onStreamEnd:d=>{u.removeStream(d.id)}}),c=async d=>{vt("%s: starting new stream on %s",r,d);let p=a.newStream(),h=new bo.Dialer(p);try{let{stream:g,protocol:m}=await h.select(d);return this.metrics&&this.metrics.trackStream({stream:g,remotePeer:o,protocol:m}),{stream:{...p,...g},protocol:m}}catch(g){throw vt.error("could not create new stream",g),ar(g,cr.ERR_UNSUPPORTED_PROTOCOL)}},i6(i,a,i).catch(vt.error));let l=n.timeline;n.timeline=new Proxy(l,{set:(...d)=>(u&&d[1]==="close"&&d[2]&&!l.close&&(async()=>{try{u.stat.status==="open"&&await u.close()}catch(p){vt.error(p)}finally{this.onConnectionEnd(u)}})().catch(p=>{vt.error(p)}),Reflect.set(...d))}),n.timeline.upgraded=Date.now();let f=()=>{throw ar(new Error("connection is not multiplexed"),cr.ERR_CONNECTION_NOT_MULTIPLEXED)};return u=new r6({localAddr:n.localAddr,remoteAddr:n.remoteAddr,localPeer:this.localPeer,remotePeer:o,stat:{direction:r,timeline:n.timeline,multiplexer:s&&s.multicodec,encryption:e},newStream:c||f,getStreams:()=>a?a.streams:f(),close:async()=>{await n.close(),a&&a.streams.map(d=>d.abort())}}),this.onConnection(u),u}_onStream({connection:e,stream:r,protocol:n}){this.protocols.get(n)({connection:e,stream:r,protocol:n})}async _encryptInbound(e,r,n){let i=new bo.Listener(r),s=Array.from(n.keys());vt("handling inbound crypto protocol selection",s);try{let{stream:o,protocol:a}=await i.handle(s),c=n.get(a);if(vt("encrypting inbound connection..."),!c)throw new Error(`no crypto module found for ${a}`);return{...await c.secureInbound(e,o),protocol:a}}catch(o){throw ar(o,cr.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r,n,i){let s=new bo.Dialer(r),o=Array.from(i.keys());vt("selecting outbound crypto protocol",o);try{let{stream:a,protocol:c}=await s.select(o),u=i.get(c);if(vt("encrypting outbound connection to %j",n),!u)throw new Error(`no crypto module found for ${c}`);return{...await u.secureOutbound(e,a,n),protocol:c}}catch(a){throw ar(a,cr.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=new bo.Dialer(e),i=Array.from(r.keys());vt("outbound selecting muxer %s",i);try{let{stream:s,protocol:o}=await n.select(i);vt("%s selected as muxer protocol",o);let a=r.get(o);return{stream:s,Muxer:a}}catch(s){throw ar(s,cr.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=new bo.Listener(e),i=Array.from(r.keys());vt("inbound handling muxers %s",i);try{let{stream:s,protocol:o}=await n.handle(i),a=r.get(o);return{stream:s,Muxer:a}}catch(s){throw ar(s,cr.ERR_MUXER_UNAVAILABLE)}}};px.exports=hx});var mx=w((gV,gx)=>{"use strict";var s6=async function*(t,e){for await(let r of t)await e(r),yield r};gx.exports=s6});var xx=w((mV,Sx)=>{"use strict";var vx=Te(),os=de(),{Multiaddr:bx}=qt(),Ku=Rt(),{codes:Kr}=je(),Ex=pu(),wx=du(),{pipe:o6}=ir(),a6=Mi(),c6=Fi(),u6=id(),l6=mx(),ke=Object.assign(vx("libp2p:peer-store:address-book"),{error:vx("libp2p:peer-store:address-book:err")}),Vu="change:multiaddrs",_x=class{constructor(e,r,n){this._emit=e,this._store=r,this._addressFilter=n}async consumePeerRecord(e){ke("consumePeerRecord await write lock");let r=await this._store.lock.writeLock();ke("consumePeerRecord got write lock");let n,i;try{let s;try{s=Ex.createFromProtobuf(e.payload)}catch(a){return ke.error("invalid peer record received"),!1}n=s.peerId;let o=s.multiaddrs;if(!n.equals(e.peerId))return ke("signing key does not match PeerId in the PeerRecord"),!1;if(!o||!o.length)return!1;if(await this._store.has(n)){let a=await this._store.load(n);if(a.peerRecordEnvelope){let c=await wx.createFromProtobuf(a.peerRecordEnvelope);if(Ex.createFromProtobuf(c.payload).seqNumber>=s.seqNumber)return!1}}i=await this._store.patchOrCreate(n,{addresses:await Nh(n,o,this._addressFilter,!0),peerRecordEnvelope:e.marshal()}),ke(`stored provided peer record for ${s.peerId.toB58String()}`)}finally{ke("consumePeerRecord release write lock"),r()}return this._emit(Vu,{peerId:n,multiaddrs:i.addresses.map(({multiaddr:s})=>s)}),!0}async getRawEnvelope(e){ke("getRawEnvelope await read lock");let r=await this._store.lock.readLock();ke("getRawEnvelope got read lock");try{return(await this._store.load(e)).peerRecordEnvelope}catch(n){if(n.code!==Kr.ERR_NOT_FOUND)throw n}finally{ke("getRawEnvelope release read lock"),r()}}async getPeerRecord(e){let r=await this.getRawEnvelope(e);if(!!r)return wx.createFromProtobuf(r)}async get(e){if(!Ku.isPeerId(e))throw ke.error("peerId must be an instance of peer-id to store data"),os(new Error("peerId must be an instance of peer-id"),Kr.ERR_INVALID_PARAMETERS);ke("get wait for read lock");let r=await this._store.lock.readLock();ke("get got read lock");try{return(await this._store.load(e)).addresses}catch(n){if(n.code!==Kr.ERR_NOT_FOUND)throw n}finally{ke("get release read lock"),r()}return[]}async set(e,r){if(!Ku.isPeerId(e))throw ke.error("peerId must be an instance of peer-id to store data"),os(new Error("peerId must be an instance of peer-id"),Kr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ke.error("multiaddrs must be an array of Multiaddrs"),os(new Error("multiaddrs must be an array of Multiaddrs"),Kr.ERR_INVALID_PARAMETERS);ke("set await write lock");let n=await this._store.lock.writeLock();ke("set got write lock");let i=!1,s;try{let o=await Nh(e,r,this._addressFilter);if(!o.length)return;try{let a=await this._store.load(e);if(i=!0,new Set([...o.map(({multiaddr:c})=>c.toString()),...a.addresses.map(({multiaddr:c})=>c.toString())]).size===a.addresses.length&&o.length===a.addresses.length)return}catch(a){if(a.code!==Kr.ERR_NOT_FOUND)throw a}s=await this._store.patchOrCreate(e,{addresses:o}),ke(`set multiaddrs for ${e.toB58String()}`)}finally{ke("set release write lock"),n()}this._emit(Vu,{peerId:e,multiaddrs:s.addresses.map(o=>o.multiaddr)}),i||this._emit("peer",e)}async add(e,r){if(!Ku.isPeerId(e))throw ke.error("peerId must be an instance of peer-id to store data"),os(new Error("peerId must be an instance of peer-id"),Kr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ke.error("multiaddrs must be an array of Multiaddrs"),os(new Error("multiaddrs must be an array of Multiaddrs"),Kr.ERR_INVALID_PARAMETERS);ke("add await write lock");let n=await this._store.lock.writeLock();ke("add got write lock");let i,s;try{let o=await Nh(e,r,this._addressFilter);if(!o.length)return;try{let a=await this._store.load(e);if(i=!0,new Set([...o.map(({multiaddr:c})=>c.toString()),...a.addresses.map(({multiaddr:c})=>c.toString())]).size===a.addresses.length)return}catch(a){if(a.code!==Kr.ERR_NOT_FOUND)throw a}s=await this._store.mergeOrCreate(e,{addresses:o}),ke(`added multiaddrs for ${e}`)}finally{ke("set release write lock"),n()}this._emit(Vu,{peerId:e,multiaddrs:s.addresses.map(o=>o.multiaddr)}),i||this._emit("peer",e)}async delete(e){if(!Ku.isPeerId(e))throw ke.error("peerId must be an instance of peer-id to store data"),os(new Error("peerId must be an instance of peer-id"),Kr.ERR_INVALID_PARAMETERS);ke("delete await write lock");let r=await this._store.lock.writeLock();ke("delete got write lock");let n;try{n=await this._store.has(e),await this._store.patchOrCreate(e,{addresses:[]})}finally{ke("delete release write lock"),r()}n&&this._emit(Vu,{peerId:e,multiaddrs:[]})}async getMultiaddrsForPeer(e,r=n=>n){let n=await this.get(e);return r(n).map(i=>{let s=i.multiaddr,o=s.getPeerId();return o&&o===e.toB58String()?s:s.encapsulate(`/p2p/${e.toB58String()}`)})}};function Nh(t,e,r,n=!1){return o6(e,i=>l6(i,s=>{if(!bx.isMultiaddr(s))throw ke.error("multiaddr must be an instance of Multiaddr"),os(new Error("multiaddr must be an instance of Multiaddr"),Kr.ERR_INVALID_PARAMETERS)}),i=>c6(i,s=>r(t,s)),i=>u6(i,s=>({multiaddr:new bx(s.toString()),isCertified:n})),i=>a6(i))}Sx.exports=_x});var Rx=w((vV,Tx)=>{"use strict";var Ax=Te(),ju=de(),{codes:Eo}=je(),Oh=Rt(),{equals:f6}=(mr(),gr),ur=Object.assign(Ax("libp2p:peer-store:key-book"),{error:Ax("libp2p:peer-store:key-book:err")}),Cx="change:pubkey",Ix=class{constructor(e,r){this._emit=e,this._store=r}async set(e,r){if(!Oh.isPeerId(e))throw ur.error("peerId must be an instance of peer-id to store data"),ju(new Error("peerId must be an instance of peer-id"),Eo.ERR_INVALID_PARAMETERS);if(!r)throw ur.error("publicKey must be an instance of PublicKey to store data"),ju(new Error("publicKey must be an instance of PublicKey"),Eo.ERR_INVALID_PARAMETERS);ur("set await write lock");let n=await this._store.lock.writeLock();ur("set got write lock");let i=!1;try{try{let s=await this._store.load(e);if(s.pubKey&&f6(s.pubKey.bytes,r.bytes))return}catch(s){if(s.code!==Eo.ERR_NOT_FOUND)throw s}await this._store.patchOrCreate(e,{pubKey:r}),i=!0}finally{ur("set release write lock"),n()}i&&this._emit(Cx,{peerId:e,pubKey:r})}async get(e){if(!Oh.isPeerId(e))throw ur.error("peerId must be an instance of peer-id to store data"),ju(new Error("peerId must be an instance of peer-id"),Eo.ERR_INVALID_PARAMETERS);ur("get await write lock");let r=await this._store.lock.readLock();ur("get got write lock");try{return(await this._store.load(e)).pubKey}catch(n){if(n.code!==Eo.ERR_NOT_FOUND)throw n}finally{ur("get release write lock"),r()}}async delete(e){if(!Oh.isPeerId(e))throw ur.error("peerId must be an instance of peer-id to store data"),ju(new Error("peerId must be an instance of peer-id"),Eo.ERR_INVALID_PARAMETERS);ur("delete await write lock");let r=await this._store.lock.writeLock();ur("delete got write lock");try{await this._store.patchOrCreate(e,{pubKey:void 0})}finally{ur("delete release write lock"),r()}this._emit(Cx,{peerId:e,pubKey:void 0})}};Tx.exports=Ix});var Ox=w((bV,Nx)=>{"use strict";var Bx=Te(),pi=de(),{codes:Tr}=je(),wo=Rt(),{equals:d6}=(mr(),gr),We=Object.assign(Bx("libp2p:peer-store:metadata-book"),{error:Bx("libp2p:peer-store:metadata-book:err")}),$u="change:metadata",Px=class{constructor(e,r){this._emit=e,this._store=r}async get(e){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);We("get await read lock");let r=await this._store.lock.readLock();We("get got read lock");try{return(await this._store.load(e)).metadata}catch(n){if(n.code!==Tr.ERR_NOT_FOUND)throw n}finally{We("get release read lock"),r()}return new Map}async getValue(e,r){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);We("getValue await read lock");let n=await this._store.lock.readLock();We("getValue got read lock");try{return(await this._store.load(e)).metadata.get(r)}catch(i){if(i.code!==Tr.ERR_NOT_FOUND)throw i}finally{We("getValue release write lock"),n()}}async set(e,r){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);if(!r||!(r instanceof Map))throw We.error("valid metadata must be provided to store data"),pi(new Error("valid metadata must be provided"),Tr.ERR_INVALID_PARAMETERS);We("set await write lock");let n=await this._store.lock.writeLock();We("set got write lock");try{await this._store.mergeOrCreate(e,{metadata:r})}finally{We("set release write lock"),n()}this._emit($u,{peerId:e,metadata:r})}async setValue(e,r,n){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);if(typeof r!="string"||!(n instanceof Uint8Array))throw We.error("valid key and value must be provided to store data"),pi(new Error("valid key and value must be provided"),Tr.ERR_INVALID_PARAMETERS);We("setValue await write lock");let i=await this._store.lock.writeLock();We("setValue got write lock");let s;try{try{let a=(await this._store.load(e)).metadata.get(r);if(a!=null&&d6(n,a))return}catch(o){if(o.code!==Tr.ERR_NOT_FOUND)throw o}s=await this._store.mergeOrCreate(e,{metadata:new Map([[r,n]])})}finally{We("setValue release write lock"),i()}this._emit($u,{peerId:e,metadata:s.metadata})}async delete(e){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);We("delete await write lock");let r=await this._store.lock.writeLock();We("delete got write lock");let n;try{n=await this._store.has(e),n&&await this._store.patch(e,{metadata:new Map})}finally{We("delete release write lock"),r()}n&&this._emit($u,{peerId:e,metadata:new Map})}async deleteValue(e,r){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);We("deleteValue await write lock");let n=await this._store.lock.writeLock();We("deleteValue got write lock");let i;try{i=(await this._store.load(e)).metadata,i.delete(r),await this._store.patch(e,{metadata:i})}catch(s){if(s.code!==Tr.ERR_NOT_FOUND)throw s}finally{We("deleteValue release write lock"),n()}i&&this._emit($u,{peerId:e,metadata:i})}};Nx.exports=Px});var qx=w((EV,kx)=>{"use strict";var Dx=Te(),_o=de(),{codes:Vr}=je(),Dh=Rt(),ot=Object.assign(Dx("libp2p:peer-store:proto-book"),{error:Dx("libp2p:peer-store:proto-book:err")}),Hu="change:protocols",Lx=class{constructor(e,r){this._emit=e,this._store=r}async get(e){ot("get wait for read lock");let r=await this._store.lock.readLock();ot("get got read lock");try{return(await this._store.load(e)).protocols}catch(n){if(n.code!==Vr.ERR_NOT_FOUND)throw n}finally{ot("get release read lock"),r()}return[]}async set(e,r){if(!Dh.isPeerId(e))throw ot.error("peerId must be an instance of peer-id to store data"),_o(new Error("peerId must be an instance of peer-id"),Vr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ot.error("protocols must be provided to store data"),_o(new Error("protocols must be provided"),Vr.ERR_INVALID_PARAMETERS);ot("set await write lock");let n=await this._store.lock.writeLock();ot("set got write lock");let i;try{try{let s=await this._store.load(e);if(new Set([...r]).size===s.protocols.length)return}catch(s){if(s.code!==Vr.ERR_NOT_FOUND)throw s}i=await this._store.patchOrCreate(e,{protocols:r}),ot(`stored provided protocols for ${e.toB58String()}`)}finally{ot("set release write lock"),n()}this._emit(Hu,{peerId:e,protocols:i.protocols})}async add(e,r){if(!Dh.isPeerId(e))throw ot.error("peerId must be an instance of peer-id to store data"),_o(new Error("peerId must be an instance of peer-id"),Vr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ot.error("protocols must be provided to store data"),_o(new Error("protocols must be provided"),Vr.ERR_INVALID_PARAMETERS);ot("add await write lock");let n=await this._store.lock.writeLock();ot("add got write lock");let i;try{try{let s=await this._store.load(e);if(new Set([...s.protocols,...r]).size===s.protocols.length)return}catch(s){if(s.code!==Vr.ERR_NOT_FOUND)throw s}i=await this._store.mergeOrCreate(e,{protocols:r}),ot(`added provided protocols for ${e.toB58String()}`)}finally{ot("add release write lock"),n()}this._emit(Hu,{peerId:e,protocols:i.protocols})}async remove(e,r){if(!Dh.isPeerId(e))throw ot.error("peerId must be an instance of peer-id to store data"),_o(new Error("peerId must be an instance of peer-id"),Vr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ot.error("protocols must be provided to store data"),_o(new Error("protocols must be provided"),Vr.ERR_INVALID_PARAMETERS);ot("remove await write lock");let n=await this._store.lock.writeLock();ot("remove got write lock");let i;try{try{let s=await this._store.load(e),o=new Set(s.protocols);for(let a of r)o.delete(a);if(s.protocols.length===o.size)return;r=Array.from(o)}catch(s){if(s.code!==Vr.ERR_NOT_FOUND)throw s}i=await this._store.patchOrCreate(e,{protocols:r})}finally{ot("remove release write lock"),n()}this._emit(Hu,{peerId:e,protocols:i.protocols})}async delete(e){ot("delete await write lock");let r=await this._store.lock.writeLock();ot("delete got write lock");let n;try{n=await this._store.has(e),await this._store.patchOrCreate(e,{protocols:[]})}catch(i){if(i.code!==Vr.ERR_NOT_FOUND)throw i}finally{ot("delete release write lock"),r()}n&&this._emit(Hu,{peerId:e,protocols:[]})}};kx.exports=Lx});var Mx=w((wV,Ux)=>{"use strict";var yi=gn(),So=yi.Reader,Lh=yi.Writer,Me=yi.util,yt=yi.roots["libp2p-peer"]||(yi.roots["libp2p-peer"]={});yt.Peer=function(){function t(r){if(this.addresses=[],this.protocols=[],this.metadata=[],r)for(var n=Object.keys(r),i=0;i<n.length;++i)r[n[i]]!=null&&(this[n[i]]=r[n[i]])}t.prototype.addresses=Me.emptyArray,t.prototype.protocols=Me.emptyArray,t.prototype.metadata=Me.emptyArray,t.prototype.pubKey=null,t.prototype.peerRecordEnvelope=null;var e;return Object.defineProperty(t.prototype,"_pubKey",{get:Me.oneOfGetter(e=["pubKey"]),set:Me.oneOfSetter(e)}),Object.defineProperty(t.prototype,"_peerRecordEnvelope",{get:Me.oneOfGetter(e=["peerRecordEnvelope"]),set:Me.oneOfSetter(e)}),t.encode=function(n,i){if(i||(i=Lh.create()),n.addresses!=null&&n.addresses.length)for(var s=0;s<n.addresses.length;++s)yt.Address.encode(n.addresses[s],i.uint32(10).fork()).ldelim();if(n.protocols!=null&&n.protocols.length)for(var s=0;s<n.protocols.length;++s)i.uint32(18).string(n.protocols[s]);if(n.metadata!=null&&n.metadata.length)for(var s=0;s<n.metadata.length;++s)yt.Metadata.encode(n.metadata[s],i.uint32(26).fork()).ldelim();return n.pubKey!=null&&Object.hasOwnProperty.call(n,"pubKey")&&i.uint32(34).bytes(n.pubKey),n.peerRecordEnvelope!=null&&Object.hasOwnProperty.call(n,"peerRecordEnvelope")&&i.uint32(42).bytes(n.peerRecordEnvelope),i},t.decode=function(n,i){n instanceof So||(n=So.create(n));for(var s=i===void 0?n.len:n.pos+i,o=new yt.Peer;n.pos<s;){var a=n.uint32();switch(a>>>3){case 1:o.addresses&&o.addresses.length||(o.addresses=[]),o.addresses.push(yt.Address.decode(n,n.uint32()));break;case 2:o.protocols&&o.protocols.length||(o.protocols=[]),o.protocols.push(n.string());break;case 3:o.metadata&&o.metadata.length||(o.metadata=[]),o.metadata.push(yt.Metadata.decode(n,n.uint32()));break;case 4:o.pubKey=n.bytes();break;case 5:o.peerRecordEnvelope=n.bytes();break;default:n.skipType(a&7);break}}return o},t.fromObject=function(n){if(n instanceof yt.Peer)return n;var i=new yt.Peer;if(n.addresses){if(!Array.isArray(n.addresses))throw TypeError(".Peer.addresses: array expected");i.addresses=[];for(var s=0;s<n.addresses.length;++s){if(typeof n.addresses[s]!="object")throw TypeError(".Peer.addresses: object expected");i.addresses[s]=yt.Address.fromObject(n.addresses[s])}}if(n.protocols){if(!Array.isArray(n.protocols))throw TypeError(".Peer.protocols: array expected");i.protocols=[];for(var s=0;s<n.protocols.length;++s)i.protocols[s]=String(n.protocols[s])}if(n.metadata){if(!Array.isArray(n.metadata))throw TypeError(".Peer.metadata: array expected");i.metadata=[];for(var s=0;s<n.metadata.length;++s){if(typeof n.metadata[s]!="object")throw TypeError(".Peer.metadata: object expected");i.metadata[s]=yt.Metadata.fromObject(n.metadata[s])}}return n.pubKey!=null&&(typeof n.pubKey=="string"?Me.base64.decode(n.pubKey,i.pubKey=Me.newBuffer(Me.base64.length(n.pubKey)),0):n.pubKey.length&&(i.pubKey=n.pubKey)),n.peerRecordEnvelope!=null&&(typeof n.peerRecordEnvelope=="string"?Me.base64.decode(n.peerRecordEnvelope,i.peerRecordEnvelope=Me.newBuffer(Me.base64.length(n.peerRecordEnvelope)),0):n.peerRecordEnvelope.length&&(i.peerRecordEnvelope=n.peerRecordEnvelope)),i},t.toObject=function(n,i){i||(i={});var s={};if((i.arrays||i.defaults)&&(s.addresses=[],s.protocols=[],s.metadata=[]),n.addresses&&n.addresses.length){s.addresses=[];for(var o=0;o<n.addresses.length;++o)s.addresses[o]=yt.Address.toObject(n.addresses[o],i)}if(n.protocols&&n.protocols.length){s.protocols=[];for(var o=0;o<n.protocols.length;++o)s.protocols[o]=n.protocols[o]}if(n.metadata&&n.metadata.length){s.metadata=[];for(var o=0;o<n.metadata.length;++o)s.metadata[o]=yt.Metadata.toObject(n.metadata[o],i)}return n.pubKey!=null&&n.hasOwnProperty("pubKey")&&(s.pubKey=i.bytes===String?Me.base64.encode(n.pubKey,0,n.pubKey.length):i.bytes===Array?Array.prototype.slice.call(n.pubKey):n.pubKey,i.oneofs&&(s._pubKey="pubKey")),n.peerRecordEnvelope!=null&&n.hasOwnProperty("peerRecordEnvelope")&&(s.peerRecordEnvelope=i.bytes===String?Me.base64.encode(n.peerRecordEnvelope,0,n.peerRecordEnvelope.length):i.bytes===Array?Array.prototype.slice.call(n.peerRecordEnvelope):n.peerRecordEnvelope,i.oneofs&&(s._peerRecordEnvelope="peerRecordEnvelope")),s},t.prototype.toJSON=function(){return this.constructor.toObject(this,yi.util.toJSONOptions)},t}();yt.Address=function(){function t(r){if(r)for(var n=Object.keys(r),i=0;i<n.length;++i)r[n[i]]!=null&&(this[n[i]]=r[n[i]])}t.prototype.multiaddr=Me.newBuffer([]),t.prototype.isCertified=null;var e;return Object.defineProperty(t.prototype,"_isCertified",{get:Me.oneOfGetter(e=["isCertified"]),set:Me.oneOfSetter(e)}),t.encode=function(n,i){return i||(i=Lh.create()),n.multiaddr!=null&&Object.hasOwnProperty.call(n,"multiaddr")&&i.uint32(10).bytes(n.multiaddr),n.isCertified!=null&&Object.hasOwnProperty.call(n,"isCertified")&&i.uint32(16).bool(n.isCertified),i},t.decode=function(n,i){n instanceof So||(n=So.create(n));for(var s=i===void 0?n.len:n.pos+i,o=new yt.Address;n.pos<s;){var a=n.uint32();switch(a>>>3){case 1:o.multiaddr=n.bytes();break;case 2:o.isCertified=n.bool();break;default:n.skipType(a&7);break}}return o},t.fromObject=function(n){if(n instanceof yt.Address)return n;var i=new yt.Address;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?Me.base64.decode(n.multiaddr,i.multiaddr=Me.newBuffer(Me.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),n.isCertified!=null&&(i.isCertified=Boolean(n.isCertified)),i},t.toObject=function(n,i){i||(i={});var s={};return i.defaults&&(i.bytes===String?s.multiaddr="":(s.multiaddr=[],i.bytes!==Array&&(s.multiaddr=Me.newBuffer(s.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(s.multiaddr=i.bytes===String?Me.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),n.isCertified!=null&&n.hasOwnProperty("isCertified")&&(s.isCertified=n.isCertified,i.oneofs&&(s._isCertified="isCertified")),s},t.prototype.toJSON=function(){return this.constructor.toObject(this,yi.util.toJSONOptions)},t}();yt.Metadata=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.key="",t.prototype.value=Me.newBuffer([]),t.encode=function(r,n){return n||(n=Lh.create()),r.key!=null&&Object.hasOwnProperty.call(r,"key")&&n.uint32(10).string(r.key),r.value!=null&&Object.hasOwnProperty.call(r,"value")&&n.uint32(18).bytes(r.value),n},t.decode=function(r,n){r instanceof So||(r=So.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new yt.Metadata;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.key=r.string();break;case 2:s.value=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof yt.Metadata)return r;var n=new yt.Metadata;return r.key!=null&&(n.key=String(r.key)),r.value!=null&&(typeof r.value=="string"?Me.base64.decode(r.value,n.value=Me.newBuffer(Me.base64.length(r.value)),0):r.value.length&&(n.value=r.value)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.key="",n.bytes===String?i.value="":(i.value=[],n.bytes!==Array&&(i.value=Me.newBuffer(i.value)))),r.key!=null&&r.hasOwnProperty("key")&&(i.key=r.key),r.value!=null&&r.hasOwnProperty("value")&&(i.value=n.bytes===String?Me.base64.encode(r.value,0,r.value.length):n.bytes===Array?Array.prototype.slice.call(r.value):r.value),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,yi.util.toJSONOptions)},t}();Ux.exports=yt});var kh=w((_V,Fx)=>{Fx.exports={WORKER_REQUEST_READ_LOCK:"lock:worker:request-read",WORKER_RELEASE_READ_LOCK:"lock:worker:release-read",MASTER_GRANT_READ_LOCK:"lock:master:grant-read",WORKER_REQUEST_WRITE_LOCK:"lock:worker:request-write",WORKER_RELEASE_WRITE_LOCK:"lock:worker:release-write",MASTER_GRANT_WRITE_LOCK:"lock:master:grant-write"}});var Kx=w(()=>{});var Xx=w((AV,Qx)=>{var h6=Qt().EventEmitter,{nanoid:p6}=(Xc(),td),{WORKER_REQUEST_READ_LOCK:Vx,WORKER_RELEASE_READ_LOCK:jx,MASTER_GRANT_READ_LOCK:$x,WORKER_REQUEST_WRITE_LOCK:Hx,WORKER_RELEASE_WRITE_LOCK:zx,MASTER_GRANT_WRITE_LOCK:Gx}=kh(),qa,Wx=(t,e,r,n,i)=>(s,o)=>{o&&o.type===r&&t.emit(e,o.name,()=>(s.send({type:i,name:o.name,identifier:o.identifier}),new Promise(a=>{let c=u=>{u&&u.type===n&&u.identifier===o.identifier&&(s.removeListener("message",c),a())};s.on("message",c)})))},Yx=(t,e,r,n)=>()=>{let i=p6();return process.send({type:e,identifier:i,name:t}),new Promise(s=>{let o=a=>{a&&a.type===r&&a.identifier===i&&(process.removeListener("message",o),s(()=>{process.send({type:n,identifier:i,name:t})}))};process.on("message",o)})};Qx.exports=t=>{try{if(qa=Kx(),!Object.keys(qa).length)return}catch(e){return}if(qa.isMaster||t.singleProcess){let e=new h6;return qa.on("message",Wx(e,"requestReadLock",Vx,jx,$x)),qa.on("message",Wx(e,"requestWriteLock",Hx,zx,Gx)),e}return{isWorker:!0,readLock:e=>Yx(e,Vx,$x,jx),writeLock:e=>Yx(e,Hx,Gx,zx)}}});var qh=w((CV,Zx)=>{var gi={},xo=t=>{t.addEventListener("message",e=>{xo.dispatchEvent("message",t,e)}),t.port&&t.port.addEventListener("message",e=>{xo.dispatchEvent("message",t,e)})};xo.addEventListener=(t,e)=>{gi[t]||(gi[t]=[]),gi[t].push(e)};xo.removeEventListener=(t,e)=>{!gi[t]||(gi[t]=gi[t].filter(r=>r===e))};xo.dispatchEvent=function(){let t=Array.prototype.slice.call(arguments),e=t.shift();!gi[e]||gi[e].forEach(r=>r.apply(null,t))};Zx.exports=xo});var uA=w((IV,cA)=>{var y6=Qt().EventEmitter,{nanoid:g6}=(Xc(),td),{WORKER_REQUEST_READ_LOCK:Jx,WORKER_RELEASE_READ_LOCK:eA,MASTER_GRANT_READ_LOCK:tA,WORKER_REQUEST_WRITE_LOCK:rA,WORKER_RELEASE_WRITE_LOCK:nA,MASTER_GRANT_WRITE_LOCK:iA}=kh(),sA=qh(),oA=(t,e,r,n,i)=>(s,o)=>{if(!o||!o.data||o.data.type!==r)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};t.emit(e,a.name,()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),new Promise(c=>{let u=l=>{if(!l||!l.data)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f&&f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})))},aA=(t,e,r,n)=>()=>{let i=g6();return globalThis.postMessage({type:e,identifier:i,name:t}),new Promise(s=>{let o=a=>{if(!a||!a.data)return;let c={type:a.data.type,identifier:a.data.identifier};c&&c.type===r&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:t})}))};globalThis.addEventListener("message",o)})},m6={singleProcess:!1};cA.exports=t=>{if(t=Object.assign({},m6,t),!!globalThis.document||t.singleProcess){let r=new y6;return sA.addEventListener("message",oA(r,"requestReadLock",Jx,eA,tA)),sA.addEventListener("message",oA(r,"requestWriteLock",rA,nA,iA)),r}return{isWorker:!0,readLock:r=>aA(r,Jx,tA,eA),writeLock:r=>aA(r,rA,iA,nA)}}});var fA=w((TV,Uh)=>{"use strict";var v6=Object.prototype.hasOwnProperty,Gt="~";function Ua(){}Object.create&&(Ua.prototype=Object.create(null),new Ua().__proto__||(Gt=!1));function b6(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function lA(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new b6(r,n||t,i),o=Gt?Gt+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],s]:t._events[o].push(s):(t._events[o]=s,t._eventsCount++),t}function zu(t,e){--t._eventsCount==0?t._events=new Ua:delete t._events[e]}function Mt(){this._events=new Ua,this._eventsCount=0}Mt.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)v6.call(r,n)&&e.push(Gt?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};Mt.prototype.listeners=function(e){var r=Gt?Gt+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Mt.prototype.listenerCount=function(e){var r=Gt?Gt+e:e,n=this._events[r];return n?n.fn?1:n.length:0};Mt.prototype.emit=function(e,r,n,i,s,o){var a=Gt?Gt+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,s),!0;case 6:return c.fn.call(c.context,r,n,i,s,o),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var d=c.length,p;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,r);break;case 3:c[f].fn.call(c[f].context,r,n);break;case 4:c[f].fn.call(c[f].context,r,n,i);break;default:if(!l)for(p=1,l=new Array(u-1);p<u;p++)l[p-1]=arguments[p];c[f].fn.apply(c[f].context,l)}}return!0};Mt.prototype.on=function(e,r,n){return lA(this,e,r,n,!1)};Mt.prototype.once=function(e,r,n){return lA(this,e,r,n,!0)};Mt.prototype.removeListener=function(e,r,n,i){var s=Gt?Gt+e:e;if(!this._events[s])return this;if(!r)return zu(this,s),this;var o=this._events[s];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&zu(this,s);else{for(var a=0,c=[],u=o.length;a<u;a++)(o[a].fn!==r||i&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:zu(this,s)}return this};Mt.prototype.removeAllListeners=function(e){var r;return e?(r=Gt?Gt+e:e,this._events[r]&&zu(this,r)):(this._events=new Ua,this._eventsCount=0),this};Mt.prototype.off=Mt.prototype.removeListener;Mt.prototype.addListener=Mt.prototype.on;Mt.prefixed=Gt;Mt.EventEmitter=Mt;typeof Uh!="undefined"&&(Uh.exports=Mt)});var hA=w((RV,dA)=>{"use strict";dA.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var yA=w((BV,Gu)=>{"use strict";var E6=hA(),Mh=class extends Error{constructor(e){super(e);this.name="TimeoutError"}},pA=(t,e,r)=>new Promise((n,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let s=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let o=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,a=r instanceof Error?r:new Mh(o);typeof t.cancel=="function"&&t.cancel(),i(a)},e);E6(t.then(n,i),()=>{clearTimeout(s)})});Gu.exports=pA;Gu.exports.default=pA;Gu.exports.TimeoutError=Mh});var gA=w(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});function w6(t,e,r){let n=0,i=t.length;for(;i>0;){let s=i/2|0,o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}Fh.default=w6});var vA=w(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var _6=gA(),mA=class{constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=_6.default(this._queue,n,(s,o)=>o.priority-s.priority);this._queue.splice(i,0,n)}dequeue(){let e=this._queue.shift();return e==null?void 0:e.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};Kh.default=mA});var wA=w(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var S6=fA(),bA=yA(),x6=vA(),Wu=()=>{},A6=new bA.TimeoutError,EA=class extends S6{constructor(e){var r,n,i,s;super();if(this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Wu,this._resolveIdle=Wu,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:x6.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${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 \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=Wu,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=Wu,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}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._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,i)=>{let s=async()=>{this._pendingCount++,this._intervalCount++;try{let o=this._timeout===void 0&&r.timeout===void 0?e():bA.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(A6)});n(await o)}catch(o){i(o)}this._next()};this._queue.enqueue(s,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Vh.default=EA});var _A=w((LV,jh)=>{"use strict";var Yu,DV=jh.exports.timeout=function(t,e){var r=new Yu,n;return Promise.race([t,new Promise(function(i,s){n=setTimeout(function(){s(r)},e)})]).then(function(i){return clearTimeout(n),i},function(i){throw clearTimeout(n),i})};Yu=jh.exports.TimeoutError=function(){Error.call(this),this.stack=Error().stack,this.message="Timeout"};Yu.prototype=Object.create(Error.prototype);Yu.prototype.name="TimeoutError"});var xA=w((kV,Hh)=>{var C6=Xx(),I6=uA(),{default:SA}=wA(),{timeout:T6}=_A(),R6=qh(),as={},mi;function $h(t,e){let r,n=new Promise(i=>{r=i});return t.add(()=>T6((()=>new Promise(i=>{r(()=>{i()})}))(),e.timeout)),n}var B6=(t,e)=>{if(mi.isWorker)return{readLock:mi.readLock(t,e),writeLock:mi.writeLock(t,e)};let r=new SA({concurrency:1}),n=null;return{readLock:()=>{if(n)return $h(n,e);n=new SA({concurrency:e.concurrency,autoStart:!1});let i=n,s=$h(n,e);return r.add(()=>(i.start(),i.onIdle().then(()=>{n===i&&(n=null)}))),s},writeLock:()=>(n=null,$h(r,e))}},P6={concurrency:1/0,timeout:846e5,global:globalThis,singleProcess:!1};Hh.exports=(t,e)=>(e||(e={}),typeof t=="object"&&(e=t,t="lock"),t||(t="lock"),e=Object.assign({},P6,e),mi||(mi=C6(e)||I6(e),mi.isWorker||(mi.on("requestReadLock",(r,n)=>{!as[r]||as[r].readLock().then(i=>n().finally(()=>i()))}),mi.on("requestWriteLock",async(r,n)=>{!as[r]||as[r].writeLock().then(i=>n().finally(()=>i()))}))),as[t]||(as[t]=B6(t,e)),as[t]);Hh.exports.Worker=function(t,e){e=e||globalThis.Worker;let r;try{r=new e(t)}catch(n){n.message.includes("not a constructor")&&(r=e(t))}if(!r)throw new Error("Could not create Worker from",e);return R6(r),r}});var DA=w((qV,OA)=>{"use strict";var AA=Te(),CA=Rt(),IA=de(),{codes:Qu}=je(),{Key:N6}=(Jc(),rd),{base32:O6}=(wi(),Ei),{keys:{unmarshalPublicKey:D6,marshalPublicKey:L6}}=Bu(),{Multiaddr:TA}=qt(),{Peer:RA}=Mx(),k6=xA(),{equals:q6}=(mr(),gr),BA=Object.assign(AA("libp2p:peer-store:store"),{error:AA("libp2p:peer-store:store:err")}),PA="/peers/",NA=class{constructor(e){this._datastore=e,this.lock=k6("peer-store",{singleProcess:!0})}_peerIdToDatastoreKey(e){if(!CA.isPeerId(e))throw BA.error("peerId must be an instance of peer-id to store data"),IA(new Error("peerId must be an instance of peer-id"),Qu.ERR_INVALID_PARAMETERS);let r=e.toString();return new N6(`${PA}${r}`)}async has(e){return this._datastore.has(this._peerIdToDatastoreKey(e))}async delete(e){await this._datastore.delete(this._peerIdToDatastoreKey(e))}async load(e){let r=await this._datastore.get(this._peerIdToDatastoreKey(e)),n=RA.decode(r),i=n.pubKey?D6(n.pubKey):e.pubKey,s=new Map;for(let o of n.metadata)s.set(o.key,o.value);return{...n,id:e,pubKey:i,addresses:n.addresses.map(({multiaddr:o,isCertified:a})=>({multiaddr:new TA(o),isCertified:a||!1})),metadata:s,peerRecordEnvelope:n.peerRecordEnvelope||void 0}}async save(e){if(e.pubKey!=null&&e.id.pubKey!=null&&!q6(e.pubKey.bytes,e.id.pubKey.bytes))throw BA.error("peer publicKey bytes do not match peer id publicKey bytes"),IA(new Error("publicKey bytes do not match peer id publicKey bytes"),Qu.ERR_INVALID_PARAMETERS);let r=new Set,n=RA.encode({addresses:e.addresses.filter(i=>r.has(i.multiaddr.toString())?!1:(r.add(i.multiaddr.toString()),!0)).sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({multiaddr:i,isCertified:s})=>({multiaddr:i.bytes,isCertified:s})),protocols:e.protocols.sort(),pubKey:e.pubKey?L6(e.pubKey):void 0,metadata:[...e.metadata.keys()].sort().map(i=>({key:i,value:e.metadata.get(i)})),peerRecordEnvelope:e.peerRecordEnvelope}).finish();return await this._datastore.put(this._peerIdToDatastoreKey(e.id),n),this.load(e.id)}async patch(e,r){let n=await this.load(e);return await this._patch(e,r,n)}async patchOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==Qu.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._patch(e,r,n)}async _patch(e,r,n){return await this.save({...n,...r,id:e})}async merge(e,r){let n=await this.load(e);return this._merge(e,r,n)}async mergeOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==Qu.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._merge(e,r,n)}async _merge(e,r,n){let i=new Map;return(r.addresses||[]).forEach(s=>{i.set(s.multiaddr.toString(),s.isCertified)}),n.addresses.forEach(({multiaddr:s,isCertified:o})=>{let a=s.toString();i.set(a,Boolean(i.get(a)||o))}),await this.save({id:e,addresses:Array.from(i.entries()).map(([s,o])=>({multiaddr:new TA(s),isCertified:o})),protocols:Array.from(new Set([...n.protocols||[],...r.protocols||[]])),metadata:new Map([...n.metadata?n.metadata.entries():[],...r.metadata?r.metadata.entries():[]]),pubKey:r.pubKey||(n!=null?n.pubKey:void 0),peerRecordEnvelope:r.peerRecordEnvelope||(n!=null?n.peerRecordEnvelope:void 0)})}async*all(){for await(let e of this._datastore.queryKeys({prefix:PA})){let r=e.toString().split("/")[2],n=O6.decode(r);yield this.load(CA.createFromBytes(n))}}};OA.exports=NA});var UA=w((UV,qA)=>{"use strict";var LA=Te(),{EventEmitter:U6}=Qt(),M6=xx(),F6=Rx(),K6=Ox(),V6=qx(),j6=DA(),Rr=Object.assign(LA("libp2p:peer-store"),{error:LA("libp2p:peer-store:err")}),kA=class extends U6{constructor({peerId:e,datastore:r,addressFilter:n}){super();this._peerId=e,this._store=new j6(r),this.addressBook=new M6(this.emit.bind(this),this._store,n),this.keyBook=new F6(this.emit.bind(this),this._store),this.metadataBook=new K6(this.emit.bind(this),this._store),this.protoBook=new V6(this.emit.bind(this),this._store)}async*getPeers(){Rr("getPeers await read lock");let e=await this._store.lock.readLock();Rr("getPeers got read lock");try{for await(let r of this._store.all())r.id.toB58String()!==this._peerId.toB58String()&&(yield r)}finally{Rr("getPeers release read lock"),e()}}async delete(e){Rr("delete await write lock");let r=await this._store.lock.writeLock();Rr("delete got write lock");try{await this._store.delete(e)}finally{Rr("delete release write lock"),r()}}async get(e){Rr("get await read lock");let r=await this._store.lock.readLock();Rr("get got read lock");try{return this._store.load(e)}finally{Rr("get release read lock"),r()}}async has(e){Rr("has await read lock");let r=await this._store.lock.readLock();Rr("has got read lock");try{return this._store.has(e)}finally{Rr("has release read lock"),r()}}};qA.exports=kA});var FA=w((MV,MA)=>{"use strict";function $6(t,e,r){let n=new t(e,r);n._subscribeAdapter=n.subscribe,n._unsubscribeAdapter=n.unsubscribe;function i(o,a){a&&n.on(o,a),n._subscribeAdapter(o)}function s(o,a){a?n.removeListener(o,a):n.removeAllListeners(o),n.listenerCount(o)===0&&n._unsubscribeAdapter(o)}return n.subscribe=i,n.unsubscribe=s,n}MA.exports=$6});var HA=w((FV,$A)=>{"use strict";var KA=()=>{},VA=Symbol.for("@libp2p/js-interfaces/topology"),jA=class{constructor({min:e=0,max:r=1/0,handlers:n={}}){this.min=e,this.max=r,this._onConnect=n.onConnect||KA,this._onDisconnect=n.onDisconnect||KA,this.peers=new Set}get[Symbol.toStringTag](){return"Topology"}get[VA](){return!0}static isTopology(e){return Boolean(e&&e[VA])}async setRegistrar(e){this._registrar=e}disconnect(e){this._onDisconnect(e)}};$A.exports=jA});var YA=w((KV,WA)=>{"use strict";var zA=Te(),H6=Object.assign(zA("libp2p:registrar"),{error:zA("libp2p:registrar:err")}),z6=de(),{codes:{ERR_INVALID_PARAMETERS:G6}}=je(),W6=HA(),GA=class{constructor({peerStore:e,connectionManager:r}){this.peerStore=e,this.connectionManager=r,this.topologies=new Map,this._handle=void 0,this._onDisconnect=this._onDisconnect.bind(this),this.connectionManager.on("peer:disconnect",this._onDisconnect)}get handle(){return this._handle}set handle(e){this._handle=e}getConnection(e){return this.connectionManager.get(e)}async register(e){if(!W6.isTopology(e))throw H6.error("topology must be an instance of interfaces/topology"),z6(new Error("topology must be an instance of interfaces/topology"),G6);let r=(Math.random()*1e9).toString(36)+Date.now();return this.topologies.set(r,e),await e.setRegistrar(this),r}unregister(e){return this.topologies.delete(e)}_onDisconnect(e){for(let[,r]of this.topologies)r.disconnect(e.remotePeer)}};WA.exports=GA});var zh=w((VV,Ma)=>{"use strict";var{Buffer:Xu}=ci(),Zu=Ji();Ma.exports=async function*(t){for await(let e of t)Xu.isBuffer(e)?yield e:Zu.isBufferList(e)?yield e.slice():yield Xu.from(e)};Ma.exports.toBuffer=Ma.exports;Ma.exports.toList=async function*(t){for await(let e of t)Xu.isBuffer(e)?yield new Zu().append(e):Zu.isBufferList(e)?yield e:yield new Zu().append(Xu.from(e))}});var ZA=w((jV,XA)=>{"use strict";var Ao=gn(),QA=Ao.Reader,Y6=Ao.Writer,rt=Ao.util,Fa=Ao.roots["libp2p-identify"]||(Ao.roots["libp2p-identify"]={});Fa.Identify=function(){function t(e){if(this.listenAddrs=[],this.protocols=[],e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.protocolVersion="",t.prototype.agentVersion="",t.prototype.publicKey=rt.newBuffer([]),t.prototype.listenAddrs=rt.emptyArray,t.prototype.observedAddr=rt.newBuffer([]),t.prototype.protocols=rt.emptyArray,t.prototype.signedPeerRecord=rt.newBuffer([]),t.encode=function(r,n){if(n||(n=Y6.create()),r.publicKey!=null&&Object.hasOwnProperty.call(r,"publicKey")&&n.uint32(10).bytes(r.publicKey),r.listenAddrs!=null&&r.listenAddrs.length)for(var i=0;i<r.listenAddrs.length;++i)n.uint32(18).bytes(r.listenAddrs[i]);if(r.protocols!=null&&r.protocols.length)for(var i=0;i<r.protocols.length;++i)n.uint32(26).string(r.protocols[i]);return r.observedAddr!=null&&Object.hasOwnProperty.call(r,"observedAddr")&&n.uint32(34).bytes(r.observedAddr),r.protocolVersion!=null&&Object.hasOwnProperty.call(r,"protocolVersion")&&n.uint32(42).string(r.protocolVersion),r.agentVersion!=null&&Object.hasOwnProperty.call(r,"agentVersion")&&n.uint32(50).string(r.agentVersion),r.signedPeerRecord!=null&&Object.hasOwnProperty.call(r,"signedPeerRecord")&&n.uint32(66).bytes(r.signedPeerRecord),n},t.decode=function(r,n){r instanceof QA||(r=QA.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new Fa.Identify;r.pos<i;){var o=r.uint32();switch(o>>>3){case 5:s.protocolVersion=r.string();break;case 6:s.agentVersion=r.string();break;case 1:s.publicKey=r.bytes();break;case 2:s.listenAddrs&&s.listenAddrs.length||(s.listenAddrs=[]),s.listenAddrs.push(r.bytes());break;case 4:s.observedAddr=r.bytes();break;case 3:s.protocols&&s.protocols.length||(s.protocols=[]),s.protocols.push(r.string());break;case 8:s.signedPeerRecord=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof Fa.Identify)return r;var n=new Fa.Identify;if(r.protocolVersion!=null&&(n.protocolVersion=String(r.protocolVersion)),r.agentVersion!=null&&(n.agentVersion=String(r.agentVersion)),r.publicKey!=null&&(typeof r.publicKey=="string"?rt.base64.decode(r.publicKey,n.publicKey=rt.newBuffer(rt.base64.length(r.publicKey)),0):r.publicKey.length&&(n.publicKey=r.publicKey)),r.listenAddrs){if(!Array.isArray(r.listenAddrs))throw TypeError(".Identify.listenAddrs: array expected");n.listenAddrs=[];for(var i=0;i<r.listenAddrs.length;++i)typeof r.listenAddrs[i]=="string"?rt.base64.decode(r.listenAddrs[i],n.listenAddrs[i]=rt.newBuffer(rt.base64.length(r.listenAddrs[i])),0):r.listenAddrs[i].length&&(n.listenAddrs[i]=r.listenAddrs[i])}if(r.observedAddr!=null&&(typeof r.observedAddr=="string"?rt.base64.decode(r.observedAddr,n.observedAddr=rt.newBuffer(rt.base64.length(r.observedAddr)),0):r.observedAddr.length&&(n.observedAddr=r.observedAddr)),r.protocols){if(!Array.isArray(r.protocols))throw TypeError(".Identify.protocols: array expected");n.protocols=[];for(var i=0;i<r.protocols.length;++i)n.protocols[i]=String(r.protocols[i])}return r.signedPeerRecord!=null&&(typeof r.signedPeerRecord=="string"?rt.base64.decode(r.signedPeerRecord,n.signedPeerRecord=rt.newBuffer(rt.base64.length(r.signedPeerRecord)),0):r.signedPeerRecord.length&&(n.signedPeerRecord=r.signedPeerRecord)),n},t.toObject=function(r,n){n||(n={});var i={};if((n.arrays||n.defaults)&&(i.listenAddrs=[],i.protocols=[]),n.defaults&&(n.bytes===String?i.publicKey="":(i.publicKey=[],n.bytes!==Array&&(i.publicKey=rt.newBuffer(i.publicKey))),n.bytes===String?i.observedAddr="":(i.observedAddr=[],n.bytes!==Array&&(i.observedAddr=rt.newBuffer(i.observedAddr))),i.protocolVersion="",i.agentVersion="",n.bytes===String?i.signedPeerRecord="":(i.signedPeerRecord=[],n.bytes!==Array&&(i.signedPeerRecord=rt.newBuffer(i.signedPeerRecord)))),r.publicKey!=null&&r.hasOwnProperty("publicKey")&&(i.publicKey=n.bytes===String?rt.base64.encode(r.publicKey,0,r.publicKey.length):n.bytes===Array?Array.prototype.slice.call(r.publicKey):r.publicKey),r.listenAddrs&&r.listenAddrs.length){i.listenAddrs=[];for(var s=0;s<r.listenAddrs.length;++s)i.listenAddrs[s]=n.bytes===String?rt.base64.encode(r.listenAddrs[s],0,r.listenAddrs[s].length):n.bytes===Array?Array.prototype.slice.call(r.listenAddrs[s]):r.listenAddrs[s]}if(r.protocols&&r.protocols.length){i.protocols=[];for(var s=0;s<r.protocols.length;++s)i.protocols[s]=r.protocols[s]}return r.observedAddr!=null&&r.hasOwnProperty("observedAddr")&&(i.observedAddr=n.bytes===String?rt.base64.encode(r.observedAddr,0,r.observedAddr.length):n.bytes===Array?Array.prototype.slice.call(r.observedAddr):r.observedAddr),r.protocolVersion!=null&&r.hasOwnProperty("protocolVersion")&&(i.protocolVersion=r.protocolVersion),r.agentVersion!=null&&r.hasOwnProperty("agentVersion")&&(i.agentVersion=r.agentVersion),r.signedPeerRecord!=null&&r.hasOwnProperty("signedPeerRecord")&&(i.signedPeerRecord=n.bytes===String?rt.base64.encode(r.signedPeerRecord,0,r.signedPeerRecord.length):n.bytes===Array?Array.prototype.slice.call(r.signedPeerRecord):r.signedPeerRecord),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Ao.util.toJSONOptions)},t}();XA.exports=Fa});var aC=w(($V,oC)=>{"use strict";var JA=Te(),lr=Object.assign(JA("libp2p:identify"),{error:JA("libp2p:identify:err")}),Gh=de(),Ju=so(),{pipe:el}=ir(),{collect:eC,take:tC,consume:rC}=Lu(),{fromString:Co}=(It(),Nt),Q6=Rt(),{Multiaddr:Wh}=qt(),{toBuffer:nC}=zh(),Ka=ZA(),iC=du(),sC=pu(),{MULTICODEC_IDENTIFY:X6,MULTICODEC_IDENTIFY_PUSH:Z6,IDENTIFY_PROTOCOL_VERSION:J6,MULTICODEC_IDENTIFY_PROTOCOL_NAME:e5,MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME:t5,MULTICODEC_IDENTIFY_PROTOCOL_VERSION:r5,MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION:n5}=vd(),{codes:Yh}=je(),cs=class{static getProtocolStr(e){return{identifyProtocolStr:`/${e._config.protocolPrefix}/${e5}/${r5}`,identifyPushProtocolStr:`/${e._config.protocolPrefix}/${t5}/${n5}`}}constructor({libp2p:e}){this._libp2p=e,this.peerStore=e.peerStore,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.handleMessage=this.handleMessage.bind(this);let r=cs.getProtocolStr(e);this.identifyProtocolStr=r.identifyProtocolStr,this.identifyPushProtocolStr=r.identifyPushProtocolStr,this._host={protocolVersion:`${e._config.protocolPrefix}/${J6}`,...e._options.host},this.connectionManager.on("peer:connect",n=>{this.identify(n).catch(lr.error)}),this.peerStore.on("change:multiaddrs",({peerId:n})=>{n.toString()===this.peerId.toString()&&this.pushToPeerStore().catch(i=>lr.error(i))}),this.peerStore.on("change:protocols",({peerId:n})=>{n.toString()===this.peerId.toString()&&this.pushToPeerStore().catch(i=>lr.error(i))})}async start(){await this.peerStore.metadataBook.setValue(this.peerId,"AgentVersion",Co(this._host.agentVersion)),await this.peerStore.metadataBook.setValue(this.peerId,"ProtocolVersion",Co(this._host.protocolVersion))}async stop(){}async push(e){let r=await this.peerStore.addressBook.getRawEnvelope(this.peerId),n=this._libp2p.multiaddrs.map(o=>o.bytes),i=await this.peerStore.protoBook.get(this.peerId),s=e.map(async o=>{try{let{stream:a}=await o.newStream(this.identifyPushProtocolStr);await el([Ka.Identify.encode({listenAddrs:n,signedPeerRecord:r,protocols:i}).finish()],Ju.encode(),a,rC)}catch(a){lr.error("could not push identify update to peer",a)}});return Promise.all(s)}async pushToPeerStore(){if(!this._libp2p.isStarted())return;let e=[],r;for await(let n of this.peerStore.getPeers())n.protocols.includes(this.identifyPushProtocolStr)&&(r=this.connectionManager.get(n.id))&&e.push(r);await this.push(e)}async identify(e){let{stream:r}=await e.newStream(this.identifyProtocolStr),[n]=await el([],r,Ju.decode(),tC(1),nC,eC);if(!n)throw Gh(new Error("No data could be retrieved"),Yh.ERR_CONNECTION_ENDED);let i;try{i=Ka.Identify.decode(n)}catch(d){throw Gh(d,Yh.ERR_INVALID_MESSAGE)}let{publicKey:s,listenAddrs:o,protocols:a,observedAddr:c,signedPeerRecord:u}=i,l=await Q6.createFromPubKey(s);if(e.remotePeer.toB58String()!==l.toB58String())throw Gh(new Error("identified peer does not match the expected peer"),Yh.ERR_INVALID_PEER);let f=cs.getCleanMultiaddr(c);try{let d=await iC.openAndCertify(u,sC.DOMAIN);if(await this.peerStore.addressBook.consumePeerRecord(d)){await this.peerStore.protoBook.set(l,a),await this.peerStore.metadataBook.setValue(l,"AgentVersion",Co(i.agentVersion)),await this.peerStore.metadataBook.setValue(l,"ProtocolVersion",Co(i.protocolVersion));return}}catch(d){lr("received invalid envelope, discard it and fallback to listenAddrs is available",d)}try{await this.peerStore.addressBook.set(l,o.map(d=>new Wh(d)))}catch(d){lr.error("received invalid addrs",d)}await this.peerStore.protoBook.set(l,a),await this.peerStore.metadataBook.setValue(l,"AgentVersion",Co(i.agentVersion)),await this.peerStore.metadataBook.setValue(l,"ProtocolVersion",Co(i.protocolVersion)),lr("received observed address of %s",f)}handleMessage({connection:e,stream:r,protocol:n}){switch(n){case this.identifyProtocolStr:return this._handleIdentify({connection:e,stream:r});case this.identifyPushProtocolStr:return this._handlePush({connection:e,stream:r});default:lr.error("cannot handle unknown protocol %s",n)}}async _handleIdentify({connection:e,stream:r}){try{let n=new Uint8Array(0);this.peerId.pubKey&&(n=this.peerId.pubKey.bytes);let i=await this.peerStore.addressBook.getRawEnvelope(this.peerId),s=await this.peerStore.protoBook.get(this.peerId),o=Ka.Identify.encode({protocolVersion:this._host.protocolVersion,agentVersion:this._host.agentVersion,publicKey:n,listenAddrs:this._libp2p.multiaddrs.map(a=>a.bytes),signedPeerRecord:i,observedAddr:e.remoteAddr.bytes,protocols:s}).finish();await el([o],Ju.encode(),r,rC)}catch(n){lr.error("could not respond to identify request",n)}}async _handlePush({connection:e,stream:r}){let n;try{let[s]=await el([],r,Ju.decode(),tC(1),nC,eC);n=Ka.Identify.decode(s)}catch(s){return lr.error("received invalid message",s)}let i=e.remotePeer;try{let s=await iC.openAndCertify(n.signedPeerRecord,sC.DOMAIN);if(await this.peerStore.addressBook.consumePeerRecord(s)){await this.peerStore.protoBook.set(i,n.protocols);return}}catch(s){lr("received invalid envelope, discard it and fallback to listenAddrs is available",s)}try{await this.peerStore.addressBook.set(i,n.listenAddrs.map(s=>new Wh(s)))}catch(s){lr.error("received invalid addrs",s)}try{await this.peerStore.protoBook.set(i,n.protocols)}catch(s){lr.error("received invalid protocols",s)}}static getCleanMultiaddr(e){if(e&&e.length>0)try{return new Wh(e)}catch(r){return null}return null}},i5={IDENTIFY:X6,IDENTIFY_PUSH:Z6};cs.multicodecs=i5;cs.Messsage=Ka;oC.exports=cs});var lC=w((HV,uC)=>{"use strict";var us=gn(),tl=us.Reader,cC=us.Writer,Io=us.util,dn=us.roots["libp2p-fetch"]||(us.roots["libp2p-fetch"]={});dn.FetchRequest=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.identifier="",t.encode=function(r,n){return n||(n=cC.create()),r.identifier!=null&&Object.hasOwnProperty.call(r,"identifier")&&n.uint32(10).string(r.identifier),n},t.decode=function(r,n){r instanceof tl||(r=tl.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new dn.FetchRequest;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.identifier=r.string();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof dn.FetchRequest)return r;var n=new dn.FetchRequest;return r.identifier!=null&&(n.identifier=String(r.identifier)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.identifier=""),r.identifier!=null&&r.hasOwnProperty("identifier")&&(i.identifier=r.identifier),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,us.util.toJSONOptions)},t}();dn.FetchResponse=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.status=0,t.prototype.data=Io.newBuffer([]),t.encode=function(r,n){return n||(n=cC.create()),r.status!=null&&Object.hasOwnProperty.call(r,"status")&&n.uint32(8).int32(r.status),r.data!=null&&Object.hasOwnProperty.call(r,"data")&&n.uint32(18).bytes(r.data),n},t.decode=function(r,n){r instanceof tl||(r=tl.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new dn.FetchResponse;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.status=r.int32();break;case 2:s.data=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof dn.FetchResponse)return r;var n=new dn.FetchResponse;switch(r.status){case"OK":case 0:n.status=0;break;case"NOT_FOUND":case 1:n.status=1;break;case"ERROR":case 2:n.status=2;break}return r.data!=null&&(typeof r.data=="string"?Io.base64.decode(r.data,n.data=Io.newBuffer(Io.base64.length(r.data)),0):r.data.length&&(n.data=r.data)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.status=n.enums===String?"OK":0,n.bytes===String?i.data="":(i.data=[],n.bytes!==Array&&(i.data=Io.newBuffer(i.data)))),r.status!=null&&r.hasOwnProperty("status")&&(i.status=n.enums===String?dn.FetchResponse.StatusCode[r.status]:r.status),r.data!=null&&r.hasOwnProperty("data")&&(i.data=n.bytes===String?Io.base64.encode(r.data,0,r.data.length):n.bytes===Array?Array.prototype.slice.call(r.data):r.data),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,us.util.toJSONOptions)},t.StatusCode=function(){var e={},r=Object.create(e);return r[e[0]="OK"]=0,r[e[1]="NOT_FOUND"]=1,r[e[2]="ERROR"]=2,r}(),t}();uC.exports=dn});var dC=w((zV,fC)=>{"use strict";fC.exports={PROTOCOL:"/libp2p/fetch/0.0.1"}});var mC=w((yC,gC)=>{"use strict";var hC=Te(),s5=Object.assign(hC("libp2p:fetch"),{error:hC("libp2p:fetch:err")}),Qh=de(),{codes:Xh}=je(),rl=so(),{FetchRequest:Zh,FetchResponse:jr}=lC(),pC=oo(),{PROTOCOL:o5}=dC(),Va=class{constructor(e){this._lookupFunctions=new Map,this._libp2p=e,this.handleMessage=this.handleMessage.bind(this)}async fetch(e,r){s5("dialing %s to %s",this._protocol,e.toB58String?e.toB58String():e);let n=await this._libp2p.dial(e),{stream:i}=await n.newStream(Va.PROTOCOL),s=pC(i),o=new Zh({identifier:r});s.write(rl.encode.single(Zh.encode(o).finish()));let a=jr.decode((await rl.decode.fromReader(s.reader).next()).value.slice());switch(a.status){case jr.StatusCode.OK:return a.data;case jr.StatusCode.NOT_FOUND:return null;case jr.StatusCode.ERROR:{let c=new TextDecoder().decode(a.data);throw Qh(new Error("Error in fetch protocol response: "+c),Xh.ERR_INVALID_PARAMETERS)}default:throw Qh(new Error("Unknown response status"),Xh.ERR_INVALID_MESSAGE)}}async handleMessage(e){let{stream:r}=e,n=pC(r),i=Zh.decode((await rl.decode.fromReader(n.reader).next()).value.slice()),s,o=this._getLookupFunction(i.identifier);if(o){let a=await o(i.identifier);a?s=new jr({status:jr.StatusCode.OK,data:a}):s=new jr({status:jr.StatusCode.NOT_FOUND})}else{let a=new TextEncoder().encode("No lookup function registered for key: "+i.identifier);s=new jr({status:jr.StatusCode.ERROR,data:a})}n.write(rl.encode.single(jr.encode(s).finish()))}_getLookupFunction(e){for(let r of this._lookupFunctions.keys())if(e.startsWith(r))return this._lookupFunctions.get(r);return null}registerLookupFunction(e,r){if(this._lookupFunctions.has(e))throw Qh(new Error("Fetch protocol handler for key prefix '"+e+"' already registered"),Xh.ERR_KEY_ALREADY_EXISTS);this._lookupFunctions.set(e,r)}unregisterLookupFunction(e,r){r!=null&&this._lookupFunctions.get(e)!==r||this._lookupFunctions.delete(e)}};Va.PROTOCOL=o5;yC=gC.exports=Va});var bC=w((GV,vC)=>{"use strict";vC.exports={PROTOCOL:"/ipfs/ping/1.0.0",PING_LENGTH:32,PROTOCOL_VERSION:"1.0.0",PROTOCOL_NAME:"ping"}});var CC=w((WV,AC)=>{"use strict";var EC=Te(),a5=Object.assign(EC("libp2p:ping"),{error:EC("libp2p:ping:err")}),c5=de(),{codes:u5}=je(),l5=Bu(),{pipe:wC}=ir(),{toBuffer:f5}=zh(),{collect:d5,take:h5}=Lu(),{equals:p5}=(mr(),gr),{PROTOCOL_NAME:_C,PING_LENGTH:y5,PROTOCOL_VERSION:SC}=bC(),xC=class{static getProtocolStr(e){return`/${e._config.protocolPrefix}/${_C}/${SC}`}constructor(e){this._libp2p=e}handleMessage({stream:e}){return wC(e,e)}async ping(e){let r=`/${this._libp2p._config.protocolPrefix}/${_C}/${SC}`;a5("dialing %s to %s",r,e.toB58String?e.toB58String():e);let n=await this._libp2p.dial(e),{stream:i}=await n.newStream(r),s=Date.now(),o=l5.randomBytes(y5),[a]=await wC([o],i,u=>h5(1,u),f5,d5),c=Date.now();if(!p5(o,a))throw c5(new Error("Received wrong ping ack"),u5.ERR_WRONG_PING_ACK);return c-s}};AC.exports=xC});var IC=w(()=>{});var TC=w(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0}),Jh.promisify=nl;var g5="__ES6-PROMISIFY--CUSTOM-ARGUMENTS__";function nl(t){if(typeof t!="function")throw new TypeError("Argument to promisify must be a function");var e=t[g5],r=nl.Promise||Promise;if(typeof r!="function")throw new Error("No Promise implementation found; do you need a polyfill?");return function(){for(var n=this,i=arguments.length,s=Array(i),o=0;o<i;o++)s[o]=arguments[o];return new r(function(a,c){s.push(function(u){if(u)return c(u);for(var l=arguments.length,f=Array(1<l?l-1:0),d=1;d<l;d++)f[d-1]=arguments[d];if(f.length===1||!e)return a(f[0]);var p={};f.forEach(function(h,g){var m=e[g];m&&(p[m]=h)}),a(p)}),t.apply(n,s)})}}nl.argumentNames="__ES6-PROMISIFY--CUSTOM-ARGUMENTS__",nl.Promise=void 0});var BC=w((ZV,RC)=>{function m5(){return typeof window!="undefined"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process!="undefined"&&typeof process.versions=="object"&&!!process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0}RC.exports=m5});var NC=w((JV,PC)=>{"use strict";var v5=BC(),il=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,ja=v5(),b5=il&&!ja,E5=ja&&!il,w5=ja&&il,_5=typeof u0=="function"&&typeof process!="undefined"&&typeof process.release!="undefined"&&process.release.name==="node"&&!ja,S5=typeof importScripts=="function"&&typeof self!="undefined"&&typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope,x5=typeof process!="undefined"&&typeof process.env!="undefined"&&!1;PC.exports={isTest:x5,isElectron:ja,isElectronMain:E5,isElectronRenderer:w5,isNode:_5,isBrowser:b5,isWebWorker:S5,isEnvWithDom:il}});var DC=w((e9,OC)=>{function Br(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}OC.exports=Br;Br.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Br.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Br.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0};Br.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Br.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};Br.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};Br.prototype.start=Br.prototype.try;Br.prototype.errors=function(){return this._errors};Br.prototype.attempts=function(){return this._attempts};Br.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,r=0,n=0;n<this._errors.length;n++){var i=this._errors[n],s=i.message,o=(t[s]||0)+1;t[s]=o,o>=r&&(e=i,r=o)}return e}});var LC=w(ls=>{var A5=DC();ls.operation=function(t){var e=ls.timeouts(t);return new A5(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};ls.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in t)e[r]=t[r];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return t&&t.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(s,o){return s-o}),n};ls.createTimeout=function(t,e){var r=e.randomize?Math.random()+1:1,n=Math.round(r*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return n=Math.min(n,e.maxTimeout),n};ls.wrap=function(t,e,r){if(e instanceof Array&&(r=e,e=null),!r){r=[];for(var n in t)typeof t[n]=="function"&&r.push(n)}for(var i=0;i<r.length;i++){var s=r[i],o=t[s];t[s]=function(c){var u=ls.operation(e),l=Array.prototype.slice.call(arguments,1),f=l.pop();l.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),f.apply(this,arguments))}),u.attempt(function(){c.apply(t,l)})}.bind(t,o),t[s].options=e}}});var qC=w((r9,kC)=>{kC.exports=LC()});var MC=w((n9,sl)=>{"use strict";var C5=qC(),I5=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],e0=class extends Error{constructor(e){super();e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},T5=(t,e,r)=>{let n=r.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=n,t},R5=t=>I5.includes(t),UC=(t,e)=>new Promise((r,n)=>{e={onFailedAttempt:()=>{},retries:10,...e};let i=C5.operation(e);i.attempt(async s=>{try{r(await t(s))}catch(o){if(!(o instanceof Error)){n(new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`));return}if(o instanceof e0)i.stop(),n(o.originalError);else if(o instanceof TypeError&&!R5(o.message))i.stop(),n(o);else{T5(o,s,e);try{await e.onFailedAttempt(o)}catch(a){n(a);return}i.retry(o)||n(i.mainError())}}})});sl.exports=UC;sl.exports.default=UC;sl.exports.AbortError=e0});var KC=w((i9,FC)=>{"use strict";function B5(t){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^::1$/.test(t)}FC.exports=B5});var jC=w((s9,VC)=>{"use strict";var P5=KC();function N5(t){let{address:e}=t.nodeAddress();return P5(e)}VC.exports=N5});var YC=w((o9,WC)=>{"use strict";var O5=IC(),$C=Te(),{promisify:t0}=TC(),{Multiaddr:D5}=qt(),To=Object.assign($C("libp2p:nat"),{error:$C("libp2p:nat:err")}),{isBrowser:HC}=NC(),r0=MC(),L5=bd(),zC=md(),k5=de(),{codes:{ERR_INVALID_PARAMETERS:q5}}=je(),U5=jC(),n0=7200;function M5(t=1024,e=65535){return Math.floor(Math.random()*(e-t+1)+t)}var GC=class{constructor({peerId:e,addressManager:r,transportManager:n,...i}){if(this._peerId=e,this._addressManager=r,this._transportManager=n,this._enabled=i.enabled,this._externalIp=i.externalIp,this._options={description:i.description||`${zC.name}@${zC.version} ${this._peerId}`,ttl:i.ttl||n0,autoUpdate:i.keepAlive||!0,gateway:i.gateway,enablePMP:Boolean(i.pmp&&i.pmp.enabled)},this._options.ttl<n0)throw k5(new Error(`NatManager ttl should be at least ${n0} seconds`),q5)}start(){HC||!this._enabled||this._start().catch(e=>{To.error(e)})}async _start(){let e=this._transportManager.getAddrs();for(let r of e){let{family:n,host:i,port:s,transport:o}=r.toOptions();if(!r.isThinWaistAddress()||o!=="tcp"||U5(r)||n!==4)continue;let a=this._getClient(),c=this._externalIp||await a.externalIp();if(L5(c))throw new Error(`${c} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`);let u=M5();To(`opening uPnP connection from ${c}:${u} to ${i}:${s}`),await a.map({publicPort:u,privatePort:s,protocol:o.toUpperCase()}),this._addressManager.addObservedAddr(D5.fromNodeAddress({family:4,address:c,port:u},o))}}_getClient(){if(this._client)return this._client;let e=new O5(this._options),r=t0(e.map.bind(e)),n=t0(e.destroy.bind(e)),i=t0(e.externalIp.bind(e));return this._client={map:(...s)=>r0(()=>r(...s),{onFailedAttempt:To.error,unref:!0}),destroy:(...s)=>r0(()=>n(...s),{onFailedAttempt:To.error,unref:!0}),externalIp:(...s)=>r0(()=>i(...s),{onFailedAttempt:To.error,unref:!0})},this._client}async stop(){if(!(HC||!this._client))try{await this._client.destroy(),this._client=null}catch(e){To.error(e)}}};WC.exports=GC});var aq=w((a9,eI)=>{"use strict";var QC=Te(),Ft=Object.assign(QC("libp2p"),{error:QC("libp2p:err")}),{EventEmitter:F5}=Qt(),i0=de(),K5=Rt(),{Multiaddr:V5}=qt(),{MemoryDatastore:j5}=(p1(),h1),$5=$1(),H5=Q1(),s0=pd(),{validate:z5}=hE(),{codes:ol,messages:G5}=je(),W5=gE(),Y5=OE(),Q5=FE(),XC=C2(),X5=U2(),Z5=m_(),ZC=gS(),J5=OS(),eq=Td(),tq=yx(),rq=UA(),nq=FA(),iq=YA(),JC=aC(),o0=mC(),a0=CC(),sq=YC(),{updateSelfPeerRecord:oq}=Cd(),$a=class extends F5{static async create(e){if(e.peerId)return new $a(e);let r=await K5.create();return e.peerId=r,new $a(e)}constructor(e){super();if(this._options=z5(e),this.peerId=this._options.peerId,this.datastore=this._options.datastore,this._options.metrics.enabled){let n=new J5({...this._options.metrics});this.metrics=n}if(this.connectionGater={denyDialPeer:async()=>Promise.resolve(!1),denyDialMultiaddr:async()=>Promise.resolve(!1),denyInboundConnection:async()=>Promise.resolve(!1),denyOutboundConnection:async()=>Promise.resolve(!1),denyInboundEncryptedConnection:async()=>Promise.resolve(!1),denyOutboundEncryptedConnection:async()=>Promise.resolve(!1),denyInboundUpgradedConnection:async()=>Promise.resolve(!1),denyOutboundUpgradedConnection:async()=>Promise.resolve(!1),filterMultiaddrForPeer:async()=>Promise.resolve(!0),...this._options.connectionGater},this.peerStore=new rq({peerId:this.peerId,datastore:this.datastore&&this._options.peerStore.persistence?this.datastore:new j5,addressFilter:this.connectionGater.filterMultiaddrForPeer}),this.addresses=this._options.addresses,this.addressManager=new W5(this.peerId,this._options.addresses),this.addressManager.on("change:addresses",()=>{oq(this).catch(n=>{Ft.error("Error updating self peer record",n)})}),this._modules=this._options.modules,this._config=this._options.config,this._transport=[],this._discovery=new Map,this.connectionManager=new Y5(this,{...this._options.connectionManager}),this._autodialler=new Q5(this,{enabled:this._config.peerDiscovery.autoDial,minConnections:this._options.connectionManager.minConnections,autoDialInterval:this._options.connectionManager.autoDialInterval}),this._options.keychain&&this._options.keychain.datastore){Ft("creating keychain");let n=ZC.generateOptions();this.keychain=new ZC(this._options.keychain.datastore,{...n,...this._options.keychain}),Ft("keychain constructed")}if(this.upgrader=new tq({connectionGater:this.connectionGater,localPeer:this.peerId,metrics:this.metrics,onConnection:n=>this.connectionManager.onConnect(n),onConnectionEnd:n=>this.connectionManager.onDisconnect(n)}),this.transportManager=new eq({libp2p:this,upgrader:this.upgrader,faultTolerance:this._options.transportManager.faultTolerance}),this.natManager=new sq({peerId:this.peerId,addressManager:this.addressManager,transportManager:this.transportManager,...this._options.config.nat}),this.registrar=new iq({peerStore:this.peerStore,connectionManager:this.connectionManager}),this.handle=this.handle.bind(this),this.registrar.handle=this.handle,!this._modules.connEncryption||!this._modules.connEncryption.length)throw i0(new Error(G5.CONN_ENCRYPTION_REQUIRED),ol.CONN_ENCRYPTION_REQUIRED);if(this._modules.connEncryption.forEach(n=>{this.upgrader.cryptos.set(n.protocol,n)}),this.dialer=new Z5({transportManager:this.transportManager,connectionGater:this.connectionGater,peerStore:this.peerStore,metrics:this.metrics,...this._options.dialer}),this._modules.transport.forEach(n=>{let i=n.prototype[Symbol.toStringTag],s=this._config.transport[i];this.transportManager.add(i,n,s)}),this._config.relay.enabled&&(this.transportManager.add(XC.prototype[Symbol.toStringTag],XC),this.relay=new X5(this)),this._modules.streamMuxer&&(this._modules.streamMuxer.forEach(i=>{this.upgrader.muxers.set(i.multicodec,i)}),this.identifyService=new JC({libp2p:this})),this._modules.connProtector)this.upgrader.protector=this._modules.connProtector;else if(globalThis.process!==void 0&&globalThis.process.env&&globalThis.process.env.LIBP2P_FORCE_PNET)throw new Error("Private network is enforced, but no protector was provided");if(this._modules.dht){let n=this._modules.dht;this._dht=n.create({libp2p:this,...this._config.dht})}if(this._modules.pubsub){let n=this._modules.pubsub;this.pubsub=nq(n,this,this._config.pubsub)}this.peerRouting=new $5(this),this.contentRouting=new H5(this),this._onDiscoveryPeer=this._onDiscoveryPeer.bind(this),this.fetchService=new o0(this),this.pingService=new a0(this)}emit(e,...r){return e==="error"&&!this._events.error?(Ft.error(r),!1):super.emit(e,...r)}async start(){Ft("libp2p is starting"),this.identifyService&&await this.handle(Object.values(JC.getProtocolStr(this)),this.identifyService.handleMessage),this.fetchService&&await this.handle(o0.PROTOCOL,this.fetchService.handleMessage),this.pingService&&await this.handle(a0.getProtocolStr(this),this.pingService.handleMessage);try{await this._onStarting(),await this._onDidStart(),Ft("libp2p has started")}catch(e){throw this.emit("error",e),Ft.error("An error occurred starting libp2p",e),await this.stop(),e}}async stop(){Ft("libp2p is stopping");try{this._isStarted=!1,this.identifyService&&await this.identifyService.stop(),this.relay&&this.relay.stop(),this.peerRouting.stop(),await this._autodialler.stop(),await(this._dht&&this._dht.stop());for(let e of this._discovery.values())e.removeListener("peer",this._onDiscoveryPeer);await Promise.all(Array.from(this._discovery.values(),e=>e.stop())),this._discovery=new Map,await this.connectionManager.stop(),await Promise.all([this.pubsub&&this.pubsub.stop(),this.metrics&&this.metrics.stop()]),await this.natManager.stop(),await this.transportManager.close(),await this.unhandle(o0.PROTOCOL),await this.unhandle(a0.getProtocolStr(this)),this.dialer.destroy()}catch(e){e&&(Ft.error(e),this.emit("error",e))}Ft("libp2p has stopped")}async loadKeychain(){if(!!this.keychain)try{await this.keychain.findKeyByName("self")}catch(e){await this.keychain.importPeer("self",this.peerId)}}isStarted(){return this._isStarted}get connections(){return this.connectionManager.connections}dial(e,r){return this._dial(e,r)}async dialProtocol(e,r,n){if(!r||!r.length)throw i0(new Error("no protocols were provided to open a stream"),ol.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this._dial(e,n)).newStream(r)}async _dial(e,r){let{id:n,multiaddrs:i}=s0(e);if(n.equals(this.peerId))throw i0(new Error("Cannot dial self"),ol.ERR_DIALED_SELF);let s=this.connectionManager.get(n);return s?i&&await this.peerStore.addressBook.add(n,i):s=await this.dialer.connectToPeer(e,r),s}get multiaddrs(){let e=this.addressManager.getAnnounceAddrs().map(i=>i.toString());e.length||(e=this.transportManager.getAddrs().map(i=>i.toString())),e=e.concat(this.addressManager.getObservedAddrs().map(i=>i.toString()));let r=this._options.addresses.announceFilter,n=new Set(e);return r(Array.from(n).map(i=>new V5(i)))}async hangUp(e){let{id:r}=s0(e),n=this.connectionManager.connections.get(r.toB58String());!n||await Promise.all(n.map(i=>i.close()))}fetch(e,r){return this.fetchService.fetch(e,r)}ping(e){let{id:r,multiaddrs:n}=s0(e);return n?this.pingService.ping(n[0]):this.pingService.ping(r)}async handle(e,r){e=Array.isArray(e)?e:[e],e.forEach(n=>{this.upgrader.protocols.set(n,r)}),await this.peerStore.protoBook.add(this.peerId,e)}async unhandle(e){e=Array.isArray(e)?e:[e],e.forEach(r=>{this.upgrader.protocols.delete(r)}),await this.peerStore.protoBook.remove(this.peerId,e)}async _onStarting(){let e=this.addressManager.getListenAddrs();await this.transportManager.listen(e),this.natManager.start(),this._config.pubsub.enabled&&this.pubsub&&await this.pubsub.start(),this._config.dht.enabled&&(this._dht&&await this._dht.start(),this._dht.on("peer",this._onDiscoveryPeer)),this.metrics&&this.metrics.start(),this.identifyService&&await this.identifyService.start()}async _onDidStart(){this._isStarted=!0,this.peerStore.on("peer",e=>{this.emit("peer:discovery",e),this._maybeConnect(e).catch(r=>{Ft.error(r)})});for await(let e of this.peerStore.getPeers())this.emit("peer:discovery",e.id);this.connectionManager.start(),await this._autodialler.start(),await this._setupPeerDiscovery(),this.relay&&this.relay.start(),this.peerRouting.start()}_onDiscoveryPeer(e){if(e.id.toB58String()===this.peerId.toB58String()){Ft.error(new Error(ol.ERR_DISCOVERED_SELF));return}e.multiaddrs&&this.peerStore.addressBook.add(e.id,e.multiaddrs).catch(r=>Ft.error(r)),e.protocols&&this.peerStore.protoBook.set(e.id,e.protocols).catch(r=>Ft.error(r))}async _maybeConnect(e){if(this._config.peerDiscovery.autoDial===!0&&!this.connectionManager.get(e)&&(this._options.connectionManager.minConnections||0)>this.connectionManager.size){Ft("connecting to discovered peer %s",e.toB58String());try{await this.dialer.connectToPeer(e)}catch(n){Ft.error(`could not connect to discovered peer ${e.toB58String()} with ${n}`)}}}async _setupPeerDiscovery(){let e=r=>{let n={enabled:!0};if(r.tag&&this._config.peerDiscovery&&this._config.peerDiscovery[r.tag]&&(n={...n,...this._config.peerDiscovery[r.tag]}),n.enabled&&!this._discovery.has(r.tag)){let i;typeof r=="function"?i=new r(Object.assign({},n,{peerId:this.peerId,libp2p:this})):i=r,i.on("peer",this._onDiscoveryPeer),this._discovery.set(r.tag,i)}};for(let r of this._modules.peerDiscovery||[])e(r);for(let r of this.transportManager.getTransports())r.discovery&&e(r.discovery);await Promise.all(Array.from(this._discovery.values(),r=>r.start()))}};eI.exports=$a});return aq();})();
45
+ `);function Ch(t){return LS.encode.single(new DS([t,kS]))}function qk(t,e){t.push(Ch(e))}async function Uk(t,e){t.push(e.reduce((r,n)=>r.append(Ch(n)),new DS))}async function Mk(t,e){let r=1,n={[Symbol.asyncIterator](){return this},next:()=>t.next(r)},i=n;e&&e.signal&&(i=kk(n,e.signal));let s=a=>{r=a},o=await Nk(i,LS.decode({onLength:s}),Lk);if(o.get(o.length-1)!==kS[0])throw Ok(new Error("missing newline"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.shallowSlice(0,-1)}qS.exports={encode:Ch,write:qk,writeAll:Uk,read:Mk}});var FS=w((oV,MS)=>{"use strict";var US=Te(),Fk=de(),go=Mu(),Kk=oo(),mo=Object.assign(US("mss:select"),{error:US("mss:select:error")});MS.exports=async function(e,r,n,i){r=Array.isArray(r)?[...r]:[r];let{reader:s,writer:o,rest:a,stream:c}=Kk(e),u=r.shift();if(!u)throw new Error("At least one protocol must be specified");n?(mo('select: write ["%s", "%s"]',n,u),go.writeAll(o,[n,u])):(mo('select: write "%s"',u),go.write(o,u));let l=(await go.read(s,i)).toString();if(mo('select: read "%s"',l),l===n&&(l=(await go.read(s,i)).toString(),mo('select: read "%s"',l)),l===u)return a(),{stream:c,protocol:u};for(let f of r){mo('select: write "%s"',f),go.write(o,f);let d=(await go.read(s,i)).toString();if(mo('select: read "%s" for "%s"',d,f),d===f)return a(),{stream:c,protocol:f}}throw a(),Fk(new Error("protocol selection failed"),"ERR_UNSUPPORTED_PROTOCOL")}});var Ih=w(KS=>{"use strict";KS.PROTOCOL_ID="/multistream/1.0.0"});var $S=w((cV,jS)=>{"use strict";var VS=Te(),Vk=Ji(),vo=Mu(),jk=oo(),{PROTOCOL_ID:Th}=Ih(),ka=Object.assign(VS("mss:handle"),{error:VS("mss:handle:error")});jS.exports=async function(e,r,n){r=Array.isArray(r)?r:[r];let{writer:i,reader:s,rest:o,stream:a}=jk(e);for(;;){let c=(await vo.read(s,n)).toString();if(ka('read "%s"',c),c===Th){ka('respond with "%s" for "%s"',Th,c),vo.write(i,Th);continue}if(r.includes(c))return vo.write(i,c),ka('respond with "%s" for "%s"',c,c),o(),{stream:a,protocol:c};if(c==="ls"){vo.write(i,new Vk(r.map(u=>vo.encode(u)))),ka('respond with "%s" for %s',r,c);continue}vo.write(i,"na"),ka('respond with "na" for "%s"',c)}}});var WS=w((uV,GS)=>{"use strict";var $k=th(),HS=Te(),zS=Mu(),Hk=oo(),zk=so(),{pipe:Gk}=ir(),Wk=Object.assign(HS("mss:ls"),{error:HS("mss:ls:error")});GS.exports=async function(e,r){let{reader:n,writer:i,rest:s,stream:o}=Hk(e);Wk('write "ls"'),zS.write(i,"ls"),s();let a=await zS.read(n,r),c=$k([a]),u=[];return await Gk(c,zk.decode(),async f=>{for await(let d of f)u.push(d.shallowSlice(0,-1).toString())}),{stream:o,protocols:u}}});var ZS=w(Fu=>{"use strict";var YS=FS(),Yk=$S(),Qk=WS(),{PROTOCOL_ID:Rh}=Ih();Fu.PROTOCOL_ID=Rh;var Bh=class{constructor(e){this._stream=e,this._shaken=!1}async _handshake(e){if(this._shaken)return;let{stream:r}=await YS(this._stream,Rh,void 0,e);this._stream=r,this._shaken=!0}},QS=class extends Bh{select(e,r){return YS(this._stream,e,this._shaken?void 0:Rh,r)}async ls(e){await this._handshake(e);let r=await Qk(this._stream,e),{stream:n,protocols:i}=r;return this._stream=n,i}};Fu.Dialer=QS;var XS=class extends Bh{handle(e,r){return Yk(this._stream,e,r)}};Fu.Listener=XS});var ex=w((fV,JS)=>{"use strict";var Xk={OPEN:"open",CLOSING:"closing",CLOSED:"closed"};JS.exports=Xk});var ox=w((dV,sx)=>{"use strict";var tx=Rt(),{Multiaddr:Zk}=qt(),or=de(),{OPEN:Jk,CLOSING:rx,CLOSED:Ph}=ex(),nx=Symbol.for("@libp2p/interface-connection/connection"),ix=class{constructor({localAddr:e,remoteAddr:r,localPeer:n,remotePeer:i,newStream:s,close:o,getStreams:a,stat:c}){e6(e,n,i,s,o,a,c),this.id=parseInt(String(Math.random()*1e9)).toString(36)+Date.now(),this.localAddr=e,this.remoteAddr=r,this.localPeer=n,this.remotePeer=i,this._stat={...c,status:Jk},this._newStream=s,this._close=o,this._getStreams=a,this.registry=new Map,this.tags=[]}get[Symbol.toStringTag](){return"Connection"}get[nx](){return!0}static isConnection(e){return Boolean(e&&e[nx])}get stat(){return this._stat}get streams(){return this._getStreams()}async newStream(e){if(this.stat.status===rx)throw or(new Error("the connection is being closed"),"ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===Ph)throw or(new Error("the connection is closed"),"ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let{stream:r,protocol:n}=await this._newStream(e);return this.addStream(r,{protocol:n}),{stream:r,protocol:n}}addStream(e,{protocol:r,metadata:n={}}){this.registry.set(e.id,{protocol:r,...n})}removeStream(e){this.registry.delete(e)}async close(){if(this.stat.status!==Ph){if(this._closing)return this._closing;this.stat.status=rx,this._closing=await this._close(),this._stat.timeline.close=Date.now(),this.stat.status=Ph}}};sx.exports=ix;function e6(t,e,r,n,i,s,o){if(t&&!Zk.isMultiaddr(t))throw or(new Error("localAddr must be an instance of multiaddr"),"ERR_INVALID_PARAMETERS");if(!tx.isPeerId(e))throw or(new Error("localPeer must be an instance of peer-id"),"ERR_INVALID_PARAMETERS");if(!tx.isPeerId(r))throw or(new Error("remotePeer must be an instance of peer-id"),"ERR_INVALID_PARAMETERS");if(typeof n!="function")throw or(new Error("new stream must be a function"),"ERR_INVALID_PARAMETERS");if(typeof i!="function")throw or(new Error("close must be a function"),"ERR_INVALID_PARAMETERS");if(typeof s!="function")throw or(new Error("getStreams must be a function"),"ERR_INVALID_PARAMETERS");if(!o)throw or(new Error("connection metadata object must be provided"),"ERR_INVALID_PARAMETERS");if(o.direction!=="inbound"&&o.direction!=="outbound")throw or(new Error('direction must be "inbound" or "outbound"'),"ERR_INVALID_PARAMETERS");if(!o.timeline)throw or(new Error("connection timeline object must be provided in the stat object"),"ERR_INVALID_PARAMETERS");if(!o.timeline.open)throw or(new Error("connection open timestamp must be provided"),"ERR_INVALID_PARAMETERS");if(!o.timeline.upgraded)throw or(new Error("connection upgraded timestamp must be provided"),"ERR_INVALID_PARAMETERS")}});var cx=w(ax=>{"use strict";ax.Connection=ox()});var lx=w((pV,ux)=>{"use strict";function t6(t){if(Array.isArray(t)){for(var e=0,r=Array(t.length);e<t.length;e++)r[e]=t[e];return r}else return Array.from(t)}ux.exports=function(e){var r=void 0,n=void 0;function i(a){if(!(a instanceof Object))throw new Error('Target "'+a+'" is not an object');n=a}function s(a){Object.keys(a).forEach(function(c){var u=a[c];if(typeof u!="function")throw new Error('Trap "'+c+": "+u+'" is not a function');if(!Reflect[c])throw new Error('Trap "'+c+": "+u+'" is not a valid trap')}),r=a}i(function(){}),e&&i(e),s(Reflect);var o=new Proxy({},{get:function(c,u){return function(){for(var l=arguments.length,f=Array(l),d=0;d<l;d++)f[d]=arguments[d];return r[u].apply(null,[n].concat(t6(f.slice(1))))}}});return{setTarget:i,setHandler:s,getTarget:function(){return n},getHandler:function(){return r},proxy:new Proxy(n,o)}}});var yx=w((yV,px)=>{"use strict";var fx=Te(),vt=Object.assign(fx("libp2p:upgrader"),{error:fx("libp2p:upgrader:err")}),ar=de(),bo=ZS(),{Connection:r6}=cx(),n6=Rt(),{pipe:i6}=ir(),dx=lx(),{codes:cr}=je(),hx=class{constructor({localPeer:e,metrics:r,connectionGater:n,cryptos:i=new Map,muxers:s=new Map,onConnectionEnd:o=()=>{},onConnection:a=()=>{}}){this.connectionGater=n,this.localPeer=e,this.metrics=r,this.cryptos=i,this.muxers=s,this.protector=null,this.protocols=new Map,this.onConnection=a,this.onConnectionEnd=o}async upgradeInbound(e){let r,n,i,s,o,a,c;if(await this.connectionGater.denyInboundConnection(e))throw ar(new Error("The multiaddr connection is blocked by gater.acceptConnection"),cr.ERR_CONNECTION_INTERCEPTED);if(this.metrics){({setTarget:a,proxy:c}=dx());let l=(Math.random()*1e9).toString(36)+Date.now();a({toB58String:()=>l}),e=this.metrics.trackStream({stream:e,remotePeer:c})}vt("Starting the inbound connection upgrade");let u=e;this.protector&&(u=await this.protector.protect(e));try{if({conn:r,remotePeer:n,protocol:o}=await this._encryptInbound(this.localPeer,u,this.cryptos),await this.connectionGater.denyInboundEncryptedConnection(n,r))throw ar(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),cr.ERR_CONNECTION_INTERCEPTED);this.muxers.size?{stream:i,Muxer:s}=await this._multiplexInbound(r,this.muxers):i=r}catch(l){throw vt.error("Failed to upgrade inbound connection",l),await e.close(l),l}if(await this.connectionGater.denyInboundUpgradedConnection(n,r))throw ar(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),cr.ERR_CONNECTION_INTERCEPTED);return this.metrics&&(this.metrics.updatePlaceholder(c,n),a(n)),vt("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:o,direction:"inbound",maConn:e,upgradedConn:i,Muxer:s,remotePeer:n})}async upgradeOutbound(e){let r=e.remoteAddr.getPeerId();if(!r)throw ar(new Error("outbound connection must have a peer id"),cr.ERR_INVALID_MULTIADDR);let n=n6.createFromB58String(r);if(await this.connectionGater.denyOutboundConnection(n,e))throw ar(new Error("The multiaddr connection is blocked by connectionGater.denyOutboundConnection"),cr.ERR_CONNECTION_INTERCEPTED);let i,s,o,a,c,u,l;if(this.metrics){({setTarget:u,proxy:l}=dx());let d=(Math.random()*1e9).toString(36)+Date.now();u({toB58String:()=>d}),e=this.metrics.trackStream({stream:e,remotePeer:l})}vt("Starting the outbound connection upgrade");let f=e;this.protector&&(f=await this.protector.protect(e));try{if({conn:i,remotePeer:s,protocol:a}=await this._encryptOutbound(this.localPeer,f,n,this.cryptos),await this.connectionGater.denyOutboundEncryptedConnection(s,i))throw ar(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),cr.ERR_CONNECTION_INTERCEPTED);this.muxers.size?{stream:o,Muxer:c}=await this._multiplexOutbound(i,this.muxers):o=i}catch(d){throw vt.error("Failed to upgrade outbound connection",d),await e.close(d),d}if(await this.connectionGater.denyOutboundUpgradedConnection(s,i))throw ar(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),cr.ERR_CONNECTION_INTERCEPTED);return this.metrics&&(this.metrics.updatePlaceholder(l,s),u(s)),vt("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:a,direction:"outbound",maConn:e,upgradedConn:o,Muxer:c,remotePeer:s})}_createConnection({cryptoProtocol:e,direction:r,maConn:n,upgradedConn:i,Muxer:s,remotePeer:o}){let a,c,u;s&&(a=new s({onStream:async d=>{if(!u)return;let p=new bo.Listener(d);try{let{stream:h,protocol:g}=await p.handle(Array.from(this.protocols.keys()));vt("%s: incoming stream opened on %s",r,g),this.metrics&&this.metrics.trackStream({stream:h,remotePeer:o,protocol:g}),u.addStream(d,{protocol:g}),this._onStream({connection:u,stream:{...d,...h},protocol:g})}catch(h){vt.error(h)}},onStreamEnd:d=>{u.removeStream(d.id)}}),c=async d=>{vt("%s: starting new stream on %s",r,d);let p=a.newStream(),h=new bo.Dialer(p);try{let{stream:g,protocol:m}=await h.select(d);return this.metrics&&this.metrics.trackStream({stream:g,remotePeer:o,protocol:m}),{stream:{...p,...g},protocol:m}}catch(g){throw vt.error("could not create new stream",g),ar(g,cr.ERR_UNSUPPORTED_PROTOCOL)}},i6(i,a,i).catch(vt.error));let l=n.timeline;n.timeline=new Proxy(l,{set:(...d)=>(u&&d[1]==="close"&&d[2]&&!l.close&&(async()=>{try{u.stat.status==="open"&&await u.close()}catch(p){vt.error(p)}finally{this.onConnectionEnd(u)}})().catch(p=>{vt.error(p)}),Reflect.set(...d))}),n.timeline.upgraded=Date.now();let f=()=>{throw ar(new Error("connection is not multiplexed"),cr.ERR_CONNECTION_NOT_MULTIPLEXED)};return u=new r6({localAddr:n.localAddr,remoteAddr:n.remoteAddr,localPeer:this.localPeer,remotePeer:o,stat:{direction:r,timeline:n.timeline,multiplexer:s&&s.multicodec,encryption:e},newStream:c||f,getStreams:()=>a?a.streams:f(),close:async()=>{await n.close(),a&&a.streams.map(d=>d.abort())}}),this.onConnection(u),u}_onStream({connection:e,stream:r,protocol:n}){this.protocols.get(n)({connection:e,stream:r,protocol:n})}async _encryptInbound(e,r,n){let i=new bo.Listener(r),s=Array.from(n.keys());vt("handling inbound crypto protocol selection",s);try{let{stream:o,protocol:a}=await i.handle(s),c=n.get(a);if(vt("encrypting inbound connection..."),!c)throw new Error(`no crypto module found for ${a}`);return{...await c.secureInbound(e,o),protocol:a}}catch(o){throw ar(o,cr.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r,n,i){let s=new bo.Dialer(r),o=Array.from(i.keys());vt("selecting outbound crypto protocol",o);try{let{stream:a,protocol:c}=await s.select(o),u=i.get(c);if(vt("encrypting outbound connection to %j",n),!u)throw new Error(`no crypto module found for ${c}`);return{...await u.secureOutbound(e,a,n),protocol:c}}catch(a){throw ar(a,cr.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=new bo.Dialer(e),i=Array.from(r.keys());vt("outbound selecting muxer %s",i);try{let{stream:s,protocol:o}=await n.select(i);vt("%s selected as muxer protocol",o);let a=r.get(o);return{stream:s,Muxer:a}}catch(s){throw ar(s,cr.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=new bo.Listener(e),i=Array.from(r.keys());vt("inbound handling muxers %s",i);try{let{stream:s,protocol:o}=await n.handle(i),a=r.get(o);return{stream:s,Muxer:a}}catch(s){throw ar(s,cr.ERR_MUXER_UNAVAILABLE)}}};px.exports=hx});var mx=w((gV,gx)=>{"use strict";var s6=async function*(t,e){for await(let r of t)await e(r),yield r};gx.exports=s6});var xx=w((mV,Sx)=>{"use strict";var vx=Te(),os=de(),{Multiaddr:bx}=qt(),Ku=Rt(),{codes:Kr}=je(),Ex=pu(),wx=du(),{pipe:o6}=ir(),a6=Mi(),c6=Fi(),u6=id(),l6=mx(),ke=Object.assign(vx("libp2p:peer-store:address-book"),{error:vx("libp2p:peer-store:address-book:err")}),Vu="change:multiaddrs",_x=class{constructor(e,r,n){this._emit=e,this._store=r,this._addressFilter=n}async consumePeerRecord(e){ke("consumePeerRecord await write lock");let r=await this._store.lock.writeLock();ke("consumePeerRecord got write lock");let n,i;try{let s;try{s=Ex.createFromProtobuf(e.payload)}catch(a){return ke.error("invalid peer record received"),!1}n=s.peerId;let o=s.multiaddrs;if(!n.equals(e.peerId))return ke("signing key does not match PeerId in the PeerRecord"),!1;if(!o||!o.length)return!1;if(await this._store.has(n)){let a=await this._store.load(n);if(a.peerRecordEnvelope){let c=await wx.createFromProtobuf(a.peerRecordEnvelope);if(Ex.createFromProtobuf(c.payload).seqNumber>=s.seqNumber)return!1}}i=await this._store.patchOrCreate(n,{addresses:await Nh(n,o,this._addressFilter,!0),peerRecordEnvelope:e.marshal()}),ke(`stored provided peer record for ${s.peerId.toB58String()}`)}finally{ke("consumePeerRecord release write lock"),r()}return this._emit(Vu,{peerId:n,multiaddrs:i.addresses.map(({multiaddr:s})=>s)}),!0}async getRawEnvelope(e){ke("getRawEnvelope await read lock");let r=await this._store.lock.readLock();ke("getRawEnvelope got read lock");try{return(await this._store.load(e)).peerRecordEnvelope}catch(n){if(n.code!==Kr.ERR_NOT_FOUND)throw n}finally{ke("getRawEnvelope release read lock"),r()}}async getPeerRecord(e){let r=await this.getRawEnvelope(e);if(!!r)return wx.createFromProtobuf(r)}async get(e){if(!Ku.isPeerId(e))throw ke.error("peerId must be an instance of peer-id to store data"),os(new Error("peerId must be an instance of peer-id"),Kr.ERR_INVALID_PARAMETERS);ke("get wait for read lock");let r=await this._store.lock.readLock();ke("get got read lock");try{return(await this._store.load(e)).addresses}catch(n){if(n.code!==Kr.ERR_NOT_FOUND)throw n}finally{ke("get release read lock"),r()}return[]}async set(e,r){if(!Ku.isPeerId(e))throw ke.error("peerId must be an instance of peer-id to store data"),os(new Error("peerId must be an instance of peer-id"),Kr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ke.error("multiaddrs must be an array of Multiaddrs"),os(new Error("multiaddrs must be an array of Multiaddrs"),Kr.ERR_INVALID_PARAMETERS);ke("set await write lock");let n=await this._store.lock.writeLock();ke("set got write lock");let i=!1,s;try{let o=await Nh(e,r,this._addressFilter);if(!o.length)return;try{let a=await this._store.load(e);if(i=!0,new Set([...o.map(({multiaddr:c})=>c.toString()),...a.addresses.map(({multiaddr:c})=>c.toString())]).size===a.addresses.length&&o.length===a.addresses.length)return}catch(a){if(a.code!==Kr.ERR_NOT_FOUND)throw a}s=await this._store.patchOrCreate(e,{addresses:o}),ke(`set multiaddrs for ${e.toB58String()}`)}finally{ke("set release write lock"),n()}this._emit(Vu,{peerId:e,multiaddrs:s.addresses.map(o=>o.multiaddr)}),i||this._emit("peer",e)}async add(e,r){if(!Ku.isPeerId(e))throw ke.error("peerId must be an instance of peer-id to store data"),os(new Error("peerId must be an instance of peer-id"),Kr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ke.error("multiaddrs must be an array of Multiaddrs"),os(new Error("multiaddrs must be an array of Multiaddrs"),Kr.ERR_INVALID_PARAMETERS);ke("add await write lock");let n=await this._store.lock.writeLock();ke("add got write lock");let i,s;try{let o=await Nh(e,r,this._addressFilter);if(!o.length)return;try{let a=await this._store.load(e);if(i=!0,new Set([...o.map(({multiaddr:c})=>c.toString()),...a.addresses.map(({multiaddr:c})=>c.toString())]).size===a.addresses.length)return}catch(a){if(a.code!==Kr.ERR_NOT_FOUND)throw a}s=await this._store.mergeOrCreate(e,{addresses:o}),ke(`added multiaddrs for ${e.toB58String()}`)}finally{ke("set release write lock"),n()}this._emit(Vu,{peerId:e,multiaddrs:s.addresses.map(o=>o.multiaddr)}),i||this._emit("peer",e)}async delete(e){if(!Ku.isPeerId(e))throw ke.error("peerId must be an instance of peer-id to store data"),os(new Error("peerId must be an instance of peer-id"),Kr.ERR_INVALID_PARAMETERS);ke("delete await write lock");let r=await this._store.lock.writeLock();ke("delete got write lock");let n;try{n=await this._store.has(e),await this._store.patchOrCreate(e,{addresses:[]})}finally{ke("delete release write lock"),r()}n&&this._emit(Vu,{peerId:e,multiaddrs:[]})}async getMultiaddrsForPeer(e,r=n=>n){let n=await this.get(e);return r(n).map(i=>{let s=i.multiaddr,o=s.getPeerId();return o&&o===e.toB58String()?s:s.encapsulate(`/p2p/${e.toB58String()}`)})}};function Nh(t,e,r,n=!1){return o6(e,i=>l6(i,s=>{if(!bx.isMultiaddr(s))throw ke.error("multiaddr must be an instance of Multiaddr"),os(new Error("multiaddr must be an instance of Multiaddr"),Kr.ERR_INVALID_PARAMETERS)}),i=>c6(i,s=>r(t,s)),i=>u6(i,s=>({multiaddr:new bx(s.toString()),isCertified:n})),i=>a6(i))}Sx.exports=_x});var Rx=w((vV,Tx)=>{"use strict";var Ax=Te(),ju=de(),{codes:Eo}=je(),Oh=Rt(),{equals:f6}=(mr(),gr),ur=Object.assign(Ax("libp2p:peer-store:key-book"),{error:Ax("libp2p:peer-store:key-book:err")}),Cx="change:pubkey",Ix=class{constructor(e,r){this._emit=e,this._store=r}async set(e,r){if(!Oh.isPeerId(e))throw ur.error("peerId must be an instance of peer-id to store data"),ju(new Error("peerId must be an instance of peer-id"),Eo.ERR_INVALID_PARAMETERS);if(!r)throw ur.error("publicKey must be an instance of PublicKey to store data"),ju(new Error("publicKey must be an instance of PublicKey"),Eo.ERR_INVALID_PARAMETERS);ur("set await write lock");let n=await this._store.lock.writeLock();ur("set got write lock");let i=!1;try{try{let s=await this._store.load(e);if(s.pubKey&&f6(s.pubKey.bytes,r.bytes))return}catch(s){if(s.code!==Eo.ERR_NOT_FOUND)throw s}await this._store.patchOrCreate(e,{pubKey:r}),i=!0}finally{ur("set release write lock"),n()}i&&this._emit(Cx,{peerId:e,pubKey:r})}async get(e){if(!Oh.isPeerId(e))throw ur.error("peerId must be an instance of peer-id to store data"),ju(new Error("peerId must be an instance of peer-id"),Eo.ERR_INVALID_PARAMETERS);ur("get await write lock");let r=await this._store.lock.readLock();ur("get got write lock");try{return(await this._store.load(e)).pubKey}catch(n){if(n.code!==Eo.ERR_NOT_FOUND)throw n}finally{ur("get release write lock"),r()}}async delete(e){if(!Oh.isPeerId(e))throw ur.error("peerId must be an instance of peer-id to store data"),ju(new Error("peerId must be an instance of peer-id"),Eo.ERR_INVALID_PARAMETERS);ur("delete await write lock");let r=await this._store.lock.writeLock();ur("delete got write lock");try{await this._store.patchOrCreate(e,{pubKey:void 0})}finally{ur("delete release write lock"),r()}this._emit(Cx,{peerId:e,pubKey:void 0})}};Tx.exports=Ix});var Ox=w((bV,Nx)=>{"use strict";var Bx=Te(),pi=de(),{codes:Tr}=je(),wo=Rt(),{equals:d6}=(mr(),gr),We=Object.assign(Bx("libp2p:peer-store:metadata-book"),{error:Bx("libp2p:peer-store:metadata-book:err")}),$u="change:metadata",Px=class{constructor(e,r){this._emit=e,this._store=r}async get(e){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);We("get await read lock");let r=await this._store.lock.readLock();We("get got read lock");try{return(await this._store.load(e)).metadata}catch(n){if(n.code!==Tr.ERR_NOT_FOUND)throw n}finally{We("get release read lock"),r()}return new Map}async getValue(e,r){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);We("getValue await read lock");let n=await this._store.lock.readLock();We("getValue got read lock");try{return(await this._store.load(e)).metadata.get(r)}catch(i){if(i.code!==Tr.ERR_NOT_FOUND)throw i}finally{We("getValue release write lock"),n()}}async set(e,r){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);if(!r||!(r instanceof Map))throw We.error("valid metadata must be provided to store data"),pi(new Error("valid metadata must be provided"),Tr.ERR_INVALID_PARAMETERS);We("set await write lock");let n=await this._store.lock.writeLock();We("set got write lock");try{await this._store.mergeOrCreate(e,{metadata:r})}finally{We("set release write lock"),n()}this._emit($u,{peerId:e,metadata:r})}async setValue(e,r,n){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);if(typeof r!="string"||!(n instanceof Uint8Array))throw We.error("valid key and value must be provided to store data"),pi(new Error("valid key and value must be provided"),Tr.ERR_INVALID_PARAMETERS);We("setValue await write lock");let i=await this._store.lock.writeLock();We("setValue got write lock");let s;try{try{let a=(await this._store.load(e)).metadata.get(r);if(a!=null&&d6(n,a))return}catch(o){if(o.code!==Tr.ERR_NOT_FOUND)throw o}s=await this._store.mergeOrCreate(e,{metadata:new Map([[r,n]])})}finally{We("setValue release write lock"),i()}this._emit($u,{peerId:e,metadata:s.metadata})}async delete(e){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);We("delete await write lock");let r=await this._store.lock.writeLock();We("delete got write lock");let n;try{n=await this._store.has(e),n&&await this._store.patch(e,{metadata:new Map})}finally{We("delete release write lock"),r()}n&&this._emit($u,{peerId:e,metadata:new Map})}async deleteValue(e,r){if(!wo.isPeerId(e))throw We.error("peerId must be an instance of peer-id to store data"),pi(new Error("peerId must be an instance of peer-id"),Tr.ERR_INVALID_PARAMETERS);We("deleteValue await write lock");let n=await this._store.lock.writeLock();We("deleteValue got write lock");let i;try{i=(await this._store.load(e)).metadata,i.delete(r),await this._store.patch(e,{metadata:i})}catch(s){if(s.code!==Tr.ERR_NOT_FOUND)throw s}finally{We("deleteValue release write lock"),n()}i&&this._emit($u,{peerId:e,metadata:i})}};Nx.exports=Px});var qx=w((EV,kx)=>{"use strict";var Dx=Te(),_o=de(),{codes:Vr}=je(),Dh=Rt(),ot=Object.assign(Dx("libp2p:peer-store:proto-book"),{error:Dx("libp2p:peer-store:proto-book:err")}),Hu="change:protocols",Lx=class{constructor(e,r){this._emit=e,this._store=r}async get(e){ot("get wait for read lock");let r=await this._store.lock.readLock();ot("get got read lock");try{return(await this._store.load(e)).protocols}catch(n){if(n.code!==Vr.ERR_NOT_FOUND)throw n}finally{ot("get release read lock"),r()}return[]}async set(e,r){if(!Dh.isPeerId(e))throw ot.error("peerId must be an instance of peer-id to store data"),_o(new Error("peerId must be an instance of peer-id"),Vr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ot.error("protocols must be provided to store data"),_o(new Error("protocols must be provided"),Vr.ERR_INVALID_PARAMETERS);ot("set await write lock");let n=await this._store.lock.writeLock();ot("set got write lock");let i;try{try{let s=await this._store.load(e);if(new Set([...r]).size===s.protocols.length)return}catch(s){if(s.code!==Vr.ERR_NOT_FOUND)throw s}i=await this._store.patchOrCreate(e,{protocols:r}),ot(`stored provided protocols for ${e.toB58String()}`)}finally{ot("set release write lock"),n()}this._emit(Hu,{peerId:e,protocols:i.protocols})}async add(e,r){if(!Dh.isPeerId(e))throw ot.error("peerId must be an instance of peer-id to store data"),_o(new Error("peerId must be an instance of peer-id"),Vr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ot.error("protocols must be provided to store data"),_o(new Error("protocols must be provided"),Vr.ERR_INVALID_PARAMETERS);ot("add await write lock");let n=await this._store.lock.writeLock();ot("add got write lock");let i;try{try{let s=await this._store.load(e);if(new Set([...s.protocols,...r]).size===s.protocols.length)return}catch(s){if(s.code!==Vr.ERR_NOT_FOUND)throw s}i=await this._store.mergeOrCreate(e,{protocols:r}),ot(`added provided protocols for ${e.toB58String()}`)}finally{ot("add release write lock"),n()}this._emit(Hu,{peerId:e,protocols:i.protocols})}async remove(e,r){if(!Dh.isPeerId(e))throw ot.error("peerId must be an instance of peer-id to store data"),_o(new Error("peerId must be an instance of peer-id"),Vr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ot.error("protocols must be provided to store data"),_o(new Error("protocols must be provided"),Vr.ERR_INVALID_PARAMETERS);ot("remove await write lock");let n=await this._store.lock.writeLock();ot("remove got write lock");let i;try{try{let s=await this._store.load(e),o=new Set(s.protocols);for(let a of r)o.delete(a);if(s.protocols.length===o.size)return;r=Array.from(o)}catch(s){if(s.code!==Vr.ERR_NOT_FOUND)throw s}i=await this._store.patchOrCreate(e,{protocols:r})}finally{ot("remove release write lock"),n()}this._emit(Hu,{peerId:e,protocols:i.protocols})}async delete(e){ot("delete await write lock");let r=await this._store.lock.writeLock();ot("delete got write lock");let n;try{n=await this._store.has(e),await this._store.patchOrCreate(e,{protocols:[]})}catch(i){if(i.code!==Vr.ERR_NOT_FOUND)throw i}finally{ot("delete release write lock"),r()}n&&this._emit(Hu,{peerId:e,protocols:[]})}};kx.exports=Lx});var Mx=w((wV,Ux)=>{"use strict";var yi=gn(),So=yi.Reader,Lh=yi.Writer,Me=yi.util,yt=yi.roots["libp2p-peer"]||(yi.roots["libp2p-peer"]={});yt.Peer=function(){function t(r){if(this.addresses=[],this.protocols=[],this.metadata=[],r)for(var n=Object.keys(r),i=0;i<n.length;++i)r[n[i]]!=null&&(this[n[i]]=r[n[i]])}t.prototype.addresses=Me.emptyArray,t.prototype.protocols=Me.emptyArray,t.prototype.metadata=Me.emptyArray,t.prototype.pubKey=null,t.prototype.peerRecordEnvelope=null;var e;return Object.defineProperty(t.prototype,"_pubKey",{get:Me.oneOfGetter(e=["pubKey"]),set:Me.oneOfSetter(e)}),Object.defineProperty(t.prototype,"_peerRecordEnvelope",{get:Me.oneOfGetter(e=["peerRecordEnvelope"]),set:Me.oneOfSetter(e)}),t.encode=function(n,i){if(i||(i=Lh.create()),n.addresses!=null&&n.addresses.length)for(var s=0;s<n.addresses.length;++s)yt.Address.encode(n.addresses[s],i.uint32(10).fork()).ldelim();if(n.protocols!=null&&n.protocols.length)for(var s=0;s<n.protocols.length;++s)i.uint32(18).string(n.protocols[s]);if(n.metadata!=null&&n.metadata.length)for(var s=0;s<n.metadata.length;++s)yt.Metadata.encode(n.metadata[s],i.uint32(26).fork()).ldelim();return n.pubKey!=null&&Object.hasOwnProperty.call(n,"pubKey")&&i.uint32(34).bytes(n.pubKey),n.peerRecordEnvelope!=null&&Object.hasOwnProperty.call(n,"peerRecordEnvelope")&&i.uint32(42).bytes(n.peerRecordEnvelope),i},t.decode=function(n,i){n instanceof So||(n=So.create(n));for(var s=i===void 0?n.len:n.pos+i,o=new yt.Peer;n.pos<s;){var a=n.uint32();switch(a>>>3){case 1:o.addresses&&o.addresses.length||(o.addresses=[]),o.addresses.push(yt.Address.decode(n,n.uint32()));break;case 2:o.protocols&&o.protocols.length||(o.protocols=[]),o.protocols.push(n.string());break;case 3:o.metadata&&o.metadata.length||(o.metadata=[]),o.metadata.push(yt.Metadata.decode(n,n.uint32()));break;case 4:o.pubKey=n.bytes();break;case 5:o.peerRecordEnvelope=n.bytes();break;default:n.skipType(a&7);break}}return o},t.fromObject=function(n){if(n instanceof yt.Peer)return n;var i=new yt.Peer;if(n.addresses){if(!Array.isArray(n.addresses))throw TypeError(".Peer.addresses: array expected");i.addresses=[];for(var s=0;s<n.addresses.length;++s){if(typeof n.addresses[s]!="object")throw TypeError(".Peer.addresses: object expected");i.addresses[s]=yt.Address.fromObject(n.addresses[s])}}if(n.protocols){if(!Array.isArray(n.protocols))throw TypeError(".Peer.protocols: array expected");i.protocols=[];for(var s=0;s<n.protocols.length;++s)i.protocols[s]=String(n.protocols[s])}if(n.metadata){if(!Array.isArray(n.metadata))throw TypeError(".Peer.metadata: array expected");i.metadata=[];for(var s=0;s<n.metadata.length;++s){if(typeof n.metadata[s]!="object")throw TypeError(".Peer.metadata: object expected");i.metadata[s]=yt.Metadata.fromObject(n.metadata[s])}}return n.pubKey!=null&&(typeof n.pubKey=="string"?Me.base64.decode(n.pubKey,i.pubKey=Me.newBuffer(Me.base64.length(n.pubKey)),0):n.pubKey.length&&(i.pubKey=n.pubKey)),n.peerRecordEnvelope!=null&&(typeof n.peerRecordEnvelope=="string"?Me.base64.decode(n.peerRecordEnvelope,i.peerRecordEnvelope=Me.newBuffer(Me.base64.length(n.peerRecordEnvelope)),0):n.peerRecordEnvelope.length&&(i.peerRecordEnvelope=n.peerRecordEnvelope)),i},t.toObject=function(n,i){i||(i={});var s={};if((i.arrays||i.defaults)&&(s.addresses=[],s.protocols=[],s.metadata=[]),n.addresses&&n.addresses.length){s.addresses=[];for(var o=0;o<n.addresses.length;++o)s.addresses[o]=yt.Address.toObject(n.addresses[o],i)}if(n.protocols&&n.protocols.length){s.protocols=[];for(var o=0;o<n.protocols.length;++o)s.protocols[o]=n.protocols[o]}if(n.metadata&&n.metadata.length){s.metadata=[];for(var o=0;o<n.metadata.length;++o)s.metadata[o]=yt.Metadata.toObject(n.metadata[o],i)}return n.pubKey!=null&&n.hasOwnProperty("pubKey")&&(s.pubKey=i.bytes===String?Me.base64.encode(n.pubKey,0,n.pubKey.length):i.bytes===Array?Array.prototype.slice.call(n.pubKey):n.pubKey,i.oneofs&&(s._pubKey="pubKey")),n.peerRecordEnvelope!=null&&n.hasOwnProperty("peerRecordEnvelope")&&(s.peerRecordEnvelope=i.bytes===String?Me.base64.encode(n.peerRecordEnvelope,0,n.peerRecordEnvelope.length):i.bytes===Array?Array.prototype.slice.call(n.peerRecordEnvelope):n.peerRecordEnvelope,i.oneofs&&(s._peerRecordEnvelope="peerRecordEnvelope")),s},t.prototype.toJSON=function(){return this.constructor.toObject(this,yi.util.toJSONOptions)},t}();yt.Address=function(){function t(r){if(r)for(var n=Object.keys(r),i=0;i<n.length;++i)r[n[i]]!=null&&(this[n[i]]=r[n[i]])}t.prototype.multiaddr=Me.newBuffer([]),t.prototype.isCertified=null;var e;return Object.defineProperty(t.prototype,"_isCertified",{get:Me.oneOfGetter(e=["isCertified"]),set:Me.oneOfSetter(e)}),t.encode=function(n,i){return i||(i=Lh.create()),n.multiaddr!=null&&Object.hasOwnProperty.call(n,"multiaddr")&&i.uint32(10).bytes(n.multiaddr),n.isCertified!=null&&Object.hasOwnProperty.call(n,"isCertified")&&i.uint32(16).bool(n.isCertified),i},t.decode=function(n,i){n instanceof So||(n=So.create(n));for(var s=i===void 0?n.len:n.pos+i,o=new yt.Address;n.pos<s;){var a=n.uint32();switch(a>>>3){case 1:o.multiaddr=n.bytes();break;case 2:o.isCertified=n.bool();break;default:n.skipType(a&7);break}}return o},t.fromObject=function(n){if(n instanceof yt.Address)return n;var i=new yt.Address;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?Me.base64.decode(n.multiaddr,i.multiaddr=Me.newBuffer(Me.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),n.isCertified!=null&&(i.isCertified=Boolean(n.isCertified)),i},t.toObject=function(n,i){i||(i={});var s={};return i.defaults&&(i.bytes===String?s.multiaddr="":(s.multiaddr=[],i.bytes!==Array&&(s.multiaddr=Me.newBuffer(s.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(s.multiaddr=i.bytes===String?Me.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),n.isCertified!=null&&n.hasOwnProperty("isCertified")&&(s.isCertified=n.isCertified,i.oneofs&&(s._isCertified="isCertified")),s},t.prototype.toJSON=function(){return this.constructor.toObject(this,yi.util.toJSONOptions)},t}();yt.Metadata=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.key="",t.prototype.value=Me.newBuffer([]),t.encode=function(r,n){return n||(n=Lh.create()),r.key!=null&&Object.hasOwnProperty.call(r,"key")&&n.uint32(10).string(r.key),r.value!=null&&Object.hasOwnProperty.call(r,"value")&&n.uint32(18).bytes(r.value),n},t.decode=function(r,n){r instanceof So||(r=So.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new yt.Metadata;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.key=r.string();break;case 2:s.value=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof yt.Metadata)return r;var n=new yt.Metadata;return r.key!=null&&(n.key=String(r.key)),r.value!=null&&(typeof r.value=="string"?Me.base64.decode(r.value,n.value=Me.newBuffer(Me.base64.length(r.value)),0):r.value.length&&(n.value=r.value)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.key="",n.bytes===String?i.value="":(i.value=[],n.bytes!==Array&&(i.value=Me.newBuffer(i.value)))),r.key!=null&&r.hasOwnProperty("key")&&(i.key=r.key),r.value!=null&&r.hasOwnProperty("value")&&(i.value=n.bytes===String?Me.base64.encode(r.value,0,r.value.length):n.bytes===Array?Array.prototype.slice.call(r.value):r.value),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,yi.util.toJSONOptions)},t}();Ux.exports=yt});var kh=w((_V,Fx)=>{Fx.exports={WORKER_REQUEST_READ_LOCK:"lock:worker:request-read",WORKER_RELEASE_READ_LOCK:"lock:worker:release-read",MASTER_GRANT_READ_LOCK:"lock:master:grant-read",WORKER_REQUEST_WRITE_LOCK:"lock:worker:request-write",WORKER_RELEASE_WRITE_LOCK:"lock:worker:release-write",MASTER_GRANT_WRITE_LOCK:"lock:master:grant-write"}});var Kx=w(()=>{});var Xx=w((AV,Qx)=>{var h6=Qt().EventEmitter,{nanoid:p6}=(Xc(),td),{WORKER_REQUEST_READ_LOCK:Vx,WORKER_RELEASE_READ_LOCK:jx,MASTER_GRANT_READ_LOCK:$x,WORKER_REQUEST_WRITE_LOCK:Hx,WORKER_RELEASE_WRITE_LOCK:zx,MASTER_GRANT_WRITE_LOCK:Gx}=kh(),qa,Wx=(t,e,r,n,i)=>(s,o)=>{o&&o.type===r&&t.emit(e,o.name,()=>(s.send({type:i,name:o.name,identifier:o.identifier}),new Promise(a=>{let c=u=>{u&&u.type===n&&u.identifier===o.identifier&&(s.removeListener("message",c),a())};s.on("message",c)})))},Yx=(t,e,r,n)=>()=>{let i=p6();return process.send({type:e,identifier:i,name:t}),new Promise(s=>{let o=a=>{a&&a.type===r&&a.identifier===i&&(process.removeListener("message",o),s(()=>{process.send({type:n,identifier:i,name:t})}))};process.on("message",o)})};Qx.exports=t=>{try{if(qa=Kx(),!Object.keys(qa).length)return}catch(e){return}if(qa.isMaster||t.singleProcess){let e=new h6;return qa.on("message",Wx(e,"requestReadLock",Vx,jx,$x)),qa.on("message",Wx(e,"requestWriteLock",Hx,zx,Gx)),e}return{isWorker:!0,readLock:e=>Yx(e,Vx,$x,jx),writeLock:e=>Yx(e,Hx,Gx,zx)}}});var qh=w((CV,Zx)=>{var gi={},xo=t=>{t.addEventListener("message",e=>{xo.dispatchEvent("message",t,e)}),t.port&&t.port.addEventListener("message",e=>{xo.dispatchEvent("message",t,e)})};xo.addEventListener=(t,e)=>{gi[t]||(gi[t]=[]),gi[t].push(e)};xo.removeEventListener=(t,e)=>{!gi[t]||(gi[t]=gi[t].filter(r=>r===e))};xo.dispatchEvent=function(){let t=Array.prototype.slice.call(arguments),e=t.shift();!gi[e]||gi[e].forEach(r=>r.apply(null,t))};Zx.exports=xo});var uA=w((IV,cA)=>{var y6=Qt().EventEmitter,{nanoid:g6}=(Xc(),td),{WORKER_REQUEST_READ_LOCK:Jx,WORKER_RELEASE_READ_LOCK:eA,MASTER_GRANT_READ_LOCK:tA,WORKER_REQUEST_WRITE_LOCK:rA,WORKER_RELEASE_WRITE_LOCK:nA,MASTER_GRANT_WRITE_LOCK:iA}=kh(),sA=qh(),oA=(t,e,r,n,i)=>(s,o)=>{if(!o||!o.data||o.data.type!==r)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};t.emit(e,a.name,()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),new Promise(c=>{let u=l=>{if(!l||!l.data)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f&&f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})))},aA=(t,e,r,n)=>()=>{let i=g6();return globalThis.postMessage({type:e,identifier:i,name:t}),new Promise(s=>{let o=a=>{if(!a||!a.data)return;let c={type:a.data.type,identifier:a.data.identifier};c&&c.type===r&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:t})}))};globalThis.addEventListener("message",o)})},m6={singleProcess:!1};cA.exports=t=>{if(t=Object.assign({},m6,t),!!globalThis.document||t.singleProcess){let r=new y6;return sA.addEventListener("message",oA(r,"requestReadLock",Jx,eA,tA)),sA.addEventListener("message",oA(r,"requestWriteLock",rA,nA,iA)),r}return{isWorker:!0,readLock:r=>aA(r,Jx,tA,eA),writeLock:r=>aA(r,rA,iA,nA)}}});var fA=w((TV,Uh)=>{"use strict";var v6=Object.prototype.hasOwnProperty,Gt="~";function Ua(){}Object.create&&(Ua.prototype=Object.create(null),new Ua().__proto__||(Gt=!1));function b6(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function lA(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new b6(r,n||t,i),o=Gt?Gt+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],s]:t._events[o].push(s):(t._events[o]=s,t._eventsCount++),t}function zu(t,e){--t._eventsCount==0?t._events=new Ua:delete t._events[e]}function Mt(){this._events=new Ua,this._eventsCount=0}Mt.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)v6.call(r,n)&&e.push(Gt?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};Mt.prototype.listeners=function(e){var r=Gt?Gt+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Mt.prototype.listenerCount=function(e){var r=Gt?Gt+e:e,n=this._events[r];return n?n.fn?1:n.length:0};Mt.prototype.emit=function(e,r,n,i,s,o){var a=Gt?Gt+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,s),!0;case 6:return c.fn.call(c.context,r,n,i,s,o),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var d=c.length,p;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,r);break;case 3:c[f].fn.call(c[f].context,r,n);break;case 4:c[f].fn.call(c[f].context,r,n,i);break;default:if(!l)for(p=1,l=new Array(u-1);p<u;p++)l[p-1]=arguments[p];c[f].fn.apply(c[f].context,l)}}return!0};Mt.prototype.on=function(e,r,n){return lA(this,e,r,n,!1)};Mt.prototype.once=function(e,r,n){return lA(this,e,r,n,!0)};Mt.prototype.removeListener=function(e,r,n,i){var s=Gt?Gt+e:e;if(!this._events[s])return this;if(!r)return zu(this,s),this;var o=this._events[s];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&zu(this,s);else{for(var a=0,c=[],u=o.length;a<u;a++)(o[a].fn!==r||i&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:zu(this,s)}return this};Mt.prototype.removeAllListeners=function(e){var r;return e?(r=Gt?Gt+e:e,this._events[r]&&zu(this,r)):(this._events=new Ua,this._eventsCount=0),this};Mt.prototype.off=Mt.prototype.removeListener;Mt.prototype.addListener=Mt.prototype.on;Mt.prefixed=Gt;Mt.EventEmitter=Mt;typeof Uh!="undefined"&&(Uh.exports=Mt)});var hA=w((RV,dA)=>{"use strict";dA.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var yA=w((BV,Gu)=>{"use strict";var E6=hA(),Mh=class extends Error{constructor(e){super(e);this.name="TimeoutError"}},pA=(t,e,r)=>new Promise((n,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let s=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let o=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,a=r instanceof Error?r:new Mh(o);typeof t.cancel=="function"&&t.cancel(),i(a)},e);E6(t.then(n,i),()=>{clearTimeout(s)})});Gu.exports=pA;Gu.exports.default=pA;Gu.exports.TimeoutError=Mh});var gA=w(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});function w6(t,e,r){let n=0,i=t.length;for(;i>0;){let s=i/2|0,o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}Fh.default=w6});var vA=w(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var _6=gA(),mA=class{constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=_6.default(this._queue,n,(s,o)=>o.priority-s.priority);this._queue.splice(i,0,n)}dequeue(){let e=this._queue.shift();return e==null?void 0:e.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};Kh.default=mA});var wA=w(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var S6=fA(),bA=yA(),x6=vA(),Wu=()=>{},A6=new bA.TimeoutError,EA=class extends S6{constructor(e){var r,n,i,s;super();if(this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Wu,this._resolveIdle=Wu,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:x6.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${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 \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=Wu,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=Wu,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}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._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,i)=>{let s=async()=>{this._pendingCount++,this._intervalCount++;try{let o=this._timeout===void 0&&r.timeout===void 0?e():bA.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(A6)});n(await o)}catch(o){i(o)}this._next()};this._queue.enqueue(s,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Vh.default=EA});var _A=w((LV,jh)=>{"use strict";var Yu,DV=jh.exports.timeout=function(t,e){var r=new Yu,n;return Promise.race([t,new Promise(function(i,s){n=setTimeout(function(){s(r)},e)})]).then(function(i){return clearTimeout(n),i},function(i){throw clearTimeout(n),i})};Yu=jh.exports.TimeoutError=function(){Error.call(this),this.stack=Error().stack,this.message="Timeout"};Yu.prototype=Object.create(Error.prototype);Yu.prototype.name="TimeoutError"});var xA=w((kV,Hh)=>{var C6=Xx(),I6=uA(),{default:SA}=wA(),{timeout:T6}=_A(),R6=qh(),as={},mi;function $h(t,e){let r,n=new Promise(i=>{r=i});return t.add(()=>T6((()=>new Promise(i=>{r(()=>{i()})}))(),e.timeout)),n}var B6=(t,e)=>{if(mi.isWorker)return{readLock:mi.readLock(t,e),writeLock:mi.writeLock(t,e)};let r=new SA({concurrency:1}),n=null;return{readLock:()=>{if(n)return $h(n,e);n=new SA({concurrency:e.concurrency,autoStart:!1});let i=n,s=$h(n,e);return r.add(()=>(i.start(),i.onIdle().then(()=>{n===i&&(n=null)}))),s},writeLock:()=>(n=null,$h(r,e))}},P6={concurrency:1/0,timeout:846e5,global:globalThis,singleProcess:!1};Hh.exports=(t,e)=>(e||(e={}),typeof t=="object"&&(e=t,t="lock"),t||(t="lock"),e=Object.assign({},P6,e),mi||(mi=C6(e)||I6(e),mi.isWorker||(mi.on("requestReadLock",(r,n)=>{!as[r]||as[r].readLock().then(i=>n().finally(()=>i()))}),mi.on("requestWriteLock",async(r,n)=>{!as[r]||as[r].writeLock().then(i=>n().finally(()=>i()))}))),as[t]||(as[t]=B6(t,e)),as[t]);Hh.exports.Worker=function(t,e){e=e||globalThis.Worker;let r;try{r=new e(t)}catch(n){n.message.includes("not a constructor")&&(r=e(t))}if(!r)throw new Error("Could not create Worker from",e);return R6(r),r}});var DA=w((qV,OA)=>{"use strict";var AA=Te(),CA=Rt(),IA=de(),{codes:Qu}=je(),{Key:N6}=(Jc(),rd),{base32:O6}=(wi(),Ei),{keys:{unmarshalPublicKey:D6,marshalPublicKey:L6}}=Bu(),{Multiaddr:TA}=qt(),{Peer:RA}=Mx(),k6=xA(),{equals:q6}=(mr(),gr),BA=Object.assign(AA("libp2p:peer-store:store"),{error:AA("libp2p:peer-store:store:err")}),PA="/peers/",NA=class{constructor(e){this._datastore=e,this.lock=k6("peer-store",{singleProcess:!0})}_peerIdToDatastoreKey(e){if(!CA.isPeerId(e))throw BA.error("peerId must be an instance of peer-id to store data"),IA(new Error("peerId must be an instance of peer-id"),Qu.ERR_INVALID_PARAMETERS);let r=e.toString();return new N6(`${PA}${r}`)}async has(e){return this._datastore.has(this._peerIdToDatastoreKey(e))}async delete(e){await this._datastore.delete(this._peerIdToDatastoreKey(e))}async load(e){let r=await this._datastore.get(this._peerIdToDatastoreKey(e)),n=RA.decode(r),i=n.pubKey?D6(n.pubKey):e.pubKey,s=new Map;for(let o of n.metadata)s.set(o.key,o.value);return{...n,id:e,pubKey:i,addresses:n.addresses.map(({multiaddr:o,isCertified:a})=>({multiaddr:new TA(o),isCertified:a||!1})),metadata:s,peerRecordEnvelope:n.peerRecordEnvelope||void 0}}async save(e){if(e.pubKey!=null&&e.id.pubKey!=null&&!q6(e.pubKey.bytes,e.id.pubKey.bytes))throw BA.error("peer publicKey bytes do not match peer id publicKey bytes"),IA(new Error("publicKey bytes do not match peer id publicKey bytes"),Qu.ERR_INVALID_PARAMETERS);let r=new Set,n=RA.encode({addresses:e.addresses.filter(i=>r.has(i.multiaddr.toString())?!1:(r.add(i.multiaddr.toString()),!0)).sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({multiaddr:i,isCertified:s})=>({multiaddr:i.bytes,isCertified:s})),protocols:e.protocols.sort(),pubKey:e.pubKey?L6(e.pubKey):void 0,metadata:[...e.metadata.keys()].sort().map(i=>({key:i,value:e.metadata.get(i)})),peerRecordEnvelope:e.peerRecordEnvelope}).finish();return await this._datastore.put(this._peerIdToDatastoreKey(e.id),n),this.load(e.id)}async patch(e,r){let n=await this.load(e);return await this._patch(e,r,n)}async patchOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==Qu.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._patch(e,r,n)}async _patch(e,r,n){return await this.save({...n,...r,id:e})}async merge(e,r){let n=await this.load(e);return this._merge(e,r,n)}async mergeOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==Qu.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._merge(e,r,n)}async _merge(e,r,n){let i=new Map;return(r.addresses||[]).forEach(s=>{i.set(s.multiaddr.toString(),s.isCertified)}),n.addresses.forEach(({multiaddr:s,isCertified:o})=>{let a=s.toString();i.set(a,Boolean(i.get(a)||o))}),await this.save({id:e,addresses:Array.from(i.entries()).map(([s,o])=>({multiaddr:new TA(s),isCertified:o})),protocols:Array.from(new Set([...n.protocols||[],...r.protocols||[]])),metadata:new Map([...n.metadata?n.metadata.entries():[],...r.metadata?r.metadata.entries():[]]),pubKey:r.pubKey||(n!=null?n.pubKey:void 0),peerRecordEnvelope:r.peerRecordEnvelope||(n!=null?n.peerRecordEnvelope:void 0)})}async*all(){for await(let e of this._datastore.queryKeys({prefix:PA})){let r=e.toString().split("/")[2],n=O6.decode(r);yield this.load(CA.createFromBytes(n))}}};OA.exports=NA});var UA=w((UV,qA)=>{"use strict";var LA=Te(),{EventEmitter:U6}=Qt(),M6=xx(),F6=Rx(),K6=Ox(),V6=qx(),j6=DA(),Rr=Object.assign(LA("libp2p:peer-store"),{error:LA("libp2p:peer-store:err")}),kA=class extends U6{constructor({peerId:e,datastore:r,addressFilter:n}){super();this._peerId=e,this._store=new j6(r),this.addressBook=new M6(this.emit.bind(this),this._store,n),this.keyBook=new F6(this.emit.bind(this),this._store),this.metadataBook=new K6(this.emit.bind(this),this._store),this.protoBook=new V6(this.emit.bind(this),this._store)}async*getPeers(){Rr("getPeers await read lock");let e=await this._store.lock.readLock();Rr("getPeers got read lock");try{for await(let r of this._store.all())r.id.toB58String()!==this._peerId.toB58String()&&(yield r)}finally{Rr("getPeers release read lock"),e()}}async delete(e){Rr("delete await write lock");let r=await this._store.lock.writeLock();Rr("delete got write lock");try{await this._store.delete(e)}finally{Rr("delete release write lock"),r()}}async get(e){Rr("get await read lock");let r=await this._store.lock.readLock();Rr("get got read lock");try{return this._store.load(e)}finally{Rr("get release read lock"),r()}}async has(e){Rr("has await read lock");let r=await this._store.lock.readLock();Rr("has got read lock");try{return this._store.has(e)}finally{Rr("has release read lock"),r()}}};qA.exports=kA});var FA=w((MV,MA)=>{"use strict";function $6(t,e,r){let n=new t(e,r);n._subscribeAdapter=n.subscribe,n._unsubscribeAdapter=n.unsubscribe;function i(o,a){a&&n.on(o,a),n._subscribeAdapter(o)}function s(o,a){a?n.removeListener(o,a):n.removeAllListeners(o),n.listenerCount(o)===0&&n._unsubscribeAdapter(o)}return n.subscribe=i,n.unsubscribe=s,n}MA.exports=$6});var HA=w((FV,$A)=>{"use strict";var KA=()=>{},VA=Symbol.for("@libp2p/js-interfaces/topology"),jA=class{constructor({min:e=0,max:r=1/0,handlers:n={}}){this.min=e,this.max=r,this._onConnect=n.onConnect||KA,this._onDisconnect=n.onDisconnect||KA,this.peers=new Set}get[Symbol.toStringTag](){return"Topology"}get[VA](){return!0}static isTopology(e){return Boolean(e&&e[VA])}async setRegistrar(e){this._registrar=e}disconnect(e){this._onDisconnect(e)}};$A.exports=jA});var YA=w((KV,WA)=>{"use strict";var zA=Te(),H6=Object.assign(zA("libp2p:registrar"),{error:zA("libp2p:registrar:err")}),z6=de(),{codes:{ERR_INVALID_PARAMETERS:G6}}=je(),W6=HA(),GA=class{constructor({peerStore:e,connectionManager:r}){this.peerStore=e,this.connectionManager=r,this.topologies=new Map,this._handle=void 0,this._onDisconnect=this._onDisconnect.bind(this),this.connectionManager.on("peer:disconnect",this._onDisconnect)}get handle(){return this._handle}set handle(e){this._handle=e}getConnection(e){return this.connectionManager.get(e)}async register(e){if(!W6.isTopology(e))throw H6.error("topology must be an instance of interfaces/topology"),z6(new Error("topology must be an instance of interfaces/topology"),G6);let r=(Math.random()*1e9).toString(36)+Date.now();return this.topologies.set(r,e),await e.setRegistrar(this),r}unregister(e){return this.topologies.delete(e)}_onDisconnect(e){for(let[,r]of this.topologies)r.disconnect(e.remotePeer)}};WA.exports=GA});var zh=w((VV,Ma)=>{"use strict";var{Buffer:Xu}=ci(),Zu=Ji();Ma.exports=async function*(t){for await(let e of t)Xu.isBuffer(e)?yield e:Zu.isBufferList(e)?yield e.slice():yield Xu.from(e)};Ma.exports.toBuffer=Ma.exports;Ma.exports.toList=async function*(t){for await(let e of t)Xu.isBuffer(e)?yield new Zu().append(e):Zu.isBufferList(e)?yield e:yield new Zu().append(Xu.from(e))}});var ZA=w((jV,XA)=>{"use strict";var Ao=gn(),QA=Ao.Reader,Y6=Ao.Writer,rt=Ao.util,Fa=Ao.roots["libp2p-identify"]||(Ao.roots["libp2p-identify"]={});Fa.Identify=function(){function t(e){if(this.listenAddrs=[],this.protocols=[],e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.protocolVersion="",t.prototype.agentVersion="",t.prototype.publicKey=rt.newBuffer([]),t.prototype.listenAddrs=rt.emptyArray,t.prototype.observedAddr=rt.newBuffer([]),t.prototype.protocols=rt.emptyArray,t.prototype.signedPeerRecord=rt.newBuffer([]),t.encode=function(r,n){if(n||(n=Y6.create()),r.publicKey!=null&&Object.hasOwnProperty.call(r,"publicKey")&&n.uint32(10).bytes(r.publicKey),r.listenAddrs!=null&&r.listenAddrs.length)for(var i=0;i<r.listenAddrs.length;++i)n.uint32(18).bytes(r.listenAddrs[i]);if(r.protocols!=null&&r.protocols.length)for(var i=0;i<r.protocols.length;++i)n.uint32(26).string(r.protocols[i]);return r.observedAddr!=null&&Object.hasOwnProperty.call(r,"observedAddr")&&n.uint32(34).bytes(r.observedAddr),r.protocolVersion!=null&&Object.hasOwnProperty.call(r,"protocolVersion")&&n.uint32(42).string(r.protocolVersion),r.agentVersion!=null&&Object.hasOwnProperty.call(r,"agentVersion")&&n.uint32(50).string(r.agentVersion),r.signedPeerRecord!=null&&Object.hasOwnProperty.call(r,"signedPeerRecord")&&n.uint32(66).bytes(r.signedPeerRecord),n},t.decode=function(r,n){r instanceof QA||(r=QA.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new Fa.Identify;r.pos<i;){var o=r.uint32();switch(o>>>3){case 5:s.protocolVersion=r.string();break;case 6:s.agentVersion=r.string();break;case 1:s.publicKey=r.bytes();break;case 2:s.listenAddrs&&s.listenAddrs.length||(s.listenAddrs=[]),s.listenAddrs.push(r.bytes());break;case 4:s.observedAddr=r.bytes();break;case 3:s.protocols&&s.protocols.length||(s.protocols=[]),s.protocols.push(r.string());break;case 8:s.signedPeerRecord=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof Fa.Identify)return r;var n=new Fa.Identify;if(r.protocolVersion!=null&&(n.protocolVersion=String(r.protocolVersion)),r.agentVersion!=null&&(n.agentVersion=String(r.agentVersion)),r.publicKey!=null&&(typeof r.publicKey=="string"?rt.base64.decode(r.publicKey,n.publicKey=rt.newBuffer(rt.base64.length(r.publicKey)),0):r.publicKey.length&&(n.publicKey=r.publicKey)),r.listenAddrs){if(!Array.isArray(r.listenAddrs))throw TypeError(".Identify.listenAddrs: array expected");n.listenAddrs=[];for(var i=0;i<r.listenAddrs.length;++i)typeof r.listenAddrs[i]=="string"?rt.base64.decode(r.listenAddrs[i],n.listenAddrs[i]=rt.newBuffer(rt.base64.length(r.listenAddrs[i])),0):r.listenAddrs[i].length&&(n.listenAddrs[i]=r.listenAddrs[i])}if(r.observedAddr!=null&&(typeof r.observedAddr=="string"?rt.base64.decode(r.observedAddr,n.observedAddr=rt.newBuffer(rt.base64.length(r.observedAddr)),0):r.observedAddr.length&&(n.observedAddr=r.observedAddr)),r.protocols){if(!Array.isArray(r.protocols))throw TypeError(".Identify.protocols: array expected");n.protocols=[];for(var i=0;i<r.protocols.length;++i)n.protocols[i]=String(r.protocols[i])}return r.signedPeerRecord!=null&&(typeof r.signedPeerRecord=="string"?rt.base64.decode(r.signedPeerRecord,n.signedPeerRecord=rt.newBuffer(rt.base64.length(r.signedPeerRecord)),0):r.signedPeerRecord.length&&(n.signedPeerRecord=r.signedPeerRecord)),n},t.toObject=function(r,n){n||(n={});var i={};if((n.arrays||n.defaults)&&(i.listenAddrs=[],i.protocols=[]),n.defaults&&(n.bytes===String?i.publicKey="":(i.publicKey=[],n.bytes!==Array&&(i.publicKey=rt.newBuffer(i.publicKey))),n.bytes===String?i.observedAddr="":(i.observedAddr=[],n.bytes!==Array&&(i.observedAddr=rt.newBuffer(i.observedAddr))),i.protocolVersion="",i.agentVersion="",n.bytes===String?i.signedPeerRecord="":(i.signedPeerRecord=[],n.bytes!==Array&&(i.signedPeerRecord=rt.newBuffer(i.signedPeerRecord)))),r.publicKey!=null&&r.hasOwnProperty("publicKey")&&(i.publicKey=n.bytes===String?rt.base64.encode(r.publicKey,0,r.publicKey.length):n.bytes===Array?Array.prototype.slice.call(r.publicKey):r.publicKey),r.listenAddrs&&r.listenAddrs.length){i.listenAddrs=[];for(var s=0;s<r.listenAddrs.length;++s)i.listenAddrs[s]=n.bytes===String?rt.base64.encode(r.listenAddrs[s],0,r.listenAddrs[s].length):n.bytes===Array?Array.prototype.slice.call(r.listenAddrs[s]):r.listenAddrs[s]}if(r.protocols&&r.protocols.length){i.protocols=[];for(var s=0;s<r.protocols.length;++s)i.protocols[s]=r.protocols[s]}return r.observedAddr!=null&&r.hasOwnProperty("observedAddr")&&(i.observedAddr=n.bytes===String?rt.base64.encode(r.observedAddr,0,r.observedAddr.length):n.bytes===Array?Array.prototype.slice.call(r.observedAddr):r.observedAddr),r.protocolVersion!=null&&r.hasOwnProperty("protocolVersion")&&(i.protocolVersion=r.protocolVersion),r.agentVersion!=null&&r.hasOwnProperty("agentVersion")&&(i.agentVersion=r.agentVersion),r.signedPeerRecord!=null&&r.hasOwnProperty("signedPeerRecord")&&(i.signedPeerRecord=n.bytes===String?rt.base64.encode(r.signedPeerRecord,0,r.signedPeerRecord.length):n.bytes===Array?Array.prototype.slice.call(r.signedPeerRecord):r.signedPeerRecord),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Ao.util.toJSONOptions)},t}();XA.exports=Fa});var aC=w(($V,oC)=>{"use strict";var JA=Te(),lr=Object.assign(JA("libp2p:identify"),{error:JA("libp2p:identify:err")}),Gh=de(),Ju=so(),{pipe:el}=ir(),{collect:eC,take:tC,consume:rC}=Lu(),{fromString:Co}=(It(),Nt),Q6=Rt(),{Multiaddr:Wh}=qt(),{toBuffer:nC}=zh(),Ka=ZA(),iC=du(),sC=pu(),{MULTICODEC_IDENTIFY:X6,MULTICODEC_IDENTIFY_PUSH:Z6,IDENTIFY_PROTOCOL_VERSION:J6,MULTICODEC_IDENTIFY_PROTOCOL_NAME:e5,MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME:t5,MULTICODEC_IDENTIFY_PROTOCOL_VERSION:r5,MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION:n5}=vd(),{codes:Yh}=je(),cs=class{static getProtocolStr(e){return{identifyProtocolStr:`/${e._config.protocolPrefix}/${e5}/${r5}`,identifyPushProtocolStr:`/${e._config.protocolPrefix}/${t5}/${n5}`}}constructor({libp2p:e}){this._libp2p=e,this.peerStore=e.peerStore,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.handleMessage=this.handleMessage.bind(this);let r=cs.getProtocolStr(e);this.identifyProtocolStr=r.identifyProtocolStr,this.identifyPushProtocolStr=r.identifyPushProtocolStr,this._host={protocolVersion:`${e._config.protocolPrefix}/${J6}`,...e._options.host},this.connectionManager.on("peer:connect",n=>{this.identify(n).catch(lr.error)}),this.peerStore.on("change:multiaddrs",({peerId:n})=>{n.toString()===this.peerId.toString()&&this.pushToPeerStore().catch(i=>lr.error(i))}),this.peerStore.on("change:protocols",({peerId:n})=>{n.toString()===this.peerId.toString()&&this.pushToPeerStore().catch(i=>lr.error(i))})}async start(){await this.peerStore.metadataBook.setValue(this.peerId,"AgentVersion",Co(this._host.agentVersion)),await this.peerStore.metadataBook.setValue(this.peerId,"ProtocolVersion",Co(this._host.protocolVersion))}async stop(){}async push(e){let r=await this.peerStore.addressBook.getRawEnvelope(this.peerId),n=this._libp2p.multiaddrs.map(o=>o.bytes),i=await this.peerStore.protoBook.get(this.peerId),s=e.map(async o=>{try{let{stream:a}=await o.newStream(this.identifyPushProtocolStr);await el([Ka.Identify.encode({listenAddrs:n,signedPeerRecord:r,protocols:i}).finish()],Ju.encode(),a,rC)}catch(a){lr.error("could not push identify update to peer",a)}});return Promise.all(s)}async pushToPeerStore(){if(!this._libp2p.isStarted())return;let e=[],r;for await(let n of this.peerStore.getPeers())n.protocols.includes(this.identifyPushProtocolStr)&&(r=this.connectionManager.get(n.id))&&e.push(r);await this.push(e)}async identify(e){let{stream:r}=await e.newStream(this.identifyProtocolStr),[n]=await el([],r,Ju.decode(),tC(1),nC,eC);if(!n)throw Gh(new Error("No data could be retrieved"),Yh.ERR_CONNECTION_ENDED);let i;try{i=Ka.Identify.decode(n)}catch(d){throw Gh(d,Yh.ERR_INVALID_MESSAGE)}let{publicKey:s,listenAddrs:o,protocols:a,observedAddr:c,signedPeerRecord:u}=i,l=await Q6.createFromPubKey(s);if(e.remotePeer.toB58String()!==l.toB58String())throw Gh(new Error("identified peer does not match the expected peer"),Yh.ERR_INVALID_PEER);let f=cs.getCleanMultiaddr(c);try{let d=await iC.openAndCertify(u,sC.DOMAIN);if(await this.peerStore.addressBook.consumePeerRecord(d)){await this.peerStore.protoBook.set(l,a),await this.peerStore.metadataBook.setValue(l,"AgentVersion",Co(i.agentVersion)),await this.peerStore.metadataBook.setValue(l,"ProtocolVersion",Co(i.protocolVersion));return}}catch(d){lr("received invalid envelope, discard it and fallback to listenAddrs is available",d)}try{await this.peerStore.addressBook.set(l,o.map(d=>new Wh(d)))}catch(d){lr.error("received invalid addrs",d)}await this.peerStore.protoBook.set(l,a),await this.peerStore.metadataBook.setValue(l,"AgentVersion",Co(i.agentVersion)),await this.peerStore.metadataBook.setValue(l,"ProtocolVersion",Co(i.protocolVersion)),lr("received observed address of %s",f)}handleMessage({connection:e,stream:r,protocol:n}){switch(n){case this.identifyProtocolStr:return this._handleIdentify({connection:e,stream:r});case this.identifyPushProtocolStr:return this._handlePush({connection:e,stream:r});default:lr.error("cannot handle unknown protocol %s",n)}}async _handleIdentify({connection:e,stream:r}){try{let n=new Uint8Array(0);this.peerId.pubKey&&(n=this.peerId.pubKey.bytes);let i=await this.peerStore.addressBook.getRawEnvelope(this.peerId),s=await this.peerStore.protoBook.get(this.peerId),o=Ka.Identify.encode({protocolVersion:this._host.protocolVersion,agentVersion:this._host.agentVersion,publicKey:n,listenAddrs:this._libp2p.multiaddrs.map(a=>a.bytes),signedPeerRecord:i,observedAddr:e.remoteAddr.bytes,protocols:s}).finish();await el([o],Ju.encode(),r,rC)}catch(n){lr.error("could not respond to identify request",n)}}async _handlePush({connection:e,stream:r}){let n;try{let[s]=await el([],r,Ju.decode(),tC(1),nC,eC);n=Ka.Identify.decode(s)}catch(s){return lr.error("received invalid message",s)}let i=e.remotePeer;try{let s=await iC.openAndCertify(n.signedPeerRecord,sC.DOMAIN);if(await this.peerStore.addressBook.consumePeerRecord(s)){await this.peerStore.protoBook.set(i,n.protocols);return}}catch(s){lr("received invalid envelope, discard it and fallback to listenAddrs is available",s)}try{await this.peerStore.addressBook.set(i,n.listenAddrs.map(s=>new Wh(s)))}catch(s){lr.error("received invalid addrs",s)}try{await this.peerStore.protoBook.set(i,n.protocols)}catch(s){lr.error("received invalid protocols",s)}}static getCleanMultiaddr(e){if(e&&e.length>0)try{return new Wh(e)}catch(r){return null}return null}},i5={IDENTIFY:X6,IDENTIFY_PUSH:Z6};cs.multicodecs=i5;cs.Messsage=Ka;oC.exports=cs});var lC=w((HV,uC)=>{"use strict";var us=gn(),tl=us.Reader,cC=us.Writer,Io=us.util,dn=us.roots["libp2p-fetch"]||(us.roots["libp2p-fetch"]={});dn.FetchRequest=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.identifier="",t.encode=function(r,n){return n||(n=cC.create()),r.identifier!=null&&Object.hasOwnProperty.call(r,"identifier")&&n.uint32(10).string(r.identifier),n},t.decode=function(r,n){r instanceof tl||(r=tl.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new dn.FetchRequest;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.identifier=r.string();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof dn.FetchRequest)return r;var n=new dn.FetchRequest;return r.identifier!=null&&(n.identifier=String(r.identifier)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.identifier=""),r.identifier!=null&&r.hasOwnProperty("identifier")&&(i.identifier=r.identifier),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,us.util.toJSONOptions)},t}();dn.FetchResponse=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.status=0,t.prototype.data=Io.newBuffer([]),t.encode=function(r,n){return n||(n=cC.create()),r.status!=null&&Object.hasOwnProperty.call(r,"status")&&n.uint32(8).int32(r.status),r.data!=null&&Object.hasOwnProperty.call(r,"data")&&n.uint32(18).bytes(r.data),n},t.decode=function(r,n){r instanceof tl||(r=tl.create(r));for(var i=n===void 0?r.len:r.pos+n,s=new dn.FetchResponse;r.pos<i;){var o=r.uint32();switch(o>>>3){case 1:s.status=r.int32();break;case 2:s.data=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof dn.FetchResponse)return r;var n=new dn.FetchResponse;switch(r.status){case"OK":case 0:n.status=0;break;case"NOT_FOUND":case 1:n.status=1;break;case"ERROR":case 2:n.status=2;break}return r.data!=null&&(typeof r.data=="string"?Io.base64.decode(r.data,n.data=Io.newBuffer(Io.base64.length(r.data)),0):r.data.length&&(n.data=r.data)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.status=n.enums===String?"OK":0,n.bytes===String?i.data="":(i.data=[],n.bytes!==Array&&(i.data=Io.newBuffer(i.data)))),r.status!=null&&r.hasOwnProperty("status")&&(i.status=n.enums===String?dn.FetchResponse.StatusCode[r.status]:r.status),r.data!=null&&r.hasOwnProperty("data")&&(i.data=n.bytes===String?Io.base64.encode(r.data,0,r.data.length):n.bytes===Array?Array.prototype.slice.call(r.data):r.data),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,us.util.toJSONOptions)},t.StatusCode=function(){var e={},r=Object.create(e);return r[e[0]="OK"]=0,r[e[1]="NOT_FOUND"]=1,r[e[2]="ERROR"]=2,r}(),t}();uC.exports=dn});var dC=w((zV,fC)=>{"use strict";fC.exports={PROTOCOL:"/libp2p/fetch/0.0.1"}});var mC=w((yC,gC)=>{"use strict";var hC=Te(),s5=Object.assign(hC("libp2p:fetch"),{error:hC("libp2p:fetch:err")}),Qh=de(),{codes:Xh}=je(),rl=so(),{FetchRequest:Zh,FetchResponse:jr}=lC(),pC=oo(),{PROTOCOL:o5}=dC(),Va=class{constructor(e){this._lookupFunctions=new Map,this._libp2p=e,this.handleMessage=this.handleMessage.bind(this)}async fetch(e,r){s5("dialing %s to %s",this._protocol,e.toB58String?e.toB58String():e);let n=await this._libp2p.dial(e),{stream:i}=await n.newStream(Va.PROTOCOL),s=pC(i),o=new Zh({identifier:r});s.write(rl.encode.single(Zh.encode(o).finish()));let a=jr.decode((await rl.decode.fromReader(s.reader).next()).value.slice());switch(a.status){case jr.StatusCode.OK:return a.data;case jr.StatusCode.NOT_FOUND:return null;case jr.StatusCode.ERROR:{let c=new TextDecoder().decode(a.data);throw Qh(new Error("Error in fetch protocol response: "+c),Xh.ERR_INVALID_PARAMETERS)}default:throw Qh(new Error("Unknown response status"),Xh.ERR_INVALID_MESSAGE)}}async handleMessage(e){let{stream:r}=e,n=pC(r),i=Zh.decode((await rl.decode.fromReader(n.reader).next()).value.slice()),s,o=this._getLookupFunction(i.identifier);if(o){let a=await o(i.identifier);a?s=new jr({status:jr.StatusCode.OK,data:a}):s=new jr({status:jr.StatusCode.NOT_FOUND})}else{let a=new TextEncoder().encode("No lookup function registered for key: "+i.identifier);s=new jr({status:jr.StatusCode.ERROR,data:a})}n.write(rl.encode.single(jr.encode(s).finish()))}_getLookupFunction(e){for(let r of this._lookupFunctions.keys())if(e.startsWith(r))return this._lookupFunctions.get(r);return null}registerLookupFunction(e,r){if(this._lookupFunctions.has(e))throw Qh(new Error("Fetch protocol handler for key prefix '"+e+"' already registered"),Xh.ERR_KEY_ALREADY_EXISTS);this._lookupFunctions.set(e,r)}unregisterLookupFunction(e,r){r!=null&&this._lookupFunctions.get(e)!==r||this._lookupFunctions.delete(e)}};Va.PROTOCOL=o5;yC=gC.exports=Va});var bC=w((GV,vC)=>{"use strict";vC.exports={PROTOCOL:"/ipfs/ping/1.0.0",PING_LENGTH:32,PROTOCOL_VERSION:"1.0.0",PROTOCOL_NAME:"ping"}});var CC=w((WV,AC)=>{"use strict";var EC=Te(),a5=Object.assign(EC("libp2p:ping"),{error:EC("libp2p:ping:err")}),c5=de(),{codes:u5}=je(),l5=Bu(),{pipe:wC}=ir(),{toBuffer:f5}=zh(),{collect:d5,take:h5}=Lu(),{equals:p5}=(mr(),gr),{PROTOCOL_NAME:_C,PING_LENGTH:y5,PROTOCOL_VERSION:SC}=bC(),xC=class{static getProtocolStr(e){return`/${e._config.protocolPrefix}/${_C}/${SC}`}constructor(e){this._libp2p=e}handleMessage({stream:e}){return wC(e,e)}async ping(e){let r=`/${this._libp2p._config.protocolPrefix}/${_C}/${SC}`;a5("dialing %s to %s",r,e.toB58String?e.toB58String():e);let n=await this._libp2p.dial(e),{stream:i}=await n.newStream(r),s=Date.now(),o=l5.randomBytes(y5),[a]=await wC([o],i,u=>h5(1,u),f5,d5),c=Date.now();if(!p5(o,a))throw c5(new Error("Received wrong ping ack"),u5.ERR_WRONG_PING_ACK);return c-s}};AC.exports=xC});var IC=w(()=>{});var TC=w(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0}),Jh.promisify=nl;var g5="__ES6-PROMISIFY--CUSTOM-ARGUMENTS__";function nl(t){if(typeof t!="function")throw new TypeError("Argument to promisify must be a function");var e=t[g5],r=nl.Promise||Promise;if(typeof r!="function")throw new Error("No Promise implementation found; do you need a polyfill?");return function(){for(var n=this,i=arguments.length,s=Array(i),o=0;o<i;o++)s[o]=arguments[o];return new r(function(a,c){s.push(function(u){if(u)return c(u);for(var l=arguments.length,f=Array(1<l?l-1:0),d=1;d<l;d++)f[d-1]=arguments[d];if(f.length===1||!e)return a(f[0]);var p={};f.forEach(function(h,g){var m=e[g];m&&(p[m]=h)}),a(p)}),t.apply(n,s)})}}nl.argumentNames="__ES6-PROMISIFY--CUSTOM-ARGUMENTS__",nl.Promise=void 0});var BC=w((ZV,RC)=>{function m5(){return typeof window!="undefined"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process!="undefined"&&typeof process.versions=="object"&&!!process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0}RC.exports=m5});var NC=w((JV,PC)=>{"use strict";var v5=BC(),il=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,ja=v5(),b5=il&&!ja,E5=ja&&!il,w5=ja&&il,_5=typeof u0=="function"&&typeof process!="undefined"&&typeof process.release!="undefined"&&process.release.name==="node"&&!ja,S5=typeof importScripts=="function"&&typeof self!="undefined"&&typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope,x5=typeof process!="undefined"&&typeof process.env!="undefined"&&!1;PC.exports={isTest:x5,isElectron:ja,isElectronMain:E5,isElectronRenderer:w5,isNode:_5,isBrowser:b5,isWebWorker:S5,isEnvWithDom:il}});var DC=w((e9,OC)=>{function Br(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}OC.exports=Br;Br.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Br.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Br.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0};Br.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Br.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};Br.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};Br.prototype.start=Br.prototype.try;Br.prototype.errors=function(){return this._errors};Br.prototype.attempts=function(){return this._attempts};Br.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,r=0,n=0;n<this._errors.length;n++){var i=this._errors[n],s=i.message,o=(t[s]||0)+1;t[s]=o,o>=r&&(e=i,r=o)}return e}});var LC=w(ls=>{var A5=DC();ls.operation=function(t){var e=ls.timeouts(t);return new A5(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};ls.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in t)e[r]=t[r];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return t&&t.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(s,o){return s-o}),n};ls.createTimeout=function(t,e){var r=e.randomize?Math.random()+1:1,n=Math.round(r*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return n=Math.min(n,e.maxTimeout),n};ls.wrap=function(t,e,r){if(e instanceof Array&&(r=e,e=null),!r){r=[];for(var n in t)typeof t[n]=="function"&&r.push(n)}for(var i=0;i<r.length;i++){var s=r[i],o=t[s];t[s]=function(c){var u=ls.operation(e),l=Array.prototype.slice.call(arguments,1),f=l.pop();l.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),f.apply(this,arguments))}),u.attempt(function(){c.apply(t,l)})}.bind(t,o),t[s].options=e}}});var qC=w((r9,kC)=>{kC.exports=LC()});var MC=w((n9,sl)=>{"use strict";var C5=qC(),I5=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],e0=class extends Error{constructor(e){super();e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},T5=(t,e,r)=>{let n=r.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=n,t},R5=t=>I5.includes(t),UC=(t,e)=>new Promise((r,n)=>{e={onFailedAttempt:()=>{},retries:10,...e};let i=C5.operation(e);i.attempt(async s=>{try{r(await t(s))}catch(o){if(!(o instanceof Error)){n(new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`));return}if(o instanceof e0)i.stop(),n(o.originalError);else if(o instanceof TypeError&&!R5(o.message))i.stop(),n(o);else{T5(o,s,e);try{await e.onFailedAttempt(o)}catch(a){n(a);return}i.retry(o)||n(i.mainError())}}})});sl.exports=UC;sl.exports.default=UC;sl.exports.AbortError=e0});var KC=w((i9,FC)=>{"use strict";function B5(t){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^::1$/.test(t)}FC.exports=B5});var jC=w((s9,VC)=>{"use strict";var P5=KC();function N5(t){let{address:e}=t.nodeAddress();return P5(e)}VC.exports=N5});var YC=w((o9,WC)=>{"use strict";var O5=IC(),$C=Te(),{promisify:t0}=TC(),{Multiaddr:D5}=qt(),To=Object.assign($C("libp2p:nat"),{error:$C("libp2p:nat:err")}),{isBrowser:HC}=NC(),r0=MC(),L5=bd(),zC=md(),k5=de(),{codes:{ERR_INVALID_PARAMETERS:q5}}=je(),U5=jC(),n0=7200;function M5(t=1024,e=65535){return Math.floor(Math.random()*(e-t+1)+t)}var GC=class{constructor({peerId:e,addressManager:r,transportManager:n,...i}){if(this._peerId=e,this._addressManager=r,this._transportManager=n,this._enabled=i.enabled,this._externalIp=i.externalIp,this._options={description:i.description||`${zC.name}@${zC.version} ${this._peerId}`,ttl:i.ttl||n0,autoUpdate:i.keepAlive||!0,gateway:i.gateway,enablePMP:Boolean(i.pmp&&i.pmp.enabled)},this._options.ttl<n0)throw k5(new Error(`NatManager ttl should be at least ${n0} seconds`),q5)}start(){HC||!this._enabled||this._start().catch(e=>{To.error(e)})}async _start(){let e=this._transportManager.getAddrs();for(let r of e){let{family:n,host:i,port:s,transport:o}=r.toOptions();if(!r.isThinWaistAddress()||o!=="tcp"||U5(r)||n!==4)continue;let a=this._getClient(),c=this._externalIp||await a.externalIp();if(L5(c))throw new Error(`${c} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`);let u=M5();To(`opening uPnP connection from ${c}:${u} to ${i}:${s}`),await a.map({publicPort:u,privatePort:s,protocol:o.toUpperCase()}),this._addressManager.addObservedAddr(D5.fromNodeAddress({family:4,address:c,port:u},o))}}_getClient(){if(this._client)return this._client;let e=new O5(this._options),r=t0(e.map.bind(e)),n=t0(e.destroy.bind(e)),i=t0(e.externalIp.bind(e));return this._client={map:(...s)=>r0(()=>r(...s),{onFailedAttempt:To.error,unref:!0}),destroy:(...s)=>r0(()=>n(...s),{onFailedAttempt:To.error,unref:!0}),externalIp:(...s)=>r0(()=>i(...s),{onFailedAttempt:To.error,unref:!0})},this._client}async stop(){if(!(HC||!this._client))try{await this._client.destroy(),this._client=null}catch(e){To.error(e)}}};WC.exports=GC});var aq=w((a9,eI)=>{"use strict";var QC=Te(),Ft=Object.assign(QC("libp2p"),{error:QC("libp2p:err")}),{EventEmitter:F5}=Qt(),i0=de(),K5=Rt(),{Multiaddr:V5}=qt(),{MemoryDatastore:j5}=(p1(),h1),$5=$1(),H5=Q1(),s0=pd(),{validate:z5}=hE(),{codes:ol,messages:G5}=je(),W5=gE(),Y5=OE(),Q5=FE(),XC=C2(),X5=U2(),Z5=m_(),ZC=gS(),J5=OS(),eq=Td(),tq=yx(),rq=UA(),nq=FA(),iq=YA(),JC=aC(),o0=mC(),a0=CC(),sq=YC(),{updateSelfPeerRecord:oq}=Cd(),$a=class extends F5{static async create(e){if(e.peerId)return new $a(e);let r=await K5.create();return e.peerId=r,new $a(e)}constructor(e){super();if(this._options=z5(e),this.peerId=this._options.peerId,this.datastore=this._options.datastore,this._options.metrics.enabled){let n=new J5({...this._options.metrics});this.metrics=n}if(this.connectionGater={denyDialPeer:async()=>Promise.resolve(!1),denyDialMultiaddr:async()=>Promise.resolve(!1),denyInboundConnection:async()=>Promise.resolve(!1),denyOutboundConnection:async()=>Promise.resolve(!1),denyInboundEncryptedConnection:async()=>Promise.resolve(!1),denyOutboundEncryptedConnection:async()=>Promise.resolve(!1),denyInboundUpgradedConnection:async()=>Promise.resolve(!1),denyOutboundUpgradedConnection:async()=>Promise.resolve(!1),filterMultiaddrForPeer:async()=>Promise.resolve(!0),...this._options.connectionGater},this.peerStore=new rq({peerId:this.peerId,datastore:this.datastore&&this._options.peerStore.persistence?this.datastore:new j5,addressFilter:this.connectionGater.filterMultiaddrForPeer}),this.addresses=this._options.addresses,this.addressManager=new W5(this.peerId,this._options.addresses),this.addressManager.on("change:addresses",()=>{oq(this).catch(n=>{Ft.error("Error updating self peer record",n)})}),this._modules=this._options.modules,this._config=this._options.config,this._transport=[],this._discovery=new Map,this.connectionManager=new Y5(this,{...this._options.connectionManager}),this._autodialler=new Q5(this,{enabled:this._config.peerDiscovery.autoDial,minConnections:this._options.connectionManager.minConnections,autoDialInterval:this._options.connectionManager.autoDialInterval}),this._options.keychain&&this._options.keychain.datastore){Ft("creating keychain");let n=ZC.generateOptions();this.keychain=new ZC(this._options.keychain.datastore,{...n,...this._options.keychain}),Ft("keychain constructed")}if(this.upgrader=new tq({connectionGater:this.connectionGater,localPeer:this.peerId,metrics:this.metrics,onConnection:n=>this.connectionManager.onConnect(n),onConnectionEnd:n=>this.connectionManager.onDisconnect(n)}),this.transportManager=new eq({libp2p:this,upgrader:this.upgrader,faultTolerance:this._options.transportManager.faultTolerance}),this.natManager=new sq({peerId:this.peerId,addressManager:this.addressManager,transportManager:this.transportManager,...this._options.config.nat}),this.registrar=new iq({peerStore:this.peerStore,connectionManager:this.connectionManager}),this.handle=this.handle.bind(this),this.registrar.handle=this.handle,!this._modules.connEncryption||!this._modules.connEncryption.length)throw i0(new Error(G5.CONN_ENCRYPTION_REQUIRED),ol.CONN_ENCRYPTION_REQUIRED);if(this._modules.connEncryption.forEach(n=>{this.upgrader.cryptos.set(n.protocol,n)}),this.dialer=new Z5({transportManager:this.transportManager,connectionGater:this.connectionGater,peerStore:this.peerStore,metrics:this.metrics,...this._options.dialer}),this._modules.transport.forEach(n=>{let i=n.prototype[Symbol.toStringTag],s=this._config.transport[i];this.transportManager.add(i,n,s)}),this._config.relay.enabled&&(this.transportManager.add(XC.prototype[Symbol.toStringTag],XC),this.relay=new X5(this)),this._modules.streamMuxer&&(this._modules.streamMuxer.forEach(i=>{this.upgrader.muxers.set(i.multicodec,i)}),this.identifyService=new JC({libp2p:this})),this._modules.connProtector)this.upgrader.protector=this._modules.connProtector;else if(globalThis.process!==void 0&&globalThis.process.env&&globalThis.process.env.LIBP2P_FORCE_PNET)throw new Error("Private network is enforced, but no protector was provided");if(this._modules.dht){let n=this._modules.dht;this._dht=n.create({libp2p:this,...this._config.dht})}if(this._modules.pubsub){let n=this._modules.pubsub;this.pubsub=nq(n,this,this._config.pubsub)}this.peerRouting=new $5(this),this.contentRouting=new H5(this),this._onDiscoveryPeer=this._onDiscoveryPeer.bind(this),this.fetchService=new o0(this),this.pingService=new a0(this)}emit(e,...r){return e==="error"&&!this._events.error?(Ft.error(r),!1):super.emit(e,...r)}async start(){Ft("libp2p is starting"),this.identifyService&&await this.handle(Object.values(JC.getProtocolStr(this)),this.identifyService.handleMessage),this.fetchService&&await this.handle(o0.PROTOCOL,this.fetchService.handleMessage),this.pingService&&await this.handle(a0.getProtocolStr(this),this.pingService.handleMessage);try{await this._onStarting(),await this._onDidStart(),Ft("libp2p has started")}catch(e){throw this.emit("error",e),Ft.error("An error occurred starting libp2p",e),await this.stop(),e}}async stop(){Ft("libp2p is stopping");try{this._isStarted=!1,this.identifyService&&await this.identifyService.stop(),this.relay&&this.relay.stop(),this.peerRouting.stop(),await this._autodialler.stop(),await(this._dht&&this._dht.stop());for(let e of this._discovery.values())e.removeListener("peer",this._onDiscoveryPeer);await Promise.all(Array.from(this._discovery.values(),e=>e.stop())),this._discovery=new Map,await this.connectionManager.stop(),await Promise.all([this.pubsub&&this.pubsub.stop(),this.metrics&&this.metrics.stop()]),await this.natManager.stop(),await this.transportManager.close(),await this.unhandle(o0.PROTOCOL),await this.unhandle(a0.getProtocolStr(this)),this.dialer.destroy()}catch(e){e&&(Ft.error(e),this.emit("error",e))}Ft("libp2p has stopped")}async loadKeychain(){if(!!this.keychain)try{await this.keychain.findKeyByName("self")}catch(e){await this.keychain.importPeer("self",this.peerId)}}isStarted(){return this._isStarted}get connections(){return this.connectionManager.connections}dial(e,r){return this._dial(e,r)}async dialProtocol(e,r,n){if(!r||!r.length)throw i0(new Error("no protocols were provided to open a stream"),ol.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this._dial(e,n)).newStream(r)}async _dial(e,r){let{id:n,multiaddrs:i}=s0(e);if(n.equals(this.peerId))throw i0(new Error("Cannot dial self"),ol.ERR_DIALED_SELF);let s=this.connectionManager.get(n);return s?i&&await this.peerStore.addressBook.add(n,i):s=await this.dialer.connectToPeer(e,r),s}get multiaddrs(){let e=this.addressManager.getAnnounceAddrs().map(i=>i.toString());e.length||(e=this.transportManager.getAddrs().map(i=>i.toString())),e=e.concat(this.addressManager.getObservedAddrs().map(i=>i.toString()));let r=this._options.addresses.announceFilter,n=new Set(e);return r(Array.from(n).map(i=>new V5(i)))}async hangUp(e){let{id:r}=s0(e),n=this.connectionManager.connections.get(r.toB58String());!n||await Promise.all(n.map(i=>i.close()))}fetch(e,r){return this.fetchService.fetch(e,r)}ping(e){let{id:r,multiaddrs:n}=s0(e);return n?this.pingService.ping(n[0]):this.pingService.ping(r)}async handle(e,r){e=Array.isArray(e)?e:[e],e.forEach(n=>{this.upgrader.protocols.set(n,r)}),await this.peerStore.protoBook.add(this.peerId,e)}async unhandle(e){e=Array.isArray(e)?e:[e],e.forEach(r=>{this.upgrader.protocols.delete(r)}),await this.peerStore.protoBook.remove(this.peerId,e)}async _onStarting(){let e=this.addressManager.getListenAddrs();await this.transportManager.listen(e),this.natManager.start(),this._config.pubsub.enabled&&this.pubsub&&await this.pubsub.start(),this._config.dht.enabled&&(this._dht&&await this._dht.start(),this._dht.on("peer",this._onDiscoveryPeer)),this.metrics&&this.metrics.start(),this.identifyService&&await this.identifyService.start()}async _onDidStart(){this._isStarted=!0,this.peerStore.on("peer",e=>{this.emit("peer:discovery",e),this._maybeConnect(e).catch(r=>{Ft.error(r)})});for await(let e of this.peerStore.getPeers())this.emit("peer:discovery",e.id);this.connectionManager.start(),await this._autodialler.start(),await this._setupPeerDiscovery(),this.relay&&this.relay.start(),this.peerRouting.start()}_onDiscoveryPeer(e){if(e.id.toB58String()===this.peerId.toB58String()){Ft.error(new Error(ol.ERR_DISCOVERED_SELF));return}e.multiaddrs&&this.peerStore.addressBook.add(e.id,e.multiaddrs).catch(r=>Ft.error(r)),e.protocols&&this.peerStore.protoBook.set(e.id,e.protocols).catch(r=>Ft.error(r))}async _maybeConnect(e){if(this._config.peerDiscovery.autoDial===!0&&!this.connectionManager.get(e)&&(this._options.connectionManager.minConnections||0)>this.connectionManager.size){Ft("connecting to discovered peer %s",e.toB58String());try{await this.dialer.connectToPeer(e)}catch(n){Ft.error(`could not connect to discovered peer ${e.toB58String()} with ${n}`)}}}async _setupPeerDiscovery(){let e=r=>{let n={enabled:!0};if(r.tag&&this._config.peerDiscovery&&this._config.peerDiscovery[r.tag]&&(n={...n,...this._config.peerDiscovery[r.tag]}),n.enabled&&!this._discovery.has(r.tag)){let i;typeof r=="function"?i=new r(Object.assign({},n,{peerId:this.peerId,libp2p:this})):i=r,i.on("peer",this._onDiscoveryPeer),this._discovery.set(r.tag,i)}};for(let r of this._modules.peerDiscovery||[])e(r);for(let r of this.transportManager.getTransports())r.discovery&&e(r.discovery);await Promise.all(Array.from(this._discovery.values(),r=>r.start()))}};eI.exports=$a});return aq();})();
46
46
  /*!
47
47
  * The buffer module from node.js, for the browser.
48
48
  *