@libp2p/tcp
Advanced tools
Comparing version
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PTcp = factory()}(typeof self !== 'undefined' ? self : this, function () { | ||
"use strict";var Libp2PTcp=(()=>{var Rr=Object.create;var xe=Object.defineProperty;var jr=Object.getOwnPropertyDescriptor;var qr=Object.getOwnPropertyNames;var Wr=Object.getPrototypeOf,Gr=Object.prototype.hasOwnProperty;var F=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var D=(r,e)=>{for(var t in e)xe(r,t,{get:e[t],enumerable:!0})},Vt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of qr(e))!Gr.call(r,o)&&o!==t&&xe(r,o,{get:()=>e[o],enumerable:!(n=jr(e,o))||n.enumerable});return r};var le=(r,e,t)=>(t=r!=null?Rr(Wr(r)):{},Vt(e||!r||!r.__esModule?xe(t,"default",{value:r,enumerable:!0}):t,r)),Hr=r=>Vt(xe({},"__esModule",{value:!0}),r);var Qo={};D(Qo,{tcp:()=>Jo});var _r=le(F("net"),1);var Bt=Symbol.for("@libp2p/transport");var zt;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(zt||(zt={}));var ge=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var V=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Z=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},we=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},be=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}};var _t=F("node:events"),ve=(r,...e)=>{try{(0,_t.setMaxListeners)(r,...e)}catch{}};var ye=class extends EventTarget{#e=new Map;constructor(){super(),ve(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Rt=Symbol.for("@libp2p/service-capabilities"),rs=Symbol.for("@libp2p/service-dependencies");var jt=F("node:buffer");function ee(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function Ee(r=0){return ee(jt.Buffer.allocUnsafe(r))}var Jr=Math.pow(2,7),Qr=Math.pow(2,14),Xr=Math.pow(2,21),Be=Math.pow(2,28),_e=Math.pow(2,35),Re=Math.pow(2,42),je=Math.pow(2,49),g=128,C=127;function z(r){if(r<Jr)return 1;if(r<Qr)return 2;if(r<Xr)return 3;if(r<Be)return 4;if(r<_e)return 5;if(r<Re)return 6;if(r<je)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Kr(r,e,t=0){switch(z(r)){case 8:e[t++]=r&255|g,r/=128;case 7:e[t++]=r&255|g,r/=128;case 6:e[t++]=r&255|g,r/=128;case 5:e[t++]=r&255|g,r/=128;case 4:e[t++]=r&255|g,r>>>=7;case 3:e[t++]=r&255|g,r>>>=7;case 2:e[t++]=r&255|g,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Yr(r,e,t=0){switch(z(r)){case 8:e.set(t++,r&255|g),r/=128;case 7:e.set(t++,r&255|g),r/=128;case 6:e.set(t++,r&255|g),r/=128;case 5:e.set(t++,r&255|g),r/=128;case 4:e.set(t++,r&255|g),r>>>=7;case 3:e.set(t++,r&255|g),r>>>=7;case 2:e.set(t++,r&255|g),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Zr(r,e){let t=r[e],n=0;if(n+=t&C,t<g||(t=r[e+1],n+=(t&C)<<7,t<g)||(t=r[e+2],n+=(t&C)<<14,t<g)||(t=r[e+3],n+=(t&C)<<21,t<g)||(t=r[e+4],n+=(t&C)*Be,t<g)||(t=r[e+5],n+=(t&C)*_e,t<g)||(t=r[e+6],n+=(t&C)*Re,t<g)||(t=r[e+7],n+=(t&C)*je,t<g))return n;throw new RangeError("Could not decode varint")}function en(r,e){let t=r.get(e),n=0;if(n+=t&C,t<g||(t=r.get(e+1),n+=(t&C)<<7,t<g)||(t=r.get(e+2),n+=(t&C)<<14,t<g)||(t=r.get(e+3),n+=(t&C)<<21,t<g)||(t=r.get(e+4),n+=(t&C)*Be,t<g)||(t=r.get(e+5),n+=(t&C)*_e,t<g)||(t=r.get(e+6),n+=(t&C)*Re,t<g)||(t=r.get(e+7),n+=(t&C)*je,t<g))return n;throw new RangeError("Could not decode varint")}function te(r,e,t=0){return e==null&&(e=Ee(z(r))),e instanceof Uint8Array?Kr(r,e,t):Yr(r,e,t)}function J(r,e=0){return r instanceof Uint8Array?Zr(r,e):en(r,e)}var Wt=F("node:buffer");function _(r,e){return ee(Wt.Buffer.concat(r,e))}var dr=F("node:buffer");var Je={};D(Je,{base10:()=>cn});var Ms=new Uint8Array(0);function Gt(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}function k(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")}function Ht(r){return new TextEncoder().encode(r)}function Jt(r){return new TextDecoder().decode(r)}function tn(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,d=r.charAt(0),m=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var I=0,T=0,x=0,w=f.length;x!==w&&f[x]===0;)x++,I++;for(var L=(w-x)*p+1>>>0,M=new Uint8Array(L);x!==w;){for(var O=f[x],j=0,N=L-1;(O!==0||j<T)&&N!==-1;N--,j++)O+=256*M[N]>>>0,M[N]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");T=j,x++}for(var B=L-T;B!==L&&M[B]===0;)B++;for(var me=d.repeat(I);B<L;++B)me+=r.charAt(M[B]);return me}function b(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var I=0;if(f[I]!==" "){for(var T=0,x=0;f[I]===d;)T++,I++;for(var w=(f.length-I)*m+1>>>0,L=new Uint8Array(w);f[I];){var M=t[f.charCodeAt(I)];if(M===255)return;for(var O=0,j=w-1;(M!==0||O<x)&&j!==-1;j--,O++)M+=a*L[j]>>>0,L[j]=M%256>>>0,M=M/256>>>0;if(M!==0)throw new Error("Non-zero carry");x=O,I++}if(f[I]!==" "){for(var N=w-x;N!==w&&L[N]===0;)N++;for(var B=new Uint8Array(T+(w-N)),me=T;N!==w;)B[me++]=L[N++];return B}}}function l(f){var I=b(f);if(I)return I;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:b,decode:l}}var rn=tn,nn=rn,Xt=nn;var qe=class{name;prefix;baseEncode;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")}},We=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Kt(this,e)}},Ge=class{decoders;constructor(e){this.decoders=e}or(e){return Kt(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Kt(r,e){return new Ge({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var He=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new qe(e,t,n),this.decoder=new We(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function re({name:r,prefix:e,encode:t,decode:n}){return new He(r,e,t,n)}function q({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Xt(t,r);return re({prefix:e,name:r,encode:n,decode:s=>k(o(s))})}function on(r,e,t,n){let o={};for(let p=0;p<e.length;++p)o[e[p]]=p;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,d=0,m=0;for(let p=0;p<s;++p){let h=o[r[p]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);d=d<<t|h,a+=t,a>=8&&(a-=8,i[m++]=255&d>>a)}if(a>=t||(255&d<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function sn(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let d=0;d<r.length;++d)for(a=a<<8|r[d],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function y({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return re({prefix:e,name:r,encode(o){return sn(o,n,t)},decode(o){return on(o,n,t,r)}})}var cn=q({prefix:"9",name:"base10",alphabet:"0123456789"});var Qe={};D(Qe,{base16:()=>an,base16upper:()=>ln});var an=y({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ln=y({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xe={};D(Xe,{base2:()=>un});var un=y({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ke={};D(Ke,{base256emoji:()=>mn});var Yt=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}"),dn=Yt.reduce((r,e,t)=>(r[t]=e,r),[]),pn=Yt.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function fn(r){return r.reduce((e,t)=>(e+=dn[t],e),"")}function hn(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=pn[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var mn=re({prefix:"\u{1F680}",name:"base256emoji",encode:fn,decode:hn});var Ye={};D(Ye,{base32:()=>R,base32hex:()=>bn,base32hexpad:()=>yn,base32hexpadupper:()=>En,base32hexupper:()=>vn,base32pad:()=>gn,base32padupper:()=>wn,base32upper:()=>xn,base32z:()=>In});var R=y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xn=y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gn=y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),wn=y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),bn=y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vn=y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yn=y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),En=y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),In=y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ze={};D(Ze,{base36:()=>ue,base36upper:()=>An});var ue=q({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),An=q({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var et={};D(et,{base58btc:()=>P,base58flickr:()=>Cn});var P=q({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Cn=q({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var tt={};D(tt,{base64:()=>Tn,base64pad:()=>Sn,base64url:()=>Pn,base64urlpad:()=>Ln});var Tn=y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sn=y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Pn=y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ln=y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var rt={};D(rt,{base8:()=>Dn});var Dn=y({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var nt={};D(nt,{identity:()=>Mn});var Mn=re({prefix:"\0",name:"identity",encode:r=>Jt(r),decode:r=>Ht(r)});var Hs=new TextEncoder,Js=new TextDecoder;var st={};D(st,{identity:()=>eo});var Nn=tr,Zt=128,Fn=127,$n=~Fn,On=Math.pow(2,31);function tr(r,e,t){e=e||[],t=t||0;for(var n=t;r>=On;)e[t++]=r&255|Zt,r/=128;for(;r&$n;)e[t++]=r&255|Zt,r>>>=7;return e[t]=r|0,tr.bytes=t-n+1,e}var Vn=ot,zn=128,er=127;function ot(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ot.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&er)<<o:(i&er)*Math.pow(2,o),o+=7}while(i>=zn);return ot.bytes=s-n,t}var Bn=Math.pow(2,7),_n=Math.pow(2,14),Rn=Math.pow(2,21),jn=Math.pow(2,28),qn=Math.pow(2,35),Wn=Math.pow(2,42),Gn=Math.pow(2,49),Hn=Math.pow(2,56),Jn=Math.pow(2,63),Qn=function(r){return r<Bn?1:r<_n?2:r<Rn?3:r<jn?4:r<qn?5:r<Wn?6:r<Gn?7:r<Hn?8:r<Jn?9:10},Xn={encode:Nn,decode:Vn,encodingLength:Qn},Kn=Xn,de=Kn;function pe(r,e=0){return[de.decode(r,e),de.decode.bytes]}function ne(r,e,t=0){return de.encode(r,e,t),e}function oe(r){return de.encodingLength(r)}function Q(r,e){let t=e.byteLength,n=oe(r),o=n+oe(t),s=new Uint8Array(o+t);return ne(r,s,0),ne(t,s,n),s.set(e,o),new se(r,t,e,s)}function Ae(r){let e=k(r),[t,n]=pe(e),[o,s]=pe(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new se(t,o,i,e)}function rr(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Gt(r.bytes,t.bytes)}}var se=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var nr=0,Yn="identity",or=k;function Zn(r){return Q(nr,or(r))}var eo={code:nr,name:Yn,encode:or,digest:Zn};var lt={};D(lt,{sha256:()=>to,sha512:()=>ro});var at=le(F("crypto"),1);function ct({name:r,code:e,encode:t}){return new it(r,e,t)}var it=class{name;code;encode;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?Q(this.code,t):t.then(n=>Q(this.code,n))}else throw Error("Unknown type, must be binary type")}};var to=ct({name:"sha2-256",code:18,encode:r=>k(at.default.createHash("sha256").update(r).digest())}),ro=ct({name:"sha2-512",code:19,encode:r=>k(at.default.createHash("sha512").update(r).digest())});function ir(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return oo(t,ut(r),e??P.encoder);default:return so(t,ut(r),e??R.encoder)}}var cr=new WeakMap;function ut(r){let e=cr.get(r);if(e==null){let t=new Map;return cr.set(r,t),t}return e}var W=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}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!==fe)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==io)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.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=Q(e,t);return r.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 r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&rr(e.multihash,n.multihash)}toString(e){return ir(this,e)}toJSON(){return{"/":ir(this)}}link(){return this}[Symbol.toStringTag]="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 r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??ar(n,o,s.bytes))}else if(t[co]===!0){let{version:n,multihash:o,code:s}=t,i=Ae(o);return r.create(n,s,i)}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!==fe)throw new Error(`Version 0 CID must use dag-pb (code: ${fe}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ar(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,fe,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=k(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new se(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,b]=pe(e.subarray(t));return t+=b,h},o=n(),s=fe;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),d=n(),m=t+d,p=m-i;return{version:o,codec:s,multihashCode:a,digestSize:d,multihashSize:p,size:m}}static parse(e,t){let[n,o]=no(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ut(s).set(n,e),s}};function no(r,e){switch(r[0]){case"Q":{let t=e??P;return[P.prefix,t.decode(`${P.prefix}${r}`)]}case P.prefix:{let t=e??P;return[P.prefix,t.decode(r)]}case R.prefix:{let t=e??R;return[R.prefix,t.decode(r)]}case ue.prefix:{let t=e??ue;return[ue.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function oo(r,e,t){let{prefix:n}=t;if(n!==P.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function so(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var fe=112,io=18;function ar(r,e,t){let n=oe(r),o=n+oe(e),s=new Uint8Array(o+t.byteLength);return ne(r,s,0),ne(e,s,n),s.set(t,o),s}var co=Symbol.for("@ipld/js-cid/CID");var he={...nt,...Xe,...rt,...Je,...Qe,...Ye,...Ze,...et,...tt,...Ke},gi={...lt,...st};function ur(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var lr=ur("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),dt=ur("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ee(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ao={utf8:lr,"utf-8":lr,hex:he.base16,latin1:dt,ascii:dt,binary:dt,...he},Ce=ao;function S(r,e="utf8"){let t=Ce[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?dr.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var Te=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let d=a==="0",m=2**(8*o)-1;for(;;){let p=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let b=Number.parseInt(h,e);if(!Number.isNaN(b))return b});if(p===void 0)break;if(s*=e,s+=p,s>m||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&d&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ti=new Te;var Ni=parseInt("0xFFFF",16),Fi=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var hr=F("node:buffer");function Se(r,e="utf8"){let t=Ce[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?ee(hr.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var U=F("node:net");function Pe(r){return!!(0,U.isIP)(r)}var mr=U.isIPv4,mo=U.isIPv6,pt=function(r){let e=0;if(r=r.toString().trim(),mr(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(mo(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=mr(t[n]),i;s&&(i=pt(t[n]),t[n]=S(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,S(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},xr=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var ce={},ft={},go=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];go.forEach(r=>{let e=wo(...r);ft[e.code]=e,ce[e.name]=e});function wo(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function v(r){if(typeof r=="number"){if(ft[r]!=null)return ft[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(ce[r]!=null)return ce[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Ec=v("ip4"),Ic=v("ip6"),Ac=v("ipcidr");function gt(r,e){switch(v(r).code){case 4:case 41:return vo(e);case 42:return xt(e);case 43:return S(e,"base10");case 6:case 273:case 33:case 132:return br(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return xt(e);case 421:return Ao(e);case 444:return wr(e);case 445:return wr(e);case 466:return Io(e);case 481:return globalThis.encodeURIComponent(xt(e));default:return S(e,"base16")}}function wt(r,e){switch(v(r).code){case 4:return gr(e);case 41:return gr(e);case 42:return mt(e);case 43:return Se(e,"base10");case 6:case 273:case 33:case 132:return bt(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return mt(e);case 421:return yo(e);case 444:return Co(e);case 445:return To(e);case 466:return Eo(e);case 481:return mt(globalThis.decodeURIComponent(e));default:return Se(e,"base16")}}var ht=Object.values(he).map(r=>r.decoder),bo=function(){let r=ht[0].or(ht[1]);return ht.slice(2).forEach(e=>r=r.or(e)),r}();function gr(r){if(!Pe(r))throw new Error("invalid ip address");return pt(r)}function vo(r){let e=xr(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Pe(e))throw new Error("invalid ip address");return e}function bt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function br(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function mt(r){let e=Se(r),t=Uint8Array.from(te(e.length));return _([t,e],t.length+e.length)}function xt(r){let e=J(r);if(r=r.slice(z(e)),r.length!==e)throw new Error("inconsistent lengths");return S(r)}function yo(r){let e;r[0]==="Q"||r[0]==="1"?e=Ae(P.decode(`z${r}`)).bytes:e=W.parse(r).multihash.bytes;let t=Uint8Array.from(te(e.length));return _([t,e],t.length+e.length)}function Eo(r){let e=bo.decode(r),t=Uint8Array.from(te(e.length));return _([t,e],t.length+e.length)}function Io(r){let e=J(r),t=r.slice(z(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+S(t,"base64url")}function Ao(r){let e=J(r),t=r.slice(z(e));if(t.length!==e)throw new Error("inconsistent lengths");return S(t,"base58btc")}function Co(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=R.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=bt(n);return _([t,o],t.length+o.length)}function To(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=R.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=bt(n);return _([t,o],t.length+o.length)}function wr(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=S(e,"base32"),o=br(t);return`${n}:${o}`}function vr(r){r=vt(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=v(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw new Le("invalid address: "+r);if(a.path===!0){n=vt(o.slice(s).join("/")),e.push([a.code,wt(a.code,n)]),t.push([a.code,n]);break}let d=wt(a.code,o[s]);e.push([a.code,d]),t.push([a.code,gt(a.code,d)])}return{string:yr(t),bytes:De(e),tuples:e,stringTuples:t,path:n}}function yt(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=J(r,o),i=z(s),a=v(s),d=So(a,r.slice(o+i));if(d===0){e.push([s]),t.push([s]),o+=i;continue}let m=r.slice(o+i,o+i+d);if(o+=d+i,o>r.length)throw new Le("Invalid address Uint8Array: "+S(r,"base16"));e.push([s,m]);let p=gt(s,m);if(t.push([s,p]),a.path===!0){n=p;break}}return{bytes:Uint8Array.from(r),string:yr(t),tuples:e,stringTuples:t,path:n}}function yr(r){let e=[];return r.map(t=>{let n=v(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),vt(e.join("/"))}function De(r){return _(r.map(e=>{let t=v(e[0]),n=Uint8Array.from(te(t.code));return e.length>1&&e[1]!=null&&(n=_([n,e[1]])),n}))}function So(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=J(e instanceof Uint8Array?e:Uint8Array.from(e));return t+z(t)}}function vt(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}var Le=class extends Error{static name="ParseError";name="ParseError";constructor(e){super(`Error parsing address: ${e}`)}};function Er(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}var Po=Symbol.for("nodejs.util.inspect.custom"),It=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Lo=[v("dns").code,v("dns4").code,v("dns6").code,v("dnsaddr").code],Et=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},Me=class r{bytes;#e;#t;#r;#n;[It]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=yt(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=vr(e)}else if(Ar(e))t=yt(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#n=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=v("tcp"),a=v("udp"),d=v("ip4"),m=v("ip6"),p=v("dns6"),h=v("ip6zone");for(let[l,f]of this.stringTuples())l===h.code&&(s=`%${f??""}`),Lo.includes(l)&&(t=i.name==="tcp"?"tcp":"udp",o=443,n=`${f??""}${s}`,e=l===p.code?6:4),(l===i.code||l===a.code)&&(t=v(l).name==="tcp"?"tcp":"udp",o=parseInt(f??"")),(l===d.code||l===m.code)&&(t=v(l).name==="tcp"?"tcp":"udp",n=`${f??""}${s}`,e=l===m.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},v(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>v(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#r.map(([e,t])=>t==null?[e]:[e,t])}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(De(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===ce.p2p.code&&e.push([n,o]),n===ce["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?S(P.decode(`z${n}`),"base58btc"):S(W.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return Er(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Ir.get(t.name);if(n==null)throw new Et(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>$(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[Po](){return`Multiaddr(${this.#e})`}};var Ir=new Map;function Ar(r){return!!r?.[It]}function $(r){return new Me(r)}var Do=c("dns4"),Mo=c("dns6"),ko=c("dnsaddr"),K=E(c("dns"),ko,Do,Mo),Ne=E(c("ip4"),c("ip6")),H=E(u(Ne,c("tcp")),u(K,c("tcp"))),Fe=u(Ne,c("udp")),Uo=u(Fe,c("utp")),No=u(Fe,c("quic")),Fo=u(Fe,c("quic-v1")),At=E(u(H,c("ws")),u(K,c("ws"))),ke=E(u(At,c("p2p")),At),Ct=E(u(H,c("wss")),u(K,c("wss")),u(H,c("tls"),c("ws")),u(K,c("tls"),c("ws"))),Ue=E(u(Ct,c("p2p")),Ct),Tt=E(u(H,c("http")),u(Ne,c("http")),u(K,c("http"))),St=E(u(H,c("https")),u(Ne,c("https")),u(K,c("https"))),Cr=u(Fe,c("webrtc-direct"),c("certhash")),Pr=E(u(Cr,c("p2p")),Cr),Tr=u(Fo,c("webtransport"),c("certhash"),c("certhash")),Lr=E(u(Tr,c("p2p")),Tr),Dr=E(u(ke,c("p2p-webrtc-star"),c("p2p")),u(Ue,c("p2p-webrtc-star"),c("p2p")),u(ke,c("p2p-webrtc-star")),u(Ue,c("p2p-webrtc-star"))),Yc=E(u(ke,c("p2p-websocket-star"),c("p2p")),u(Ue,c("p2p-websocket-star"),c("p2p")),u(ke,c("p2p-websocket-star")),u(Ue,c("p2p-websocket-star"))),Mr=E(u(Tt,c("p2p-webrtc-direct"),c("p2p")),u(St,c("p2p-webrtc-direct"),c("p2p")),u(Tt,c("p2p-webrtc-direct")),u(St,c("p2p-webrtc-direct"))),Y=E(At,Ct,Tt,St,Dr,Mr,H,Uo,No,K,Pr,Lr),Zc=E(u(Y,c("p2p-stardust"),c("p2p")),u(Y,c("p2p-stardust"))),G=E(u(Y,c("p2p")),Dr,Mr,Pr,Lr,c("p2p")),Sr=E(u(G,c("p2p-circuit"),G),u(G,c("p2p-circuit")),u(c("p2p-circuit"),G),u(Y,c("p2p-circuit")),u(c("p2p-circuit"),Y),c("p2p-circuit")),kr=()=>E(u(Sr,kr),Sr),X=kr(),ea=E(u(X,G,X),u(G,X),u(X,G),X,G);var ta=E(u(X,c("webrtc"),c("p2p")),u(X,c("webrtc")),u(Y,c("webrtc"),c("p2p")),u(Y,c("webrtc")),c("webrtc"));function Ur(r){function e(t){let n;try{n=$(t)}catch{return!1}let o=r(n.protoNames());return o===null?!1:o===!0||o===!1?o:o.length===0}return e}function u(...r){function e(t){if(t.length<r.length)return null;let n=t;return r.some(o=>(n=typeof o=="function"?o().partialMatch(t):o.partialMatch(t),Array.isArray(n)&&(t=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Ur(e),partialMatch:e}}function E(...r){function e(n){let o=null;return r.some(s=>{let i=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return i!=null?(o=i,!0):!1}),o}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Ur(e),partialMatch:e}}function c(r){let e=r;function t(o){let s;try{s=$(o)}catch{return!1}let i=s.protoNames();return i.length===1&&i[0]===e}function n(o){return o.length===0?null:o[0]===e?o.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:n}}var $e=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Br=le(F("net"),1);var Pt=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Lt=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Nr=r=>globalThis.DOMException===void 0?new Lt(r):new DOMException(r),Fr=r=>{let e=r.reason===void 0?Nr("This operation was aborted."):r.reason;return e instanceof Error?e:Nr(e)};function Dt(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,m=new Promise((p,h)=>{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:l}=e;l.aborted&&h(Fr(l)),a=()=>{h(Fr(l))},l.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(p,h);return}let b=new Pt;i=s.setTimeout.call(void 0,()=>{if(n){try{p(n())}catch(l){h(l)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?p():o instanceof Error?h(o):(b.message=o??`Promise timed out after ${t} milliseconds`,h(b))},t),(async()=>{try{p(await r)}catch(l){h(l)}})()}).finally(()=>{m.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return m.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},m}var Oo=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Vo(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),d=[],{addListener:m,removeListener:p}=Oo(r),h=(...l)=>{let f=t.multiArgs?l:l[0];t.filter&&!t.filter(f)||(d.push(f),t.count===d.length&&(n(),s(d)))},b=l=>{n(),i(l)};n=()=>{for(let l of a)p(l,h);for(let l of t.rejectionEvents)p(l,b)};for(let l of a)m(l,h);for(let l of t.rejectionEvents)m(l,b);t.signal&&t.signal.addEventListener("abort",()=>{b(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(d)});if(o.cancel=n,typeof t.timeout=="number"){let s=Dt(o,{milliseconds:t.timeout});return s.cancel=n,s}return o}function Mt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Vo(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function $r(r,e){if(typeof r!="string")throw new V(`invalid ip provided: ${r}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new V(`invalid port provided: ${e}`);if((0,U.isIPv4)(r))return $(`/ip4/${r}/tcp/${e}`);if((0,U.isIPv6)(r))return $(`/ip6/${r}/tcp/${e}`);throw new V(`invalid ip:port for creating a multiaddr: ${r}:${e}`)}function kt(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ut=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Nt(r,e,t,n){let o=new Ut(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",p),r.removeEventListener(e,d),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,m)}let d=h=>{try{if(n?.filter?.(h)===!1)return}catch(b){a(),i(b);return}a(),s(h)},m=h=>{a(),i(h.detail)},p=()=>{a(),i(o)};t?.addEventListener("abort",p),r.addEventListener(e,d),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,m)})}function Or(r){if(Bo(r))return async function*(){let e=r.getReader();try{for(;;){let{done:t,value:n}=await e.read();if(t)return;yield n}}finally{e.releaseLock()}}();if(zo(r))return r;throw new Error("unknown stream")}function zo(r){return r[Symbol.asyncIterator]!=null}function Bo(r){return typeof r?.getReader=="function"}function Vr(r){return async e=>{let t=async()=>{_o(e)&&await e.return(void 0)},n,o,s=x=>{n=x,t().catch(w=>{w=new AggregateError([n,w],"The Writable emitted an error, additionally an error occurred while ending the Source")}).finally(()=>{o?.(x)})},i,a=!1,d=()=>{a=!0,i?.()},m,p=!1,h=()=>{p=!0,m?.()},b,l=()=>{b?.()},f=async()=>new Promise((x,w)=>{i=b=x,o=w,r.once("drain",l)}),I=async()=>(await t(),new Promise((x,w)=>{if(a||p||n!=null){x();return}m=i=x,o=w})),T=()=>{r.removeListener("error",s),r.removeListener("close",d),r.removeListener("finish",h),r.removeListener("drain",l)};r.once("error",s),r.once("close",d),r.once("finish",h);try{for await(let x of e){if(!r.writable||r.destroyed||n!=null)break;r.write(x)||await f()}}catch(x){n==null&&r.destroy(x),n=x}try{if(r.writable&&r.end(),await I(),n!=null)throw n}finally{T()}}}function _o(r){return r.return!=null}function Ft(r){return{sink:Vr(r),source:Or(r)}}var $t=le(F("os"),1),zr=le(F("path"),1);var Ro={ip4:"IPv4",ip6:"IPv6"};function ae(r,e={}){let t=r.getPath();if(t!=null)return $t.default.platform()==="win32"?{path:zr.default.join("\\\\.\\pipe\\",t)}:{path:t};let n=r.toOptions();return{...e,...n,ipv6Only:n.family===6}}function Ot(r,e,t){let n=o=>$(`/${r}/${o}/tcp/${t}`);return(jo(e)?Wo(Ro[r]):[e]).map(n)}function jo(r){return["0.0.0.0","::"].includes(r)}var qo=$t.default.networkInterfaces();function Wo(r){let e=[];for(let[,t]of Object.entries(qo))if(t!=null)for(let n of t)n.family===r&&e.push(n.address);return e}var Oe=(r,e)=>{let t,n=e.logger.forComponent("libp2p:tcp:socket"),o=e.direction,s=e.metrics,i=e.metricPrefix??"",a=e.socketInactivityTimeout??12e4,d=e.socketCloseTimeout??500,m=!1,p=!1;e.listeningAddr?.getPath()!=null&&(e.remoteAddr=e.listeningAddr),e.remoteAddr?.getPath()!=null&&(e.localAddr=e.remoteAddr),r.on("error",x=>{p=!0,m||(n.error("%s socket error - %e",o,x),s?.increment({[`${i}error`]:!0})),r.destroy(),T.timeline.close=Date.now()});let h;if(e.remoteAddr!=null)h=e.remoteAddr;else{if(r.remoteAddress==null||r.remotePort==null)throw new V("Could not determine remote address or port");h=$r(r.remoteAddress,r.remotePort)}let b=ae(h),l=b.path??`${b.host??""}:${b.port??""}`,{sink:f,source:I}=Ft(r);r.setTimeout(a),r.once("timeout",()=>{m=!0,n("%s %s socket read timeout",o,l),s?.increment({[`${i}timeout`]:!0}),r.destroy(new Z),T.timeline.close=Date.now()}),r.once("close",()=>{!m&&!p&&(n("%s %s socket close",o,l),s?.increment({[`${i}close`]:!0})),r.destroy(),T.timeline.close=Date.now()}),r.once("end",()=>{n("%s %s socket end",o,l),s?.increment({[`${i}end`]:!0})});let T={async sink(x){try{await f(async function*(){for await(let w of x)w instanceof Uint8Array?yield w:yield w.subarray()}())}catch(w){w.type!=="aborted"&&n.error("%s %s error in sink - %e",o,l,w)}r.end()},source:I,remoteAddr:h,timeline:{open:Date.now()},async close(x={}){if(r.closed){n("the %s %s socket is already closed",o,l);return}if(r.destroyed){n("the %s %s socket is already destroyed",o,l);return}if(t!=null)return t.promise;try{t=kt(),r.end();let w=Go(r),L=x.signal??AbortSignal.timeout(d);r.writableLength>0&&(n("%s %s draining socket",o,l),await Nt(w,"drain",L,{errorEvent:"error"}),n("%s %s socket drained",o,l)),await Promise.all([Nt(w,"close",L,{errorEvent:"error"}),r.destroy()])}catch(w){this.abort(w)}finally{t.resolve()}},abort:x=>{n("%s %s socket abort due to error - %e",o,l,x),r.destroy(),T.timeline.close=Date.now()},log:n};return T};function Go(r){return{addEventListener:(t,n)=>{r.addListener(t,n)},removeEventListener:(t,n)=>{r.removeListener(t,n)}}}var A;(function(r){r[r.INACTIVE=0]="INACTIVE",r[r.ACTIVE=1]="ACTIVE",r[r.PAUSED=2]="PAUSED"})(A||(A={}));var Ve=class extends ye{context;server;sockets=new Set;status={code:A.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,this.shutdownController=new AbortController,ve(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=Br.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new V("closeAbove must be >= listenBelow");this.server.on("listening",()=>{if(e.metrics!=null){let t=this.server.address();t==null?this.addr="unknown":typeof t=="string"?this.addr=t:this.addr=`${t.address}:${t.port}`,e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.metrics?.status.update({[this.addr]:A.ACTIVE})}this.safeDispatchEvent("listening")}).on("error",t=>{this.metrics?.errors.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:t})}).on("close",()=>{this.metrics?.status.update({[this.addr]:this.status.code}),this.status.code!==A.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics?.events.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics?.events.increment({[`${this.addr} connection`]:!0}),this.status.code!==A.ACTIVE)throw e.destroy(),new we("Server is not listening yet");let t;try{t=Oe(e,{listeningAddr:this.status.listeningAddr,socketInactivityTimeout:this.context.socketInactivityTimeout,socketCloseTimeout:this.context.socketCloseTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,logger:this.context.logger,direction:"inbound"})}catch(n){this.log.error("inbound connection failed",n),this.metrics?.errors.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",t.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(t,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",t.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(n=>{this.log.error("error attempting to listen server once connection count under limit",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&this.pause()}).catch(async n=>{this.log.error("inbound connection upgrade failed",n),this.metrics?.errors.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),t.abort(n)})}getAddrs(){if(this.status.code===A.INACTIVE)return[];let e=[],t=this.server.address(),{listeningAddr:n,peerId:o}=this.status;if(t==null)return[];if(typeof t=="string")e=[n];else try{n.toString().startsWith("/ip4")?e=e.concat(Ot("ip4",t.address,t.port)):t.family==="IPv6"&&(e=e.concat(Ot("ip6",t.address,t.port)))}catch(s){this.log.error("could not turn %s:%s into multiaddr",t.address,t.port,s)}return e.map(s=>o!=null?s.encapsulate(`/p2p/${o}`):s)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===A.ACTIVE||this.status.code===A.PAUSED)throw new be("server is already listening");let t=e.getPeerId(),n=t==null?e.decapsulateCode(421):e,{backlog:o}=this.context;try{this.status={code:A.ACTIVE,listeningAddr:n,peerId:t,netConfig:ae(n,{backlog:o})},await this.resume()}catch(s){throw this.status={code:A.INACTIVE},s}}async close(){let e=[];this.server.listening&&e.push(Mt(this.server,"close")),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(t=>{t.readable&&(e.push(Mt(t,"close")),t.destroy())}),await Promise.all(e)}async resume(){if(this.server.listening||this.status.code===A.INACTIVE)return;let e=this.status.netConfig;await new Promise((t,n)=>{this.server.once("error",n),this.server.listen(e,t)}),this.status={...this.status,code:A.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===A.PAUSED&&e){this.status={code:A.INACTIVE};return}!this.server.listening||this.status.code!==A.ACTIVE||(this.log("closing server on %s",this.server.address()),this.status=e?{code:A.INACTIVE}:{...this.status,code:A.PAUSED},this.server.close())}};var ze=class{opts;metrics;components;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=t,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[Bt]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Rt]=["@libp2p/transport"];async dial(e,t){t.keepAlive=t.keepAlive??!0,t.noDelay=t.noDelay??!0;let n=await this._connect(e,t),o;try{o=Oe(n,{remoteAddr:e,socketInactivityTimeout:this.opts.outboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.metrics?.events,logger:this.components.logger,direction:"outbound"})}catch(s){throw this.metrics?.errors.increment({outbound_to_connection:!0}),n.destroy(s),s}try{return this.log("new outbound connection %s",o.remoteAddr),await t.upgrader.upgradeOutbound(o,t)}catch(s){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection",s),o.abort(s),s}}async _connect(e,t){t.signal.throwIfAborted(),t.onProgress?.(new $e("tcp:open-connection"));let n;return new Promise((o,s)=>{let i=Date.now(),a=ae(e,{...this.opts.dialOpts??{},...t});this.log("dialing %a",e),n=_r.default.connect(a);let d=l=>{this.log.error("dial to %a errored - %e",e,l);let f=a.path??`${a.host??""}:${a.port}`;l.message=`connection error ${f}: ${l.message}`,this.metrics?.events.increment({error:!0}),b(l)},m=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let l=new Z(`Connection timeout after ${Date.now()-i}ms`);n.emit("error",l)},p=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),b()},h=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),b(new ge)},b=l=>{if(n.removeListener("error",d),n.removeListener("timeout",m),n.removeListener("connect",p),t.signal!=null&&t.signal.removeEventListener("abort",h),l!=null){s(l);return}o(n)};n.on("error",d),n.on("timeout",m),n.on("connect",p),t.signal.addEventListener("abort",h)}).catch(o=>{throw n?.destroy(),o})}createListener(e){return new Ve({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,socketInactivityTimeout:this.opts.inboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>t.protoCodes().includes(290)?!1:t.protoCodes().includes(400)?!0:H.matches(t.decapsulateCode(421)))}dialFilter(e){return this.listenFilter(e)}};function Jo(r={}){return e=>new ze(e,r)}return Hr(Qo);})(); | ||
"use strict";var Libp2PTcp=(()=>{var Jr=Object.create;var ye=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Kr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Zr=Object.prototype.hasOwnProperty;var F=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,e)=>{for(var r in e)ye(t,r,{get:e[r],enumerable:!0})},jt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Kr(e))!Zr.call(t,o)&&o!==r&&ye(t,o,{get:()=>e[o],enumerable:!(n=Xr(e,o))||n.enumerable});return t};var Z=(t,e,r)=>(r=t!=null?Jr(Yr(t)):{},jt(e||!t||!t.__esModule?ye(r,"default",{value:t,enumerable:!0}):r,t)),en=t=>jt(ye({},"__esModule",{value:!0}),t);var Zo={};k(Zo,{tcp:()=>Yo});var Qr=Z(F("net"),1);var qt=Symbol.for("@libp2p/transport");var Wt;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Wt||(Wt={}));var ve=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var B=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var ee=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Ee=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},Ie=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}};var Gt=F("node:events"),Ae=(t,...e)=>{try{(0,Gt.setMaxListeners)(t,...e)}catch{}};var Te=class extends EventTarget{#e=new Map;constructor(){super(),Ae(1/0,this)}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#e.set(e,o))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var Ht=Symbol.for("@libp2p/service-capabilities"),is=Symbol.for("@libp2p/service-dependencies");var S=F("node:net");function Ce(t){return!!(0,S.isIP)(t)}var Je={};k(Je,{base58btc:()=>P,base58flickr:()=>cn});var Ds=new Uint8Array(0);function Qt(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function O(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Jt(t){return new TextEncoder().encode(t)}function Xt(t){return new TextDecoder().decode(t)}function tn(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var c=t.length,l=t.charAt(0),f=Math.log(c)/Math.log(256),u=Math.log(256)/Math.log(c);function p(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 T=0,N=0,x=0,b=d.length;x!==b&&d[x]===0;)x++,T++;for(var M=(b-x)*u+1>>>0,$=new Uint8Array(M);x!==b;){for(var z=d[x],H=0,V=M-1;(z!==0||H<N)&&V!==-1;V--,H++)z+=256*$[V]>>>0,$[V]=z%c>>>0,z=z/c>>>0;if(z!==0)throw new Error("Non-zero carry");N=H,x++}for(var j=M-N;j!==M&&$[j]===0;)j++;for(var be=l.repeat(T);j<M;++j)be+=t.charAt($[j]);return be}function y(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var T=0;if(d[T]!==" "){for(var N=0,x=0;d[T]===l;)N++,T++;for(var b=(d.length-T)*f+1>>>0,M=new Uint8Array(b);d[T];){var $=r[d.charCodeAt(T)];if($===255)return;for(var z=0,H=b-1;($!==0||z<x)&&H!==-1;H--,z++)$+=c*M[H]>>>0,M[H]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");x=z,T++}if(d[T]!==" "){for(var V=b-x;V!==b&&M[V]===0;)V++;for(var j=new Uint8Array(N+(b-V)),be=N;V!==b;)j[be++]=M[V++];return j}}}function a(d){var T=y(d);if(T)return T;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:y,decode:a}}var rn=tn,nn=rn,Yt=nn;var qe=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ge=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Zt(this,e)}},He=class{decoders;constructor(e){this.decoders=e}or(e){return Zt(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Zt(t,e){return new He({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Qe=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new qe(e,r,n),this.decoder=new Ge(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function te({name:t,prefix:e,encode:r,decode:n}){return new Qe(t,e,r,n)}function Q({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=Yt(r,t);return te({prefix:e,name:t,encode:n,decode:s=>O(o(s))})}function on(t,e,r,n){let o={};for(let u=0;u<e.length;++u)o[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;let i=new Uint8Array(s*r/8|0),c=0,l=0,f=0;for(let u=0;u<s;++u){let p=o[t[u]];if(p===void 0)throw new SyntaxError(`Non-${n} character`);l=l<<r|p,c+=r,c>=8&&(c-=8,i[f++]=255&l>>c)}if(c>=r||(255&l<<8-c)!==0)throw new SyntaxError("Unexpected end of data");return i}function sn(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,c=0;for(let l=0;l<t.length;++l)for(c=c<<8|t[l],i+=8;i>r;)i-=r,s+=e[o&c>>i];if(i!==0&&(s+=e[o&c<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function A({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return te({prefix:e,name:t,encode(o){return sn(o,n,r)},decode(o){return on(o,n,r,t)}})}var P=Q({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cn=Q({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ke={};k(Ke,{base64:()=>an,base64pad:()=>ln,base64url:()=>Xe,base64urlpad:()=>un});var an=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ln=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Xe=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),un=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var dn=t=>t.toString().split("/").slice(1),re=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),h=t=>({match:e=>re(r=>r===t).match(e),pattern:t}),X=()=>({match:t=>re(e=>typeof e=="string").match(t),pattern:"{string}"}),de=()=>({match:t=>re(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),v=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{P.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),pe=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{Xe.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),g=t=>({match:e=>{let r=t.match(e);return r===!1?e:r},pattern:`optional(${t.pattern})`}),L=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1},pattern:`or(${t.map(e=>e.pattern).join(", ")})`}),m=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${t.map(e=>e.pattern).join(", ")})`});function I(...t){function e(o){let s=dn(o);for(let i of t){let c=i.match(s);if(c===!1)return!1;s=c}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var Pe=m(h("dns4"),X()),Le=m(h("dns6"),X()),De=m(h("dnsaddr"),X()),Ze=m(h("dns"),X()),Rs=I(Pe,g(v())),js=I(Le,g(v())),Ws=I(De,g(v())),qs=I(L(Ze,De,Pe,Le),g(v())),er=m(h("ip4"),re(S.isIPv4)),tr=m(h("ip6"),re(S.isIPv6)),et=L(er,tr),W=L(et,Ze,Pe,Le,De),Gs=I(L(et,m(L(Ze,De,Pe,Le),g(v())))),Hs=I(er),Qs=I(tr),Js=I(et),tt=m(W,h("tcp"),de()),fe=m(W,h("udp"),de()),rr=I(m(tt,g(v()))),Xs=I(fe),rt=m(fe,h("quic"),g(v())),Ne=m(fe,h("quic-v1"),g(v())),pn=L(rt,Ne),Ks=I(rt),Ys=I(Ne),Ye=L(W,tt,fe,rt,Ne),nr=L(m(Ye,h("ws"),g(v()))),Zs=I(nr),or=L(m(Ye,h("wss"),g(v())),m(Ye,h("tls"),g(m(h("sni"),X())),h("ws"),g(v()))),ei=I(or),sr=m(fe,h("webrtc-direct"),g(pe()),g(pe()),g(v())),ti=I(sr),ir=m(Ne,h("webtransport"),g(pe()),g(pe()),g(v())),ri=I(ir),Se=L(nr,or,m(tt,g(v())),m(pn,g(v())),m(W,g(v())),sr,ir,v()),ni=I(Se),fn=m(Se,h("p2p-circuit"),v()),oi=I(fn),hn=L(m(Se,h("p2p-circuit"),h("webrtc"),g(v())),m(Se,h("webrtc"),g(v())),m(h("webrtc"),g(v()))),si=I(hn),mn=L(m(W,h("tcp"),de(),h("http"),g(v())),m(W,h("http"),g(v()))),ii=I(mn),xn=L(m(W,h("tcp"),L(m(h("443"),h("http")),m(de(),h("https"))),g(v())),m(W,h("tls"),h("http"),g(v())),m(W,h("https"),g(v()))),ci=I(xn),gn=L(m(h("memory"),X(),g(v()))),ai=I(gn);var Ue=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var Hr=Z(F("net"),1);var Vr=Z(F("node:os"),1);var cr=F("node:buffer");function ne(t){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Me(t=0){return ne(cr.Buffer.allocUnsafe(t))}var wn=Math.pow(2,7),bn=Math.pow(2,14),yn=Math.pow(2,21),nt=Math.pow(2,28),ot=Math.pow(2,35),st=Math.pow(2,42),it=Math.pow(2,49),w=128,D=127;function R(t){if(t<wn)return 1;if(t<bn)return 2;if(t<yn)return 3;if(t<nt)return 4;if(t<ot)return 5;if(t<st)return 6;if(t<it)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function vn(t,e,r=0){switch(R(t)){case 8:e[r++]=t&255|w,t/=128;case 7:e[r++]=t&255|w,t/=128;case 6:e[r++]=t&255|w,t/=128;case 5:e[r++]=t&255|w,t/=128;case 4:e[r++]=t&255|w,t>>>=7;case 3:e[r++]=t&255|w,t>>>=7;case 2:e[r++]=t&255|w,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function En(t,e,r=0){switch(R(t)){case 8:e.set(r++,t&255|w),t/=128;case 7:e.set(r++,t&255|w),t/=128;case 6:e.set(r++,t&255|w),t/=128;case 5:e.set(r++,t&255|w),t/=128;case 4:e.set(r++,t&255|w),t>>>=7;case 3:e.set(r++,t&255|w),t>>>=7;case 2:e.set(r++,t&255|w),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function In(t,e){let r=t[e],n=0;if(n+=r&D,r<w||(r=t[e+1],n+=(r&D)<<7,r<w)||(r=t[e+2],n+=(r&D)<<14,r<w)||(r=t[e+3],n+=(r&D)<<21,r<w)||(r=t[e+4],n+=(r&D)*nt,r<w)||(r=t[e+5],n+=(r&D)*ot,r<w)||(r=t[e+6],n+=(r&D)*st,r<w)||(r=t[e+7],n+=(r&D)*it,r<w))return n;throw new RangeError("Could not decode varint")}function An(t,e){let r=t.get(e),n=0;if(n+=r&D,r<w||(r=t.get(e+1),n+=(r&D)<<7,r<w)||(r=t.get(e+2),n+=(r&D)<<14,r<w)||(r=t.get(e+3),n+=(r&D)<<21,r<w)||(r=t.get(e+4),n+=(r&D)*nt,r<w)||(r=t.get(e+5),n+=(r&D)*ot,r<w)||(r=t.get(e+6),n+=(r&D)*st,r<w)||(r=t.get(e+7),n+=(r&D)*it,r<w))return n;throw new RangeError("Could not decode varint")}function oe(t,e,r=0){return e==null&&(e=Me(R(t))),e instanceof Uint8Array?vn(t,e,r):En(t,e,r)}function K(t,e=0){return t instanceof Uint8Array?In(t,e):An(t,e)}var lr=F("node:buffer");function q(t,e){return ne(lr.Buffer.concat(t,e))}var Ir=F("node:buffer");var ct={};k(ct,{base10:()=>Tn});var Tn=Q({prefix:"9",name:"base10",alphabet:"0123456789"});var at={};k(at,{base16:()=>Cn,base16upper:()=>Sn});var Cn=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Sn=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var lt={};k(lt,{base2:()=>Pn});var Pn=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ut={};k(ut,{base256emoji:()=>Mn});var ur=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}"),Ln=ur.reduce((t,e,r)=>(t[r]=e,t),[]),Dn=ur.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function Nn(t){return t.reduce((e,r)=>(e+=Ln[r],e),"")}function Un(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Dn[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Mn=te({prefix:"\u{1F680}",name:"base256emoji",encode:Nn,decode:Un});var dt={};k(dt,{base32:()=>G,base32hex:()=>On,base32hexpad:()=>_n,base32hexpadupper:()=>zn,base32hexupper:()=>Vn,base32pad:()=>$n,base32padupper:()=>Fn,base32upper:()=>kn,base32z:()=>Bn});var G=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kn=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$n=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Fn=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),On=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vn=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),_n=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zn=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Bn=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var pt={};k(pt,{base36:()=>he,base36upper:()=>Rn});var he=Q({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Rn=Q({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ft={};k(ft,{base8:()=>jn});var jn=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ht={};k(ht,{identity:()=>Wn});var Wn=te({prefix:"\0",name:"identity",encode:t=>Xt(t),decode:t=>Jt(t)});var Ci=new TextEncoder,Si=new TextDecoder;var xt={};k(xt,{identity:()=>ho});var Hn=fr,dr=128,Qn=127,Jn=~Qn,Xn=Math.pow(2,31);function fr(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Xn;)e[r++]=t&255|dr,t/=128;for(;t&Jn;)e[r++]=t&255|dr,t>>>=7;return e[r]=t|0,fr.bytes=r-n+1,e}var Kn=mt,Yn=128,pr=127;function mt(t,n){var r=0,n=n||0,o=0,s=n,i,c=t.length;do{if(s>=c)throw mt.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&pr)<<o:(i&pr)*Math.pow(2,o),o+=7}while(i>=Yn);return mt.bytes=s-n,r}var Zn=Math.pow(2,7),eo=Math.pow(2,14),to=Math.pow(2,21),ro=Math.pow(2,28),no=Math.pow(2,35),oo=Math.pow(2,42),so=Math.pow(2,49),io=Math.pow(2,56),co=Math.pow(2,63),ao=function(t){return t<Zn?1:t<eo?2:t<to?3:t<ro?4:t<no?5:t<oo?6:t<so?7:t<io?8:t<co?9:10},lo={encode:Hn,decode:Kn,encodingLength:ao},uo=lo,me=uo;function xe(t,e=0){return[me.decode(t,e),me.decode.bytes]}function se(t,e,r=0){return me.encode(t,e,r),e}function ie(t){return me.encodingLength(t)}function Y(t,e){let r=e.byteLength,n=ie(t),o=n+ie(r),s=new Uint8Array(o+r);return se(t,s,0),se(r,s,n),s.set(e,o),new ce(t,r,e,s)}function $e(t){let e=O(t),[r,n]=xe(e),[o,s]=xe(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ce(r,o,i,e)}function hr(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Qt(t.bytes,r.bytes)}}var ce=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var mr=0,po="identity",xr=O;function fo(t){return Y(mr,xr(t))}var ho={code:mr,name:po,encode:xr,digest:fo};var yt={};k(yt,{sha256:()=>mo,sha512:()=>xo});var bt=Z(F("crypto"),1);function wt({name:t,code:e,encode:r}){return new gt(t,e,r)}var gt=class{name;code;encode;constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Y(this.code,r):r.then(n=>Y(this.code,n))}else throw Error("Unknown type, must be binary type")}};var mo=wt({name:"sha2-256",code:18,encode:t=>O(bt.default.createHash("sha256").update(t).digest())}),xo=wt({name:"sha2-512",code:19,encode:t=>O(bt.default.createHash("sha512").update(t).digest())});function wr(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return wo(r,vt(t),e??P.encoder);default:return bo(r,vt(t),e??G.encoder)}}var br=new WeakMap;function vt(t){let e=br.get(t);if(e==null){let r=new Map;return br.set(t,r),r}return e}var J=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}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:r}=this;if(e!==ge)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==yo)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:r}=this.multihash,n=Y(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&hr(e.multihash,n.multihash)}toString(e){return wr(this,e)}toJSON(){return{"/":wr(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??yr(n,o,s.bytes))}else if(r[vo]===!0){let{version:n,multihash:o,code:s}=r,i=$e(o);return t.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="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(r!==ge)throw new Error(`Version 0 CID must use dag-pb (code: ${ge}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=yr(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,ge,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=O(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new ce(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[p,y]=xe(e.subarray(r));return r+=y,p},o=n(),s=ge;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,c=n(),l=n(),f=r+l,u=f-i;return{version:o,codec:s,multihashCode:c,digestSize:l,multihashSize:u,size:f}}static parse(e,r){let[n,o]=go(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vt(s).set(n,e),s}};function go(t,e){switch(t[0]){case"Q":{let r=e??P;return[P.prefix,r.decode(`${P.prefix}${t}`)]}case P.prefix:{let r=e??P;return[P.prefix,r.decode(t)]}case G.prefix:{let r=e??G;return[G.prefix,r.decode(t)]}case he.prefix:{let r=e??he;return[he.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function wo(t,e,r){let{prefix:n}=r;if(n!==P.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function bo(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var ge=112,yo=18;function yr(t,e,r){let n=ie(t),o=n+ie(e),s=new Uint8Array(o+r.byteLength);return se(t,s,0),se(e,s,n),s.set(r,o),s}var vo=Symbol.for("@ipld/js-cid/CID");var we={...ht,...lt,...ft,...ct,...at,...dt,...pt,...Je,...Ke,...ut},Xi={...yt,...xt};function Er(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var vr=Er("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Et=Er("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Me(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Eo={utf8:vr,"utf-8":vr,hex:we.base16,latin1:Et,ascii:Et,binary:Et,...we},Fe=Eo;function U(t,e="utf8"){let r=Fe[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?Ir.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var Oe=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,o){return this.readAtomically(()=>{let s=0,i=0,c=this.peekChar();if(c===void 0)return;let l=c==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let p=this.readChar();if(p===void 0)return;let y=Number.parseInt(p,e);if(!Number.isNaN(y))return y});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&l&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=e(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[c]=e(s.subarray(0,i));return r.set(s.subarray(0,c),16-c),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var sc=new Oe;var fc=parseInt("0xFFFF",16),hc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Cr=F("node:buffer");function Ve(t,e="utf8"){let r=Fe[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?ne(Cr.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var Sr=S.isIPv4,Po=S.isIPv6,It=function(t){let e=0;if(t=t.toString().trim(),Sr(t)){let r=new Uint8Array(e+4);return t.split(/\./g).forEach(n=>{r[e++]=parseInt(n,10)&255}),r}if(Po(t)){let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Sr(r[n]),i;s&&(i=It(r[n]),r[n]=U(i.slice(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,U(i.slice(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(e+16);for(n=0;n<r.length;n++){let s=parseInt(r[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},Pr=function(t,e=0,r){e=~~e,r=r??t.length-e;let n=new DataView(t.buffer);if(r===4){let o=[];for(let s=0;s<r;s++)o.push(t[e+s]);return o.join(".")}if(r===16){let o=[];for(let s=0;s<r;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var le={},At={},Do=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Do.forEach(t=>{let e=No(...t);At[e.code]=e,le[e.name]=e});function No(t,e,r,n,o){return{code:t,size:e,name:r,resolvable:!!n,path:!!o}}function E(t){if(typeof t=="number"){if(At[t]!=null)return At[t];throw new Error(`no protocol with code: ${t}`)}else if(typeof t=="string"){if(le[t]!=null)return le[t];throw new Error(`no protocol with name: ${t}`)}throw new Error(`invalid protocol id type: ${typeof t}`)}var ea=E("ip4"),ta=E("ip6"),ra=E("ipcidr");function Pt(t,e){switch(E(t).code){case 4:case 41:return Mo(e);case 42:return St(e);case 43:return U(e,"base10");case 6:case 273:case 33:case 132:return Nr(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return St(e);case 421:return Oo(e);case 444:return Dr(e);case 445:return Dr(e);case 466:return Fo(e);case 481:return globalThis.encodeURIComponent(St(e));default:return U(e,"base16")}}function Lt(t,e){switch(E(t).code){case 4:return Lr(e);case 41:return Lr(e);case 42:return Ct(e);case 43:return Ve(e,"base10");case 6:case 273:case 33:case 132:return Dt(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ct(e);case 421:return ko(e);case 444:return Vo(e);case 445:return _o(e);case 466:return $o(e);case 481:return Ct(globalThis.decodeURIComponent(e));default:return Ve(e,"base16")}}var Tt=Object.values(we).map(t=>t.decoder),Uo=function(){let t=Tt[0].or(Tt[1]);return Tt.slice(2).forEach(e=>t=t.or(e)),t}();function Lr(t){if(!Ce(t))throw new Error("invalid ip address");return It(t)}function Mo(t){let e=Pr(t,0,t.length);if(e==null)throw new Error("ipBuff is required");if(!Ce(e))throw new Error("invalid ip address");return e}function Dt(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function Nr(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function Ct(t){let e=Ve(t),r=Uint8Array.from(oe(e.length));return q([r,e],r.length+e.length)}function St(t){let e=K(t);if(t=t.slice(R(e)),t.length!==e)throw new Error("inconsistent lengths");return U(t)}function ko(t){let e;t[0]==="Q"||t[0]==="1"?e=$e(P.decode(`z${t}`)).bytes:e=J.parse(t).multihash.bytes;let r=Uint8Array.from(oe(e.length));return q([r,e],r.length+e.length)}function $o(t){let e=Uo.decode(t),r=Uint8Array.from(oe(e.length));return q([r,e],r.length+e.length)}function Fo(t){let e=K(t),r=t.slice(R(e));if(r.length!==e)throw new Error("inconsistent lengths");return"u"+U(r,"base64url")}function Oo(t){let e=K(t),r=t.slice(R(e));if(r.length!==e)throw new Error("inconsistent lengths");return U(r,"base58btc")}function Vo(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=G.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Dt(n);return q([r,o],r.length+o.length)}function _o(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=G.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Dt(n);return q([r,o],r.length+o.length)}function Dr(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=U(e,"base32"),o=Nr(r);return`${n}:${o}`}function Ur(t){t=Nt(t);let e=[],r=[],n=null,o=t.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],c=E(i);if(c.size===0){e.push([c.code]),r.push([c.code]);continue}if(s++,s>=o.length)throw new _e("invalid address: "+t);if(c.path===!0){n=Nt(o.slice(s).join("/")),e.push([c.code,Lt(c.code,n)]),r.push([c.code,n]);break}let l=Lt(c.code,o[s]);e.push([c.code,l]),r.push([c.code,Pt(c.code,l)])}return{string:Mr(r),bytes:ze(e),tuples:e,stringTuples:r,path:n}}function Ut(t){let e=[],r=[],n=null,o=0;for(;o<t.length;){let s=K(t,o),i=R(s),c=E(s),l=zo(c,t.slice(o+i));if(l===0){e.push([s]),r.push([s]),o+=i;continue}let f=t.slice(o+i,o+i+l);if(o+=l+i,o>t.length)throw new _e("Invalid address Uint8Array: "+U(t,"base16"));e.push([s,f]);let u=Pt(s,f);if(r.push([s,u]),c.path===!0){n=u;break}}return{bytes:Uint8Array.from(t),string:Mr(r),tuples:e,stringTuples:r,path:n}}function Mr(t){let e=[];return t.map(r=>{let n=E(r[0]);return e.push(n.name),r.length>1&&r[1]!=null&&e.push(r[1]),null}),Nt(e.join("/"))}function ze(t){return q(t.map(e=>{let r=E(e[0]),n=Uint8Array.from(oe(r.code));return e.length>1&&e[1]!=null&&(n=q([n,e[1]])),n}))}function zo(t,e){if(t.size>0)return t.size/8;if(t.size===0)return 0;{let r=K(e instanceof Uint8Array?e:Uint8Array.from(e));return r+R(r)}}function Nt(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}var _e=class extends Error{static name="ParseError";name="ParseError";constructor(e){super(`Error parsing address: ${e}`)}};function kr(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}var Bo=Symbol.for("nodejs.util.inspect.custom"),kt=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Ro=[E("dns").code,E("dns4").code,E("dns6").code,E("dnsaddr").code],Mt=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},Be=class t{bytes;#e;#t;#r;#n;[kt]=!0;constructor(e){e==null&&(e="");let r;if(e instanceof Uint8Array)r=Ut(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);r=Ur(e)}else if(Fr(e))r=Ut(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=r.bytes,this.#e=r.string,this.#t=r.tuples,this.#r=r.stringTuples,this.#n=r.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,r,n,o,s="",i=E("tcp"),c=E("udp"),l=E("ip4"),f=E("ip6"),u=E("dns6"),p=E("ip6zone");for(let[a,d]of this.stringTuples())a===p.code&&(s=`%${d??""}`),Ro.includes(a)&&(r=i.name==="tcp"?"tcp":"udp",o=443,n=`${d??""}${s}`,e=a===u.code?6:4),(a===i.code||a===c.code)&&(r=E(a).name==="tcp"?"tcp":"udp",o=parseInt(d??"")),(a===l.code||a===f.code)&&(r=E(a).name==="tcp"?"tcp":"udp",n=`${d??""}${s}`,e=a===f.code?6:4);if(e==null||r==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:r,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},E(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>E(e).name)}tuples(){return this.#t.map(([e,r])=>r==null?[e]:[e,r])}stringTuples(){return this.#r.map(([e,r])=>r==null?[e]:[e,r])}encapsulate(e){return e=new t(e),new t(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new t(n.slice(0,o))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new t(ze(r.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===le.p2p.code&&e.push([n,o]),n===le["p2p-circuit"].code&&(e=[])});let r=e.pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?U(P.decode(`z${n}`),"base58btc"):U(J.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return kr(this.bytes,e.bytes)}async resolve(e){let r=this.protos().find(s=>s.resolvable);if(r==null)return[this];let n=$r.get(r.name);if(n==null)throw new Mt(`no available resolver for ${r.name}`);return(await n(this,e)).map(s=>_(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let r=(e??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[Bo](){return`Multiaddr(${this.#e})`}};var $r=new Map;function Fr(t){return!!t?.[kt]}function _(t){return new Be(t)}function Or(t){return!!(t.startsWith("169.254.")||t.toLowerCase().startsWith("fe80"))}var jo={4:"IPv4",6:"IPv6"};function Wo(t){return["0.0.0.0","::"].includes(t)}function qo(t){let e=[],r=Vr.default.networkInterfaces();for(let[,n]of Object.entries(r))if(n!=null)for(let o of n)Or(o.address)||o.family===jo[t]&&e.push(o.address);return e}function _r(t,e){if(t==null)return[];let r=t.toOptions();if(Wo(r.host)){let n=[];for(let o of qo(r.family))n.push(_(`/ip${r.family}/${o}/${r.transport}/${e??r.port}`));return n}return[_(`/ip${r.family}/${r.host}/${r.transport}/${e??r.port}`)]}var $t=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Ft=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},zr=t=>globalThis.DOMException===void 0?new Ft(t):new DOMException(t),Br=t=>{let e=t.reason===void 0?zr("This operation was aborted."):t.reason;return e instanceof Error?e:zr(e)};function Ot(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c,f=new Promise((u,p)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(e.signal){let{signal:a}=e;a.aborted&&p(Br(a)),c=()=>{p(Br(a))},a.addEventListener("abort",c,{once:!0})}if(r===Number.POSITIVE_INFINITY){t.then(u,p);return}let y=new $t;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(a){p(a)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?p(o):(y.message=o??`Promise timed out after ${r} milliseconds`,p(y))},r),(async()=>{try{u(await t)}catch(a){p(a)}})()}).finally(()=>{f.clear(),c&&e.signal&&e.signal.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},f}var Go=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Ho(t,e,r){let n,o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let c=[e].flat(),l=[],{addListener:f,removeListener:u}=Go(t),p=(...a)=>{let d=r.multiArgs?a:a[0];r.filter&&!r.filter(d)||(l.push(d),r.count===l.length&&(n(),s(l)))},y=a=>{n(),i(a)};n=()=>{for(let a of c)u(a,p);for(let a of r.rejectionEvents)u(a,y)};for(let a of c)f(a,p);for(let a of r.rejectionEvents)f(a,y);r.signal&&r.signal.addEventListener("abort",()=>{y(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(l)});if(o.cancel=n,typeof r.timeout=="number"){let s=Ot(o,{milliseconds:r.timeout});return s.cancel=n,s}return o}function Vt(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Ho(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Rr(t,e){if(typeof t!="string")throw new B(`invalid ip provided: ${t}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new B(`invalid port provided: ${e}`);if((0,S.isIPv4)(t))return _(`/ip4/${t}/tcp/${e}`);if((0,S.isIPv6)(t))return _(`/ip6/${t}/tcp/${e}`);throw new B(`invalid ip:port for creating a multiaddr: ${t}:${e}`)}function _t(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var zt=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=r??"ABORT_ERR"}};async function Bt(t,e,r,n){let o=new zt(n?.errorMessage,n?.errorCode);return r?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function c(){r?.removeEventListener("abort",u),t.removeEventListener(e,l),n?.errorEvent!=null&&t.removeEventListener(n.errorEvent,f)}let l=p=>{try{if(n?.filter?.(p)===!1)return}catch(y){c(),i(y);return}c(),s(p)},f=p=>{c(),i(p.detail)},u=()=>{c(),i(o)};r?.addEventListener("abort",u),t.addEventListener(e,l),n?.errorEvent!=null&&t.addEventListener(n.errorEvent,f)})}function jr(t){if(Jo(t))return async function*(){let e=t.getReader();try{for(;;){let{done:r,value:n}=await e.read();if(r)return;yield n}}finally{e.releaseLock()}}();if(Qo(t))return t;throw new Error("unknown stream")}function Qo(t){return t[Symbol.asyncIterator]!=null}function Jo(t){return typeof t?.getReader=="function"}function Wr(t){return async e=>{let r=async()=>{Xo(e)&&await e.return(void 0)},n,o,s=x=>{n=x,r().catch(b=>{b=new AggregateError([n,b],"The Writable emitted an error, additionally an error occurred while ending the Source")}).finally(()=>{o?.(x)})},i,c=!1,l=()=>{c=!0,i?.()},f,u=!1,p=()=>{u=!0,f?.()},y,a=()=>{y?.()},d=async()=>new Promise((x,b)=>{i=y=x,o=b,t.once("drain",a)}),T=async()=>(await r(),new Promise((x,b)=>{if(c||u||n!=null){x();return}f=i=x,o=b})),N=()=>{t.removeListener("error",s),t.removeListener("close",l),t.removeListener("finish",p),t.removeListener("drain",a)};t.once("error",s),t.once("close",l),t.once("finish",p);try{for await(let x of e){if(!t.writable||t.destroyed||n!=null)break;t.write(x)||await d()}}catch(x){n==null&&t.destroy(x),n=x}try{if(t.writable&&t.end(),await T(),n!=null)throw n}finally{N()}}}function Xo(t){return t.return!=null}function Rt(t){return{sink:Wr(t),source:jr(t)}}var qr=Z(F("os"),1),Gr=Z(F("path"),1);function ue(t,e={}){let r=t.getPath();if(r!=null)return qr.default.platform()==="win32"?{path:Gr.default.join("\\\\.\\pipe\\",r)}:{path:r};let n=t.toOptions();return{...e,...n,ipv6Only:n.family===6}}var Re=(t,e)=>{let r,n=e.logger.forComponent("libp2p:tcp:socket"),o=e.direction,s=e.metrics,i=e.metricPrefix??"",c=e.socketInactivityTimeout??12e4,l=e.socketCloseTimeout??500,f=!1,u=!1;e.listeningAddr?.getPath()!=null&&(e.remoteAddr=e.listeningAddr),e.remoteAddr?.getPath()!=null&&(e.localAddr=e.remoteAddr),t.on("error",x=>{u=!0,f||(n.error("%s socket error - %e",o,x),s?.increment({[`${i}error`]:!0})),t.destroy(),N.timeline.close=Date.now()});let p;if(e.remoteAddr!=null)p=e.remoteAddr;else{if(t.remoteAddress==null||t.remotePort==null)throw new B("Could not determine remote address or port");p=Rr(t.remoteAddress,t.remotePort)}let y=ue(p),a=y.path??`${y.host??""}:${y.port??""}`,{sink:d,source:T}=Rt(t);t.setTimeout(c),t.once("timeout",()=>{f=!0,n("%s %s socket read timeout",o,a),s?.increment({[`${i}timeout`]:!0}),t.destroy(new ee),N.timeline.close=Date.now()}),t.once("close",()=>{!f&&!u&&(n("%s %s socket close",o,a),s?.increment({[`${i}close`]:!0})),t.destroy(),N.timeline.close=Date.now()}),t.once("end",()=>{n("%s %s socket end",o,a),s?.increment({[`${i}end`]:!0})});let N={async sink(x){try{await d(async function*(){for await(let b of x)b instanceof Uint8Array?yield b:yield b.subarray()}())}catch(b){b.type!=="aborted"&&n.error("%s %s error in sink - %e",o,a,b)}t.end()},source:T,remoteAddr:p,timeline:{open:Date.now()},async close(x={}){if(t.closed){n("the %s %s socket is already closed",o,a);return}if(t.destroyed){n("the %s %s socket is already destroyed",o,a);return}if(r!=null)return r.promise;try{r=_t(),t.end();let b=Ko(t),M=x.signal??AbortSignal.timeout(l);t.writableLength>0&&(n("%s %s draining socket",o,a),await Bt(b,"drain",M,{errorEvent:"error"}),n("%s %s socket drained",o,a)),await Promise.all([Bt(b,"close",M,{errorEvent:"error"}),t.destroy()])}catch(b){this.abort(b)}finally{r.resolve()}},abort:x=>{n("%s %s socket abort due to error - %e",o,a,x),t.destroy(),N.timeline.close=Date.now()},log:n};return N};function Ko(t){return{addEventListener:(r,n)=>{t.addListener(r,n)},removeEventListener:(r,n)=>{t.removeListener(r,n)}}}var C;(function(t){t[t.INACTIVE=0]="INACTIVE",t[t.ACTIVE=1]="ACTIVE",t[t.PAUSED=2]="PAUSED"})(C||(C={}));var je=class extends Te{context;server;sockets=new Set;status={code:C.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,this.shutdownController=new AbortController,Ae(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=Hr.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new B("closeAbove must be >= listenBelow");this.server.on("listening",()=>{if(e.metrics!=null){let r=this.server.address();r==null?this.addr="unknown":typeof r=="string"?this.addr=r:this.addr=`${r.address}:${r.port}`,e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.metrics?.status.update({[this.addr]:C.ACTIVE})}this.safeDispatchEvent("listening")}).on("error",r=>{this.metrics?.errors.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:r})}).on("close",()=>{this.metrics?.status.update({[this.addr]:this.status.code}),this.status.code!==C.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics?.events.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics?.events.increment({[`${this.addr} connection`]:!0}),this.status.code!==C.ACTIVE)throw e.destroy(),new Ee("Server is not listening yet");let r;try{r=Re(e,{listeningAddr:this.status.listeningAddr,socketInactivityTimeout:this.context.socketInactivityTimeout,socketCloseTimeout:this.context.socketCloseTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,logger:this.context.logger,direction:"inbound"})}catch(n){this.log.error("inbound connection failed",n),this.metrics?.errors.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",r.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(r,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",r.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(n=>{this.log.error("error attempting to listen server once connection count under limit",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&this.pause()}).catch(async n=>{this.log.error("inbound connection upgrade failed",n),this.metrics?.errors.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),r.abort(n)})}getAddrs(){if(this.status.code===C.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[_(`/unix/${e}`)]:_r(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===C.ACTIVE||this.status.code===C.PAUSED)throw new Ie("server is already listening");try{this.status={code:C.ACTIVE,listeningAddr:e,netConfig:ue(e,this.context)},await this.resume()}catch(r){throw this.status={code:C.INACTIVE},r}}async close(){let e=[];this.server.listening&&e.push(Vt(this.server,"close")),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(r=>{r.readable&&(e.push(Vt(r,"close")),r.destroy())}),await Promise.all(e)}async resume(){if(this.server.listening||this.status.code===C.INACTIVE)return;let e=this.status.netConfig;await new Promise((r,n)=>{this.server.once("error",n),this.server.listen(e,r)}),this.status={...this.status,code:C.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===C.PAUSED&&e){this.status={code:C.INACTIVE};return}!this.server.listening||this.status.code!==C.ACTIVE||(this.log("closing server on %s",this.server.address()),this.status=e?{code:C.INACTIVE}:{...this.status,code:C.PAUSED},this.server.close())}};var We=class{opts;metrics;components;log;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=r,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[qt]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Ht]=["@libp2p/transport"];async dial(e,r){r.keepAlive=r.keepAlive??!0,r.noDelay=r.noDelay??!0;let n=await this._connect(e,r),o;try{o=Re(n,{remoteAddr:e,socketInactivityTimeout:this.opts.outboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.metrics?.events,logger:this.components.logger,direction:"outbound"})}catch(s){throw this.metrics?.errors.increment({outbound_to_connection:!0}),n.destroy(s),s}try{return this.log("new outbound connection %s",o.remoteAddr),await r.upgrader.upgradeOutbound(o,r)}catch(s){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection",s),o.abort(s),s}}async _connect(e,r){r.signal.throwIfAborted(),r.onProgress?.(new Ue("tcp:open-connection"));let n;return new Promise((o,s)=>{let i=Date.now(),c=ue(e,{...this.opts.dialOpts??{},...r});this.log("dialing %a",e),n=Qr.default.connect(c);let l=a=>{this.log.error("dial to %a errored - %e",e,a);let d=c.path??`${c.host??""}:${c.port}`;a.message=`connection error ${d}: ${a.message}`,this.metrics?.events.increment({error:!0}),y(a)},f=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let a=new ee(`Connection timeout after ${Date.now()-i}ms`);n.emit("error",a)},u=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),y()},p=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),y(new ve)},y=a=>{if(n.removeListener("error",l),n.removeListener("timeout",f),n.removeListener("connect",u),r.signal!=null&&r.signal.removeEventListener("abort",p),a!=null){s(a);return}o(n)};n.on("error",l),n.on("timeout",f),n.on("connect",u),r.signal.addEventListener("abort",p)}).catch(o=>{throw n?.destroy(),o})}createListener(e){return new je({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,socketInactivityTimeout:this.opts.inboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(r=>rr.exactMatch(r)||r.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function Yo(t={}){return e=>new We(e,t)}return en(Zo);})(); | ||
return Libp2PTcp})); |
@@ -1,6 +0,3 @@ | ||
export declare const CODE_P2P = 421; | ||
export declare const CODE_CIRCUIT = 290; | ||
export declare const CODE_UNIX = 400; | ||
export declare const CLOSE_TIMEOUT = 500; | ||
export declare const SOCKET_TIMEOUT: number; | ||
//# sourceMappingURL=constants.d.ts.map |
@@ -1,9 +0,5 @@ | ||
// p2p multi-address code | ||
export const CODE_P2P = 421; | ||
export const CODE_CIRCUIT = 290; | ||
export const CODE_UNIX = 400; | ||
// Time to wait for a connection to close gracefully before destroying it manually | ||
export const CLOSE_TIMEOUT = 500; | ||
// Close the socket if there is no activity after this long in ms | ||
export const SOCKET_TIMEOUT = 2 * 60000; // 2 mins | ||
export const SOCKET_TIMEOUT = 2 * 60_000; // 2 mins | ||
//# sourceMappingURL=constants.js.map |
import net from 'net'; | ||
import { AlreadyStartedError, InvalidParametersError, NotStartedError, TypedEventEmitter, setMaxListeners } from '@libp2p/interface'; | ||
import { getThinWaistAddresses } from '@libp2p/utils/get-thin-waist-addresses'; | ||
import { multiaddr } from '@multiformats/multiaddr'; | ||
import { pEvent } from 'p-event'; | ||
import { CODE_P2P } from './constants.js'; | ||
import { toMultiaddrConnection } from './socket-to-conn.js'; | ||
import { getMultiaddrs, multiaddrToNetConfig } from './utils.js'; | ||
import { multiaddrToNetConfig } from './utils.js'; | ||
var TCPListenerStatusCode; | ||
@@ -179,5 +180,3 @@ (function (TCPListenerStatusCode) { | ||
} | ||
let addrs = []; | ||
const address = this.server.address(); | ||
const { listeningAddr, peerId } = this.status; | ||
if (address == null) { | ||
@@ -187,20 +186,8 @@ return []; | ||
if (typeof address === 'string') { | ||
addrs = [listeningAddr]; | ||
return [ | ||
// TODO: wrap with encodeURIComponent https://github.com/multiformats/multiaddr/pull/174 | ||
multiaddr(`/unix/${address}`) | ||
]; | ||
} | ||
else { | ||
try { | ||
// Because TCP will only return the IPv6 version | ||
// we need to capture from the passed multiaddr | ||
if (listeningAddr.toString().startsWith('/ip4')) { | ||
addrs = addrs.concat(getMultiaddrs('ip4', address.address, address.port)); | ||
} | ||
else if (address.family === 'IPv6') { | ||
addrs = addrs.concat(getMultiaddrs('ip6', address.address, address.port)); | ||
} | ||
} | ||
catch (err) { | ||
this.log.error('could not turn %s:%s into multiaddr', address.address, address.port, err); | ||
} | ||
} | ||
return addrs.map(ma => peerId != null ? ma.encapsulate(`/p2p/${peerId}`) : ma); | ||
return getThinWaistAddresses(this.status.listeningAddr, address.port); | ||
} | ||
@@ -213,11 +200,7 @@ updateAnnounceAddrs() { | ||
} | ||
const peerId = ma.getPeerId(); | ||
const listeningAddr = peerId == null ? ma.decapsulateCode(CODE_P2P) : ma; | ||
const { backlog } = this.context; | ||
try { | ||
this.status = { | ||
code: TCPListenerStatusCode.ACTIVE, | ||
listeningAddr, | ||
peerId, | ||
netConfig: multiaddrToNetConfig(listeningAddr, { backlog }) | ||
listeningAddr: ma, | ||
netConfig: multiaddrToNetConfig(ma, this.context) | ||
}; | ||
@@ -224,0 +207,0 @@ await this.resume(); |
@@ -31,5 +31,4 @@ /** | ||
import { AbortError, TimeoutError, serviceCapabilities, transportSymbol } from '@libp2p/interface'; | ||
import * as mafmt from '@multiformats/mafmt'; | ||
import { TCP as TCPMatcher } from '@multiformats/multiaddr-matcher'; | ||
import { CustomProgressEvent } from 'progress-events'; | ||
import { CODE_CIRCUIT, CODE_P2P, CODE_UNIX } from './constants.js'; | ||
import { TCPListener } from './listener.js'; | ||
@@ -178,12 +177,3 @@ import { toMultiaddrConnection } from './socket-to-conn.js'; | ||
listenFilter(multiaddrs) { | ||
multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]; | ||
return multiaddrs.filter(ma => { | ||
if (ma.protoCodes().includes(CODE_CIRCUIT)) { | ||
return false; | ||
} | ||
if (ma.protoCodes().includes(CODE_UNIX)) { | ||
return true; | ||
} | ||
return mafmt.TCP.matches(ma.decapsulateCode(CODE_P2P)); | ||
}); | ||
return multiaddrs.filter(ma => TCPMatcher.exactMatch(ma) || ma.toString().startsWith('/unix/')); | ||
} | ||
@@ -190,0 +180,0 @@ /** |
@@ -6,4 +6,2 @@ /// <reference types="node" /> | ||
export declare function multiaddrToNetConfig(addr: Multiaddr, config?: NetConfig): NetConfig; | ||
export declare function getMultiaddrs(proto: 'ip4' | 'ip6', ip: string, port: number): Multiaddr[]; | ||
export declare function isAnyAddr(ip: string): boolean; | ||
//# sourceMappingURL=utils.d.ts.map |
import os from 'os'; | ||
import path from 'path'; | ||
import { multiaddr } from '@multiformats/multiaddr'; | ||
const ProtoFamily = { ip4: 'IPv4', ip6: 'IPv6' }; | ||
export function multiaddrToNetConfig(addr, config = {}) { | ||
@@ -25,23 +23,2 @@ const listenPath = addr.getPath(); | ||
} | ||
export function getMultiaddrs(proto, ip, port) { | ||
const toMa = (ip) => multiaddr(`/${proto}/${ip}/tcp/${port}`); | ||
return (isAnyAddr(ip) ? getNetworkAddrs(ProtoFamily[proto]) : [ip]).map(toMa); | ||
} | ||
export function isAnyAddr(ip) { | ||
return ['0.0.0.0', '::'].includes(ip); | ||
} | ||
const networks = os.networkInterfaces(); | ||
function getNetworkAddrs(family) { | ||
const addresses = []; | ||
for (const [, netAddrs] of Object.entries(networks)) { | ||
if (netAddrs != null) { | ||
for (const netAddr of netAddrs) { | ||
if (netAddr.family === family) { | ||
addresses.push(netAddr.address); | ||
} | ||
} | ||
} | ||
} | ||
return addresses; | ||
} | ||
//# sourceMappingURL=utils.js.map |
{ | ||
"name": "@libp2p/tcp", | ||
"version": "10.1.7", | ||
"version": "10.1.8-b2124c2db", | ||
"description": "A TCP transport for libp2p", | ||
@@ -63,6 +63,6 @@ "license": "Apache-2.0 OR MIT", | ||
"dependencies": { | ||
"@libp2p/interface": "^2.7.0", | ||
"@libp2p/utils": "^6.5.8", | ||
"@multiformats/mafmt": "^12.1.6", | ||
"@libp2p/interface": "2.7.0-b2124c2db", | ||
"@libp2p/utils": "6.6.0-b2124c2db", | ||
"@multiformats/multiaddr": "^12.3.3", | ||
"@multiformats/multiaddr-matcher": "^1.6.0", | ||
"@types/sinon": "^17.0.3", | ||
@@ -76,3 +76,3 @@ "p-defer": "^4.0.1", | ||
"devDependencies": { | ||
"@libp2p/logger": "^5.1.13", | ||
"@libp2p/logger": "5.1.13-b2124c2db", | ||
"aegir": "^45.1.1", | ||
@@ -79,0 +79,0 @@ "p-wait-for": "^5.0.2", |
@@ -1,6 +0,1 @@ | ||
// p2p multi-address code | ||
export const CODE_P2P = 421 | ||
export const CODE_CIRCUIT = 290 | ||
export const CODE_UNIX = 400 | ||
// Time to wait for a connection to close gracefully before destroying it manually | ||
@@ -10,2 +5,2 @@ export const CLOSE_TIMEOUT = 500 | ||
// Close the socket if there is no activity after this long in ms | ||
export const SOCKET_TIMEOUT = 2 * 60000 // 2 mins | ||
export const SOCKET_TIMEOUT = 2 * 60_000 // 2 mins |
import net from 'net' | ||
import { AlreadyStartedError, InvalidParametersError, NotStartedError, TypedEventEmitter, setMaxListeners } from '@libp2p/interface' | ||
import { getThinWaistAddresses } from '@libp2p/utils/get-thin-waist-addresses' | ||
import { multiaddr } from '@multiformats/multiaddr' | ||
import { pEvent } from 'p-event' | ||
import { CODE_P2P } from './constants.js' | ||
import { toMultiaddrConnection } from './socket-to-conn.js' | ||
import { | ||
getMultiaddrs, | ||
multiaddrToNetConfig, | ||
type NetConfig | ||
} from './utils.js' | ||
import { multiaddrToNetConfig } from './utils.js' | ||
import type { TCPCreateListenerOptions } from './index.js' | ||
import type { NetConfig } from './utils.js' | ||
import type { ComponentLogger, Logger, MultiaddrConnection, CounterGroup, MetricGroup, Metrics, Listener, ListenerEvents, Upgrader } from '@libp2p/interface' | ||
@@ -64,3 +62,2 @@ import type { Multiaddr } from '@multiformats/multiaddr' | ||
listeningAddr: Multiaddr | ||
peerId: string | null | ||
netConfig: NetConfig | ||
@@ -251,5 +248,3 @@ } | ||
let addrs: Multiaddr[] = [] | ||
const address = this.server.address() | ||
const { listeningAddr, peerId } = this.status | ||
@@ -261,18 +256,9 @@ if (address == null) { | ||
if (typeof address === 'string') { | ||
addrs = [listeningAddr] | ||
} else { | ||
try { | ||
// Because TCP will only return the IPv6 version | ||
// we need to capture from the passed multiaddr | ||
if (listeningAddr.toString().startsWith('/ip4')) { | ||
addrs = addrs.concat(getMultiaddrs('ip4', address.address, address.port)) | ||
} else if (address.family === 'IPv6') { | ||
addrs = addrs.concat(getMultiaddrs('ip6', address.address, address.port)) | ||
} | ||
} catch (err) { | ||
this.log.error('could not turn %s:%s into multiaddr', address.address, address.port, err) | ||
} | ||
return [ | ||
// TODO: wrap with encodeURIComponent https://github.com/multiformats/multiaddr/pull/174 | ||
multiaddr(`/unix/${address}`) | ||
] | ||
} | ||
return addrs.map(ma => peerId != null ? ma.encapsulate(`/p2p/${peerId}`) : ma) | ||
return getThinWaistAddresses(this.status.listeningAddr, address.port) | ||
} | ||
@@ -289,12 +275,7 @@ | ||
const peerId = ma.getPeerId() | ||
const listeningAddr = peerId == null ? ma.decapsulateCode(CODE_P2P) : ma | ||
const { backlog } = this.context | ||
try { | ||
this.status = { | ||
code: TCPListenerStatusCode.ACTIVE, | ||
listeningAddr, | ||
peerId, | ||
netConfig: multiaddrToNetConfig(listeningAddr, { backlog }) | ||
listeningAddr: ma, | ||
netConfig: multiaddrToNetConfig(ma, this.context) | ||
} | ||
@@ -301,0 +282,0 @@ |
@@ -32,5 +32,4 @@ /** | ||
import { AbortError, TimeoutError, serviceCapabilities, transportSymbol } from '@libp2p/interface' | ||
import * as mafmt from '@multiformats/mafmt' | ||
import { TCP as TCPMatcher } from '@multiformats/multiaddr-matcher' | ||
import { CustomProgressEvent } from 'progress-events' | ||
import { CODE_CIRCUIT, CODE_P2P, CODE_UNIX } from './constants.js' | ||
import { TCPListener } from './listener.js' | ||
@@ -208,15 +207,3 @@ import { toMultiaddrConnection } from './socket-to-conn.js' | ||
listenFilter (multiaddrs: Multiaddr[]): Multiaddr[] { | ||
multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs] | ||
return multiaddrs.filter(ma => { | ||
if (ma.protoCodes().includes(CODE_CIRCUIT)) { | ||
return false | ||
} | ||
if (ma.protoCodes().includes(CODE_UNIX)) { | ||
return true | ||
} | ||
return mafmt.TCP.matches(ma.decapsulateCode(CODE_P2P)) | ||
}) | ||
return multiaddrs.filter(ma => TCPMatcher.exactMatch(ma) || ma.toString().startsWith('/unix/')) | ||
} | ||
@@ -223,0 +210,0 @@ |
import os from 'os' | ||
import path from 'path' | ||
import { multiaddr } from '@multiformats/multiaddr' | ||
import type { Multiaddr } from '@multiformats/multiaddr' | ||
import type { ListenOptions, IpcSocketConnectOpts, TcpSocketConnectOpts } from 'net' | ||
const ProtoFamily = { ip4: 'IPv4', ip6: 'IPv6' } | ||
export type NetConfig = ListenOptions | (IpcSocketConnectOpts & TcpSocketConnectOpts) | ||
@@ -33,28 +30,1 @@ | ||
} | ||
export function getMultiaddrs (proto: 'ip4' | 'ip6', ip: string, port: number): Multiaddr[] { | ||
const toMa = (ip: string): Multiaddr => multiaddr(`/${proto}/${ip}/tcp/${port}`) | ||
return (isAnyAddr(ip) ? getNetworkAddrs(ProtoFamily[proto]) : [ip]).map(toMa) | ||
} | ||
export function isAnyAddr (ip: string): boolean { | ||
return ['0.0.0.0', '::'].includes(ip) | ||
} | ||
const networks = os.networkInterfaces() | ||
function getNetworkAddrs (family: string): string[] { | ||
const addresses: string[] = [] | ||
for (const [, netAddrs] of Object.entries(networks)) { | ||
if (netAddrs != null) { | ||
for (const netAddr of netAddrs) { | ||
if (netAddr.family === family) { | ||
addresses.push(netAddr.address) | ||
} | ||
} | ||
} | ||
} | ||
return addresses | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
157091
-5.08%38
-2.56%2038
-6.13%2
100%+ Added
+ Added
+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed