@libp2p/daemon-server 9.0.10 → 9.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -10,8 +10,8 @@ ${e}${n.split(`
10
10
  `).join(`
11
11
  ${e}`)}`:n!=null?`${n.split(`
12
12
  `).join(`
13
- ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Jl(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function ma(r,e=""){if(Jl(r)){let t=ha(r,e);return r.errors.length>0?(e=`${e} `,t+=`${r.errors.map(n=>`
14
- ${e}${ma(n,`${e}`)}`).join(`
13
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Jl(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function ma(r,e=""){if(Jl(r)){let t=ha(r,e);return r.errors.length>0?(e=`${e} `,t+=`
14
+ ${e}${r.errors.map(n=>`${ma(n,`${e}`)}`).join(`
15
15
  ${e}`)}`):t+=`
16
16
  ${e}[Error list was empty]`,t.trim()}return ha(r,e)}Ie.formatters.e=r=>r==null?"undefined":ma(r);function ef(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function ba(r){return{forComponent(e){return at(e,r)}}}function at(r,e){let t=ef(`${r}:trace`);return Ie.enabled(`${r}:trace`)&&Ie.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ie(`${r}:trace`,e)),Object.assign(Ie(r,e),{error:Ie(`${r}:error`,e),trace:t,newScope:n=>at(`${r}:${n}`,e)})}function pa(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var tn=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Z=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},rn=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var nn=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var ct=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},hr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var on=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Vt=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},sn=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},an=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}};var pr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var cn=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},Gt=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},un=class extends Gt{constructor(e,t){super(!0,e,t)}},ln=class extends Gt{constructor(e,t){super(!1,e,t)}};var us=Symbol.for("@libp2p/peer-id");var ga=Symbol.for("@libp2p/transport");var ya;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(ya||(ya={}));var xa=oe("node:events"),fn=(r,...e)=>{try{(0,xa.setMaxListeners)(r,...e)}catch{}};var Ft=class extends EventTarget{#e=new Map;constructor(){super(),fn(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 Ea=Symbol.for("@libp2p/service-capabilities"),Qp=Symbol.for("@libp2p/service-dependencies");function Ce(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 wa=oe("node:buffer");function We(r,e){return pt(wa.Buffer.concat(r,e))}var Sa=Symbol.for("@achingbrain/uint8arraylist");function va(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function dn(r){return!!r?.[Sa]}var H=class r{bufs;length;[Sa]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(dn(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(dn(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=va(this.bufs,e);return t.buf[t.index]}set(e,t){let n=va(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(dn(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return We(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:We(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!dn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let p=l;p>=0;p--){let d=this.get(f+p);if(n[p]!==d){u=Math.max(1,p-a[d]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=Ze(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=Ze(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=Ze(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=Ze(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=Ze(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=Ze(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=Ze(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=Ze(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ce(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Ia=oe("node:buffer");function te(r,e="utf8"){let t=Mr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?Ia.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var tf=parseInt("11111",2),ls=parseInt("10000000",2),rf=parseInt("01111111",2),Aa={0:mr,1:mr,2:nf,3:af,4:cf,5:sf,6:of,16:mr,22:mr,48:mr};function fs(r,e={offset:0}){let t=r[e.offset]&tf;if(e.offset++,Aa[t]!=null)return Aa[t](r,e);throw new Error("No decoder for tag "+t)}function br(r,e){let t=0;if((r[e.offset]&ls)===ls){let n=r[e.offset]&rf,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function mr(r,e){br(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=fs(r,e);if(n===null)break;t.push(n)}return t}function nf(r,e){let t=br(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function of(r,e){let t=br(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function sf(r,e){return e.offset++,null}function af(r,e){let t=br(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function cf(r,e){let t=br(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function uf(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new H;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function ds(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=uf(r.byteLength);return new H(Uint8Array.from([e.byteLength|ls]),e)}function La(r){let e=new H,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new H(Uint8Array.from([2]),ds(e),e)}function Ta(r){let e=Uint8Array.from([0]),t=new H(e,r);return new H(Uint8Array.from([3]),ds(t),t)}function hn(r,e=48){let t=new H;for(let n of r)t.append(n);return new H(Uint8Array.from([e]),ds(t),t)}async function Da(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var lf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ff=Uint8Array.from([6,5,43,129,4,0,34]),df=Uint8Array.from([6,5,43,129,4,0,35]),hf={ext:!0,kty:"EC",crv:"P-256"},pf={ext:!0,kty:"EC",crv:"P-384"},mf={ext:!0,kty:"EC",crv:"P-521"},hs=32,ps=48,ms=66;function Ca(r){let e=fs(r);return _a(e)}function _a(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===hs*2+1)return n=te(e.subarray(t,t+hs),"base64url"),o=te(e.subarray(t+hs),"base64url"),new zt({...hf,key_ops:["verify"],x:n,y:o});if(e.byteLength===ps*2+1)return n=te(e.subarray(t,t+ps),"base64url"),o=te(e.subarray(t+ps),"base64url"),new zt({...pf,key_ops:["verify"],x:n,y:o});if(e.byteLength===ms*2+1)return n=te(e.subarray(t,t+ms),"base64url"),o=te(e.subarray(t+ms),"base64url"),new zt({...mf,key_ops:["verify"],x:n,y:o});throw new Z(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ba(r){return hn([La(Uint8Array.from([1])),hn([bf(r.crv)],160),hn([Ta(new H(Uint8Array.from([4]),ye(r.x??"","base64url"),ye(r.y??"","base64url")))],161)]).subarray()}function bf(r){if(r==="P-256")return lf;if(r==="P-384")return ff;if(r==="P-521")return df;throw new Z(`Invalid curve ${r}`)}var zt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ba(this.jwk)),this._raw}toMultihash(){return Ke.digest(ut(this))}toCID(){return se.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ce(this.raw,e.raw)}async verify(e,t,n){return Da(this.jwk,t,e,n)}};var pn=Te(oe("crypto"),1);var nb=pn.default.generateKeyPairSync,yr=32;var yf=64;function Oa(r,e,t){if(r.byteLength!==yr)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==yf)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=pn.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:te(r,"base64url"),kty:"OKP"}});return pn.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}function Ra(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var mn=class{type="Ed25519";raw;constructor(e){this.raw=bs(e,yr)}toMultihash(){return Ke.digest(ut(this))}toCID(){return se.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ce(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Oa(this.raw,t,e);return Ra(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Na(r){return r=bs(r,yr),new mn(r)}function bs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Z(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var _e;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(_e||(_e={}));var ys;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ys||(ys={}));(function(r){r.codec=()=>He(ys)})(_e||(_e={}));var gr;(function(r){let e;r.codec=()=>(e==null&&(e=Y((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),_e.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=_e.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>q(t,r.codec()),r.decode=(t,n)=>W(t,r.codec(),n)})(gr||(gr={}));var gs;(function(r){let e;r.codec=()=>(e==null&&(e=Y((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),_e.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=_e.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>q(t,r.codec()),r.decode=(t,n)=>W(t,r.codec(),n)})(gs||(gs={}));function xr(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function qe(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function K(r,e,t=""){let n=xr(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function bn(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");qe(r.outputLen),qe(r.blockLen)}function Wt(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Ua(r,e){K(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function wt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function yn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function $e(r,e){return r<<32-e|r>>>e}var Ma=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ef=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function vt(r){if(K(r),Ma)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Ef[r[t]];return e}var je={_0:48,_9:57,A:65,F:70,a:97,f:102};function ka(r){if(r>=je._0&&r<=je._9)return r-je._0;if(r>=je.A&&r<=je.F)return r-(je.A-10);if(r>=je.a&&r<=je.f)return r-(je.a-10)}function St(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ma)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=ka(r.charCodeAt(s)),a=ka(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ve(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];K(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Ka(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function gn(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var Ha=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function $a(r,e,t){return r&e^~r&t}function Va(r,e,t){return r&e^r&t^e&t}var xn=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=yn(this.buffer)}update(e){Wt(this),K(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=yn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Wt(this),Ua(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,wt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=yn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Je=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var wf=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),lt=new Uint32Array(64),xs=class extends xn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)lt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let p=lt[f-15],d=lt[f-2],g=$e(p,7)^$e(p,18)^p>>>3,w=$e(d,17)^$e(d,19)^d>>>10;lt[f]=w+lt[f-7]+g+lt[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let p=$e(a,6)^$e(a,11)^$e(a,25),d=u+p+$a(a,c,l)+wf[f]+lt[f]|0,w=($e(n,2)^$e(n,13)^$e(n,22))+Va(n,o,s)|0;u=l,l=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){wt(lt)}destroy(){this.set(0,0,0,0,0,0,0,0),wt(this.buffer)}},Es=class extends xs{A=Je[0]|0;B=Je[1]|0;C=Je[2]|0;D=Je[3]|0;E=Je[4]|0;F=Je[5]|0;G=Je[6]|0;H=Je[7]|0;constructor(){super(32)}};var Ga=Ka(()=>new Es,Ha(1));var xc=Te(oe("node:crypto"),1);var vs=BigInt(0),ws=BigInt(1);function Er(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Fa(r){if(typeof r=="bigint"){if(!En(r))throw new Error("positive bigint expected, got "+r)}else qe(r);return r}function wr(r){let e=Fa(r).toString(16);return e.length&1?"0"+e:e}function za(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?vs:BigInt("0x"+r)}function qt(r){return za(vt(r))}function Ss(r){return za(vt(vf(K(r)).reverse()))}function wn(r,e){qe(e),r=Fa(r);let t=St(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Is(r,e){return wn(r,e).reverse()}function vf(r){return Uint8Array.from(r)}var En=r=>typeof r=="bigint"&&vs<=r;function Sf(r,e,t){return En(r)&&En(e)&&En(t)&&e<=r&&r<t}function Wa(r,e,t,n){if(!Sf(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function As(r){let e;for(e=0;r>vs;r>>=ws,e+=1);return e}var vr=r=>(ws<<BigInt(r))-ws;function qa(r,e,t){if(qe(r,"hashLen"),qe(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=b=>new Uint8Array(b),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},p=(...b)=>t(l,Ve(c,...b)),d=(b=o)=>{l=p(s,b),c=p(),b.length!==0&&(l=p(i,b),c=p())},g=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,E=[];for(;b<e;){c=p();let _=c.slice();E.push(_),b+=c.length}return Ve(...E)};return(b,E)=>{f(),d(b);let _;for(;!(_=E(g()));)d();return f(),_}}function Sr(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}function Ls(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var we=BigInt(0),ge=BigInt(1),It=BigInt(2),Xa=BigInt(3),Qa=BigInt(4),ja=BigInt(5),If=BigInt(7),Ja=BigInt(8),Af=BigInt(9),ec=BigInt(16);function Ge(r,e){let t=r%e;return t>=we?t:e+t}function Be(r,e,t){let n=r;for(;e-- >we;)n*=n,n%=t;return n}function Ya(r,e){if(r===we)throw new Error("invert: expected non-zero number");if(e<=we)throw new Error("invert: expected positive modulus, got "+e);let t=Ge(r,e),n=e,o=we,s=ge,i=ge,a=we;for(;t!==we;){let l=n/t,u=n%t,f=o-i*l,p=s-a*l;n=t,t=u,o=i,s=a,i=f,a=p}if(n!==ge)throw new Error("invert: does not exist");return Ge(o,e)}function Ds(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function tc(r,e){let t=(r.ORDER+ge)/Qa,n=r.pow(e,t);return Ds(r,n,e),n}function Lf(r,e){let t=(r.ORDER-ja)/Ja,n=r.mul(e,It),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,It),o),a=r.mul(s,r.sub(i,r.ONE));return Ds(r,a,e),a}function Tf(r){let e=Yt(r),t=rc(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+If)/ec;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,o),p=a.mul(l,s),d=a.eql(a.sqr(u),c),g=a.eql(a.sqr(f),c);l=a.cmov(l,u,d),u=a.cmov(p,f,g);let w=a.eql(a.sqr(u),c),b=a.cmov(l,u,w);return Ds(a,b,c),b}}function rc(r){if(r<Xa)throw new Error("sqrt is not defined for small field");let e=r-ge,t=0;for(;e%It===we;)e/=It,t++;let n=It,o=Yt(r);for(;Za(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return tc;let s=o.pow(n,e),i=(e+ge)/It;return function(c,l){if(c.is0(l))return l;if(Za(c,l)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,s),p=c.pow(l,e),d=c.pow(l,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let g=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(g++,w=c.sqr(w),g===u)throw new Error("Cannot find square root");let b=ge<<BigInt(u-g-1),E=c.pow(f,b);u=g,f=c.sqr(E),p=c.mul(p,f),d=c.mul(d,E)}return d}}function Df(r){return r%Qa===Xa?tc:r%Ja===ja?Lf:r%ec===Af?Tf(r):rc(r)}var Cf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Cs(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Cf.reduce((n,o)=>(n[o]="function",n),e);return Sr(r,t),r}function _f(r,e,t){if(t<we)throw new Error("invalid exponent, negatives unsupported");if(t===we)return r.ONE;if(t===ge)return e;let n=r.ONE,o=e;for(;t>we;)t&ge&&(n=r.mul(n,o)),o=r.sqr(o),t>>=ge;return n}function vn(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Za(r,e){let t=(r.ORDER-ge)/It,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Bf(r,e){e!==void 0&&qe(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var Ts=class{ORDER;BITS;BYTES;isLE;ZERO=we;ONE=ge;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=we)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=Bf(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Ge(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return we<=e&&e<this.ORDER}is0(e){return e===we}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ge)===ge}neg(e){return Ge(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Ge(e*e,this.ORDER)}add(e,t){return Ge(e+t,this.ORDER)}sub(e,t){return Ge(e-t,this.ORDER)}mul(e,t){return Ge(e*t,this.ORDER)}pow(e,t){return _f(this,e,t)}div(e,t){return Ge(e*Ya(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Ya(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Df(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Is(e,this.BYTES):wn(e,this.BYTES)}fromBytes(e,t=!1){K(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Ss(e):qt(e);if(a&&(c=Ge(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return vn(this,e)}cmov(e,t,n){return n?t:e}};function Yt(r,e={}){return new Ts(r,e)}function nc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function _s(r){let e=nc(r);return e+Math.ceil(e/2)}function Bs(r,e,t=!1){K(r);let n=r.length,o=nc(e),s=_s(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Ss(r):qt(r),a=Ge(i,e-ge)+ge;return t?Is(a,o):wn(a,o)}var Zt=BigInt(0),At=BigInt(1);function Ir(r,e){let t=e.negate();return r?t:e}function Ns(r,e){let t=vn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ac(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Os(r,e){ac(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=vr(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function oc(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=At);let l=e*n,u=l+Math.abs(a)-1,f=a===0,p=a<0,d=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:p,isNegF:d,offsetF:l}}var Ps=new WeakMap,cc=new WeakMap;function Rs(r){return cc.get(r)||1}function sc(r){if(r!==Zt)throw new Error("invalid wNAF")}var Sn=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Zt;)t&At&&(n=n.add(o)),o=o.double(),t>>=At;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Os(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Os(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:p,offsetF:d}=oc(n,a,i);n=c,u?s=s.add(Ir(p,t[d])):o=o.add(Ir(f,t[l]))}return sc(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Os(e,this.bits);for(let i=0;i<s.windows&&n!==Zt;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=oc(n,i,s);if(n=a,!l){let f=t[c];o=o.add(u?f.negate():f)}}return sc(n),o}getPrecomputes(e,t,n){let o=Ps.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Ps.set(t,o))),o}cached(e,t,n){let o=Rs(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Rs(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){ac(t,this.bits),cc.set(e,t),Ps.delete(e)}hasCache(e){return Rs(e)!==1}};function uc(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Zt||n>Zt;)t&At&&(s=s.add(o)),n&At&&(i=i.add(o)),o=o.double(),t>>=At,n>>=At;return{p1:s,p2:i}}function ic(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Cs(e),e}else return Yt(r,{isLE:t})}function lc(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Zt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=ic(e.p,t.Fp,n),s=ic(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function fc(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var In=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(bn(e),K(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),wt(o)}update(e){return Wt(this),this.iHash.update(e),this}digestInto(e){Wt(this),K(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ks=(r,e,t)=>new In(r,e).update(t).digest();ks.create=(r,e)=>new In(r,e);var dc=(r,e)=>(r+(r>=0?e:-e)/hc)/e;function Of(r,e,t){let[[n,o],[s,i]]=e,a=dc(i*r,t),c=dc(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,f=l<et,p=u<et;f&&(l=-l),p&&(u=-u);let d=vr(Math.ceil(As(t)/2))+Xt;if(l<et||l>=d||u<et||u>=d)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:p,k2:u}}function Ms(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Us(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Er(t.lowS,"lowS"),Er(t.prehash,"prehash"),t.format!==void 0&&Ms(t.format),t}var Ks=class extends Error{constructor(e=""){super(e)}},ft={Err:Ks,_tlv:{encode:(r,e)=>{let{Err:t}=ft;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=wr(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?wr(o.length/2|128):"";return wr(r)+s+o+e},decode(r,e){let{Err:t}=ft,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=ft;if(r<et)throw new e("integer: negative integers are not allowed");let t=wr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=ft;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return qt(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=ft,o=K(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=ft,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},et=BigInt(0),Xt=BigInt(1),hc=BigInt(2),An=BigInt(3),Pf=BigInt(4);function pc(r,e={}){let t=lc("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Sr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=bc(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(M,y,m){let{x:h,y:x}=y.toAffine(),S=n.toBytes(h);if(Er(m,"isCompressed"),m){u();let L=!n.isOdd(x);return Ve(mc(L),S)}else return Ve(Uint8Array.of(4),S,n.toBytes(x))}function p(M){K(M,void 0,"Point");let{publicKey:y,publicKeyUncompressed:m}=l,h=M.length,x=M[0],S=M.subarray(1);if(h===y&&(x===2||x===3)){let L=n.fromBytes(S);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let A=w(L),v;try{v=n.sqrt(A)}catch(ne){let F=ne instanceof Error?": "+ne.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}u();let T=n.isOdd(v);return(x&1)===1!==T&&(v=n.neg(v)),{x:L,y:v}}else if(h===m&&x===4){let L=n.BYTES,A=n.fromBytes(S.subarray(0,L)),v=n.fromBytes(S.subarray(L,L*2));if(!b(A,v))throw new Error("bad point: is not on curve");return{x:A,y:v}}else throw new Error(`bad point: got length ${h}, expected compressed=${y} or uncompressed=${m}`)}let d=e.toBytes||f,g=e.fromBytes||p;function w(M){let y=n.sqr(M),m=n.mul(y,M);return n.add(n.add(m,n.mul(M,s.a)),s.b)}function b(M,y){let m=n.sqr(y),h=w(M);return n.eql(m,h)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(s.a,An),Pf),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(E,_)))throw new Error("bad curve params: a or b");function P(M,y,m=!1){if(!n.isValid(y)||m&&n.is0(y))throw new Error(`bad point coordinate ${M}`);return y}function N(M){if(!(M instanceof C))throw new Error("Weierstrass Point expected")}function $(M){if(!c||!c.basises)throw new Error("no endo");return Of(M,c.basises,o.ORDER)}let ie=Ls((M,y)=>{let{X:m,Y:h,Z:x}=M;if(n.eql(x,n.ONE))return{x:m,y:h};let S=M.is0();y==null&&(y=S?n.ONE:n.inv(x));let L=n.mul(m,y),A=n.mul(h,y),v=n.mul(x,y);if(S)return{x:n.ZERO,y:n.ZERO};if(!n.eql(v,n.ONE))throw new Error("invZ was invalid");return{x:L,y:A}}),re=Ls(M=>{if(M.is0()){if(e.allowInfinityPoint&&!n.is0(M.Y))return;throw new Error("bad point: ZERO")}let{x:y,y:m}=M.toAffine();if(!n.isValid(y)||!n.isValid(m))throw new Error("bad point: x or y not field elements");if(!b(y,m))throw new Error("bad point: equation left != right");if(!M.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function le(M,y,m,h,x){return m=new C(n.mul(m.X,M),m.Y,m.Z),y=Ir(h,y),m=Ir(x,m),y.add(m)}class C{static BASE=new C(s.Gx,s.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(y,m,h){this.X=P("x",y),this.Y=P("y",m,!0),this.Z=P("z",h),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){let{x:m,y:h}=y||{};if(!y||!n.isValid(m)||!n.isValid(h))throw new Error("invalid affine point");if(y instanceof C)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(h)?C.ZERO:new C(m,h,n.ONE)}static fromBytes(y){let m=C.fromAffine(g(K(y,void 0,"point")));return m.assertValidity(),m}static fromHex(y){return C.fromBytes(St(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,m=!0){return ht.createCache(this,y),m||this.multiply(An),this}assertValidity(){re(this)}hasEvenY(){let{y}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(y)}equals(y){N(y);let{X:m,Y:h,Z:x}=this,{X:S,Y:L,Z:A}=y,v=n.eql(n.mul(m,A),n.mul(S,x)),T=n.eql(n.mul(h,A),n.mul(L,x));return v&&T}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:y,b:m}=s,h=n.mul(m,An),{X:x,Y:S,Z:L}=this,A=n.ZERO,v=n.ZERO,T=n.ZERO,D=n.mul(x,x),ne=n.mul(S,S),F=n.mul(L,L),O=n.mul(x,S);return O=n.add(O,O),T=n.mul(x,L),T=n.add(T,T),A=n.mul(y,T),v=n.mul(h,F),v=n.add(A,v),A=n.sub(ne,v),v=n.add(ne,v),v=n.mul(A,v),A=n.mul(O,A),T=n.mul(h,T),F=n.mul(y,F),O=n.sub(D,F),O=n.mul(y,O),O=n.add(O,T),T=n.add(D,D),D=n.add(T,D),D=n.add(D,F),D=n.mul(D,O),v=n.add(v,D),F=n.mul(S,L),F=n.add(F,F),D=n.mul(F,O),A=n.sub(A,D),T=n.mul(F,ne),T=n.add(T,T),T=n.add(T,T),new C(A,v,T)}add(y){N(y);let{X:m,Y:h,Z:x}=this,{X:S,Y:L,Z:A}=y,v=n.ZERO,T=n.ZERO,D=n.ZERO,ne=s.a,F=n.mul(s.b,An),O=n.mul(m,S),X=n.mul(h,L),fe=n.mul(x,A),Fe=n.add(m,h),Q=n.add(S,L);Fe=n.mul(Fe,Q),Q=n.add(O,X),Fe=n.sub(Fe,Q),Q=n.add(m,x);let pe=n.add(S,A);return Q=n.mul(Q,pe),pe=n.add(O,fe),Q=n.sub(Q,pe),pe=n.add(h,x),v=n.add(L,A),pe=n.mul(pe,v),v=n.add(X,fe),pe=n.sub(pe,v),D=n.mul(ne,Q),v=n.mul(F,fe),D=n.add(v,D),v=n.sub(X,D),D=n.add(X,D),T=n.mul(v,D),X=n.add(O,O),X=n.add(X,O),fe=n.mul(ne,fe),Q=n.mul(F,Q),X=n.add(X,fe),fe=n.sub(O,fe),fe=n.mul(ne,fe),Q=n.add(Q,fe),O=n.mul(X,Q),T=n.add(T,O),O=n.mul(pe,Q),v=n.mul(Fe,v),v=n.sub(v,O),O=n.mul(Fe,X),D=n.mul(pe,D),D=n.add(D,O),new C(v,T,D)}subtract(y){return this.add(y.negate())}is0(){return this.equals(C.ZERO)}multiply(y){let{endo:m}=e;if(!o.isValidNot0(y))throw new Error("invalid scalar: out of range");let h,x,S=L=>ht.cached(this,L,A=>Ns(C,A));if(m){let{k1neg:L,k1:A,k2neg:v,k2:T}=$(y),{p:D,f:ne}=S(A),{p:F,f:O}=S(T);x=ne.add(O),h=le(m.beta,D,F,L,v)}else{let{p:L,f:A}=S(y);h=L,x=A}return Ns(C,[h,x])[0]}multiplyUnsafe(y){let{endo:m}=e,h=this;if(!o.isValid(y))throw new Error("invalid scalar: out of range");if(y===et||h.is0())return C.ZERO;if(y===Xt)return h;if(ht.hasCache(this))return this.multiply(y);if(m){let{k1neg:x,k1:S,k2neg:L,k2:A}=$(y),{p1:v,p2:T}=uc(C,h,S,A);return le(m.beta,v,T,x,L)}else return ht.unsafe(h,y)}toAffine(y){return ie(this,y)}isTorsionFree(){let{isTorsionFree:y}=e;return i===Xt?!0:y?y(C,this):ht.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:y}=e;return i===Xt?this:y?y(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(y=!0){return Er(y,"isCompressed"),this.assertValidity(),d(C,this,y)}toHex(y=!0){return vt(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Ot=o.BITS,ht=new Sn(C,e.endo?Math.ceil(Ot/2):Ot);return C.BASE.precompute(8),C}function mc(r){return Uint8Array.of(r?2:3)}function bc(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Rf(r,e={}){let{Fn:t}=r,n=e.randomBytes||gn,o=Object.assign(bc(r.Fp,t),{seed:_s(t.ORDER)});function s(d){try{let g=t.fromBytes(d);return t.isValidNot0(g)}catch{return!1}}function i(d,g){let{publicKey:w,publicKeyUncompressed:b}=o;try{let E=d.length;return g===!0&&E!==w||g===!1&&E!==b?!1:!!r.fromBytes(d)}catch{return!1}}function a(d=n(o.seed)){return Bs(K(d,o.seed,"seed"),t.ORDER)}function c(d,g=!0){return r.BASE.multiply(t.fromBytes(d)).toBytes(g)}function l(d){let{secretKey:g,publicKey:w,publicKeyUncompressed:b}=o;if(!xr(d)||"_lengths"in t&&t._lengths||g===w)return;let E=K(d,void 0,"key").length;return E===w||E===b}function u(d,g,w=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(g)===!1)throw new Error("second arg must be public key");let b=t.fromBytes(d);return r.fromBytes(g).multiply(b).toBytes(w)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},p=fc(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:r,utils:f,lengths:o})}function yc(r,e,t={}){bn(e),Sr(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||gn,o=t.hmac||((m,h)=>ks(e,m,h)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:p,lengths:d}=Rf(r,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},w=a*hc<s.ORDER;function b(m){let h=a>>Xt;return m>h}function E(m,h){if(!i.isValidNot0(h))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return h}function _(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(m,h){Ms(h);let x=d.signature,S=h==="compact"?x:h==="recovered"?x+1:void 0;return K(m,S)}class N{r;s;recovery;constructor(h,x,S){if(this.r=E("r",h),this.s=E("s",x),S!=null){if(_(),![0,1,2,3].includes(S))throw new Error("invalid recovery id");this.recovery=S}Object.freeze(this)}static fromBytes(h,x=g.format){P(h,x);let S;if(x==="der"){let{r:T,s:D}=ft.toSig(K(h));return new N(T,D)}x==="recovered"&&(S=h[0],x="compact",h=h.subarray(1));let L=d.signature/2,A=h.subarray(0,L),v=h.subarray(L,L*2);return new N(i.fromBytes(A),i.fromBytes(v),S)}static fromHex(h,x){return this.fromBytes(St(h),x)}assertRecovery(){let{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new N(this.r,this.s,h)}recoverPublicKey(h){let{r:x,s:S}=this,L=this.assertRecovery(),A=L===2||L===3?x+a:x;if(!s.isValid(A))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let v=s.toBytes(A),T=r.fromBytes(Ve(mc((L&1)===0),v)),D=i.inv(A),ne=ie(K(h,void 0,"msgHash")),F=i.create(-ne*D),O=i.create(S*D),X=r.BASE.multiplyUnsafe(F).add(T.multiplyUnsafe(O));if(X.is0())throw new Error("invalid recovery: point at infinify");return X.assertValidity(),X}hasHighS(){return b(this.s)}toBytes(h=g.format){if(Ms(h),h==="der")return St(ft.hexFromSig(this));let{r:x,s:S}=this,L=i.toBytes(x),A=i.toBytes(S);return h==="recovered"?(_(),Ve(Uint8Array.of(this.assertRecovery()),L,A)):Ve(L,A)}toHex(h){return vt(this.toBytes(h))}}let $=t.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");let x=qt(h),S=h.length*8-c;return S>0?x>>BigInt(S):x},ie=t.bits2int_modN||function(h){return i.create($(h))},re=vr(c);function le(m){return Wa("num < 2^"+c,m,et,re),i.toBytes(m)}function C(m,h){return K(m,void 0,"message"),h?K(e(m),void 0,"prehashed message"):m}function Ot(m,h,x){let{lowS:S,prehash:L,extraEntropy:A}=Us(x,g);m=C(m,L);let v=ie(m),T=i.fromBytes(h);if(!i.isValidNot0(T))throw new Error("invalid private key");let D=[le(T),le(v)];if(A!=null&&A!==!1){let X=A===!0?n(d.secretKey):A;D.push(K(X,void 0,"extraEntropy"))}let ne=Ve(...D),F=v;function O(X){let fe=$(X);if(!i.isValidNot0(fe))return;let Fe=i.inv(fe),Q=r.BASE.multiply(fe).toAffine(),pe=i.create(Q.x);if(pe===et)return;let Or=i.create(Fe*i.create(F+pe*T));if(Or===et)return;let Ci=(Q.x===pe?0:2)|Number(Q.y&Xt),_i=Or;return S&&b(Or)&&(_i=i.neg(Or),Ci^=1),new N(pe,_i,w?void 0:Ci)}return{seed:ne,k2sig:O}}function ht(m,h,x={}){let{seed:S,k2sig:L}=Ot(m,h,x);return qa(e.outputLen,i.BYTES,o)(S,L).toBytes(x.format)}function M(m,h,x,S={}){let{lowS:L,prehash:A,format:v}=Us(S,g);if(x=K(x,void 0,"publicKey"),h=C(h,A),!xr(m)){let T=m instanceof N?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}P(m,v);try{let T=N.fromBytes(m,v),D=r.fromBytes(x);if(L&&T.hasHighS())return!1;let{r:ne,s:F}=T,O=ie(h),X=i.inv(F),fe=i.create(O*X),Fe=i.create(ne*X),Q=r.BASE.multiplyUnsafe(fe).add(D.multiplyUnsafe(Fe));return Q.is0()?!1:i.create(Q.x)===ne}catch{return!1}}function y(m,h,x={}){let{prehash:S}=Us(x,g);return h=C(h,S),N.fromBytes(m,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:p,lengths:d,Point:r,sign:ht,verify:M,recoverPublicKey:y,Signature:N,hash:e})}var $s={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Nf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var gc=BigInt(2);function kf(r){let e=$s.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=Be(u,t,e)*u%e,p=Be(f,t,e)*u%e,d=Be(p,gc,e)*l%e,g=Be(d,o,e)*d%e,w=Be(g,s,e)*g%e,b=Be(w,a,e)*w%e,E=Be(b,c,e)*b%e,_=Be(E,a,e)*w%e,P=Be(_,t,e)*u%e,N=Be(P,i,e)*g%e,$=Be(N,n,e)*l%e,ie=Be($,gc,e);if(!Hs.eql(Hs.sqr(ie),r))throw new Error("Cannot find square root");return ie}var Hs=Yt($s.p,{sqrt:kf}),Uf=pc($s,{Fp:Hs,endo:Nf}),Ar=yc(Uf,Ga);var Ln=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function Ec(r,e,t,n){n?.signal?.throwIfAborted();let o=xc.default.createHash("sha256");if(t instanceof Uint8Array)o.update(t);else for(let i of t)o.update(i);let s=o.digest();try{return Ar.verify(e,s,r,{prehash:!1,format:"der"})}catch(i){throw new Ln(String(i))}}var Tn=class{type="secp256k1";raw;_key;constructor(e){this._key=vc(e),this.raw=wc(this._key)}toMultihash(){return Ke.digest(ut(this))}toCID(){return se.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ce(this.raw,e.raw)}verify(e,t,n){return Ec(this._key,t,e,n)}};function Sc(r){return new Tn(r)}function wc(r){return Ar.Point.fromBytes(r).toBytes()}function vc(r){try{return Ar.Point.fromBytes(r),r}catch(e){throw new rn(String(e))}}function Ic(r){let{Type:e,Data:t}=gr.decode(r.digest),n=t??new Uint8Array;switch(e){case _e.Ed25519:return Na(n);case _e.secp256k1:return Sc(n);case _e.ECDSA:return Ca(n);default:throw new pr}}function ut(r){return gr.encode({Type:_e[r.type],Data:r.raw})}var Ac=Symbol.for("nodejs.util.inspect.custom"),Mf=114,Lr=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[us]=!0;toString(){return this.string==null&&(this.string=J.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return se.createV1(Mf,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ce(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ce(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ac](){return`PeerId(${this.toString()})`}},Dn=class extends Lr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Cn=class extends Lr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},_n=class extends Lr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Kf=2336,Bn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ke.digest(ye(this.url))}[Ac](){return`PeerId(${this.url})`}[us]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return se.createV1(Kf,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=te(e)),e.toString()===this.toString())}};function Qt(r){if($f(r))return new Dn({multihash:r});if(Hf(r))try{let e=Ic(r);if(e.type==="Ed25519")return new Cn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new _n({multihash:r,publicKey:e})}catch{let t=te(r.digest);return new Bn(new URL(t))}throw new on("Supplied PeerID Multihash is invalid")}function Hf(r){return r.code===Ke.code}function $f(r){return r.code===Qo.code}var uu=Te(oe("net"),1);var he=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},tt=class extends Error{static name="ValidationError";name="ValidationError"},On=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Pn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Oe=oe("node:net");function Gs(r){return e=>te(e,r)}function Fs(r){return e=>ye(e,r)}function jt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Lt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Lc(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=ye(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Lt(n);return We([t,o],t.length+o.length)}function Tc(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=ze.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=Lt(n);return We([t,o],t.length+o.length)}function zs(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=te(e,"base32"),o=jt(t);return`${n}:${o}`}var Ws=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new he("Invalid byte value in IP address");e[n]=o}),e},Dc=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=(0,Oe.isIPv4)(t[n]),i;s&&(i=Ws(t[n]),t[n]=te(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,te(i.subarray(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++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new he("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Cc=function(r){if(r.byteLength!==4)throw new he("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},_c=function(r){if(r.byteLength!==16)throw new he("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new he(`Invalid IPv6 address "${t}"`)}};function Bc(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new he(`Invalid IPv6 address "${r}"`)}}var Vs=Object.values(cr).map(r=>r.decoder),Vf=(function(){let r=Vs[0].or(Vs[1]);return Vs.slice(2).forEach(e=>r=r.or(e)),r})();function Oc(r){return Vf.decode(r)}function Pc(r){return e=>r.encoder.encode(e)}function Gf(r){if(parseInt(r).toString()!==r)throw new tt("Value must be an integer")}function Ff(r){if(r<0)throw new tt("Value must be a positive integer, or zero")}function zf(r){return e=>{if(e>r)throw new tt(`Value must be smaller than or equal to ${r}`)}}function Wf(...r){return e=>{for(let t of r)t(e)}}var Tr=Wf(Gf,Ff,zf(65535));var ce=-1,qs=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Pn(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},rt=new qs,ad=[{code:4,name:"ip4",size:32,valueToBytes:Ws,bytesToValue:Cc,validate:r=>{if(!(0,Oe.isIPv4)(r))throw new tt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Lt,bytesToValue:jt,validate:Tr},{code:273,name:"udp",size:16,valueToBytes:Lt,bytesToValue:jt,validate:Tr},{code:33,name:"dccp",size:16,valueToBytes:Lt,bytesToValue:jt,validate:Tr},{code:41,name:"ip6",size:128,valueToBytes:Dc,bytesToValue:_c,stringToValue:Bc,validate:r=>{if(!(0,Oe.isIPv6)(r))throw new tt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ce},{code:43,name:"ipcidr",size:8,bytesToValue:Gs("base10"),valueToBytes:Fs("base10")},{code:53,name:"dns",size:ce},{code:54,name:"dns4",size:ce},{code:55,name:"dns6",size:ce},{code:56,name:"dnsaddr",size:ce},{code:132,name:"sctp",size:16,valueToBytes:Lt,bytesToValue:jt,validate:Tr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ce,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ce,bytesToValue:Gs("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Fs("base58btc")(r):se.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:zs,valueToBytes:Lc},{code:445,name:"onion3",size:296,bytesToValue:zs,valueToBytes:Tc},{code:446,name:"garlic64",size:ce},{code:447,name:"garlic32",size:ce},{code:448,name:"tls"},{code:449,name:"sni",size:ce},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ce,bytesToValue:Pc(Vo),valueToBytes:Oc},{code:480,name:"http"},{code:481,name:"http-path",size:ce,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ce}];ad.forEach(r=>{rt.addProtocol(r)});function Rc(r){let e=[],t=0;for(;t<r.length;){let n=mt(r,t),o=rt.getProtocol(n),s=ae(n),i=cd(o,r,t+s),a=0;i>0&&o.size===ce&&(a=ae(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??te(f)}e.push(l),t+=c}return e}function Nc(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=rt.getProtocol(n.code),s=ae(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??ye(n.value),a=i.byteLength,o.size===ce&&(c=ae(a)));let l=new Uint8Array(s+c+a),u=0;Pt(n.code,l,u),u+=s,i!=null&&(o.size===ce&&(Pt(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return We(t,e)}function kc(r){if(r.charAt(0)!=="/")throw new he('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=rt.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new he(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new he(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new he("Incomplete multiaddr");return e}function Uc(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=rt.getProtocol(e.code);if(t==null)throw new he(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function cd(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:mt(e,t)}var ud=Symbol.for("nodejs.util.inspect.custom"),ii=Symbol.for("@multiformats/multiaddr");function ld(r){if(r==null&&(r="/"),Mc(r))return r.getComponents();if(r instanceof Uint8Array)return Rc(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),kc(r);if(Array.isArray(r))return r;throw new he("Must be a string, Uint8Array, Component[], or another Multiaddr")}var $n=class r{[ii]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=ld(e),t.validate!==!1&&fd(this)}get bytes(){return this.#r==null&&(this.#r=Nc(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Uc(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new On(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Ce(this.bytes,e.bytes)}[ud](){return`Multiaddr(${this.toString()})`}};function fd(r){r.getComponents().forEach(e=>{let t=rt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Mc(r){return!!r?.[ii]}function Ye(r){return new $n(r)}var V=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),I=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Kc=r=>({match:e=>r.match(e)===!1?e:!1}),B=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),xe=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),U=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function G(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var dd=I(421),My=G(dd),Gn=I(54),Fn=I(55),zn=I(56),ci=I(53),Ky=G(Gn,B(I(421))),Hy=G(Fn,B(I(421))),$y=G(zn,B(I(421))),Vy=G(xe(ci,zn,Gn,Fn),B(I(421))),Hc=U(I(4),B(I(43))),$c=U(B(I(42)),I(41),B(I(43))),ui=xe(Hc,$c),Ct=xe(ui,ci,Gn,Fn,zn),Gy=G(xe(ui,U(xe(ci,zn,Gn,Fn),B(I(421))))),Fy=G(Hc),zy=G($c),Wy=G(ui),li=U(Ct,I(6)),Cr=U(Ct,I(273)),Vc=G(U(li,B(I(421)))),qy=G(Cr),fi=U(Cr,V(460),B(I(421))),Wn=U(Cr,V(461),B(I(421))),hd=xe(fi,Wn),Yy=G(fi),Zy=G(Wn),ai=xe(Ct,li,Cr,fi,Wn),Gc=xe(U(ai,V(477),B(I(421)))),Xy=G(Gc),Fc=xe(U(ai,V(478),B(I(421))),U(ai,V(448),B(I(449)),V(477),B(I(421)))),Qy=G(Fc),zc=U(Cr,V(280),B(I(466)),B(I(466)),B(I(421))),jy=G(zc),Wc=U(Wn,V(465),B(I(466)),B(I(466)),B(I(421))),Jy=G(Wc),Vn=xe(Gc,Fc,U(li,B(I(421))),U(hd,B(I(421))),U(Ct,B(I(421))),zc,Wc,I(421)),eg=G(Vn),pd=U(B(Vn),V(290),Kc(V(281)),B(I(421))),tg=G(pd),md=xe(U(Vn,V(290),V(281),B(I(421))),U(Vn,V(281),B(I(421))),U(V(281),B(I(421)))),rg=G(md),bd=xe(U(Ct,I(6),V(480),B(I(421))),U(Ct,V(480),B(I(421)))),ng=G(bd),yd=U(Ct,xe(U(I(6,"443"),V(480)),U(I(6),V(443)),U(I(6),V(448),V(480)),U(V(448),V(480)),V(448),V(443)),B(I(421))),og=G(yd),gd=xe(U(I(777),B(I(421)))),sg=G(gd),xd=xe(U(I(400),B(I(421)))),qn=G(xd);var Yn=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var cu=Te(oe("node:net"),1);function Zn(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new Z(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}function nt(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Xn=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},rr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Xn(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Xn(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var di=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function dt(r={}){return Ed(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ed(r,e){e=e??{};let t=e.onEnd,n=new rr,o,s,i,a=nt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((b,E)=>{s=_=>{s=null,n.push(_);try{b(r(n))}catch(P){E(P)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=nt()})}},l=b=>s!=null?s(b):(n.push(b),o),u=b=>(n=new rr,s!=null?s({error:b}):(n.push({error:b}),o)),f=b=>{if(i)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},p=b=>i?o:(i=!0,b!=null?u(b):l({done:!0})),d=()=>(n=new rr,p(),{done:!0}),g=b=>(p(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:g,push:f,end:p,get readableLength(){return n.size},onEmpty:async b=>{let E=b?.signal;if(E?.throwIfAborted(),n.isEmpty())return;let _,P;E!=null&&(_=new Promise((N,$)=>{P=()=>{$(new di)},E.addEventListener("abort",P)}));try{await Promise.race([a.promise,_])}finally{P!=null&&E!=null&&E?.removeEventListener("abort",P)}}},t==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(b){return w.throw(b),t!=null&&(t(b),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(b){return w.end(b),t!=null&&(t(b),t=void 0),o},get readableLength(){return w.readableLength},onEmpty:b=>w.onEmpty(b)},o}var hi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},pi=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},qc=r=>globalThis.DOMException===void 0?new pi(r):new DOMException(r),Yc=r=>{let e=r.reason===void 0?qc("This operation was aborted."):r.reason;return e instanceof Error?e:qc(e)};function mi(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,f)=>{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:d}=e;d.aborted&&f(Yc(d)),a=()=>{f(Yc(d))},d.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let p=new hi;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(p.message=o??`Promise timed out after ${t} milliseconds`,f(p))},t),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var wd=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 vd(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!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(),c=[],{addListener:l,removeListener:u}=wd(r),f=async(...d)=>{let g=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(g))return}catch(w){n(),i(w);return}c.push(g),t.count===c.length&&(n(),s(c))},p=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,f);for(let d of t.rejectionEvents)a.includes(d)||u(d,p)};for(let d of a)l(d,f);for(let d of t.rejectionEvents)a.includes(d)||l(d,p);t.signal&&t.signal.addEventListener("abort",()=>{p(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=mi(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Pe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=vd(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var _t=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var Qn=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Sd(r){return r.reason}async function jn(r,e,t){if(e==null)return r;let n=t?.translateError??Sd;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Id=Math.pow(2,20)*4,Jn=class extends Ft{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Id,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new H,this.writeBuffer=new H,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new Qn)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),jn(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=dt(),t=s=>{e.push(s.data)};this.addEventListener("message",t);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new ct(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new un(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ct("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ct("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ct(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ct(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new nn;this.dispatchEvent(new ln(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Gt))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new H(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new cn(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new hr(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new hr(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var eo=class extends Jn{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Pe(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Pe(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};var Xc=Te(oe("node:os"),1);function Zc(r){return!!(r.startsWith("169.254.")||r.toLowerCase().startsWith("fe80"))}function bi(r,e,t){let n=[r.type,t??r.host];if(r.protocol!=null){let o=e??r.port;o!=null&&n.push(r.protocol,o)}return r.type==="ip6"&&r.zone!=null&&n.unshift("ip6zone",r.zone),r.cidr!=null&&n.push("ipcidr",r.cidr),Ye(`/${n.join("/")}`)}var Ad={4:"IPv4",6:"IPv6"};function Ld(r){return["0.0.0.0","::"].includes(r)}function Td(r){let e=[],t=Xc.default.networkInterfaces();for(let[,n]of Object.entries(t))if(n!=null)for(let o of n)Zc(o.address)||o.family===Ad[r]&&e.push(o.address);return e}function Qc(r,e){if(r==null)return[];let t=Zn(r);return(t.type==="ip4"||t.type==="ip6")&&Ld(t.host)?Td(t.type==="ip4"?4:6).map(n=>bi(t,e,n)):[bi(t,e)]}function jc(r,e){if(typeof r!="string")throw new Z(`invalid ip provided: ${r}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new Z(`invalid port provided: ${e}`);if((0,Oe.isIPv4)(r))return Ye(`/ip4/${r}/tcp/${e}`);if((0,Oe.isIPv6)(r))return Ye(`/ip6/${r}/tcp/${e}`);throw new Z(`invalid ip:port for creating a multiaddr: ${r}:${e}`)}var to=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Jc(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new to(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new to(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var yi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=nt(),this.haveNext=nt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=nt(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=nt(),await Jc(this.readNext.promise,t?.signal,t)}};function eu(){return new yi}function Dd(r){return r[Symbol.asyncIterator]!=null}async function Cd(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*_d(r){let e=new AbortController,t=eu();Cd(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Bd(r){for(let e of r)yield*e}function Od(...r){let e=[];for(let t of r)Dd(t)||e.push(t);return e.length===r.length?Bd(e):_d(r)}var tu=Od;function ru(r,...e){if(r==null)throw new Error("Empty pipeline");if(gi(r)){let n=r;r=()=>n.source}else if(ou(r)||nu(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&gi(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)gi(t[n])&&(t[n]=Rd(t[n]));return Pd(...t)}var Pd=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},nu=r=>r?.[Symbol.asyncIterator]!=null,ou=r=>r?.[Symbol.iterator]!=null,gi=r=>r==null?!1:r.sink!=null&&r.source!=null,Rd=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=dt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(nu(s))o=async function*(){yield*s,n.end()};else if(ou(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return tu(n,o())}return r.source};var Nd=4194304,ro=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ei=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},wi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},vi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function kd(r){return typeof r?.closeRead=="function"}function Ud(r){return typeof r?.close=="function"}function xi(r){return kd(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Ud(r)?r.status!=="open":!1}function Md(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Kd(r,e){let t=e?.maxBufferSize??Nd,n=new H,o,s=!1;if(!Md(r))throw new Z("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new ro("Stream was unwrapped");if(xi(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new _t(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await jn(o.promise,u?.signal),xi(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(xi(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,p),new _t(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return l.read(u)}let d=n.sublist(0,p);return n.consume(p),d},async write(u,f){if(s===!0)throw new ro("Stream was unwrapped");r.send(u)||await Pe(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function _r(r,e={}){let t=Kd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ae(e.maxDataLength));let n=e?.lengthDecoder??mt,o=e?.lengthEncoder??Rr;return{async read(i){let a=-1,c=new H;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new Ei("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new vi(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new wi(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new _t(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new _t(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new H(o(i.byteLength),i),a)},async writeV(i,a){let c=new H(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Si(r,e){let t=_r(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function Hd(r){return r?.addEventListener!=null}function $d(r){let e=dt(),t,n=i=>{e.push(i.data)},o=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",s),r.removeEventListener("remoteCloseWrite",o)},s=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",s),r.removeEventListener("remoteCloseWrite",o)};return r.addEventListener("message",n),r.addEventListener("close",s,{once:!0}),r.addEventListener("remoteCloseWrite",o,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:l,value:u}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(u!=null&&(r.send(u)||await Promise.race([Pe(r,"drain",{rejectionEvents:["close"]})])),l===!0))break}await r.close()}}}function Ii(...r){let e=r.map(t=>Hd(t)?$d(t):t);return ru(...e)}var no=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},nr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},oo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Br=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function so(r){return r[Symbol.asyncIterator]!=null}function su(r,e){if(r.byteLength>e)throw new nr("Message length too long")}var ao=r=>{let e=ae(r),t=Se(e);return Rr(r,t),ao.bytes=e,t};ao.bytes=0;function co(r,e){e=e??{};let t=e.lengthEncoder??ao,n=e?.maxDataLength??4194304;function*o(s){su(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return so(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}co.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ao,n=e?.maxDataLength??4194304;return su(r,n),new H(t(r.byteLength),r)};var Bt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Bt||(Bt={}));var Li=r=>{let e=mt(r);return Li.bytes=ae(e),e};Li.bytes=0;function Ai(r,e){let t=new H,n=Bt.LENGTH,o=-1,s=e?.lengthDecoder??Li,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Bt.LENGTH)try{if(o=s(t),o<0)throw new no("Invalid message length");if(o>a)throw new nr("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=Bt.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new oo("Message length length too long");break}throw l}if(n===Bt.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=Bt.LENGTH}}}return so(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Br("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Br("Unexpected end of input")})()}Ai.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Ai(n,{...e??{},onLength:s=>{t=s}})};var Ti=class extends eo{socket;constructor(e){let t=e.remoteAddr;if(e.localAddr!=null&&qn.matches(e.localAddr))t=e.localAddr;else if(t==null){if(e.socket.remoteAddress==null||e.socket.remotePort==null)throw new Z("Could not determine remote address or port");t=jc(e.socket.remoteAddress,e.socket.remotePort)}super({...e,remoteAddr:t}),this.socket=e.socket,this.socket.on("data",n=>{this.onData(n)}),this.socket.on("error",n=>{this.log("tcp error",t,n),this.abort(n)}),this.socket.setTimeout(e.inactivityTimeout??120*1e3),this.socket.once("timeout",()=>{this.log("tcp timeout",t),this.abort(new Vt)}),this.socket.once("end",()=>{this.log("tcp end",t),this.onTransportClosed()}),this.socket.once("close",n=>{if(this.log("tcp close",t),n){this.abort(new Error("TCP transmission error"));return}this.onTransportClosed()}),this.socket.on("drain",()=>{this.log("tcp drain"),this.safeDispatchEvent("drain")})}sendData(e){let t=0,n=!0;for(let o of e)if(t+=o.byteLength,n=this.socket.write(o),!n)break;return{sentBytes:t,canSendMore:n}}async sendClose(e){this.socket.destroyed||(this.socket.destroySoon(),await Pe(this.socket,"close",e))}sendReset(){this.socket.resetAndDestroy()}sendPause(){this.socket.pause()}sendResume(){this.socket.resume()}},uo=r=>new Ti(r);var iu=Te(oe("os"),1),au=Te(oe("path"),1);function lo(r,e={}){if(qn.exactMatch(r)){let s=r.getComponents().find(i=>i.code===400)?.value;if(s==null)throw new Z(`Multiaddr ${r} was not a Unix address`);return iu.default.platform()==="win32"?{path:au.default.join("\\\\.\\pipe\\",s)}:{path:s}}let t=Zn(r),n=t.host,o=t.port;return{host:n,port:o,ipv6Only:t.type==="ip6",...e}}var ue;(function(r){r[r.INACTIVE=0]="INACTIVE",r[r.ACTIVE=1]="ACTIVE",r[r.PAUSED=2]="PAUSED"})(ue||(ue={}));var fo=class extends Ft{context;server;sockets=new Set;status={code:ue.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,e.allowHalfOpen=e.allowHalfOpen??!1,this.shutdownController=new AbortController,fn(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=cu.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 Z("closeAbove must be >= listenBelow");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.server.on("listening",()=>{let t=this.server.address();t==null?this.addr="unknown":typeof t=="string"?this.addr=t:this.addr=`${t.address}:${t.port}`,this.metrics.status?.update({[this.addr]:ue.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!==ue.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!==ue.ACTIVE)throw e.destroy(),new sn("Server is not listening yet");let t;try{t=uo({socket:e,inactivityTimeout:this.context.inactivityTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,direction:"inbound",localAddr:this.status.listeningAddr,log:this.context.logger.forComponent("libp2p:tcp:connection")})}catch(n){this.log.error("inbound connection failed - %e",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 - %e",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&(this.log("pausing incoming connections as limit is exceeded - %d/%d",this.sockets.size,this.context.closeServerOnMaxConnections.closeAbove),this.pause())}).catch(async n=>{this.log.error("inbound connection upgrade failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),t.abort(n)})}getAddrs(){if(this.status.code===ue.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[Ye(`/unix/${encodeURIComponent(e)}`)]:Qc(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===ue.ACTIVE||this.status.code===ue.PAUSED)throw new an("server is already listening");try{this.status={code:ue.ACTIVE,listeningAddr:e,netConfig:lo(e,this.context)},await this.resume()}catch(t){throw this.status={code:ue.INACTIVE},t}}async close(e){let t=[];this.server.listening&&t.push(Pe(this.server,"close",e)),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(n=>{n.readable&&(t.push(Pe(n,"close",e)),n.destroy())}),await Promise.all(t)}async resume(){if(this.server.listening||this.status.code===ue.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:ue.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===ue.PAUSED&&e){this.status={code:ue.INACTIVE};return}!this.server.listening||this.status.code!==ue.ACTIVE||(this.log("%s server on %s",e?"closing":"pausing",this.server.address()),this.status=e?{code:ue.INACTIVE}:{...this.status,code:ue.PAUSED},this.server.close())}};var ho=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"})})}[ga]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Ea]=["@libp2p/transport"];async dial(e,t){t.keepAlive=t.keepAlive??!0,t.noDelay=t.noDelay??!0,t.allowHalfOpen=t.allowHalfOpen??!1;let n=await this._connect(e,t),o;try{o=uo({socket:n,inactivityTimeout:this.opts.outboundSocketInactivityTimeout,metrics:this.metrics?.events,direction:"outbound",remoteAddr:e,log:this.log.newScope("connection")})}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 - %e",s),o.abort(s),s}}async _connect(e,t){t.signal.throwIfAborted(),t.onProgress?.(new Yn("tcp:open-connection"));let n;return new Promise((o,s)=>{let i=Date.now(),a=lo(e,{...this.opts.dialOpts??{},...t});this.log("dialing %a with opts %o",e,a),n=uu.default.connect(a);let c=d=>{this.log.error("dial to %a errored - %e",e,d);let g=a.path??`${a.host??""}:${a.port}`;d.message=`connection error ${g}: ${d.message}`,this.metrics?.events.increment({error:!0}),p(d)},l=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let d=new Vt(`Connection timeout after ${Date.now()-i}ms`);n.emit("error",d)},u=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),p()},f=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),p(new tn)},p=d=>{if(n.removeListener("error",c),n.removeListener("timeout",l),n.removeListener("connect",u),t.signal!=null&&t.signal.removeEventListener("abort",f),d!=null){s(d);return}o(n)};n.on("error",c),n.on("timeout",l),n.on("connect",u),t.signal.addEventListener("abort",f)}).catch(o=>{throw n?.destroy(),o})}createListener(e){return new fo({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,inactivityTimeout:this.opts.inboundSocketInactivityTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(t=>Vc.exactMatch(t)||t.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function lu(r={}){return e=>new ho(e,r)}function Fd(r){return r[Symbol.asyncIterator]!=null}function zd(r){if(Fd(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Di=zd;function Ae(r){return ee.encode({type:ee.Type.OK,peers:[],...r}).subarray()}function Ee(r){return ee.encode({type:ee.Type.ERROR,error:{msg:r.message},peers:[]}).subarray()}var po=at("libp2p:daemon-server:dht"),mo=class{dht;constructor(e){let{dht:t}=e;this.dht=t}async*provide(e){try{await Di(this.dht.provide(e)),yield Ae()}catch(t){po.error("failed to provide CID %s - %e",e,t),yield Ee(t)}}async*getClosestPeers(e){yield Ae({dht:{type:de.Type.BEGIN}});for await(let t of this.dht.getClosestPeers(e))t.name==="PEER_RESPONSE"&&(yield*t.closer.map(n=>de.encode({type:de.Type.VALUE,value:n.id.toMultihash().bytes})));yield de.encode({type:de.Type.END})}async*getPublicKey(e){yield Ee(new Error("FIX ME: not implemented"))}async*getValue(e){try{for await(let t of this.dht.get(e))t.name==="VALUE"&&(yield Ae({dht:{type:de.Type.VALUE,value:t.value}}))}catch(t){po.error("error getting value for key %b - %e",e,t),yield Ee(t)}}async*putValue(e,t){try{await Di(this.dht.put(e,t)),yield Ae()}catch(n){po.error("error putting value %b for key %b - %e",t,e,n),yield Ee(n)}}async*findPeer(e){try{for await(let t of this.dht.findPeer(e))t.name==="FINAL_PEER"&&(yield Ae({dht:{type:de.Type.VALUE,peer:{id:t.peer.id.toMultihash().bytes,addrs:t.peer.multiaddrs.map(n=>n.bytes)}}}));throw new Error("Peer not found")}catch(t){po.error("peer not found %p - %e",e,t),yield Ee(t)}}async*findProviders(e,t){yield Ae({dht:{type:de.Type.BEGIN}});try{let n=t,o=0;for await(let s of this.dht.findProviders(e))if(s.name==="PEER_RESPONSE"){for(let i of s.providers)o++,yield de.encode({type:de.Type.VALUE,peer:{id:i.id.toMultihash().bytes,addrs:(i.multiaddrs??[]).map(a=>a.bytes)}});if(n===o)break}}catch(n){yield Ee(n)}yield de.encode({type:de.Type.END})}};var bo=at("libp2p:daemon-server:pubsub"),yo=class{pubsub;constructor(e){let{pubsub:t}=e;this.pubsub=t}async*getTopics(){try{yield Ae({pubsub:{topics:this.pubsub.getTopics(),peerIDs:[]}})}catch(e){bo.error("failed to get pubsub topics - %e",e),yield Ee(e)}}async*subscribe(e){try{let t=dt();this.pubsub.subscribe(e),this.pubsub.addEventListener("message",n=>{let o=n.detail;o.topic===e&&(o.type==="signed"?t.push(fr.encode({from:o.from.toMultihash().bytes,data:o.data,seqno:o.sequenceNumber==null?void 0:ye(o.sequenceNumber.toString(16).padStart(16,"0"),"base16"),topicIDs:[o.topic],signature:o.signature,key:ut(o.key)}).subarray()):t.push(fr.encode({data:o.data,topicIDs:[o.topic]}).subarray()))}),yield Ae(),yield*t}catch(t){bo.error("failed to subscribe to topic %s - %e",e,t),yield Ee(t)}}async*publish(e,t){try{await this.pubsub.publish(e,t),yield Ae()}catch(n){bo.error("failed to publish message to topic %s - %e",e,n),yield Ee(n)}}async*listPeers(e){try{yield Ae({pubsub:{topics:[e],peerIDs:this.pubsub.getSubscribers(e).map(t=>t.toMultihash().bytes)}})}catch(t){bo.error("failed to list peers for topic %s - %e",e,t),yield Ee(t)}}};var fu=1<<22,ve=at("libp2p:daemon-server"),go=class{multiaddr;libp2p;tcp;listener;dhtOperations;pubsubOperations;constructor(e){let{multiaddr:t,libp2pNode:n}=e;this.multiaddr=t,this.libp2p=n,this.tcp=lu()({logger:ba()}),this.listener=this.tcp.createListener({upgrader:new dr(this.handleConnection.bind(this))}),this._onExit=this._onExit.bind(this),n.services.dht!=null&&(this.dhtOperations=new mo({dht:n.services.dht})),n.services.pubsub!=null&&(this.pubsubOperations=new yo({pubsub:n.services.pubsub}))}async connect(e){if(e.connect?.addrs==null)throw new Error("Invalid request");let t=e.connect.peer,n=e.connect.addrs.map(s=>Ye(s)),o=Qt(Xe(t));return ve("connect - adding multiaddrs %a to peer %p",n,o),await this.libp2p.peerStore.merge(o,{multiaddrs:n}),ve("connect - dial %p",o),this.libp2p.dial(o)}async openStream(e){if(e.streamOpen?.proto==null)throw new Error("Invalid request");let{peer:t,proto:n}=e.streamOpen,o=Qt(Xe(t));ve("openStream - dial %p",o);let s=await this.libp2p.dial(o);ve("openStream - open stream for protocol(s) %s",n);let i=await s.newStream(n,{runOnLimitedConnection:!0});return{streamInfo:{peer:o.toMultihash().bytes,addr:s.remoteAddr.bytes,proto:i.protocol??""},connection:i}}async registerStreamHandler(e){if(e.streamHandler?.proto==null)throw new Error("Invalid request");let t=e.streamHandler.proto,n=Ye(e.streamHandler.addr),o;ve("registerStreamHandler - handle %s at %a",t,n),await this.libp2p.handle(t,async(s,i)=>{try{ve("open stream for protocol %o to %a",t,n);let a=AbortSignal.timeout(1e4);o=await this.tcp.dial(n,{upgrader:new dr,signal:a});let c=Ht.encode({peer:i.remotePeer.toMultihash().bytes,addr:i.remoteAddr.bytes,proto:s.protocol??""}),l=co.single(c);o.send(l)||await Pe(o,"drain",{rejectionEvents:["close"],signal:a}),await Ii(s,o,s)}catch(a){ve.error("error handling stream handler - %e",a),o?.abort(a)}finally{try{await o?.close()}catch(a){o?.abort(a)}}},{runOnLimitedConnection:!0})}_listen(){process.on("SIGTERM",this._onExit),process.on("SIGINT",this._onExit),process.on("SIGHUP",this._onExit)}_onExit(){this.stop({exit:!0}).catch(e=>{ve.error("failed to stop daemon during exit - %e",e)})}async start(){this._listen(),await this.libp2p.start(),await this.listener.listen(this.multiaddr)}getMultiaddr(){let e=this.listener.getAddrs();if(e.length>0)return e[0];throw new Error("Not started")}async stop(e={exit:!1}){await this.libp2p.stop(),await this.listener.close(),e.exit&&ve("server closed, exiting"),process.removeListener("SIGTERM",this._onExit),process.removeListener("SIGINT",this._onExit),process.removeListener("SIGHUP",this._onExit)}async*handlePeerStoreRequest(e){try{switch(e.type){case xt.Type.GET_PROTOCOLS:if(e.id==null)throw new Error("Invalid request");let t=Qt(Xe(e.id)),o=(await this.libp2p.peerStore.get(t)).protocols;yield Ae({peerStore:{protos:o}});return;case xt.Type.GET_PEER_INFO:throw new Error("ERR_NOT_IMPLEMENTED");default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(t){ve.error("error handling peerstore request - %e",t),yield Ee(t)}}async*handlePubsubRequest(e){try{if(this.libp2p.services.pubsub==null||this.pubsubOperations==null)throw new Error("PubSub not configured");switch(e.type){case Qe.Type.GET_TOPICS:yield*this.pubsubOperations.getTopics();return;case Qe.Type.SUBSCRIBE:if(e.topic==null)throw new Error("Invalid request");yield*this.pubsubOperations.subscribe(e.topic);return;case Qe.Type.PUBLISH:if(e.topic==null||e.data==null)throw new Error("Invalid request");yield*this.pubsubOperations.publish(e.topic,e.data);return;case Qe.Type.LIST_PEERS:if(e.topic==null)throw new Error("Invalid request");yield*this.pubsubOperations.listPeers(e.topic);return;default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(t){ve.error("error handling pubsub request - %e",t),yield Ee(t)}}async*handleDHTRequest(e){try{if(this.libp2p.services.dht==null||this.dhtOperations==null)throw new Error("DHT not configured");switch(e.type){case ke.Type.FIND_PEER:if(e.peer==null)throw new Error("Invalid request");yield*this.dhtOperations.findPeer(Qt(Xe(e.peer)));return;case ke.Type.FIND_PROVIDERS:if(e.cid==null)throw new Error("Invalid request");yield*this.dhtOperations.findProviders(se.decode(e.cid),e.count??20);return;case ke.Type.PROVIDE:if(e.cid==null)throw new Error("Invalid request");yield*this.dhtOperations.provide(se.decode(e.cid));return;case ke.Type.GET_CLOSEST_PEERS:if(e.key==null)throw new Error("Invalid request");yield*this.dhtOperations.getClosestPeers(e.key);return;case ke.Type.GET_PUBLIC_KEY:if(e.peer==null)throw new Error("Invalid request");yield*this.dhtOperations.getPublicKey(Qt(Xe(e.peer)));return;case ke.Type.GET_VALUE:if(e.key==null)throw new Error("Invalid request");yield*this.dhtOperations.getValue(e.key);return;case ke.Type.PUT_VALUE:if(e.key==null||e.value==null)throw new Error("Invalid request");yield*this.dhtOperations.putValue(e.key,e.value);return;default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(t){ve.error("error handling DHT request - %e",t),yield Ee(t)}}handleConnection(e){Promise.resolve().then(async()=>{let t=this,n=Si(e,{maxDataLength:fu}),o=await n.read(Ne);ve("read",o);try{switch(o.type){case Ne.Type.CONNECT:{await t.connect(o),await n.write({type:ee.Type.OK},ee);break}case Ne.Type.IDENTIFY:{await n.write({type:ee.Type.OK,identify:{id:t.libp2p.peerId.toMultihash().bytes,addrs:t.libp2p.getMultiaddrs().map(s=>s.decapsulateCode(421)).map(s=>s.bytes)}},ee);break}case Ne.Type.LIST_PEERS:{let s=[],i=new Set;for(let a of t.libp2p.getConnections()){let c=a.remotePeer.toString();i.has(c)||(i.add(c),s.push({id:a.remotePeer.toMultihash().bytes,addrs:[a.remoteAddr.bytes]}))}await n.write({type:ee.Type.OK,peers:s},ee);break}case Ne.Type.STREAM_OPEN:{let s=await t.openStream(o);await n.write({type:ee.Type.OK,streamInfo:s.streamInfo},ee);let i=n.unwrap();await Ii(i,s.connection,i);break}case Ne.Type.STREAM_HANDLER:{await t.registerStreamHandler(o),await n.write({type:ee.Type.OK},ee);break}case Ne.Type.PEERSTORE:{if(o.peerStore==null)throw new Error("ERR_INVALID_REQUEST");let s=n.unwrap(),i=_r(s);for await(let a of t.handlePeerStoreRequest(o.peerStore))await i.write(a);break}case Ne.Type.PUBSUB:{if(o.pubsub==null)throw new Error("ERR_INVALID_REQUEST");let s=n.unwrap(),i=_r(s);for await(let a of t.handlePubsubRequest(o.pubsub))await i.write(a);break}case Ne.Type.DHT:{if(o.dht==null)throw new Error("ERR_INVALID_REQUEST");let s=n.unwrap(),i=_r(s);for await(let a of t.handleDHTRequest(o.dht))await i.write(a);break}default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(s){ve.error("error handling incoming connection - %e",s);let i=n.unwrap();if(i.status!=="open")return;n=Si(i,{maxDataLength:fu}),await n.write({type:ee.Type.ERROR,error:{msg:s.message},peers:[]},ee)}finally{await n.unwrap().close()}}).catch(t=>{ve.error("error handling incoming connection - %e",t)})}},Wd=(r,e)=>new go({multiaddr:r,libp2pNode:e});return yu(qd);})();
17
17
  /*! Bundled license information: