helia 4.2.2-21ef20c → 4.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -49,7 +49,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
49
49
  a=ice-ufrag:`+e+`
50
50
  `).replace(/\na=ice-pwd:[^\n]*\n/,`
51
51
  a=ice-pwd:`+e+`
52
- `),r}var LE=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),PE=r=>[...Array(r)].map(()=>LE.at(Math.floor(Math.random()*LE.length))).join("");var iN=1e4,Ace=ee("webrtc-direct").code,NE=ee("certhash").code,rf=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw Wy("WebRTCTransport.createListener")}listenFilter(e){return e.filter(Tg.exactMatch)}dialFilter(e){return this.listenFilter(e)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[an]=!0;async _connect(e,t){let n=new AbortController,o=n.signal,s=e.getPeerId();if(s===null)throw Bd("we need to have the remote's PeerId");let i=ge(s),a=F3(tf(e)),c=await Zi.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:V3(a.name)}),l=new Zi({certificates:[c]});try{let d=new Promise((R,T)=>{let P=l.createDataChannel("",{negotiated:!0,id:0}),N=setTimeout(()=>{let B=`Data channel was never opened: state: ${P.readyState}`;this.log.error(B),this.metrics?.dialerEvents.increment({open_error:!0}),T(o3("data",B))},iN);P.onopen=B=>{clearTimeout(N),R(P)},P.onerror=B=>{clearTimeout(N);let X=`Error opening a data channel for handshaking: ${B.target?.toString()??"not specified"}`;this.log.error(X),this.metrics?.dialerEvents.increment({unknown_error:!0}),T(o3("data",X))}}),u="libp2p+webrtc+v1/"+PE(32),h=await l.createOffer(),f=CE(h,u);await l.setLocalDescription(f);let p=kE(e,u);await l.setRemoteDescription(p);let m=await d,y=this.components.peerId,w=this.generateNoisePrologue(l,a.code,e),b=Pi({prologueBytes:w})(this.components),E=ji({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),x={...E,sink:E.sink.bind(E),source:async function*(){for await(let R of E.source)for(let T of R)yield T}()},v=new ks(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),I=Sc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(I,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(R=>{this.log.error("error closing connection",R)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let S=new Cs(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(y,x,i),await t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:S})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Rc("no local certificate");let o=TE(e,{log:this.log});if(o==null)throw Rc("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=M(s,"hex"),a=OE.encode(i,t),c=U3.decode(tf(n)),l=M("libp2p-webrtc-noise:");return ve([l,a,c])}};function BE(r){return e=>new rf(e,r)}function ME(r){return e=>new Hd(e,r)}var UE=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",s)}function o(){n(),e()}function s(i){n(),t(i.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",s)})};var FE=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await UE(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,s)=>{r.addEventListener("close",i=>{if(i.wasClean||i.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:i});s(a)}}),setTimeout(()=>{r.close()})})});var HE=Qe(KE(),1);function $E(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var qE=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,i)=>{if(n){s();return}if(o!=null){i(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(s)},l=d=>{a(()=>{i(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new HE.EventIterator(({push:i,stop:a,fail:c})=>{let l=u=>{let h=null;typeof u.data=="string"&&(h=M(u.data)),$E(u.data)&&(h=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(h=u.data),h!=null&&i(h)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let i of s)yield $E(i)?new Uint8Array(i):i}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",s=>{n||(o=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var GE=(r,e)=>{e=e??{};let t=qE(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let i=new URL(r.url);n=i.hostname,o=parseInt(i.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:FE(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(i=>{r.addEventListener("close",()=>{i()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var WE=WebSocket;var cN={"http:":"ws:","https:":"wss:"},zE="ws:",YE=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??zE}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??zE,o=e.host,s=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${s}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(cN))t.protocol===n&&(t.protocol=o);return t};function XE(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=YE(r,t),o=new WE(n.toString(),e.websocket);return GE(o,e)}function QE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Mi.matches(t)||_s.matches(t)})}function jE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return _s.matches(t)})}function ZE(){throw new Error("WebSocket Servers can not be created in the browser!")}function JE(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o={log:n,async sink(s){try{await r.sink(async function*(){for await(let i of s)i instanceof Uint8Array?yield i:yield i.subarray()}())}catch(i){i.type!=="aborted"&&n.error(i)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(s={}){let i=Date.now();if(s.signal==null){let c=AbortSignal.timeout(500);s={...s,signal:c}}let a=()=>{let{host:c,port:l}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",c,l,Date.now()-i),this.abort(new g("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};s.signal?.addEventListener("abort",a);try{await r.close()}catch(c){n.error("error closing WebSocket gracefully",c),this.abort(c)}finally{s.signal?.removeEventListener("abort",a),o.timeline.close=Date.now()}},abort(s){let{host:i,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",i,a,s),r.destroy(),o.timeline.close=Date.now()}};return r.socket.addEventListener("close",()=>{o.timeline.close==null&&(o.timeline.close=Date.now())},{once:!0}),o}var H3=class{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[an]=!0;async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=JE(n,e,{logger:this.logger});this.log("new outbound connection %s",o.remoteAddr);let s=await t.upgrader.upgradeOutbound(o);return this.log("outbound connection %s upgraded",o.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Kt;let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=J(),s=XE(a1(e),this.init);if(s.socket.addEventListener("error",()=>{let c=new g(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",c),o.reject(c)}),t.signal==null)return await Promise.race([s.connected(),o.promise]),this.log("connected %s",e),s;let i,a=new Promise((c,l)=>{if(i=()=>{l(new Kt),s.close().catch(d=>{this.log.error("error closing raw socket",d)})},t?.signal?.aborted===!0){i();return}t?.signal?.addEventListener("abort",i)});try{await Promise.race([a,o.promise,s.connected()])}finally{i!=null&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return ZE({logger:this.logger},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):ed||td?jE(e):QE(e)}dialFilter(e){return this.listenFilter(e)}};function eb(r={}){return e=>new H3(e,r)}function q3(r){throw new Error("Not implemented")}var G3=class extends yn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new ce(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ue(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ue(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ue(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ue(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function W3(r,e,t,n,o,s){let i=s.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new G3({bidiStream:r,id:e,direction:t,log:i,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function sf(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function tb(r,e,t,n){let o=0,s=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let a=[];return Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)s(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await W3(d,String(o++),"inbound",a,i?.onStreamEnd,t);a.push(u),i?.onIncomingStream?.(u)}}}),{protocol:"webtransport",streams:a,newStream:async l=>{s("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await W3(d,String(o++),i?.direction??"outbound",a,i?.onStreamEnd,t);return a.push(u),u},close:async()=>{s("closing webtransport muxer gracefully"),r.close()},abort:l=>{s("closing webtransport muxer with err:",l),r.close()},...sf()}}}}function rb(r,e){return e.filter(n=>!!r.find(o=>Z(n,o))).length===e.length}var fN=Object.values(br).map(r=>r.decoder).reduce((r,e)=>r.or(e));function hN(r){return Er.decode(fN.decode(r))}function z3(r){if(!i1.matches(r))throw new g("Invalid multiaddr, was not a WebTransport address","ERR_INVALID_MULTIADDR");let e=r.stringTuples(),t=e.filter(([i,a])=>i===ee("certhash").code).map(([i,a])=>hN(a??"")),n=e.filter(([i,a])=>i===ee("p2p").code).map(([i,a])=>ge(a??""))[0],o=r.toOptions(),s=o.host;return o.family===6&&s?.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${o.port}`,certhashes:t,remotePeer:n}}var nb=WebTransport;var Y3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[an]=!0;async dial(e,t){if(t?.signal?.aborted===!0)throw new Kt;this.log("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new g("Need a local peerid","ERR_INVALID_PARAMETERS");t=t??{};let{url:o,certhashes:s,remotePeer:i}=z3(e),a,c,l=()=>{},d=!1,u=!1,h=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let f=new nb(`${o}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(p=>({algorithm:"sha-256",value:p.digest}))});if(l=p=>{if(!d)try{this.metrics?.dialerEvents.increment({[p]:!0}),f.close()}catch(m){this.log.error("error closing wt session",m)}finally{c!=null&&(c.timeline.close=Date.now()),d=!0}},a=()=>{l(u?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",a,{once:!0}),this.log("wait for session to be ready"),await Promise.race([f.closed,f.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),f.closed.catch(p=>{this.log.error("error on remote wt session close",p)}).finally(()=>{l("remote_close")}),h=await Ue(this.authenticateWebTransport(f,n,i,s),t.signal),!h)throw new g("Failed to authenticate webtransport","ERR_AUTHENTICATION_FAILED");return this.metrics?.dialerEvents.increment({open:!0}),c={close:async()=>{this.log("closing webtransport"),l("close")},abort:p=>{this.log("aborting webtransport due to passed err",p),l("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...sf()},await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:tb(f,f.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0})}catch(f){throw this.log.error("caught wt session err",f),l(h?"upgrade_error":u?"noise_error":"ready_error"),f}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport(e,t,n,o=[],s){if(s?.aborted===!0)throw new Kt;let i=await e.createBidirectionalStream(),a=i.writable.getWriter(),c=i.readable.getReader(),l={source:async function*(){for(;;){let h=await c.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async h=>{for await(let f of h){await Ue(a.ready,s);let p=f instanceof Uint8Array?f:f.subarray();a.write(p).catch(m=>{this.log.error("could not write chunk during authentication of WebTransport stream",m)})}}},d=Pi()(this.components),{remoteExtensions:u}=await d.secureOutbound(t,l,n);if(a.close().catch(h=>{this.log.error(`Failed to close authentication stream writer: ${h.message}`)}),c.cancel().catch(h=>{this.log.error(`Failed to close authentication stream reader: ${h.message}`)}),!rb(u?.webtransportCerthashes??[],o.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return q3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return e.filter(t=>{if(!i1.exactMatch(t))return!1;let{url:n,certhashes:o}=z3(t);return n!=null&&o.length>0})}};function ob(r={}){return e=>new Y3(e,r)}var X3=Qe(p1(),1);function sb(r,e){let t=e.map((n,o)=>({record:mn(n),index:o}));return t.sort((n,o)=>{let s=n.record.sequence,i=o.record.sequence;if(s>i)return-1;if(s<i)return 1;if(n.record.validityType===Xt.ValidityType.EOL&&o.record.validityType===Xt.ValidityType.EOL){let a=X3.default.fromString(n.record.validity).toDate(),c=X3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var af="1.6.0",cf="libp2p";var ab="4.2.2-21ef20c",cb="helia";var lb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function lf(r={}){let e=`${cb}/${ab} ${cf}/${af} UserAgent=${globalThis.navigator.userAgent}`;return{peerId:r.peerId,dns:r.dns,addresses:{listen:["/webrtc"]},transports:[kp({discoverRelays:1}),ME(),BE(),ob(),eb()],connectionEncryption:[Pi()],streamMuxers:[j7(),Ky()],peerDiscovery:[h9(lb)],services:{autoNAT:t9(),dcutr:D9(),delegatedRouting:()=>e7("https://delegated-ipfs.dev"),dht:py({clientMode:!0,validators:{ipns:y1},selectors:{ipns:sb}}),identify:$9({agentVersion:e}),identifyPush:H9({agentVersion:e}),keychain:Nd(r.keychain),ping:Gy()}}}var It={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var ca;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),df.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=df.codec().decode(i,i.uint32());break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),uf.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(uf.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(l.key,l.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(ca||(ca={}));var uf;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(uf||(uf={}));var df;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(df||(df={}));function la(r,e){let t=ca.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=u8({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Q3="/peers/";function ua(r){if(!Ms(r)||r.type==null)throw new g("Invalid PeerId",It.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Pe(`${Q3}${e}`)}async function ub(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=j(o.multiaddr)),!ko(o.multiaddr))throw new g("Multiaddr was invalid",It.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function hf(r,e,t,n){if(e==null)throw new g("Invalid PeerData",It.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!Z(e.publicKey,r.publicKey))throw new g("publicKey bytes do not match peer id publicKey bytes",It.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new g("peer id did not match existing peer id",It.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ff(u,{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ff(u,{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,f]of u)f==null?a.delete(h):a.set(h,f);a=ff([...a.entries()],{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[f,p]of u)p==null?h.delete(f):h.set(f,p);c=ff([...h.entries()],{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d={addresses:await ub(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((u,h)=>u.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function ff(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function db(r,e){if(typeof r!="string")throw new g("Metadata key must be a string",It.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new g("Metadata value must be a Uint8Array",It.ERR_INVALID_PARAMETERS)}function fb(r,e){if(typeof r!="string")throw new g("Tag name must be a string",It.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new g("Tag value must be an integer",It.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new g("Tag value must be between 0-100",It.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new g("Tag ttl must be an integer",It.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new g("Tag ttl must be between greater than 0",It.ERR_INVALID_PARAMETERS)}}function hb(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function pf(r,e,t){let n=r.toString().split("/")[2],o=ut.decode(n),s=Je(o),i=t.get(s);if(i!=null)return i;let a=la(s,e);return t.set(s,a),a}function pN(r,e){return r==null?{}:{prefix:Q3,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(pf(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(pf(n.key,n.value,e),pf(o.key,o.value,e)))}}var mf=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Ya({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ua(e))}async delete(e){if(this.peerId.equals(e))throw new g("Cannot delete self peer",It.ERR_INVALID_PARAMETERS);await this.datastore.delete(ua(e))}async load(e){let t=await this.datastore.get(ua(e));return la(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new it;for await(let{key:n,value:o}of this.datastore.query(pN(e??{},t))){let s=pf(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(ua(e)),n=la(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=ca.encode(t);return n!=null&&Z(s,n)?{peer:la(e,s),previous:o,updated:!1}:(await this.datastore.put(ua(e),s),{peer:la(e,s),previous:o,updated:!0})}};var gf=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new mf(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await sc(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mr.openAndCertify(e,Vt.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Vt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mr.createFromProtobuf(s.peerRecordEnvelope),a=Vt.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function pb(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var mN=r=>r;function j3(r,e){let t=r.getPeerId();return t!=null&&ge(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var yf=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??mN,this._updatePeerStoreAddresses=pb(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>j(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>j(e))}addObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>j(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Z3=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=So())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Fc(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},gN=["metrics","connectionProtector","dns"],yN=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mb(r={}){let e=new Z3(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!yN.includes(o)){let i=e.components[o];if(i==null&&!gN.includes(o))throw new g(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function gb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Yt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function J3(r){try{let{address:e}=r.nodeAddress();return!!Yt(e)}catch{return!0}}function wN(r,e){let t=J3(r.multiaddr),n=J3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function EN(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function bN(r,e){let t=bs.exactMatch(r.multiaddr),n=bs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function da(r,e){let t=wN(r,e);if(t!==0)return t;let n=bN(r,e);return n!==0?n:EN(r,e)}var xN=32,{code:vN}=ee("dnsaddr"),Ps=async function(e,t={}){let n=t.maxRecursiveDepth??xN;if(n===0)throw new g("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([l])=>l===vN)??[],i=await(t?.dns??wu()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[ar.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let d=l.data.replace(/["']/g,"").trim().split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=j(d);if(d.startsWith("/dnsaddr")){let h=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(f=>f.toString()))}else c.push(u.toString())}return c};var Jn;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Jn||(Jn={}));var z;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(z||(z={}));var RN={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ps},addressSorter:da},transportManager:{faultTolerance:to.FATAL_ALL}};async function yb(r){let e=Xi(RN,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new g(Jn.ERR_PROTECTOR_REQUIRED,z.ERR_PROTECTOR_REQUIRED);if(!(await dt(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new g("Private key doesn't match peer id",z.ERR_INVALID_KEY);return e}function wf(r){if(Ms(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ge(t),r.forEach(n=>{if(!ko(n))throw new g("Invalid Multiaddr",z.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}else{let s=ge(o);if(e==null||!e.equals(s))throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Ef="last-dial-failure";var bf=5,xf=100,vf=50,Rf=1e3*60*7;var Os={minConnections:bf,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Sf=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Os.minConnections,this.autoDialPriority=t.autoDialPriority??Os.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Os.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Os.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Os.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Os.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new wr({concurrency:t.autoDialConcurrency??Os.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ht(this.connectionManager.getDialQueue().map(l=>l.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[l=>l.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",l.id),!1):e.has(l.id)?(this.log.trace("not autodialing %p because they are already connected",l.id),!1):n.has(l.id)?(this.log.trace("not autodialing %p because they are already being dialed",l.id),!1):this.queue.has(l.id)?(this.log.trace("not autodialing %p because they are already being autodialed",l.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new it;for(let l of s)i.has(l.id)||i.set(l.id,[...l.tags.values()].reduce((d,u)=>d+u.value,0));let c=s.sort((l,d)=>{let u=i.get(l.id)??0,h=i.get(d.id)??0;return u>h?-1:u<h?1:0}).filter(l=>{let d=l.metadata.get(Ef);if(d==null)return!0;let u=parseInt(O(d));return isNaN(u)?!0:Date.now()-u>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let l of c)this.queue.add(async()=>{let d=this.connectionManager.getConnectionsMap().size;if(d>=this.minConnections){this.log("got enough connections now %d/%d",d,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",l.id),await this.connectionManager.openConnection(l.id,{priority:this.autoDialPriority})},{peerId:l.id}).catch(d=>{this.log.error("could not connect to peerStore stored peer",d)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var _N=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function wb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??_N;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Eb={maxConnections:xf,allow:[]},_f=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Eb.maxConnections,this.allow=t.allow??Eb.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new it;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await wb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Af=class extends tr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};async function bb(r,e){let t=!1;for(let o of Di.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Lc={addressSorter:da,maxParallelDials:vf,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ps}},If=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Lc.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Lc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Lc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Lc.dialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Di.set(n,o);this.queue=new Af({concurrency:t.maxParallelDials??Lc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=wf(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new g("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let h of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new g("Peer had more than maxPeerAddrsToDial",z.ERR_TOO_MANY_ADDRESSES);d++;try{let f=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),f}catch(f){if(this.log.error("dial failed to %a",h.multiaddr,f),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Ef]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new g(f.message,vn);u.push(f)}}throw u.length===1?u[0]:new Uc(u,"All multiaddr dials failed",z.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??a4,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=Ae([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return H(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:j(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new g("Tried to dial self",z.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new g("The dial request is blocked by gater.allowDialPeer",z.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(u){if(u.code!==z.ERR_NOT_FOUND)throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...u.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(u){u.code!==z.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let s=(await Promise.all(o.map(async u=>{let h=await bb(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(u.multiaddr)?u:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(u),isCertified:h.isCertified}:h)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let h=u.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let u of i){let h=u.multiaddr.toString(),f=a.get(h);if(f!=null){f.isCertified=f.isCertified||u.isCertified||!1;continue}a.set(h,u)}let c=[...a.values()];if(c.length===0)throw new g("The dial request has no valid addresses",z.ERR_NO_VALID_ADDRESSES);let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=l.sort(this.addressSorter);if(d.length===0)throw new g("The connection gater denied all addresses in the dial request",z.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!bs.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var a4=50,eo={minConnections:bf,maxConnections:xf,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Df=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??eo.maxConnections;let n=t.minConnections??eo.minConnections;if(this.maxConnections<n)throw new g("Connection Manager maxConnections must be greater than minConnections",z.ERR_INVALID_PARAMETERS);this.connections=new it,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>j(o)),this.deny=(t.deny??[]).map(o=>j(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??eo.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Qi({points:t.inboundConnectionThreshold??eo.inboundConnectionThreshold,duration:1}),this.autoDial=new Sf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??eo.autoDialConcurrency,autoDialPriority:t.autoDialPriority??eo.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??eo.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eo.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??eo.autoDialMaxQueueLength}),this.connectionPruner=new _f({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new If(e,{addressSorter:t.addressSorter??da,maxParallelDials:t.maxParallelDials??vf,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ps},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(R4)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=wf(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??a4}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Tf=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of Mt(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var kf=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new g("Should not try to find self",z.ERR_FIND_SELF);let n=this,o=Mt(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new g(Jn.NOT_FOUND,z.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of en(async function*(){let i=Mt(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var Cf=class extends ye{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ae([this.shutdownController.signal,e?.signal]);H(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=J(),yield(await er(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,H(1/0,this.walkController.signal);let e=Ae([this.walkController.signal,this.shutdownController.signal]);H(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{for await(let o of this.peerRouting.getClosestPeers(pt(32),{signal:e}))e.throwIfAborted(),this.log("found peer %p",o.id),n++,this.safeDispatchEvent("walk:peer",{detail:o}),this.walkers===1&&this.needNext!=null&&await Ue(this.needNext.promise,e)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var c4=32,l4=64,Nf=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new g(`No handler registered for protocol ${e}`,z.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new g(`Handler already registered for protocol ${e}`,z.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=Xi.bind({ignoreUndefined:!0})({maxInboundStreams:c4,maxOutboundStreams:l4},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new g("invalid topology",z.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==z.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Lf=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Wu({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??to.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new g("Transport must have a valid tag",z.ERR_INVALID_KEY);if(this.transports.has(t))throw new g(`There is already a transport with the tag ${t}`,z.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new g(`No transport available for address ${String(e)}`,z.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=z.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let l of s){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let h=u.findIndex(f=>f===d);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),i.push(d.listen(l))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==to.NO_FATAL)throw new g(`Transport (${n}) could not listen on any available address`,z.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===to.FATAL_ALL)throw new g(n,z.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Dt="/multistream/1.0.0";var DN=M(`
52
+ `),r}var LE=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),PE=r=>[...Array(r)].map(()=>LE.at(Math.floor(Math.random()*LE.length))).join("");var iN=1e4,Ace=ee("webrtc-direct").code,NE=ee("certhash").code,rf=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw Wy("WebRTCTransport.createListener")}listenFilter(e){return e.filter(Tg.exactMatch)}dialFilter(e){return this.listenFilter(e)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[an]=!0;async _connect(e,t){let n=new AbortController,o=n.signal,s=e.getPeerId();if(s===null)throw Bd("we need to have the remote's PeerId");let i=ge(s),a=F3(tf(e)),c=await Zi.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:V3(a.name)}),l=new Zi({certificates:[c]});try{let d=new Promise((R,T)=>{let P=l.createDataChannel("",{negotiated:!0,id:0}),N=setTimeout(()=>{let B=`Data channel was never opened: state: ${P.readyState}`;this.log.error(B),this.metrics?.dialerEvents.increment({open_error:!0}),T(o3("data",B))},iN);P.onopen=B=>{clearTimeout(N),R(P)},P.onerror=B=>{clearTimeout(N);let X=`Error opening a data channel for handshaking: ${B.target?.toString()??"not specified"}`;this.log.error(X),this.metrics?.dialerEvents.increment({unknown_error:!0}),T(o3("data",X))}}),u="libp2p+webrtc+v1/"+PE(32),h=await l.createOffer(),f=CE(h,u);await l.setLocalDescription(f);let p=kE(e,u);await l.setRemoteDescription(p);let m=await d,y=this.components.peerId,w=this.generateNoisePrologue(l,a.code,e),b=Pi({prologueBytes:w})(this.components),E=ji({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),x={...E,sink:E.sink.bind(E),source:async function*(){for await(let R of E.source)for(let T of R)yield T}()},v=new ks(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),I=Sc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(I,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(R=>{this.log.error("error closing connection",R)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let S=new Cs(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(y,x,i),await t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:S})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Rc("no local certificate");let o=TE(e,{log:this.log});if(o==null)throw Rc("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=M(s,"hex"),a=OE.encode(i,t),c=U3.decode(tf(n)),l=M("libp2p-webrtc-noise:");return ve([l,a,c])}};function BE(r){return e=>new rf(e,r)}function ME(r){return e=>new Hd(e,r)}var UE=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",s)}function o(){n(),e()}function s(i){n(),t(i.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",s)})};var FE=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await UE(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,s)=>{r.addEventListener("close",i=>{if(i.wasClean||i.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:i});s(a)}}),setTimeout(()=>{r.close()})})});var HE=Qe(KE(),1);function $E(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var qE=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,i)=>{if(n){s();return}if(o!=null){i(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(s)},l=d=>{a(()=>{i(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new HE.EventIterator(({push:i,stop:a,fail:c})=>{let l=u=>{let h=null;typeof u.data=="string"&&(h=M(u.data)),$E(u.data)&&(h=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(h=u.data),h!=null&&i(h)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let i of s)yield $E(i)?new Uint8Array(i):i}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",s=>{n||(o=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var GE=(r,e)=>{e=e??{};let t=qE(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let i=new URL(r.url);n=i.hostname,o=parseInt(i.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:FE(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(i=>{r.addEventListener("close",()=>{i()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var WE=WebSocket;var cN={"http:":"ws:","https:":"wss:"},zE="ws:",YE=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??zE}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??zE,o=e.host,s=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${s}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(cN))t.protocol===n&&(t.protocol=o);return t};function XE(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=YE(r,t),o=new WE(n.toString(),e.websocket);return GE(o,e)}function QE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Mi.matches(t)||_s.matches(t)})}function jE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return _s.matches(t)})}function ZE(){throw new Error("WebSocket Servers can not be created in the browser!")}function JE(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o={log:n,async sink(s){try{await r.sink(async function*(){for await(let i of s)i instanceof Uint8Array?yield i:yield i.subarray()}())}catch(i){i.type!=="aborted"&&n.error(i)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(s={}){let i=Date.now();if(s.signal==null){let c=AbortSignal.timeout(500);s={...s,signal:c}}let a=()=>{let{host:c,port:l}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",c,l,Date.now()-i),this.abort(new g("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};s.signal?.addEventListener("abort",a);try{await r.close()}catch(c){n.error("error closing WebSocket gracefully",c),this.abort(c)}finally{s.signal?.removeEventListener("abort",a),o.timeline.close=Date.now()}},abort(s){let{host:i,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",i,a,s),r.destroy(),o.timeline.close=Date.now()}};return r.socket.addEventListener("close",()=>{o.timeline.close==null&&(o.timeline.close=Date.now())},{once:!0}),o}var H3=class{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[an]=!0;async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=JE(n,e,{logger:this.logger});this.log("new outbound connection %s",o.remoteAddr);let s=await t.upgrader.upgradeOutbound(o);return this.log("outbound connection %s upgraded",o.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Kt;let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=J(),s=XE(a1(e),this.init);if(s.socket.addEventListener("error",()=>{let c=new g(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",c),o.reject(c)}),t.signal==null)return await Promise.race([s.connected(),o.promise]),this.log("connected %s",e),s;let i,a=new Promise((c,l)=>{if(i=()=>{l(new Kt),s.close().catch(d=>{this.log.error("error closing raw socket",d)})},t?.signal?.aborted===!0){i();return}t?.signal?.addEventListener("abort",i)});try{await Promise.race([a,o.promise,s.connected()])}finally{i!=null&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return ZE({logger:this.logger},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):ed||td?jE(e):QE(e)}dialFilter(e){return this.listenFilter(e)}};function eb(r={}){return e=>new H3(e,r)}function q3(r){throw new Error("Not implemented")}var G3=class extends yn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new ce(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ue(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ue(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ue(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ue(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function W3(r,e,t,n,o,s){let i=s.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new G3({bidiStream:r,id:e,direction:t,log:i,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function sf(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function tb(r,e,t,n){let o=0,s=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let a=[];return Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)s(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await W3(d,String(o++),"inbound",a,i?.onStreamEnd,t);a.push(u),i?.onIncomingStream?.(u)}}}),{protocol:"webtransport",streams:a,newStream:async l=>{s("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await W3(d,String(o++),i?.direction??"outbound",a,i?.onStreamEnd,t);return a.push(u),u},close:async()=>{s("closing webtransport muxer gracefully"),r.close()},abort:l=>{s("closing webtransport muxer with err:",l),r.close()},...sf()}}}}function rb(r,e){return e.filter(n=>!!r.find(o=>Z(n,o))).length===e.length}var fN=Object.values(br).map(r=>r.decoder).reduce((r,e)=>r.or(e));function hN(r){return Er.decode(fN.decode(r))}function z3(r){if(!i1.matches(r))throw new g("Invalid multiaddr, was not a WebTransport address","ERR_INVALID_MULTIADDR");let e=r.stringTuples(),t=e.filter(([i,a])=>i===ee("certhash").code).map(([i,a])=>hN(a??"")),n=e.filter(([i,a])=>i===ee("p2p").code).map(([i,a])=>ge(a??""))[0],o=r.toOptions(),s=o.host;return o.family===6&&s?.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${o.port}`,certhashes:t,remotePeer:n}}var nb=WebTransport;var Y3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[an]=!0;async dial(e,t){if(t?.signal?.aborted===!0)throw new Kt;this.log("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new g("Need a local peerid","ERR_INVALID_PARAMETERS");t=t??{};let{url:o,certhashes:s,remotePeer:i}=z3(e),a,c,l=()=>{},d=!1,u=!1,h=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let f=new nb(`${o}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(p=>({algorithm:"sha-256",value:p.digest}))});if(l=p=>{if(!d)try{this.metrics?.dialerEvents.increment({[p]:!0}),f.close()}catch(m){this.log.error("error closing wt session",m)}finally{c!=null&&(c.timeline.close=Date.now()),d=!0}},a=()=>{l(u?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",a,{once:!0}),this.log("wait for session to be ready"),await Promise.race([f.closed,f.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),f.closed.catch(p=>{this.log.error("error on remote wt session close",p)}).finally(()=>{l("remote_close")}),h=await Ue(this.authenticateWebTransport(f,n,i,s),t.signal),!h)throw new g("Failed to authenticate webtransport","ERR_AUTHENTICATION_FAILED");return this.metrics?.dialerEvents.increment({open:!0}),c={close:async()=>{this.log("closing webtransport"),l("close")},abort:p=>{this.log("aborting webtransport due to passed err",p),l("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...sf()},await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:tb(f,f.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0})}catch(f){throw this.log.error("caught wt session err",f),l(h?"upgrade_error":u?"noise_error":"ready_error"),f}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport(e,t,n,o=[],s){if(s?.aborted===!0)throw new Kt;let i=await e.createBidirectionalStream(),a=i.writable.getWriter(),c=i.readable.getReader(),l={source:async function*(){for(;;){let h=await c.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async h=>{for await(let f of h){await Ue(a.ready,s);let p=f instanceof Uint8Array?f:f.subarray();a.write(p).catch(m=>{this.log.error("could not write chunk during authentication of WebTransport stream",m)})}}},d=Pi()(this.components),{remoteExtensions:u}=await d.secureOutbound(t,l,n);if(a.close().catch(h=>{this.log.error(`Failed to close authentication stream writer: ${h.message}`)}),c.cancel().catch(h=>{this.log.error(`Failed to close authentication stream reader: ${h.message}`)}),!rb(u?.webtransportCerthashes??[],o.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return q3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return e.filter(t=>{if(!i1.exactMatch(t))return!1;let{url:n,certhashes:o}=z3(t);return n!=null&&o.length>0})}};function ob(r={}){return e=>new Y3(e,r)}var X3=Qe(p1(),1);function sb(r,e){let t=e.map((n,o)=>({record:mn(n),index:o}));return t.sort((n,o)=>{let s=n.record.sequence,i=o.record.sequence;if(s>i)return-1;if(s<i)return 1;if(n.record.validityType===Xt.ValidityType.EOL&&o.record.validityType===Xt.ValidityType.EOL){let a=X3.default.fromString(n.record.validity).toDate(),c=X3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var af="1.6.0",cf="libp2p";var ab="4.2.3",cb="helia";var lb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function lf(r={}){let e=`${cb}/${ab} ${cf}/${af} UserAgent=${globalThis.navigator.userAgent}`;return{peerId:r.peerId,dns:r.dns,addresses:{listen:["/webrtc"]},transports:[kp({discoverRelays:1}),ME(),BE(),ob(),eb()],connectionEncryption:[Pi()],streamMuxers:[j7(),Ky()],peerDiscovery:[h9(lb)],services:{autoNAT:t9(),dcutr:D9(),delegatedRouting:()=>e7("https://delegated-ipfs.dev"),dht:py({clientMode:!0,validators:{ipns:y1},selectors:{ipns:sb}}),identify:$9({agentVersion:e}),identifyPush:H9({agentVersion:e}),keychain:Nd(r.keychain),ping:Gy()}}}var It={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var ca;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),df.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=df.codec().decode(i,i.uint32());break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),uf.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(uf.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(l.key,l.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(ca||(ca={}));var uf;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(uf||(uf={}));var df;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(df||(df={}));function la(r,e){let t=ca.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=u8({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Q3="/peers/";function ua(r){if(!Ms(r)||r.type==null)throw new g("Invalid PeerId",It.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Pe(`${Q3}${e}`)}async function ub(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=j(o.multiaddr)),!ko(o.multiaddr))throw new g("Multiaddr was invalid",It.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function hf(r,e,t,n){if(e==null)throw new g("Invalid PeerData",It.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!Z(e.publicKey,r.publicKey))throw new g("publicKey bytes do not match peer id publicKey bytes",It.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new g("peer id did not match existing peer id",It.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ff(u,{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ff(u,{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,f]of u)f==null?a.delete(h):a.set(h,f);a=ff([...a.entries()],{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[f,p]of u)p==null?h.delete(f):h.set(f,p);c=ff([...h.entries()],{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d={addresses:await ub(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((u,h)=>u.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function ff(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function db(r,e){if(typeof r!="string")throw new g("Metadata key must be a string",It.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new g("Metadata value must be a Uint8Array",It.ERR_INVALID_PARAMETERS)}function fb(r,e){if(typeof r!="string")throw new g("Tag name must be a string",It.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new g("Tag value must be an integer",It.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new g("Tag value must be between 0-100",It.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new g("Tag ttl must be an integer",It.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new g("Tag ttl must be between greater than 0",It.ERR_INVALID_PARAMETERS)}}function hb(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function pf(r,e,t){let n=r.toString().split("/")[2],o=ut.decode(n),s=Je(o),i=t.get(s);if(i!=null)return i;let a=la(s,e);return t.set(s,a),a}function pN(r,e){return r==null?{}:{prefix:Q3,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(pf(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(pf(n.key,n.value,e),pf(o.key,o.value,e)))}}var mf=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Ya({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ua(e))}async delete(e){if(this.peerId.equals(e))throw new g("Cannot delete self peer",It.ERR_INVALID_PARAMETERS);await this.datastore.delete(ua(e))}async load(e){let t=await this.datastore.get(ua(e));return la(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new it;for await(let{key:n,value:o}of this.datastore.query(pN(e??{},t))){let s=pf(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(ua(e)),n=la(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=ca.encode(t);return n!=null&&Z(s,n)?{peer:la(e,s),previous:o,updated:!1}:(await this.datastore.put(ua(e),s),{peer:la(e,s),previous:o,updated:!0})}};var gf=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new mf(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await sc(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mr.openAndCertify(e,Vt.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Vt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mr.createFromProtobuf(s.peerRecordEnvelope),a=Vt.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function pb(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var mN=r=>r;function j3(r,e){let t=r.getPeerId();return t!=null&&ge(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var yf=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??mN,this._updatePeerStoreAddresses=pb(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>j(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>j(e))}addObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>j(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Z3=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=So())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Fc(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},gN=["metrics","connectionProtector","dns"],yN=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mb(r={}){let e=new Z3(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!yN.includes(o)){let i=e.components[o];if(i==null&&!gN.includes(o))throw new g(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function gb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Yt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function J3(r){try{let{address:e}=r.nodeAddress();return!!Yt(e)}catch{return!0}}function wN(r,e){let t=J3(r.multiaddr),n=J3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function EN(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function bN(r,e){let t=bs.exactMatch(r.multiaddr),n=bs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function da(r,e){let t=wN(r,e);if(t!==0)return t;let n=bN(r,e);return n!==0?n:EN(r,e)}var xN=32,{code:vN}=ee("dnsaddr"),Ps=async function(e,t={}){let n=t.maxRecursiveDepth??xN;if(n===0)throw new g("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([l])=>l===vN)??[],i=await(t?.dns??wu()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[ar.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let d=l.data.replace(/["']/g,"").trim().split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=j(d);if(d.startsWith("/dnsaddr")){let h=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(f=>f.toString()))}else c.push(u.toString())}return c};var Jn;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Jn||(Jn={}));var z;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(z||(z={}));var RN={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ps},addressSorter:da},transportManager:{faultTolerance:to.FATAL_ALL}};async function yb(r){let e=Xi(RN,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new g(Jn.ERR_PROTECTOR_REQUIRED,z.ERR_PROTECTOR_REQUIRED);if(!(await dt(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new g("Private key doesn't match peer id",z.ERR_INVALID_KEY);return e}function wf(r){if(Ms(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ge(t),r.forEach(n=>{if(!ko(n))throw new g("Invalid Multiaddr",z.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}else{let s=ge(o);if(e==null||!e.equals(s))throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Ef="last-dial-failure";var bf=5,xf=100,vf=50,Rf=1e3*60*7;var Os={minConnections:bf,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Sf=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Os.minConnections,this.autoDialPriority=t.autoDialPriority??Os.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Os.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Os.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Os.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Os.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new wr({concurrency:t.autoDialConcurrency??Os.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ht(this.connectionManager.getDialQueue().map(l=>l.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[l=>l.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",l.id),!1):e.has(l.id)?(this.log.trace("not autodialing %p because they are already connected",l.id),!1):n.has(l.id)?(this.log.trace("not autodialing %p because they are already being dialed",l.id),!1):this.queue.has(l.id)?(this.log.trace("not autodialing %p because they are already being autodialed",l.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new it;for(let l of s)i.has(l.id)||i.set(l.id,[...l.tags.values()].reduce((d,u)=>d+u.value,0));let c=s.sort((l,d)=>{let u=i.get(l.id)??0,h=i.get(d.id)??0;return u>h?-1:u<h?1:0}).filter(l=>{let d=l.metadata.get(Ef);if(d==null)return!0;let u=parseInt(O(d));return isNaN(u)?!0:Date.now()-u>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let l of c)this.queue.add(async()=>{let d=this.connectionManager.getConnectionsMap().size;if(d>=this.minConnections){this.log("got enough connections now %d/%d",d,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",l.id),await this.connectionManager.openConnection(l.id,{priority:this.autoDialPriority})},{peerId:l.id}).catch(d=>{this.log.error("could not connect to peerStore stored peer",d)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var _N=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function wb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??_N;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Eb={maxConnections:xf,allow:[]},_f=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Eb.maxConnections,this.allow=t.allow??Eb.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new it;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await wb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Af=class extends tr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};async function bb(r,e){let t=!1;for(let o of Di.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Lc={addressSorter:da,maxParallelDials:vf,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ps}},If=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Lc.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Lc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Lc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Lc.dialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Di.set(n,o);this.queue=new Af({concurrency:t.maxParallelDials??Lc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=wf(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new g("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let h of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new g("Peer had more than maxPeerAddrsToDial",z.ERR_TOO_MANY_ADDRESSES);d++;try{let f=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),f}catch(f){if(this.log.error("dial failed to %a",h.multiaddr,f),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Ef]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new g(f.message,vn);u.push(f)}}throw u.length===1?u[0]:new Uc(u,"All multiaddr dials failed",z.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??a4,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=Ae([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return H(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:j(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new g("Tried to dial self",z.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new g("The dial request is blocked by gater.allowDialPeer",z.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(u){if(u.code!==z.ERR_NOT_FOUND)throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...u.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(u){u.code!==z.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let s=(await Promise.all(o.map(async u=>{let h=await bb(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(u.multiaddr)?u:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(u),isCertified:h.isCertified}:h)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let h=u.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let u of i){let h=u.multiaddr.toString(),f=a.get(h);if(f!=null){f.isCertified=f.isCertified||u.isCertified||!1;continue}a.set(h,u)}let c=[...a.values()];if(c.length===0)throw new g("The dial request has no valid addresses",z.ERR_NO_VALID_ADDRESSES);let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=l.sort(this.addressSorter);if(d.length===0)throw new g("The connection gater denied all addresses in the dial request",z.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!bs.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var a4=50,eo={minConnections:bf,maxConnections:xf,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Df=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??eo.maxConnections;let n=t.minConnections??eo.minConnections;if(this.maxConnections<n)throw new g("Connection Manager maxConnections must be greater than minConnections",z.ERR_INVALID_PARAMETERS);this.connections=new it,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>j(o)),this.deny=(t.deny??[]).map(o=>j(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??eo.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Qi({points:t.inboundConnectionThreshold??eo.inboundConnectionThreshold,duration:1}),this.autoDial=new Sf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??eo.autoDialConcurrency,autoDialPriority:t.autoDialPriority??eo.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??eo.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eo.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??eo.autoDialMaxQueueLength}),this.connectionPruner=new _f({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new If(e,{addressSorter:t.addressSorter??da,maxParallelDials:t.maxParallelDials??vf,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ps},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(R4)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=wf(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??a4}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Tf=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of Mt(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var kf=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new g("Should not try to find self",z.ERR_FIND_SELF);let n=this,o=Mt(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new g(Jn.NOT_FOUND,z.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of en(async function*(){let i=Mt(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var Cf=class extends ye{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ae([this.shutdownController.signal,e?.signal]);H(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=J(),yield(await er(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,H(1/0,this.walkController.signal);let e=Ae([this.walkController.signal,this.shutdownController.signal]);H(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{for await(let o of this.peerRouting.getClosestPeers(pt(32),{signal:e}))e.throwIfAborted(),this.log("found peer %p",o.id),n++,this.safeDispatchEvent("walk:peer",{detail:o}),this.walkers===1&&this.needNext!=null&&await Ue(this.needNext.promise,e)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var c4=32,l4=64,Nf=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new g(`No handler registered for protocol ${e}`,z.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new g(`Handler already registered for protocol ${e}`,z.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=Xi.bind({ignoreUndefined:!0})({maxInboundStreams:c4,maxOutboundStreams:l4},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new g("invalid topology",z.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==z.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Lf=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Wu({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??to.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new g("Transport must have a valid tag",z.ERR_INVALID_KEY);if(this.transports.has(t))throw new g(`There is already a transport with the tag ${t}`,z.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new g(`No transport available for address ${String(e)}`,z.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=z.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let l of s){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let h=u.findIndex(f=>f===d);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),i.push(d.listen(l))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==to.NO_FATAL)throw new g(`Transport (${n}) could not listen on any available address`,z.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===to.FATAL_ALL)throw new g(n,z.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Dt="/multistream/1.0.0";var DN=M(`
53
53
  `);async function Bs(r,e,t){await r.write(e,t)}async function xb(r,e,t){await r.writeV(e,t)}async function TN(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==DN[0])throw e.log.error("Invalid mss message - missing newline",t),new g("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function qo(r,e){let t=await TN(r,e);return O(t.subarray())}async function Pc(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return kN(r,e[0],t);let n=gn(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Dt,o);let s=M(`${Dt}
54
54
  `),i=M(`${o}
55
55
  `);await xb(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await qo(n,t);if(t.log.trace('select: read "%s"',a),a===Dt&&(t.log.trace("select: reading protocol response"),a=await qo(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Bs(n,M(`${c}
@@ -1,3 +1,3 @@
1
- export declare const version = "4.2.2-21ef20c";
1
+ export declare const version = "4.2.3";
2
2
  export declare const name = "helia";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,kBAAkB,CAAA;AACtC,eAAO,MAAM,IAAI,UAAU,CAAA"}
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,UAAU,CAAA;AAC9B,eAAO,MAAM,IAAI,UAAU,CAAA"}
@@ -1,3 +1,3 @@
1
- export const version = '4.2.2-21ef20c';
1
+ export const version = '4.2.3';
2
2
  export const name = 'helia';
3
3
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,eAAe,CAAA;AACtC,MAAM,CAAC,MAAM,IAAI,GAAG,OAAO,CAAA"}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAA;AAC9B,MAAM,CAAC,MAAM,IAAI,GAAG,OAAO,CAAA"}
@@ -0,0 +1,12 @@
1
+ {
2
+ "DAGWalker": "https://ipfs.github.io/helia/interfaces/helia.DAGWalker.html",
3
+ ".:DAGWalker": "https://ipfs.github.io/helia/interfaces/helia.DAGWalker.html",
4
+ "DefaultLibp2pServices": "https://ipfs.github.io/helia/interfaces/helia.DefaultLibp2pServices.html",
5
+ "HeliaInit": "https://ipfs.github.io/helia/interfaces/helia.HeliaInit.html",
6
+ ".:HeliaInit": "https://ipfs.github.io/helia/interfaces/helia.HeliaInit.html",
7
+ "HeliaLibp2p": "https://ipfs.github.io/helia/interfaces/helia.HeliaLibp2p.html",
8
+ ".:HeliaLibp2p": "https://ipfs.github.io/helia/interfaces/helia.HeliaLibp2p.html",
9
+ "createHelia": "https://ipfs.github.io/helia/functions/helia.createHelia.html",
10
+ ".:createHelia": "https://ipfs.github.io/helia/functions/helia.createHelia.html",
11
+ "libp2pDefaults": "https://ipfs.github.io/helia/functions/helia.libp2pDefaults.html"
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "helia",
3
- "version": "4.2.2-21ef20c",
3
+ "version": "4.2.3",
4
4
  "description": "An implementation of IPFS in JavaScript",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/ipfs/helia/tree/main/packages/helia#readme",
@@ -56,11 +56,11 @@
56
56
  "dependencies": {
57
57
  "@chainsafe/libp2p-noise": "^15.0.0",
58
58
  "@chainsafe/libp2p-yamux": "^6.0.2",
59
- "@helia/block-brokers": "3.0.1-21ef20c",
59
+ "@helia/block-brokers": "^3.0.2",
60
60
  "@helia/delegated-routing-v1-http-api-client": "^3.0.0",
61
- "@helia/interface": "4.3.0-21ef20c",
62
- "@helia/routers": "1.1.0-21ef20c",
63
- "@helia/utils": "0.3.1-21ef20c",
61
+ "@helia/interface": "^4.3.0",
62
+ "@helia/routers": "^1.1.0",
63
+ "@helia/utils": "^0.3.2",
64
64
  "@libp2p/autonat": "^1.0.13",
65
65
  "@libp2p/bootstrap": "^10.0.16",
66
66
  "@libp2p/circuit-relay-v2": "^1.0.16",
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '4.2.2-21ef20c'
1
+ export const version = '4.2.3'
2
2
  export const name = 'helia'