helia 1.3.10 → 1.3.11

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
@@ -81,7 +81,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
81
81
  a=ice-ufrag:`+e+`
82
82
  `).replace(/\na=ice-pwd:[^\n]*\n/,`
83
83
  a=ice-pwd:`+e+`
84
- `),r}var SN=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),AN=r=>[...Array(r)].map(()=>SN.at(Math.floor(Math.random()*SN.length))).join("");var s2=C("libp2p:webrtc:transport"),Wre=1e4,Yre=se("webrtc-direct").code,k6=se("certhash").code,i2=class{metrics;components;init;constructor(e,t={}){this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return s2(`dialing address - ${e.toString()}`),n}createListener(e){throw pP("WebRTCTransport.createListener")}filter(e){return e.filter(Qre)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[qs]=!0;async _connect(e,t){let n=new AbortController,s=n.signal,i=e.getPeerId();if(i===null)throw F1("we need to have the remote's PeerId");let o=he(i),a=C6(n2(e)),c=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:P6(a.name)}),l=new RTCPeerConnection({certificates:[c]}),u=new Promise((A,D)=>{let H=l.createDataChannel("",{negotiated:!0,id:0}),ee=setTimeout(()=>{let j=`Data channel was never opened: state: ${H.readyState}`;s2.error(j),this.metrics?.dialerEvents.increment({open_error:!0}),D(_y("data",j))},Wre);H.onopen=j=>{clearTimeout(ee),A(H)},H.onerror=j=>{clearTimeout(ee);let Ie=`Error opening a data channel for handshaking: ${j.target?.toString()??"not specified"}`;s2.error(Ie),this.metrics?.dialerEvents.increment({unknown_error:!0}),D(_y("data",Ie))}}),f="libp2p+webrtc+v1/"+AN(32),h=await l.createOffer(),p=_N(h,f);await l.setLocalDescription(p);let d=vN(e,f);await l.setRemoteDescription(d);let m=await u,g=this.components.peerId,y=this.generateNoisePrologue(l,a.code,e),b=Il({prologueBytes:y})(),w=Vl({channel:m,direction:"inbound",dataChannelOptions:this.init.dataChannel}),v={...w,sink:w.sink.bind(w),source:async function*(){for await(let A of w.source)for(let D of A)yield D}()},x=new Ua({peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=Ah?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(_,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":x.close().catch(A=>{s2.error("error closing connection",A)}).finally(()=>{n.abort()});break;default:break}},{signal:s}),this.metrics?.dialerEvents.increment({peer_connection:!0});let S=new Fa({peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(g,v,o),t.upgrader.upgradeOutbound(x,{skipProtection:!0,skipEncryption:!0,muxerFactory:S})}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Sh("no local certificate");let s=EN(e);if(s==null)throw Sh("no local fingerprint found");let i=s.trim().toLowerCase().replaceAll(":",""),o=$(i,"hex"),a=RN.encode(o,t),c=D6.decode(n2(n)),l=$("libp2p-webrtc-noise:");return Ee([l,a,c])}};function Qre(r){let e=r.protoCodes();return e.includes(Yre)&&e.includes(k6)&&r.getPeerId()!=null&&!e.includes(se("p2p-circuit").code)}function IN(r){return e=>new i2(e,r)}function TN(r){return e=>new H1(e,r)}function DN(r){let e;try{e=se("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function CN(r){return r.some(([e,t])=>e===se("tls").code)}function Dn(r,e,t){let n=PN[se(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${se(r).name}`);let s=n(e,t);return r===se("ip6").code?`[${s}]`:s}var PN={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${Dn(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${Dn(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=CN(e),n=DN(e);if(t&&n!==null)return`https://${n}`;let s=t?"https://":"http://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=Dn(i[0],i[1]??"",e);return o=o.replace("tcp://",""),`${s}${o}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return Dn(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return Dn(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=Dn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=CN(e),n=DN(e);if(t&&n!==null)return`wss://${n}`;let s=t?"wss://":"ws://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=Dn(i[0],i[1]??"",e);return o=o.replace("tcp://",""),`${s}${o}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=Dn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function kN(r,e){let n=fe(r).stringTuples(),s=n.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=se(s[0]),o=PN[i.name];if(o==null)throw new Error(`No interpreter found for ${i.name}`);let a=o(s[1]??"",n);return e?.assumeHttp!==!1&&s[0]===se("tcp").code&&(a=a.replace("tcp://","http://"),(s[1]==="443"||s[1]==="80")&&(s[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}var NN=WebSocket;var MN=W(LN(),1);function BN(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var UN=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((i,o)=>{if(n){i();return}if(s!=null){o(s);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(i)},l=u=>{a(()=>{o(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let i=new MN.EventIterator(({push:o,stop:a,fail:c})=>{let l=f=>{let h=null;typeof f.data=="string"&&(h=$(f.data)),BN(f.data)&&(h=new Uint8Array(f.data)),f.data instanceof Uint8Array&&(h=f.data),h!=null&&o(h)},u=f=>{c(f.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let o of i)yield BN(o)?new Uint8Array(o):o}(),n=r.readyState===1,s;return r.addEventListener("open",()=>{n=!0,s=null}),r.addEventListener("close",()=>{n=!1,s=null}),r.addEventListener("error",i=>{n||(s=i.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var FN=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",s),r.removeEventListener("error",i)}function s(){n(),e()}function i(o){n(),t(o.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",s),r.addEventListener("error",i)})};var VN=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let s of n){try{await FN(r)}catch(i){if(i.message==="socket closed")break;throw i}r.send(s)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((s,i)=>{r.addEventListener("close",o=>{if(o.wasClean||o.code===1006)s();else{let a=Object.assign(new Error("ws error"),{event:o});i(a)}}),setTimeout(()=>{r.close()})})});var zN=(r,e)=>{e=e??{};let t=UN(r),n=e.remoteAddress,s=e.remotePort;if(r.url!=null)try{let o=new URL(r.url);n=o.hostname,s=parseInt(o.port,10)}catch{}if(n==null||s==null)throw new Error("Remote connection did not have address and/or port");return{sink:VN(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(o=>{r.addEventListener("close",()=>{o()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:s,socket:r}};var QN=W(YN(),1),one={http:"ws",https:"wss"},ane="ws",XN=(r,e)=>(0,QN.relative)(r,e,one,ane);function jN(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=XN(r,t.toString()),s=new NN(n,e.websocket);return zN(s,e)}var eO=W(JN(),1),M6=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,c2=(0,eO.default)(),l2=M6&&!c2,tO=c2&&!M6,rO=c2&&M6,nO=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!c2,u2=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,Ske=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",sO=typeof navigator<"u"&&navigator.product==="ReactNative";function aO(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Cl.matches(t)||ka.matches(t)})}function cO(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return ka.matches(t)})}function lO(){throw new Error("WebSocket Servers can not be created in the browser!")}var U6=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},F6=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},uO=r=>globalThis.DOMException===void 0?new F6(r):new DOMException(r),fO=r=>{let e=r.reason===void 0?uO("This operation was aborted."):r.reason;return e instanceof Error?e:uO(e)};function V6(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:i={setTimeout,clearTimeout}}=e,o,c=new Promise((l,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(fO(h)),h.addEventListener("abort",()=>{u(fO(h))})}if(t===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new U6;o=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?l():s instanceof Error?u(s):(f.message=s??`Promise timed out after ${t} milliseconds`,u(f))},t),(async()=>{try{l(await r)}catch(h){u(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},c}var hO=C("libp2p:websockets:socket");function dO(r,e,t){t=t??{};let n={async sink(s){t?.signal!=null&&(s=bt(s,t.signal));try{await r.sink(s)}catch(i){i.type!=="aborted"&&hO.error(i)}},source:t.signal!=null?bt(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(){let s=Date.now();try{await V6(r.close(),{milliseconds:2e3})}catch{let{host:o,port:a}=n.remoteAddr.toOptions();hO("timeout closing stream to %s:%s after %dms, destroying it manually",o,a,Date.now()-s),r.destroy()}finally{n.timeline.close=Date.now()}}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}var Oo=C("libp2p:websockets"),z6=class{init;constructor(e){this.init=e}[Symbol.toStringTag]="@libp2p/websockets";[qs]=!0;async dial(e,t){Oo("dialing %s",e),t=t??{};let n=await this._connect(e,t),s=dO(n,e);Oo("new outbound connection %s",s.remoteAddr);let i=await t.upgrader.upgradeOutbound(s);return Oo("outbound connection %s upgraded",s.remoteAddr),i}async _connect(e,t){if(t?.signal?.aborted===!0)throw new cn;let n=e.toOptions();Oo("dialing %s:%s",n.host,n.port);let s=De(),i=l=>{Oo.error("connection error:",l),s.reject(l)},o=jN(kN(e),this.init);if(o.socket.on!=null?o.socket.on("error",i):o.socket.onerror=i,t.signal==null)return await Promise.race([o.connected(),s.promise]),Oo("connected %s",e),o;let a,c=new Promise((l,u)=>{if(a=()=>{u(new cn),o.close().catch(f=>{Oo.error("error closing raw socket",f)})},t?.signal?.aborted===!0){a();return}t?.signal?.addEventListener("abort",a)});try{await Promise.race([c,s.promise,o.connected()])}finally{a!=null&&t?.signal?.removeEventListener("abort",a)}return Oo("connected %s",e),o}createListener(e){return lO({...this.init,...e})}filter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):l2||u2?cO(e):aO(e)}};function pO(r={}){return()=>new z6(r)}var G6={};Y(G6,{identity:()=>gne});function fne(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,v=new Uint8Array(w);y!==b;){for(var x=d[y],_=0,S=w-1;(x!==0||_<g)&&S!==-1;S--,_++)x+=256*v[S]>>>0,v[S]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");g=_,y++}for(var A=w-g;A!==w&&v[A]===0;)A++;for(var D=c.repeat(m);A<w;++A)D+=r.charAt(v[A]);return D}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var v=t[d.charCodeAt(m)];if(v===255)return;for(var x=0,_=b-1;(v!==0||x<y)&&_!==-1;_--,x++)v+=a*w[_]>>>0,w[_]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");y=x,m++}if(d[m]!==" "){for(var S=b-y;S!==b&&w[S]===0;)S++;for(var A=new Uint8Array(g+(b-S)),D=g;S!==b;)A[D++]=w[S++];return A}}}function p(d){var m=h(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var hne=fne,dne=hne,mO=dne;var Qke=new Uint8Array(0);var gO=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},Ci=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var yO=r=>new TextEncoder().encode(r),bO=r=>new TextDecoder().decode(r);var q6=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},K6=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return xO(this,e)}},$6=class{constructor(e){this.decoders=e}or(e){return xO(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},xO=(r,e)=>new $6({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),H6=class{constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new q6(e,t,n),this.decoder=new K6(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},tu=({name:r,prefix:e,encode:t,decode:n})=>new H6(r,e,t,n),Lo=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:s}=mO(t,e);return tu({prefix:r,name:e,encode:n,decode:i=>Ci(s(i))})},pne=(r,e,t,n)=>{let s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=s[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},mne=(r,e,t)=>{let n=e[e.length-1]==="=",s=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,i+=e[s&a>>o];if(o&&(i+=e[s&a<<t-o]),n)for(;i.length*t&7;)i+="=";return i},Vt=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>tu({prefix:e,name:r,encode(s){return mne(s,n,t)},decode(s){return pne(s,n,t,r)}});var gne=tu({prefix:"\0",name:"identity",encode:r=>bO(r),decode:r=>yO(r)});var W6={};Y(W6,{base2:()=>yne});var yne=Vt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Y6={};Y(Y6,{base8:()=>bne});var bne=Vt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Q6={};Y(Q6,{base10:()=>wne});var wne=Lo({prefix:"9",name:"base10",alphabet:"0123456789"});var X6={};Y(X6,{base16:()=>xne,base16upper:()=>Ene});var xne=Vt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ene=Vt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var j6={};Y(j6,{base32:()=>ru,base32hex:()=>Ane,base32hexpad:()=>Ine,base32hexpadupper:()=>Tne,base32hexupper:()=>Rne,base32pad:()=>_ne,base32padupper:()=>Sne,base32upper:()=>vne,base32z:()=>Dne});var ru=Vt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),vne=Vt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_ne=Vt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Sne=Vt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ane=Vt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Rne=Vt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ine=Vt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Tne=Vt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Dne=Vt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Z6={};Y(Z6,{base36:()=>Cne,base36upper:()=>Pne});var Cne=Lo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Pne=Lo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var J6={};Y(J6,{base58btc:()=>Xs,base58flickr:()=>kne});var Xs=Lo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kne=Lo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var e7={};Y(e7,{base64:()=>Nne,base64pad:()=>One,base64url:()=>Lne,base64urlpad:()=>Bne});var Nne=Vt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),One=Vt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Lne=Vt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bne=Vt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var t7={};Y(t7,{base256emoji:()=>zne});var EO=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Mne=EO.reduce((r,e,t)=>(r[t]=e,r),[]),Une=EO.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Fne(r){return r.reduce((e,t)=>(e+=Mne[t],e),"")}function Vne(r){let e=[];for(let t of r){let n=Une[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var zne=tu({prefix:"\u{1F680}",name:"base256emoji",encode:Fne,decode:Vne});var a7={};Y(a7,{sha256:()=>ose,sha512:()=>ase});var Mo={};Y(Mo,{Digest:()=>$a,create:()=>Bo,decode:()=>n7,equals:()=>s7});var qne=SO,vO=128,Kne=127,$ne=~Kne,Hne=Math.pow(2,31);function SO(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Hne;)e[t++]=r&255|vO,r/=128;for(;r&$ne;)e[t++]=r&255|vO,r>>>=7;return e[t]=r|0,SO.bytes=t-n+1,e}var Gne=r7,Wne=128,_O=127;function r7(r,n){var t=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw r7.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=s<28?(o&_O)<<s:(o&_O)*Math.pow(2,s),s+=7}while(o>=Wne);return r7.bytes=i-n,t}var Yne=Math.pow(2,7),Qne=Math.pow(2,14),Xne=Math.pow(2,21),jne=Math.pow(2,28),Zne=Math.pow(2,35),Jne=Math.pow(2,42),ese=Math.pow(2,49),tse=Math.pow(2,56),rse=Math.pow(2,63),nse=function(r){return r<Yne?1:r<Qne?2:r<Xne?3:r<jne?4:r<Zne?5:r<Jne?6:r<ese?7:r<tse?8:r<rse?9:10},sse={encode:qne,decode:Gne,encodingLength:nse},ise=sse,Fh=ise;var Vh=(r,e=0)=>[Fh.decode(r,e),Fh.decode.bytes],nu=(r,e,t=0)=>(Fh.encode(r,e,t),e),su=r=>Fh.encodingLength(r);var Bo=(r,e)=>{let t=e.byteLength,n=su(r),s=n+su(t),i=new Uint8Array(s+t);return nu(r,i,0),nu(t,i,n),i.set(e,s),new $a(r,t,e,i)},n7=r=>{let e=Ci(r),[t,n]=Vh(e),[s,i]=Vh(e.subarray(n)),o=e.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new $a(t,s,o,e)},s7=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&gO(r.bytes,t.bytes)}},$a=class{constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var o7=({name:r,code:e,encode:t})=>new i7(r,e,t),i7=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Bo(this.code,t):t.then(n=>Bo(this.code,n))}else throw Error("Unknown type, must be binary type")}};var RO=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),ose=o7({name:"sha2-256",code:18,encode:RO("SHA-256")}),ase=o7({name:"sha2-512",code:19,encode:RO("SHA-512")});var c7={};Y(c7,{identity:()=>use});var IO=0,cse="identity",TO=Ci,lse=r=>Bo(IO,TO(r)),use={code:IO,name:cse,encode:TO,digest:lse};var gNe=new TextEncoder,yNe=new TextDecoder;var DO=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return pse(t,l7(r),e||Xs.encoder);default:return mse(t,l7(r),e||ru.encoder)}};var CO=new WeakMap,l7=r=>{let e=CO.get(r);if(e==null){let t=new Map;return CO.set(r,t),t}return e},er=class{constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==zh)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==gse)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return er.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Bo(e,t);return er.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return er.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&s7(e.multihash,n.multihash)}toString(e){return DO(this,e)}toJSON(){return{"/":DO(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof er)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:i,bytes:o}=t;return new er(n,s,i,o||PO(n,s,i.bytes))}else if(t[yse]===!0){let{version:n,multihash:s,code:i}=t,o=n7(s);return er.create(n,i,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==zh)throw new Error(`Version 0 CID must use dag-pb (code: ${zh}) block encoding`);return new er(e,t,n,n.bytes)}case 1:{let s=PO(e,t,n.bytes);return new er(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return er.create(0,zh,e)}static createV1(e,t){return er.create(1,e,t)}static decode(e){let[t,n]=er.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=er.inspectBytes(e),n=t.size-t.multihashSize,s=Ci(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),o=new $a(t.multihashCode,t.digestSize,i,s);return[t.version===0?er.createV0(o):er.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=Vh(e.subarray(t));return t+=h,f},s=n(),i=zh;if(s===18?(s=0,t=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,a=n(),c=n(),l=t+c,u=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=dse(e,t),i=er.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return l7(i).set(n,e),i}},dse=(r,e)=>{switch(r[0]){case"Q":{let t=e||Xs;return[Xs.prefix,t.decode(`${Xs.prefix}${r}`)]}case Xs.prefix:{let t=e||Xs;return[Xs.prefix,t.decode(r)]}case ru.prefix:{let t=e||ru;return[ru.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},pse=(r,e,t)=>{let{prefix:n}=t;if(n!==Xs.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return s},mse=(r,e,t)=>{let{prefix:n}=t,s=e.get(n);if(s==null){let i=t.encode(r);return e.set(n,i),i}else return s},zh=112,gse=18,PO=(r,e,t)=>{let n=su(r),s=n+su(e),i=new Uint8Array(s+t.byteLength);return nu(r,i,0),nu(e,i,n),i.set(t,s),i},yse=Symbol.for("@ipld/js-cid/CID");var kO={...G6,...W6,...Y6,...Q6,...X6,...j6,...Z6,...J6,...e7,...t7},INe={...a7,...c7};var en=C("libp2p:webtransport"),bse=Object.values(kO).map(r=>r.decoder).reduce((r,e)=>r.or(e));function wse(r){return Mo.decode(bse.decode(r))}function NO(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}async function OO(r,e,t,n,s){let i=r.writable.getWriter(),o=r.readable.getReader();await i.ready;function a(){let h=n.findIndex(p=>p===f);h!==-1&&(n.splice(h,1),f.stat.timeline.close=Date.now(),s?.(f))}let c=!1,l=!1;(async function(){let h=await i.closed.catch(p=>p);if(h!=null){let p=h.message;p.includes("aborted by the remote server")||p.includes("STOP_SENDING")||en.error(`WebTransport writer closed unexpectedly: streamId=${e} err=${h.message}`)}c=!0,c&&l&&a()})().catch(()=>{en.error("WebTransport failed to cleanup closed stream")}),async function(){let h=await o.closed.catch(p=>p);h!=null&&en.error(`WebTransport reader closed unexpectedly: streamId=${e} err=${h.message}`),l=!0,c&&l&&a()}().catch(()=>{en.error("WebTransport failed to cleanup closed stream")});let u=!1,f={id:e,abort(h){c||(i.abort(),c=!0),f.closeRead(),l=!0,a()},close(){f.closeRead(),f.closeWrite(),a()},closeRead(){l||(o.cancel().catch(h=>{h.toString().includes("RESET_STREAM")===!0&&(c=!0)}),l=!0),c&&a()},closeWrite(){c||(c=!0,i.close().catch(h=>{h.toString().includes("RESET_STREAM")===!0&&(l=!0)})),l&&a()},reset(){f.close()},stat:{direction:t,timeline:{open:Date.now()}},metadata:{},source:async function*(){for(;;){let h=await o.read();if(h.done===!0){l=!0,c&&a();return}yield new ye(h.value)}}(),sink:async function(h){if(u)throw new Error("sink already called on stream");u=!0;try{for await(let p of h)if(p instanceof Uint8Array)await i.write(p);else for(let d of p)await i.write(d)}finally{f.closeWrite()}}};return f}function xse(r){let e=r.stringTuples(),{url:t,certhashes:n,remotePeer:s}=e.reduce((i,[o,a])=>{switch(o){case se("ip6").code:case se("dns6").code:a?.includes(":")===!0&&(a=`[${a}]`);case se("ip4").code:case se("dns4").code:if(i.seenHost||i.seenPort)throw new Error("Invalid multiaddr, saw host and already saw the host or port");return{...i,url:`${i.url}${a??""}`,seenHost:!0};case se("quic").code:case se("quic-v1").code:case se("webtransport").code:if(!i.seenHost||!i.seenPort)throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");return i;case se("udp").code:if(i.seenPort)throw new Error("Invalid multiaddr, saw port but already saw the port");return{...i,url:`${i.url}:${a??""}`,seenPort:!0};case se("certhash").code:if(!i.seenHost||!i.seenPort)throw new Error("Invalid multiaddr, saw the certhash before seeing the host and port");return{...i,certhashes:i.certhashes.concat([wse(a??"")])};case se("p2p").code:return{...i,remotePeer:he(a??"")};default:throw new Error(`unexpected component in multiaddr: ${o} ${se(o).name} ${a??""} `)}},{url:"https://",seenHost:!1,seenPort:!1,certhashes:[]});return{url:t,certhashes:n,remotePeer:s}}function Ese(r,e){return e.filter(n=>!!r.find(s=>{if(n.length!==s.length)return!1;for(let i=0;i<n.length;i++)if(s[i]!==n[i])return!1;return!0})).length===e.length}var u7=class{components;config;constructor(e,t={}){this.components=e,this.config={maxInboundStreams:t.maxInboundStreams??1e3}}[Symbol.toStringTag]="@libp2p/webtransport";[qs]=!0;async dial(e,t){en("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new Error("Need a local peerid");t=t??{};let{url:s,certhashes:i,remotePeer:o}=xse(e);if(i.length===0)throw new Error("Expected multiaddr to contain certhashes");let a=new WebTransport(`${s}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:i.map(l=>({algorithm:"sha-256",value:l.digest}))});if(a.closed.catch(l=>{en.error("WebTransport transport closed due to:",l)}),await a.ready,o==null)throw new Error("Need a target peerid");if(!await this.authenticateWebTransport(a,n,o,i))throw new Error("Failed to authenticate webtransport");let c={close:async l=>{l!=null&&en("Closing webtransport with err:",l),a.close()},remoteAddr:e,timeline:{open:Date.now()},...NO()};a.closed.catch(l=>{en.error("WebTransport connection closed:",l),c.timeline.close=Date.now()});try{t?.signal?.throwIfAborted()}catch(l){throw a.close(),l}return t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:this.webtransportMuxer(a),skipProtection:!0})}async authenticateWebTransport(e,t,n,s){let i=await e.createBidirectionalStream(),o=i.writable.getWriter(),a=i.readable.getReader();await o.ready;let c={source:async function*(){for(;;){let f=await a.read();if(f.value!=null&&(yield f.value),f.done===!0)break}}(),sink:async function(f){for await(let h of f)await o.write(h)}},l=Il()(),{remoteExtensions:u}=await l.secureOutbound(t,c,n);if(o.close().catch(f=>{en.error(`Failed to close authentication stream writer: ${f.message}`)}),a.cancel().catch(f=>{en.error(`Failed to close authentication stream reader: ${f.message}`)}),!Ese(u?.webtransportCerthashes??[],s.map(f=>f.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}webtransportMuxer(e){let t=0,n=this.config;return{protocol:"webtransport",createStreamMuxer:s=>{typeof s=="function"&&(s={onIncomingStream:s});let i=[];(async function(){let a=e.incomingBidirectionalStreams.getReader();for(;;){let{done:c,value:l}=await a.read();if(c===!0)break;if(i.length>=n.maxInboundStreams)l.writable.close().catch(u=>{en.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),l.readable.cancel().catch(u=>{en.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await OO(l,String(t++),"inbound",i,s?.onStreamEnd);i.push(u),s?.onIncomingStream?.(u)}}})().catch(()=>{en.error("WebTransport failed to receive incoming stream")});let o={protocol:"webtransport",streams:i,newStream:async a=>{let c=await e.createBidirectionalStream(),l=await OO(c,String(t++),s?.direction??"outbound",i,s?.onStreamEnd);return i.push(l),l},close:a=>{a!=null&&en("Closing webtransport muxer with err:",a),e.close()},...NO()};try{s?.signal?.throwIfAborted()}catch(a){throw e.close(),a}return o}}}createListener(e){throw new Error("Webtransport servers are not supported in Node or the browser")}filter(e){return e.filter(t=>t.protoNames().includes("webtransport"))}};function LO(r={}){return e=>new u7(e,r)}var js;(function(r){let e;(function(s){s.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(s){s[s.EOL=0]="EOL"})(t||(t={})),function(s){s.codec=()=>Pt(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=me((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.value!=null&&(i.uint32(10),i.bytes(s.value)),s.signature!=null&&(i.uint32(18),i.bytes(s.signature)),s.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(s.validityType,i)),s.validity!=null&&(i.uint32(34),i.bytes(s.validity)),s.sequence!=null&&(i.uint32(40),i.uint64(s.sequence)),s.ttl!=null&&(i.uint32(48),i.uint64(s.ttl)),s.pubKey!=null&&(i.uint32(58),i.bytes(s.pubKey)),s.signatureV2!=null&&(i.uint32(66),i.bytes(s.signatureV2)),s.data!=null&&(i.uint32(74),i.bytes(s.data)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.value=s.bytes();break;case 2:o.signature=s.bytes();break;case 3:o.validityType=r.ValidityType.codec().decode(s);break;case 4:o.validity=s.bytes();break;case 5:o.sequence=s.uint64();break;case 6:o.ttl=s.uint64();break;case 7:o.pubKey=s.bytes();break;case 8:o.signatureV2=s.bytes();break;case 9:o.data=s.bytes();break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>pe(s,r.codec()),r.decode=s=>de(s,r.codec())})(js||(js={}));var qh=W(Ko(),1);var BO="ERR_IPNS_EXPIRED_RECORD",h2="ERR_UNRECOGNIZED_VALIDITY";var Uo="ERR_SIGNATURE_VERIFICATION",MO="ERR_UNRECOGNIZED_FORMAT";var f7="ERR_UNDEFINED_PARAMETER",UO="ERR_INVALID_RECORD_DATA",FO="ERR_INVALID_EMBEDDED_KEY";var VO="ERR_RECORD_TOO_LARGE";var qO=C("ipns:utils"),vse=$("/ipns/");function Kh(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),s=parseInt(t[2],10)-1,i=parseInt(t[3],10),o=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,s,i,o,a,c,l))}var KO=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw qO.error(n),(0,qh.default)(n,f7)}let t;if(e.pubKey!=null){try{t=Yr(e.pubKey)}catch(s){throw qO.error(s),s}if(!(await _r(e.pubKey)).equals(r))throw(0,qh.default)(new Error("Embedded public key did not match PeerID"),FO)}else r.publicKey!=null&&(t=Yr(r.publicKey));if(t!=null)return t;throw(0,qh.default)(new Error("no public key is available"),f7)};var $O=r=>{let e=$("ipns-signature:");return Ee([e,r])};var HO=r=>{let e=js.decode(r);return e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),{value:e.value??new Uint8Array(0),signature:e.signature??new Uint8Array(0),validityType:e.validityType??js.ValidityType.EOL,validity:e.validity??new Uint8Array(0),sequence:e.sequence??0n,pubKey:e.pubKey,ttl:e.ttl??void 0,signatureV2:e.signatureV2,data:e.data}};var GO=r=>_t(r.slice(vse.length));var WO=r=>{let e=es(r);if(e.ValidityType===0)e.ValidityType=js.ValidityType.EOL;else throw(0,qh.default)(new Error("Unknown validity type"),h2);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e};var YO=(r,e)=>{let t=e.map((n,s)=>({entry:js.decode(n),index:s}));return t.sort((n,s)=>{if(n.entry.signatureV2!=null&&s.entry.signatureV2==null)return-1;if(n.entry.signatureV2==null&&s.entry.signatureV2!=null)return 1;let i=n.entry.sequence??0n,o=s.entry.sequence??0n;if(i>o)return-1;if(i<o)return 1;let a=n.entry.validity??new Uint8Array(0),c=s.entry.validity??new Uint8Array(0),l=Kh(M(a)),u=Kh(M(c));return l.getTime()>u.getTime()?-1:l.getTime()<u.getTime()?1:0}),t[0].index};var Cn=W(Ko(),1);var $h=C("ipns:validator"),_se=1024*10,Sse=async(r,e)=>{let{value:t,validityType:n,validity:s}=e,i,o;if(e.signatureV2!=null&&e.data!=null)o=e.signatureV2,i=$O(e.data),Ase(e);else throw(0,Cn.default)(new Error("missing data or signatureV2"),Uo);let a;try{a=await r.verify(i,o)}catch{a=!1}if(!a)throw $h.error("record signature verification failed"),(0,Cn.default)(new Error("record signature verification failed"),Uo);if(s!=null&&n===js.ValidityType.EOL){let c;try{c=Kh(M(s))}catch{throw $h.error("unrecognized validity format (not an rfc3339 format)"),(0,Cn.default)(new Error("unrecognized validity format (not an rfc3339 format)"),MO)}if(c.getTime()<Date.now())throw $h.error("record has expired"),(0,Cn.default)(new Error("record has expired"),BO)}else if(n!=null)throw $h.error("unrecognized validity type"),(0,Cn.default)(new Error("unrecognized validity type"),h2);$h("ipns entry for %b is valid",t)},Ase=r=>{if(r.data==null)throw(0,Cn.default)(new Error("Record data is missing"),UO);let e=WO(r.data);if(!be(e.Value,r.value))throw(0,Cn.default)(new Error('Field "value" did not match between protobuf and CBOR'),Uo);if(!be(e.Validity,r.validity))throw(0,Cn.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Uo);if(e.ValidityType!==r.validityType)throw(0,Cn.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Uo);if(e.Sequence!==r.sequence)throw(0,Cn.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Uo);if(e.TTL!==r.ttl)throw(0,Cn.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Uo)},QO=async(r,e)=>{if(e.byteLength>_se)throw(0,Cn.default)(new Error("record too large"),VO);let t=GO(r),n=HO(e),s=await KO(t,n);await Sse(s,n)};var d7=W(fn(),1);var XO="libp2p",jO="autonat",ZO="1.0.0";var Ae;(function(r){let e;(function(l){l.DIAL="DIAL",l.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(l){l[l.DIAL=0]="DIAL",l[l.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(l){l.codec=()=>Pt(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(l){l.OK="OK",l.E_DIAL_ERROR="E_DIAL_ERROR",l.E_DIAL_REFUSED="E_DIAL_REFUSED",l.E_BAD_REQUEST="E_BAD_REQUEST",l.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(l){l[l.OK=0]="OK",l[l.E_DIAL_ERROR=100]="E_DIAL_ERROR",l[l.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",l[l.E_BAD_REQUEST=200]="E_BAD_REQUEST",l[l.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(s||(s={})),function(l){l.codec=()=>Pt(s)}(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(l){let u;l.codec=()=>(u==null&&(u=me((f,h,p={})=>{if(p.lengthDelimited!==!1&&h.fork(),f.id!=null&&(h.uint32(10),h.bytes(f.id)),f.addrs!=null)for(let d of f.addrs)h.uint32(18),h.bytes(d);p.lengthDelimited!==!1&&h.ldelim()},(f,h)=>{let p={addrs:[]},d=h==null?f.len:f.pos+h;for(;f.pos<d;){let m=f.uint32();switch(m>>>3){case 1:p.id=f.bytes();break;case 2:p.addrs.push(f.bytes());break;default:f.skipType(m&7);break}}return p})),u),l.encode=f=>pe(f,l.codec()),l.decode=f=>de(f,l.codec())})(i=r.PeerInfo||(r.PeerInfo={}));let o;(function(l){let u;l.codec=()=>(u==null&&(u=me((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.peer!=null&&(h.uint32(10),r.PeerInfo.codec().encode(f.peer,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h)=>{let p={},d=h==null?f.len:f.pos+h;for(;f.pos<d;){let m=f.uint32();switch(m>>>3){case 1:p.peer=r.PeerInfo.codec().decode(f,f.uint32());break;default:f.skipType(m&7);break}}return p})),u),l.encode=f=>pe(f,l.codec()),l.decode=f=>de(f,l.codec())})(o=r.Dial||(r.Dial={}));let a;(function(l){let u;l.codec=()=>(u==null&&(u=me((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.status!=null&&(h.uint32(8),r.ResponseStatus.codec().encode(f.status,h)),f.statusText!=null&&(h.uint32(18),h.string(f.statusText)),f.addr!=null&&(h.uint32(26),h.bytes(f.addr)),p.lengthDelimited!==!1&&h.ldelim()},(f,h)=>{let p={},d=h==null?f.len:f.pos+h;for(;f.pos<d;){let m=f.uint32();switch(m>>>3){case 1:p.status=r.ResponseStatus.codec().decode(f);break;case 2:p.statusText=f.string();break;case 3:p.addr=f.bytes();break;default:f.skipType(m&7);break}}return p})),u),l.encode=f=>pe(f,l.codec()),l.decode=f=>de(f,l.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=me((l,u,f={})=>{f.lengthDelimited!==!1&&u.fork(),l.type!=null&&(u.uint32(8),r.MessageType.codec().encode(l.type,u)),l.dial!=null&&(u.uint32(18),r.Dial.codec().encode(l.dial,u)),l.dialResponse!=null&&(u.uint32(26),r.DialResponse.codec().encode(l.dialResponse,u)),f.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let f={},h=u==null?l.len:l.pos+u;for(;l.pos<h;){let p=l.uint32();switch(p>>>3){case 1:f.type=r.MessageType.codec().decode(l);break;case 2:f.dial=r.Dial.codec().decode(l,l.uint32());break;case 3:f.dialResponse=r.DialResponse.codec().decode(l,l.uint32());break;default:l.skipType(p&7);break}}return f})),c),r.encode=l=>pe(l,r.codec()),r.decode=l=>de(l,r.codec())})(Ae||(Ae={}));var Qe=C("libp2p:autonat"),h7=4,p7=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??XO}/${jO}/${ZO}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Qe.error("error handling incoming autonat stream",t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=ot([AbortSignal.timeout(this.timeout)]);try{(0,d7.setMaxListeners)?.(1/0,t)}catch{}let n=this.components.addressManager.getAddresses().map(s=>s.toOptions().host);try{let s=Er(e.stream,t),i=this;await Re(s,o=>kt(o),async function*(o){let a=await fs(o);if(a==null){Qe("no message received"),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=Ae.decode(a)}catch(m){Qe.error("could not decode message",m),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let l=c.dial;if(l==null){Qe.error("dial was missing from message"),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let u,f=l.peer;if(f==null||f.id==null){Qe.error("PeerId missing from message"),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{u=_t(f.id)}catch(m){Qe.error("invalid PeerId",m),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Qe("incoming request from %p",u),!e.connection.remotePeer.equals(u)){Qe("target peer %p did not equal sending peer %p",u,e.connection.remotePeer),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let h=f.addrs.map(m=>fe(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Qe.trace("request to dial %s was sent from %s is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(Vn(g)??!1);return Qe.trace("host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!n.includes(g);return Qe.trace("host %s was not our host %s",g,y),y}).filter(m=>{let g=!!i.components.transportManager.transportForMultiaddr(m);return Qe.trace("transport for %s is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${u.toString()}`)),m));if(h.length===0){Qe("no valid multiaddrs for %p in message",u),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Qe("dial multiaddrs %s for peer %p",h.map(m=>m.toString()).join(", "),u);let p="",d=h[0];for await(let m of h){let g;d=m;try{if(g=await i.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Qe.error("tried to dial %s but dialed %s",m,g.remoteAddr),new Error("Unexpected remote address");Qe("Success %p",u),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(se("p2p").code).bytes}});return}catch(y){Qe("could not dial %p",u,y),p=y.message}finally{g!=null&&await g.close()}}yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_DIAL_ERROR,statusText:p,addr:d.bytes}})},o=>wt(o),e.stream)}catch(s){Qe.error("error handling incoming autonat stream",s)}finally{t.clear()}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Qe.error("error verifying external address",e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(i=>{let o=i.toOptions();return!(Vn(o.host)??!1)});if(t.length===0){Qe("no public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,d7.setMaxListeners)?.(1/0,n)}catch{}let s=this;try{Qe("verify multiaddrs %s",t.map(f=>f.toString()).join(", "));let i=Ae.encode({type:Ae.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(f=>f.bytes)}}}),a=(await Gd()).toBytes(),c={},l=[],u=async f=>{try{Qe("asking %p to verify multiaddr",f.id);let h=await s.components.connectionManager.openConnection(f.id,{signal:n}),p=await h.newStream(this.protocol,{signal:n}),d=Er(p,n),m=await Re([i],y=>wt(y),d,y=>kt(y),async y=>fs(y));if(m==null){Qe("no response received from %p",h.remotePeer);return}let g=Ae.decode(m);if(g.type!==Ae.MessageType.DIAL_RESPONSE||g.dialResponse==null){Qe("invalid autonat response from %p",h.remotePeer);return}if(g.dialResponse.status===Ae.ResponseStatus.OK){let y=h.remoteAddr.toOptions(),b;if(y.family===4)b=y.host.split(".")[0];else if(y.family===6)b=y.host.split(":")[0];else{Qe('remote address "%s" was not IP4 or IP6?',y.host);return}if(l.includes(b)){Qe("already have response from network segment %d - %s",b,y.host);return}l.push(b)}return g.dialResponse}catch(h){Qe.error("error asking remote to verify multiaddr",h)}};for await(let f of Oa(Qn(this.components.peerRouting.getClosestPeers(a,{signal:n}),h=>async()=>u(h)),{concurrency:h7}))try{if(f==null)continue;let h=f.addr==null?t[0]:fe(f.addr);if(Qe("autonat response for %a is %s",h,f.status),f.status===Ae.ResponseStatus.E_BAD_REQUEST||f.status===Ae.ResponseStatus.E_DIAL_REFUSED||f.addr==null&&t.length>1)continue;if(!t.some(d=>d.equals(h))){Qe("peer reported %a as %s but it was not in our observed address list",h,f.status);continue}let p=h.toString();if(c[p]==null&&(c[p]={success:0,failure:0}),f.status===Ae.ResponseStatus.OK?c[p].success++:f.status===Ae.ResponseStatus.E_DIAL_ERROR&&c[p].failure++,c[p].success===h7){Qe("%a is externally dialable",h),e.confirmObservedAddr(h);return}if(c[p].failure===h7){Qe("%a is not externally dialable",h),e.removeObservedAddr(h);return}}catch(h){Qe.error("could not verify external address",h)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function JO(r={}){return e=>new p7(e,r)}var uie=W(fn(),1);var m7="/libp2p/relay";var eL="circuit-relay-relay";var tL=BigInt(131072),Fo="/libp2p/circuit/relay/0.2.0/hop",d2="/libp2p/circuit/relay/0.2.0/stop",Pse=30*1e3,kse=30*1e3;var Pi;(function(r){let e;(function(s){s.RESERVE="RESERVE",s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.RESERVE=0]="RESERVE",s[s.CONNECT=1]="CONNECT",s[s.STATUS=2]="STATUS"})(t||(t={})),function(s){s.codec=()=>Pt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=me((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.type!=null&&(i.uint32(8),r.Type.codec().encode(s.type,i)),s.peer!=null&&(i.uint32(18),iu.codec().encode(s.peer,i)),s.reservation!=null&&(i.uint32(26),p2.codec().encode(s.reservation,i)),s.limit!=null&&(i.uint32(34),ou.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(40),mr.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(s);break;case 2:o.peer=iu.codec().decode(s,s.uint32());break;case 3:o.reservation=p2.codec().decode(s,s.uint32());break;case 4:o.limit=ou.codec().decode(s,s.uint32());break;case 5:o.status=mr.codec().decode(s);break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>pe(s,r.codec()),r.decode=s=>de(s,r.codec())})(Pi||(Pi={}));var xs;(function(r){let e;(function(s){s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.CONNECT=0]="CONNECT",s[s.STATUS=1]="STATUS"})(t||(t={})),function(s){s.codec=()=>Pt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=me((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.type!=null&&(i.uint32(8),r.Type.codec().encode(s.type,i)),s.peer!=null&&(i.uint32(18),iu.codec().encode(s.peer,i)),s.limit!=null&&(i.uint32(26),ou.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(32),mr.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(s);break;case 2:o.peer=iu.codec().decode(s,s.uint32());break;case 3:o.limit=ou.codec().decode(s,s.uint32());break;case 4:o.status=mr.codec().decode(s);break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>pe(s,r.codec()),r.decode=s=>de(s,r.codec())})(xs||(xs={}));var iu;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let i of t.addrs)n.uint32(18),n.bytes(i);s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={id:new Uint8Array(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.id=t.bytes();break;case 2:s.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(iu||(iu={}));var p2;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let i of t.addrs)n.uint32(18),n.bytes(i);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.expire=t.uint64();break;case 2:s.addrs.push(t.bytes());break;case 3:s.voucher=t.bytes();break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(p2||(p2={}));var ou;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.duration=t.uint32();break;case 2:s.data=t.uint64();break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(ou||(ou={}));var mr;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(mr||(mr={}));var g7;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(g7||(g7={}));(function(r){r.codec=()=>Pt(g7)})(mr||(mr={}));var y7;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.relay=t.bytes();break;case 2:s.peer=t.bytes();break;case 3:s.expiration=t.uint64();break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(y7||(y7={}));var Nse=sL,rL=128,Ose=127,Lse=~Ose,Bse=Math.pow(2,31);function sL(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Bse;)e[t++]=r&255|rL,r/=128;for(;r&Lse;)e[t++]=r&255|rL,r>>>=7;return e[t]=r|0,sL.bytes=t-n+1,e}var Mse=b7,Use=128,nL=127;function b7(r,n){var t=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw b7.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=s<28?(o&nL)<<s:(o&nL)*Math.pow(2,s),s+=7}while(o>=Use);return b7.bytes=i-n,t}var Fse=Math.pow(2,7),Vse=Math.pow(2,14),zse=Math.pow(2,21),qse=Math.pow(2,28),Kse=Math.pow(2,35),$se=Math.pow(2,42),Hse=Math.pow(2,49),Gse=Math.pow(2,56),Wse=Math.pow(2,63),Yse=function(r){return r<Fse?1:r<Vse?2:r<zse?3:r<qse?4:r<Kse?5:r<$se?6:r<Hse?7:r<Gse?8:r<Wse?9:10},Qse={encode:Nse,decode:Mse,encodingLength:Yse},Xse=Qse,Hh=Xse;var Gh=(r,e=0)=>[Hh.decode(r,e),Hh.decode.bytes],au=(r,e,t=0)=>(Hh.encode(r,e,t),e),cu=r=>Hh.encodingLength(r);var SOe=new Uint8Array(0);var oL=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},lu=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var Wh=(r,e)=>{let t=e.byteLength,n=cu(r),s=n+cu(t),i=new Uint8Array(s+t);return au(r,i,0),au(t,i,n),i.set(e,s),new uu(r,t,e,i)},aL=r=>{let e=lu(r),[t,n]=Gh(e),[s,i]=Gh(e.subarray(n)),o=e.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new uu(t,s,o,e)},cL=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&oL(r.bytes,t.bytes)}},uu=class{constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function jse(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,v=new Uint8Array(w);y!==b;){for(var x=d[y],_=0,S=w-1;(x!==0||_<g)&&S!==-1;S--,_++)x+=256*v[S]>>>0,v[S]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");g=_,y++}for(var A=w-g;A!==w&&v[A]===0;)A++;for(var D=c.repeat(m);A<w;++A)D+=r.charAt(v[A]);return D}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var v=t[d.charCodeAt(m)];if(v===255)return;for(var x=0,_=b-1;(v!==0||x<y)&&_!==-1;_--,x++)v+=a*w[_]>>>0,w[_]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");y=x,m++}if(d[m]!==" "){for(var S=b-y;S!==b&&w[S]===0;)S++;for(var A=new Uint8Array(g+(b-S)),D=g;S!==b;)A[D++]=w[S++];return A}}}function p(d){var m=h(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var Zse=jse,Jse=Zse,uL=Jse;var w7=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},x7=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return fL(this,e)}},E7=class{constructor(e){this.decoders=e}or(e){return fL(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},fL=(r,e)=>new E7({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),v7=class{constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new w7(e,t,n),this.decoder=new x7(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},hL=({name:r,prefix:e,encode:t,decode:n})=>new v7(r,e,t,n),_7=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:s}=uL(t,e);return hL({prefix:r,name:e,encode:n,decode:i=>lu(s(i))})},eie=(r,e,t,n)=>{let s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=s[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},tie=(r,e,t)=>{let n=e[e.length-1]==="=",s=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,i+=e[s&a>>o];if(o&&(i+=e[s&a<<t-o]),n)for(;i.length*t&7;)i+="=";return i},Zs=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>hL({prefix:e,name:r,encode(s){return tie(s,n,t)},decode(s){return eie(s,n,t,r)}});var ki=_7({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kOe=_7({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Yh=Zs({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),LOe=Zs({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),BOe=Zs({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),MOe=Zs({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),UOe=Zs({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),FOe=Zs({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),VOe=Zs({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zOe=Zs({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),qOe=Zs({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var dL=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return nie(t,S7(r),e||ki.encoder);default:return sie(t,S7(r),e||Yh.encoder)}};var pL=new WeakMap,S7=r=>{let e=pL.get(r);if(e==null){let t=new Map;return pL.set(r,t),t}return e},tr=class{constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Qh)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==iie)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return tr.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Wh(e,t);return tr.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return tr.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&cL(e.multihash,n.multihash)}toString(e){return dL(this,e)}toJSON(){return{"/":dL(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof tr)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:i,bytes:o}=t;return new tr(n,s,i,o||mL(n,s,i.bytes))}else if(t[oie]===!0){let{version:n,multihash:s,code:i}=t,o=aL(s);return tr.create(n,i,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Qh)throw new Error(`Version 0 CID must use dag-pb (code: ${Qh}) block encoding`);return new tr(e,t,n,n.bytes)}case 1:{let s=mL(e,t,n.bytes);return new tr(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return tr.create(0,Qh,e)}static createV1(e,t){return tr.create(1,e,t)}static decode(e){let[t,n]=tr.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=tr.inspectBytes(e),n=t.size-t.multihashSize,s=lu(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),o=new uu(t.multihashCode,t.digestSize,i,s);return[t.version===0?tr.createV0(o):tr.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=Gh(e.subarray(t));return t+=h,f},s=n(),i=Qh;if(s===18?(s=0,t=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,a=n(),c=n(),l=t+c,u=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=rie(e,t),i=tr.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return S7(i).set(n,e),i}},rie=(r,e)=>{switch(r[0]){case"Q":{let t=e||ki;return[ki.prefix,t.decode(`${ki.prefix}${r}`)]}case ki.prefix:{let t=e||ki;return[ki.prefix,t.decode(r)]}case Yh.prefix:{let t=e||Yh;return[Yh.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},nie=(r,e,t)=>{let{prefix:n}=t;if(n!==ki.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return s},sie=(r,e,t)=>{let{prefix:n}=t,s=e.get(n);if(s==null){let i=t.encode(r);return e.set(n,i),i}else return s},Qh=112,iie=18,mL=(r,e,t)=>{let n=cu(r),s=n+cu(e),i=new Uint8Array(s+t.byteLength);return au(r,i,0),au(e,i,n),i.set(t,s),i},oie=Symbol.for("@ipld/js-cid/CID");var R7=({name:r,code:e,encode:t})=>new A7(r,e,t),A7=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Wh(this.code,t):t.then(n=>Wh(this.code,n))}else throw Error("Unknown type, must be binary type")}};var gL=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),yL=R7({name:"sha2-256",code:18,encode:gL("SHA-256")}),jOe=R7({name:"sha2-512",code:19,encode:gL("SHA-512")});var iLe=C("libp2p:circuit-relay:utils");async function I7(r){let e=new TextEncoder().encode(r),t=await yL.digest(e);return tr.createV0(t)}function T7(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var lie=W(vL(),1);var bLe=C("libp2p:circuit-relay:advert-service");var YLe=C("libp2p:circuit-relay:server");var fie=C("libp2p:stream:converter");function D7(r,e={}){let{stream:t,remoteAddr:n}=r,{sink:s,source:i}=t,o=async function*(){for await(let l of i)l instanceof Uint8Array?yield l:yield*l}(),a={async sink(l){e.signal!=null&&(l=bt(l,e.signal));try{await s(l),await c()}catch(u){u.type!=="aborted"&&fie(u)}},source:e.signal!=null?bt(o,e.signal):o,remoteAddr:n,timeline:{open:Date.now(),close:void 0},async close(){await s(async function*(){yield new Uint8Array(0)}()),await c()}};async function c(){a.timeline.close==null&&(a.timeline.close=Date.now()),await Promise.resolve()}return a}var Vo=C("libp2p:circuit-relay:discover-relays"),m2=class extends $e{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.contentRouting=e.contentRouting,this.registrar=e.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Fo,Fi({onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}})),this.discover().catch(e=>{Vo.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){Vo("searching peer store for relays");let e=await this.peerStore.all({filters:[t=>t.protocols.includes(Fo)],orders:[()=>Math.random()<.5?1:-1]});for(let t of e)Vo("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});Vo("found %d relay peers in peer store",e.length);try{Vo("searching content routing for relays");let t=await I7(m7),n=0;for await(let s of this.contentRouting.findProviders(t))if(s.multiaddrs.length>0&&!s.id.equals(this.peerId)){let i=s.id;n++,await this.peerStore.merge(i,{multiaddrs:s.multiaddrs}),Vo("found relay peer %p in content routing",i),this.safeDispatchEvent("relay:discover",{detail:i})}Vo("found %d relay peers in content routing",n)}catch(t){Vo.error("failed when finding relays on the network",t)}}};var SL=C("libp2p:circuit-relay:transport:listener"),C7=class extends $e{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new Sr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){SL("listen on %s",e);let t=e.getPeerId(),n;if(t!=null){let i=he(t),o=this.connectionManager.getConnectionsMap().get(i)??[];o.length>0&&(n=o[0])}if(n==null){let i=e.toString().split("/p2p-circuit").find(a=>a!==""),o=fe(i);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let s=this.relayStore.getReservation(n.remotePeer);if(s==null)throw new E("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){SL("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,s.addrs.map(i=>fe(i).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function AL(r){return new C7(r)}var zr=C("libp2p:circuit-relay:transport:reservation-store"),die=60*1e3*10,pie=60*1e3*5,mie=30*1e3,g2=class extends $e{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;maxReservationQueueLength;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Sr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.started=!1,this.reserveQueue=new fl({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!0}async addRelay(e,t){if(this.peerId.equals(e)){zr("not trying to use self as relay");return}if(this.reserveQueue.size>this.maxReservationQueueLength){zr("not adding relay as the queue is full");return}if(this.reserveQueue.hasJob(e)){zr("relay peer is already in the reservation queue");return}zr("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(T7(n.reservation.expire)>die){zr("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((l,u)=>(u.type==="discovered"&&l++,l),0)>=this.maxDiscoveredRelays){zr("already have enough discovered relays");return}let s=await this.connectionManager.openConnection(e);if(s.remoteAddr.protoNames().includes("p2p-circuit")){zr("not creating reservation over relayed connection");return}let i=await this.#e(s);zr("created reservation on relay peer %p",e);let o=T7(i.expire),a=Math.min(Math.max(o-pie,mie),Math.pow(2,31)-1),c=setTimeout(()=>{this.addRelay(e,t).catch(l=>{zr.error("could not refresh reservation to relay %p",e,l)})},a);this.reservations.set(e,{timeout:c,reservation:i,type:t}),await this.peerStore.merge(e,{tags:{[eL]:{value:1,ttl:o}}}),await this.transportManager.listen([fe(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){zr.error("could not reserve slot on %p",e,n),this.reservations.delete(e)}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e){zr("requesting reservation from %s",e.remotePeer);let t=await e.newStream(Fo),s=jr(t).pb(Pi);s.write({type:Pi.Type.RESERVE});let i;try{i=await s.read()}catch(a){throw zr.error("error parsing reserve message response from %p because",e.remotePeer,a),a}finally{t.close()}if(i.status===mr.OK&&i.reservation!=null)return i.reservation;let o=`reservation failed with status ${i.status??"undefined"}`;throw zr.error(o),new Error(o)}#t(e){let t=this.reservations.get(e);t!=null&&(zr("connection to relay %p closed, removing reservation from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),this.safeDispatchEvent("relay:removed",{detail:e}),this.reservations.size<this.maxDiscoveredRelays&&(zr("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};var tn=C("libp2p:circuit-relay:transport"),gie=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(fe)}catch{return!1}return!0},RL={maxInboundStopStreams:300,maxOutboundStopStreams:300},P7=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,this.maxInboundStopStreams=t.maxInboundStopStreams??RL.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??RL.maxOutboundStopStreams,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new m2(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{tn.error("could not add discovered relay %p",n.detail,s)})})),this.reservationStore=new g2(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{tn.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(d2,e=>{this.onStop(e).catch(t=>{tn.error(t)})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(d2),this.started=!1}[qs]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(d=>d===290).length!==1){let d="Invalid circuit relay address";throw tn.error(d,e),new E(d,z.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),s=fe(n[0]),i=fe(n[n.length-1]),o=s.getPeerId(),a=i.getPeerId();if(o==null||a==null){let d=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw tn.error(d),new E(d,z.ERR_RELAYED_DIAL)}let c=he(o),l=he(a),u=!1,h=this.connectionManager.getConnections(c)[0];h==null&&(await this.peerStore.merge(c,{multiaddrs:[s]}),h=await this.connectionManager.openConnection(c,t),u=!0);let p;try{return p=await h.newStream([Fo]),await this.connectV2({stream:p,connection:h,destinationPeer:l,destinationAddr:i,relayAddr:s,ma:e,disconnectOnFailure:u})}catch(d){throw tn.error(`Circuit relay dial to destination ${l.toString()} via relay ${c.toString()} failed`,d),p?.abort(d),u&&await h.close(),d}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:s,relayAddr:i,ma:o,disconnectOnFailure:a}){try{let c=jr(e),l=c.pb(Pi);l.write({type:Pi.Type.CONNECT,peer:{id:n.toBytes(),addrs:[fe(s).bytes]}});let u=await l.read();if(u.status!==mr.OK)throw new E(`failed to connect via relay with status ${u?.status?.toString()??"undefined"}`,z.ERR_HOP_REQUEST_FAILED);let f=D7({stream:c.unwrap(),remoteAddr:o,localAddr:i.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return tn("new outbound connection %s",f.remoteAddr),await this.upgrader.upgradeOutbound(f)}catch(c){throw tn.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return AL({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>gs.matches(t))}async onStop({connection:e,stream:t}){let n=jr(t),s=await n.readPB(xs);if(tn("received circuit v2 stop protocol request from %s",e.remotePeer),s?.type===void 0)return;let i=n.pb(xs);if(tn("new circuit relay v2 stop stream from %s",e.remotePeer),s.type!==xs.Type.CONNECT){tn.error("invalid stop connect request via peer %s",e.remotePeer),i.write({type:xs.Type.STATUS,status:mr.UNEXPECTED_MESSAGE});return}if(!gie(s)){tn.error("invalid stop connect request via peer %s",e.remotePeer),i.write({type:xs.Type.STATUS,status:mr.MALFORMED_MESSAGE});return}let o=_t(s.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){i.write({type:xs.Type.STATUS,status:mr.PERMISSION_DENIED});return}i.write({type:xs.Type.STATUS,status:mr.OK});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],l=D7({stream:n.unwrap(),remoteAddr:a,localAddr:c});tn("new inbound connection %s",l.remoteAddr),await this.upgrader.upgradeInbound(l),tn("%s connection %s upgraded","inbound",l.remoteAddr)}};function k7(r={}){return e=>new P7(e,r)}var IL="0.45.9";var N7=`js-libp2p/${IL}`;var TL="0.1.0",DL="id",CL="id/push",PL="1.0.0",kL="1.0.0";var y2=W(fn(),1);var zo;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let i of t.listenAddrs)n.uint32(18),n.bytes(i);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let i of t.protocols)n.uint32(26),n.string(i);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={listenAddrs:[],protocols:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 5:s.protocolVersion=t.string();break;case 6:s.agentVersion=t.string();break;case 1:s.publicKey=t.bytes();break;case 2:s.listenAddrs.push(t.bytes());break;case 4:s.observedAddr=t.bytes();break;case 3:s.protocols.push(t.string());break;case 8:s.signedPeerRecord=t.bytes();break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(zo||(zo={}));var qr=C("libp2p:identify"),NL=1024*8,Es={protocolPrefix:"ipfs",agentVersion:N7,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192},b2=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??Es.protocolPrefix}/${DL}/${PL}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??Es.protocolPrefix}/${CL}/${kL}`,this.timeout=t.timeout??Es.timeout,this.maxInboundStreams=t.maxInboundStreams??Es.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??Es.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??Es.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??Es.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??Es.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??Es.maxObservedAddresses,this.host={protocolVersion:`${t.protocolPrefix??Es.protocolPrefix}/${TL}`,agentVersion:t.agentVersion??Es.agentVersion},e.events.addEventListener("connection:open",n=>{let s=n.detail;this.identify(s).catch(i=>{qr.error("error during identify trigged by connection:open",i)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(s=>{qr.error(s)})}),this.host.agentVersion===N7&&(nO||tO?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(l2||u2||rO||sO)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:$(this.host.agentVersion),ProtocolVersion:$(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{qr.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{qr.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(u=>u.decapsulateCode(se("p2p").code)),n=new Rr({peerId:this.peerId,multiaddrs:t}),s=await Lr.seal(n,this.peerId),i=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=M(o.metadata.get("AgentVersion")??$(this.host.agentVersion)),c=M(o.metadata.get("ProtocolVersion")??$(this.host.protocolVersion)),l=e.map(async u=>{let f,h=AbortSignal.timeout(this.timeout);try{(0,y2.setMaxListeners)?.(1/0,h)}catch{}try{f=await u.newStream([this.identifyPushProtocolStr],{signal:h}),await Er(f,h).sink(Re([zo.encode({listenAddrs:t.map(d=>d.bytes),signedPeerRecord:s.marshal(),protocols:i,agentVersion:a,protocolVersion:c})],d=>wt(d)))}catch(p){qr.error("could not push identify update to peer",p)}finally{f?.close()}});await Promise.all(l)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==z.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n,s=ot([AbortSignal.timeout(this.timeout),t?.signal]);try{(0,y2.setMaxListeners)?.(1/0,s)}catch{}try{n=await e.newStream([this.identifyProtocolStr],{signal:s});let i=Er(n,s),o=await Re([],i,a=>kt(a,{maxDataLength:this.maxIdentifyMessageSize??NL}),async a=>fs(a));if(o==null)throw new E("No data could be retrieved",z.ERR_CONNECTION_ENDED);try{return zo.decode(o)}catch(a){throw new E(String(a),z.ERR_INVALID_MESSAGE)}}finally{n?.close(),s.clear()}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:s,protocols:i,observedAddr:o}=n;if(s==null)throw new E("public key was missing from identify message",z.ERR_MISSING_PUBLIC_KEY);let a=await _r(s);if(!e.remotePeer.equals(a))throw new E("identified peer does not match the expected peer",z.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new E("identified peer is our own peer id?",z.ERR_INVALID_PEER);let c=yie(o);qr("identify completed for peer %p and protocols %o",a,i),qr("our observed address is %s",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(qr("storing our observed address %s",c?.toString()),this.addressManager.addObservedAddr(c));let l=await this.#e(e.remotePeer,n),u={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(f=>fe(f)),observedAddr:n.observedAddr==null?void 0:fe(n.observedAddr),protocols:n.protocols,signedPeerRecord:l};this.events.safeDispatchEvent("peer:identify",{detail:u})}async _handleIdentify(e){let{connection:t,stream:n}=e,s=AbortSignal.timeout(this.timeout);try{(0,y2.setMaxListeners)?.(1/0,s)}catch{}try{let i=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(h=>h.decapsulateCode(se("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let h=new Rr({peerId:this.peerId,multiaddrs:a});c=(await Lr.seal(h,this.peerId)).marshal().subarray()}let l=zo.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:i,listenAddrs:a.map(h=>h.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols}),u=Er(n,s),f=Re([l],h=>wt(h));await u.sink(f)}catch(i){qr.error("could not respond to identify request",i)}finally{n.close()}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let s=Er(n,AbortSignal.timeout(this.timeout)),o=await jr(s,{maxDataLength:this.maxIdentifyMessageSize??NL}).readPB(zo);await this.#e(t.remotePeer,o)}catch(s){qr.error("received invalid message",s);return}finally{n.close()}qr("handled push from %p",t.remotePeer)}async#e(e,t){if(qr("received identify from %p",e),t==null)throw new Error("Message was null or undefined");let n={addresses:t.listenAddrs.map(i=>({isCertified:!1,multiaddr:fe(i)})),protocols:t.protocols,metadata:new Map,peerRecordEnvelope:t.signedPeerRecord},s;if(t.signedPeerRecord!=null){qr("received signedPeerRecord in push from %p",e);let i=t.signedPeerRecord,o=await Lr.openAndCertify(i,Rr.DOMAIN),a=Rr.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(a.peerId))throw new Error("signing key does not match remote PeerId");let c;try{c=await this.peerStore.get(a.peerId)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}if(c!=null&&(n.metadata=c.metadata,c.peerRecordEnvelope!=null)){let l=await Lr.createFromProtobuf(c.peerRecordEnvelope),u=Rr.createFromProtobuf(l.payload);u.seqNumber>=a.seqNumber&&(qr("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,a.seqNumber),a=u,i=c.peerRecordEnvelope)}n.peerRecordEnvelope=i,n.addresses=a.multiaddrs.map(l=>({isCertified:!0,multiaddr:l})),s={seq:a.seqNumber,addresses:a.multiaddrs}}else qr("%p did not send a signed peer record",e);return t.agentVersion!=null&&n.metadata.set("AgentVersion",$(t.agentVersion)),t.protocolVersion!=null&&n.metadata.set("ProtocolVersion",$(t.protocolVersion)),await this.peerStore.patch(e,n),s}};function yie(r){if(r!=null&&r.length>0)try{return fe(r)}catch{}}function OL(r={}){return e=>new b2(e,r)}var LL={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function BL(){return{addresses:{listen:["/webrtc"]},transports:[TN(),IN(),LO(),pO(),k7({discoverRelays:1})],connectionEncryption:[Il()],streamMuxers:[ZD(),dP()],peerDiscovery:[uC(LL)],contentRouters:[yC("https://cid.contact")],services:{identify:OL(),autoNAT:JO(),pubsub:zT(),dht:rP({clientMode:!0,validators:{ipns:QO},selectors:{ipns:YO}})}}}async function ML(r,e){let t=BL();return e=e??{},RI({datastore:r,...t,...e,start:!1})}var O7="1.3.10",w2="helia";var bie=C("helia");async function wie(r={}){let e=r.datastore??new Wo,t=r.blockstore??new yu,n;xie(r.libp2p)?n=r.libp2p:n=await ML(e,r.libp2p);let s=new id({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await s.start(),s.libp2p.isStarted()?await UL(s):s.libp2p.addEventListener("start",()=>{UL(s).catch(i=>{bie.error("could not add Helia to agent version",i)})}),s}function xie(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}async function UL(r){let t=(await r.libp2p.peerStore.get(r.libp2p.peerId)).metadata.get("AgentVersion");if(t==null)return;let n=new TextDecoder().decode(t);n.match(/js-libp2p\/\d+\.\d+\.\d+\sUserAgent=/)!=null&&(n.includes(w2)?n=`${w2}/${O7} ${n.split(" ").slice(1).join(" ")}`:n=`${w2}/${O7} ${n}`,await r.libp2p.peerStore.merge(r.libp2p.peerId,{metadata:{AgentVersion:new TextEncoder().encode(n)}}))}return Zh(Eie);})();
84
+ `),r}var SN=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),AN=r=>[...Array(r)].map(()=>SN.at(Math.floor(Math.random()*SN.length))).join("");var s2=C("libp2p:webrtc:transport"),Wre=1e4,Yre=se("webrtc-direct").code,k6=se("certhash").code,i2=class{metrics;components;init;constructor(e,t={}){this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return s2(`dialing address - ${e.toString()}`),n}createListener(e){throw pP("WebRTCTransport.createListener")}filter(e){return e.filter(Qre)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[qs]=!0;async _connect(e,t){let n=new AbortController,s=n.signal,i=e.getPeerId();if(i===null)throw F1("we need to have the remote's PeerId");let o=he(i),a=C6(n2(e)),c=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:P6(a.name)}),l=new RTCPeerConnection({certificates:[c]}),u=new Promise((A,D)=>{let H=l.createDataChannel("",{negotiated:!0,id:0}),ee=setTimeout(()=>{let j=`Data channel was never opened: state: ${H.readyState}`;s2.error(j),this.metrics?.dialerEvents.increment({open_error:!0}),D(_y("data",j))},Wre);H.onopen=j=>{clearTimeout(ee),A(H)},H.onerror=j=>{clearTimeout(ee);let Ie=`Error opening a data channel for handshaking: ${j.target?.toString()??"not specified"}`;s2.error(Ie),this.metrics?.dialerEvents.increment({unknown_error:!0}),D(_y("data",Ie))}}),f="libp2p+webrtc+v1/"+AN(32),h=await l.createOffer(),p=_N(h,f);await l.setLocalDescription(p);let d=vN(e,f);await l.setRemoteDescription(d);let m=await u,g=this.components.peerId,y=this.generateNoisePrologue(l,a.code,e),b=Il({prologueBytes:y})(),w=Vl({channel:m,direction:"inbound",dataChannelOptions:this.init.dataChannel}),v={...w,sink:w.sink.bind(w),source:async function*(){for await(let A of w.source)for(let D of A)yield D}()},x=new Ua({peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=Ah?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(_,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":x.close().catch(A=>{s2.error("error closing connection",A)}).finally(()=>{n.abort()});break;default:break}},{signal:s}),this.metrics?.dialerEvents.increment({peer_connection:!0});let S=new Fa({peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(g,v,o),t.upgrader.upgradeOutbound(x,{skipProtection:!0,skipEncryption:!0,muxerFactory:S})}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Sh("no local certificate");let s=EN(e);if(s==null)throw Sh("no local fingerprint found");let i=s.trim().toLowerCase().replaceAll(":",""),o=$(i,"hex"),a=RN.encode(o,t),c=D6.decode(n2(n)),l=$("libp2p-webrtc-noise:");return Ee([l,a,c])}};function Qre(r){let e=r.protoCodes();return e.includes(Yre)&&e.includes(k6)&&r.getPeerId()!=null&&!e.includes(se("p2p-circuit").code)}function IN(r){return e=>new i2(e,r)}function TN(r){return e=>new H1(e,r)}function DN(r){let e;try{e=se("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function CN(r){return r.some(([e,t])=>e===se("tls").code)}function Dn(r,e,t){let n=PN[se(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${se(r).name}`);let s=n(e,t);return r===se("ip6").code?`[${s}]`:s}var PN={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${Dn(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${Dn(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=CN(e),n=DN(e);if(t&&n!==null)return`https://${n}`;let s=t?"https://":"http://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=Dn(i[0],i[1]??"",e);return o=o.replace("tcp://",""),`${s}${o}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return Dn(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return Dn(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=Dn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=CN(e),n=DN(e);if(t&&n!==null)return`wss://${n}`;let s=t?"wss://":"ws://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=Dn(i[0],i[1]??"",e);return o=o.replace("tcp://",""),`${s}${o}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=Dn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Dn(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function kN(r,e){let n=fe(r).stringTuples(),s=n.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=se(s[0]),o=PN[i.name];if(o==null)throw new Error(`No interpreter found for ${i.name}`);let a=o(s[1]??"",n);return e?.assumeHttp!==!1&&s[0]===se("tcp").code&&(a=a.replace("tcp://","http://"),(s[1]==="443"||s[1]==="80")&&(s[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}var NN=WebSocket;var MN=W(LN(),1);function BN(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var UN=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((i,o)=>{if(n){i();return}if(s!=null){o(s);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(i)},l=u=>{a(()=>{o(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let i=new MN.EventIterator(({push:o,stop:a,fail:c})=>{let l=f=>{let h=null;typeof f.data=="string"&&(h=$(f.data)),BN(f.data)&&(h=new Uint8Array(f.data)),f.data instanceof Uint8Array&&(h=f.data),h!=null&&o(h)},u=f=>{c(f.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let o of i)yield BN(o)?new Uint8Array(o):o}(),n=r.readyState===1,s;return r.addEventListener("open",()=>{n=!0,s=null}),r.addEventListener("close",()=>{n=!1,s=null}),r.addEventListener("error",i=>{n||(s=i.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var FN=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",s),r.removeEventListener("error",i)}function s(){n(),e()}function i(o){n(),t(o.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",s),r.addEventListener("error",i)})};var VN=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let s of n){try{await FN(r)}catch(i){if(i.message==="socket closed")break;throw i}r.send(s)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((s,i)=>{r.addEventListener("close",o=>{if(o.wasClean||o.code===1006)s();else{let a=Object.assign(new Error("ws error"),{event:o});i(a)}}),setTimeout(()=>{r.close()})})});var zN=(r,e)=>{e=e??{};let t=UN(r),n=e.remoteAddress,s=e.remotePort;if(r.url!=null)try{let o=new URL(r.url);n=o.hostname,s=parseInt(o.port,10)}catch{}if(n==null||s==null)throw new Error("Remote connection did not have address and/or port");return{sink:VN(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(o=>{r.addEventListener("close",()=>{o()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:s,socket:r}};var QN=W(YN(),1),one={http:"ws",https:"wss"},ane="ws",XN=(r,e)=>(0,QN.relative)(r,e,one,ane);function jN(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=XN(r,t.toString()),s=new NN(n,e.websocket);return zN(s,e)}var eO=W(JN(),1),M6=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,c2=(0,eO.default)(),l2=M6&&!c2,tO=c2&&!M6,rO=c2&&M6,nO=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!c2,u2=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,Ske=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",sO=typeof navigator<"u"&&navigator.product==="ReactNative";function aO(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Cl.matches(t)||ka.matches(t)})}function cO(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return ka.matches(t)})}function lO(){throw new Error("WebSocket Servers can not be created in the browser!")}var U6=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},F6=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},uO=r=>globalThis.DOMException===void 0?new F6(r):new DOMException(r),fO=r=>{let e=r.reason===void 0?uO("This operation was aborted."):r.reason;return e instanceof Error?e:uO(e)};function V6(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:i={setTimeout,clearTimeout}}=e,o,c=new Promise((l,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(fO(h)),h.addEventListener("abort",()=>{u(fO(h))})}if(t===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new U6;o=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?l():s instanceof Error?u(s):(f.message=s??`Promise timed out after ${t} milliseconds`,u(f))},t),(async()=>{try{l(await r)}catch(h){u(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},c}var hO=C("libp2p:websockets:socket");function dO(r,e,t){t=t??{};let n={async sink(s){t?.signal!=null&&(s=bt(s,t.signal));try{await r.sink(s)}catch(i){i.type!=="aborted"&&hO.error(i)}},source:t.signal!=null?bt(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(){let s=Date.now();try{await V6(r.close(),{milliseconds:2e3})}catch{let{host:o,port:a}=n.remoteAddr.toOptions();hO("timeout closing stream to %s:%s after %dms, destroying it manually",o,a,Date.now()-s),r.destroy()}finally{n.timeline.close=Date.now()}}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}var Oo=C("libp2p:websockets"),z6=class{init;constructor(e){this.init=e}[Symbol.toStringTag]="@libp2p/websockets";[qs]=!0;async dial(e,t){Oo("dialing %s",e),t=t??{};let n=await this._connect(e,t),s=dO(n,e);Oo("new outbound connection %s",s.remoteAddr);let i=await t.upgrader.upgradeOutbound(s);return Oo("outbound connection %s upgraded",s.remoteAddr),i}async _connect(e,t){if(t?.signal?.aborted===!0)throw new cn;let n=e.toOptions();Oo("dialing %s:%s",n.host,n.port);let s=De(),i=l=>{Oo.error("connection error:",l),s.reject(l)},o=jN(kN(e),this.init);if(o.socket.on!=null?o.socket.on("error",i):o.socket.onerror=i,t.signal==null)return await Promise.race([o.connected(),s.promise]),Oo("connected %s",e),o;let a,c=new Promise((l,u)=>{if(a=()=>{u(new cn),o.close().catch(f=>{Oo.error("error closing raw socket",f)})},t?.signal?.aborted===!0){a();return}t?.signal?.addEventListener("abort",a)});try{await Promise.race([c,s.promise,o.connected()])}finally{a!=null&&t?.signal?.removeEventListener("abort",a)}return Oo("connected %s",e),o}createListener(e){return lO({...this.init,...e})}filter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):l2||u2?cO(e):aO(e)}};function pO(r={}){return()=>new z6(r)}var G6={};Y(G6,{identity:()=>gne});function fne(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,v=new Uint8Array(w);y!==b;){for(var x=d[y],_=0,S=w-1;(x!==0||_<g)&&S!==-1;S--,_++)x+=256*v[S]>>>0,v[S]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");g=_,y++}for(var A=w-g;A!==w&&v[A]===0;)A++;for(var D=c.repeat(m);A<w;++A)D+=r.charAt(v[A]);return D}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var v=t[d.charCodeAt(m)];if(v===255)return;for(var x=0,_=b-1;(v!==0||x<y)&&_!==-1;_--,x++)v+=a*w[_]>>>0,w[_]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");y=x,m++}if(d[m]!==" "){for(var S=b-y;S!==b&&w[S]===0;)S++;for(var A=new Uint8Array(g+(b-S)),D=g;S!==b;)A[D++]=w[S++];return A}}}function p(d){var m=h(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var hne=fne,dne=hne,mO=dne;var Qke=new Uint8Array(0);var gO=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},Ci=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var yO=r=>new TextEncoder().encode(r),bO=r=>new TextDecoder().decode(r);var q6=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},K6=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return xO(this,e)}},$6=class{constructor(e){this.decoders=e}or(e){return xO(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},xO=(r,e)=>new $6({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),H6=class{constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new q6(e,t,n),this.decoder=new K6(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},tu=({name:r,prefix:e,encode:t,decode:n})=>new H6(r,e,t,n),Lo=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:s}=mO(t,e);return tu({prefix:r,name:e,encode:n,decode:i=>Ci(s(i))})},pne=(r,e,t,n)=>{let s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=s[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},mne=(r,e,t)=>{let n=e[e.length-1]==="=",s=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,i+=e[s&a>>o];if(o&&(i+=e[s&a<<t-o]),n)for(;i.length*t&7;)i+="=";return i},Vt=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>tu({prefix:e,name:r,encode(s){return mne(s,n,t)},decode(s){return pne(s,n,t,r)}});var gne=tu({prefix:"\0",name:"identity",encode:r=>bO(r),decode:r=>yO(r)});var W6={};Y(W6,{base2:()=>yne});var yne=Vt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Y6={};Y(Y6,{base8:()=>bne});var bne=Vt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Q6={};Y(Q6,{base10:()=>wne});var wne=Lo({prefix:"9",name:"base10",alphabet:"0123456789"});var X6={};Y(X6,{base16:()=>xne,base16upper:()=>Ene});var xne=Vt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ene=Vt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var j6={};Y(j6,{base32:()=>ru,base32hex:()=>Ane,base32hexpad:()=>Ine,base32hexpadupper:()=>Tne,base32hexupper:()=>Rne,base32pad:()=>_ne,base32padupper:()=>Sne,base32upper:()=>vne,base32z:()=>Dne});var ru=Vt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),vne=Vt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_ne=Vt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Sne=Vt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ane=Vt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Rne=Vt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ine=Vt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Tne=Vt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Dne=Vt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Z6={};Y(Z6,{base36:()=>Cne,base36upper:()=>Pne});var Cne=Lo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Pne=Lo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var J6={};Y(J6,{base58btc:()=>Xs,base58flickr:()=>kne});var Xs=Lo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kne=Lo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var e7={};Y(e7,{base64:()=>Nne,base64pad:()=>One,base64url:()=>Lne,base64urlpad:()=>Bne});var Nne=Vt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),One=Vt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Lne=Vt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bne=Vt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var t7={};Y(t7,{base256emoji:()=>zne});var EO=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Mne=EO.reduce((r,e,t)=>(r[t]=e,r),[]),Une=EO.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Fne(r){return r.reduce((e,t)=>(e+=Mne[t],e),"")}function Vne(r){let e=[];for(let t of r){let n=Une[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var zne=tu({prefix:"\u{1F680}",name:"base256emoji",encode:Fne,decode:Vne});var a7={};Y(a7,{sha256:()=>ose,sha512:()=>ase});var Mo={};Y(Mo,{Digest:()=>$a,create:()=>Bo,decode:()=>n7,equals:()=>s7});var qne=SO,vO=128,Kne=127,$ne=~Kne,Hne=Math.pow(2,31);function SO(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Hne;)e[t++]=r&255|vO,r/=128;for(;r&$ne;)e[t++]=r&255|vO,r>>>=7;return e[t]=r|0,SO.bytes=t-n+1,e}var Gne=r7,Wne=128,_O=127;function r7(r,n){var t=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw r7.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=s<28?(o&_O)<<s:(o&_O)*Math.pow(2,s),s+=7}while(o>=Wne);return r7.bytes=i-n,t}var Yne=Math.pow(2,7),Qne=Math.pow(2,14),Xne=Math.pow(2,21),jne=Math.pow(2,28),Zne=Math.pow(2,35),Jne=Math.pow(2,42),ese=Math.pow(2,49),tse=Math.pow(2,56),rse=Math.pow(2,63),nse=function(r){return r<Yne?1:r<Qne?2:r<Xne?3:r<jne?4:r<Zne?5:r<Jne?6:r<ese?7:r<tse?8:r<rse?9:10},sse={encode:qne,decode:Gne,encodingLength:nse},ise=sse,Fh=ise;var Vh=(r,e=0)=>[Fh.decode(r,e),Fh.decode.bytes],nu=(r,e,t=0)=>(Fh.encode(r,e,t),e),su=r=>Fh.encodingLength(r);var Bo=(r,e)=>{let t=e.byteLength,n=su(r),s=n+su(t),i=new Uint8Array(s+t);return nu(r,i,0),nu(t,i,n),i.set(e,s),new $a(r,t,e,i)},n7=r=>{let e=Ci(r),[t,n]=Vh(e),[s,i]=Vh(e.subarray(n)),o=e.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new $a(t,s,o,e)},s7=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&gO(r.bytes,t.bytes)}},$a=class{constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var o7=({name:r,code:e,encode:t})=>new i7(r,e,t),i7=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Bo(this.code,t):t.then(n=>Bo(this.code,n))}else throw Error("Unknown type, must be binary type")}};var RO=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),ose=o7({name:"sha2-256",code:18,encode:RO("SHA-256")}),ase=o7({name:"sha2-512",code:19,encode:RO("SHA-512")});var c7={};Y(c7,{identity:()=>use});var IO=0,cse="identity",TO=Ci,lse=r=>Bo(IO,TO(r)),use={code:IO,name:cse,encode:TO,digest:lse};var gNe=new TextEncoder,yNe=new TextDecoder;var DO=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return pse(t,l7(r),e||Xs.encoder);default:return mse(t,l7(r),e||ru.encoder)}};var CO=new WeakMap,l7=r=>{let e=CO.get(r);if(e==null){let t=new Map;return CO.set(r,t),t}return e},er=class{constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==zh)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==gse)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return er.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Bo(e,t);return er.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return er.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&s7(e.multihash,n.multihash)}toString(e){return DO(this,e)}toJSON(){return{"/":DO(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof er)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:i,bytes:o}=t;return new er(n,s,i,o||PO(n,s,i.bytes))}else if(t[yse]===!0){let{version:n,multihash:s,code:i}=t,o=n7(s);return er.create(n,i,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==zh)throw new Error(`Version 0 CID must use dag-pb (code: ${zh}) block encoding`);return new er(e,t,n,n.bytes)}case 1:{let s=PO(e,t,n.bytes);return new er(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return er.create(0,zh,e)}static createV1(e,t){return er.create(1,e,t)}static decode(e){let[t,n]=er.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=er.inspectBytes(e),n=t.size-t.multihashSize,s=Ci(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),o=new $a(t.multihashCode,t.digestSize,i,s);return[t.version===0?er.createV0(o):er.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=Vh(e.subarray(t));return t+=h,f},s=n(),i=zh;if(s===18?(s=0,t=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,a=n(),c=n(),l=t+c,u=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=dse(e,t),i=er.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return l7(i).set(n,e),i}},dse=(r,e)=>{switch(r[0]){case"Q":{let t=e||Xs;return[Xs.prefix,t.decode(`${Xs.prefix}${r}`)]}case Xs.prefix:{let t=e||Xs;return[Xs.prefix,t.decode(r)]}case ru.prefix:{let t=e||ru;return[ru.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},pse=(r,e,t)=>{let{prefix:n}=t;if(n!==Xs.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return s},mse=(r,e,t)=>{let{prefix:n}=t,s=e.get(n);if(s==null){let i=t.encode(r);return e.set(n,i),i}else return s},zh=112,gse=18,PO=(r,e,t)=>{let n=su(r),s=n+su(e),i=new Uint8Array(s+t.byteLength);return nu(r,i,0),nu(e,i,n),i.set(t,s),i},yse=Symbol.for("@ipld/js-cid/CID");var kO={...G6,...W6,...Y6,...Q6,...X6,...j6,...Z6,...J6,...e7,...t7},INe={...a7,...c7};var en=C("libp2p:webtransport"),bse=Object.values(kO).map(r=>r.decoder).reduce((r,e)=>r.or(e));function wse(r){return Mo.decode(bse.decode(r))}function NO(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}async function OO(r,e,t,n,s){let i=r.writable.getWriter(),o=r.readable.getReader();await i.ready;function a(){let h=n.findIndex(p=>p===f);h!==-1&&(n.splice(h,1),f.stat.timeline.close=Date.now(),s?.(f))}let c=!1,l=!1;(async function(){let h=await i.closed.catch(p=>p);if(h!=null){let p=h.message;p.includes("aborted by the remote server")||p.includes("STOP_SENDING")||en.error(`WebTransport writer closed unexpectedly: streamId=${e} err=${h.message}`)}c=!0,c&&l&&a()})().catch(()=>{en.error("WebTransport failed to cleanup closed stream")}),async function(){let h=await o.closed.catch(p=>p);h!=null&&en.error(`WebTransport reader closed unexpectedly: streamId=${e} err=${h.message}`),l=!0,c&&l&&a()}().catch(()=>{en.error("WebTransport failed to cleanup closed stream")});let u=!1,f={id:e,abort(h){c||(i.abort(),c=!0),f.closeRead(),l=!0,a()},close(){f.closeRead(),f.closeWrite(),a()},closeRead(){l||(o.cancel().catch(h=>{h.toString().includes("RESET_STREAM")===!0&&(c=!0)}),l=!0),c&&a()},closeWrite(){c||(c=!0,i.close().catch(h=>{h.toString().includes("RESET_STREAM")===!0&&(l=!0)})),l&&a()},reset(){f.close()},stat:{direction:t,timeline:{open:Date.now()}},metadata:{},source:async function*(){for(;;){let h=await o.read();if(h.done===!0){l=!0,c&&a();return}yield new ye(h.value)}}(),sink:async function(h){if(u)throw new Error("sink already called on stream");u=!0;try{for await(let p of h)if(p instanceof Uint8Array)await i.write(p);else for(let d of p)await i.write(d)}finally{f.closeWrite()}}};return f}function xse(r){let e=r.stringTuples(),{url:t,certhashes:n,remotePeer:s}=e.reduce((i,[o,a])=>{switch(o){case se("ip6").code:case se("dns6").code:a?.includes(":")===!0&&(a=`[${a}]`);case se("ip4").code:case se("dns4").code:if(i.seenHost||i.seenPort)throw new Error("Invalid multiaddr, saw host and already saw the host or port");return{...i,url:`${i.url}${a??""}`,seenHost:!0};case se("quic").code:case se("quic-v1").code:case se("webtransport").code:if(!i.seenHost||!i.seenPort)throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");return i;case se("udp").code:if(i.seenPort)throw new Error("Invalid multiaddr, saw port but already saw the port");return{...i,url:`${i.url}:${a??""}`,seenPort:!0};case se("certhash").code:if(!i.seenHost||!i.seenPort)throw new Error("Invalid multiaddr, saw the certhash before seeing the host and port");return{...i,certhashes:i.certhashes.concat([wse(a??"")])};case se("p2p").code:return{...i,remotePeer:he(a??"")};default:throw new Error(`unexpected component in multiaddr: ${o} ${se(o).name} ${a??""} `)}},{url:"https://",seenHost:!1,seenPort:!1,certhashes:[]});return{url:t,certhashes:n,remotePeer:s}}function Ese(r,e){return e.filter(n=>!!r.find(s=>{if(n.length!==s.length)return!1;for(let i=0;i<n.length;i++)if(s[i]!==n[i])return!1;return!0})).length===e.length}var u7=class{components;config;constructor(e,t={}){this.components=e,this.config={maxInboundStreams:t.maxInboundStreams??1e3}}[Symbol.toStringTag]="@libp2p/webtransport";[qs]=!0;async dial(e,t){en("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new Error("Need a local peerid");t=t??{};let{url:s,certhashes:i,remotePeer:o}=xse(e);if(i.length===0)throw new Error("Expected multiaddr to contain certhashes");let a=new WebTransport(`${s}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:i.map(l=>({algorithm:"sha-256",value:l.digest}))});if(a.closed.catch(l=>{en.error("WebTransport transport closed due to:",l)}),await a.ready,o==null)throw new Error("Need a target peerid");if(!await this.authenticateWebTransport(a,n,o,i))throw new Error("Failed to authenticate webtransport");let c={close:async l=>{l!=null&&en("Closing webtransport with err:",l),a.close()},remoteAddr:e,timeline:{open:Date.now()},...NO()};a.closed.catch(l=>{en.error("WebTransport connection closed:",l),c.timeline.close=Date.now()});try{t?.signal?.throwIfAborted()}catch(l){throw a.close(),l}return t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:this.webtransportMuxer(a),skipProtection:!0})}async authenticateWebTransport(e,t,n,s){let i=await e.createBidirectionalStream(),o=i.writable.getWriter(),a=i.readable.getReader();await o.ready;let c={source:async function*(){for(;;){let f=await a.read();if(f.value!=null&&(yield f.value),f.done===!0)break}}(),sink:async function(f){for await(let h of f)await o.write(h)}},l=Il()(),{remoteExtensions:u}=await l.secureOutbound(t,c,n);if(o.close().catch(f=>{en.error(`Failed to close authentication stream writer: ${f.message}`)}),a.cancel().catch(f=>{en.error(`Failed to close authentication stream reader: ${f.message}`)}),!Ese(u?.webtransportCerthashes??[],s.map(f=>f.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}webtransportMuxer(e){let t=0,n=this.config;return{protocol:"webtransport",createStreamMuxer:s=>{typeof s=="function"&&(s={onIncomingStream:s});let i=[];(async function(){let a=e.incomingBidirectionalStreams.getReader();for(;;){let{done:c,value:l}=await a.read();if(c===!0)break;if(i.length>=n.maxInboundStreams)l.writable.close().catch(u=>{en.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),l.readable.cancel().catch(u=>{en.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await OO(l,String(t++),"inbound",i,s?.onStreamEnd);i.push(u),s?.onIncomingStream?.(u)}}})().catch(()=>{en.error("WebTransport failed to receive incoming stream")});let o={protocol:"webtransport",streams:i,newStream:async a=>{let c=await e.createBidirectionalStream(),l=await OO(c,String(t++),s?.direction??"outbound",i,s?.onStreamEnd);return i.push(l),l},close:a=>{a!=null&&en("Closing webtransport muxer with err:",a),e.close()},...NO()};try{s?.signal?.throwIfAborted()}catch(a){throw e.close(),a}return o}}}createListener(e){throw new Error("Webtransport servers are not supported in Node or the browser")}filter(e){return e.filter(t=>t.protoNames().includes("webtransport"))}};function LO(r={}){return e=>new u7(e,r)}var js;(function(r){let e;(function(s){s.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(s){s[s.EOL=0]="EOL"})(t||(t={})),function(s){s.codec=()=>Pt(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=me((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.value!=null&&(i.uint32(10),i.bytes(s.value)),s.signature!=null&&(i.uint32(18),i.bytes(s.signature)),s.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(s.validityType,i)),s.validity!=null&&(i.uint32(34),i.bytes(s.validity)),s.sequence!=null&&(i.uint32(40),i.uint64(s.sequence)),s.ttl!=null&&(i.uint32(48),i.uint64(s.ttl)),s.pubKey!=null&&(i.uint32(58),i.bytes(s.pubKey)),s.signatureV2!=null&&(i.uint32(66),i.bytes(s.signatureV2)),s.data!=null&&(i.uint32(74),i.bytes(s.data)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.value=s.bytes();break;case 2:o.signature=s.bytes();break;case 3:o.validityType=r.ValidityType.codec().decode(s);break;case 4:o.validity=s.bytes();break;case 5:o.sequence=s.uint64();break;case 6:o.ttl=s.uint64();break;case 7:o.pubKey=s.bytes();break;case 8:o.signatureV2=s.bytes();break;case 9:o.data=s.bytes();break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>pe(s,r.codec()),r.decode=s=>de(s,r.codec())})(js||(js={}));var qh=W(Ko(),1);var BO="ERR_IPNS_EXPIRED_RECORD",h2="ERR_UNRECOGNIZED_VALIDITY";var Uo="ERR_SIGNATURE_VERIFICATION",MO="ERR_UNRECOGNIZED_FORMAT";var f7="ERR_UNDEFINED_PARAMETER",UO="ERR_INVALID_RECORD_DATA",FO="ERR_INVALID_EMBEDDED_KEY";var VO="ERR_RECORD_TOO_LARGE";var qO=C("ipns:utils"),vse=$("/ipns/");function Kh(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),s=parseInt(t[2],10)-1,i=parseInt(t[3],10),o=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,s,i,o,a,c,l))}var KO=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw qO.error(n),(0,qh.default)(n,f7)}let t;if(e.pubKey!=null){try{t=Yr(e.pubKey)}catch(s){throw qO.error(s),s}if(!(await _r(e.pubKey)).equals(r))throw(0,qh.default)(new Error("Embedded public key did not match PeerID"),FO)}else r.publicKey!=null&&(t=Yr(r.publicKey));if(t!=null)return t;throw(0,qh.default)(new Error("no public key is available"),f7)};var $O=r=>{let e=$("ipns-signature:");return Ee([e,r])};var HO=r=>{let e=js.decode(r);return e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),{value:e.value??new Uint8Array(0),signature:e.signature??new Uint8Array(0),validityType:e.validityType??js.ValidityType.EOL,validity:e.validity??new Uint8Array(0),sequence:e.sequence??0n,pubKey:e.pubKey,ttl:e.ttl??void 0,signatureV2:e.signatureV2,data:e.data}};var GO=r=>_t(r.slice(vse.length));var WO=r=>{let e=es(r);if(e.ValidityType===0)e.ValidityType=js.ValidityType.EOL;else throw(0,qh.default)(new Error("Unknown validity type"),h2);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e};var YO=(r,e)=>{let t=e.map((n,s)=>({entry:js.decode(n),index:s}));return t.sort((n,s)=>{if(n.entry.signatureV2!=null&&s.entry.signatureV2==null)return-1;if(n.entry.signatureV2==null&&s.entry.signatureV2!=null)return 1;let i=n.entry.sequence??0n,o=s.entry.sequence??0n;if(i>o)return-1;if(i<o)return 1;let a=n.entry.validity??new Uint8Array(0),c=s.entry.validity??new Uint8Array(0),l=Kh(M(a)),u=Kh(M(c));return l.getTime()>u.getTime()?-1:l.getTime()<u.getTime()?1:0}),t[0].index};var Cn=W(Ko(),1);var $h=C("ipns:validator"),_se=1024*10,Sse=async(r,e)=>{let{value:t,validityType:n,validity:s}=e,i,o;if(e.signatureV2!=null&&e.data!=null)o=e.signatureV2,i=$O(e.data),Ase(e);else throw(0,Cn.default)(new Error("missing data or signatureV2"),Uo);let a;try{a=await r.verify(i,o)}catch{a=!1}if(!a)throw $h.error("record signature verification failed"),(0,Cn.default)(new Error("record signature verification failed"),Uo);if(s!=null&&n===js.ValidityType.EOL){let c;try{c=Kh(M(s))}catch{throw $h.error("unrecognized validity format (not an rfc3339 format)"),(0,Cn.default)(new Error("unrecognized validity format (not an rfc3339 format)"),MO)}if(c.getTime()<Date.now())throw $h.error("record has expired"),(0,Cn.default)(new Error("record has expired"),BO)}else if(n!=null)throw $h.error("unrecognized validity type"),(0,Cn.default)(new Error("unrecognized validity type"),h2);$h("ipns entry for %b is valid",t)},Ase=r=>{if(r.data==null)throw(0,Cn.default)(new Error("Record data is missing"),UO);let e=WO(r.data);if(!be(e.Value,r.value))throw(0,Cn.default)(new Error('Field "value" did not match between protobuf and CBOR'),Uo);if(!be(e.Validity,r.validity))throw(0,Cn.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Uo);if(e.ValidityType!==r.validityType)throw(0,Cn.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Uo);if(e.Sequence!==r.sequence)throw(0,Cn.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Uo);if(e.TTL!==r.ttl)throw(0,Cn.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Uo)},QO=async(r,e)=>{if(e.byteLength>_se)throw(0,Cn.default)(new Error("record too large"),VO);let t=GO(r),n=HO(e),s=await KO(t,n);await Sse(s,n)};var d7=W(fn(),1);var XO="libp2p",jO="autonat",ZO="1.0.0";var Ae;(function(r){let e;(function(l){l.DIAL="DIAL",l.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(l){l[l.DIAL=0]="DIAL",l[l.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(l){l.codec=()=>Pt(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(l){l.OK="OK",l.E_DIAL_ERROR="E_DIAL_ERROR",l.E_DIAL_REFUSED="E_DIAL_REFUSED",l.E_BAD_REQUEST="E_BAD_REQUEST",l.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(l){l[l.OK=0]="OK",l[l.E_DIAL_ERROR=100]="E_DIAL_ERROR",l[l.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",l[l.E_BAD_REQUEST=200]="E_BAD_REQUEST",l[l.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(s||(s={})),function(l){l.codec=()=>Pt(s)}(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(l){let u;l.codec=()=>(u==null&&(u=me((f,h,p={})=>{if(p.lengthDelimited!==!1&&h.fork(),f.id!=null&&(h.uint32(10),h.bytes(f.id)),f.addrs!=null)for(let d of f.addrs)h.uint32(18),h.bytes(d);p.lengthDelimited!==!1&&h.ldelim()},(f,h)=>{let p={addrs:[]},d=h==null?f.len:f.pos+h;for(;f.pos<d;){let m=f.uint32();switch(m>>>3){case 1:p.id=f.bytes();break;case 2:p.addrs.push(f.bytes());break;default:f.skipType(m&7);break}}return p})),u),l.encode=f=>pe(f,l.codec()),l.decode=f=>de(f,l.codec())})(i=r.PeerInfo||(r.PeerInfo={}));let o;(function(l){let u;l.codec=()=>(u==null&&(u=me((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.peer!=null&&(h.uint32(10),r.PeerInfo.codec().encode(f.peer,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h)=>{let p={},d=h==null?f.len:f.pos+h;for(;f.pos<d;){let m=f.uint32();switch(m>>>3){case 1:p.peer=r.PeerInfo.codec().decode(f,f.uint32());break;default:f.skipType(m&7);break}}return p})),u),l.encode=f=>pe(f,l.codec()),l.decode=f=>de(f,l.codec())})(o=r.Dial||(r.Dial={}));let a;(function(l){let u;l.codec=()=>(u==null&&(u=me((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.status!=null&&(h.uint32(8),r.ResponseStatus.codec().encode(f.status,h)),f.statusText!=null&&(h.uint32(18),h.string(f.statusText)),f.addr!=null&&(h.uint32(26),h.bytes(f.addr)),p.lengthDelimited!==!1&&h.ldelim()},(f,h)=>{let p={},d=h==null?f.len:f.pos+h;for(;f.pos<d;){let m=f.uint32();switch(m>>>3){case 1:p.status=r.ResponseStatus.codec().decode(f);break;case 2:p.statusText=f.string();break;case 3:p.addr=f.bytes();break;default:f.skipType(m&7);break}}return p})),u),l.encode=f=>pe(f,l.codec()),l.decode=f=>de(f,l.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=me((l,u,f={})=>{f.lengthDelimited!==!1&&u.fork(),l.type!=null&&(u.uint32(8),r.MessageType.codec().encode(l.type,u)),l.dial!=null&&(u.uint32(18),r.Dial.codec().encode(l.dial,u)),l.dialResponse!=null&&(u.uint32(26),r.DialResponse.codec().encode(l.dialResponse,u)),f.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let f={},h=u==null?l.len:l.pos+u;for(;l.pos<h;){let p=l.uint32();switch(p>>>3){case 1:f.type=r.MessageType.codec().decode(l);break;case 2:f.dial=r.Dial.codec().decode(l,l.uint32());break;case 3:f.dialResponse=r.DialResponse.codec().decode(l,l.uint32());break;default:l.skipType(p&7);break}}return f})),c),r.encode=l=>pe(l,r.codec()),r.decode=l=>de(l,r.codec())})(Ae||(Ae={}));var Qe=C("libp2p:autonat"),h7=4,p7=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??XO}/${jO}/${ZO}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Qe.error("error handling incoming autonat stream",t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=ot([AbortSignal.timeout(this.timeout)]);try{(0,d7.setMaxListeners)?.(1/0,t)}catch{}let n=this.components.addressManager.getAddresses().map(s=>s.toOptions().host);try{let s=Er(e.stream,t),i=this;await Re(s,o=>kt(o),async function*(o){let a=await fs(o);if(a==null){Qe("no message received"),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=Ae.decode(a)}catch(m){Qe.error("could not decode message",m),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let l=c.dial;if(l==null){Qe.error("dial was missing from message"),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let u,f=l.peer;if(f==null||f.id==null){Qe.error("PeerId missing from message"),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{u=_t(f.id)}catch(m){Qe.error("invalid PeerId",m),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Qe("incoming request from %p",u),!e.connection.remotePeer.equals(u)){Qe("target peer %p did not equal sending peer %p",u,e.connection.remotePeer),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let h=f.addrs.map(m=>fe(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Qe.trace("request to dial %s was sent from %s is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(Vn(g)??!1);return Qe.trace("host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!n.includes(g);return Qe.trace("host %s was not our host %s",g,y),y}).filter(m=>{let g=!!i.components.transportManager.transportForMultiaddr(m);return Qe.trace("transport for %s is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${u.toString()}`)),m));if(h.length===0){Qe("no valid multiaddrs for %p in message",u),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Qe("dial multiaddrs %s for peer %p",h.map(m=>m.toString()).join(", "),u);let p="",d=h[0];for await(let m of h){let g;d=m;try{if(g=await i.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Qe.error("tried to dial %s but dialed %s",m,g.remoteAddr),new Error("Unexpected remote address");Qe("Success %p",u),yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(se("p2p").code).bytes}});return}catch(y){Qe("could not dial %p",u,y),p=y.message}finally{g!=null&&await g.close()}}yield Ae.encode({type:Ae.MessageType.DIAL_RESPONSE,dialResponse:{status:Ae.ResponseStatus.E_DIAL_ERROR,statusText:p,addr:d.bytes}})},o=>wt(o),e.stream)}catch(s){Qe.error("error handling incoming autonat stream",s)}finally{t.clear()}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Qe.error("error verifying external address",e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(i=>{let o=i.toOptions();return!(Vn(o.host)??!1)});if(t.length===0){Qe("no public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,d7.setMaxListeners)?.(1/0,n)}catch{}let s=this;try{Qe("verify multiaddrs %s",t.map(f=>f.toString()).join(", "));let i=Ae.encode({type:Ae.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(f=>f.bytes)}}}),a=(await Gd()).toBytes(),c={},l=[],u=async f=>{try{Qe("asking %p to verify multiaddr",f.id);let h=await s.components.connectionManager.openConnection(f.id,{signal:n}),p=await h.newStream(this.protocol,{signal:n}),d=Er(p,n),m=await Re([i],y=>wt(y),d,y=>kt(y),async y=>fs(y));if(m==null){Qe("no response received from %p",h.remotePeer);return}let g=Ae.decode(m);if(g.type!==Ae.MessageType.DIAL_RESPONSE||g.dialResponse==null){Qe("invalid autonat response from %p",h.remotePeer);return}if(g.dialResponse.status===Ae.ResponseStatus.OK){let y=h.remoteAddr.toOptions(),b;if(y.family===4)b=y.host.split(".")[0];else if(y.family===6)b=y.host.split(":")[0];else{Qe('remote address "%s" was not IP4 or IP6?',y.host);return}if(l.includes(b)){Qe("already have response from network segment %d - %s",b,y.host);return}l.push(b)}return g.dialResponse}catch(h){Qe.error("error asking remote to verify multiaddr",h)}};for await(let f of Oa(Qn(this.components.peerRouting.getClosestPeers(a,{signal:n}),h=>async()=>u(h)),{concurrency:h7}))try{if(f==null)continue;let h=f.addr==null?t[0]:fe(f.addr);if(Qe("autonat response for %a is %s",h,f.status),f.status===Ae.ResponseStatus.E_BAD_REQUEST||f.status===Ae.ResponseStatus.E_DIAL_REFUSED||f.addr==null&&t.length>1)continue;if(!t.some(d=>d.equals(h))){Qe("peer reported %a as %s but it was not in our observed address list",h,f.status);continue}let p=h.toString();if(c[p]==null&&(c[p]={success:0,failure:0}),f.status===Ae.ResponseStatus.OK?c[p].success++:f.status===Ae.ResponseStatus.E_DIAL_ERROR&&c[p].failure++,c[p].success===h7){Qe("%a is externally dialable",h),e.confirmObservedAddr(h);return}if(c[p].failure===h7){Qe("%a is not externally dialable",h),e.removeObservedAddr(h);return}}catch(h){Qe.error("could not verify external address",h)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function JO(r={}){return e=>new p7(e,r)}var uie=W(fn(),1);var m7="/libp2p/relay";var eL="circuit-relay-relay";var tL=BigInt(131072),Fo="/libp2p/circuit/relay/0.2.0/hop",d2="/libp2p/circuit/relay/0.2.0/stop",Pse=30*1e3,kse=30*1e3;var Pi;(function(r){let e;(function(s){s.RESERVE="RESERVE",s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.RESERVE=0]="RESERVE",s[s.CONNECT=1]="CONNECT",s[s.STATUS=2]="STATUS"})(t||(t={})),function(s){s.codec=()=>Pt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=me((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.type!=null&&(i.uint32(8),r.Type.codec().encode(s.type,i)),s.peer!=null&&(i.uint32(18),iu.codec().encode(s.peer,i)),s.reservation!=null&&(i.uint32(26),p2.codec().encode(s.reservation,i)),s.limit!=null&&(i.uint32(34),ou.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(40),mr.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(s);break;case 2:o.peer=iu.codec().decode(s,s.uint32());break;case 3:o.reservation=p2.codec().decode(s,s.uint32());break;case 4:o.limit=ou.codec().decode(s,s.uint32());break;case 5:o.status=mr.codec().decode(s);break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>pe(s,r.codec()),r.decode=s=>de(s,r.codec())})(Pi||(Pi={}));var xs;(function(r){let e;(function(s){s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.CONNECT=0]="CONNECT",s[s.STATUS=1]="STATUS"})(t||(t={})),function(s){s.codec=()=>Pt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=me((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.type!=null&&(i.uint32(8),r.Type.codec().encode(s.type,i)),s.peer!=null&&(i.uint32(18),iu.codec().encode(s.peer,i)),s.limit!=null&&(i.uint32(26),ou.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(32),mr.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(s);break;case 2:o.peer=iu.codec().decode(s,s.uint32());break;case 3:o.limit=ou.codec().decode(s,s.uint32());break;case 4:o.status=mr.codec().decode(s);break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>pe(s,r.codec()),r.decode=s=>de(s,r.codec())})(xs||(xs={}));var iu;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let i of t.addrs)n.uint32(18),n.bytes(i);s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={id:new Uint8Array(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.id=t.bytes();break;case 2:s.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(iu||(iu={}));var p2;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let i of t.addrs)n.uint32(18),n.bytes(i);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.expire=t.uint64();break;case 2:s.addrs.push(t.bytes());break;case 3:s.voucher=t.bytes();break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(p2||(p2={}));var ou;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.duration=t.uint32();break;case 2:s.data=t.uint64();break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(ou||(ou={}));var mr;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(mr||(mr={}));var g7;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(g7||(g7={}));(function(r){r.codec=()=>Pt(g7)})(mr||(mr={}));var y7;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.relay=t.bytes();break;case 2:s.peer=t.bytes();break;case 3:s.expiration=t.uint64();break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(y7||(y7={}));var Nse=sL,rL=128,Ose=127,Lse=~Ose,Bse=Math.pow(2,31);function sL(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Bse;)e[t++]=r&255|rL,r/=128;for(;r&Lse;)e[t++]=r&255|rL,r>>>=7;return e[t]=r|0,sL.bytes=t-n+1,e}var Mse=b7,Use=128,nL=127;function b7(r,n){var t=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw b7.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=s<28?(o&nL)<<s:(o&nL)*Math.pow(2,s),s+=7}while(o>=Use);return b7.bytes=i-n,t}var Fse=Math.pow(2,7),Vse=Math.pow(2,14),zse=Math.pow(2,21),qse=Math.pow(2,28),Kse=Math.pow(2,35),$se=Math.pow(2,42),Hse=Math.pow(2,49),Gse=Math.pow(2,56),Wse=Math.pow(2,63),Yse=function(r){return r<Fse?1:r<Vse?2:r<zse?3:r<qse?4:r<Kse?5:r<$se?6:r<Hse?7:r<Gse?8:r<Wse?9:10},Qse={encode:Nse,decode:Mse,encodingLength:Yse},Xse=Qse,Hh=Xse;var Gh=(r,e=0)=>[Hh.decode(r,e),Hh.decode.bytes],au=(r,e,t=0)=>(Hh.encode(r,e,t),e),cu=r=>Hh.encodingLength(r);var SOe=new Uint8Array(0);var oL=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},lu=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var Wh=(r,e)=>{let t=e.byteLength,n=cu(r),s=n+cu(t),i=new Uint8Array(s+t);return au(r,i,0),au(t,i,n),i.set(e,s),new uu(r,t,e,i)},aL=r=>{let e=lu(r),[t,n]=Gh(e),[s,i]=Gh(e.subarray(n)),o=e.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new uu(t,s,o,e)},cL=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&oL(r.bytes,t.bytes)}},uu=class{constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function jse(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,y=0,b=d.length;y!==b&&d[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,v=new Uint8Array(w);y!==b;){for(var x=d[y],_=0,S=w-1;(x!==0||_<g)&&S!==-1;S--,_++)x+=256*v[S]>>>0,v[S]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");g=_,y++}for(var A=w-g;A!==w&&v[A]===0;)A++;for(var D=c.repeat(m);A<w;++A)D+=r.charAt(v[A]);return D}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var g=0,y=0;d[m]===c;)g++,m++;for(var b=(d.length-m)*l+1>>>0,w=new Uint8Array(b);d[m];){var v=t[d.charCodeAt(m)];if(v===255)return;for(var x=0,_=b-1;(v!==0||x<y)&&_!==-1;_--,x++)v+=a*w[_]>>>0,w[_]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");y=x,m++}if(d[m]!==" "){for(var S=b-y;S!==b&&w[S]===0;)S++;for(var A=new Uint8Array(g+(b-S)),D=g;S!==b;)A[D++]=w[S++];return A}}}function p(d){var m=h(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var Zse=jse,Jse=Zse,uL=Jse;var w7=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},x7=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return fL(this,e)}},E7=class{constructor(e){this.decoders=e}or(e){return fL(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},fL=(r,e)=>new E7({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),v7=class{constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new w7(e,t,n),this.decoder=new x7(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},hL=({name:r,prefix:e,encode:t,decode:n})=>new v7(r,e,t,n),_7=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:s}=uL(t,e);return hL({prefix:r,name:e,encode:n,decode:i=>lu(s(i))})},eie=(r,e,t,n)=>{let s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=s[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},tie=(r,e,t)=>{let n=e[e.length-1]==="=",s=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,i+=e[s&a>>o];if(o&&(i+=e[s&a<<t-o]),n)for(;i.length*t&7;)i+="=";return i},Zs=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>hL({prefix:e,name:r,encode(s){return tie(s,n,t)},decode(s){return eie(s,n,t,r)}});var ki=_7({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kOe=_7({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Yh=Zs({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),LOe=Zs({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),BOe=Zs({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),MOe=Zs({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),UOe=Zs({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),FOe=Zs({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),VOe=Zs({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zOe=Zs({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),qOe=Zs({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var dL=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return nie(t,S7(r),e||ki.encoder);default:return sie(t,S7(r),e||Yh.encoder)}};var pL=new WeakMap,S7=r=>{let e=pL.get(r);if(e==null){let t=new Map;return pL.set(r,t),t}return e},tr=class{constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Qh)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==iie)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return tr.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Wh(e,t);return tr.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return tr.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&cL(e.multihash,n.multihash)}toString(e){return dL(this,e)}toJSON(){return{"/":dL(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof tr)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:i,bytes:o}=t;return new tr(n,s,i,o||mL(n,s,i.bytes))}else if(t[oie]===!0){let{version:n,multihash:s,code:i}=t,o=aL(s);return tr.create(n,i,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Qh)throw new Error(`Version 0 CID must use dag-pb (code: ${Qh}) block encoding`);return new tr(e,t,n,n.bytes)}case 1:{let s=mL(e,t,n.bytes);return new tr(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return tr.create(0,Qh,e)}static createV1(e,t){return tr.create(1,e,t)}static decode(e){let[t,n]=tr.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=tr.inspectBytes(e),n=t.size-t.multihashSize,s=lu(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),o=new uu(t.multihashCode,t.digestSize,i,s);return[t.version===0?tr.createV0(o):tr.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=Gh(e.subarray(t));return t+=h,f},s=n(),i=Qh;if(s===18?(s=0,t=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,a=n(),c=n(),l=t+c,u=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=rie(e,t),i=tr.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return S7(i).set(n,e),i}},rie=(r,e)=>{switch(r[0]){case"Q":{let t=e||ki;return[ki.prefix,t.decode(`${ki.prefix}${r}`)]}case ki.prefix:{let t=e||ki;return[ki.prefix,t.decode(r)]}case Yh.prefix:{let t=e||Yh;return[Yh.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},nie=(r,e,t)=>{let{prefix:n}=t;if(n!==ki.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return s},sie=(r,e,t)=>{let{prefix:n}=t,s=e.get(n);if(s==null){let i=t.encode(r);return e.set(n,i),i}else return s},Qh=112,iie=18,mL=(r,e,t)=>{let n=cu(r),s=n+cu(e),i=new Uint8Array(s+t.byteLength);return au(r,i,0),au(e,i,n),i.set(t,s),i},oie=Symbol.for("@ipld/js-cid/CID");var R7=({name:r,code:e,encode:t})=>new A7(r,e,t),A7=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Wh(this.code,t):t.then(n=>Wh(this.code,n))}else throw Error("Unknown type, must be binary type")}};var gL=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),yL=R7({name:"sha2-256",code:18,encode:gL("SHA-256")}),jOe=R7({name:"sha2-512",code:19,encode:gL("SHA-512")});var iLe=C("libp2p:circuit-relay:utils");async function I7(r){let e=new TextEncoder().encode(r),t=await yL.digest(e);return tr.createV0(t)}function T7(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var lie=W(vL(),1);var bLe=C("libp2p:circuit-relay:advert-service");var YLe=C("libp2p:circuit-relay:server");var fie=C("libp2p:stream:converter");function D7(r,e={}){let{stream:t,remoteAddr:n}=r,{sink:s,source:i}=t,o=async function*(){for await(let l of i)l instanceof Uint8Array?yield l:yield*l}(),a={async sink(l){e.signal!=null&&(l=bt(l,e.signal));try{await s(l),await c()}catch(u){u.type!=="aborted"&&fie(u)}},source:e.signal!=null?bt(o,e.signal):o,remoteAddr:n,timeline:{open:Date.now(),close:void 0},async close(){await s(async function*(){yield new Uint8Array(0)}()),await c()}};async function c(){a.timeline.close==null&&(a.timeline.close=Date.now()),await Promise.resolve()}return a}var Vo=C("libp2p:circuit-relay:discover-relays"),m2=class extends $e{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.contentRouting=e.contentRouting,this.registrar=e.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Fo,Fi({onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}})),this.discover().catch(e=>{Vo.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){Vo("searching peer store for relays");let e=await this.peerStore.all({filters:[t=>t.protocols.includes(Fo)],orders:[()=>Math.random()<.5?1:-1]});for(let t of e)Vo("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});Vo("found %d relay peers in peer store",e.length);try{Vo("searching content routing for relays");let t=await I7(m7),n=0;for await(let s of this.contentRouting.findProviders(t))if(s.multiaddrs.length>0&&!s.id.equals(this.peerId)){let i=s.id;n++,await this.peerStore.merge(i,{multiaddrs:s.multiaddrs}),Vo("found relay peer %p in content routing",i),this.safeDispatchEvent("relay:discover",{detail:i})}Vo("found %d relay peers in content routing",n)}catch(t){Vo.error("failed when finding relays on the network",t)}}};var SL=C("libp2p:circuit-relay:transport:listener"),C7=class extends $e{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new Sr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){SL("listen on %s",e);let t=e.getPeerId(),n;if(t!=null){let i=he(t),o=this.connectionManager.getConnectionsMap().get(i)??[];o.length>0&&(n=o[0])}if(n==null){let i=e.toString().split("/p2p-circuit").find(a=>a!==""),o=fe(i);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let s=this.relayStore.getReservation(n.remotePeer);if(s==null)throw new E("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){SL("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,s.addrs.map(i=>fe(i).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function AL(r){return new C7(r)}var zr=C("libp2p:circuit-relay:transport:reservation-store"),die=60*1e3*10,pie=60*1e3*5,mie=30*1e3,g2=class extends $e{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;maxReservationQueueLength;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Sr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.started=!1,this.reserveQueue=new fl({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!0}async addRelay(e,t){if(this.peerId.equals(e)){zr("not trying to use self as relay");return}if(this.reserveQueue.size>this.maxReservationQueueLength){zr("not adding relay as the queue is full");return}if(this.reserveQueue.hasJob(e)){zr("relay peer is already in the reservation queue");return}zr("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(T7(n.reservation.expire)>die){zr("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((l,u)=>(u.type==="discovered"&&l++,l),0)>=this.maxDiscoveredRelays){zr("already have enough discovered relays");return}let s=await this.connectionManager.openConnection(e);if(s.remoteAddr.protoNames().includes("p2p-circuit")){zr("not creating reservation over relayed connection");return}let i=await this.#e(s);zr("created reservation on relay peer %p",e);let o=T7(i.expire),a=Math.min(Math.max(o-pie,mie),Math.pow(2,31)-1),c=setTimeout(()=>{this.addRelay(e,t).catch(l=>{zr.error("could not refresh reservation to relay %p",e,l)})},a);this.reservations.set(e,{timeout:c,reservation:i,type:t}),await this.peerStore.merge(e,{tags:{[eL]:{value:1,ttl:o}}}),await this.transportManager.listen([fe(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){zr.error("could not reserve slot on %p",e,n),this.reservations.delete(e)}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e){zr("requesting reservation from %s",e.remotePeer);let t=await e.newStream(Fo),s=jr(t).pb(Pi);s.write({type:Pi.Type.RESERVE});let i;try{i=await s.read()}catch(a){throw zr.error("error parsing reserve message response from %p because",e.remotePeer,a),a}finally{t.close()}if(i.status===mr.OK&&i.reservation!=null)return i.reservation;let o=`reservation failed with status ${i.status??"undefined"}`;throw zr.error(o),new Error(o)}#t(e){let t=this.reservations.get(e);t!=null&&(zr("connection to relay %p closed, removing reservation from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),this.safeDispatchEvent("relay:removed",{detail:e}),this.reservations.size<this.maxDiscoveredRelays&&(zr("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};var tn=C("libp2p:circuit-relay:transport"),gie=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(fe)}catch{return!1}return!0},RL={maxInboundStopStreams:300,maxOutboundStopStreams:300},P7=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,this.maxInboundStopStreams=t.maxInboundStopStreams??RL.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??RL.maxOutboundStopStreams,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new m2(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{tn.error("could not add discovered relay %p",n.detail,s)})})),this.reservationStore=new g2(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{tn.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(d2,e=>{this.onStop(e).catch(t=>{tn.error(t)})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(d2),this.started=!1}[qs]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(d=>d===290).length!==1){let d="Invalid circuit relay address";throw tn.error(d,e),new E(d,z.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),s=fe(n[0]),i=fe(n[n.length-1]),o=s.getPeerId(),a=i.getPeerId();if(o==null||a==null){let d=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw tn.error(d),new E(d,z.ERR_RELAYED_DIAL)}let c=he(o),l=he(a),u=!1,h=this.connectionManager.getConnections(c)[0];h==null&&(await this.peerStore.merge(c,{multiaddrs:[s]}),h=await this.connectionManager.openConnection(c,t),u=!0);let p;try{return p=await h.newStream([Fo]),await this.connectV2({stream:p,connection:h,destinationPeer:l,destinationAddr:i,relayAddr:s,ma:e,disconnectOnFailure:u})}catch(d){throw tn.error(`Circuit relay dial to destination ${l.toString()} via relay ${c.toString()} failed`,d),p?.abort(d),u&&await h.close(),d}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:s,relayAddr:i,ma:o,disconnectOnFailure:a}){try{let c=jr(e),l=c.pb(Pi);l.write({type:Pi.Type.CONNECT,peer:{id:n.toBytes(),addrs:[fe(s).bytes]}});let u=await l.read();if(u.status!==mr.OK)throw new E(`failed to connect via relay with status ${u?.status?.toString()??"undefined"}`,z.ERR_HOP_REQUEST_FAILED);let f=D7({stream:c.unwrap(),remoteAddr:o,localAddr:i.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return tn("new outbound connection %s",f.remoteAddr),await this.upgrader.upgradeOutbound(f)}catch(c){throw tn.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return AL({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>gs.matches(t))}async onStop({connection:e,stream:t}){let n=jr(t),s=await n.readPB(xs);if(tn("received circuit v2 stop protocol request from %s",e.remotePeer),s?.type===void 0)return;let i=n.pb(xs);if(tn("new circuit relay v2 stop stream from %s",e.remotePeer),s.type!==xs.Type.CONNECT){tn.error("invalid stop connect request via peer %s",e.remotePeer),i.write({type:xs.Type.STATUS,status:mr.UNEXPECTED_MESSAGE});return}if(!gie(s)){tn.error("invalid stop connect request via peer %s",e.remotePeer),i.write({type:xs.Type.STATUS,status:mr.MALFORMED_MESSAGE});return}let o=_t(s.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){i.write({type:xs.Type.STATUS,status:mr.PERMISSION_DENIED});return}i.write({type:xs.Type.STATUS,status:mr.OK});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],l=D7({stream:n.unwrap(),remoteAddr:a,localAddr:c});tn("new inbound connection %s",l.remoteAddr),await this.upgrader.upgradeInbound(l),tn("%s connection %s upgraded","inbound",l.remoteAddr)}};function k7(r={}){return e=>new P7(e,r)}var IL="0.45.9";var N7=`js-libp2p/${IL}`;var TL="0.1.0",DL="id",CL="id/push",PL="1.0.0",kL="1.0.0";var y2=W(fn(),1);var zo;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let i of t.listenAddrs)n.uint32(18),n.bytes(i);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let i of t.protocols)n.uint32(26),n.string(i);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={listenAddrs:[],protocols:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 5:s.protocolVersion=t.string();break;case 6:s.agentVersion=t.string();break;case 1:s.publicKey=t.bytes();break;case 2:s.listenAddrs.push(t.bytes());break;case 4:s.observedAddr=t.bytes();break;case 3:s.protocols.push(t.string());break;case 8:s.signedPeerRecord=t.bytes();break;default:t.skipType(o&7);break}}return s})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(zo||(zo={}));var qr=C("libp2p:identify"),NL=1024*8,Es={protocolPrefix:"ipfs",agentVersion:N7,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192},b2=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??Es.protocolPrefix}/${DL}/${PL}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??Es.protocolPrefix}/${CL}/${kL}`,this.timeout=t.timeout??Es.timeout,this.maxInboundStreams=t.maxInboundStreams??Es.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??Es.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??Es.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??Es.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??Es.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??Es.maxObservedAddresses,this.host={protocolVersion:`${t.protocolPrefix??Es.protocolPrefix}/${TL}`,agentVersion:t.agentVersion??Es.agentVersion},e.events.addEventListener("connection:open",n=>{let s=n.detail;this.identify(s).catch(i=>{qr.error("error during identify trigged by connection:open",i)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(s=>{qr.error(s)})}),this.host.agentVersion===N7&&(nO||tO?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(l2||u2||rO||sO)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:$(this.host.agentVersion),ProtocolVersion:$(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{qr.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{qr.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(u=>u.decapsulateCode(se("p2p").code)),n=new Rr({peerId:this.peerId,multiaddrs:t}),s=await Lr.seal(n,this.peerId),i=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=M(o.metadata.get("AgentVersion")??$(this.host.agentVersion)),c=M(o.metadata.get("ProtocolVersion")??$(this.host.protocolVersion)),l=e.map(async u=>{let f,h=AbortSignal.timeout(this.timeout);try{(0,y2.setMaxListeners)?.(1/0,h)}catch{}try{f=await u.newStream([this.identifyPushProtocolStr],{signal:h}),await Er(f,h).sink(Re([zo.encode({listenAddrs:t.map(d=>d.bytes),signedPeerRecord:s.marshal(),protocols:i,agentVersion:a,protocolVersion:c})],d=>wt(d)))}catch(p){qr.error("could not push identify update to peer",p)}finally{f?.close()}});await Promise.all(l)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==z.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n,s=ot([AbortSignal.timeout(this.timeout),t?.signal]);try{(0,y2.setMaxListeners)?.(1/0,s)}catch{}try{n=await e.newStream([this.identifyProtocolStr],{signal:s});let i=Er(n,s),o=await Re([],i,a=>kt(a,{maxDataLength:this.maxIdentifyMessageSize??NL}),async a=>fs(a));if(o==null)throw new E("No data could be retrieved",z.ERR_CONNECTION_ENDED);try{return zo.decode(o)}catch(a){throw new E(String(a),z.ERR_INVALID_MESSAGE)}}finally{n?.close(),s.clear()}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:s,protocols:i,observedAddr:o}=n;if(s==null)throw new E("public key was missing from identify message",z.ERR_MISSING_PUBLIC_KEY);let a=await _r(s);if(!e.remotePeer.equals(a))throw new E("identified peer does not match the expected peer",z.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new E("identified peer is our own peer id?",z.ERR_INVALID_PEER);let c=yie(o);qr("identify completed for peer %p and protocols %o",a,i),qr("our observed address is %s",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(qr("storing our observed address %s",c?.toString()),this.addressManager.addObservedAddr(c));let l=await this.#e(e.remotePeer,n),u={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(f=>fe(f)),observedAddr:n.observedAddr==null?void 0:fe(n.observedAddr),protocols:n.protocols,signedPeerRecord:l};this.events.safeDispatchEvent("peer:identify",{detail:u})}async _handleIdentify(e){let{connection:t,stream:n}=e,s=AbortSignal.timeout(this.timeout);try{(0,y2.setMaxListeners)?.(1/0,s)}catch{}try{let i=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(h=>h.decapsulateCode(se("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let h=new Rr({peerId:this.peerId,multiaddrs:a});c=(await Lr.seal(h,this.peerId)).marshal().subarray()}let l=zo.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:i,listenAddrs:a.map(h=>h.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols}),u=Er(n,s),f=Re([l],h=>wt(h));await u.sink(f)}catch(i){qr.error("could not respond to identify request",i)}finally{n.close()}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let s=Er(n,AbortSignal.timeout(this.timeout)),o=await jr(s,{maxDataLength:this.maxIdentifyMessageSize??NL}).readPB(zo);await this.#e(t.remotePeer,o)}catch(s){qr.error("received invalid message",s);return}finally{n.close()}qr("handled push from %p",t.remotePeer)}async#e(e,t){if(qr("received identify from %p",e),t==null)throw new Error("Message was null or undefined");let n={addresses:t.listenAddrs.map(i=>({isCertified:!1,multiaddr:fe(i)})),protocols:t.protocols,metadata:new Map,peerRecordEnvelope:t.signedPeerRecord},s;if(t.signedPeerRecord!=null){qr("received signedPeerRecord in push from %p",e);let i=t.signedPeerRecord,o=await Lr.openAndCertify(i,Rr.DOMAIN),a=Rr.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(a.peerId))throw new Error("signing key does not match remote PeerId");let c;try{c=await this.peerStore.get(a.peerId)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}if(c!=null&&(n.metadata=c.metadata,c.peerRecordEnvelope!=null)){let l=await Lr.createFromProtobuf(c.peerRecordEnvelope),u=Rr.createFromProtobuf(l.payload);u.seqNumber>=a.seqNumber&&(qr("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,a.seqNumber),a=u,i=c.peerRecordEnvelope)}n.peerRecordEnvelope=i,n.addresses=a.multiaddrs.map(l=>({isCertified:!0,multiaddr:l})),s={seq:a.seqNumber,addresses:a.multiaddrs}}else qr("%p did not send a signed peer record",e);return t.agentVersion!=null&&n.metadata.set("AgentVersion",$(t.agentVersion)),t.protocolVersion!=null&&n.metadata.set("ProtocolVersion",$(t.protocolVersion)),await this.peerStore.patch(e,n),s}};function yie(r){if(r!=null&&r.length>0)try{return fe(r)}catch{}}function OL(r={}){return e=>new b2(e,r)}var LL={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function BL(){return{addresses:{listen:["/webrtc"]},transports:[TN(),IN(),LO(),pO(),k7({discoverRelays:1})],connectionEncryption:[Il()],streamMuxers:[ZD(),dP()],peerDiscovery:[uC(LL)],contentRouters:[yC("https://cid.contact")],services:{identify:OL(),autoNAT:JO(),pubsub:zT(),dht:rP({clientMode:!0,validators:{ipns:QO},selectors:{ipns:YO}})}}}async function ML(r,e){let t=BL();return e=e??{},RI({datastore:r,...t,...e,start:!1})}var O7="1.3.11",w2="helia";var bie=C("helia");async function wie(r={}){let e=r.datastore??new Wo,t=r.blockstore??new yu,n;xie(r.libp2p)?n=r.libp2p:n=await ML(e,r.libp2p);let s=new id({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await s.start(),s.libp2p.isStarted()?await UL(s):s.libp2p.addEventListener("start",()=>{UL(s).catch(i=>{bie.error("could not add Helia to agent version",i)})}),s}function xie(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}async function UL(r){let t=(await r.libp2p.peerStore.get(r.libp2p.peerId)).metadata.get("AgentVersion");if(t==null)return;let n=new TextDecoder().decode(t);n.match(/js-libp2p\/\d+\.\d+\.\d+\sUserAgent=/)!=null&&(n.includes(w2)?n=`${w2}/${O7} ${n.split(" ").slice(1).join(" ")}`:n=`${w2}/${O7} ${n}`,await r.libp2p.peerStore.merge(r.libp2p.peerId,{metadata:{AgentVersion:new TextEncoder().encode(n)}}))}return Zh(Eie);})();
85
85
  /*! Bundled license information:
86
86
 
87
87
  @noble/ed25519/lib/esm/index.js:
@@ -1,3 +1,3 @@
1
- export declare const version = "1.3.10";
1
+ export declare const version = "1.3.11";
2
2
  export declare const name = "helia";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1,3 +1,3 @@
1
- export const version = '1.3.10';
1
+ export const version = '1.3.11';
2
2
  export const name = 'helia';
3
3
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "helia",
3
- "version": "1.3.10",
3
+ "version": "1.3.11",
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/master/packages/helia#readme",
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '1.3.10'
1
+ export const version = '1.3.11'
2
2
  export const name = 'helia'