libp2p 0.46.11-972b10a9 → 0.46.11-e3ab1929
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 +1 -1
- package/dist/src/connection-manager/auto-dial.js +4 -4
- package/dist/src/connection-manager/auto-dial.js.map +1 -1
- package/dist/src/identify/consts.d.ts +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +21 -21
- package/src/connection-manager/auto-dial.ts +4 -4
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
(?:${He}:){1}(?:(?::${He}){0,4}:${Xt}|(?::${He}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
46
46
|
(?::(?:(?::${He}){0,5}:${Xt}|(?::${He}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
47
47
|
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
48
|
-
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),y_=new RegExp(`(?:^${Xt}$)|(?:^${ma}$)`),g_=new RegExp(`^${Xt}$`),x_=new RegExp(`^${ma}$`),$l=t=>t&&t.exact?y_:new RegExp(`(?:${rn(t)}${Xt}${rn(t)})|(?:${rn(t)}${ma}${rn(t)})`,"g");$l.v4=t=>t&&t.exact?g_:new RegExp(`${rn(t)}${Xt}${rn(t)}`,"g");$l.v6=t=>t&&t.exact?x_:new RegExp(`${rn(t)}${ma}${rn(t)}`,"g");var sy=$l;var fy=te(cy(),1),{isValid:E_,parse:w_}=fy.default,b_=["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"],v_=b_.map(t=>new ly.Netmask(t));function __(t){for(let e of v_)if(e.contains(t))return!0;return!1}function uy(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)}var hy=t=>{if(E_(t)){let e=w_(t);if(e.kind()==="ipv4")return __(e.toNormalizedString());if(e.kind()==="ipv6")return uy(t)}else if(Ri(t)&&sy.v6().test(t))return uy(t)};var ga=hy;function dy(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!ga(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}var kL=Symbol.for("@libp2p/transport");var nn;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(nn||(nn={}));var A_=t=>t.toString().split("/").slice(1),Bo=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),qe=t=>({match:e=>Bo(r=>r===t).match(e),pattern:t}),wa=()=>({match:t=>Bo(e=>typeof e=="string").match(t),pattern:"{string}"}),py=()=>({match:t=>Bo(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),kt=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{Le.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),xa=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{Pc.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),lr=t=>({match:e=>{let r=t.match(e);return r===!1?e:r},pattern:`optional(${t.pattern})`}),fr=(...t)=>({match:e=>{let r;for(let n of t){let i=n.match(e);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${t.map(e=>e.pattern).join(", ")})`}),Ve=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${t.map(e=>e.pattern).join(", ")})`});function et(...t){function e(i){let o=A_(i);for(let s of t){let a=s.match(o);if(a===!1)return!1;o=a}return o}function r(i){return e(i)!==!1}function n(i){let o=e(i);return o===!1?!1:o.length===0}return{matches:r,exactMatch:n}}var zl=Ve(qe("dns4"),wa()),Gl=Ve(qe("dns6"),wa()),Yl=Ve(qe("dnsaddr"),wa()),my=Ve(qe("dns"),wa()),qL=et(zl),VL=et(Gl),$L=et(Yl),HL=et(fr(my,Yl,zl,Gl)),yy=Ve(qe("ip4"),Bo(Ys)),gy=Ve(qe("ip6"),Bo(Ws)),xy=fr(yy,gy),ba=fr(xy,my,zl,Gl,Yl),zL=et(yy),GL=et(gy),YL=et(xy),va=Ve(ba,qe("tcp"),py()),Lo=Ve(ba,qe("udp"),py()),S_=fr(va,Lo),WL=et(va),QL=et(Lo),Wl=Ve(Lo,qe("quic")),_a=Ve(Lo,qe("quic-v1")),I_=fr(Wl,_a),XL=et(Wl),ZL=et(_a),Hl=fr(ba,va,Lo,Wl,_a),Ey=fr(Ve(Hl,qe("ws"),lr(kt()))),jL=et(Ey),wy=fr(Ve(Hl,qe("wss"),lr(kt())),Ve(Hl,qe("tls"),qe("ws"),lr(kt()))),JL=et(wy),by=Ve(S_,qe("webrtc-direct"),xa(),lr(xa()),lr(kt())),e6=et(by),vy=Ve(_a,qe("webtransport"),xa(),xa(),lr(kt())),t6=et(vy),Ea=fr(Ey,wy,Ve(va,lr(kt())),Ve(I_,lr(kt())),Ve(ba,lr(kt())),by,vy,kt()),r6=et(Ea),R_=Ve(Ea,qe("p2p-circuit"),kt()),Ql=et(R_),C_=fr(Ve(Ea,qe("p2p-circuit"),qe("webrtc"),kt()),Ve(Ea,qe("webrtc"),lr(kt())),qe("webrtc")),n6=et(C_);function Xl(t){try{let{address:e}=t.nodeAddress();return!!ga(e)}catch{return!0}}function T_(t,e){let r=Xl(t.multiaddr),n=Xl(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function B_(t,e){return t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function L_(t,e){let r=Ql.exactMatch(t.multiaddr),n=Ql.exactMatch(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function Di(t,e){let r=T_(t,e);if(r!==0)return r;let n=L_(t,e);return n!==0?n:B_(t,e)}var jl=te(Hu(),1),Jl=te(Sy(),1);var Iy=globalThis.fetch,Ry=globalThis.Headers,f6=globalThis.Request,h6=globalThis.Response;function Aa(t,e,r){return`${t}?name=${e}&type=${r}`}async function Cy(t,e){return await(await Iy(t,{headers:new Ry({accept:"application/dns-json"}),signal:e})).json()}function qn(t,e){return`${e}_${t}`}var Zl=Object.assign((0,jl.default)("dns-over-http-resolver"),{error:(0,jl.default)("dns-over-http-resolver:error")}),ef=class{constructor(e={}){this._cache=new Jl.default({max:e?.maxCache??100}),this._TXTcache=new Jl.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Cy,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...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}async resolve(e,r="A"){switch(r){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(qn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Aa(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(qn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Zl.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(qn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Aa(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(qn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Zl.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(qn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Aa(o,e,r),s.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(qn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Zl.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},Ty=ef;var By=Ty;var{code:O_}=be("dnsaddr");async function Ni(t,e={}){let r=new By;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===O_)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var hr;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(hr||(hr={}));var F;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TIMEOUT="ERR_TIMEOUT",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(F||(F={}));var M_={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Ni},addressSorter:Di},transportManager:{faultTolerance:nn.FATAL_ALL}};function Ly(t){let e=Qr(M_,t);if(e.transports==null||e.transports.length<1)throw new b(hr.ERR_TRANSPORTS_REQUIRED,F.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new b(hr.ERR_PROTECTOR_REQUIRED,F.ERR_PROTECTOR_REQUIRED);return e}var Py="keep-alive";var Lg=te(Ig(),1);var EA=ie("libp2p:get-peer");function Ia(t){if(Us(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:de(r),t.forEach(n=>{if(!Mn(n))throw EA.error("multiaddr %s was invalid",n),new b("Invalid Multiaddr",F.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new b("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}else{let o=de(i);if(e==null||!e.equals(o))throw new b("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function wA(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var gf=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new b("missing peer id",F.ERR_INVALID_PARAMETERS);let o={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(o);return}let s=wA(this.#e,o,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,o)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let r=e.peerId;return this.#e.filter(n=>r.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}},Ra=class extends Jr{constructor(e={}){super({...e,queueClass:gf})}hasJob(e){return this.sizeBy({peerId:e})>0}};var Ca="last-dial-failure";var Ta=5,Ba=100,La=50,Rg=1e3*60*7;var tt=ie("libp2p:connection-manager:auto-dial"),Vn={minConnections:Ta,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Rg,autoDialDiscoveredPeersDebounce:10},Pa=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??Vn.minConnections,this.autoDialPriority=r.autoDialPriority??Vn.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??Vn.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??Vn.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??Vn.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??Vn.autoDialDiscoveredPeersDebounce,this.started=!1,this.running=!1,this.queue=new Ra({concurrency:r.autoDialConcurrency??Vn.autoDialConcurrency}),this.queue.addListener("error",i=>{tt.error("error during auto-dial",i)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(i=>{tt.error(i)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(i=>{tt.error(i)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{tt.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{tt.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),r=e.size;if(r>=this.minConnections){this.minConnections>0&&tt.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){tt("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){tt("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,tt("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new On(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[u=>u.addresses.length===0?(tt.trace("not autodialing %p because they have no addresses"),!1):e.has(u.id)?(tt.trace("not autodialing %p because they are already connected"),!1):n.has(u.id)?(tt.trace("not autodialing %p because they are already being dialed"),!1):this.queue.hasJob(u.id)?(tt.trace("not autodialing %p because they are already being autodialed"),!1):!0]}),o=i.sort(()=>Math.random()>.5?1:-1),s=new Yt;for(let u of o)s.has(u.id)||s.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=o.sort((u,l)=>{let f=s.get(u.id)??0,h=s.get(l.id)??0;return f>h?-1:f<h?1:0}).filter(u=>{let l=u.metadata.get(Ca);if(l==null)return!0;let f=parseInt(Z(l));return isNaN(f)?!0:Date.now()-f>this.autoDialPeerRetryThresholdMs});tt("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){tt("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}tt("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(l=>{tt.error("could not connect to peerStore stored peer",l)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(u=>{tt.error("error while autodialing",u)})},this.autoDialIntervalMs))}};var Fi=ie("libp2p:connection-manager:connection-pruner"),Cg={maxConnections:Ba,allow:[]},Da=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??Cg.maxConnections,this.allow=r.allow??Cg.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Fi.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(Fi("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;Fi("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new Yt;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&Fi.error("error loading peer tags",u)}}}let o=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.timeline.open,h=c.timeline.open;return f<h?1:f>h?-1:0}),s=[];for(let a of o)if(Fi("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||s.push(a),s.length===n)break;await Promise.all(s.map(async a=>{try{await a.close()}catch(c){Fi.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:s})}};var _f=te(Xn(),1);function Na(t){let e=new globalThis.AbortController;function r(){e.abort();for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of t){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function sn(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var bf=te(Xn(),1);var Tg=ie("libp2p:connection-manager:utils");async function vf(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await _A(t,e),s=(await Promise.all(n.map(async a=>vf(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return Tg("resolved %s to",t,s.map(a=>a.toString())),s}async function _A(t,e){try{return t=Ye(t.toString()),await t.resolve(e)}catch(r){return Tg.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function Bg(...t){let e=[];for(let n of t)if(n!=null){try{(0,bf.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=Na(e);try{(0,bf.setMaxListeners)?.(1/0,r)}catch{}return r}var lt=ie("libp2p:connection-manager:dial-queue"),Do={addressSorter:Di,maxParallelDials:La,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:1,dialTimeout:3e4,resolvers:{dnsaddr:Ni}},ka=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??Do.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??Do.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??Do.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??Do.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,_f.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))pl.set(n,i);this.queue=new Jr({concurrency:r.maxParallelDials??Do.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{lt.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,r={}){let{peerId:n,multiaddrs:i}=Ia(e),o=i.map(l=>({multiaddr:l,isCertified:!1})),s=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,o,{...r,signal:s})}catch(l){throw s.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return lt("joining existing dial target for %p",n),s.clear(),c.promise;lt("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:AA(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:s}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),s.clear()}).catch(async l=>{if(lt.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),n!=null)try{await this.peerStore.patch(n,{metadata:{[Ca]:G(Date.now().toString())}})}catch(f){lt.error("could not update last dial failure key for %p",n,f)}throw s.aborted?new b(l.message,F.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=Na([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,_f.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new b("Tried to dial self",F.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new b("The dial request is blocked by gater.allowDialPeer",F.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){lt("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),lt("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==F.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await vf(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat(),o=i.filter(l=>{if(this.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let f=l.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),s=new Map;for(let l of o){let f=l.multiaddr.toString(),h=s.get(f);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}s.set(f,l)}let a=[...s.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(lt("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),lt("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new b("The dial request has no valid addresses",F.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new b("dial with more addresses than allowed",F.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let h=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:h!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new b("The connection gater denied all addresses in the dial request",F.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Jr({concurrency:this.maxParallelDialsPerPeer});i.on("error",s=>{lt.error("error dialling",s)});let o=await Promise.any(e.multiaddrs.map(async(s,a)=>{let c=n[a];if(c==null)throw new b("dialAction did not come with an AbortController",F.ERR_INVALID_PARAMETERS);let u=Bg(c.signal,r.signal);u.addEventListener("abort",()=>{lt("dial to %a aborted",s)});let l=sn();return await i.add(async()=>{if(u.aborted){lt("dial to %a was aborted before reaching the head of the peer dial queue",s),l.reject(new ti);return}await this.queue.add(async()=>{try{if(u.aborted){lt("dial to %a was aborted before reaching the head of the dial queue",s),l.reject(new ti);return}e.status="active";let f=await this.transportManager.dial(s,{...r,signal:u});if(c.signal.aborted){lt("multiple dials succeeded, closing superfluous connection"),f.close().catch(h=>{lt.error("error closing superfluous connection",h)}),l.reject(new ti);return}n[a]=void 0,n.forEach(h=>{h!==void 0&&h.abort()}),lt("dial to %a succeeded",s),l.resolve(f)}catch(f){lt.error("error during dial of %a",s,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(o==null)throw new b("successful dial led to empty object returned from peer dial queue",F.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",o}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function AA(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Tt=ie("libp2p:connection-manager"),RA=50,$n={minConnections:Ta,maxConnections:Ba,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Oa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??$n.maxConnections;let n=r.minConnections??$n.minConnections;if(this.maxConnections<n)throw new b("Connection Manager maxConnections must be greater than minConnections",F.ERR_INVALID_PARAMETERS);this.connections=new Yt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>Ye(i)),this.deny=(r.deny??[]).map(i=>Ye(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??$n.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Lg.RateLimiterMemory({points:r.inboundConnectionThreshold??$n.inboundConnectionThreshold,duration:1}),this.autoDial=new Pa({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??$n.autoDialConcurrency,autoDialPriority:r.autoDialPriority??$n.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??$n.autoDialMaxQueueLength}),this.connectionPruner=new Da({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new ka({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??Di,maxParallelDials:r.maxParallelDials??La,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,maxParallelDialsPerPeer:r.maxParallelDialsPerPeer??1,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Ni}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let o=`${i.direction} ${i.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let o={};for(let s of i.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))e[s]=e[s]??[],e[s].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);r[n]=i[o]}return r}}),this.autoDial.start(),this.started=!0,Tt("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(Py)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{Tt.error(n)})}))}).catch(e=>{Tt.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){Tt.error(i)}})());Tt("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),Tt("stopped")}onConnect(e){this._onConnect(e).catch(r=>{Tt.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),o=!1;i!=null?i.push(r):(o=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(o=>o.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new b("Not started",F.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=Ia(e);if(n!=null&&r.force!==!0){Tt("dial %p",n);let a=this.getConnections(n);if(a.length>0)return Tt("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??RA}),o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)a.id===i.id&&(s=!0);return s||o.push(i),i}async closeConnections(e,r={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(o){i.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return Tt("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return Tt("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return Tt("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(Tt("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var Ma=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Ki=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ma(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Ma(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Rf=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Hn(t={}){return CA(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function CA(t,e){e=e??{};let r=e.onEnd,n=new Ki,i,o,s,a=sn(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{o=x=>{o=null,n.push(x);try{y(t(n))}catch(w){g(w)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=sn()})}},u=y=>o!=null?o(y):(n.push(y),i),l=y=>(n=new Ki,o!=null?o({error:y}):(n.push({error:y}),i)),f=y=>{if(s)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},h=y=>s?i:(s=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new Ki,h(),{done:!0}),d=y=>(h(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:f,end:h,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,w;g!=null&&(x=new Promise((C,_)=>{w=()=>{_(new Rf)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,x])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength}},i}function TA(t){return t[Symbol.asyncIterator]!=null}function BA(...t){let e=[];for(let r of t)TA(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=Hn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var an=BA;function zn(t,...e){if(t==null)throw new Error("Empty pipeline");if(Cf(t)){let n=t;t=()=>n.source}else if(Dg(t)||Pg(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Cf(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Cf(r[n])&&(r[n]=PA(r[n]));return LA(...r)}var LA=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Pg=t=>t?.[Symbol.asyncIterator]!=null,Dg=t=>t?.[Symbol.iterator]!=null,Cf=t=>t==null?!1:t.sink!=null&&t.source!=null,PA=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Hn({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,o=t.source;if(Pg(o))i=async function*(){yield*o,n.end()};else if(Dg(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return an(n,i())}return t.source};function DA(t){return t[Symbol.asyncIterator]!=null}function NA(t,e){if(DA(t))return async function*(){for await(let a of t)yield e(a)}();let r=fa(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of r)yield e(a)}();let s=e;return function*(){yield o;for(let a of r)yield s(a)}()}var Ng=NA;async function*No(t,e){yield*Ng(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Ua(t){let e=new Set;return Qt(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*Fa(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new b(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var Ka=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new b("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*zn(an(...this.routers.map(n=>n.findProviders(e,r))),n=>No(n,this.components.peerStore),n=>Ua(n),n=>Fa(n))}async provide(e,r={}){if(this.routers.length===0)throw new b("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new b(hr.NOT_STARTED_YET,F.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new b(hr.NOT_STARTED_YET,F.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function kA(t){return t[Symbol.asyncIterator]!=null}function OA(t){if(kA(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var qa=OA;var MA=ie("libp2p:peer-routing"),Va=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new b("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new b("Should not try to find self",F.ERR_FIND_SELF);let n=await zn(an(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(o){MA.error(o)}}())),i=>Qt(i,Boolean),i=>No(i,this.components.peerStore),async i=>qa(i));if(n!=null)return n;throw new b(hr.NOT_FOUND,F.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new b("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*zn(an(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>No(n,this.components.peerStore),n=>Ua(n),n=>Fa(n))}};var Tf=ie("libp2p:registrar"),Bf=32,Lf=64,$a=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new b(`No handler registered for protocol ${e}`,F.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new b(`Handler already registered for protocol ${e}`,F.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=Qr.bind({ignoreUndefined:!0})({maxInboundStreams:Bf,maxOutboundStreams:Lf},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,r){if(r==null)throw new b("invalid topology",F.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect?.(r)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&Tf.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){Tf("peer %p connected but the connection manager did not have a connection",n);return}for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.onConnect?.(r,i)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&Tf.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(s=>!r.protocols.includes(s)),o=r.protocols.filter(s=>!(n?.protocols??[]).includes(s));for(let s of i){let a=this.topologies.get(s);if(a!=null)for(let c of a.values())c.onDisconnect?.(r.id)}for(let s of o){let a=this.topologies.get(s);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect?.(r.id,u)}}}};var Pf=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function kg(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Pf({name:e,metrics:r}):n=new Map,n}var Gn=ie("libp2p:transports"),Ha=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=kg({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??nn.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new b("Transport must have a valid tag",F.ERR_INVALID_KEY);if(this.transports.has(r))throw new b(`There is already a transport with the tag ${r}`,F.ERR_DUPLICATE_TRANSPORT);Gn("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[r,n]of this.listeners)for(Gn("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),Gn("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new b(`No transport available for address ${String(e)}`,F.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=F.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 Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(!this.isStarted())throw new b("Not started",F.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){Gn("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let o=i.filter(e),s=[];for(let u of o){Gn("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=f.findIndex(p=>p===l);f.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),s.push(l.listen(u))}if(s.length===0){r.push(n);continue}if((await Promise.allSettled(s)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==nn.NO_FATAL)throw new b(`Transport (${n}) could not listen on any available address`,F.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===nn.FATAL_ALL)throw new b(n,F.ERR_NO_VALID_ADDRESSES);Gn(`libp2p in dial mode only: ${n}`)}}async remove(e){Gn("removing %s",e);for(let r of this.listeners.get(e)??[])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)}};var Of=te(Xn(),1);var Dr="/multistream/1.0.0";function Df(t){let e=async function*(){let r=yield,n=new Je;for await(let i of t){if(r==null){n.append(i),r=yield n,n=new Je;continue}for(n.append(i);n.length>=r;){let o=n.sublist(0,r);if(n.consume(r),r=yield o,r==null){n.length>0&&(r=yield n,n=new Je);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function za(t){let e=Hn(),r=Df(t.source),n=sn(),i,o=t.sink(async function*(){yield*e,yield*await n.promise}());return o.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await o},source:r},rest:()=>e.end(),write:e.push,read:async()=>{let a=await r.next();if(a.value!=null)return a.value}}}var ko=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Og(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function Mg(t,e,r){let n=r??{},i=Og(t);async function*o(){let s,a=()=>{s?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new ko(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:h,abortCode:p}=n;f(new ko(h,p))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function Ga(t){return t[Symbol.asyncIterator]!=null}var Ya=t=>{let e=Et(t),r=Kt(e);return Nt(t,r),Ya.bytes=e,r};Ya.bytes=0;function Wa(t,e){e=e??{};let r=e.lengthEncoder??Ya;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Ga(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}Wa.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??Ya;return new Je(r(t.byteLength),t)};var qi=te(Kl(),1);var UA=8,FA=1024*1024*4,Yn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Yn||(Yn={}));var Nf=t=>{let e=Lr(t);return Nf.bytes=Et(e),e};Nf.bytes=0;function Oo(t,e){let r=new Je,n=Yn.LENGTH,i=-1,o=e?.lengthDecoder??Nf,s=e?.maxLengthLength??UA,a=e?.maxDataLength??FA;function*c(){for(;r.byteLength>0;){if(n===Yn.LENGTH)try{if(i=o(r),i<0)throw(0,qi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,qi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=Yn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,qi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Yn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=Yn.LENGTH}}}return Ga(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,qi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,qi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Oo.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await t.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return Oo(n,{...e??{},onLength:o=>{r=o}})};var VA=ie("libp2p:mss"),Ug=G(`
|
|
48
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),y_=new RegExp(`(?:^${Xt}$)|(?:^${ma}$)`),g_=new RegExp(`^${Xt}$`),x_=new RegExp(`^${ma}$`),$l=t=>t&&t.exact?y_:new RegExp(`(?:${rn(t)}${Xt}${rn(t)})|(?:${rn(t)}${ma}${rn(t)})`,"g");$l.v4=t=>t&&t.exact?g_:new RegExp(`${rn(t)}${Xt}${rn(t)}`,"g");$l.v6=t=>t&&t.exact?x_:new RegExp(`${rn(t)}${ma}${rn(t)}`,"g");var sy=$l;var fy=te(cy(),1),{isValid:E_,parse:w_}=fy.default,b_=["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"],v_=b_.map(t=>new ly.Netmask(t));function __(t){for(let e of v_)if(e.contains(t))return!0;return!1}function uy(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)}var hy=t=>{if(E_(t)){let e=w_(t);if(e.kind()==="ipv4")return __(e.toNormalizedString());if(e.kind()==="ipv6")return uy(t)}else if(Ri(t)&&sy.v6().test(t))return uy(t)};var ga=hy;function dy(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!ga(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}var kL=Symbol.for("@libp2p/transport");var nn;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(nn||(nn={}));var A_=t=>t.toString().split("/").slice(1),Bo=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),qe=t=>({match:e=>Bo(r=>r===t).match(e),pattern:t}),wa=()=>({match:t=>Bo(e=>typeof e=="string").match(t),pattern:"{string}"}),py=()=>({match:t=>Bo(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),kt=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{Le.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),xa=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{Pc.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),lr=t=>({match:e=>{let r=t.match(e);return r===!1?e:r},pattern:`optional(${t.pattern})`}),fr=(...t)=>({match:e=>{let r;for(let n of t){let i=n.match(e);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${t.map(e=>e.pattern).join(", ")})`}),Ve=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${t.map(e=>e.pattern).join(", ")})`});function et(...t){function e(i){let o=A_(i);for(let s of t){let a=s.match(o);if(a===!1)return!1;o=a}return o}function r(i){return e(i)!==!1}function n(i){let o=e(i);return o===!1?!1:o.length===0}return{matches:r,exactMatch:n}}var zl=Ve(qe("dns4"),wa()),Gl=Ve(qe("dns6"),wa()),Yl=Ve(qe("dnsaddr"),wa()),my=Ve(qe("dns"),wa()),qL=et(zl),VL=et(Gl),$L=et(Yl),HL=et(fr(my,Yl,zl,Gl)),yy=Ve(qe("ip4"),Bo(Ys)),gy=Ve(qe("ip6"),Bo(Ws)),xy=fr(yy,gy),ba=fr(xy,my,zl,Gl,Yl),zL=et(yy),GL=et(gy),YL=et(xy),va=Ve(ba,qe("tcp"),py()),Lo=Ve(ba,qe("udp"),py()),S_=fr(va,Lo),WL=et(va),QL=et(Lo),Wl=Ve(Lo,qe("quic")),_a=Ve(Lo,qe("quic-v1")),I_=fr(Wl,_a),XL=et(Wl),ZL=et(_a),Hl=fr(ba,va,Lo,Wl,_a),Ey=fr(Ve(Hl,qe("ws"),lr(kt()))),jL=et(Ey),wy=fr(Ve(Hl,qe("wss"),lr(kt())),Ve(Hl,qe("tls"),qe("ws"),lr(kt()))),JL=et(wy),by=Ve(S_,qe("webrtc-direct"),xa(),lr(xa()),lr(kt())),e6=et(by),vy=Ve(_a,qe("webtransport"),xa(),xa(),lr(kt())),t6=et(vy),Ea=fr(Ey,wy,Ve(va,lr(kt())),Ve(I_,lr(kt())),Ve(ba,lr(kt())),by,vy,kt()),r6=et(Ea),R_=Ve(Ea,qe("p2p-circuit"),kt()),Ql=et(R_),C_=fr(Ve(Ea,qe("p2p-circuit"),qe("webrtc"),kt()),Ve(Ea,qe("webrtc"),lr(kt())),qe("webrtc")),n6=et(C_);function Xl(t){try{let{address:e}=t.nodeAddress();return!!ga(e)}catch{return!0}}function T_(t,e){let r=Xl(t.multiaddr),n=Xl(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function B_(t,e){return t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function L_(t,e){let r=Ql.exactMatch(t.multiaddr),n=Ql.exactMatch(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function Di(t,e){let r=T_(t,e);if(r!==0)return r;let n=L_(t,e);return n!==0?n:B_(t,e)}var jl=te(Hu(),1),Jl=te(Sy(),1);var Iy=globalThis.fetch,Ry=globalThis.Headers,f6=globalThis.Request,h6=globalThis.Response;function Aa(t,e,r){return`${t}?name=${e}&type=${r}`}async function Cy(t,e){return await(await Iy(t,{headers:new Ry({accept:"application/dns-json"}),signal:e})).json()}function qn(t,e){return`${e}_${t}`}var Zl=Object.assign((0,jl.default)("dns-over-http-resolver"),{error:(0,jl.default)("dns-over-http-resolver:error")}),ef=class{constructor(e={}){this._cache=new Jl.default({max:e?.maxCache??100}),this._TXTcache=new Jl.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Cy,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...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}async resolve(e,r="A"){switch(r){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(qn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Aa(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(qn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Zl.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(qn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Aa(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(qn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Zl.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(qn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Aa(o,e,r),s.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(qn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Zl.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},Ty=ef;var By=Ty;var{code:O_}=be("dnsaddr");async function Ni(t,e={}){let r=new By;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===O_)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var hr;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(hr||(hr={}));var F;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TIMEOUT="ERR_TIMEOUT",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(F||(F={}));var M_={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Ni},addressSorter:Di},transportManager:{faultTolerance:nn.FATAL_ALL}};function Ly(t){let e=Qr(M_,t);if(e.transports==null||e.transports.length<1)throw new b(hr.ERR_TRANSPORTS_REQUIRED,F.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new b(hr.ERR_PROTECTOR_REQUIRED,F.ERR_PROTECTOR_REQUIRED);return e}var Py="keep-alive";var Lg=te(Ig(),1);var EA=ie("libp2p:get-peer");function Ia(t){if(Us(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:de(r),t.forEach(n=>{if(!Mn(n))throw EA.error("multiaddr %s was invalid",n),new b("Invalid Multiaddr",F.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new b("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}else{let o=de(i);if(e==null||!e.equals(o))throw new b("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function wA(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var gf=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new b("missing peer id",F.ERR_INVALID_PARAMETERS);let o={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(o);return}let s=wA(this.#e,o,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,o)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let r=e.peerId;return this.#e.filter(n=>r.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}},Ra=class extends Jr{constructor(e={}){super({...e,queueClass:gf})}hasJob(e){return this.sizeBy({peerId:e})>0}};var Ca="last-dial-failure";var Ta=5,Ba=100,La=50,Rg=1e3*60*7;var tt=ie("libp2p:connection-manager:auto-dial"),Vn={minConnections:Ta,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Rg,autoDialDiscoveredPeersDebounce:10},Pa=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??Vn.minConnections,this.autoDialPriority=r.autoDialPriority??Vn.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??Vn.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??Vn.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??Vn.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??Vn.autoDialDiscoveredPeersDebounce,this.started=!1,this.running=!1,this.queue=new Ra({concurrency:r.autoDialConcurrency??Vn.autoDialConcurrency}),this.queue.addListener("error",i=>{tt.error("error during auto-dial",i)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(i=>{tt.error(i)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(i=>{tt.error(i)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{tt.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{tt.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),r=e.size;if(r>=this.minConnections){this.minConnections>0&&tt.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){tt("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){tt("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,tt("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new On(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[u=>u.addresses.length===0?(tt.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(tt.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(tt.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.hasJob(u.id)?(tt.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),o=i.sort(()=>Math.random()>.5?1:-1),s=new Yt;for(let u of o)s.has(u.id)||s.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=o.sort((u,l)=>{let f=s.get(u.id)??0,h=s.get(l.id)??0;return f>h?-1:f<h?1:0}).filter(u=>{let l=u.metadata.get(Ca);if(l==null)return!0;let f=parseInt(Z(l));return isNaN(f)?!0:Date.now()-f>this.autoDialPeerRetryThresholdMs});tt("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){tt("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}tt("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(l=>{tt.error("could not connect to peerStore stored peer",l)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(u=>{tt.error("error while autodialing",u)})},this.autoDialIntervalMs))}};var Fi=ie("libp2p:connection-manager:connection-pruner"),Cg={maxConnections:Ba,allow:[]},Da=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??Cg.maxConnections,this.allow=r.allow??Cg.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Fi.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(Fi("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;Fi("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new Yt;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&Fi.error("error loading peer tags",u)}}}let o=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.timeline.open,h=c.timeline.open;return f<h?1:f>h?-1:0}),s=[];for(let a of o)if(Fi("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||s.push(a),s.length===n)break;await Promise.all(s.map(async a=>{try{await a.close()}catch(c){Fi.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:s})}};var _f=te(Xn(),1);function Na(t){let e=new globalThis.AbortController;function r(){e.abort();for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of t){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function sn(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var bf=te(Xn(),1);var Tg=ie("libp2p:connection-manager:utils");async function vf(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await _A(t,e),s=(await Promise.all(n.map(async a=>vf(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return Tg("resolved %s to",t,s.map(a=>a.toString())),s}async function _A(t,e){try{return t=Ye(t.toString()),await t.resolve(e)}catch(r){return Tg.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function Bg(...t){let e=[];for(let n of t)if(n!=null){try{(0,bf.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=Na(e);try{(0,bf.setMaxListeners)?.(1/0,r)}catch{}return r}var lt=ie("libp2p:connection-manager:dial-queue"),Do={addressSorter:Di,maxParallelDials:La,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:1,dialTimeout:3e4,resolvers:{dnsaddr:Ni}},ka=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??Do.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??Do.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??Do.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??Do.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,_f.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))pl.set(n,i);this.queue=new Jr({concurrency:r.maxParallelDials??Do.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{lt.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,r={}){let{peerId:n,multiaddrs:i}=Ia(e),o=i.map(l=>({multiaddr:l,isCertified:!1})),s=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,o,{...r,signal:s})}catch(l){throw s.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return lt("joining existing dial target for %p",n),s.clear(),c.promise;lt("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:AA(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:s}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),s.clear()}).catch(async l=>{if(lt.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),n!=null)try{await this.peerStore.patch(n,{metadata:{[Ca]:G(Date.now().toString())}})}catch(f){lt.error("could not update last dial failure key for %p",n,f)}throw s.aborted?new b(l.message,F.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=Na([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,_f.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new b("Tried to dial self",F.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new b("The dial request is blocked by gater.allowDialPeer",F.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){lt("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),lt("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==F.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await vf(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat(),o=i.filter(l=>{if(this.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let f=l.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),s=new Map;for(let l of o){let f=l.multiaddr.toString(),h=s.get(f);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}s.set(f,l)}let a=[...s.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(lt("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),lt("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new b("The dial request has no valid addresses",F.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new b("dial with more addresses than allowed",F.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let h=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:h!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new b("The connection gater denied all addresses in the dial request",F.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Jr({concurrency:this.maxParallelDialsPerPeer});i.on("error",s=>{lt.error("error dialling",s)});let o=await Promise.any(e.multiaddrs.map(async(s,a)=>{let c=n[a];if(c==null)throw new b("dialAction did not come with an AbortController",F.ERR_INVALID_PARAMETERS);let u=Bg(c.signal,r.signal);u.addEventListener("abort",()=>{lt("dial to %a aborted",s)});let l=sn();return await i.add(async()=>{if(u.aborted){lt("dial to %a was aborted before reaching the head of the peer dial queue",s),l.reject(new ti);return}await this.queue.add(async()=>{try{if(u.aborted){lt("dial to %a was aborted before reaching the head of the dial queue",s),l.reject(new ti);return}e.status="active";let f=await this.transportManager.dial(s,{...r,signal:u});if(c.signal.aborted){lt("multiple dials succeeded, closing superfluous connection"),f.close().catch(h=>{lt.error("error closing superfluous connection",h)}),l.reject(new ti);return}n[a]=void 0,n.forEach(h=>{h!==void 0&&h.abort()}),lt("dial to %a succeeded",s),l.resolve(f)}catch(f){lt.error("error during dial of %a",s,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(o==null)throw new b("successful dial led to empty object returned from peer dial queue",F.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",o}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function AA(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Tt=ie("libp2p:connection-manager"),RA=50,$n={minConnections:Ta,maxConnections:Ba,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Oa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??$n.maxConnections;let n=r.minConnections??$n.minConnections;if(this.maxConnections<n)throw new b("Connection Manager maxConnections must be greater than minConnections",F.ERR_INVALID_PARAMETERS);this.connections=new Yt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>Ye(i)),this.deny=(r.deny??[]).map(i=>Ye(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??$n.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Lg.RateLimiterMemory({points:r.inboundConnectionThreshold??$n.inboundConnectionThreshold,duration:1}),this.autoDial=new Pa({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??$n.autoDialConcurrency,autoDialPriority:r.autoDialPriority??$n.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??$n.autoDialMaxQueueLength}),this.connectionPruner=new Da({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new ka({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??Di,maxParallelDials:r.maxParallelDials??La,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,maxParallelDialsPerPeer:r.maxParallelDialsPerPeer??1,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Ni}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let o=`${i.direction} ${i.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let o={};for(let s of i.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))e[s]=e[s]??[],e[s].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);r[n]=i[o]}return r}}),this.autoDial.start(),this.started=!0,Tt("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(Py)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{Tt.error(n)})}))}).catch(e=>{Tt.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){Tt.error(i)}})());Tt("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),Tt("stopped")}onConnect(e){this._onConnect(e).catch(r=>{Tt.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),o=!1;i!=null?i.push(r):(o=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(o=>o.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new b("Not started",F.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=Ia(e);if(n!=null&&r.force!==!0){Tt("dial %p",n);let a=this.getConnections(n);if(a.length>0)return Tt("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??RA}),o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)a.id===i.id&&(s=!0);return s||o.push(i),i}async closeConnections(e,r={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(o){i.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return Tt("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return Tt("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return Tt("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(Tt("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var Ma=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Ki=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ma(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Ma(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Rf=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Hn(t={}){return CA(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function CA(t,e){e=e??{};let r=e.onEnd,n=new Ki,i,o,s,a=sn(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{o=x=>{o=null,n.push(x);try{y(t(n))}catch(w){g(w)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=sn()})}},u=y=>o!=null?o(y):(n.push(y),i),l=y=>(n=new Ki,o!=null?o({error:y}):(n.push({error:y}),i)),f=y=>{if(s)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},h=y=>s?i:(s=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new Ki,h(),{done:!0}),d=y=>(h(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:f,end:h,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,w;g!=null&&(x=new Promise((C,_)=>{w=()=>{_(new Rf)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,x])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength}},i}function TA(t){return t[Symbol.asyncIterator]!=null}function BA(...t){let e=[];for(let r of t)TA(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=Hn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var an=BA;function zn(t,...e){if(t==null)throw new Error("Empty pipeline");if(Cf(t)){let n=t;t=()=>n.source}else if(Dg(t)||Pg(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Cf(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Cf(r[n])&&(r[n]=PA(r[n]));return LA(...r)}var LA=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Pg=t=>t?.[Symbol.asyncIterator]!=null,Dg=t=>t?.[Symbol.iterator]!=null,Cf=t=>t==null?!1:t.sink!=null&&t.source!=null,PA=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Hn({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,o=t.source;if(Pg(o))i=async function*(){yield*o,n.end()};else if(Dg(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return an(n,i())}return t.source};function DA(t){return t[Symbol.asyncIterator]!=null}function NA(t,e){if(DA(t))return async function*(){for await(let a of t)yield e(a)}();let r=fa(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of r)yield e(a)}();let s=e;return function*(){yield o;for(let a of r)yield s(a)}()}var Ng=NA;async function*No(t,e){yield*Ng(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Ua(t){let e=new Set;return Qt(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*Fa(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new b(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var Ka=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new b("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*zn(an(...this.routers.map(n=>n.findProviders(e,r))),n=>No(n,this.components.peerStore),n=>Ua(n),n=>Fa(n))}async provide(e,r={}){if(this.routers.length===0)throw new b("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new b(hr.NOT_STARTED_YET,F.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new b(hr.NOT_STARTED_YET,F.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function kA(t){return t[Symbol.asyncIterator]!=null}function OA(t){if(kA(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var qa=OA;var MA=ie("libp2p:peer-routing"),Va=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new b("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new b("Should not try to find self",F.ERR_FIND_SELF);let n=await zn(an(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(o){MA.error(o)}}())),i=>Qt(i,Boolean),i=>No(i,this.components.peerStore),async i=>qa(i));if(n!=null)return n;throw new b(hr.NOT_FOUND,F.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new b("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*zn(an(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>No(n,this.components.peerStore),n=>Ua(n),n=>Fa(n))}};var Tf=ie("libp2p:registrar"),Bf=32,Lf=64,$a=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new b(`No handler registered for protocol ${e}`,F.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new b(`Handler already registered for protocol ${e}`,F.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=Qr.bind({ignoreUndefined:!0})({maxInboundStreams:Bf,maxOutboundStreams:Lf},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,r){if(r==null)throw new b("invalid topology",F.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect?.(r)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&Tf.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){Tf("peer %p connected but the connection manager did not have a connection",n);return}for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.onConnect?.(r,i)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&Tf.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(s=>!r.protocols.includes(s)),o=r.protocols.filter(s=>!(n?.protocols??[]).includes(s));for(let s of i){let a=this.topologies.get(s);if(a!=null)for(let c of a.values())c.onDisconnect?.(r.id)}for(let s of o){let a=this.topologies.get(s);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect?.(r.id,u)}}}};var Pf=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function kg(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Pf({name:e,metrics:r}):n=new Map,n}var Gn=ie("libp2p:transports"),Ha=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=kg({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??nn.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new b("Transport must have a valid tag",F.ERR_INVALID_KEY);if(this.transports.has(r))throw new b(`There is already a transport with the tag ${r}`,F.ERR_DUPLICATE_TRANSPORT);Gn("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[r,n]of this.listeners)for(Gn("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),Gn("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new b(`No transport available for address ${String(e)}`,F.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=F.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 Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(!this.isStarted())throw new b("Not started",F.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){Gn("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let o=i.filter(e),s=[];for(let u of o){Gn("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=f.findIndex(p=>p===l);f.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),s.push(l.listen(u))}if(s.length===0){r.push(n);continue}if((await Promise.allSettled(s)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==nn.NO_FATAL)throw new b(`Transport (${n}) could not listen on any available address`,F.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===nn.FATAL_ALL)throw new b(n,F.ERR_NO_VALID_ADDRESSES);Gn(`libp2p in dial mode only: ${n}`)}}async remove(e){Gn("removing %s",e);for(let r of this.listeners.get(e)??[])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)}};var Of=te(Xn(),1);var Dr="/multistream/1.0.0";function Df(t){let e=async function*(){let r=yield,n=new Je;for await(let i of t){if(r==null){n.append(i),r=yield n,n=new Je;continue}for(n.append(i);n.length>=r;){let o=n.sublist(0,r);if(n.consume(r),r=yield o,r==null){n.length>0&&(r=yield n,n=new Je);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function za(t){let e=Hn(),r=Df(t.source),n=sn(),i,o=t.sink(async function*(){yield*e,yield*await n.promise}());return o.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await o},source:r},rest:()=>e.end(),write:e.push,read:async()=>{let a=await r.next();if(a.value!=null)return a.value}}}var ko=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Og(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function Mg(t,e,r){let n=r??{},i=Og(t);async function*o(){let s,a=()=>{s?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new ko(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:h,abortCode:p}=n;f(new ko(h,p))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function Ga(t){return t[Symbol.asyncIterator]!=null}var Ya=t=>{let e=Et(t),r=Kt(e);return Nt(t,r),Ya.bytes=e,r};Ya.bytes=0;function Wa(t,e){e=e??{};let r=e.lengthEncoder??Ya;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Ga(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}Wa.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??Ya;return new Je(r(t.byteLength),t)};var qi=te(Kl(),1);var UA=8,FA=1024*1024*4,Yn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Yn||(Yn={}));var Nf=t=>{let e=Lr(t);return Nf.bytes=Et(e),e};Nf.bytes=0;function Oo(t,e){let r=new Je,n=Yn.LENGTH,i=-1,o=e?.lengthDecoder??Nf,s=e?.maxLengthLength??UA,a=e?.maxDataLength??FA;function*c(){for(;r.byteLength>0;){if(n===Yn.LENGTH)try{if(i=o(r),i<0)throw(0,qi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,qi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=Yn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,qi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Yn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=Yn.LENGTH}}}return Ga(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,qi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,qi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Oo.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await t.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return Oo(n,{...e??{},onLength:o=>{r=o}})};var VA=ie("libp2p:mss"),Ug=G(`
|
|
49
49
|
`);function Mo(t){let e=new Je(t,Ug);return Wa.single(e)}function Wn(t,e,r={}){let n=Mo(e);r.writeBytes===!0?t.push(n.subarray()):t.push(n)}function Fg(t,e,r={}){let n=new Je;for(let i of e)n.append(Mo(i));r.writeBytes===!0?t.push(n.subarray()):t.push(n)}async function $A(t,e){let r=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>t.next(r)},i=n;e?.signal!=null&&(i=Mg(n,e.signal));let o=a=>{r=a},s=await zn(i,a=>Oo(a,{onLength:o,maxDataLength:1024}),async a=>qa(a));if(s==null||s.length===0)throw new b("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(s.get(s.byteLength-1)!==Ug[0])throw VA.error("Invalid mss message - missing newline - %s",s.subarray()),new b("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return s.sublist(0,-1)}async function Vi(t,e){let r=await $A(t,e);return Z(r.subarray())}var Uo=ie("libp2p:mss:select");async function Fo(t,e,r={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:o,stream:s}=za(t),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");Uo.trace('select: write ["%s", "%s"]',Dr,a);let c=G(Dr),u=G(a);Fg(i,[c,u],r);let l=await Vi(n,r);if(Uo.trace('select: read "%s"',l),l===Dr&&(l=await Vi(n,r),Uo.trace('select: read "%s"',l)),l===a)return o(),{stream:s,protocol:a};for(let f of e){Uo.trace('select: write "%s"',f),Wn(i,G(f),r);let h=await Vi(n,r);if(Uo.trace('select: read "%s" for "%s"',h,f),h===f)return o(),{stream:s,protocol:f}}throw o(),new b("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var Ko=ie("libp2p:mss:handle");async function qo(t,e,r){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:o,stream:s}=za(t);for(;;){let a=await Vi(i,r);if(Ko.trace('read "%s"',a),a===Dr){Ko.trace('respond with "%s" for "%s"',Dr,a),Wn(n,G(Dr),r);continue}if(e.includes(a))return Wn(n,G(a),r),Ko.trace('respond with "%s" for "%s"',a,a),o(),{stream:s,protocol:a};if(a==="ls"){Wn(n,new Je(...e.map(c=>Mo(G(c)))),r),Ko.trace('respond with "%s" for %s',e,a);continue}Wn(n,G("na"),r),Ko('respond with "na" for "%s"',a)}}var Vg=te(Xn(),1);var qg=Symbol.for("@libp2p/connection");var Qa=ie("libp2p:connection"),zA=500,kf=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:o,abort:s,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this._newStream=i,this._close=o,this._abort=s,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[qg]=!0;get streams(){return this._getStreams()}async newStream(e,r){if(this.status==="closing")throw new b("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new b("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&r?.runOnTransientConnection!==!0)throw new b("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,r);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){Qa("closing connection to %a",this.remoteAddr),this.status="closing",e.signal=e?.signal??AbortSignal.timeout(zA);try{(0,Vg.setMaxListeners)?.(1/0,e.signal)}catch{}try{await Promise.all(this.streams.map(async r=>r.close(e))),await this._close(e),this.timeline.close=Date.now(),this.status="closed"}catch(r){Qa.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(e){Qa.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(r=>{r.abort(e)}),Qa.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function $g(t){return new kf(t)}var Be=ie("libp2p:upgrader");function YA(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Bf}function WA(t,e,r={}){try{let{options:n}=e.getHandler(t);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??Lf}function Hg(t,e,r){let n=0;return r.streams.forEach(i=>{i.direction===e&&i.protocol===t&&n++}),n}var Xa=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,r){this.components=e,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,r,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,r))throw new b(`The multiaddr connection is blocked by gater.${n}`,F.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new b("connection denied",F.ERR_CONNECTION_DENIED);let i,o,s,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),l=()=>{e.abort(new b("inbound upgrade timeout",F.ERR_TIMEOUT))};u.addEventListener("abort",l,{once:!0});try{(0,Of.setMaxListeners)?.(1/0,u)}catch{}try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new b("The multiaddr connection is blocked by gater.acceptConnection",F.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),Be("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(Be("protecting the inbound connection"),f=await h.protect(e))}try{if(i=f,r?.skipEncryption!==!0){({conn:i,remotePeer:o,protocol:c}=await this._encryptInbound(f));let h={...f,...i};await this.shouldBlockConnection(o,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new b("inbound connection that skipped encryption must have a peer id",F.ERR_INVALID_MULTIADDR);let p=de(h);c="native",o=p}if(s=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...f,...i},this.muxers);a=h.muxerFactory,s=h.stream}}catch(h){throw Be.error("Failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(o,e,"denyInboundUpgradedConnection"),Be("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:o,transient:r?.transient})}finally{u.removeEventListener("abort",l),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=de(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let o,s,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),Be("Starting the outbound connection upgrade");let l=e;if(r?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(e))}try{if(o=l,r?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...o};await this.shouldBlockConnection(s,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new b("Encryption was skipped but no peer id was passed",F.ERR_INVALID_PEER);c="native",s=i}if(a=o,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...o},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw Be.error("Failed to upgrade outbound connection",f),await e.close(f),f}return await this.shouldBlockConnection(s,e,"denyOutboundUpgradedConnection"),Be("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:s,transient:r?.transient})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:o,remotePeer:s,muxerFactory:a,transient:c}=e,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{f!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:y,protocol:g}=await qo(d,m);if(Be("%s: incoming stream opened on %s",n,g),f==null)return;let x=YA(g,this.components.registrar);if(Hg(g,"inbound",f)===x){let C=new b(`Too many inbound protocol streams for protocol "${g}" - limit ${x}`,F.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(C),C}d.source=y.source,d.sink=y.sink,d.protocol=g,await this.components.peerStore.merge(s,{protocols:[g]}),this.components.metrics?.trackProtocolStream(d,f),this._onStream({connection:f,stream:d,protocol:g})}).catch(async m=>{Be.error(m),d.timeline.close==null&&await d.close()})}}),l=async(d,m={})=>{if(u==null)throw new b("Stream is not multiplexed",F.ERR_MUXER_UNAVAILABLE);Be("%s: starting new stream on %s",n,d);let y=await u.newStream();try{if(m.signal==null){Be("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),m.signal=AbortSignal.timeout(3e4);try{(0,Of.setMaxListeners)?.(1/0,m.signal)}catch{}}let{stream:g,protocol:x}=await Fo(y,d,m),w=WA(x,this.components.registrar,m);if(Hg(x,"outbound",f)>=w){let _=new b(`Too many outbound protocol streams for protocol "${x}" - limit ${w}`,F.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(_),_}return await this.components.peerStore.merge(s,{protocols:[x]}),y.source=g.source,y.sink=g.sink,y.protocol=x,this.components.metrics?.trackProtocolStream(y,f),y}catch(g){throw Be.error("could not create new stream",g),y.timeline.close==null&&y.abort(g),g.code!=null?g:new b(String(g),F.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(o.source),o.sink(u.source)]).catch(d=>{Be.error(d)}));let h=i.timeline;i.timeline=new Proxy(h,{set:(...d)=>(f!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(m){Be.error(m)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(m=>{Be.error(m)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let p=()=>{throw new b("connection is not multiplexed",F.ERR_CONNECTION_NOT_MULTIPLEXED)};return f=$g({remoteAddr:i.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:i.timeline,multiplexer:u?.protocol,encryption:r,transient:c,newStream:l??p,getStreams:()=>u!=null?u.streams:[],close:async d=>{await i.close(d),u!=null&&await u.close(d)},abort:d=>{i.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:o,options:s}=this.components.registrar.getHandler(i);if(r.transient&&s.runOnTransientConnection!==!0)throw new b("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");o({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());Be("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await qo(e,r,{writeBytes:!0}),o=this.connectionEncryption.get(i);if(o==null)throw new Error(`no crypto module found for ${i}`);return Be("encrypting inbound connection..."),{...await o.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new b(String(n),F.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());Be("selecting outbound crypto protocol",n);try{let{stream:i,protocol:o}=await Fo(e,n,{writeBytes:!0}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return Be("encrypting outbound connection to %p",r),{...await s.secureOutbound(this.components.peerId,i,r),protocol:o}}catch(i){throw new b(String(i),F.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());Be("outbound selecting muxer %s",n);try{let{stream:i,protocol:o}=await Fo(e,n,{writeBytes:!0});Be("%s selected as muxer protocol",o);let s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw Be.error("error multiplexing outbound stream",i),new b(String(i),F.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());Be("inbound handling muxers %s",n);try{let{stream:i,protocol:o}=await qo(e,n,{writeBytes:!0}),s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw Be.error("error multiplexing inbound stream",i),new b(String(i),F.ERR_MUXER_UNAVAILABLE)}}};var wt=ie("libp2p"),Mf=class extends mo{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let r=new mo,n=r.dispatchEvent.bind(r);r.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new Ku(c.type,{detail:c.detail}));return u||l};try{(0,zg.setMaxListeners)?.(1/0,r)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=ny({peerId:e.peerId,events:r,datastore:e.datastore??new da,connectionGater:dy(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new la(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",c=>{if(c.detail.previous==null){let u={id:c.detail.peer.id,multiaddrs:c.detail.peer.addresses.map(l=>l.multiaddr),protocols:c.detail.peer.protocols};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Xa(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Ha(this.components,e.transportManager)),this.configureComponent("connectionManager",new Oa(this.components,e.connectionManager)),this.configureComponent("registrar",new $a(this.components)),this.configureComponent("addressManager",new pa(this.components,e.addresses));let o=kn.generateOptions();this.keychain=this.configureComponent("keyChain",new kn(this.components,{...o,...e.keychain}));let s=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Va(this.components,{routers:s}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ka(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",f=>{this.#t(f)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){wt.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[Uu]!=null&&(wt("registering service %s for content routing",c),a.push(l[Uu])),l[Vu]!=null&&(wt("registering service %s for peer routing",c),s.push(l[Vu])),l[qu]!=null&&(wt("registering service %s for peer discovery",c),l[qu].addEventListener("peer",f=>{this.#t(f)}))}}configureComponent(e,r){return r==null&&wt.error("component %s was null or undefined",e),this.components[e]=r,r}async start(){if(this.#e)return;this.#e=!0,wt("libp2p is starting"),(await this.keychain.listKeys()).find(r=>r.name==="self")==null&&(wt("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),wt("libp2p has started")}catch(r){throw wt.error("An error occurred starting libp2p",r),await this.stop(),r}}async stop(){this.#e&&(wt("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),wt("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new On;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){return this.components.connectionManager.openConnection(e,r)}async dialProtocol(e,r,n={}){if(r==null)throw new b("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new b("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,r={}){Mn(e)&&(e=de(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,r)}async getPublicKey(e,r={}){if(wt("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=Ue([G("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(i,r);return ho(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,r,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,r,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async r=>{await this.components.registrar.unhandle(r)}))}async register(e,r){return this.components.registrar.register(e,r)}unregister(e){this.components.registrar.unregister(e)}#t(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){wt.error(new Error(F.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs,protocols:r.protocols}).catch(n=>{wt.error(n)})}};async function Gg(t){if(t.peerId==null){let e=t.datastore;if(e!=null)try{let r=new kn({datastore:e},Qr(kn.generateOptions(),t.keychain));t.peerId=await r.exportPeerId("self")}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}}return t.peerId==null&&(t.peerId=await um()),new Mf(Ly(t))}async function QA(t){let e=await Gg(t);return t.start!==!1&&await e.start(),e}return s1(XA);})();
|
|
50
50
|
/*! Bundled license information:
|
|
51
51
|
|
|
@@ -130,22 +130,22 @@ export class AutoDial {
|
|
|
130
130
|
(peer) => {
|
|
131
131
|
// Remove peers without addresses
|
|
132
132
|
if (peer.addresses.length === 0) {
|
|
133
|
-
log.trace('not autodialing %p because they have no addresses');
|
|
133
|
+
log.trace('not autodialing %p because they have no addresses', peer.id);
|
|
134
134
|
return false;
|
|
135
135
|
}
|
|
136
136
|
// remove peers we are already connected to
|
|
137
137
|
if (connections.has(peer.id)) {
|
|
138
|
-
log.trace('not autodialing %p because they are already connected');
|
|
138
|
+
log.trace('not autodialing %p because they are already connected', peer.id);
|
|
139
139
|
return false;
|
|
140
140
|
}
|
|
141
141
|
// remove peers we are already dialling
|
|
142
142
|
if (dialQueue.has(peer.id)) {
|
|
143
|
-
log.trace('not autodialing %p because they are already being dialed');
|
|
143
|
+
log.trace('not autodialing %p because they are already being dialed', peer.id);
|
|
144
144
|
return false;
|
|
145
145
|
}
|
|
146
146
|
// remove peers already in the autodial queue
|
|
147
147
|
if (this.queue.hasJob(peer.id)) {
|
|
148
|
-
log.trace('not autodialing %p because they are already being autodialed');
|
|
148
|
+
log.trace('not autodialing %p because they are already being autodialed', peer.id);
|
|
149
149
|
return false;
|
|
150
150
|
}
|
|
151
151
|
return true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-dial.js","sourceRoot":"","sources":["../../../src/connection-manager/auto-dial.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAA;AAC3D,OAAO,EAAE,QAAQ,IAAI,kBAAkB,EAAE,MAA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CAAA;oBAClB,OAAM;iBACP;gBAED,GAAG,CAAC,0CAA0C,EAAE,IAAI,CAAC,EAAE,CAAC,CAAA;gBACxD,MAAM,IAAI,CAAC,iBAAiB,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE,EAAE;oBACnD,QAAQ,EAAE,IAAI,CAAC,gBAAgB;iBAChC,CAAC,CAAA;YACJ,CAAC,EAAE;gBACD,MAAM,EAAE,IAAI,CAAC,EAAE;aAChB,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;gBACb,GAAG,CAAC,KAAK,CAAC,4CAA4C,EAAE,GAAG,CAAC,CAAA;YAC9D,CAAC,CAAC,CAAA;SACH;QAED,IAAI,CAAC,OAAO,GAAG,KAAK,CAAA;QAEpB,IAAI,IAAI,CAAC,OAAO,EAAE;YAChB,IAAI,CAAC,gBAAgB,GAAG,UAAU,CAAC,GAAG,EAAE;gBACtC,IAAI,CAAC,QAAQ,EAAE;qBACZ,KAAK,CAAC,GAAG,CAAC,EAAE;oBACX,GAAG,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAA;gBAC3C,CAAC,CAAC,CAAA;YACN,CAAC,EAAE,IAAI,CAAC,kBAAkB,CAAC,CAAA;SAC5B;IACH,CAAC;CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export declare const PROTOCOL_VERSION = "ipfs/0.1.0";
|
|
2
|
-
export declare const AGENT_VERSION = "js-libp2p/0.46.11-
|
|
2
|
+
export declare const AGENT_VERSION = "js-libp2p/0.46.11-e3ab1929";
|
|
3
3
|
export declare const MULTICODEC_IDENTIFY = "/ipfs/id/1.0.0";
|
|
4
4
|
export declare const MULTICODEC_IDENTIFY_PUSH = "/ipfs/id/push/1.0.0";
|
|
5
5
|
export declare const IDENTIFY_PROTOCOL_VERSION = "0.1.0";
|
package/dist/src/version.d.ts
CHANGED
package/dist/src/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "libp2p",
|
|
3
|
-
"version": "0.46.11-
|
|
3
|
+
"version": "0.46.11-e3ab1929",
|
|
4
4
|
"description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/libp2p/js-libp2p/tree/master/packages/libp2p#readme",
|
|
@@ -120,18 +120,18 @@
|
|
|
120
120
|
},
|
|
121
121
|
"dependencies": {
|
|
122
122
|
"@achingbrain/nat-port-mapper": "^1.0.9",
|
|
123
|
-
"@libp2p/crypto": "2.0.4-
|
|
124
|
-
"@libp2p/interface": "0.1.2-
|
|
125
|
-
"@libp2p/interface-internal": "0.1.5-
|
|
126
|
-
"@libp2p/keychain": "3.0.4-
|
|
127
|
-
"@libp2p/logger": "3.0.2-
|
|
128
|
-
"@libp2p/multistream-select": "4.0.2-
|
|
129
|
-
"@libp2p/peer-collections": "4.0.4-
|
|
130
|
-
"@libp2p/peer-id": "3.0.2-
|
|
131
|
-
"@libp2p/peer-id-factory": "3.0.4-
|
|
132
|
-
"@libp2p/peer-record": "6.0.5-
|
|
133
|
-
"@libp2p/peer-store": "9.0.5-
|
|
134
|
-
"@libp2p/utils": "4.0.3-
|
|
123
|
+
"@libp2p/crypto": "2.0.4-e3ab1929",
|
|
124
|
+
"@libp2p/interface": "0.1.2-e3ab1929",
|
|
125
|
+
"@libp2p/interface-internal": "0.1.5-e3ab1929",
|
|
126
|
+
"@libp2p/keychain": "3.0.4-e3ab1929",
|
|
127
|
+
"@libp2p/logger": "3.0.2-e3ab1929",
|
|
128
|
+
"@libp2p/multistream-select": "4.0.2-e3ab1929",
|
|
129
|
+
"@libp2p/peer-collections": "4.0.4-e3ab1929",
|
|
130
|
+
"@libp2p/peer-id": "3.0.2-e3ab1929",
|
|
131
|
+
"@libp2p/peer-id-factory": "3.0.4-e3ab1929",
|
|
132
|
+
"@libp2p/peer-record": "6.0.5-e3ab1929",
|
|
133
|
+
"@libp2p/peer-store": "9.0.5-e3ab1929",
|
|
134
|
+
"@libp2p/utils": "4.0.3-e3ab1929",
|
|
135
135
|
"@multiformats/mafmt": "^12.1.2",
|
|
136
136
|
"@multiformats/multiaddr": "^12.1.5",
|
|
137
137
|
"@multiformats/multiaddr-matcher": "^1.0.0",
|
|
@@ -169,17 +169,17 @@
|
|
|
169
169
|
"@chainsafe/libp2p-gossipsub": "^10.0.0",
|
|
170
170
|
"@chainsafe/libp2p-noise": "^13.0.0",
|
|
171
171
|
"@chainsafe/libp2p-yamux": "^5.0.0",
|
|
172
|
-
"@libp2p/bootstrap": "9.0.6-
|
|
172
|
+
"@libp2p/bootstrap": "9.0.6-e3ab1929",
|
|
173
173
|
"@libp2p/daemon-client": "^7.0.0",
|
|
174
174
|
"@libp2p/daemon-server": "^6.0.0",
|
|
175
|
-
"@libp2p/floodsub": "8.0.7-
|
|
176
|
-
"@libp2p/interface-compliance-tests": "4.0.6-
|
|
175
|
+
"@libp2p/floodsub": "8.0.7-e3ab1929",
|
|
176
|
+
"@libp2p/interface-compliance-tests": "4.0.6-e3ab1929",
|
|
177
177
|
"@libp2p/interop": "^9.0.0",
|
|
178
|
-
"@libp2p/kad-dht": "10.0.7-
|
|
179
|
-
"@libp2p/mdns": "9.0.8-
|
|
180
|
-
"@libp2p/mplex": "9.0.6-
|
|
181
|
-
"@libp2p/tcp": "8.0.7-
|
|
182
|
-
"@libp2p/websockets": "7.0.7-
|
|
178
|
+
"@libp2p/kad-dht": "10.0.7-e3ab1929",
|
|
179
|
+
"@libp2p/mdns": "9.0.8-e3ab1929",
|
|
180
|
+
"@libp2p/mplex": "9.0.6-e3ab1929",
|
|
181
|
+
"@libp2p/tcp": "8.0.7-e3ab1929",
|
|
182
|
+
"@libp2p/websockets": "7.0.7-e3ab1929",
|
|
183
183
|
"@types/xsalsa20": "^1.1.0",
|
|
184
184
|
"aegir": "^40.0.8",
|
|
185
185
|
"execa": "^8.0.1",
|
|
@@ -172,25 +172,25 @@ export class AutoDial implements Startable {
|
|
|
172
172
|
(peer) => {
|
|
173
173
|
// Remove peers without addresses
|
|
174
174
|
if (peer.addresses.length === 0) {
|
|
175
|
-
log.trace('not autodialing %p because they have no addresses')
|
|
175
|
+
log.trace('not autodialing %p because they have no addresses', peer.id)
|
|
176
176
|
return false
|
|
177
177
|
}
|
|
178
178
|
|
|
179
179
|
// remove peers we are already connected to
|
|
180
180
|
if (connections.has(peer.id)) {
|
|
181
|
-
log.trace('not autodialing %p because they are already connected')
|
|
181
|
+
log.trace('not autodialing %p because they are already connected', peer.id)
|
|
182
182
|
return false
|
|
183
183
|
}
|
|
184
184
|
|
|
185
185
|
// remove peers we are already dialling
|
|
186
186
|
if (dialQueue.has(peer.id)) {
|
|
187
|
-
log.trace('not autodialing %p because they are already being dialed')
|
|
187
|
+
log.trace('not autodialing %p because they are already being dialed', peer.id)
|
|
188
188
|
return false
|
|
189
189
|
}
|
|
190
190
|
|
|
191
191
|
// remove peers already in the autodial queue
|
|
192
192
|
if (this.queue.hasJob(peer.id)) {
|
|
193
|
-
log.trace('not autodialing %p because they are already being autodialed')
|
|
193
|
+
log.trace('not autodialing %p because they are already being autodialed', peer.id)
|
|
194
194
|
return false
|
|
195
195
|
}
|
|
196
196
|
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const version = '0.46.11-
|
|
1
|
+
export const version = '0.46.11-e3ab1929'
|
|
2
2
|
export const name = 'libp2p'
|