@helia/bitswap 4.0.13 → 4.0.14-16fc74d3

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
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBitswap = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaBitswap=(()=>{var yo=Object.defineProperty;var eu=Object.getOwnPropertyDescriptor;var tu=Object.getOwnPropertyNames;var ru=Object.prototype.hasOwnProperty;var we=(r,e)=>{for(var t in e)yo(r,t,{get:e[t],enumerable:!0})},nu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of tu(e))!ru.call(r,o)&&o!==t&&yo(r,o,{get:()=>e[o],enumerable:!(n=eu(e,o))||n.enumerable});return r};var ou=r=>nu(yo({},"__esModule",{value:!0}),r);var Rh={};we(Rh,{withBitswap:()=>Oh});var Te=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Se=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Pr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Or=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Rr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Nr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Mr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var tr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Ur=Symbol.for("@libp2p/peer-id");function Fr(r){return!!r?.[Ur]}function su(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function bi(...r){let e=[];for(let t of r)su(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}function iu(r){return typeof r?.handleEvent=="function"}function au(r){return r===!0||r===!1}function cu(r){return au(r)?r:r?.capture??!1}function bo(r){let e={capture:cu(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function wi(r,e){return bo(r).capture===bo(e).capture}var Ne=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=bo(n);if(o?.signal?.aborted===!0)return;let s=u=>{o.once&&this.removeEventListener(e,t,o),iu(t)?t.handleEvent(u):t(u)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(u=>u.callback!==t?!1:wi(u.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,t,o)};o.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:s,options:o,onAbort:c})}removeEventListener(e,t,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,o.filter(s=>s.callback===t&&wi(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ce=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function xi(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Hh=new Uint8Array(0);function vi(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _e(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return ft(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return ft(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Si(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var Ei=4096;function _i(r){let e=r.length;if(e<=Ei)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=Ei));return t}function uu(r){return r?.buffer instanceof ArrayBuffer}function ft(r){return uu(r)?r:r.slice()}var So={};we(So,{base32:()=>Qe,base32hex:()=>wu,base32hexpad:()=>Eu,base32hexpadupper:()=>vu,base32hexupper:()=>xu,base32pad:()=>yu,base32padupper:()=>bu,base32upper:()=>gu,base32z:()=>Su});function lu(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),u!==a&&(n[u]=s)}}var l=r.length,d=r.charAt(0),f=Math.log(l)/Math.log(256),h=Math.log(256)/Math.log(l);function v(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var S=0,g=0,A=0,T=x.length;A!==T&&x[A]===0;)A++,S++;for(var U=(T-A)*h+1>>>0,F=new Uint8Array(U);A!==T;){for(var R=x[A],P=0,O=U-1;(R!==0||P<g)&&O!==-1;O--,P++)R+=256*F[O]>>>0,F[O]=R%l>>>0,R=R/l>>>0;if(R!==0)throw new Error("Non-zero carry");g=P,A++}for(var z=U-g;z!==U&&F[z]===0;)z++;for(var L=d.repeat(S);z<U;++z)L+=r.charAt(F[z]);return L}function E(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var S=0;if(x[S]!==" "){for(var g=0,A=0;x[S]===d;)g++,S++;for(var T=(x.length-S)*f+1>>>0,U=new Uint8Array(T);x[S];){var F=n[x.charCodeAt(S)];if(F===255)return;for(var R=0,P=T-1;(F!==0||R<A)&&P!==-1;P--,R++)F+=l*U[P]>>>0,U[P]=F%256>>>0,F=F/256>>>0;if(F!==0)throw new Error("Non-zero carry");A=R,S++}if(x[S]!==" "){for(var O=T-A;O!==T&&U[O]===0;)O++;for(var z=new Uint8Array(g+(T-O)),L=g;O!==T;)z[L++]=U[O++];return z}}}function y(x){var S=E(x);if(S)return S;throw new Error(`Non-${e} character`)}return{encode:v,decodeUnsafe:E,decode:y}}var fu=lu,du=fu,Bi=du;var wo=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},xo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ti(this,e)}},Eo=class{decoders;constructor(e){this.decoders=e}or(e){return Ti(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Ti(r,e){return new Eo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var vo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new wo(e,t,n),this.decoder=new xo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Pt({name:r,prefix:e,encode:t,decode:n}){return new vo(r,e,t,n)}function Xe({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Bi(t,r,n);return Pt({prefix:e,name:r,encode:o,decode:i=>_e(s(i))})}function hu(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function pu(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function mu(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function re({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=mu(n,o);return Pt({prefix:e,name:r,encode(i){return pu(i,n,t)},decode(i){return hu(i,s,t,r)}})}var Qe=re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),gu=re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),yu=re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),bu=re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),wu=re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),xu=re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Eu=re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),vu=re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Su=re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _o={};we(_o,{base36:()=>rr,base36upper:()=>_u});var rr=Xe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),_u=Xe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Ao={};we(Ao,{base58btc:()=>oe,base58flickr:()=>Au});var oe=Xe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Au=Xe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Bu=ki,Ii=128,Tu=127,Iu=~Tu,Du=Math.pow(2,31);function ki(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Du;)e[t++]=r&255|Ii,r/=128;for(;r&Iu;)e[t++]=r&255|Ii,r>>>=7;return e[t]=r|0,ki.bytes=t-n+1,e}var ku=Bo,Lu=128,Di=127;function Bo(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Bo.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Di)<<o:(i&Di)*Math.pow(2,o),o+=7}while(i>=Lu);return Bo.bytes=s-n,t}var Cu=Math.pow(2,7),Pu=Math.pow(2,14),Ou=Math.pow(2,21),Ru=Math.pow(2,28),Nu=Math.pow(2,35),Mu=Math.pow(2,42),Uu=Math.pow(2,49),Fu=Math.pow(2,56),zu=Math.pow(2,63),Ku=function(r){return r<Cu?1:r<Pu?2:r<Ou?3:r<Ru?4:r<Nu?5:r<Mu?6:r<Uu?7:r<Fu?8:r<zu?9:10},qu={encode:Bu,decode:ku,encodingLength:Ku},Hu=qu,nr=Hu;function or(r,e=0){let t=nr.decode(r,e),n=nr.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Ot(r,e,t=0){return nr.encode(r,e,t),e}function Rt(r){return nr.encodingLength(r)}function Mt(r,e){let t=e.byteLength,n=Rt(r),o=n+Rt(t),s=new Uint8Array(o+t);return Ot(r,s,0),Ot(t,s,n),s.set(e,o),new Nt(r,t,e,s)}function Kr(r){let e=_e(r),[t,n]=or(e),[o,s]=or(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Nt(t,o,i,e)}function Li(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&vi(r.bytes,t.bytes)}}var Nt=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=ft(n),this.bytes=ft(o)}};function Ci(r,e){let{bytes:t,version:n}=r;return n===0?Wu(t,To(r),e??oe.encoder):$u(t,To(r),e??Qe.encoder)}var Pi=new WeakMap;function To(r){let e=Pi.get(r);if(e==null){let t=new Map;return Pi.set(r,t),t}return e}var Q=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=ft(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==sr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==ju)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Mt(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Li(e.multihash,n.multihash)}toString(e){return Ci(this,e)}toJSON(){return{"/":Ci(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Oi(n,o,s.bytes))}else if(t[Gu]===!0){let{version:n,multihash:o,code:s}=t,i=Kr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==sr)throw new Error(`Version 0 CID must use dag-pb (code: ${sr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Oi(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,sr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_e(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Nt(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=or(e.subarray(t));return t+=f,d},o=n(),s=sr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Vu(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return To(s).set(n,e),s}};function Vu(r,e){switch(r[0]){case"Q":{let t=e??oe;return[oe.prefix,t.decode(`${oe.prefix}${r}`)]}case oe.prefix:{let t=e??oe;return[oe.prefix,t.decode(r)]}case Qe.prefix:{let t=e??Qe;return[Qe.prefix,t.decode(r)]}case rr.prefix:{let t=e??rr;return[rr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Wu(r,e,t){let{prefix:n}=t;if(n!==oe.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function $u(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var sr=112,ju=18;function Oi(r,e,t){let n=Rt(r),o=n+Rt(e),s=new Uint8Array(o+t.byteLength);return Ot(r,s,0),Ot(e,s,n),s.set(t,o),s}var Gu=Symbol.for("@ipld/js-cid/CID");var Zu=20;function Do({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Io(r,e,t,n,o)}var Io=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Zu,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Ri(n,this.code,t?.truncate):n.then(o=>Ri(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ri(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Mt(e,r)}var Lo={};we(Lo,{base64:()=>ht,base64pad:()=>Yu,base64url:()=>ko,base64urlpad:()=>Xu});var ht=re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Yu=re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ko=re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xu=re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Co={};we(Co,{identity:()=>Ie});var Mi=0,Qu="identity",Ui=_e;function Ju(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Mt(Mi,Ui(r))}var Ie={code:Mi,name:Qu,encode:Ui,digest:Ju};function ue(r=0){return new Uint8Array(r)}function ie(r=0){return new Uint8Array(r)}function el(r){return r?.buffer instanceof ArrayBuffer}function Po(r){if(el(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function xe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ie(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return Po(t)}function ne(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 zi=Symbol.for("@achingbrain/uint8arraylist");function Fi(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 qr(r){return!!r?.[zi]}var le=class r{bufs;length;[zi]=!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(qr(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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(qr(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=Fi(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Fi(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(qr(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 xe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:xe(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 u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){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(!qr(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 d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let d=t;d<=c;d+=l){l=0;for(let f=u;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){l=Math.max(1,f-a[h]);break}}if(l===0)return d}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=ie(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=ue(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=ue(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=ue(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=ie(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=ue(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=ue(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=ue(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=ue(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=ue(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(!ne(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}};function tl(r){return r.buffer instanceof ArrayBuffer}function De(r){return tl(r)?r:r.slice()}var rl=Math.pow(2,7),nl=Math.pow(2,14),ol=Math.pow(2,21),Oo=Math.pow(2,28),Ro=Math.pow(2,35),No=Math.pow(2,42),Mo=Math.pow(2,49),H=128,he=127;function G(r){if(r<rl)return 1;if(r<nl)return 2;if(r<ol)return 3;if(r<Oo)return 4;if(r<Ro)return 5;if(r<No)return 6;if(r<Mo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ut(r,e,t=0){switch(G(r)){case 8:e[t++]=r&255|H,r/=128;case 7:e[t++]=r&255|H,r/=128;case 6:e[t++]=r&255|H,r/=128;case 5:e[t++]=r&255|H,r/=128;case 4:e[t++]=r&255|H,r>>>=7;case 3:e[t++]=r&255|H,r>>>=7;case 2:e[t++]=r&255|H,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function sl(r,e,t=0){switch(G(r)){case 8:e.set(t++,r&255|H),r/=128;case 7:e.set(t++,r&255|H),r/=128;case 6:e.set(t++,r&255|H),r/=128;case 5:e.set(t++,r&255|H),r/=128;case 4:e.set(t++,r&255|H),r>>>=7;case 3:e.set(t++,r&255|H),r>>>=7;case 2:e.set(t++,r&255|H),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Uo(r,e){let t=r[e],n=0;if(n+=t&he,t<H||(t=r[e+1],n+=(t&he)<<7,t<H)||(t=r[e+2],n+=(t&he)<<14,t<H)||(t=r[e+3],n+=(t&he)<<21,t<H)||(t=r[e+4],n+=(t&he)*Oo,t<H)||(t=r[e+5],n+=(t&he)*Ro,t<H)||(t=r[e+6],n+=(t&he)*No,t<H)||(t=r[e+7],n+=(t&he)*Mo,t<H))return n;throw new RangeError("Could not decode varint")}function il(r,e){let t=r.get(e),n=0;if(n+=t&he,t<H||(t=r.get(e+1),n+=(t&he)<<7,t<H)||(t=r.get(e+2),n+=(t&he)<<14,t<H)||(t=r.get(e+3),n+=(t&he)<<21,t<H)||(t=r.get(e+4),n+=(t&he)*Oo,t<H)||(t=r.get(e+5),n+=(t&he)*Ro,t<H)||(t=r.get(e+6),n+=(t&he)*No,t<H)||(t=r.get(e+7),n+=(t&he)*Mo,t<H))return n;throw new RangeError("Could not decode varint")}function Hr(r,e,t=0){return e==null&&(e=ie(G(r))),e instanceof Uint8Array?Ut(r,e,t):sl(r,e,t)}function pt(r,e=0){return r instanceof Uint8Array?Uo(r,e):il(r,e)}var zo=new Float32Array([-0]),Je=new Uint8Array(zo.buffer);function Ki(r,e,t){zo[0]=r,e[t]=Je[0],e[t+1]=Je[1],e[t+2]=Je[2],e[t+3]=Je[3]}function qi(r,e){return Je[0]=r[e],Je[1]=r[e+1],Je[2]=r[e+2],Je[3]=r[e+3],zo[0]}var Ko=new Float64Array([-0]),pe=new Uint8Array(Ko.buffer);function Hi(r,e,t){Ko[0]=r,e[t]=pe[0],e[t+1]=pe[1],e[t+2]=pe[2],e[t+3]=pe[3],e[t+4]=pe[4],e[t+5]=pe[5],e[t+6]=pe[6],e[t+7]=pe[7]}function Vi(r,e){return pe[0]=r[e],pe[1]=r[e+1],pe[2]=r[e+2],pe[3]=r[e+3],pe[4]=r[e+4],pe[5]=r[e+5],pe[6]=r[e+6],pe[7]=r[e+7],Ko[0]}var al=BigInt(Number.MAX_SAFE_INTEGER),cl=BigInt(Number.MIN_SAFE_INTEGER),Ee=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return mt;if(e<al&&e>cl)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Wi&&(o=0n,++n>Wi&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return mt;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):mt}},mt=new Ee(0,0);mt.toBigInt=function(){return 0n};mt.zzEncode=mt.zzDecode=function(){return this};mt.length=function(){return 1};var Wi=4294967296n;function $i(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function ji(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function qo(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ke(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Vr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Ho=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=De(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ke(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ke(this,4);return Vr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ke(this,4);return Vr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ke(this,4);let e=qi(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ke(this,4);let e=Vi(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ke(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return ji(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ke(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ke(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ee(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ke(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ke(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ke(this,8);let e=Vr(this.buf,this.pos+=4),t=Vr(this.buf,this.pos+=4);return new Ee(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Uo(this.buf,this.pos);return this.pos+=G(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ir(r){return new Ho(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=ir(r);return e.decode(n,void 0,t)}var Vo={};we(Vo,{base10:()=>ul});var ul=Xe({prefix:"9",name:"base10",alphabet:"0123456789"});var Wo={};we(Wo,{base16:()=>ll,base16upper:()=>fl});var ll=re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),fl=re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var $o={};we($o,{base2:()=>dl});var dl=re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jo={};we(jo,{base256emoji:()=>yl});var Zi=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),hl=Zi.reduce((r,e,t)=>(r[t]=e,r),[]),pl=Zi.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function ml(r){return r.reduce((e,t)=>(e+=hl[t],e),"")}function gl(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=pl[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var yl=Pt({prefix:"\u{1F680}",name:"base256emoji",encode:ml,decode:gl});var Go={};we(Go,{base8:()=>bl});var bl=re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Zo={};we(Zo,{identity:()=>wl});var wl=Pt({prefix:"\0",name:"identity",encode:r=>_i(_e(r)),decode:r=>_e(Si(r))});var Vp=new TextEncoder,Wp=new TextDecoder;var Yo={};we(Yo,{sha256:()=>et,sha512:()=>vl});function Yi(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var et=Do({name:"sha2-256",code:18,encode:Yi("SHA-256")}),vl=Do({name:"sha2-512",code:19,encode:Yi("SHA-512")});var ar={...Zo,...$o,...Go,...Vo,...Wo,...So,..._o,...Ao,...Lo,...jo},Zp={...Yo,...Co};function Qi(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Xi=Qi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xo=Qi("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ie(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Sl={utf8:Xi,"utf-8":Xi,hex:ar.base16,latin1:Xo,ascii:Xo,binary:Xo,...ar},Wr=Sl;function Z(r,e="utf8"){let t=Wr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Qo(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ie(i);o+i>e&&(n=ie(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var gt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Jo(){}var ts=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},_l=Qo();function Al(r){return globalThis.Buffer!=null?ie(r):_l(r)}var ur=class{len;head;tail;states;constructor(){this.len=0,this.head=new gt(Jo,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new gt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new rs((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push($r,10,Ee.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ee.fromBigInt(e);return this._push($r,t.length(),t)}uint64Number(e){return this._push(Ut,G(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Ee.fromBigInt(e).zzEncode();return this._push($r,t.length(),t)}sint64Number(e){let t=Ee.fromNumber(e).zzEncode();return this._push($r,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(es,1,e?1:0)}fixed32(e){return this._push(cr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ee.fromBigInt(e);return this._push(cr,4,t.lo)._push(cr,4,t.hi)}fixed64Number(e){let t=Ee.fromNumber(e);return this._push(cr,4,t.lo)._push(cr,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Ki,4,e)}double(e){return this._push(Hi,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(es,1,0):this.uint32(t)._push(Tl,t,e)}string(e){let t=$i(e);return t!==0?this.uint32(t)._push(qo,t,e):this._push(es,1,0)}fork(){return this.states=new ts(this),this.head=this.tail=new gt(Jo,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new gt(Jo,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Al(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function es(r,e,t){e[t]=r&255}function Bl(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var rs=class extends gt{next;constructor(e,t){super(Bl,e,t),this.next=void 0}};function $r(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function cr(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Tl(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ur.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Il,e,r),this},ur.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Dl,e,r),this});function Il(r,e,t){e.set(r,t)}function Dl(r,e,t){r.length<40?qo(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Z(r),t)}function ns(){return new ur}function Ue(r,e){let t=ns();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Fe(r,e,t){let n=ir(r);yield*e.stream(n,void 0,"$",t)}var jr={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Gr(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Ft(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Gr("enum",jr.VARINT,t,n,o)}function ze(r,e,t){return Gr("message",jr.LENGTH_DELIMITED,r,e,t)}var He=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Zr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Yr=class extends Error{static name="NoEvictionError";name="NoEvictionError"};var os={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ji={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ea=new globalThis.TextEncoder;function kl(r,e){let t=os[e],n=Ji[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Ll(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=os[e],o=Ji[e],s=r;for(;s.length>0;){let i=ea.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function ss(r,{size:e=32,utf8Buffer:t}={}){if(!os[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Ll(r,e,t);r=ea.encode(r)}return kl(r,e)}var lr={hash:r=>Number(ss(r,{size:32})),hashV:(r,e)=>Cl(lr.hash(r,e))};function Cl(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),Z(e,"base16")}var is=64,Le=class{fp;h;seed;constructor(e,t,n,o=2){if(o>is)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ue(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ne(this.fp,e.fp):!1}};function yt(r,e){return Math.floor(Math.random()*(e-r))+r}var bt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Le))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Le))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Le))throw new TypeError("Invalid Fingerprint");let t=yt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Le))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Pl=500,fr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??lr,this.seed=e.seed??yt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=Z(e));let t=new Le(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new bt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new bt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[yt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new bt(this.bucketSize));for(let a=0;a<Pl;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new bt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=Z(e));let t=new Le(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=Z(e));let t=new Le(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Ol={1:.5,2:.84,4:.95,8:.98};function Rl(r=.001){return r>.002?2:r>1e-5?4:8}function ta(r,e=.001){let t=Rl(e),n=Ol[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),is);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Xr=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??lr,this.seed=e.seed??yt(0,Math.pow(2,10)),this.filterSeries=[new fr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=Z(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new fr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=Z(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=Z(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Qr(r,e=.001,t){return new Xr({...ta(r,e),...t??{}})}var Jr=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Nl=45,Ml=15,en=new Jr;function ra(r){if(!(r.length>Ml))return en.new(r).parseWith(()=>en.readIPv4Addr())}function na(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Nl))return en.new(r).parseWith(()=>en.readIPv6Addr())}function tn(r){return!!ra(r)}function oa(r){return!!na(r)}function $(r,e="utf8"){let t=Wr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var fe=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ve=class extends Error{static name="ValidationError";name="ValidationError"},rn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},nn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function cs(r){return e=>$(e,r)}function us(r){return e=>Z(e,r)}function zt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function wt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function sa(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=Z(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=wt(n);return xe([t,o],t.length+o.length)}function ia(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=Qe.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=wt(n);return xe([t,o],t.length+o.length)}function ls(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=$(e,"base32"),o=zt(t);return`${n}:${o}`}var fs=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 fe("Invalid byte value in IP address");e[n]=o}),e},aa=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=tn(t[n]),i;s&&(i=fs(t[n]),t[n]=$(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,$(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 fe("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},ca=function(r){if(r.byteLength!==4)throw new fe("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ua=function(r){if(r.byteLength!==16)throw new fe("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 fe(`Invalid IPv6 address "${t}"`)}};function la(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new fe(`Invalid IPv6 address "${r}"`)}}var as=Object.values(ar).map(r=>r.decoder),Ul=(function(){let r=as[0].or(as[1]);return as.slice(2).forEach(e=>r=r.or(e)),r})();function fa(r){return Ul.decode(r)}function da(r){return e=>r.encoder.encode(e)}function Fl(r){if(parseInt(r).toString()!==r)throw new Ve("Value must be an integer")}function zl(r){if(r<0)throw new Ve("Value must be a positive integer, or zero")}function Kl(r){return e=>{if(e>r)throw new Ve(`Value must be smaller than or equal to ${r}`)}}function ql(...r){return e=>{for(let t of r)t(e)}}var dr=ql(Fl,zl,Kl(65535));var ae=-1,ds=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 nn(`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)}))}},We=new ds,kf=[{code:4,name:"ip4",size:32,valueToBytes:fs,bytesToValue:ca,validate:r=>{if(!tn(r))throw new Ve(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:wt,bytesToValue:zt,validate:dr},{code:273,name:"udp",size:16,valueToBytes:wt,bytesToValue:zt,validate:dr},{code:33,name:"dccp",size:16,valueToBytes:wt,bytesToValue:zt,validate:dr},{code:41,name:"ip6",size:128,valueToBytes:aa,bytesToValue:ua,stringToValue:la,validate:r=>{if(!oa(r))throw new Ve(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ae},{code:43,name:"ipcidr",size:8,bytesToValue:cs("base10"),valueToBytes:us("base10")},{code:53,name:"dns",size:ae},{code:54,name:"dns4",size:ae},{code:55,name:"dns6",size:ae},{code:56,name:"dnsaddr",size:ae},{code:132,name:"sctp",size:16,valueToBytes:wt,bytesToValue:zt,validate:dr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ae,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ae,bytesToValue:cs("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?us("base58btc")(r):Q.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ls,valueToBytes:sa},{code:445,name:"onion3",size:296,bytesToValue:ls,valueToBytes:ia},{code:446,name:"garlic64",size:ae},{code:447,name:"garlic32",size:ae},{code:448,name:"tls"},{code:449,name:"sni",size:ae},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ae,bytesToValue:da(ko),valueToBytes:fa},{code:480,name:"http"},{code:481,name:"http-path",size:ae,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:ae}];kf.forEach(r=>{We.addProtocol(r)});function ha(r){let e=[],t=0;for(;t<r.length;){let n=pt(r,t),o=We.getProtocol(n),s=G(n),i=Lf(o,r,t+s),a=0;i>0&&o.size===ae&&(a=G(i));let c=s+a+i,u={code:n,name:o.name,bytes:De(r.subarray(t,t+c))};if(i>0){let l=t+s+a,d=r.subarray(l,l+i);u.value=o.bytesToValue?.(d)??$(d)}e.push(u),t+=c}return e}function pa(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=We.getProtocol(n.code),s=G(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,o.size===ae&&(c=G(a)));let u=new Uint8Array(s+c+a),l=0;Ut(n.code,u,l),l+=s,i!=null&&(o.size===ae&&(Ut(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return xe(t,e)}function ma(r){if(r.charAt(0)!=="/")throw new fe('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=We.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 fe(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new fe(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new fe("Incomplete multiaddr");return e}function ga(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=We.getProtocol(e.code);if(t==null)throw new fe(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Lf(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:pt(e,t)}var Cf=Symbol.for("nodejs.util.inspect.custom"),ps=Symbol.for("@multiformats/multiaddr");function Pf(r){if(r==null&&(r="/"),on(r))return r.getComponents();if(r instanceof Uint8Array)return ha(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ma(r);if(Array.isArray(r))return r;throw new fe("Must be a string, Uint8Array, Component[], or another Multiaddr")}var hs=class r{[ps]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Pf(e),t.validate!==!1&&Of(this)}get bytes(){return this.#r==null&&(this.#r=pa(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ga(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 rn(`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 ne(this.bytes,e.bytes)}[Cf](){return`Multiaddr(${this.toString()})`}};function Of(r){r.getComponents().forEach(e=>{let t=We.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function on(r){return!!r?.[ps]}function Ce(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var sn=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}},Kt=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new sn(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 sn(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 ms=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function an(r={}){return Rf(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 Rf(r,e){e=e??{};let t=e.onEnd,n=new Kt,o,s,i,a=Ce(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,x)=>{s=S=>{s=null,n.push(S);try{y(r(n))}catch(g){x(g)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ce()})}},u=y=>s!=null?s(y):(n.push(y),o),l=y=>(n=new Kt,s!=null?s({error:y}):(n.push({error:y}),o)),d=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},f=y=>i?o:(i=!0,y!=null?l(y):u({done:!0})),h=()=>(n=new Kt,f(),{done:!0}),v=y=>(f(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:v,push:d,end:f,get readableLength(){return n.size},onEmpty:async y=>{let x=y?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let S,g;x!=null&&(S=new Promise((A,T)=>{g=()=>{T(new ms)},x.addEventListener("abort",g)}));try{await Promise.race([a.promise,S])}finally{g!=null&&x!=null&&x?.removeEventListener("abort",g)}}},t==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(y){return E.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return E.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(y){return E.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return E.readableLength},onEmpty:y=>E.onEmpty(y)},o}var gs=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ya=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function ys(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((d,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){f(ya(i));return}if(i&&(c=()=>{f(ya(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new gs;a=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(v){f(v)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var Nf=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 Mf(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:u,removeListener:l}=Nf(r),d=async(...h)=>{let v=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(v))return}catch(E){n(),i(E);return}c.push(v),t.count===c.length&&(n(),s(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f)};for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=ys(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function cn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Mf(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function bs(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var un=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Uf(r){return r.reason}function ln(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??Uf;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var fn=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ce(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Te)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ff(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var dn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Ff(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Te),this.cleanup())}async join(e){let t=new fn(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await ln(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var tt=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=bs(this.emitEmpty.bind(this),1),this.emitIdle=bs(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new un;let n=new dn(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Te)}),this.clear()}async onEmpty(e){this.size!==0&&await cn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await cn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await cn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=an({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Te("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var hn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},qt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},pn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},hr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function mn(r){return r[Symbol.asyncIterator]!=null}function ba(r,e){if(r.byteLength>e)throw new qt("Message length too long")}var yn=r=>{let e=G(r),t=ie(e);return Hr(r,t),yn.bytes=e,t};yn.bytes=0;function bn(r,e){e=e??{};let t=e.lengthEncoder??yn,n=e?.maxDataLength??4194304;function*o(s){ba(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return mn(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}bn.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??yn,n=e?.maxDataLength??4194304;return ba(r,n),new le(t(r.byteLength),r)};var xt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(xt||(xt={}));var ws=r=>{let e=pt(r);return ws.bytes=G(e),e};ws.bytes=0;function pr(r,e){let t=new le,n=xt.LENGTH,o=-1,s=e?.lengthDecoder??ws,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===xt.LENGTH)try{if(o=s(t),o<0)throw new hn("Invalid message length");if(o>a)throw new qt("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=xt.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new pn("Message length length too long");break}throw u}if(n===xt.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=xt.LENGTH}}}return mn(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new hr("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new hr("Unexpected end of input")})()}pr.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 pr(n,{...e??{},onLength:s=>{t=s}})};var wn=class extends tt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var xs=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function wa(r){let{name:e,metrics:t}=r,n;return t!=null?n=new xs({name:e,metrics:t}):n=new Map,n}var xn=class extends Ne{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Qr(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=ht.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=Ce(),i={promise:s.promise,observers:1,queryFilter:Qr(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,u=new tt({concurrency:this.maxProviders});u.addEventListener("failure",f=>{if(f.detail.job.options.provider.fallback){this.log.error("error querying fallback provider %s - %e",f.detail.job.options.provider,f.detail.error);return}if(f.detail.error.name==="NoEvictionError"){this.log.error("no-eviction error querying provider %s - %e",f.detail.job.options.provider,f.detail.error);return}this.log.error("error querying provider %s, evicting from session - %e",f.detail.job.options.provider,f.detail.error),this.evict(f.detail.job.options.provider)}),u.addEventListener("success",f=>{c=!0,s.resolve(f.detail.result)}),u.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let f=0;f<this.minProviders&&this.providers.length!==0;f++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];h.fallback||(this.log("evicting %s to make room for more providers",h),this.evict(h))}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(f=>{this.log.error("could not find new providers for %c - %e",e,f),s.reject(f)})});let l=f=>{let h=this.toFilterKey(f.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,f.detail,t),u.add(async()=>this.queryProvider(e,f.detail,t),{provider:f.detail}).catch(v=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,v)}))};if(this.addEventListener("provider",l),a)try{await ln(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(f){throw a&&this.log("failed to find initial session peers for %c - %e",e,f),this.requests.delete(n),i.observers>1&&s.reject(f),f}Promise.all([...this.providers].filter(f=>{let h=this.toFilterKey(f),v=i.queryFilter.has(h);return v||i.queryFilter.add(this.toFilterKey(f)),!v}).map(async f=>u.add(async()=>this.queryProvider(e,f,t),{provider:f}))).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,f)});let d=()=>{s.reject(new Te(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",d);try{return await s.promise}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",d),u.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=Ce(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let u=i.initialProviders.pop();if(u==null)continue;let l=await i.convertToProvider(u,"manual",n);l!=null&&(yield l)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let u of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(u)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(u),this.safeDispatchEvent("provider",{detail:u}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new Zr(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};function Wf(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Ea=Wf;function $f(r){return r[Symbol.asyncIterator]!=null}function jf(r){if($f(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=xe([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return xe(e,t)}var va=jf;function En(r){return r==null?!1:Q.asCID(r)!=null}async function Sa(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,De(e),De(t.subarray()));return n?.signal?.throwIfAborted(),s}var Gf=parseInt("11111",2),Es=parseInt("10000000",2),Zf=parseInt("01111111",2),_a={0:mr,1:mr,2:Yf,3:Jf,4:ed,5:Qf,6:Xf,16:mr,22:mr,48:mr};function vs(r,e={offset:0}){let t=r[e.offset]&Gf;if(e.offset++,_a[t]!=null)return _a[t](r,e);throw new Error("No decoder for tag "+t)}function gr(r,e){let t=0;if((r[e.offset]&Es)===Es){let n=r[e.offset]&Zf,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");o+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(o,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function mr(r,e){gr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=vs(r,e);if(n===null)break;t.push(n)}return t}function Yf(r,e){let t=gr(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 Xf(r,e){let t=gr(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 u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let d=0;d<c.length;d++)l+=c[d]<<d*7;a+=`.${l}`,c=[]}}return a}function Qf(r,e){return e.offset++,null}function Jf(r,e){let t=gr(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 ed(r,e){let t=gr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function td(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new le;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Ss(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=td(r.byteLength);return new le(Uint8Array.from([e.byteLength|Es]),e)}function Aa(r){let e=new le,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new le(Uint8Array.from([2]),Ss(e),e)}function Ba(r){let e=Uint8Array.from([0]),t=new le(e,r);return new le(Uint8Array.from([3]),Ss(t),t)}function vn(r,e=48){let t=new le;for(let n of r)t.append(n);return new le(Uint8Array.from([e]),Ss(t),t)}var rd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),nd=Uint8Array.from([6,5,43,129,4,0,34]),od=Uint8Array.from([6,5,43,129,4,0,35]),sd={ext:!0,kty:"EC",crv:"P-256"},id={ext:!0,kty:"EC",crv:"P-384"},ad={ext:!0,kty:"EC",crv:"P-521"},_s=32,As=48,Bs=66;function Ta(r){let e=vs(r);return Ia(e)}function Ia(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===_s*2+1)return n=$(e.subarray(t,t+_s),"base64url"),o=$(e.subarray(t+_s),"base64url"),new Ht({...sd,key_ops:["verify"],x:n,y:o});if(e.byteLength===As*2+1)return n=$(e.subarray(t,t+As),"base64url"),o=$(e.subarray(t+As),"base64url"),new Ht({...id,key_ops:["verify"],x:n,y:o});if(e.byteLength===Bs*2+1)return n=$(e.subarray(t,t+Bs),"base64url"),o=$(e.subarray(t+Bs),"base64url"),new Ht({...ad,key_ops:["verify"],x:n,y:o});throw new Se(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Da(r){return vn([Aa(Uint8Array.from([1])),vn([cd(r.crv)],160),vn([Ba(new le(Uint8Array.from([4]),Z(r.x??"","base64url"),Z(r.y??"","base64url")))],161)]).subarray()}function cd(r){if(r==="P-256")return rd;if(r==="P-384")return nd;if(r==="P-521")return od;throw new Se(`Invalid curve ${r}`)}var Ht=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Da(this.jwk)),this._raw}toMultihash(){return Ie.digest(Vt(this))}toCID(){return Q.createV1(114,this.toMultihash())}toString(){return oe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ne(this.raw,e.raw)}async verify(e,t,n){return Sa(this.jwk,t,e,n)}};var Sn=BigInt(4294967295),ka=BigInt(32);function ud(r,e=!1){return e?{h:Number(r&Sn),l:Number(r>>ka&Sn)}:{h:Number(r>>ka&Sn)|0,l:Number(r&Sn)|0}}function La(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=ud(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var ld=r=>r/2**32|0,fd=r=>r>>>0;function Ca(r,e,t,n){let o=ld(t),s=fd(t);r.setUint32(e,n?s:o,n),r.setUint32(e+4,n?o:s,n)}var Ts=(r,e,t)=>r>>>t,Is=(r,e,t)=>r<<32-t|e>>>t,Et=(r,e,t)=>r>>>t|e<<32-t,vt=(r,e,t)=>r<<32-t|e>>>t,yr=(r,e,t)=>r<<64-t|e>>>t-32,br=(r,e,t)=>r>>>t-32|e<<64-t;function Ke(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Pa=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Oa=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Ra=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Na=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Ma=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Ua=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;function _n(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Ds=r=>r?`"${r}" `:"";function $e(r,e=""){if(typeof r!="number")throw new TypeError(Ds(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Ds(e)+"expected integer >= 0, got "+r);return r}function Ae(r,e,t=""){if(_n(r)&&(e===void 0||r.length===e))return r;e!==void 0&&$e(e,"length");let n=_n(r),o=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,i=Ds(t)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function An(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if($e(r.outputLen),$e(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Fa=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)};function Wt(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function Bn(r,e){Ae(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function St(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Tn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Pe(r,e){return r<<32-e|r>>>e}var Ka=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hd=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function In(r){if(Ae(r),Ka)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=hd[r[t]];return e}function za(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function Dn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Ka)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("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=za(r.charCodeAt(s)),a=za(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ks(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ae(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 pd(r,e,t="opts"){return Fa(r,"defaults"),e!==void 0&&Fa(e,t),Object.assign(r,e)}function Ls(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=pd({},e,"info");let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function qa(r=32){$e(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Cs=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ha(r,e,t){return r&e^~r&t}function Va(r,e,t){return r&e^r&t^e&t}var wr=class{blockLen;outputLen;canXOF=!1;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=Tn(this.buffer)}update(e){Wt(this),Ae(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let u=Tn(e);for(;o<=s-a;a+=o)this.process(u,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Wt(this),Bn(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>o-i&&(this.process(n,0),t.fill(0)),Ca(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===t?n:Tn(e),c=this.outputLen,u=c/4,l=this.get();if(c%4||u>l.length)throw new Error("invalid outputLen");for(let d=0;d<u;d++)a.setUint32(4*d,l[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Wa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var $a=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var md=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]),rt=new Uint32Array(64),Ps=class extends wr{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}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}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)rt[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=rt[d-15],h=rt[d-2],v=Pe(f,7)^Pe(f,18)^f>>>3,E=Pe(h,17)^Pe(h,19)^h>>>10;rt[d]=E+rt[d-7]+v+rt[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let d=0;d<64;d++){let f=Pe(a,6)^Pe(a,11)^Pe(a,25),h=l+f+Ha(a,c,u)+md[d]+rt[d]|0,E=(Pe(n,2)^Pe(n,13)^Pe(n,22))+Va(n,o,s)|0;l=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+E|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,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){St(rt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),St(this.buffer)}},Os=class extends Ps{constructor(){super(32,Wa)}};var ja=La(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),gd=ja[0],yd=ja[1],nt=new Uint32Array(80),ot=new Uint32Array(80),Rs=class extends wr{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:d,Fl:f,Gh:h,Gl:v,Hh:E,Hl:y}=this;return[e,t,n,o,s,i,a,c,u,l,d,f,h,v,E,y]}set(e,t,n,o,s,i,a,c,u,l,d,f,h,v,E,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=d|0,this.Fl=f|0,this.Gh=h|0,this.Gl=v|0,this.Hh=E|0,this.Hl=y|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let g=0;g<16;g++,t+=4)nt[g]=e.getUint32(t),ot[g]=e.getUint32(t+=4);for(let g=16;g<80;g++){let A=nt[g-15]|0,T=ot[g-15]|0,U=Et(A,T,1)^Et(A,T,8)^Ts(A,T,7),F=vt(A,T,1)^vt(A,T,8)^Is(A,T,7),R=nt[g-2]|0,P=ot[g-2]|0,O=Et(R,P,19)^yr(R,P,61)^Ts(R,P,6),z=vt(R,P,19)^br(R,P,61)^Is(R,P,6),L=Ra(F,z,ot[g-7],ot[g-16]),j=Na(L,U,O,nt[g-7],nt[g-16]);nt[g]=j|0,ot[g]=L|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:d,El:f,Fh:h,Fl:v,Gh:E,Gl:y,Hh:x,Hl:S}=this;for(let g=0;g<80;g++){let A=Et(d,f,14)^Et(d,f,18)^yr(d,f,41),T=vt(d,f,14)^vt(d,f,18)^br(d,f,41),U=d&h^~d&E,F=f&v^~f&y,R=Ma(S,T,F,yd[g],ot[g]),P=Ua(R,x,A,U,gd[g],nt[g]),O=R|0,z=Et(n,o,28)^yr(n,o,34)^yr(n,o,39),L=vt(n,o,28)^br(n,o,34)^br(n,o,39),j=n&s^n&a^s&a,k=o&i^o&c^i&c;x=E|0,S=y|0,E=h|0,y=v|0,h=d|0,v=f|0,{h:d,l:f}=Ke(u|0,l|0,P|0,O|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=Pa(O,L,k);n=Oa(D,P,z,j),o=D|0}({h:n,l:o}=Ke(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ke(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ke(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Ke(this.Dh|0,this.Dl|0,u|0,l|0),{h:d,l:f}=Ke(this.Eh|0,this.El|0,d|0,f|0),{h,l:v}=Ke(this.Fh|0,this.Fl|0,h|0,v|0),{h:E,l:y}=Ke(this.Gh|0,this.Gl|0,E|0,y|0),{h:x,l:S}=Ke(this.Hh|0,this.Hl|0,x|0,S|0),this.set(n,o,s,i,a,c,u,l,d,f,h,v,E,y,x,S)}roundClean(){St(nt,ot)}destroy(){this.destroyed=!0,St(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ns=class extends Rs{constructor(){super(64,$a)}};var Ga=Ls(()=>new Os,Cs(1));var Ms=Ls(()=>new Ns,Cs(3));function Ln(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var V=(r,e,t)=>Ae(r,e,t),Us=$e;function Ya(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function st(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function _t(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var xr=In,Be=(...r)=>ks(...r),$t=r=>Dn(r),at=_n,At=r=>qa(r),kn=BigInt(0),Za=BigInt(1),bd=r=>r?`"${r}" `:"";function ye(r,e=""){if(typeof r!="boolean")throw new TypeError(bd(e)+"expected boolean, got type="+typeof r);return r}function Cn(r){if(typeof r=="bigint"){if(!it(r))throw new RangeError("positive bigint expected, got "+r)}else Us(r);return r}function ct(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Er(r){let e=Cn(r).toString(16);return e.length&1?"0"+e:e}function Xa(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?kn:BigInt("0x"+r)}function qe(r){return Xa(In(r))}function Bt(r){return Xa(In(On(Ae(r)).reverse()))}function Pn(r,e){if($e(e),e===0)throw new Error("zero output length is invalid");r=Cn(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return Dn(n.padStart(t,"0"))}function Fs(r,e){return Pn(r,e).reverse()}function On(r){return Uint8Array.from(V(r))}function it(r){return typeof r=="bigint"&&kn<=r}function zs(r,e,t){return it(r)&&it(e)&&it(t)&&e<=r&&r<t}function jt(r,e,t,n){if(!zs(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Gt(r){if(r<kn)throw new Error("expected non-negative bigint, got "+r);return r===kn?0:r.toString(2).length}var vr=r=>(ct(r,"n"),(Za<<BigInt(r))-Za);function Qa(r,e,t){if($e(r,"hashLen"),$e(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),l=0,d=()=>{c.fill(1),u.fill(0),l=0},f=(...y)=>t(u,Be(c,...y)),h=(y=o)=>{u=f(s,y),c=f(),y.length!==0&&(u=f(i,y),c=f())},v=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,x=[];for(;y<e;){c=f();let S=c.slice();x.push(S),y+=c.length}return Be(...x)};return(y,x)=>{d(),h(y);let S;for(;(S=x(v()))===void 0;)h();return d(),S}}function be(r,e={},t={},n="object"){st(r,n),st(e,"fields"),st(t,"optFields");function o(i,a,c){let u=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,l=r[i];if(!Object.hasOwn(r,i)&&(c?l!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(c&&l===void 0)return;let d=typeof l;if(d!==a||l===null)throw new TypeError(`${u} is invalid: expected ${a}, got ${d}`)}let s=(i,a)=>Object.entries(i).forEach(([c,u])=>o(c,u,a));s(e,!1),s(t,!0)}var se=BigInt(0),W=BigInt(1),ut=BigInt(2),tc=BigInt(3),Ks=BigInt(4),rc=BigInt(5),wd=BigInt(7),nc=BigInt(8),xd=BigInt(9),Ed=BigInt(15),oc=BigInt(16),vd=BigInt("0x10000000000000000");function J(r,e){if(e<=se)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=se?t:e+t}function sc(r,e,t){if(t<=W)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<se)throw new Error("invalid exponent, negatives unsupported");if(e===se)return W;if(e===W)return r;let n=r%t;if(n<se&&(n+=t),e<vd){let a=W;for(;e>se;)e&W&&(a=a*n%t),n=n*n%t,e>>=W;return a}let o=[];for(;e>se;)o.push(Number(e&Ed)),e>>=Ks;let s=new Array(16);s[0]=W,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%t;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=o[a];c!==0&&(i=i*s[c]%t)}return i}function Y(r,e,t){if(t<=W)throw new Error("pow2: expected modulus > 1, got "+t);if(e<se)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >se;)n*=n,n%=t;return n}function Ja(r,e){if(r===se)throw new Error("invert: expected non-zero number");if(e<=W)throw new Error("invert: expected modulus > 1, got "+e);let t=J(r,e),n=e,o=se,s=W;for(;t!==se;){let a=n/t,c=n-t*a,u=o-s*a;n=t,t=c,o=s,s=u}if(n!==W)throw new Error("invert: does not exist");return J(o,e)}function ic(r,e){if(e<=W)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=J(r,e);if(t===se)throw new Error("invertCt: expected non-zero number");let n=sc(t,e-ut,e);if(J(t*n,e)!==W)throw new Error("invertCt: does not exist");return n}function qs(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Hs(r,e){if((r&W)===se)throw new Error(e+": expected odd modulus, got "+r)}function ac(r,e){let t=r,n=(t.ORDER+W)/Ks,o=t.pow(e,n);return qs(t,o,e),o}function Sd(r,e){let t=r,n=(t.ORDER-rc)/nc,o=t.mul(e,ut),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,ut),s),c=t.mul(i,t.sub(a,t.ONE));return qs(t,c,e),c}function _d(r){let e=Yt(r),t=cc(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+wd)/oc;return((a,c)=>{let u=a,l=u.pow(c,i),d=u.mul(l,n),f=u.mul(l,o),h=u.mul(l,s),v=u.eql(u.sqr(d),c),E=u.eql(u.sqr(f),c);l=u.cmov(l,d,v),d=u.cmov(h,f,E);let y=u.eql(u.sqr(d),c),x=u.cmov(l,d,y);return qs(u,x,c),x})}function cc(r){if(r<tc)throw new Error("sqrt is not defined for small field");Hs(r,"tonelliShanks");let e=r-W,t=0;for(;e%ut===se;)e/=ut,t++;let n=ut,o=Yt(r);for(;Sr(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ac;let s=o.pow(n,e),i=(e+W)/ut;return function(c,u){let l=c;if(l.is0(u))return u;if(Sr(l,u)!==1)throw new Error("Cannot find square root");let d=t,f=l.mul(l.ONE,s),h=l.pow(u,e),v=l.pow(u,i);for(;!l.eql(h,l.ONE);){if(l.is0(h))throw new Error("Cannot find square root: probably non-prime P");let E=1,y=l.sqr(h);for(;!l.eql(y,l.ONE);)if(E++,y=l.sqr(y),E===d)throw new Error("Cannot find square root");let x=W<<BigInt(d-E-1),S=l.pow(f,x);d=E,f=l.sqr(S),h=l.mul(h,f),v=l.mul(v,S)}return v}}function Ad(r){return Hs(r,"Fp.sqrt"),r%Ks===tc?ac:r%nc===rc?Sd:r%oc===xd?_d(r):cc(r)}var uc=(r,e)=>(J(r,e)&W)===W,Bd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Zt(r){if(st(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);ct(r.BYTES,"BYTES"),ct(r.BITS,"BITS");for(let e of Bd)_t(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=W)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Nn(r,e,t=!1){Zt(r),Ln(e,"nums"),ye(t,"passZero");let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function Sr(r,e){Zt(r);let t=r;Hs(t.ORDER,"FpLegendre");let n=(t.ORDER-W)/ut,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Td(r,e){if(e!==void 0&&Us(e),r<=se)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Gt(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var ec=new WeakMap,Rn=class{ORDER;BITS;BYTES;isLE;ZERO=se;ONE=W;_lengths;_mod;constructor(e,t={}){if(e<=W)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=Td(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return J(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return se<=e&&e<this.ORDER}is0(e){return e===se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&W)===W}neg(e){return J(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return J(e*e,this.ORDER)}add(e,t){return J(e+t,this.ORDER)}sub(e,t){return J(e-t,this.ORDER)}mul(e,t){return J(e*t,this.ORDER)}pow(e,t){return sc(e,t,this.ORDER)}div(e,t){return J(e*Ja(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 Ja(e,this.ORDER)}sqrt(e){let t=ec.get(this);return t||ec.set(this,t=Ad(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Fs(e,this.BYTES):Pn(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Bt(e):qe(e);if(a&&(c=J(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nn(this,e,!0)}cmov(e,t,n){return ye(n,"condition"),n?t:e}};function Yt(r,e={}){return Object.freeze(Rn.prototype),new Rn(r,e)}function lc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=W)throw new Error("field order must be greater than 1");let e=Gt(r-W);return Math.ceil(e/8)}function Mn(r){let e=lc(r);return e+Math.ceil(e/2)}function Un(r,e,t=!1){V(r);let n=r.length,o=lc(e),s=Math.max(Mn(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Bt(r):qe(r),a=J(i,e-W)+W;return t?Fs(a,o):Pn(a,o)}var $s=BigInt(0),_r=BigInt(1),Id=BigInt(4),Vs=16,fc=128,Dd=5,dc=2**31;function lt(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);_t(e.fromAffine,"Point.fromAffine"),_t(e.fromBytes,"Point.fromBytes"),_t(e.fromHex,"Point.fromHex"),st(e.BASE,"Point.BASE"),st(e.ZERO,"Point.ZERO"),Zt(e.Fp),Zt(e.Fn)}function Fn(r,e){lt(r),pc(e,r);let t=Nn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function kd(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function Ld(r,e){let t=r*(4*e+128);if(t>dc)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+dc/2**20+" MiB")}function js(r,e){if(r!==void 0){_t(r,"randomBytes");try{let t=r(e);if(!at(t)||t.length!==e)return}catch{return}return r}}function pc(r,e){Ln(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Cd(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,o)=>{if(!(t===void 0?e.isValid(n):it(n)&&n<t))throw new Error("invalid scalar at index "+o)})}var mc=new WeakMap;function Ws(r){return mc.get(r)||1}function Pd(r,e){let t=r.double(),n=[r];for(let o=1;o<e;o++)n.push(n[o-1].add(t));return n}function Od(r,e){let t=2**e,n=t/2,o=BigInt(t-1),s=[];for(;r>$s;){let i=0;r&_r&&(i=Number(r&o),i>=n&&(i-=t),r-=BigInt(i)),s.push(i),r>>=_r}return s}function Rd(r,e,t){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let u=Number(r&s);r>>=i,u>o&&(u-=n,r+=_r),a.push(u)}if(r!==$s)throw new Error("invalid wnaf");return a}function Nd(r,e,t){let n=0;for(let s of t)n=Math.max(n,s.length);let o=r;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<t.length;i++){let a=t[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Xt=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){lt(e),this.randomBytes=js(t,Vs),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let o=Math.ceil(n/t)+1,s=2**(t-1),i=[],a=e;for(let c=0;c<o;c++){let u=a;for(let l=0;l<s;l++)i.push(u),u=u.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:o,comp:i}}wnafCachedCT(e,t){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=Rd(t,n,o),c=this.ZERO,u=this.BASE;for(let l=0;l<o;l++){let d=a[l],f=l*i,h=Math.abs(d)-1,v=s[f];for(let y=1;y<i;y++)v=y===h?s[f+y]:v;let E=v.negate();d===0?u=u.add(s[f]):c=c.add(d<0?E:v)}return{p:c,f:u}}getWnafPrecomputes(e,t,n,o){let s=this.wnafPrecomputes.get(t),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!zs(t,_r,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,o){let s=Ws(e);return s===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+fc,s=this.randomBytes(Vs);if(!at(s)||s.length!==Vs)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=t+qe(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,t,n){let o=Dd,s=1<<o,i=vr(o),a=new Array(s);a[0]=this.ZERO;for(let l=1;l<s;l++)a[l]=a[l-1].add(e);let c=Math.ceil(n/o),u=this.ZERO;for(let l=c-1;l>=0;l--){if(l!==c-1)for(let h=0;h<o;h++)u=u.double();let d=Number(t>>BigInt(l*o)&i),f=a[0];for(let h=1;h<s;h++)f=h===d?a[h]:f;u=u.add(f)}return{p:u,f:u}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===_r?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,n){if(this.assertPoint(e),!it(t))throw new Error("invalid scalar");let o=Ws(e);if(o===1||t>=this.Point.Fn.ORDER)return zn(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),kd(t,this.bits);let n=Math.ceil((this.bits+fc)/t)+1;Ld(n*2**(t-1),this.Point.Fp.BYTES),mc.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Ws(e)!==1}};function zn(r,e,t,n=!1){if(lt(r),pc(e,r),ye(n,"allowOversized"),Cd(t,r.Fn,n?r.Fn.ORDER**Id:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>Pd(i,4)),s=t.map(i=>Od(i,4));return Nd(r.ZERO,o,s)}function hc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Zt(e),e}else return Yt(r,{isLE:t})}function Kn(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);be(t);for(let c of["p","n","h"]){let u=e[c];if(!(it(u)&&u!==$s))throw new Error(`CURVE.${c} must be positive bigint`)}let o=hc(e.p,t.Fp,n),s=hc(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 qn(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Hn=BigInt(0),Vn=BigInt(1),Wn=BigInt(2),Md=BigInt(4),gc=BigInt(8);function Ud(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function yc(r,e={}){be(e,{},{},"extraOpts");let t=e,n=Kn("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(Sr(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Sr(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");be(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?At:t.randomBytes,u=Wn<<BigInt(o.BYTES*8)-Vn;function l(S){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(S)}let d=t.uvRatio===void 0?(S,g)=>{try{return{isValid:!0,value:o.sqrt(o.div(S,g))}}catch{return{isValid:!1,value:Hn}}}:t.uvRatio;if(!Ud(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let f=o.eql(i.a,o.neg(o.ONE))?S=>o.neg(S):o.eql(i.a,o.ONE)?S=>S:S=>o.mul(i.a,S);function h(S,g,A=!1){let T=A?Vn:Hn;return jt("coordinate "+S,g,T,u),g}function v(S){if(!(S instanceof E))throw new Error("EdwardsPoint expected")}class E{static BASE=new E(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new E(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(g,A,T,U){this.X=h("x",g),this.Y=h("y",A),this.Z=h("z",T,!0),this.T=h("t",U),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){if(g instanceof E)throw new Error("extended point not allowed");let{x:A,y:T}=g||{};return h("x",A),h("y",T),new E(A,T,o.ONE,o.mul(A,T))}static fromBytes(g,A=!1){let T=o.BYTES,{a:U,d:F}=i;g=On(V(g,T,"point")),ye(A,"zip215");let R=On(g),P=g[T-1];R[T-1]=P&-129;let O=Bt(R),z=A?u:o.ORDER;jt("point.y",O,Hn,z);let L=o.sqr(O),j=o.sub(L,o.ONE),k=o.sub(o.mulN(F,L),U),{isValid:D,value:p}=d(j,k);if(!D)throw new Error("bad point: invalid y coordinate");let b=l(p),_=(P&128)!==0;if(!A&&o.is0(p)&&_)throw new Error("bad point: x=0 and x_0=1");return _!==b&&(p=o.neg(p)),E.fromAffine({x:p,y:O})}static fromHex(g,A=!1){return E.fromBytes($t(g),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=6,A=!0){return x.setWindowSize(this,g),A||this.multiply(Wn),this}assertValidity(){let g=this,{a:A,d:T}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:U,Y:F,Z:R,T:P}=g,O=o.sqr(U),z=o.sqr(F),L=o.sqr(R),j=o.sqr(L),k=o.mul(O,A),D=o.mul(o.add(k,z),L),p=o.add(j,o.mul(T,o.mul(O,z)));if(!o.eql(D,p))throw new Error("bad point: equation left != right (1)");let b=o.mul(U,F),_=o.mul(R,P);if(!o.eql(b,_))throw new Error("bad point: equation left != right (2)")}equals(g){v(g);let{X:A,Y:T,Z:U}=this,{X:F,Y:R,Z:P}=g,O=o.mul(A,P),z=o.mul(F,U),L=o.mul(T,P),j=o.mul(R,U);return o.eql(O,z)&&o.eql(L,j)}is0(){return this.equals(E.ZERO)}negate(){return new E(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:g,Y:A,Z:T}=this,U=o.sqr(g),F=o.sqr(A),R=o.mul(o.sqr(T),Wn),P=f(U),O=o.addN(g,A),z=o.sub(o.subN(o.sqr(O),U),F),L=o.addN(P,F),j=o.subN(L,R),k=o.subN(P,F),D=o.mul(z,j),p=o.mul(L,k),b=o.mul(z,k),_=o.mul(j,L);return new E(D,p,_,b)}add(g){v(g);let{d:A}=i,{X:T,Y:U,Z:F,T:R}=this,{X:P,Y:O,Z:z,T:L}=g,j=o.mul(T,P),k=o.mul(U,O),D=o.mul(o.mulN(R,A),L),p=o.mul(F,z),b=o.sub(o.subN(o.mulN(o.addN(T,U),o.addN(P,O)),j),k),_=o.subN(p,D),C=o.addN(p,D),w=o.sub(k,f(j)),m=o.mul(b,_),B=o.mul(C,w),I=o.mul(b,w),N=o.mul(_,C);return new E(m,B,N,I)}subtract(g){return v(g),this.add(g.negate())}multiply(g){if(!s.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:A,f:T}=x.mulSecret(this,g,a,y);return y([A,T])[0]}multiplyUnsafe(g){if(!s.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===Hn?E.ZERO:this.is0()||g===Vn?this:x.mulUnsafe(this,g,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.mulUnsafe(this,i.n).is0()}toAffine(g){let A=this,T=g;if(T!=null&&typeof T!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof T);let{X:U,Y:F,Z:R}=A,P=A.is0();T==null&&(T=P?o.create(gc):o.inv(R));let O=o.mul(U,T),z=o.mul(F,T),L=o.mul(R,T);if(P)return{x:o.ZERO,y:o.ONE};if(!o.eql(L,o.ONE))throw new Error("invZ was invalid");return{x:O,y:z}}clearCofactor(){return a===Vn?this:a===Wn?this.double():a===Md?this.double().double():a===gc?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:g,y:A}=this.toAffine(),T=o.toBytes(A);return T[T.length-1]|=l(g)?128:0,T}toHex(){return xr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=S=>Fn(E,S),x=new Xt(E,c);return x.bits>=6&&E.BASE.precompute(6),Object.freeze(E.prototype),Object.freeze(E),E}function bc(r,e,t={}){if(lt(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;be(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(ct(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let d=o.randomBytes===void 0?At:o.randomBytes,f=o.toMontgomery,h=o.toMontgomerySecret,v=o.adjustScalarBytes===void 0?k=>k:o.adjustScalarBytes,E=o.domain===void 0?(k,D,p)=>{if(ye(p,"phflag"),D.length||p)throw new Error("Contexts/pre-hash are not supported");return k}:o.domain;function y(k){return c.create(Bt(k))}function x(k){let D=P.secretKey;V(k,P.secretKey,"secretKey");let p=V(n(k),2*D,"hashedSecretKey"),b=v(p.slice(0,D)),_=p.slice(D,2*D),C=y(b);return{head:b,prefix:_,scalar:C}}function S(k){let{head:D,prefix:p,scalar:b}=x(k),_=i.multiply(b),C=_.toBytes();return{head:D,prefix:p,scalar:b,point:_,pointBytes:C}}function g(k){return S(k).pointBytes}function A(k=Uint8Array.of(),...D){let p=Be(...D);return y(n(E(p,V(k,void 0,"context"),!!s)))}function T(k,D,p={}){be(p,{},{},"options"),k=V(k,void 0,"message"),s&&(k=s(k));let{prefix:b,scalar:_,pointBytes:C}=S(D),w=A(p.context,b,k),m=i.multiply(w).toBytes(),B=A(p.context,m,C,k),I=c.create(w+B*_);if(!c.isValid(I))throw new Error("sign failed: invalid s");let N=Be(m,c.toBytes(I));return V(N,P.signature,"result")}let U={zip215:o.zip215};function F(k,D,p,b=U){be(b);let{context:_}=b,C=b.zip215===void 0?!!U.zip215:b.zip215,w=P.signature;k=V(k,w,"signature"),D=V(D,void 0,"message"),p=V(p,P.publicKey,"publicKey"),C!==void 0&&ye(C,"zip215"),s&&(D=s(D));let m=w/2,B=k.subarray(0,m),I=Bt(k.subarray(m,w)),N,M,q;try{N=r.fromBytes(p,C),M=r.fromBytes(B,C),q=i.multiplyUnsafe(I)}catch{return!1}if(!C&&N.isSmallOrder())return!1;let K=A(_,B,p,D);return M.add(N.multiplyUnsafe(K)).subtract(q).clearCofactor().is0()}let R=a.BYTES,P={secretKey:R,publicKey:R,signature:2*R,seed:R};function O(k){return k=k===void 0?d(P.seed):k,V(k,P.seed,"seed")}function z(k){return at(k)&&k.length===P.secretKey}function L(k,D){try{return!!r.fromBytes(k,D===void 0?U.zip215:D)}catch{return!1}}let j={getExtendedPublicKey:S,randomSecretKey:O,isValidSecretKey:z,isValidPublicKey:L,toMontgomery(k){if(f===void 0)throw new Error("Montgomery conversion is not supported for this curve");return f(r.fromBytes(k))},toMontgomerySecret(k){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(k)}};return Object.freeze(P),Object.freeze(j),Object.freeze({keygen:qn(O,g),getPublicKey:g,sign:T,verify:F,utils:j,Point:r,lengths:P})}var Gs=BigInt(1),wc=BigInt(2);var Fd=BigInt(5),zd=BigInt(8),Zs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Kd={p:Zs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:zd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function qd(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Zs,a=r*r%s*r%s,c=Y(a,wc,s)*a%s,u=Y(c,Gs,s)*r%s,l=Y(u,Fd,s)*u%s,d=Y(l,e,s)*l%s,f=Y(d,t,s)*d%s,h=Y(f,n,s)*f%s,v=Y(h,o,s)*h%s,E=Y(v,o,s)*h%s,y=Y(E,e,s)*l%s;return{pow_p_5_8:Y(y,wc,s)*r%s,b2:a}}function vc(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var xc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Hd(r,e){let t=Zs,n=J(e*e*e,t),o=J(n*n*e,t),s=qd(r*o).pow_p_5_8,i=J(r*n*s,t),a=J(e*i*i,t),c=i,u=J(i*xc,t),l=a===r,d=a===J(-r,t),f=a===J(-r*xc,t);return l&&(i=c),(d||f)&&(i=u),uc(i,t)&&(i=J(-i,t)),{isValid:l||d,value:i}}var Ys=yc(Kd,{uvRatio:Hd}),Ec=Ys.Fp;function Vd(r){let{y:e}=r;return Ec.toBytes(Ec.div(Gs+e,Gs-e))}function Wd(r){let e=Ys.Fp.BYTES;return Ae(r,e),vc(Ms(r.subarray(0,e))).subarray(0,e)}function $d(r){return bc(Ys,Ms,Object.assign({adjustScalarBytes:vc,toMontgomery:Vd,toMontgomerySecret:Wd,zip215:!0},r))}var Sc=$d({});var Ar=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},$n=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var jn={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new $n("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Gn=32;var Xs,jd=(async()=>{try{return await jn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Gd(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await jn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await jn.get().subtle.verify({name:"Ed25519"},n,De(e),De(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Zd(r,e,t){return Sc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function _c(r,e,t){return Xs==null&&(Xs=await jd),Xs?Gd(r,e,t):Zd(r,e,t)}function Zn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Yn=class{type="Ed25519";raw;constructor(e){this.raw=Qs(e,Gn)}toMultihash(){return Ie.digest(Vt(this))}toCID(){return Q.createV1(114,this.toMultihash())}toString(){return oe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ne(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=_c(this.raw,t,e);return Zn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Bc(r){return r=Qs(r,Gn),new Yn(r)}function Qs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Se(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ge||(ge={}));var Js;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Js||(Js={}));(function(r){r.codec=()=>Ft(Js)})(ge||(ge={}));var Br;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Br||(Br={}));var ei;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(ei||(ei={}));var Xn=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(An(e),Ae(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");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),St(o)}update(e){return Wt(this),this.iHash.update(e),this}digestInto(e){Wt(this),Bn(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),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,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,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()}},Tc=(()=>{let r=((e,t,n)=>new Xn(e,t).update(n).digest());return r.create=(e,t)=>new Xn(e,t),r})();var Qd=BigInt(0),ti=class extends Error{constructor(e=""){super(e)}},je={Err:ti,_tlv:{encode:(r,e)=>{let{Err:t}=je;if(ct(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(Ya(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Er(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Er(o.length/2|128):"";return Er(r)+s+o+e},decode(r,e){let{Err:t}=je;e=V(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: 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 u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;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}=je;if(Cn(r),r<Qd)throw new e("integer: negative integers are not allowed");let t=Er(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}=je;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return qe(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=je,o=V(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:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=je;be(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},ri=(Object.freeze(je._tlv),Object.freeze(je._int),Object.freeze(je));var Ic=(r,e)=>(r+(r>=0?e:-e)/Dc)/e;function Jd(r,e,t){jt("scalar",r,Ge,t);let[[n,o],[s,i]]=e,a=Ic(i*r,t),c=Ic(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,d=u<Ge,f=l<Ge;d&&(u=-u),f&&(l=-l);let h=vr(Math.ceil(Gt(t)/2))+Tt;if(u<Ge||u>=h||l<Ge||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:u,k2neg:f,k2:l}}function si(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ni(r,e){be(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return ye(t.lowS,"lowS"),ye(t.prehash,"prehash"),t.format!==void 0&&si(t.format),t}var Ge=BigInt(0),Tt=BigInt(1),Dc=BigInt(2),oi=BigInt(3),eh=BigInt(4);function kc(r,e={}){let t=Kn("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;be(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:u}=e,l=e.randomBytes===void 0?At:e.randomBytes;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 d=Cc(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(D,p,b){if(u&&p.is0())return Uint8Array.of(0);let{x:_,y:C}=p.toAffine(),w=n.toBytes(_);if(ye(b,"isCompressed"),b){f();let m=!n.isOdd(C);return Be(Lc(m),w)}else return Be(Uint8Array.of(4),w,n.toBytes(C))}function v(D){V(D,void 0,"Point");let{publicKey:p,publicKeyUncompressed:b}=d,_=D.length,C=D[0],w=D.subarray(1);if(u&&_===1&&C===0)return{x:n.ZERO,y:n.ZERO};if(_===p&&(C===2||C===3)){let m=n.fromBytes(w);if(!n.isValid(m))throw new Error("bad point: is not on curve, wrong x");let B=g(m),I;try{I=n.sqrt(B)}catch(q){let K=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}f();let N=n.isOdd(I);return(C&1)===1!==N&&(I=n.neg(I)),{x:m,y:I}}else if(_===b&&C===4){let m=n.BYTES,B=n.fromBytes(w.subarray(0,m)),I=n.fromBytes(w.subarray(m,m*2));if(!A(B,I))throw new Error("bad point: is not on curve");return{x:B,y:I}}else throw new Error(`bad point: got length ${_}, expected compressed=${p} or uncompressed=${b}`)}let E=e.toBytes===void 0?h:e.toBytes,y=e.fromBytes===void 0?v:e.fromBytes,x=n.mul(s.b,oi),S=n.is0(s.a)?D=>n.ZERO:D=>n.mul(s.a,D);function g(D){let p=n.sqr(D),b=n.mul(p,D);return n.add(n.add(b,n.mul(D,s.a)),s.b)}function A(D,p){let b=n.sqr(p),_=g(D);return n.eql(b,_)}if(!A(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let T=n.mul(n.pow(s.a,oi),eh),U=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(T,U)))throw new Error("bad curve params: a or b");function F(D,p,b=!1){if(!n.isValid(p)||b&&n.is0(p))throw new Error(`bad point coordinate ${D}`);return p}function R(D){if(!(D instanceof L))throw new Error("Weierstrass Point expected")}function P(D){if(!c||!c.basises)throw new Error("no endo");return Jd(D,c.basises,o.ORDER)}function O(D,p,b,_){if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(c){let{k1neg:C,k1:w,k2neg:m,k2:B}=P(_),I=new L(n.mul(b.X,c.beta),b.Y,b.Z);D.push(C?b.negate():b,m?I.negate():I),p.push(w,B)}else D.push(b),p.push(_)}let z=new WeakSet;class L{static BASE=new L(s.Gx,s.Gy,n.ONE);static ZERO=new L(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,b,_){this.X=F("x",p),this.Y=F("y",b,!0),this.Z=F("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x:b,y:_}=p||{};if(!p||!n.isValid(b)||!n.isValid(_))throw new Error("invalid affine point");if(p instanceof L)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(_)?L.ZERO:new L(b,_,n.ONE)}static fromBytes(p){let b=L.fromAffine(y(V(p,void 0,"point")));return b.assertValidity(),b}static fromHex(p){return L.fromBytes($t(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=6,b=!0){return k.setWindowSize(this,p),b||this.multiply(oi),this}assertValidity(){let p=this;if(p.is0()){if(e.allowInfinityPoint&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}if(z.has(p))return;let{x:b,y:_}=p.toAffine();if(!n.isValid(b)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!A(b,_))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");z.add(p)}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){R(p);let{X:b,Y:_,Z:C}=this,{X:w,Y:m,Z:B}=p,I=n.eql(n.mul(b,B),n.mul(w,C)),N=n.eql(n.mul(_,B),n.mul(m,C));return I&&N}negate(){return new L(this.X,n.neg(this.Y),this.Z)}double(){let{X:p,Y:b,Z:_}=this,C=n.ZERO,w=n.ZERO,m=n.ZERO,B=n.mul(p,p),I=n.mul(b,b),N=n.mul(_,_),M=n.mul(p,b);return M=n.add(M,M),m=n.mul(p,_),m=n.add(m,m),C=S(m),w=n.mul(x,N),w=n.add(C,w),C=n.sub(I,w),w=n.add(I,w),w=n.mul(C,w),C=n.mul(M,C),m=n.mul(x,m),N=S(N),M=n.sub(B,N),M=S(M),M=n.add(M,m),m=n.add(B,B),B=n.add(m,B),B=n.add(B,N),B=n.mul(B,M),w=n.add(w,B),N=n.mul(b,_),N=n.add(N,N),B=n.mul(N,M),C=n.sub(C,B),m=n.mul(N,I),m=n.add(m,m),m=n.add(m,m),new L(C,w,m)}add(p){R(p);let{X:b,Y:_,Z:C}=this,{X:w,Y:m,Z:B}=p,I=n.ZERO,N=n.ZERO,M=n.ZERO,q=n.mul(b,w),K=n.mul(_,m),ee=n.mul(C,B),me=n.add(b,_),te=n.add(w,m);me=n.mul(me,te),te=n.add(q,K),me=n.sub(me,te),te=n.add(b,C);let de=n.add(w,B);return te=n.mul(te,de),de=n.add(q,ee),te=n.sub(te,de),de=n.add(_,C),I=n.add(m,B),de=n.mul(de,I),I=n.add(K,ee),de=n.sub(de,I),M=S(te),I=n.mul(x,ee),M=n.add(I,M),I=n.sub(K,M),M=n.add(K,M),N=n.mul(I,M),K=n.add(q,q),K=n.add(K,q),ee=S(ee),te=n.mul(x,te),K=n.add(K,ee),ee=n.sub(q,ee),ee=S(ee),te=n.add(te,ee),q=n.mul(K,te),N=n.add(N,q),q=n.mul(de,te),I=n.mul(me,I),I=n.sub(I,q),q=n.mul(me,K),M=n.mul(de,M),M=n.add(M,q),new L(I,N,M)}subtract(p){return R(p),this.add(p.negate())}is0(){return this.equals(L.ZERO)}multiply(p){if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let{p:b,f:_}=k.mulSecret(this,p,i,j);return j([b,_])[0]}multiplyUnsafe(p){let b=this,_=p;if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(_===Ge||b.is0())return L.ZERO;if(_===Tt)return b;if(k.hasWindowSize(this))return k.mulUnsafe(b,_,j);let C=[],w=[];return O(C,w,b,_),zn(L,C,w)}mulAddUnsafe(p,b,_){R(b);let C=[],w=[];return O(C,w,this,p),O(C,w,b,_),zn(L,C,w)}toAffine(p){let b=this,_=p;if(_!=null&&!n.isValid(_))throw new RangeError('"invertedZ" expected valid field element');let{X:C,Y:w,Z:m}=b;if(n.eql(m,n.ONE))return{x:C,y:w};let B=b.is0();_==null&&(_=B?n.ONE:n.inv(m));let I=n.mul(C,_),N=n.mul(w,_),M=n.mul(m,_);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(M,n.ONE))throw new Error("invZ was invalid");return{x:I,y:N}}isTorsionFree(){let{isTorsionFree:p}=e;return i===Tt?!0:p?p(L,this):k.mulUnsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return i===Tt?this:p?p(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Tt?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return ye(p,"isCompressed"),this.assertValidity(),E(L,this,p)}toHex(p=!0){return xr(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let j=D=>Fn(L,D),k=new Xt(L,l);return k.bits>=6&&L.BASE.precompute(6),Object.freeze(L.prototype),Object.freeze(L),L}function Lc(r){return Uint8Array.of(r?2:3)}function Cc(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function th(r,e={}){lt(r);let{Fn:t}=r,n=e.randomBytes===void 0?At:e.randomBytes,o=Object.assign(Cc(r.Fp,t),{seed:Math.max(Mn(t.ORDER),16)});function s(h){try{let v=t.fromBytes(h);return t.isValidNot0(v)}catch{return!1}}function i(h,v){let{publicKey:E,publicKeyUncompressed:y}=o;try{let x=h.length;return v===!0&&x!==E||v===!1&&x!==y?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,Un(V(h,o.seed,"seed"),t.ORDER)}function c(h,v=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(v)}function u(h){let{secretKey:v,publicKey:E,publicKeyUncompressed:y}=o,x=t._lengths;if(!at(h))return;let S=V(h,void 0,"key").length,g=S===E||S===y,A=S===v||!!x?.includes(S);if(!(g&&A))return g}function l(h,v,E=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(v)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(h);return r.fromBytes(v).multiply(y).toBytes(E)}let d={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},f=qn(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:f,Point:r,utils:d,lengths:o})}function Pc(r,e,t={}){lt(r);let n=e;An(n),be(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},t),s=o.randomBytes===void 0?At:o.randomBytes,i=o.hmac===void 0?(w,m)=>Tc(n,w,m):o.hmac,{Fp:a,Fn:c}=r,{ORDER:u,BITS:l}=c,d=Mn(u),f=js(s,d),{keygen:h,getPublicKey:v,getSharedSecret:E,utils:y,lengths:x}=th(r,o),S={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},g=u*Dc+Tt<a.ORDER;function A(w){let m=u>>Tt;return w>m}function T(w,m){if(!c.isValidNot0(m))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return m}function U(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function F(w,m,B){return U(),(w===B?0:2)|Number(a.isOdd(m))}function R(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(w,m){si(m);let B=x.signature,I=m==="compact"?B:m==="recovered"?B+1:void 0;return V(w,I)}class O{r;s;recovery;constructor(m,B,I){if(this.r=T("r",m),this.s=T("s",B),I!=null){if(R(),![0,1,2,3].includes(I))throw new Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(m,B=S.format){P(m,B);let I;if(B==="der"){let{r:K,s:ee}=ri.toSig(V(m));return new O(K,ee)}B==="recovered"&&(I=m[0],B="compact",m=m.subarray(1));let N=x.signature/2,M=m.subarray(0,N),q=m.subarray(N,N*2);return new O(c.fromBytes(M),c.fromBytes(q),I)}static fromHex(m,B){return this.fromBytes($t(m),B)}assertRecovery(){let{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new O(this.r,this.s,m)}recoverPublicKey(m){let{r:B,s:I}=this,N=this.assertRecovery(),M=N===2||N===3?B+u:B;if(!a.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let q=a.toBytes(M),K=r.fromBytes(Be(Lc((N&1)===0),q)),ee=c.inv(M),me=L(V(m,void 0,"msgHash")),te=c.create(-me*ee),de=c.create(I*ee),Oe=r.BASE.mulAddUnsafe(te,K,de);if(Oe.is0())throw new Error("invalid recovery: point at infinify");return Oe.assertValidity(),Oe}hasHighS(){return A(this.s)}toBytes(m=S.format){if(si(m),m==="der")return $t(ri.hexFromSig(this));let{r:B,s:I}=this,N=c.toBytes(B),M=c.toBytes(I);return m==="recovered"?(R(),Be(Uint8Array.of(this.assertRecovery()),N,M)):Be(N,M)}toHex(m){return xr(this.toBytes(m))}}Object.freeze(O.prototype),Object.freeze(O);let z=o.bits2int===void 0?function(m){if(m.length>8192)throw new Error("input is too large");let B=qe(m),I=m.length*8-l;return I>0?B>>BigInt(I):B}:o.bits2int,L=o.bits2int_modN===void 0?function(m){return c.create(z(m))}:o.bits2int_modN,j=vr(l);function k(w){return jt("num < 2^"+l,w,Ge,j),c.toBytes(w)}function D(w,m){return V(w,void 0,"message"),m?V(n(w),void 0,"prehashed message"):w}function p(w,m,B){let{lowS:I,prehash:N,extraEntropy:M}=ni(B,S);w=D(w,N);let q=L(w),K=c.fromBytes(m);if(!c.isValidNot0(K))throw new Error("invalid private key");let ee=[k(K),k(q)];if(M!=null&&M!==!1){let Oe=M===!0?s(x.secretKey):M;ee.push(V(Oe,void 0,"extraEntropy"))}let me=Be(...ee),te=q;function de(Oe){let Ct=z(Oe);if(!c.isValidNot0(Ct))return;let Jt=r.BASE.multiply(Ct).toAffine(),Ye=c.create(Jt.x);if(Ye===Ge)return;let Re;if(f!==void 0){let er=qe(Un(f(d),u)),Xc=c.inv(c.mul(er,Ct)),Qc=c.mul(er,te),Jc=c.mul(er,K);Re=c.create(Xc*c.create(Qc+Jc*Ye))}else{let er=ic(Ct,u);Re=c.create(er*c.create(te+Ye*K))}if(Re===Ge)return;let go=F(Jt.x,Jt.y,Ye),yi=Re;return I&&A(Re)&&(yi=c.neg(Re),go^=1),new O(Ye,yi,g?void 0:go)}return{seed:me,k2sig:de}}function b(w,m,B={}){let{seed:I,k2sig:N}=p(w,m,B);return Qa(n.outputLen,c.BYTES,i)(I,N).toBytes(B.format)}function _(w,m,B,I={}){let{lowS:N,prehash:M,format:q}=ni(I,S);if(B=V(B,void 0,"publicKey"),m=D(m,M),!at(w)){let K=w instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+K)}P(w,q);try{let K=O.fromBytes(w,q),ee=r.fromBytes(B);if(N&&K.hasHighS())return!1;let{r:me,s:te}=K,de=L(m),Oe=c.inv(te),Ct=c.create(de*Oe),Jt=c.create(me*Oe),Ye=r.BASE.mulAddUnsafe(Ct,ee,Jt);if(Ye.is0())return!1;let Re=Ye.toAffine();return!(c.create(Re.x)!==me||q==="recovered"&&K.recovery!==F(Re.x,Re.y,me))}catch{return!1}}function C(w,m,B={}){let{prehash:I}=ni(B,S);return m=D(m,I),O.fromBytes(w,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:h,getPublicKey:v,getSharedSecret:E,utils:y,lengths:x,Point:r,sign:b,verify:_,recoverPublicKey:C,Signature:O,hash:n})}var ai={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},rh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Oc=BigInt(2);function nh(r){let e=ai.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,d=Y(l,t,e)*l%e,f=Y(d,t,e)*l%e,h=Y(f,Oc,e)*u%e,v=Y(h,o,e)*h%e,E=Y(v,s,e)*v%e,y=Y(E,a,e)*E%e,x=Y(y,c,e)*y%e,S=Y(x,a,e)*E%e,g=Y(S,t,e)*l%e,A=Y(g,i,e)*v%e,T=Y(A,n,e)*u%e,U=Y(T,Oc,e);if(!ii.eql(ii.sqr(U),r))throw new Error("Cannot find square root");return U}var ii=Yt(ai.p,{sqrt:nh}),oh=kc(ai,{Fp:ii,endo:rh}),Qt=Pc(oh,Ga);function Rc(r,e,t,n){let o=et.digest(t instanceof Uint8Array?t:t.subarray());if(Zn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Qt.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Ar(String(s))});try{return n?.signal?.throwIfAborted(),Qt.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Ar(String(s))}}var Qn=class{type="secp256k1";raw;_key;constructor(e){this._key=Mc(e),this.raw=Nc(this._key)}toMultihash(){return Ie.digest(Vt(this))}toCID(){return Q.createV1(114,this.toMultihash())}toString(){return oe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ne(this.raw,e.raw)}verify(e,t,n){return Rc(this._key,t,e,n)}};function Uc(r){return new Qn(r)}function Nc(r){return Qt.Point.fromBytes(r).toBytes()}function Mc(r){try{return Qt.Point.fromBytes(r),r}catch(e){throw new Pr(String(e))}}function Fc(r){let{Type:e,Data:t}=Br.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return Bc(n);case ge.secp256k1:return Uc(n);case ge.ECDSA:return Ta(n);default:throw new tr}}function Vt(r){return Br.encode({Type:ge[r.type],Data:r.raw})}var zc=Symbol.for("nodejs.util.inspect.custom"),sh=114,Tr=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()})`}[Ur]=!0;toString(){return this.string==null&&(this.string=oe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Q.createV1(sh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ne(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ne(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[zc](){return`PeerId(${this.toString()})`}},Jn=class extends Tr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},eo=class extends Tr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},to=class extends Tr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},ih=2336,Ir=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ie.digest(Z(this.url))}[zc](){return`PeerId(${this.url})`}[Ur]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Q.createV1(ih,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var ah=114,Kc=2336;function ch(r){if(lh(r))return new Jn({multihash:r});if(uh(r))try{let e=Fc(r);if(e.type==="Ed25519")return new eo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new to({multihash:r,publicKey:e})}catch{let t=$(r.digest);return new Ir(new URL(t))}throw new Rr("Supplied PeerID Multihash is invalid")}function ro(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==ah&&r.code!==Kc)throw new Or("Supplied PeerID CID is invalid");if(r.code===Kc){let e=$(r.multihash.digest);return new Ir(new URL(e))}return ch(r.multihash)}function uh(r){return r.code===Ie.code}function lh(r){return r.code===et.code}function fh(r){return r[Symbol.asyncIterator]!=null}function dh(r){if(fh(r))return(async()=>{for await(let e of r);})();for(let e of r);}var qc=dh;function hh(r){return r[Symbol.asyncIterator]!=null}function ph(r,e){let t=0;if(hh(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=Ea(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Hc=ph;function mh(r){return r[Symbol.asyncIterator]!=null}function gh(r,e){return mh(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Vc=gh;var ci="/ipfs/bitswap/1.2.0";var X;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(X||(X={}));var ui;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ui||(ui={}));(function(r){r.codec=()=>Ft(ui)})(X||(X={}));var It;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),X.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:ue(0),priority:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=X.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:X.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(It||(It={}));var Dr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),It.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new He('Decode error - repeated field "entries" had too many elements');c.entries.push(It.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={entries:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let d=s.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&u.entries===c.limits.entries)throw new He('Streaming decode error - repeated field "entries" had too many elements');for(let f of It.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...f,index:u.entries};u.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Dr||(Dr={}));var Dt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:ue(0),data:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Dt||(Dt={}));var ve;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(ve||(ve={}));var no;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(no||(no={}));(function(r){r.codec=()=>Ft(no)})(ve||(ve={}));var kt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&no[s.type]!==0&&(i.uint32(16),ve.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:ue(0),type:ve.HaveBlock},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=ve.codec().decode(s);break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:ve.codec().decode(s)};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(kt||(kt={}));var Lt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),Dr.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Dt.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),kt.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.wantlist=Dr.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new He('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Dt.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new He('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(kt.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={blocks:0,blockPresences:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let d=s.uint32();switch(d>>>3){case 1:{yield*Dr.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&u.blocks===c.limits.blocks)throw new He('Streaming decode error - repeated field "blocks" had too many elements');for(let f of Dt.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...f,index:u.blocks};u.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&u.blockPresences===c.limits.blockPresences)throw new He('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of kt.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...f,index:u.blockPresences};u.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Lt||(Lt={}));function Wc(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var oo=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var yh=4193648,bh=yh+16;function*$c(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let u={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},l=Lt.encode(u).byteLength,{added:d,hasMore:f,newSize:h}=li(o,u.blocks,a,e,l,wh);a+=d,l=h;let v=f;({added:d,hasMore:f,newSize:h}=li(n,u.blockPresences,i,e,l,xh)),i+=d,l=h;let E=f;if({added:d,hasMore:f,newSize:h}=li(t,u.wantlist.entries,s,e,l,Eh),s+=d,l=h,c=!v&&!E&&!f,c||(u.wantlist.full=!1),yield Lt.encode(u),c)break}}function li(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let u=r[c],l=s(u);if(l>bh)throw new oo("Cannot send block as after encoding it is over the max message size");let d=o+l;if(d>n){a=!0;break}e.push(u),i++,o=d}return{hasMore:a,added:i,newSize:o}}function wh(r){return fi(3,Dt.encode(r))}function xh(r){return fi(4,kt.encode(r))}function Eh(r){return fi(1,It.encode(r))}function fi(r,e){let t=G(r),n=G(e.byteLength);return t+n+e.byteLength}function Lh(r){if(Fr(r))return r;if(En(r))return ro(r);if(on(r)||Array.isArray(r))return r;throw new Se(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var so=class extends Ne{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[ci],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new wn({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new Nr(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=an();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of pr(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Lt.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new ce("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,router:n.router})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await qc(Hc(Vc(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=Wc(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Se("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new ce("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,ci,s);await a.closeRead(s);try{for(let c of $c(i,this.maxOutgoingMessageSize))a.send(bn.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new ce("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Mr("Network isn't running");return e=Lh(e),t?.onProgress?.(new ce("bitswap:dial",e)),this.libp2p.dial(e,t)}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function io(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var kr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return io(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return io(this.map.values(),e=>e.key)}values(){return io(this.map.values(),e=>e.value)}get size(){return this.map.size}};var di=class extends kr{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Lr(r){let{name:e,metrics:t}=r,n;return t!=null?n=new di({name:e,metrics:t}):n=new kr,n}var ao=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};var Ze=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=ht.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=ht.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=ht.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Ch(r){let e=new Uint8Array(r.reduce((n,o)=>n+G(o),0)),t=0;for(let n of r)e=Hr(n,e,t),t+=G(n);return e}var jc=Ch;function hi(r){return jc([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var co=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;sendQueue;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024,this.sendQueue=new tt({concurrency:t.sendBlocksConcurrency??1,maxSize:t.sendBlocksMaxQueueLength??10})}stop(){this.sendQueue.abort()}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=Q.decode(n.cid),s=$(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===X.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===X.WantHave&&(n.wantType==null||n.wantType===X.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??X.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??X.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=$(e.multihash.bytes,"base64");return this.wants.has(t)}queueSendOperation(e,t){e!=null&&(this.receivedBytes(e.blocks?.reduce((n,o)=>n+o.data.byteLength,0)??0),this.addWants(e.wantlist));try{this.sendQueue.add(async n=>{this.log("send blocks to peer"),await this.sendBlocksToPeer(n)},t).catch(n=>{n.name==="QueueFullError"?this.log.error("Dropping bitswap message as peer send queue is full"):this.log.error("Error when trying to add queue a send operation")})}catch(n){if(n.name==="QueueFullError")this.log.error("Dropping bitswap message as peer send queue is full");else throw n}}async sendBlocksToPeer(e){let t=new Ze,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");if(o.length!==0){o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{if(!await this.blockstore.has(i.cid,e))throw new ao;let c=await va(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===X.WantHave?c.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:c,prefix:hi(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ve.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:c,prefix:hi(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ve.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}}};var uo=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;sendBlocksConcurrency;sendBlocksMaxQueueLength;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.sendBlocksConcurrency=t.sendBlocksConcurrency,this.sendBlocksMaxQueueLength=t.sendBlocksMaxQueueLength,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Lr({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{try{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message)}catch(o){this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)}}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}start(){}stop(){this.ledgerMap.forEach(e=>{e.stop()})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount,sendQueue:t.sendQueue}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new co({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize,sendBlocksConcurrency:this.sendBlocksConcurrency,sendBlocksMaxQueueLength:this.sendBlocksMaxQueueLength}),this.ledgerMap.set(e,n)),n.queueSendOperation(t)}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.queueSendOperation(void 0,t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var pi=class extends xn{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){if(n.signal?.aborted===!0)throw new Yr(`Signal to want session block for CID ${e} from peer ${t} was aborted prior to want`);let o=ro(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,router:n.router,toString:()=>`Bitswap(${n.id})`,fallback:n.fallback}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(En(e))return{peerId:e,router:t,toString:()=>`Bitswap(${e})`,fallback:!1};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),router:t,toString:()=>`Bitswap(${o.remotePeer})`,fallback:!1}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],router:t.router,fallback:t.fallback},router:t.router}))}};function Gc(r,e){return new pi(r,e)}var lo=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var fo=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Cr(r,e,t,n){let o=new fo(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){gi(t,"abort",d),gi(r,e,u),gi(r,s,l)}let u=f=>{try{if(n?.filter?.(f)===!1)return}catch(h){c(),a(h);return}c(),i(f)},l=f=>{if(c(),f instanceof Error){a(f);return}a(f.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(o)};mi(t,"abort",d),mi(r,e,u),mi(r,s,l)})}function mi(r,e,t){r!=null&&(Zc(r)?r.addEventListener(e,t):r.addListener(e,t))}function gi(r,e,t){r!=null&&(Zc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Zc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Ph(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=pt(r);e.push(t),r=r.slice(G(t))}return e}var Yc=Ph;var ho=class extends Ne{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Lr({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=wa({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=$(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??X.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===X.WantHave&&t.wantType===X.WantBlock&&(o.wantType=X.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===X.WantBlock?(await Cr(this,"block",t?.signal,{filter:a=>ne(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Cr(this,"presence",t?.signal,{filter:i=>ne(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ce(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Ze;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=$(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Ze;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:X.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await Cr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&ne(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:X.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Ze;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:X.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await Cr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&ne(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=$(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=Yc(o.prefix),i=s[0],a=s[1],c=s[2],u=s[3],l=c===et.code?et:await this.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let d=l.digest(o.data,{truncate:u});d.then!=null&&(d=await d);let f=Q.create(i===0?0:1,a,d);this.log("received block from %p for %c",e.remotePeer,f),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:f,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:f,has:!0,block:o.data}});let h=$(f.multihash.bytes,"base64"),v=this.wants.get(h);v!=null&&(v.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=Q.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===ve.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Ze(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:X.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var po=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new lo(e),this.network=new so(e,t),this.peerWantLists=new uo({...e,network:this.network},t),this.wantList=new ho({...e,network:this.network},t)}createSession(e={}){return Gc({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=xi([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new ce("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),this.peerWantLists.stop(),await this.network.stop()}};var mo=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new po(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!Fr(o.detail))return;t.onProgress(new ce("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new ce("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new ce("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new ce("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function Oh(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new mo(n,e);await bi(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}return ou(Rh);})();
2
+ "use strict";var HeliaBitswap=(()=>{var bo=Object.defineProperty;var tu=Object.getOwnPropertyDescriptor;var ru=Object.getOwnPropertyNames;var nu=Object.prototype.hasOwnProperty;var Se=(r,e)=>{for(var t in e)bo(r,t,{get:e[t],enumerable:!0})},ou=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ru(e))!nu.call(r,o)&&o!==t&&bo(r,o,{get:()=>e[o],enumerable:!(n=tu(e,o))||n.enumerable});return r};var su=r=>ou(bo({},"__esModule",{value:!0}),r);var Mh={};Se(Mh,{withBitswap:()=>Nh});var Ie=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var De=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Or=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Rr=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Nr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Mr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Ur=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var tr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Fr=Symbol.for("@libp2p/peer-id");function zr(r){return!!r?.[Fr]}function iu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function bi(...r){let e=[];for(let t of r)iu(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}function au(r){return typeof r?.handleEvent=="function"}function cu(r){return r===!0||r===!1}function uu(r){return cu(r)?r:r?.capture??!1}function wo(r){let e={capture:uu(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function wi(r,e){return wo(r).capture===wo(e).capture}var Fe=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=wo(n);if(o?.signal?.aborted===!0)return;let s=u=>{o.once&&this.removeEventListener(e,t,o),au(t)?t.handleEvent(u):t(u)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(u=>u.callback!==t?!1:wi(u.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,t,o)};o.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:s,options:o,onAbort:c})}removeEventListener(e,t,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,o.filter(s=>s.callback===t&&wi(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var pe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function xi(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Vh=new Uint8Array(0);function vi(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ke(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return ht(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return ht(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Si(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var Ei=4096;function _i(r){let e=r.length;if(e<=Ei)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=Ei));return t}function lu(r){return r?.buffer instanceof ArrayBuffer}function ht(r){return lu(r)?r:r.slice()}var _o={};Se(_o,{base32:()=>tt,base32hex:()=>xu,base32hexpad:()=>vu,base32hexpadupper:()=>Su,base32hexupper:()=>Eu,base32pad:()=>bu,base32padupper:()=>wu,base32upper:()=>yu,base32z:()=>_u});function fu(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),u!==a&&(n[u]=s)}}var l=r.length,f=r.charAt(0),d=Math.log(l)/Math.log(256),p=Math.log(256)/Math.log(l);function E(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var S=0,m=0,_=0,A=x.length;_!==A&&x[_]===0;)_++,S++;for(var O=(A-_)*p+1>>>0,M=new Uint8Array(O);_!==A;){for(var R=x[_],k=0,C=O-1;(R!==0||k<m)&&C!==-1;C--,k++)R+=256*M[C]>>>0,M[C]=R%l>>>0,R=R/l>>>0;if(R!==0)throw new Error("Non-zero carry");m=k,_++}for(var K=O-m;K!==O&&M[K]===0;)K++;for(var z=f.repeat(S);K<O;++K)z+=r.charAt(M[K]);return z}function w(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var S=0;if(x[S]!==" "){for(var m=0,_=0;x[S]===f;)m++,S++;for(var A=(x.length-S)*d+1>>>0,O=new Uint8Array(A);x[S];){var M=n[x.charCodeAt(S)];if(M===255)return;for(var R=0,k=A-1;(M!==0||R<_)&&k!==-1;k--,R++)M+=l*O[k]>>>0,O[k]=M%256>>>0,M=M/256>>>0;if(M!==0)throw new Error("Non-zero carry");_=R,S++}if(x[S]!==" "){for(var C=A-_;C!==A&&O[C]===0;)C++;for(var K=new Uint8Array(m+(A-C)),z=m;C!==A;)K[z++]=O[C++];return K}}}function y(x){var S=w(x);if(S)return S;throw new Error(`Non-${e} character`)}return{encode:E,decodeUnsafe:w,decode:y}}var du=fu,hu=du,Bi=hu;var xo=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Eo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ti(this,e)}},vo=class{decoders;constructor(e){this.decoders=e}or(e){return Ti(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Ti(r,e){return new vo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var So=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new xo(e,t,n),this.decoder=new Eo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ot({name:r,prefix:e,encode:t,decode:n}){return new So(r,e,t,n)}function et({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Bi(t,r,n);return Ot({prefix:e,name:r,encode:o,decode:i=>ke(s(i))})}function pu(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function mu(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function gu(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function se({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=gu(n,o);return Ot({prefix:e,name:r,encode(i){return mu(i,n,t)},decode(i){return pu(i,s,t,r)}})}var tt=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),yu=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),bu=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),wu=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),xu=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Eu=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),vu=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Su=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),_u=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ao={};Se(Ao,{base36:()=>rr,base36upper:()=>Au});var rr=et({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Au=et({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Bo={};Se(Bo,{base58btc:()=>ue,base58flickr:()=>Bu});var ue=et({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bu=et({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Tu=ki,Ii=128,Iu=127,Du=~Iu,ku=Math.pow(2,31);function ki(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ku;)e[t++]=r&255|Ii,r/=128;for(;r&Du;)e[t++]=r&255|Ii,r>>>=7;return e[t]=r|0,ki.bytes=t-n+1,e}var Lu=To,Cu=128,Di=127;function To(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw To.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Di)<<o:(i&Di)*Math.pow(2,o),o+=7}while(i>=Cu);return To.bytes=s-n,t}var Pu=Math.pow(2,7),Ou=Math.pow(2,14),Ru=Math.pow(2,21),Nu=Math.pow(2,28),Mu=Math.pow(2,35),Uu=Math.pow(2,42),Fu=Math.pow(2,49),zu=Math.pow(2,56),Ku=Math.pow(2,63),qu=function(r){return r<Pu?1:r<Ou?2:r<Ru?3:r<Nu?4:r<Mu?5:r<Uu?6:r<Fu?7:r<zu?8:r<Ku?9:10},Hu={encode:Tu,decode:Lu,encodingLength:qu},Wu=Hu,nr=Wu;function or(r,e=0){let t=nr.decode(r,e),n=nr.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Rt(r,e,t=0){return nr.encode(r,e,t),e}function Nt(r){return nr.encodingLength(r)}function Ut(r,e){let t=e.byteLength,n=Nt(r),o=n+Nt(t),s=new Uint8Array(o+t);return Rt(r,s,0),Rt(t,s,n),s.set(e,o),new Mt(r,t,e,s)}function qr(r){let e=ke(r),[t,n]=or(e),[o,s]=or(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Mt(t,o,i,e)}function Li(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&vi(r.bytes,t.bytes)}}var Mt=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=ht(n),this.bytes=ht(o)}};function Ci(r,e){let{bytes:t,version:n}=r;return n===0?$u(t,Io(r),e??ue.encoder):ju(t,Io(r),e??tt.encoder)}var Pi=new WeakMap;function Io(r){let e=Pi.get(r);if(e==null){let t=new Map;return Pi.set(r,t),t}return e}var ne=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=ht(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==sr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Gu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ut(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Li(e.multihash,n.multihash)}toString(e){return Ci(this,e)}toJSON(){return{"/":Ci(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Oi(n,o,s.bytes))}else if(t[Zu]===!0){let{version:n,multihash:o,code:s}=t,i=qr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==sr)throw new Error(`Version 0 CID must use dag-pb (code: ${sr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Oi(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,sr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=ke(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Mt(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=or(e.subarray(t));return t+=d,f},o=n(),s=sr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Vu(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Io(s).set(n,e),s}};function Vu(r,e){switch(r[0]){case"Q":{let t=e??ue;return[ue.prefix,t.decode(`${ue.prefix}${r}`)]}case ue.prefix:{let t=e??ue;return[ue.prefix,t.decode(r)]}case tt.prefix:{let t=e??tt;return[tt.prefix,t.decode(r)]}case rr.prefix:{let t=e??rr;return[rr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function $u(r,e,t){let{prefix:n}=t;if(n!==ue.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function ju(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var sr=112,Gu=18;function Oi(r,e,t){let n=Nt(r),o=n+Nt(e),s=new Uint8Array(o+t.byteLength);return Rt(r,s,0),Rt(e,s,n),s.set(t,o),s}var Zu=Symbol.for("@ipld/js-cid/CID");var Yu=20;function ko({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Do(r,e,t,n,o)}var Do=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Yu,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Ri(n,this.code,t?.truncate):n.then(o=>Ri(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ri(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ut(e,r)}var Co={};Se(Co,{base64:()=>mt,base64pad:()=>Xu,base64url:()=>Lo,base64urlpad:()=>Qu});var mt=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Xu=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Lo=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Qu=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Po={};Se(Po,{identity:()=>Pe});var Mi=0,Ju="identity",Ui=ke;function el(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ut(Mi,Ui(r))}var Pe={code:Mi,name:Ju,encode:Ui,digest:el};function me(r=0){return new Uint8Array(r)}function de(r=0){return new Uint8Array(r)}function tl(r){return r?.buffer instanceof ArrayBuffer}function Oo(r){if(tl(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function _e(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=de(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return Oo(t)}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 zi=Symbol.for("@achingbrain/uint8arraylist");function Fi(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 Hr(r){return!!r?.[zi]}var ge=class r{bufs;length;[zi]=!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(Hr(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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(Hr(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=Fi(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Fi(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(Hr(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 _e(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:_e(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 u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){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(!Hr(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,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let p=this.get(f+d);if(n[d]!==p){l=Math.max(1,d-a[p]);break}}if(l===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=de(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=me(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=me(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=me(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=de(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=me(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=me(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=me(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=me(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=me(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}};function rl(r){return r.buffer instanceof ArrayBuffer}function Oe(r){return rl(r)?r:r.slice()}var nl=Math.pow(2,7),ol=Math.pow(2,14),sl=Math.pow(2,21),Ro=Math.pow(2,28),No=Math.pow(2,35),Mo=Math.pow(2,42),Uo=Math.pow(2,49),W=128,be=127;function Q(r){if(r<nl)return 1;if(r<ol)return 2;if(r<sl)return 3;if(r<Ro)return 4;if(r<No)return 5;if(r<Mo)return 6;if(r<Uo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ft(r,e,t=0){switch(Q(r)){case 8:e[t++]=r&255|W,r/=128;case 7:e[t++]=r&255|W,r/=128;case 6:e[t++]=r&255|W,r/=128;case 5:e[t++]=r&255|W,r/=128;case 4:e[t++]=r&255|W,r>>>=7;case 3:e[t++]=r&255|W,r>>>=7;case 2:e[t++]=r&255|W,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function il(r,e,t=0){switch(Q(r)){case 8:e.set(t++,r&255|W),r/=128;case 7:e.set(t++,r&255|W),r/=128;case 6:e.set(t++,r&255|W),r/=128;case 5:e.set(t++,r&255|W),r/=128;case 4:e.set(t++,r&255|W),r>>>=7;case 3:e.set(t++,r&255|W),r>>>=7;case 2:e.set(t++,r&255|W),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Fo(r,e){let t=r[e],n=0;if(n+=t&be,t<W||(t=r[e+1],n+=(t&be)<<7,t<W)||(t=r[e+2],n+=(t&be)<<14,t<W)||(t=r[e+3],n+=(t&be)<<21,t<W)||(t=r[e+4],n+=(t&be)*Ro,t<W)||(t=r[e+5],n+=(t&be)*No,t<W)||(t=r[e+6],n+=(t&be)*Mo,t<W)||(t=r[e+7],n+=(t&be)*Uo,t<W))return n;throw new RangeError("Could not decode varint")}function al(r,e){let t=r.get(e),n=0;if(n+=t&be,t<W||(t=r.get(e+1),n+=(t&be)<<7,t<W)||(t=r.get(e+2),n+=(t&be)<<14,t<W)||(t=r.get(e+3),n+=(t&be)<<21,t<W)||(t=r.get(e+4),n+=(t&be)*Ro,t<W)||(t=r.get(e+5),n+=(t&be)*No,t<W)||(t=r.get(e+6),n+=(t&be)*Mo,t<W)||(t=r.get(e+7),n+=(t&be)*Uo,t<W))return n;throw new RangeError("Could not decode varint")}function Wr(r,e,t=0){return e==null&&(e=de(Q(r))),e instanceof Uint8Array?Ft(r,e,t):il(r,e,t)}function gt(r,e=0){return r instanceof Uint8Array?Fo(r,e):al(r,e)}var Ko=new Float32Array([-0]),rt=new Uint8Array(Ko.buffer);function Ki(r,e,t){Ko[0]=r,e[t]=rt[0],e[t+1]=rt[1],e[t+2]=rt[2],e[t+3]=rt[3]}function qi(r,e){return rt[0]=r[e],rt[1]=r[e+1],rt[2]=r[e+2],rt[3]=r[e+3],Ko[0]}var qo=new Float64Array([-0]),we=new Uint8Array(qo.buffer);function Hi(r,e,t){qo[0]=r,e[t]=we[0],e[t+1]=we[1],e[t+2]=we[2],e[t+3]=we[3],e[t+4]=we[4],e[t+5]=we[5],e[t+6]=we[6],e[t+7]=we[7]}function Wi(r,e){return we[0]=r[e],we[1]=r[e+1],we[2]=r[e+2],we[3]=r[e+3],we[4]=r[e+4],we[5]=r[e+5],we[6]=r[e+6],we[7]=r[e+7],qo[0]}var cl=BigInt(Number.MAX_SAFE_INTEGER),ul=BigInt(Number.MIN_SAFE_INTEGER),Ae=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return yt;if(e<cl&&e>ul)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Vi&&(o=0n,++n>Vi&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return yt;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):yt}},yt=new Ae(0,0);yt.toBigInt=function(){return 0n};yt.zzEncode=yt.zzDecode=function(){return this};yt.length=function(){return 1};var Vi=4294967296n;function $i(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function ji(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ho(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Re(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Vr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Wo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Oe(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Re(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Re(this,4);return Vr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Re(this,4);return Vr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Re(this,4);let e=qi(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Re(this,4);let e=Wi(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Re(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return ji(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Re(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Re(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ae(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Re(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Re(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Re(this,8);let e=Vr(this.buf,this.pos+=4),t=Vr(this.buf,this.pos+=4);return new Ae(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Fo(this.buf,this.pos);return this.pos+=Q(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ir(r){return new Wo(r instanceof Uint8Array?r:r.subarray())}function ze(r,e,t){let n=ir(r);return e.decode(n,void 0,t)}var Vo={};Se(Vo,{base10:()=>ll});var ll=et({prefix:"9",name:"base10",alphabet:"0123456789"});var $o={};Se($o,{base16:()=>fl,base16upper:()=>dl});var fl=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),dl=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var jo={};Se(jo,{base2:()=>hl});var hl=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Go={};Se(Go,{base256emoji:()=>bl});var Zi=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),pl=Zi.reduce((r,e,t)=>(r[t]=e,r),[]),ml=Zi.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function gl(r){return r.reduce((e,t)=>(e+=pl[t],e),"")}function yl(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=ml[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var bl=Ot({prefix:"\u{1F680}",name:"base256emoji",encode:gl,decode:yl});var Zo={};Se(Zo,{base8:()=>wl});var wl=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Yo={};Se(Yo,{identity:()=>xl});var xl=Ot({prefix:"\0",name:"identity",encode:r=>_i(ke(r)),decode:r=>ke(Si(r))});var $p=new TextEncoder,jp=new TextDecoder;var Xo={};Se(Xo,{sha256:()=>nt,sha512:()=>Sl});function Yi(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var nt=ko({name:"sha2-256",code:18,encode:Yi("SHA-256")}),Sl=ko({name:"sha2-512",code:19,encode:Yi("SHA-512")});var ar={...Yo,...jo,...Zo,...Vo,...$o,..._o,...Ao,...Bo,...Co,...Go},Xp={...Xo,...Po};function Qi(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Xi=Qi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Qo=Qi("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=de(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),_l={utf8:Xi,"utf-8":Xi,hex:ar.base16,latin1:Qo,ascii:Qo,binary:Qo,...ar},$r=_l;function J(r,e="utf8"){let t=$r[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Jo(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return de(i);o+i>e&&(n=de(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var bt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function es(){}var rs=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Al=Jo();function Bl(r){return globalThis.Buffer!=null?de(r):Al(r)}var ur=class{len;head;tail;states;constructor(){this.len=0,this.head=new bt(es,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new bt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ns((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(jr,10,Ae.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ae.fromBigInt(e);return this._push(jr,t.length(),t)}uint64Number(e){return this._push(Ft,Q(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Ae.fromBigInt(e).zzEncode();return this._push(jr,t.length(),t)}sint64Number(e){let t=Ae.fromNumber(e).zzEncode();return this._push(jr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ts,1,e?1:0)}fixed32(e){return this._push(cr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ae.fromBigInt(e);return this._push(cr,4,t.lo)._push(cr,4,t.hi)}fixed64Number(e){let t=Ae.fromNumber(e);return this._push(cr,4,t.lo)._push(cr,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Ki,4,e)}double(e){return this._push(Hi,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ts,1,0):this.uint32(t)._push(Il,t,e)}string(e){let t=$i(e);return t!==0?this.uint32(t)._push(Ho,t,e):this._push(ts,1,0)}fork(){return this.states=new rs(this),this.head=this.tail=new bt(es,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new bt(es,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Bl(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function ts(r,e,t){e[t]=r&255}function Tl(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ns=class extends bt{next;constructor(e,t){super(Tl,e,t),this.next=void 0}};function jr(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function cr(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Il(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ur.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Dl,e,r),this},ur.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(kl,e,r),this});function Dl(r,e,t){e.set(r,t)}function kl(r,e,t){r.length<40?Ho(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(J(r),t)}function os(){return new ur}function Ke(r,e){let t=os();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*qe(r,e,t){let n=ir(r);yield*e.stream(n,".",void 0,t)}var Gr={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Zr(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function zt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i,a){};return Zr("enum",Gr.VARINT,t,n,o)}function He(r,e,t){return Zr("message",Gr.LENGTH_DELIMITED,r,e,t)}var $e=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Yr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Xr=class extends Error{static name="NoEvictionError";name="NoEvictionError"};var ss={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ji={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ea=new globalThis.TextEncoder;function Ll(r,e){let t=ss[e],n=Ji[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Cl(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ss[e],o=Ji[e],s=r;for(;s.length>0;){let i=ea.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function is(r,{size:e=32,utf8Buffer:t}={}){if(!ss[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Cl(r,e,t);r=ea.encode(r)}return Ll(r,e)}var lr={hash:r=>Number(is(r,{size:32})),hashV:(r,e)=>Pl(lr.hash(r,e))};function Pl(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),J(e,"base16")}var as=64,Ne=class{fp;h;seed;constructor(e,t,n,o=2){if(o>as)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=me(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ce(this.fp,e.fp):!1}};function wt(r,e){return Math.floor(Math.random()*(e-r))+r}var xt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ne))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ne))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Ne))throw new TypeError("Invalid Fingerprint");let t=wt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Ne))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Ol=500,fr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??lr,this.seed=e.seed??wt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=J(e));let t=new Ne(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new xt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new xt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[wt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new xt(this.bucketSize));for(let a=0;a<Ol;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new xt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=J(e));let t=new Ne(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=J(e));let t=new Ne(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Rl={1:.5,2:.84,4:.95,8:.98};function Nl(r=.001){return r>.002?2:r>1e-5?4:8}function ta(r,e=.001){let t=Nl(e),n=Rl[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),as);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Qr=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??lr,this.seed=e.seed??wt(0,Math.pow(2,10)),this.filterSeries=[new fr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=J(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new fr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=J(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=J(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Jr(r,e=.001,t){return new Qr({...ta(r,e),...t??{}})}var en=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ml=45,Ul=15,tn=new en;function ra(r){if(!(r.length>Ul))return tn.new(r).parseWith(()=>tn.readIPv4Addr())}function na(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ml))return tn.new(r).parseWith(()=>tn.readIPv6Addr())}function rn(r){return!!ra(r)}function oa(r){return!!na(r)}function j(r,e="utf8"){let t=$r[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ye=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},je=class extends Error{static name="ValidationError";name="ValidationError"},nn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},on=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function us(r){return e=>j(e,r)}function ls(r){return e=>J(e,r)}function Kt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Et(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function sa(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=J(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=Et(n);return _e([t,o],t.length+o.length)}function ia(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=tt.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=Et(n);return _e([t,o],t.length+o.length)}function fs(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=j(e,"base32"),o=Kt(t);return`${n}:${o}`}var ds=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 ye("Invalid byte value in IP address");e[n]=o}),e},aa=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=rn(t[n]),i;s&&(i=ds(t[n]),t[n]=j(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,j(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 ye("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},ca=function(r){if(r.byteLength!==4)throw new ye("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ua=function(r){if(r.byteLength!==16)throw new ye("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 ye(`Invalid IPv6 address "${t}"`)}};function la(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new ye(`Invalid IPv6 address "${r}"`)}}var cs=Object.values(ar).map(r=>r.decoder),Fl=(function(){let r=cs[0].or(cs[1]);return cs.slice(2).forEach(e=>r=r.or(e)),r})();function fa(r){return Fl.decode(r)}function da(r){return e=>r.encoder.encode(e)}function zl(r){if(parseInt(r).toString()!==r)throw new je("Value must be an integer")}function Kl(r){if(r<0)throw new je("Value must be a positive integer, or zero")}function ql(r){return e=>{if(e>r)throw new je(`Value must be smaller than or equal to ${r}`)}}function Hl(...r){return e=>{for(let t of r)t(e)}}var dr=Hl(zl,Kl,ql(65535));var he=-1,hs=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 on(`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)}))}},Ge=new hs,Lf=[{code:4,name:"ip4",size:32,valueToBytes:ds,bytesToValue:ca,validate:r=>{if(!rn(r))throw new je(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Et,bytesToValue:Kt,validate:dr},{code:273,name:"udp",size:16,valueToBytes:Et,bytesToValue:Kt,validate:dr},{code:33,name:"dccp",size:16,valueToBytes:Et,bytesToValue:Kt,validate:dr},{code:41,name:"ip6",size:128,valueToBytes:aa,bytesToValue:ua,stringToValue:la,validate:r=>{if(!oa(r))throw new je(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:he},{code:43,name:"ipcidr",size:8,bytesToValue:us("base10"),valueToBytes:ls("base10")},{code:53,name:"dns",size:he},{code:54,name:"dns4",size:he},{code:55,name:"dns6",size:he},{code:56,name:"dnsaddr",size:he},{code:132,name:"sctp",size:16,valueToBytes:Et,bytesToValue:Kt,validate:dr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:he,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:he,bytesToValue:us("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ls("base58btc")(r):ne.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:fs,valueToBytes:sa},{code:445,name:"onion3",size:296,bytesToValue:fs,valueToBytes:ia},{code:446,name:"garlic64",size:he},{code:447,name:"garlic32",size:he},{code:448,name:"tls"},{code:449,name:"sni",size:he},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:he,bytesToValue:da(Lo),valueToBytes:fa},{code:480,name:"http"},{code:481,name:"http-path",size:he,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:he}];Lf.forEach(r=>{Ge.addProtocol(r)});function ha(r){let e=[],t=0;for(;t<r.length;){let n=gt(r,t),o=Ge.getProtocol(n),s=Q(n),i=Cf(o,r,t+s),a=0;i>0&&o.size===he&&(a=Q(i));let c=s+a+i,u={code:n,name:o.name,bytes:Oe(r.subarray(t,t+c))};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??j(f)}e.push(u),t+=c}return e}function pa(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ge.getProtocol(n.code),s=Q(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??J(n.value),a=i.byteLength,o.size===he&&(c=Q(a)));let u=new Uint8Array(s+c+a),l=0;Ft(n.code,u,l),l+=s,i!=null&&(o.size===he&&(Ft(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return _e(t,e)}function ma(r){if(r.charAt(0)!=="/")throw new ye('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=Ge.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 ye(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new ye(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new ye("Incomplete multiaddr");return e}function ga(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ge.getProtocol(e.code);if(t==null)throw new ye(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Cf(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:gt(e,t)}var Pf=Symbol.for("nodejs.util.inspect.custom"),ms=Symbol.for("@multiformats/multiaddr");function Of(r){if(r==null&&(r="/"),sn(r))return r.getComponents();if(r instanceof Uint8Array)return ha(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ma(r);if(Array.isArray(r))return r;throw new ye("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ps=class r{[ms]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Of(e),t.validate!==!1&&Rf(this)}get bytes(){return this.#r==null&&(this.#r=pa(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ga(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 nn(`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)}[Pf](){return`Multiaddr(${this.toString()})`}};function Rf(r){r.getComponents().forEach(e=>{let t=Ge.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function sn(r){return!!r?.[ms]}function Me(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var an=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}},qt=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new an(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 an(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 gs=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function cn(r={}){return Nf(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 Nf(r,e){e=e??{};let t=e.onEnd,n=new qt,o,s,i,a=Me(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,x)=>{s=S=>{s=null,n.push(S);try{y(r(n))}catch(m){x(m)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Me()})}},u=y=>s!=null?s(y):(n.push(y),o),l=y=>(n=new qt,s!=null?s({error:y}):(n.push({error:y}),o)),f=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},d=y=>i?o:(i=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new qt,d(),{done:!0}),E=y=>(d(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:E,push:f,end:d,get readableLength(){return n.size},onEmpty:async y=>{let x=y?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let S,m;x!=null&&(S=new Promise((_,A)=>{m=()=>{A(new gs)},x.addEventListener("abort",m)}));try{await Promise.race([a.promise,S])}finally{m!=null&&x!=null&&x?.removeEventListener("abort",m)}}},t==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(y){return w.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(y){return w.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return w.readableLength},onEmpty:y=>w.onEmpty(y)},o}var ys=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ya=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function bs(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(ya(i));return}if(i&&(c=()=>{d(ya(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let p=new ys;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(E){d(E)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(p.message=o??`Promise timed out after ${t} milliseconds`,d(p))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var Mf=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 Uf(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:u,removeListener:l}=Mf(r),f=async(...p)=>{let E=t.multiArgs?p:p[0];if(t.filter)try{if(!await t.filter(E))return}catch(w){n(),i(w);return}c.push(E),t.count===c.length&&(n(),s(c))},d=(...p)=>{n(),i(t.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)l(p,f);for(let p of t.rejectionEvents)a.includes(p)||l(p,d)};for(let p of a)u(p,f);for(let p of t.rejectionEvents)a.includes(p)||u(p,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=bs(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function un(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Uf(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ws(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var ln=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Ff(r){return r.reason}function fn(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??Ff;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var dn=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Me(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ie)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function zf(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ba=new WeakMap,hn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=zf(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ie),this.cleanup())}async join(e){let t=new dn(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await fn(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof t=="object"&&t!==null){let n=ba.get(t);if(n==null&&(n=new WeakSet,ba.set(t,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.deferred.reject(e.signal?.reason??new Ie),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var ot=class extends Fe{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=ws(this.emitEmpty.bind(this),1),this.emitIdle=ws(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ln;let n=new hn(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ie)}),this.clear()}async onEmpty(e){this.size!==0&&await un(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await un(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await un(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=cn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ie("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var pn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ht=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},mn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},hr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function gn(r){return r[Symbol.asyncIterator]!=null}function wa(r,e){if(r.byteLength>e)throw new Ht("Message length too long")}var bn=r=>{let e=Q(r),t=de(e);return Wr(r,t),bn.bytes=e,t};bn.bytes=0;function wn(r,e){e=e??{};let t=e.lengthEncoder??bn,n=e?.maxDataLength??4194304;function*o(s){wa(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return gn(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}wn.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??bn,n=e?.maxDataLength??4194304;return wa(r,n),new ge(t(r.byteLength),r)};var vt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(vt||(vt={}));var xs=r=>{let e=gt(r);return xs.bytes=Q(e),e};xs.bytes=0;function pr(r,e){let t=new ge,n=vt.LENGTH,o=-1,s=e?.lengthDecoder??xs,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===vt.LENGTH)try{if(o=s(t),o<0)throw new pn("Invalid message length");if(o>a)throw new Ht("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=vt.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new mn("Message length length too long");break}throw u}if(n===vt.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=vt.LENGTH}}}return gn(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new hr("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new hr("Unexpected end of input")})()}pr.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 pr(n,{...e??{},onLength:s=>{t=s}})};var xn=class extends ot{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Es=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function xa(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Es({name:e,metrics:t}):n=new Map,n}var En=class extends Fe{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Jr(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=mt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=Me(),i={promise:s.promise,observers:1,queryFilter:Jr(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,u=new ot({concurrency:this.maxProviders});u.addEventListener("failure",d=>{if(d.detail.job.options.provider.fallback){this.log.error("error querying fallback provider %s - %e",d.detail.job.options.provider,d.detail.error);return}if(d.detail.error.name==="NoEvictionError"){this.log.error("no-eviction error querying provider %s - %e",d.detail.job.options.provider,d.detail.error);return}this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),u.addEventListener("success",d=>{c=!0,s.resolve(d.detail.result)}),u.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let p=this.providers[Math.floor(Math.random()*this.providers.length)];p.fallback||(this.log("evicting %s to make room for more providers",p),this.evict(p))}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),s.reject(d)})});let l=d=>{let p=this.toFilterKey(d.detail);i.queryFilter.has(p)||(i.queryFilter.add(p),this.emitFoundProviderProgressEvent(e,d.detail,t),u.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(E=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,E)}))};if(this.addEventListener("provider",l),a)try{await fn(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),i.observers>1&&s.reject(d),d}Promise.all([...this.providers].filter(d=>{let p=this.toFilterKey(d),E=i.queryFilter.has(p);return E||i.queryFilter.add(this.toFilterKey(d)),!E}).map(async d=>u.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let f=()=>{s.reject(new Ie(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",f);try{return await s.promise}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",f),u.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=Me(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let u=i.initialProviders.pop();if(u==null)continue;let l=await i.convertToProvider(u,"manual",n);l!=null&&(yield l)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let u of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(u)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(u),this.safeDispatchEvent("provider",{detail:u}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new Yr(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};function $f(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var va=$f;function jf(r){return r[Symbol.asyncIterator]!=null}function Gf(r){if(jf(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=_e([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return _e(e,t)}var Sa=Gf;function vn(r){return r==null?!1:ne.asCID(r)!=null}async function _a(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,Oe(e),Oe(t.subarray()));return n?.signal?.throwIfAborted(),s}var Zf=parseInt("11111",2),vs=parseInt("10000000",2),Yf=parseInt("01111111",2),Aa={0:mr,1:mr,2:Xf,3:ed,4:td,5:Jf,6:Qf,16:mr,22:mr,48:mr};function Ss(r,e={offset:0}){let t=r[e.offset]&Zf;if(e.offset++,Aa[t]!=null)return Aa[t](r,e);throw new Error("No decoder for tag "+t)}function gr(r,e){let t=0;if((r[e.offset]&vs)===vs){let n=r[e.offset]&Yf,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");o+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(o,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function mr(r,e){gr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Ss(r,e);if(n===null)break;t.push(n)}return t}function Xf(r,e){let t=gr(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 Qf(r,e){let t=gr(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 u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function Jf(r,e){return e.offset++,null}function ed(r,e){let t=gr(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 td(r,e){let t=gr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function rd(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ge;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function _s(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=rd(r.byteLength);return new ge(Uint8Array.from([e.byteLength|vs]),e)}function Ba(r){let e=new ge,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ge(Uint8Array.from([2]),_s(e),e)}function Ta(r){let e=Uint8Array.from([0]),t=new ge(e,r);return new ge(Uint8Array.from([3]),_s(t),t)}function Sn(r,e=48){let t=new ge;for(let n of r)t.append(n);return new ge(Uint8Array.from([e]),_s(t),t)}var nd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),od=Uint8Array.from([6,5,43,129,4,0,34]),sd=Uint8Array.from([6,5,43,129,4,0,35]),id={ext:!0,kty:"EC",crv:"P-256"},ad={ext:!0,kty:"EC",crv:"P-384"},cd={ext:!0,kty:"EC",crv:"P-521"},As=32,Bs=48,Ts=66;function Ia(r){let e=Ss(r);return Da(e)}function Da(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===As*2+1)return n=j(e.subarray(t,t+As),"base64url"),o=j(e.subarray(t+As),"base64url"),new Wt({...id,key_ops:["verify"],x:n,y:o});if(e.byteLength===Bs*2+1)return n=j(e.subarray(t,t+Bs),"base64url"),o=j(e.subarray(t+Bs),"base64url"),new Wt({...ad,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ts*2+1)return n=j(e.subarray(t,t+Ts),"base64url"),o=j(e.subarray(t+Ts),"base64url"),new Wt({...cd,key_ops:["verify"],x:n,y:o});throw new De(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function ka(r){return Sn([Ba(Uint8Array.from([1])),Sn([ud(r.crv)],160),Sn([Ta(new ge(Uint8Array.from([4]),J(r.x??"","base64url"),J(r.y??"","base64url")))],161)]).subarray()}function ud(r){if(r==="P-256")return nd;if(r==="P-384")return od;if(r==="P-521")return sd;throw new De(`Invalid curve ${r}`)}var Wt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ka(this.jwk)),this._raw}toMultihash(){return Pe.digest(Vt(this))}toCID(){return ne.createV1(114,this.toMultihash())}toString(){return ue.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 _a(this.jwk,t,e,n)}};var _n=BigInt(4294967295),La=BigInt(32);function ld(r,e=!1){return e?{h:Number(r&_n),l:Number(r>>La&_n)}:{h:Number(r>>La&_n)|0,l:Number(r&_n)|0}}function Ca(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=ld(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var fd=r=>r/2**32|0,dd=r=>r>>>0;function Pa(r,e,t,n){let o=fd(t),s=dd(t);r.setUint32(e,n?s:o,n),r.setUint32(e+4,n?o:s,n)}var Is=(r,e,t)=>r>>>t,Ds=(r,e,t)=>r<<32-t|e>>>t,St=(r,e,t)=>r>>>t|e<<32-t,_t=(r,e,t)=>r<<32-t|e>>>t,yr=(r,e,t)=>r<<64-t|e>>>t-32,br=(r,e,t)=>r>>>t-32|e<<64-t;function We(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Oa=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Ra=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Na=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ma=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Ua=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Fa=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;function An(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var ks=r=>r?`"${r}" `:"";function Ze(r,e=""){if(typeof r!="number")throw new TypeError(ks(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(ks(e)+"expected integer >= 0, got "+r);return r}function Le(r,e,t=""){if(An(r)&&(e===void 0||r.length===e))return r;e!==void 0&&Ze(e,"length");let n=An(r),o=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,i=ks(t)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function Bn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Ze(r.outputLen),Ze(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var pd=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},za=(r,e)=>{pd(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function $t(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function Tn(r,e){Le(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function At(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function In(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ue(r,e){return r<<32-e|r>>>e}var qa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",md=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Dn(r){if(Le(r),qa)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=md[r[t]];return e}function Ka(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function kn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(qa)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("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 RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ls(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Le(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 gd(r,e,t="opts"){return za(r,"defaults"),e!==void 0&&za(e,t),Object.assign(Object.create(null),r,e)}function Cs(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=gd({},e,"info");let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Ha(r=32){Ze(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Ps=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Wa(r,e,t){return r&e^~r&t}function Va(r,e,t){return r&e^r&t^e&t}var wr=class{blockLen;outputLen;canXOF=!1;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=In(this.buffer)}update(e){$t(this),Le(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let u=In(e);for(;o<=s-a;a+=o)this.process(u,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){$t(this),Tn(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>o-i&&(this.process(n,0),t.fill(0)),Pa(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===t?n:In(e),c=this.outputLen,u=c/4,l=this.get();if(c%4||u>l.length)throw new Error("invalid outputLen");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},$a=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ja=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var yd=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]),st=new Uint32Array(64),Os=class extends wr{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}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}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let f=0;f<16;f++,t+=4)st[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=st[f-15],p=st[f-2],E=Ue(d,7)^Ue(d,18)^d>>>3,w=Ue(p,17)^Ue(p,19)^p>>>10;st[f]=w+st[f-7]+E+st[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Ue(a,6)^Ue(a,11)^Ue(a,25),p=l+d+Wa(a,c,u)+yd[f]+st[f]|0,w=(Ue(n,2)^Ue(n,13)^Ue(n,22))+Va(n,o,s)|0;l=u,u=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+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,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){At(st)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),At(this.buffer)}},Rs=class extends Os{constructor(){super(32,$a)}};var Ga=Ca(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),bd=Ga[0],wd=Ga[1],it=new Uint32Array(80),at=new Uint32Array(80),Ns=class extends wr{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:p,Gl:E,Hh:w,Hl:y}=this;return[e,t,n,o,s,i,a,c,u,l,f,d,p,E,w,y]}set(e,t,n,o,s,i,a,c,u,l,f,d,p,E,w,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=p|0,this.Gl=E|0,this.Hh=w|0,this.Hl=y|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let m=0;m<16;m++,t+=4)it[m]=e.getUint32(t),at[m]=e.getUint32(t+=4);for(let m=16;m<80;m++){let _=it[m-15]|0,A=at[m-15]|0,O=St(_,A,1)^St(_,A,8)^Is(_,A,7),M=_t(_,A,1)^_t(_,A,8)^Ds(_,A,7),R=it[m-2]|0,k=at[m-2]|0,C=St(R,k,19)^yr(R,k,61)^Is(R,k,6),K=_t(R,k,19)^br(R,k,61)^Ds(R,k,6),z=Na(M,K,at[m-7],at[m-16]),G=Ma(z,O,C,it[m-7],it[m-16]);it[m]=G|0,at[m]=z|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:p,Fl:E,Gh:w,Gl:y,Hh:x,Hl:S}=this;for(let m=0;m<80;m++){let _=St(f,d,14)^St(f,d,18)^yr(f,d,41),A=_t(f,d,14)^_t(f,d,18)^br(f,d,41),O=f&p^~f&w,M=d&E^~d&y,R=Ua(S,A,M,wd[m],at[m]),k=Fa(R,x,_,O,bd[m],it[m]),C=R|0,K=St(n,o,28)^yr(n,o,34)^yr(n,o,39),z=_t(n,o,28)^br(n,o,34)^br(n,o,39),G=n&s^n&a^s&a,T=o&i^o&c^i&c;x=w|0,S=y|0,w=p|0,y=E|0,p=f|0,E=d|0,{h:f,l:d}=We(u|0,l|0,k|0,C|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let U=Oa(C,z,T);n=Ra(U,k,K,G),o=U|0}({h:n,l:o}=We(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=We(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=We(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=We(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=We(this.Eh|0,this.El|0,f|0,d|0),{h:p,l:E}=We(this.Fh|0,this.Fl|0,p|0,E|0),{h:w,l:y}=We(this.Gh|0,this.Gl|0,w|0,y|0),{h:x,l:S}=We(this.Hh|0,this.Hl|0,x|0,S|0),this.set(n,o,s,i,a,c,u,l,f,d,p,E,w,y,x,S)}roundClean(){At(it,at)}destroy(){this.destroyed=!0,At(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ms=class extends Ns{constructor(){super(64,ja)}};var Za=Cs(()=>new Rs,Ps(1));var Us=Cs(()=>new Ms,Ps(3));function Cn(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var V=(r,e,t)=>Le(r,e,t),Fs=Ze;function Xa(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function ct(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function Bt(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var xr=Dn,Ce=(...r)=>Ls(...r),jt=r=>kn(r),lt=An,Tt=r=>Ha(r),Ln=BigInt(0),Ya=BigInt(1),xd=r=>r?`"${r}" `:"";function Ee(r,e=""){if(typeof r!="boolean")throw new TypeError(xd(e)+"expected boolean, got type="+typeof r);return r}function Pn(r){if(typeof r=="bigint"){if(!ut(r))throw new RangeError("positive bigint expected, got "+r)}else Fs(r);return r}function Ye(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Er(r){let e=Pn(r).toString(16);return e.length&1?"0"+e:e}function Qa(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Ln:BigInt("0x"+r)}function Ve(r){return Qa(Dn(r))}function It(r){return Qa(Dn(vr(Le(r)).reverse()))}function On(r,e){if(Ze(e),e===0)throw new Error("zero output length is invalid");r=Pn(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return kn(n.padStart(t,"0"))}function zs(r,e){return On(r,e).reverse()}function vr(r){return Uint8Array.from(V(r))}function ut(r){return typeof r=="bigint"&&Ln<=r}function Ks(r,e,t){return ut(r)&&ut(e)&&ut(t)&&e<=r&&r<t}function Gt(r,e,t,n){if(!Ks(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Zt(r){if(r<Ln)throw new Error("expected non-negative bigint, got "+r);return r===Ln?0:r.toString(2).length}var Sr=r=>(Ye(r,"n"),(Ya<<BigInt(r))-Ya);function Ja(r,e,t){if(Ze(r,"hashLen"),Ze(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},d=(...y)=>t(u,Ce(c,...y)),p=(y=o)=>{u=d(s,y),c=d(),y.length!==0&&(u=d(i,y),c=d())},E=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,x=[];for(;y<e;){c=d();let S=c.slice();x.push(S),y+=c.length}return Ce(...x)};return(y,x)=>{f(),p(y);let S;for(;(S=x(E()))===void 0;)p();return f(),S}}function ve(r,e={},t={},n="object"){ct(r,n),ct(e,"fields"),ct(t,"optFields");function o(i,a,c){let u=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,l=r[i];if(!Object.hasOwn(r,i)&&(c?l!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(c&&l===void 0)return;let f=typeof l;if(f!==a||l===null)throw new TypeError(`${u} is invalid: expected ${a}, got ${f}`)}let s=(i,a)=>Object.entries(i).forEach(([c,u])=>o(c,u,a));s(e,!1),s(t,!0)}var le=BigInt(0),$=BigInt(1),ft=BigInt(2),rc=BigInt(3),qs=BigInt(4),nc=BigInt(5),Ed=BigInt(7),oc=BigInt(8),vd=BigInt(9),Sd=BigInt(15),sc=BigInt(16),_d=BigInt("0x10000000000000000");function oe(r,e){if(e<=le)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=le?t:e+t}function ic(r,e,t){if(t<=$)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<le)throw new Error("invalid exponent, negatives unsupported");if(e===le)return $;if(e===$)return r;let n=r%t;if(n<le&&(n+=t),e<_d){let a=$;for(;e>le;)e&$&&(a=a*n%t),n=n*n%t,e>>=$;return a}let o=[];for(;e>le;)o.push(Number(e&Sd)),e>>=qs;let s=new Array(16);s[0]=$,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%t;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=o[a];c!==0&&(i=i*s[c]%t)}return i}function ee(r,e,t){if(t<=$)throw new Error("pow2: expected modulus > 1, got "+t);if(e<le)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >le;)n*=n,n%=t;return n}function ec(r,e){if(r===le)throw new Error("invert: expected non-zero number");if(e<=$)throw new Error("invert: expected modulus > 1, got "+e);let t=oe(r,e),n=e,o=le,s=$;for(;t!==le;){let a=n/t,c=n-t*a,u=o-s*a;n=t,t=c,o=s,s=u}if(n!==$)throw new Error("invert: does not exist");return oe(o,e)}function ac(r,e){if(e<=$)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=oe(r,e);if(t===le)throw new Error("invertCt: expected non-zero number");let n=ic(t,e-ft,e);if(oe(t*n,e)!==$)throw new Error("invertCt: does not exist");return n}function Hs(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Ws(r,e){if((r&$)===le)throw new Error(e+": expected odd modulus, got "+r)}function cc(r,e){let t=r,n=(t.ORDER+$)/qs,o=t.pow(e,n);return Hs(t,o,e),o}function Ad(r,e){let t=r,n=(t.ORDER-nc)/oc,o=t.mul(e,ft),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,ft),s),c=t.mul(i,t.sub(a,t.ONE));return Hs(t,c,e),c}function Bd(r){let e=Xt(r),t=uc(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Ed)/sc;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),d=u.mul(l,o),p=u.mul(l,s),E=u.eql(u.sqr(f),c),w=u.eql(u.sqr(d),c);l=u.cmov(l,f,E),f=u.cmov(p,d,w);let y=u.eql(u.sqr(f),c),x=u.cmov(l,f,y);return Hs(u,x,c),x})}function uc(r){if(r<rc)throw new Error("sqrt is not defined for small field");Ws(r,"tonelliShanks");let e=r-$,t=0;for(;e%ft===le;)e/=ft,t++;let n=ft,o=Xt(r);for(;_r(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return cc;let s=o.pow(n,e),i=(e+$)/ft;return function(c,u){let l=c;if(l.is0(u))return u;if(_r(l,u)!==1)throw new Error("Cannot find square root");let f=t,d=l.mul(l.ONE,s),p=l.pow(u,e),E=l.pow(u,i);for(;!l.eql(p,l.ONE);){if(l.is0(p))throw new Error("Cannot find square root: probably non-prime P");let w=1,y=l.sqr(p);for(;!l.eql(y,l.ONE);)if(w++,y=l.sqr(y),w===f)throw new Error("Cannot find square root");let x=$<<BigInt(f-w-1),S=l.pow(d,x);f=w,d=l.sqr(S),p=l.mul(p,d),E=l.mul(E,S)}return E}}function Td(r){return Ws(r,"Fp.sqrt"),r%qs===rc?cc:r%oc===nc?Ad:r%sc===vd?Bd(r):uc(r)}var lc=(r,e)=>(oe(r,e)&$)===$,Id=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yt(r){if(ct(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);Ye(r.BYTES,"BYTES"),Ye(r.BITS,"BITS");for(let e of Id)Bt(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=$)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Nn(r,e,t=!1){Yt(r),Cn(e,"nums"),Ee(t,"passZero");let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function _r(r,e){Yt(r);let t=r;Ws(t.ORDER,"FpLegendre");let n=(t.ORDER-$)/ft,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Dd(r,e){if(e!==void 0&&Fs(e),r<=le)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Zt(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var tc=new WeakMap,Rn=class{ORDER;BITS;BYTES;isLE;ZERO=le;ONE=$;_lengths;_mod;constructor(e,t={}){if(e<=$)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=Dd(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return oe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return le<=e&&e<this.ORDER}is0(e){return e===le}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&$)===$}neg(e){return oe(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return oe(e*e,this.ORDER)}add(e,t){return oe(e+t,this.ORDER)}sub(e,t){return oe(e-t,this.ORDER)}mul(e,t){return oe(e*t,this.ORDER)}pow(e,t){return ic(e,t,this.ORDER)}div(e,t){return oe(e*ec(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 ec(e,this.ORDER)}sqrt(e){let t=tc.get(this);return t||tc.set(this,t=Td(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?zs(e,this.BYTES):On(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?It(e):Ve(e);if(a&&(c=oe(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nn(this,e,!0)}cmov(e,t,n){return Ee(n,"condition"),n?t:e}};function Xt(r,e={}){return Object.freeze(Rn.prototype),new Rn(r,e)}function fc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=$)throw new Error("field order must be greater than 1");let e=Zt(r-$);return Math.ceil(e/8)}function Mn(r){let e=fc(r);return e+Math.ceil(e/2)}function Un(r,e,t=!1){V(r);let n=r.length,o=fc(e),s=Math.max(Mn(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?It(r):Ve(r),a=oe(i,e-$)+$;return t?zs(a,o):On(a,o)}var js=BigInt(0),Ar=BigInt(1),kd=BigInt(4),Vs=16,dc=128,Ld=5,hc=2**31;function dt(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);Bt(e.fromAffine,"Point.fromAffine"),Bt(e.fromBytes,"Point.fromBytes"),Bt(e.fromHex,"Point.fromHex"),ct(e.BASE,"Point.BASE"),ct(e.ZERO,"Point.ZERO"),Yt(e.Fp),Yt(e.Fn)}function Fn(r,e){dt(r),mc(e,r);let t=Nn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Cd(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function Pd(r,e){let t=r*(4*e+128);if(t>hc)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+hc/2**20+" MiB")}function Gs(r,e){if(r!==void 0){Bt(r,"randomBytes");try{let t=r(e);if(!lt(t)||t.length!==e)return}catch{return}return r}}function mc(r,e){Cn(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Od(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,o)=>{if(!(t===void 0?e.isValid(n):ut(n)&&n<t))throw new Error("invalid scalar at index "+o)})}var gc=new WeakMap;function $s(r){return gc.get(r)||1}function Rd(r,e){let t=r.double(),n=[r];for(let o=1;o<e;o++)n.push(n[o-1].add(t));return n}function Nd(r,e){let t=2**e,n=t/2,o=BigInt(t-1),s=[];for(;r>js;){let i=0;r&Ar&&(i=Number(r&o),i>=n&&(i-=t),r-=BigInt(i)),s.push(i),r>>=Ar}return s}function Md(r,e,t){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let u=Number(r&s);r>>=i,u>o&&(u-=n,r+=Ar),a.push(u)}if(r!==js)throw new Error("invalid wnaf");return a}function Ud(r,e,t){let n=0;for(let s of t)n=Math.max(n,s.length);let o=r;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<t.length;i++){let a=t[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Qt=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){dt(e),this.randomBytes=Gs(t,Vs),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let o=Math.ceil(n/t)+1,s=2**(t-1),i=[],a=e;for(let c=0;c<o;c++){let u=a;for(let l=0;l<s;l++)i.push(u),u=u.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:o,comp:i}}wnafCachedCT(e,t){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=Md(t,n,o),c=this.ZERO,u=this.BASE;for(let l=0;l<o;l++){let f=a[l],d=l*i,p=Math.abs(f)-1,E=s[d];for(let y=1;y<i;y++)E=y===p?s[d+y]:E;let w=E.negate();f===0?u=u.add(s[d]):c=c.add(f<0?w:E)}return{p:c,f:u}}getWnafPrecomputes(e,t,n,o){let s=this.wnafPrecomputes.get(t),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!Ks(t,Ar,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,o){let s=$s(e);return s===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+dc,s=this.randomBytes(Vs);if(!lt(s)||s.length!==Vs)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=t+Ve(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,t,n){let o=Ld,s=1<<o,i=Sr(o),a=new Array(s);a[0]=this.ZERO;for(let l=1;l<s;l++)a[l]=a[l-1].add(e);let c=Math.ceil(n/o),u=this.ZERO;for(let l=c-1;l>=0;l--){if(l!==c-1)for(let p=0;p<o;p++)u=u.double();let f=Number(t>>BigInt(l*o)&i),d=a[0];for(let p=1;p<s;p++)d=p===f?a[p]:d;u=u.add(d)}return{p:u,f:u}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Ar?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,n){if(this.assertPoint(e),!ut(t))throw new Error("invalid scalar");let o=$s(e);if(o===1||t>=this.Point.Fn.ORDER)return zn(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),Cd(t,this.bits);let n=Math.ceil((this.bits+dc)/t)+1;Pd(n*2**(t-1),this.Point.Fp.BYTES),gc.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return $s(e)!==1}};function zn(r,e,t,n=!1){if(dt(r),mc(e,r),Ee(n,"allowOversized"),Od(t,r.Fn,n?r.Fn.ORDER**kd:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>Rd(i,4)),s=t.map(i=>Nd(i,4));return Ud(r.ZERO,o,s)}function pc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Yt(e),e}else return Xt(r,{isLE:t})}function Kn(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);ve(t);for(let c of["p","n","h"]){let u=e[c];if(!(ut(u)&&u!==js))throw new Error(`CURVE.${c} must be positive bigint`)}let o=pc(e.p,t.Fp,n),s=pc(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 qn(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Hn=BigInt(0),Wn=BigInt(1),Vn=BigInt(2),Fd=BigInt(4),yc=BigInt(8);function zd(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function bc(r,e={}){ve(e,{},{},"extraOpts");let t=e,n=Kn("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(_r(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(_r(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");ve(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Tt:t.randomBytes,u=Vn<<BigInt(o.BYTES*8)-Wn;function l(S){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(S)}let f=t.uvRatio===void 0?(S,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(S,m))}}catch{return{isValid:!1,value:Hn}}}:t.uvRatio;if(!zd(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let d=o.eql(i.a,o.neg(o.ONE))?S=>o.neg(S):o.eql(i.a,o.ONE)?S=>S:S=>o.mul(i.a,S);function p(S,m,_=!1){let A=_?Wn:Hn;return Gt("coordinate "+S,m,A,u),m}function E(S){if(!(S instanceof w))throw new Error("EdwardsPoint expected")}class w{static BASE=new w(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new w(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,_,A,O){this.X=p("x",m),this.Y=p("y",_),this.Z=p("z",A,!0),this.T=p("t",O),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof w)throw new Error("extended point not allowed");let{x:_,y:A}=m||{};return p("x",_),p("y",A),new w(_,A,o.ONE,o.mul(_,A))}static fromBytes(m,_=!1){let A=o.BYTES,{a:O,d:M}=i;m=vr(V(m,A,"point")),Ee(_,"zip215");let R=vr(m),k=m[A-1];R[A-1]=k&-129;let C=It(R),K=_?u:o.ORDER;Gt("point.y",C,Hn,K);let z=o.sqr(C),G=o.sub(z,o.ONE),T=o.sub(o.mulN(M,z),O),{isValid:U,value:F}=f(G,T);if(!U)throw new Error("bad point: invalid y coordinate");let L=l(F),Z=(k&128)!==0;if(!_&&o.is0(F)&&Z)throw new Error("bad point: x=0 and x_0=1");return Z!==L&&(F=o.neg(F)),w.fromAffine({x:F,y:C})}static fromHex(m,_=!1){return w.fromBytes(jt(m),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=6,_=!0){return x.setWindowSize(this,m),_||this.multiply(Vn),this}assertValidity(){let m=this,{a:_,d:A}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:O,Y:M,Z:R,T:k}=m,C=o.sqr(O),K=o.sqr(M),z=o.sqr(R),G=o.sqr(z),T=o.mul(C,_),U=o.mul(o.add(T,K),z),F=o.add(G,o.mul(A,o.mul(C,K)));if(!o.eql(U,F))throw new Error("bad point: equation left != right (1)");let L=o.mul(O,M),Z=o.mul(R,k);if(!o.eql(L,Z))throw new Error("bad point: equation left != right (2)")}equals(m){E(m);let{X:_,Y:A,Z:O}=this,{X:M,Y:R,Z:k}=m,C=o.mul(_,k),K=o.mul(M,O),z=o.mul(A,k),G=o.mul(R,O);return o.eql(C,K)&&o.eql(z,G)}is0(){return this.equals(w.ZERO)}negate(){return new w(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:m,Y:_,Z:A}=this,O=o.sqr(m),M=o.sqr(_),R=o.mul(o.sqr(A),Vn),k=d(O),C=o.addN(m,_),K=o.sub(o.subN(o.sqr(C),O),M),z=o.addN(k,M),G=o.subN(z,R),T=o.subN(k,M),U=o.mul(K,G),F=o.mul(z,T),L=o.mul(K,T),Z=o.mul(G,z);return new w(U,F,Z,L)}add(m){E(m);let{d:_}=i,{X:A,Y:O,Z:M,T:R}=this,{X:k,Y:C,Z:K,T:z}=m,G=o.mul(A,k),T=o.mul(O,C),U=o.mul(o.mulN(R,_),z),F=o.mul(M,K),L=o.sub(o.subN(o.mulN(o.addN(A,O),o.addN(k,C)),G),T),Z=o.subN(F,U),re=o.addN(F,U),v=o.sub(T,d(G)),h=o.mul(L,Z),g=o.mul(re,v),b=o.mul(L,v),B=o.mul(Z,re);return new w(h,g,B,b)}subtract(m){return E(m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:A}=x.mulSecret(this,m,a,y);return y([_,A])[0]}multiplyUnsafe(m){if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===Hn?w.ZERO:this.is0()||m===Wn?this:x.mulUnsafe(this,m,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.mulUnsafe(this,i.n).is0()}toAffine(m){let _=this,A=m;if(A!=null&&typeof A!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof A);let{X:O,Y:M,Z:R}=_,k=_.is0();A==null&&(A=k?o.create(yc):o.inv(R));let C=o.mul(O,A),K=o.mul(M,A),z=o.mul(R,A);if(k)return{x:o.ZERO,y:o.ONE};if(!o.eql(z,o.ONE))throw new Error("invZ was invalid");return{x:C,y:K}}clearCofactor(){return a===Wn?this:a===Vn?this.double():a===Fd?this.double().double():a===yc?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:m,y:_}=this.toAffine(),A=o.toBytes(_);return A[A.length-1]|=l(m)?128:0,A}toHex(){return xr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=S=>Fn(w,S),x=new Qt(w,c);return x.bits>=6&&w.BASE.precompute(6),Object.freeze(w.prototype),Object.freeze(w),w}function wc(r,e,t={}){if(dt(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;ve(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(Ye(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=o.randomBytes===void 0?Tt:o.randomBytes,d=o.toMontgomery,p=o.toMontgomerySecret,E=o.adjustScalarBytes===void 0?T=>T:o.adjustScalarBytes,w=o.domain===void 0?(T,U,F)=>{if(Ee(F,"phflag"),U.length||F)throw new Error("Contexts/pre-hash are not supported");return T}:o.domain;function y(T){return c.create(It(T))}function x(T){let U=k.secretKey;V(T,k.secretKey,"secretKey");let F=V(n(T),2*U,"hashedSecretKey"),L=E(F.slice(0,U)),Z=F.slice(U,2*U),re=y(L);return{head:L,prefix:Z,scalar:re}}function S(T){let{head:U,prefix:F,scalar:L}=x(T),Z=i.multiply(L),re=Z.toBytes();return{head:U,prefix:F,scalar:L,point:Z,pointBytes:re}}function m(T){return S(T).pointBytes}function _(T=Uint8Array.of(),...U){let F=Ce(...U);return y(n(w(F,V(T,void 0,"context"),!!s)))}function A(T,U,F={}){ve(F,{},{},"options"),T=vr(V(T,void 0,"message")),s&&(T=s(T));let{prefix:L,scalar:Z,pointBytes:re}=S(U),v=_(F.context,L,T),h=i.multiply(v).toBytes(),g=_(F.context,h,re,T),b=c.create(v+g*Z);if(!c.isValid(b))throw new Error("sign failed: invalid s");let B=Ce(h,c.toBytes(b));return V(B,k.signature,"result")}let O={zip215:o.zip215};function M(T,U,F,L=O){ve(L);let{context:Z}=L,re=L.zip215===void 0?!!O.zip215:L.zip215,v=k.signature;T=V(T,v,"signature"),U=V(U,void 0,"message"),F=V(F,k.publicKey,"publicKey"),re!==void 0&&Ee(re,"zip215"),s&&(U=s(U));let h=v/2,g=T.subarray(0,h),b=It(T.subarray(h,v)),B,I,D;try{B=r.fromBytes(F,re),I=r.fromBytes(g,re),D=i.multiplyUnsafe(b)}catch{return!1}if(!re&&B.isSmallOrder())return!1;let P=_(Z,g,F,U);return I.add(B.multiplyUnsafe(P)).subtract(D).clearCofactor().is0()}let R=a.BYTES,k={secretKey:R,publicKey:R,signature:2*R,seed:R};function C(T){return T=T===void 0?f(k.seed):T,V(T,k.seed,"seed")}function K(T){return lt(T)&&T.length===k.secretKey}function z(T,U){try{return!!r.fromBytes(T,U===void 0?O.zip215:U)}catch{return!1}}let G={getExtendedPublicKey:S,randomSecretKey:C,isValidSecretKey:K,isValidPublicKey:z,toMontgomery(T){if(d===void 0)throw new Error("Montgomery conversion is not supported for this curve");return d(r.fromBytes(T))},toMontgomerySecret(T){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(T)}};return Object.freeze(k),Object.freeze(G),Object.freeze({keygen:qn(C,m),getPublicKey:m,sign:A,verify:M,utils:G,Point:r,lengths:k})}var Zs=BigInt(1),xc=BigInt(2);var Kd=BigInt(5),qd=BigInt(8),Ys=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Hd={p:Ys,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:qd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Wd(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ys,a=r*r%s*r%s,c=ee(a,xc,s)*a%s,u=ee(c,Zs,s)*r%s,l=ee(u,Kd,s)*u%s,f=ee(l,e,s)*l%s,d=ee(f,t,s)*f%s,p=ee(d,n,s)*d%s,E=ee(p,o,s)*p%s,w=ee(E,o,s)*p%s,y=ee(w,e,s)*l%s;return{pow_p_5_8:ee(y,xc,s)*r%s,b2:a}}function Sc(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Ec=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Vd(r,e){let t=Ys,n=oe(e*e*e,t),o=oe(n*n*e,t),s=Wd(r*o).pow_p_5_8,i=oe(r*n*s,t),a=oe(e*i*i,t),c=i,u=oe(i*Ec,t),l=a===r,f=a===oe(-r,t),d=a===oe(-r*Ec,t);return l&&(i=c),(f||d)&&(i=u),lc(i,t)&&(i=oe(-i,t)),{isValid:l||f,value:i}}var Xs=bc(Hd,{uvRatio:Vd}),vc=Xs.Fp;function $d(r){let{y:e}=r;return vc.toBytes(vc.div(Zs+e,Zs-e))}function jd(r){let e=Xs.Fp.BYTES;return Le(r,e),Sc(Us(r.subarray(0,e))).subarray(0,e)}function Gd(r){return wc(Xs,Us,Object.assign({adjustScalarBytes:Sc,toMontgomery:$d,toMontgomerySecret:jd,zip215:!0},r))}var _c=Gd({});var Br=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},$n=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var jn={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new $n("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Gn=32;var Qs,Zd=(async()=>{try{return await jn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Yd(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await jn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await jn.get().subtle.verify({name:"Ed25519"},n,Oe(e),Oe(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Xd(r,e,t){return _c.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Ac(r,e,t){return Qs==null&&(Qs=await Zd),Qs?Yd(r,e,t):Xd(r,e,t)}function Zn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Yn=class{type="Ed25519";raw;constructor(e){this.raw=Js(e,Gn)}toMultihash(){return Pe.digest(Vt(this))}toCID(){return ne.createV1(114,this.toMultihash())}toString(){return ue.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=Ac(this.raw,t,e);return Zn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Tc(r){return r=Js(r,Gn),new Yn(r)}function Js(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new De(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var xe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(xe||(xe={}));var ei;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ei||(ei={}));(function(r){r.codec=()=>zt(ei)})(xe||(xe={}));var Tr;(function(r){let e;r.codec=()=>(e==null&&(e=He((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),xe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=xe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:xe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return ze(s,r.codec(),i)}r.decode=n;function o(s,i){return qe(s,r.codec(),i)}r.stream=o})(Tr||(Tr={}));var ti;(function(r){let e;r.codec=()=>(e==null&&(e=He((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),xe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=xe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:xe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return ze(s,r.codec(),i)}r.decode=n;function o(s,i){return qe(s,r.codec(),i)}r.stream=o})(ti||(ti={}));var Xn=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Bn(e),Le(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");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),At(o)}update(e){return $t(this),this.iHash.update(e),this}digestInto(e){$t(this),Tn(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),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,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,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()}},Ic=(()=>{let r=((e,t,n)=>new Xn(e,t).update(n).digest());return r.create=(e,t)=>new Xn(e,t),r})();var eh=BigInt(0),ri=class extends Error{constructor(e=""){super(e)}},Xe={Err:ri,_tlv:{encode:(r,e)=>{let{Err:t}=Xe;if(Ye(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(Xa(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Er(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Er(o.length/2|128):"";return Er(r)+s+o+e},decode(r,e){let{Err:t}=Xe;e=V(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: 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 u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;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}=Xe;if(Pn(r),r<eh)throw new e("integer: negative integers are not allowed");let t=Er(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}=Xe;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ve(r)}},toSig(r,e){let{Err:t,_int:n,_tlv:o}=Xe;if(e!==void 0&&(Ye(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let s=V(r,void 0,"signature"),{v:i,l:a}=o.decode(48,s);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l:u}=o.decode(2,i),{v:l,l:f}=o.decode(2,u);if(f.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||l.length>e))throw new t("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Xe;ve(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Qn=(Object.freeze(Xe._tlv),Object.freeze(Xe._int),Object.freeze(Xe));var Dc=(r,e)=>(r+(r>=0?e:-e)/kc)/e;function th(r,e,t){Gt("scalar",r,Qe,t);let[[n,o],[s,i]]=e,a=Dc(i*r,t),c=Dc(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,f=u<Qe,d=l<Qe;f&&(u=-u),d&&(l=-l);let p=Sr(Math.ceil(Zt(t)/2))+Dt;if(u<Qe||u>=p||l<Qe||l>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:d,k2:l}}function si(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ni(r,e){ve(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ee(t.lowS,"lowS"),Ee(t.prehash,"prehash"),t.format!==void 0&&si(t.format),t}var Qe=BigInt(0),Dt=BigInt(1),kc=BigInt(2),oi=BigInt(3),rh=BigInt(4);function Lc(r,e={}){let t=Kn("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;ve(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:u,clearCofactor:l,isTorsionFree:f,fromBytes:d,toBytes:p}=e,E=e.randomBytes===void 0?Tt:e.randomBytes;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 w=c?{beta:c.beta,basises:c.basises.map(v=>[...v])}:void 0,y=Pc(n,o);function x(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function S(v,h,g){if(h.is0()){if(!u)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:b,y:B}=h.toAffine(),I=n.toBytes(b);if(Ee(g,"isCompressed"),g){x();let D=!n.isOdd(B);return Ce(Cc(D),I)}else return Ce(Uint8Array.of(4),I,n.toBytes(B))}function m(v){V(v,void 0,"Point");let{publicKey:h,publicKeyUncompressed:g}=y,b=v.length,B=v[0],I=v.subarray(1);if(u&&b===1&&B===0)return{x:n.ZERO,y:n.ZERO};if(b===h&&(B===2||B===3)){let D=n.fromBytes(I);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");let P=R(D),N;try{N=n.sqrt(P)}catch(ie){let Y=ie instanceof Error?": "+ie.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}x();let H=n.isOdd(N);return(B&1)===1!==H&&(N=n.neg(N)),{x:D,y:N}}else if(b===g&&B===4){let D=n.BYTES,P=n.fromBytes(I.subarray(0,D)),N=n.fromBytes(I.subarray(D,D*2));if(!k(P,N))throw new Error("bad point: is not on curve");return{x:P,y:N}}else throw new Error(`bad point: got length ${b}, expected compressed=${h} or uncompressed=${g}`)}let _=p===void 0?S:p,A=d===void 0?m:d,O=n.mul(s.b,oi),M=n.is0(s.a)?v=>n.ZERO:v=>n.mul(s.a,v);function R(v){let h=n.sqr(v),g=n.mul(h,v);return n.add(n.add(g,n.mul(v,s.a)),s.b)}function k(v,h){let g=n.sqr(h),b=R(v);return n.eql(g,b)}if(!k(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let C=n.mul(n.pow(s.a,oi),rh),K=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(C,K)))throw new Error("bad curve params: a or b");function z(v,h,g=!1){if(!n.isValid(h)||g&&n.is0(h))throw new Error(`bad point coordinate ${v}`);return typeof h=="object"&&h!==null?n.create(h):h}function G(v){if(!(v instanceof L))throw new Error("Weierstrass Point expected")}function T(v){if(!w||!w.basises)throw new Error("no endo");return th(v,w.basises,o.ORDER)}function U(v,h,g,b){if(!o.isValid(b))throw new RangeError("invalid scalar: out of range");if(w){let{k1neg:B,k1:I,k2neg:D,k2:P}=T(b),N=new L(n.mul(g.X,w.beta),g.Y,g.Z);v.push(B?g.negate():g,D?N.negate():N),h.push(I,P)}else v.push(g),h.push(b)}let F=new WeakSet;class L{static BASE=new L(s.Gx,s.Gy,n.ONE);static ZERO=new L(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(h,g,b){this.X=z("x",h),this.Y=z("y",g,!0),this.Z=z("z",b),Object.freeze(this)}static CURVE(){return s}static fromAffine(h){let{x:g,y:b}=h||{};if(!h||!n.isValid(g)||!n.isValid(b))throw new Error("invalid affine point");if(h instanceof L)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(b)?L.ZERO:new L(g,b,n.ONE)}static fromBytes(h){let g=L.fromAffine(A(V(h,void 0,"point")));return g.assertValidity(),g}static fromHex(h){return L.fromBytes(jt(h))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=6,g=!0){return re.setWindowSize(this,h),g||this.multiply(oi),this}assertValidity(){let h=this;if(h.is0()){if(u&&n.is0(h.X)&&n.eql(h.Y,n.ONE)&&n.is0(h.Z))return;throw new Error("bad point: ZERO")}if(F.has(h))return;let{x:g,y:b}=h.toAffine();if(!n.isValid(g)||!n.isValid(b))throw new Error("bad point: x or y not field elements");if(!k(g,b))throw new Error("bad point: equation left != right");if(!h.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");F.add(h)}hasEvenY(){let{y:h}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(h)}equals(h){G(h);let{X:g,Y:b,Z:B}=this,{X:I,Y:D,Z:P}=h,N=n.eql(n.mul(g,P),n.mul(I,B)),H=n.eql(n.mul(b,P),n.mul(D,B));return N&&H}negate(){return new L(this.X,n.neg(this.Y),this.Z)}double(){let{X:h,Y:g,Z:b}=this,B=n.ZERO,I=n.ZERO,D=n.ZERO,P=n.mul(h,h),N=n.mul(g,g),H=n.mul(b,b),q=n.mul(h,g);return q=n.add(q,q),D=n.mul(h,b),D=n.add(D,D),B=M(D),I=n.mul(O,H),I=n.add(B,I),B=n.sub(N,I),I=n.add(N,I),I=n.mul(B,I),B=n.mul(q,B),D=n.mul(O,D),H=M(H),q=n.sub(P,H),q=M(q),q=n.add(q,D),D=n.add(P,P),P=n.add(D,P),P=n.add(P,H),P=n.mul(P,q),I=n.add(I,P),H=n.mul(g,b),H=n.add(H,H),P=n.mul(H,q),B=n.sub(B,P),D=n.mul(H,N),D=n.add(D,D),D=n.add(D,D),new L(B,I,D)}add(h){G(h);let{X:g,Y:b,Z:B}=this,{X:I,Y:D,Z:P}=h,N=n.ZERO,H=n.ZERO,q=n.ZERO,ie=n.mul(g,I),Y=n.mul(b,D),fe=n.mul(B,P),Te=n.add(g,b),X=n.add(I,D);Te=n.mul(Te,X),X=n.add(ie,Y),Te=n.sub(Te,X),X=n.add(g,B);let ae=n.add(I,P);return X=n.mul(X,ae),ae=n.add(ie,fe),X=n.sub(X,ae),ae=n.add(b,B),N=n.add(D,P),ae=n.mul(ae,N),N=n.add(Y,fe),ae=n.sub(ae,N),q=M(X),N=n.mul(O,fe),q=n.add(N,q),N=n.sub(Y,q),q=n.add(Y,q),H=n.mul(N,q),Y=n.add(ie,ie),Y=n.add(Y,ie),fe=M(fe),X=n.mul(O,X),Y=n.add(Y,fe),fe=n.sub(ie,fe),fe=M(fe),X=n.add(X,fe),ie=n.mul(Y,X),H=n.add(H,ie),ie=n.mul(ae,X),N=n.mul(Te,N),N=n.sub(N,ie),ie=n.mul(Te,Y),q=n.mul(ae,q),q=n.add(q,ie),new L(N,H,q)}subtract(h){return G(h),this.add(h.negate())}is0(){return this.equals(L.ZERO)}multiply(h){if(!o.isValidNot0(h))throw new RangeError("invalid scalar: out of range");let{p:g,f:b}=re.mulSecret(this,h,i,Z);return Z([g,b])[0]}multiplyUnsafe(h){let g=this,b=h;if(!o.isValid(b))throw new RangeError("invalid scalar: out of range");if(b===Qe||g.is0())return L.ZERO;if(b===Dt)return g;if(re.hasWindowSize(this))return re.mulUnsafe(g,b,Z);let B=[],I=[];return U(B,I,g,b),zn(L,B,I)}mulAddUnsafe(h,g,b){G(g);let B=[],I=[];return U(B,I,this,h),U(B,I,g,b),zn(L,B,I)}toAffine(h){let g=this,b=h;if(b!=null&&!n.isValid(b))throw new RangeError('"invertedZ" expected valid field element');let{X:B,Y:I,Z:D}=g;if(n.eql(D,n.ONE))return{x:B,y:I};let P=g.is0();b==null&&(b=P?n.ONE:n.inv(D));let N=n.mul(B,b),H=n.mul(I,b),q=n.mul(D,b);if(P)return{x:n.ZERO,y:n.ZERO};if(!n.eql(q,n.ONE))throw new Error("invZ was invalid");return{x:N,y:H}}isTorsionFree(){return i===Dt?!0:f?f(L,this):re.mulUnsafe(this,a).is0()}clearCofactor(){return i===Dt?this:l?l(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Dt?this.is0():this.clearCofactor().is0()}toBytes(h=!0){return Ee(h,"isCompressed"),this.assertValidity(),_(L,this,h)}toHex(h=!0){return xr(this.toBytes(h))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Z=v=>Fn(L,v),re=new Qt(L,E);return re.bits>=6&&L.BASE.precompute(6),Object.freeze(L.prototype),Object.freeze(L),L}function Cc(r){return Uint8Array.of(r?2:3)}function Pc(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function nh(r,e={}){dt(r);let{Fn:t}=r,n=e.randomBytes===void 0?Tt:e.randomBytes,o=Object.assign(Pc(r.Fp,t),{seed:Math.max(Mn(t.ORDER),16)});function s(p){try{let E=t.fromBytes(p);return t.isValidNot0(E)}catch{return!1}}function i(p,E){let{publicKey:w,publicKeyUncompressed:y}=o;try{let x=p.length;return E===!0&&x!==w||E===!1&&x!==y?!1:!r.fromBytes(p).is0()}catch{return!1}}function a(p){return p=p===void 0?n(o.seed):p,Un(V(p,o.seed,"seed"),t.ORDER)}function c(p,E=!0){return r.BASE.multiply(t.fromBytes(p)).toBytes(E)}function u(p){let{secretKey:E,publicKey:w,publicKeyUncompressed:y}=o,x=t._lengths;if(!lt(p))return;let S=V(p,void 0,"key").length,m=S===w||S===y,_=S===E||!!x?.includes(S);if(!(m&&_))return m}function l(p,E,w=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(E)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(p),x=r.fromBytes(E);if(x.is0())throw new Error("invalid public key: point at infinity");return x.multiply(y).toBytes(w)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=qn(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:r,utils:f,lengths:o})}function Oc(r,e,t={}){dt(r);let n=e;Bn(n),ve(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},t),s=o.randomBytes===void 0?Tt:o.randomBytes,i=o.hmac===void 0?(v,h)=>Ic(n,v,h):o.hmac,{Fp:a,Fn:c}=r,{ORDER:u,BITS:l}=c,f=Mn(u),d=Gs(s,f),{keygen:p,getPublicKey:E,getSharedSecret:w,utils:y,lengths:x}=nh(r,o),S={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},m=u*kc+Dt<a.ORDER;function _(v){let h=u>>Dt;return v>h}function A(v,h){if(!c.isValidNot0(h))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return h}function O(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function M(v,h,g){return O(),(v===g?0:2)|Number(a.isOdd(h))}function R(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(v,h){si(h);let g=x.signature,b=h==="compact"?g:h==="recovered"?g+1:void 0;return V(v,b)}class C{r;s;recovery;constructor(h,g,b){if(this.r=A("r",h),this.s=A("s",g),b!=null){if(R(),![0,1,2,3].includes(b))throw new Error("invalid recovery id");this.recovery=b}Object.freeze(this)}static fromBytes(h,g=S.format){k(h,g);let b;if(g==="der"){if(h.length>2*c.BYTES+16)throw new Qn.Err("invalid signature: DER signature too long");let{r:P,s:N}=Qn.toSig(V(h),c.BYTES+1);return new C(P,N)}g==="recovered"&&(b=h[0],g="compact",h=h.subarray(1));let B=x.signature/2,I=h.subarray(0,B),D=h.subarray(B,B*2);return new C(c.fromBytes(I),c.fromBytes(D),b)}static fromHex(h,g){return this.fromBytes(jt(h),g)}assertRecovery(){let{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new C(this.r,this.s,h)}recoverPublicKey(h){let{r:g,s:b}=this,B=this.assertRecovery(),I=B===2||B===3?g+u:g;if(!a.isValid(I))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let D=a.toBytes(I),P=r.fromBytes(Ce(Cc((B&1)===0),D)),N=c.inv(I),H=z(V(h,void 0,"msgHash")),q=c.create(-H*N),ie=c.create(b*N),Y=r.BASE.mulAddUnsafe(q,P,ie);if(Y.is0())throw new Error("invalid recovery: point at infinify");return Y.assertValidity(),Y}hasHighS(){return _(this.s)}toBytes(h=S.format){if(si(h),h==="der")return jt(Qn.hexFromSig(this));let{r:g,s:b}=this,B=c.toBytes(g),I=c.toBytes(b);return h==="recovered"?(R(),Ce(Uint8Array.of(this.assertRecovery()),B,I)):Ce(B,I)}toHex(h){return xr(this.toBytes(h))}}Object.freeze(C.prototype),Object.freeze(C);let K=o.bits2int===void 0?function(h){if(h.length>8192)throw new Error("input is too large");let g=Ve(h),b=h.length*8-l;return b>0?g>>BigInt(b):g}:o.bits2int,z=o.bits2int_modN===void 0?function(h){return c.create(K(h))}:o.bits2int_modN,G=Sr(l);function T(v){return Gt("num < 2^"+l,v,Qe,G),c.toBytes(v)}function U(v,h){return V(v,void 0,"message"),h?V(n(v),void 0,"prehashed message"):v}function F(v,h,g){let{lowS:b,prehash:B,extraEntropy:I}=ni(g,S);v=U(v,B);let D=z(v),P=c.fromBytes(h);if(!c.isValidNot0(P))throw new Error("invalid private key");let N=[T(P),T(D)];if(I!=null&&I!==!1){let Y=I===!0?s(x.secretKey):I;N.push(V(Y,void 0,"extraEntropy"))}let H=Ce(...N),q=D;function ie(Y){let fe=K(Y);if(!c.isValidNot0(fe))return;let Te=r.BASE.multiply(fe).toAffine(),X=c.create(Te.x);if(X===Qe)return;let ae;if(d!==void 0){let er=Ve(Un(d(f),u)),Qc=c.inv(c.mul(er,fe)),Jc=c.mul(er,q),eu=c.mul(er,P);ae=c.create(Qc*c.create(Jc+eu*X))}else{let er=ac(fe,u);ae=c.create(er*c.create(q+X*P))}if(ae===Qe)return;let yo=M(Te.x,Te.y,X),yi=ae;return b&&_(ae)&&(yi=c.neg(ae),yo^=1),new C(X,yi,m?void 0:yo)}return{seed:H,k2sig:ie}}function L(v,h,g={}){let{seed:b,k2sig:B}=F(v,h,g);return Ja(n.outputLen,c.BYTES,i)(b,B).toBytes(g.format)}function Z(v,h,g,b={}){let{lowS:B,prehash:I,format:D}=ni(b,S);if(g=V(g,void 0,"publicKey"),h=U(h,I),!lt(v)){let P=v instanceof C?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}k(v,D);try{let P=C.fromBytes(v,D),N=r.fromBytes(g);if(N.is0()||B&&P.hasHighS())return!1;let{r:H,s:q}=P,ie=z(h),Y=c.inv(q),fe=c.create(ie*Y),Te=c.create(H*Y),X=r.BASE.mulAddUnsafe(fe,N,Te);if(X.is0())return!1;let ae=X.toAffine();return!(c.create(ae.x)!==H||D==="recovered"&&P.recovery!==M(ae.x,ae.y,H))}catch{return!1}}function re(v,h,g={}){let{prehash:b}=ni(g,S);return h=U(h,b),C.fromBytes(v,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:p,getPublicKey:E,getSharedSecret:w,utils:y,lengths:x,Point:r,sign:L,verify:Z,recoverPublicKey:re,Signature:C,hash:n})}var ai={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},oh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Rc=BigInt(2);function sh(r){let e=ai.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=ee(l,t,e)*l%e,d=ee(f,t,e)*l%e,p=ee(d,Rc,e)*u%e,E=ee(p,o,e)*p%e,w=ee(E,s,e)*E%e,y=ee(w,a,e)*w%e,x=ee(y,c,e)*y%e,S=ee(x,a,e)*w%e,m=ee(S,t,e)*l%e,_=ee(m,i,e)*E%e,A=ee(_,n,e)*u%e,O=ee(A,Rc,e);if(!ii.eql(ii.sqr(O),r))throw new Error("Cannot find square root");return O}var ii=Xt(ai.p,{sqrt:sh}),ih=Lc(ai,{Fp:ii,endo:oh}),Jt=Oc(ih,Za);function Nc(r,e,t,n){let o=nt.digest(t instanceof Uint8Array?t:t.subarray());if(Zn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Jt.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Br(String(s))});try{return n?.signal?.throwIfAborted(),Jt.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Br(String(s))}}var Jn=class{type="secp256k1";raw;_key;constructor(e){this._key=Uc(e),this.raw=Mc(this._key)}toMultihash(){return Pe.digest(Vt(this))}toCID(){return ne.createV1(114,this.toMultihash())}toString(){return ue.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 Nc(this._key,t,e,n)}};function Fc(r){return new Jn(r)}function Mc(r){return Jt.Point.fromBytes(r).toBytes()}function Uc(r){try{return Jt.Point.fromBytes(r),r}catch(e){throw new Or(String(e))}}function zc(r){let{Type:e,Data:t}=Tr.decode(r.digest),n=t??new Uint8Array;switch(e){case xe.Ed25519:return Tc(n);case xe.secp256k1:return Fc(n);case xe.ECDSA:return Ia(n);default:throw new tr}}function Vt(r){return Tr.encode({Type:xe[r.type],Data:r.raw})}var Kc=Symbol.for("nodejs.util.inspect.custom"),ah=114,Ir=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()})`}[Fr]=!0;toString(){return this.string==null&&(this.string=ue.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ne.createV1(ah,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")}[Kc](){return`PeerId(${this.toString()})`}},eo=class extends Ir{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},to=class extends Ir{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ro=class extends Ir{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},ch=2336,Dr=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Pe.digest(J(this.url))}[Kc](){return`PeerId(${this.url})`}[Fr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ne.createV1(ch,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var uh=114,qc=2336;function lh(r){if(dh(r))return new eo({multihash:r});if(fh(r))try{let e=zc(r);if(e.type==="Ed25519")return new to({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ro({multihash:r,publicKey:e})}catch{let t=j(r.digest);return new Dr(new URL(t))}throw new Nr("Supplied PeerID Multihash is invalid")}function no(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==uh&&r.code!==qc)throw new Rr("Supplied PeerID CID is invalid");if(r.code===qc){let e=j(r.multihash.digest);return new Dr(new URL(e))}return lh(r.multihash)}function fh(r){return r.code===Pe.code}function dh(r){return r.code===nt.code}function hh(r){return r[Symbol.asyncIterator]!=null}function ph(r){if(hh(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Hc=ph;function mh(r){return r[Symbol.asyncIterator]!=null}function gh(r,e){let t=0;if(mh(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=va(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Wc=gh;function yh(r){return r[Symbol.asyncIterator]!=null}function bh(r,e){return yh(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Vc=bh;var ci="/ipfs/bitswap/1.2.0";var te;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(te||(te={}));var ui;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ui||(ui={}));(function(r){r.codec=()=>zt(ui)})(te||(te={}));var kt;(function(r){let e;r.codec=()=>(e==null&&(e=He((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),te.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:me(0),priority:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=te.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=a==null?s.len:s.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"WantlistEntry"});s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${i}cid`,value:s.bytes()};break}case 2:{yield{field:`${i}priority`,value:s.int32()};break}case 3:{yield{field:`${i}cancel`,value:s.bool()};break}case 4:{yield{field:`${i}wantType`,value:te.codec().decode(s)};break}case 5:{yield{field:`${i}sendDontHave`,value:s.bool()};break}default:{s.skipType(l&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"WantlistEntry"})})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return ze(s,r.codec(),i)}r.decode=n;function o(s,i){return qe(s,r.codec(),i)}r.stream=o})(kt||(kt={}));var kr;(function(r){let e;r.codec=()=>(e==null&&(e=He((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),kt.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new $e('Decode error - repeated field "entries" had too many elements');c.entries.push(kt.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={entries:0},l=a==null?s.len:s.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"Wantlist"});s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{if(c.limits?.entries!=null&&u.entries===c.limits.entries)throw new $e('Streaming decode error - repeated field "entries" had too many elements');for(let d of kt.codec().stream(s,`${i}entries[].`,s.uint32(),{limits:c.limits?.entries$}))yield{...d,index:u.entries};u.entries++;break}case 2:{yield{field:`${i}full`,value:s.bool()};break}default:{s.skipType(f&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"Wantlist"})})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return ze(s,r.codec(),i)}r.decode=n;function o(s,i){return qe(s,r.codec(),i)}r.stream=o})(kr||(kr={}));var Lt;(function(r){let e;r.codec=()=>(e==null&&(e=He((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:me(0),data:me(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=a==null?s.len:s.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"Block"});s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${i}prefix`,value:s.bytes()};break}case 2:{yield{field:`${i}data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"Block"})})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return ze(s,r.codec(),i)}r.decode=n;function o(s,i){return qe(s,r.codec(),i)}r.stream=o})(Lt||(Lt={}));var Be;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Be||(Be={}));var oo;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(oo||(oo={}));(function(r){r.codec=()=>zt(oo)})(Be||(Be={}));var Ct;(function(r){let e;r.codec=()=>(e==null&&(e=He((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&oo[s.type]!==0&&(i.uint32(16),Be.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:me(0),type:Be.HaveBlock},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=Be.codec().decode(s);break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=a==null?s.len:s.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"BlockPresence"});s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${i}cid`,value:s.bytes()};break}case 2:{yield{field:`${i}type`,value:Be.codec().decode(s)};break}default:{s.skipType(l&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"BlockPresence"})})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return ze(s,r.codec(),i)}r.decode=n;function o(s,i){return qe(s,r.codec(),i)}r.stream=o})(Ct||(Ct={}));var Pt;(function(r){let e;r.codec=()=>(e==null&&(e=He((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),kr.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Lt.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Ct.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.wantlist=kr.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new $e('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Lt.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new $e('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Ct.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={blocks:0,blockPresences:0},l=a==null?s.len:s.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"BitswapMessage"});s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{yield*kr.codec().stream(s,`${i}wantlist.`,s.uint32(),{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&u.blocks===c.limits.blocks)throw new $e('Streaming decode error - repeated field "blocks" had too many elements');for(let d of Lt.codec().stream(s,`${i}blocks[].`,s.uint32(),{limits:c.limits?.blocks$}))yield{...d,index:u.blocks};u.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&u.blockPresences===c.limits.blockPresences)throw new $e('Streaming decode error - repeated field "blockPresences" had too many elements');for(let d of Ct.codec().stream(s,`${i}blockPresences[].`,s.uint32(),{limits:c.limits?.blockPresences$}))yield{...d,index:u.blockPresences};u.blockPresences++;break}case 5:{yield{field:`${i}pendingBytes`,value:s.int32()};break}default:{s.skipType(f&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"BitswapMessage"})})),e);function t(s){return Ke(s,r.codec())}r.encode=t;function n(s,i){return ze(s,r.codec(),i)}r.decode=n;function o(s,i){return qe(s,r.codec(),i)}r.stream=o})(Pt||(Pt={}));function $c(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var so=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var wh=4193648,xh=wh+16;function*jc(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let u={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},l=Pt.encode(u).byteLength,{added:f,hasMore:d,newSize:p}=li(o,u.blocks,a,e,l,Eh);a+=f,l=p;let E=d;({added:f,hasMore:d,newSize:p}=li(n,u.blockPresences,i,e,l,vh)),i+=f,l=p;let w=d;if({added:f,hasMore:d,newSize:p}=li(t,u.wantlist.entries,s,e,l,Sh),s+=f,l=p,c=!E&&!w&&!d,c||(u.wantlist.full=!1),yield Pt.encode(u),c)break}}function li(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let u=r[c],l=s(u);if(l>xh)throw new so("Cannot send block as after encoding it is over the max message size");let f=o+l;if(f>n){a=!0;break}e.push(u),i++,o=f}return{hasMore:a,added:i,newSize:o}}function Eh(r){return fi(3,Lt.encode(r))}function vh(r){return fi(4,Ct.encode(r))}function Sh(r){return fi(1,kt.encode(r))}function fi(r,e){let t=Q(r),n=Q(e.byteLength);return t+n+e.byteLength}function Ph(r){if(zr(r))return r;if(vn(r))return no(r);if(sn(r)||Array.isArray(r))return r;throw new De(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var io=class extends Fe{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[ci],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new xn({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new Mr(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=cn();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of pr(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Pt.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new pe("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new pe("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,router:n.router})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Hc(Wc(Vc(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=$c(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new De("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new pe("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,ci,s);await a.closeRead(s);try{for(let c of jc(i,this.maxOutgoingMessageSize))a.send(wn.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new pe("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Ur("Network isn't running");return e=Ph(e),t?.onProgress?.(new pe("bitswap:dial",e)),this.libp2p.dial(e,t)}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function ao(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Lr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return ao(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return ao(this.map.values(),e=>e.key)}values(){return ao(this.map.values(),e=>e.value)}get size(){return this.map.size}};var di=class extends Lr{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Cr(r){let{name:e,metrics:t}=r,n;return t!=null?n=new di({name:e,metrics:t}):n=new Lr,n}var co=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};var Je=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=mt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=mt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=mt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Oh(r){let e=new Uint8Array(r.reduce((n,o)=>n+Q(o),0)),t=0;for(let n of r)e=Wr(n,e,t),t+=Q(n);return e}var Gc=Oh;function hi(r){return Gc([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var uo=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;sendQueue;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024,this.sendQueue=new ot({concurrency:t.sendBlocksConcurrency??1,maxSize:t.sendBlocksMaxQueueLength??10})}stop(){this.sendQueue.abort()}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=ne.decode(n.cid),s=j(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===te.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===te.WantHave&&(n.wantType==null||n.wantType===te.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??te.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??te.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=j(e.multihash.bytes,"base64");return this.wants.has(t)}queueSendOperation(e,t){e!=null&&(this.receivedBytes(e.blocks?.reduce((n,o)=>n+o.data.byteLength,0)??0),this.addWants(e.wantlist));try{this.sendQueue.add(async n=>{this.log("send blocks to peer"),await this.sendBlocksToPeer(n)},t).catch(n=>{n.name==="QueueFullError"?this.log.error("Dropping bitswap message as peer send queue is full"):this.log.error("Error when trying to add queue a send operation")})}catch(n){if(n.name==="QueueFullError")this.log.error("Dropping bitswap message as peer send queue is full");else throw n}}async sendBlocksToPeer(e){let t=new Je,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");if(o.length!==0){o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{if(!await this.blockstore.has(i.cid,e))throw new co;let c=await Sa(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===te.WantHave?c.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:c,prefix:hi(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Be.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:c,prefix:hi(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Be.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}}};var lo=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;sendBlocksConcurrency;sendBlocksMaxQueueLength;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.sendBlocksConcurrency=t.sendBlocksConcurrency,this.sendBlocksMaxQueueLength=t.sendBlocksMaxQueueLength,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Cr({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{try{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message)}catch(o){this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)}}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}start(){}stop(){this.ledgerMap.forEach(e=>{e.stop()})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount,sendQueue:t.sendQueue}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new uo({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize,sendBlocksConcurrency:this.sendBlocksConcurrency,sendBlocksMaxQueueLength:this.sendBlocksMaxQueueLength}),this.ledgerMap.set(e,n)),n.queueSendOperation(t)}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.queueSendOperation(void 0,t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var pi=class extends En{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){if(n.signal?.aborted===!0)throw new Xr(`Signal to want session block for CID ${e} from peer ${t} was aborted prior to want`);let o=no(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,router:n.router,toString:()=>`Bitswap(${n.id})`,fallback:n.fallback}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(vn(e))return{peerId:e,router:t,toString:()=>`Bitswap(${e})`,fallback:!1};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),router:t,toString:()=>`Bitswap(${o.remotePeer})`,fallback:!1}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new pe("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],router:t.router,fallback:t.fallback},router:t.router}))}};function Zc(r,e){return new pi(r,e)}var fo=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var ho=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Pr(r,e,t,n){let o=new ho(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){gi(t,"abort",f),gi(r,e,u),gi(r,s,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(p){c(),a(p);return}c(),i(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};mi(t,"abort",f),mi(r,e,u),mi(r,s,l)})}function mi(r,e,t){r!=null&&(Yc(r)?r.addEventListener(e,t):r.addListener(e,t))}function gi(r,e,t){r!=null&&(Yc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Yc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Rh(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=gt(r);e.push(t),r=r.slice(Q(t))}return e}var Xc=Rh;var po=class extends Fe{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Cr({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=xa({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=j(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??te.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===te.WantHave&&t.wantType===te.WantBlock&&(o.wantType=te.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===te.WantBlock?(await Pr(this,"block",t?.signal,{filter:a=>ce(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Pr(this,"presence",t?.signal,{filter:i=>ce(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Me(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Je;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=j(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Je;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:te.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await Pr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&ce(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:te.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Je;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:te.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await Pr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&ce(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=j(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=Xc(o.prefix),i=s[0],a=s[1],c=s[2],u=s[3],l=c===nt.code?nt:await this.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let f=l.digest(o.data,{truncate:u});f.then!=null&&(f=await f);let d=ne.create(i===0?0:1,a,f);this.log("received block from %p for %c",e.remotePeer,d),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:d,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:d,has:!0,block:o.data}});let p=j(d.multihash.bytes,"base64"),E=this.wants.get(p);E!=null&&(E.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=ne.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===Be.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Je(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:te.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var mo=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new fo(e),this.network=new io(e,t),this.peerWantLists=new lo({...e,network:this.network},t),this.wantList=new po({...e,network:this.network},t)}createSession(e={}){return Zc({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=xi([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new pe("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),this.peerWantLists.stop(),await this.network.stop()}};var go=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new mo(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!zr(o.detail))return;t.onProgress(new pe("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new pe("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new pe("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new pe("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function Nh(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new go(n,e);await bi(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}return su(Mh);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/curves/utils.js: