@helia/block-brokers 5.2.0 → 5.2.1-ef5363e8
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 +10 -10
- package/dist/index.min.js.map +4 -4
- package/dist/src/trustless-gateway/session.d.ts +1 -2
- package/dist/src/trustless-gateway/session.d.ts.map +1 -1
- package/dist/src/trustless-gateway/session.js.map +1 -1
- package/package.json +18 -18
- package/src/trustless-gateway/session.ts +1 -2
- package/dist/typedoc-urls.json +0 -10
package/dist/index.min.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBlockBrokers = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaBlockBrokers=(()=>{var Iu=Object.create;var ln=Object.defineProperty;var Au=Object.getOwnPropertyDescriptor;var ku=Object.getOwnPropertyNames;var Tu=Object.getPrototypeOf,Du=Object.prototype.hasOwnProperty;var un=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),At=(r,t)=>{for(var e in t)ln(r,e,{get:t[e],enumerable:!0})},ya=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ku(t))!Du.call(r,s)&&s!==e&&ln(r,s,{get:()=>t[s],enumerable:!(n=Au(t,s))||n.enumerable});return r};var wa=(r,t,e)=>(e=r!=null?Iu(Tu(r)):{},ya(t||!r||!r.__esModule?ln(e,"default",{value:r,enumerable:!0}):e,r)),Lu=r=>ya(ln({},"__esModule",{value:!0}),r);var gi=un(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.Netmask4Impl=void 0;hr.ip2long=fr;hr.long2ip=Gt;function Gt(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,s=r&255;return[t,e,n,s].join(".")}var rd=48,nd=97,sd=65;function od(r){let t=0,e=10,n="9",s=0;r.length>1&&r[s]==="0"&&(r[s+1]==="x"||r[s+1]==="X"?(s+=2,e=16):"0"<=r[s+1]&&r[s+1]<="9"&&(s++,e=8,n="7"));let o=s;for(;s<r.length;){if("0"<=r[s]&&r[s]<=n)t=t*e+(r.charCodeAt(s)-rd)>>>0;else if(e===16)if("a"<=r[s]&&r[s]<="f")t=t*e+(10+r.charCodeAt(s)-nd)>>>0;else if("A"<=r[s]&&r[s]<="F")t=t*e+(10+r.charCodeAt(s)-sd)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");s++}if(s===o)throw new Error("empty octet");return[t,s]}function fr(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,s]=od(r);r=r.substring(s),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var mi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let s=t.split("/",2);t=s[0],n=s[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=fr(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let s=32;s>=0;s--)if(this.maskLong===4294967295<<32-s>>>0){this.bitmask=s;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(fr(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Gt(this.netLong),this.mask=Gt(this.maskLong),this.hostmask=Gt(~this.maskLong),this.first=this.bitmask<=30?Gt(this.netLong+1):this.base,this.last=this.bitmask<=30?Gt(this.netLong+this.size-2):Gt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Gt(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(fr(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Gt(this.netLong+this.size*t),this.mask)}forEach(t){let e=fr(this.first),n=fr(this.last),s=0;for(;e<=n;)t(Gt(e),e,s),s++,e++}toString(){return this.base+"/"+this.bitmask}};hr.Netmask4Impl=mi});var pl=un(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.Netmask6Impl=void 0;dr.ip6bigint=yi;dr.bigint2ip6=Re;var id=gi(),bi=(1n<<128n)-1n;function yi(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),s=(0,id.ip2long)(n),o=r.substring(0,e+1)+"0:0";return dl(o)&~0xffffffffn|BigInt(s)}return dl(r)}function dl(r){let t=r.indexOf("::"),e;if(t!==-1){let s=r.substring(0,t),o=r.substring(t+2),i=s===""?[]:s.split(":"),a=o===""?[]:o.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let s=0;s<8;s++){let o=e[s];if(o.length===0||o.length>4)throw new Error('Invalid IPv6: bad group "'+o+'"');let i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+o+'"');n=n<<16n|BigInt(i)}return n}function Re(r){if(r<0n||r>bi)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,s=-1,o=0;for(let i=0;i<8;i++)t[i]===0?s===-1?(s=i,o=1):o++:(o>n&&o>=2&&(e=s,n=o),s=-1,o=0);if(o>n&&o>=2&&(e=s,n=o),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var wi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let s=t.indexOf("/");s!==-1?(n=parseInt(t.substring(s+1),10),t=t.substring(0,s)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=bi>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=yi(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Re(this.netBigint),this.mask=Re(this.maskBigint),this.hostmask=Re(~this.maskBigint&bi),this.first=this.base,this.last=Re(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(yi(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(Re(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),s=this.netBigint+n-1n,o=0;for(;e<=s;)t(Re(e),Number(e),o),o++,e++}toString(){return this.base+"/"+this.bitmask}};dr.Netmask6Impl=wi});var ml=un(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.long2ip=ye.ip2long=ye.Netmask=void 0;var jn=gi();Object.defineProperty(ye,"ip2long",{enumerable:!0,get:function(){return jn.ip2long}});Object.defineProperty(ye,"long2ip",{enumerable:!0,get:function(){return jn.long2ip}});var ad=pl(),xi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new ad.Netmask6Impl(t,e):this._impl=new jn.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof jn.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};ye.Netmask=xi});var Zl=un((a2,Gl)=>{Gl.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Qp={};At(Qp,{bitswap:()=>Ql,trustlessGateway:()=>Su});var Bt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var kt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},fn=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var hn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},dn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},pn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var mn=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},gn=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var vr=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var bn=Symbol.for("@libp2p/peer-id");function Ve(r){return!!r?.[bn]}var Ht=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function xa(r){let t=new globalThis.AbortController;function e(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}var V=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var _r=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},yn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Ea={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new yn("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 t}};var wn=Ea;var Gs={};At(Gs,{base58btc:()=>at,base58flickr:()=>Uu});var um=new Uint8Array(0);function va(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Zt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function _a(r){return new TextEncoder().encode(r)}function Sa(r){return new TextDecoder().decode(r)}function Cu(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var _=0,w=0,y=0,I=d.length;y!==I&&d[y]===0;)y++,_++;for(var x=(I-y)*u+1>>>0,A=new Uint8Array(x);y!==I;){for(var R=d[y],M=0,F=x-1;(R!==0||M<w)&&F!==-1;F--,M++)R+=256*A[F]>>>0,A[F]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");w=M,y++}for(var v=x-w;v!==x&&A[v]===0;)v++;for(var E=c.repeat(_);v<x;++v)E+=r.charAt(A[v]);return E}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var _=0;if(d[_]!==" "){for(var w=0,y=0;d[_]===c;)w++,_++;for(var I=(d.length-_)*l+1>>>0,x=new Uint8Array(I);d[_];){var A=e[d.charCodeAt(_)];if(A===255)return;for(var R=0,M=I-1;(A!==0||R<y)&&M!==-1;M--,R++)A+=a*x[M]>>>0,x[M]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");y=R,_++}if(d[_]!==" "){for(var F=I-y;F!==I&&x[F]===0;)F++;for(var v=new Uint8Array(w+(I-F)),E=w;F!==I;)v[E++]=x[F++];return v}}}function p(d){var _=f(d);if(_)return _;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var Bu=Cu,Pu=Bu,Aa=Pu;var Ks=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},zs=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return ka(this,t)}},Vs=class{decoders;constructor(t){this.decoders=t}or(t){return ka(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ka(r,t){return new Vs({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Ws=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new Ks(t,e,n),this.decoder=new zs(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function We({name:r,prefix:t,encode:e,decode:n}){return new Ws(r,t,e,n)}function ce({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Aa(e,r);return We({prefix:t,name:r,encode:n,decode:o=>Zt(s(o))})}function Ru(r,t,e,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Ou(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;(o.length*e&7)!==0;)o+="=";return o}function Nu(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function ot({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let s=Nu(n);return We({prefix:t,name:r,encode(o){return Ou(o,n,e)},decode(o){return Ru(o,s,e,r)}})}var at=ce({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Uu=ce({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Zs={};At(Zs,{base32:()=>le,base32hex:()=>$u,base32hexpad:()=>Ku,base32hexpadupper:()=>zu,base32hexupper:()=>qu,base32pad:()=>Fu,base32padupper:()=>Hu,base32upper:()=>Mu,base32z:()=>Vu});var le=ot({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Mu=ot({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Fu=ot({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Hu=ot({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$u=ot({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),qu=ot({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ku=ot({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zu=ot({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Vu=ot({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ys={};At(Ys,{base36:()=>Sr,base36upper:()=>Wu});var Sr=ce({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Wu=ce({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gu=La,Ta=128,Zu=127,Yu=~Zu,ju=Math.pow(2,31);function La(r,t,e){t=t||[],e=e||0;for(var n=e;r>=ju;)t[e++]=r&255|Ta,r/=128;for(;r&Yu;)t[e++]=r&255|Ta,r>>>=7;return t[e]=r|0,La.bytes=e-n+1,t}var Xu=js,Qu=128,Da=127;function js(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw js.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&Da)<<s:(i&Da)*Math.pow(2,s),s+=7}while(i>=Qu);return js.bytes=o-n,e}var Ju=Math.pow(2,7),tf=Math.pow(2,14),ef=Math.pow(2,21),rf=Math.pow(2,28),nf=Math.pow(2,35),sf=Math.pow(2,42),of=Math.pow(2,49),af=Math.pow(2,56),cf=Math.pow(2,63),lf=function(r){return r<Ju?1:r<tf?2:r<ef?3:r<rf?4:r<nf?5:r<sf?6:r<of?7:r<af?8:r<cf?9:10},uf={encode:Gu,decode:Xu,encodingLength:lf},ff=uf,Ir=ff;function Ar(r,t=0){return[Ir.decode(r,t),Ir.decode.bytes]}function Ge(r,t,e=0){return Ir.encode(r,t,e),t}function Ze(r){return Ir.encodingLength(r)}function je(r,t){let e=t.byteLength,n=Ze(r),s=n+Ze(e),o=new Uint8Array(s+e);return Ge(r,o,0),Ge(e,o,n),o.set(t,s),new Ye(r,e,t,o)}function En(r){let t=Zt(r),[e,n]=Ar(t),[s,o]=Ar(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ye(e,s,i,t)}function Ca(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&va(r.bytes,e.bytes)}}var Ye=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};function Ba(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return df(e,Xs(r),t??at.encoder);default:return pf(e,Xs(r),t??le.encoder)}}var Pa=new WeakMap;function Xs(r){let t=Pa.get(r);if(t==null){let e=new Map;return Pa.set(r,e),e}return t}var et=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==kr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==mf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=je(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Ca(t.multihash,n.multihash)}toString(t){return Ba(this,t)}toJSON(){return{"/":Ba(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??Ra(n,s,o.bytes))}else if(e[gf]===!0){let{version:n,multihash:s,code:o}=e,i=En(s);return r.create(n,o,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==kr)throw new Error(`Version 0 CID must use dag-pb (code: ${kr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Ra(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,kr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=Zt(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Ye(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=Ar(t.subarray(e));return e+=f,h},s=n(),o=kr;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,s]=hf(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Xs(o).set(n,t),o}};function hf(r,t){switch(r[0]){case"Q":{let e=t??at;return[at.prefix,e.decode(`${at.prefix}${r}`)]}case at.prefix:{let e=t??at;return[at.prefix,e.decode(r)]}case le.prefix:{let e=t??le;return[le.prefix,e.decode(r)]}case Sr.prefix:{let e=t??Sr;return[Sr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function df(r,t,e){let{prefix:n}=e;if(n!==at.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function pf(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var kr=112,mf=18;function Ra(r,t,e){let n=Ze(r),s=n+Ze(t),o=new Uint8Array(s+e.byteLength);return Ge(r,o,0),Ge(t,o,n),o.set(e,s),o}var gf=Symbol.for("@ipld/js-cid/CID");var Qs={};At(Qs,{identity:()=>Tt});var Oa=0,bf="identity",Na=Zt;function yf(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return je(Oa,Na(r))}var Tt={code:Oa,name:bf,encode:Na,digest:yf};function ct(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function yt(r=0){return new Uint8Array(r)}function wt(r=0){return new Uint8Array(r)}function Ct(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=wt(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}var Ma=Symbol.for("@achingbrain/uint8arraylist");function Ua(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function vn(r){return!!r?.[Ma]}var ut=class r{bufs;length;[Ma]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(vn(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(vn(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Ua(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ua(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(vn(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return Ct(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Ct(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!vn(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<s;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let p=this.get(h+f);if(n[f]!==p){u=Math.max(1,f-a[p]);break}}if(u===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=yt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=yt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=yt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=yt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=yt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=yt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=yt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=yt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!ct(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,o)=>s+o.byteLength,0)),n.length=e,n}};var Js={};At(Js,{base10:()=>wf});var wf=ce({prefix:"9",name:"base10",alphabet:"0123456789"});var to={};At(to,{base16:()=>xf,base16upper:()=>Ef});var xf=ot({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ef=ot({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var eo={};At(eo,{base2:()=>vf});var vf=ot({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ro={};At(ro,{base256emoji:()=>kf});var Fa=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}"),_f=Fa.reduce((r,t,e)=>(r[e]=t,r),[]),Sf=Fa.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function If(r){return r.reduce((t,e)=>(t+=_f[e],t),"")}function Af(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=Sf[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var kf=We({prefix:"\u{1F680}",name:"base256emoji",encode:If,decode:Af});var so={};At(so,{base64:()=>Yt,base64pad:()=>Tf,base64url:()=>no,base64urlpad:()=>Df});var Yt=ot({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Tf=ot({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),no=ot({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Df=ot({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var oo={};At(oo,{base8:()=>Lf});var Lf=ot({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var io={};At(io,{identity:()=>Cf});var Cf=We({prefix:"\0",name:"identity",encode:r=>Sa(r),decode:r=>_a(r)});var Gm=new TextEncoder,Zm=new TextDecoder;var lo={};At(lo,{sha256:()=>ue,sha512:()=>Of});var Rf=20;function co({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:s}){return new ao(r,t,e,n,s)}var ao=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,s,o){this.name=t,this.code=e,this.encode=n,this.minDigestLength=s??Rf,this.maxDigestLength=o}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Ha(n,this.code,e?.truncate):n.then(s=>Ha(s,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ha(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return je(t,r)}function qa(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var ue=co({name:"sha2-256",code:18,encode:qa("SHA-256")}),Of=co({name:"sha2-512",code:19,encode:qa("SHA-512")});var Tr={...io,...eo,...oo,...Js,...to,...Zs,...Ys,...Gs,...so,...ro},i0={...lo,...Qs};function za(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ka=za("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),uo=za("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=wt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Nf={utf8:Ka,"utf-8":Ka,hex:Tr.base16,latin1:uo,ascii:uo,binary:uo,...Tr},_n=Nf;function Z(r,t="utf8"){let e=_n[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function W(r,t="utf8"){let e=_n[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Uf=parseInt("11111",2),fo=parseInt("10000000",2),Mf=parseInt("01111111",2),Va={0:Dr,1:Dr,2:Ff,3:qf,4:Kf,5:$f,6:Hf,16:Dr,22:Dr,48:Dr};function ho(r,t={offset:0}){let e=r[t.offset]&Uf;if(t.offset++,Va[e]!=null)return Va[e](r,t);throw new Error("No decoder for tag "+e)}function Lr(r,t){let e=0;if((r[t.offset]&fo)===fo){let n=r[t.offset]&Mf,s="0x";t.offset++;for(let o=0;o<n;o++,t.offset++)s+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(s,16)}else e=r[t.offset],t.offset++;return e}function Dr(r,t){Lr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ho(r,t);if(n===null)break;e.push(n)}return e}function Ff(r,t){let e=Lr(r,t),n=t.offset,s=t.offset+e,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return t.offset+=e,Uint8Array.from(o)}function Hf(r,t){let e=Lr(r,t),n=t.offset+e,s=r[t.offset];t.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function $f(r,t){return t.offset++,null}function qf(r,t){let e=Lr(r,t),n=r[t.offset];t.offset++;let s=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function Kf(r,t){let e=Lr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function zf(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ut;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function po(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=zf(r.byteLength);return new ut(Uint8Array.from([t.byteLength|fo]),t)}function Wa(r){let t=new ut,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ut(Uint8Array.from([2]),po(t),t)}function Ga(r){let t=Uint8Array.from([0]),e=new ut(t,r);return new ut(Uint8Array.from([3]),po(e),e)}function Sn(r,t=48){let e=new ut;for(let n of r)e.append(n);return new ut(Uint8Array.from([t]),po(e),e)}async function Za(r,t,e,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,e.subarray());return n?.signal?.throwIfAborted(),o}var Vf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Wf=Uint8Array.from([6,5,43,129,4,0,34]),Gf=Uint8Array.from([6,5,43,129,4,0,35]),Zf={ext:!0,kty:"EC",crv:"P-256"},Yf={ext:!0,kty:"EC",crv:"P-384"},jf={ext:!0,kty:"EC",crv:"P-521"},mo=32,go=48,bo=66;function Ya(r){let t=ho(r);return ja(t)}function ja(r){let t=r[1][1][0],e=1,n,s;if(t.byteLength===mo*2+1)return n=W(t.subarray(e,e+mo),"base64url"),s=W(t.subarray(e+mo),"base64url"),new Xe({...Zf,key_ops:["verify"],x:n,y:s});if(t.byteLength===go*2+1)return n=W(t.subarray(e,e+go),"base64url"),s=W(t.subarray(e+go),"base64url"),new Xe({...Yf,key_ops:["verify"],x:n,y:s});if(t.byteLength===bo*2+1)return n=W(t.subarray(e,e+bo),"base64url"),s=W(t.subarray(e+bo),"base64url"),new Xe({...jf,key_ops:["verify"],x:n,y:s});throw new kt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Xa(r){return Sn([Wa(Uint8Array.from([1])),Sn([Xf(r.crv)],160),Sn([Ga(new ut(Uint8Array.from([4]),Z(r.x??"","base64url"),Z(r.y??"","base64url")))],161)]).subarray()}function Xf(r){if(r==="P-256")return Vf;if(r==="P-384")return Wf;if(r==="P-521")return Gf;throw new kt(`Invalid curve ${r}`)}var Xe=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Xa(this.jwk)),this._raw}toMultihash(){return Tt.digest(Qe(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return at.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}async verify(t,e,n){return Za(this.jwk,e,t,n)}};function ve(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function $t(r,t=""){if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${r}`)}}function U(r,t,e=""){let n=ve(r),s=r?.length,o=t!==void 0;if(!n||o&&s!==t){let i=e&&`"${e}" `,a=o?` of length ${t}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function In(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");$t(r.outputLen),$t(r.blockLen)}function Je(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Ja(r,t){U(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Xt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function An(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Pt(r,t){return r<<32-t|r>>>t}var tc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qf=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Qt(r){if(U(r),tc)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Qf[r[e]];return t}var jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Qa(r){if(r>=jt._0&&r<=jt._9)return r-jt._0;if(r>=jt.A&&r<=jt.F)return r-(jt.A-10);if(r>=jt.a&&r<=jt.f)return r-(jt.a-10)}function Jt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(tc)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let s=0,o=0;s<e;s++,o+=2){let i=Qa(r.charCodeAt(o)),a=Qa(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function It(...r){let t=0;for(let n=0;n<r.length;n++){let s=r[n];U(s),t+=s.length}let e=new Uint8Array(t);for(let n=0,s=0;n<r.length;n++){let o=r[n];e.set(o,s),s+=o.length}return e}function yo(r,t={}){let e=(s,o)=>r(o).update(s).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=s=>r(s),Object.assign(e,t),Object.freeze(e)}function tr(r=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(r))}var wo=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ec(r,t,e){return r&t^~r&e}function rc(r,t,e){return r&t^r&e^t&e}var Cr=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,s){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=An(this.buffer)}update(t){Je(this),U(t);let{view:e,buffer:n,blockLen:s}=this,o=t.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=An(t);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Je(this),Ja(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;e[i++]=128,Xt(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let h=i;h<s;h++)e[h]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=An(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=o,t.length=s,t.pos=a,s%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},te=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var mt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var kn=BigInt(4294967295),nc=BigInt(32);function Jf(r,t=!1){return t?{h:Number(r&kn),l:Number(r>>nc&kn)}:{h:Number(r>>nc&kn)|0,l:Number(r&kn)|0}}function sc(r,t=!1){let e=r.length,n=new Uint32Array(e),s=new Uint32Array(e);for(let o=0;o<e;o++){let{h:i,l:a}=Jf(r[o],t);[n[o],s[o]]=[i,a]}return[n,s]}var xo=(r,t,e)=>r>>>e,Eo=(r,t,e)=>r<<32-e|t>>>e,_e=(r,t,e)=>r>>>e|t<<32-e,Se=(r,t,e)=>r<<32-e|t>>>e,Br=(r,t,e)=>r<<64-e|t>>>e-32,Pr=(r,t,e)=>r>>>e-32|t<<64-e;function qt(r,t,e,n){let s=(t>>>0)+(n>>>0);return{h:r+e+(s/2**32|0)|0,l:s|0}}var oc=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),ic=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ac=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),cc=(r,t,e,n,s)=>t+e+n+s+(r/2**32|0)|0,lc=(r,t,e,n,s)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(s>>>0),uc=(r,t,e,n,s,o)=>t+e+n+s+o+(r/2**32|0)|0;var eh=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]),fe=new Uint32Array(64),vo=class extends Cr{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[t,e,n,s,o,i,a,c]}set(t,e,n,s,o,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let h=0;h<16;h++,e+=4)fe[h]=t.getUint32(e,!1);for(let h=16;h<64;h++){let f=fe[h-15],p=fe[h-2],d=Pt(f,7)^Pt(f,18)^f>>>3,_=Pt(p,17)^Pt(p,19)^p>>>10;fe[h]=_+fe[h-7]+d+fe[h-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let f=Pt(a,6)^Pt(a,11)^Pt(a,25),p=u+f+ec(a,c,l)+eh[h]+fe[h]|0,_=(Pt(n,2)^Pt(n,13)^Pt(n,22))+rc(n,s,o)|0;u=l,l=c,c=a,a=i+p|0,i=o,o=s,s=n,n=p+_|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){Xt(fe)}destroy(){this.set(0,0,0,0,0,0,0,0),Xt(this.buffer)}},_o=class extends vo{A=te[0]|0;B=te[1]|0;C=te[2]|0;D=te[3]|0;E=te[4]|0;F=te[5]|0;G=te[6]|0;H=te[7]|0;constructor(){super(32)}};var fc=sc(["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))),rh=fc[0],nh=fc[1],he=new Uint32Array(80),de=new Uint32Array(80),So=class extends Cr{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:p,Gl:d,Hh:_,Hl:w}=this;return[t,e,n,s,o,i,a,c,l,u,h,f,p,d,_,w]}set(t,e,n,s,o,i,a,c,l,u,h,f,p,d,_,w){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=_|0,this.Hl=w|0}process(t,e){for(let x=0;x<16;x++,e+=4)he[x]=t.getUint32(e),de[x]=t.getUint32(e+=4);for(let x=16;x<80;x++){let A=he[x-15]|0,R=de[x-15]|0,M=_e(A,R,1)^_e(A,R,8)^xo(A,R,7),F=Se(A,R,1)^Se(A,R,8)^Eo(A,R,7),v=he[x-2]|0,E=de[x-2]|0,O=_e(v,E,19)^Br(v,E,61)^xo(v,E,6),H=Se(v,E,19)^Pr(v,E,61)^Eo(v,E,6),L=ac(F,H,de[x-7],de[x-16]),g=cc(L,M,O,he[x-7],he[x-16]);he[x]=g|0,de[x]=L|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:p,Fl:d,Gh:_,Gl:w,Hh:y,Hl:I}=this;for(let x=0;x<80;x++){let A=_e(h,f,14)^_e(h,f,18)^Br(h,f,41),R=Se(h,f,14)^Se(h,f,18)^Pr(h,f,41),M=h&p^~h&_,F=f&d^~f&w,v=lc(I,R,F,nh[x],de[x]),E=uc(v,y,A,M,rh[x],he[x]),O=v|0,H=_e(n,s,28)^Br(n,s,34)^Br(n,s,39),L=Se(n,s,28)^Pr(n,s,34)^Pr(n,s,39),g=n&o^n&a^o&a,b=s&i^s&c^i&c;y=_|0,I=w|0,_=p|0,w=d|0,p=h|0,d=f|0,{h,l:f}=qt(l|0,u|0,E|0,O|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let m=oc(O,L,b);n=ic(m,E,H,g),s=m|0}({h:n,l:s}=qt(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=qt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=qt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=qt(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=qt(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=qt(this.Fh|0,this.Fl|0,p|0,d|0),{h:_,l:w}=qt(this.Gh|0,this.Gl|0,_|0,w|0),{h:y,l:I}=qt(this.Hh|0,this.Hl|0,y|0,I|0),this.set(n,s,o,i,a,c,l,u,h,f,p,d,_,w,y,I)}roundClean(){Xt(he,de)}destroy(){Xt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Io=class extends So{Ah=mt[0]|0;Al=mt[1]|0;Bh=mt[2]|0;Bl=mt[3]|0;Ch=mt[4]|0;Cl=mt[5]|0;Dh=mt[6]|0;Dl=mt[7]|0;Eh=mt[8]|0;El=mt[9]|0;Fh=mt[10]|0;Fl=mt[11]|0;Gh=mt[12]|0;Gl=mt[13]|0;Hh=mt[14]|0;Hl=mt[15]|0;constructor(){super(64)}};var hc=yo(()=>new _o,wo(1));var dc=yo(()=>new Io,wo(3));var ko=BigInt(0),Ao=BigInt(1);function ee(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function pc(r){if(typeof r=="bigint"){if(!Tn(r))throw new Error("positive bigint expected, got "+r)}else $t(r);return r}function Rr(r){let t=pc(r).toString(16);return t.length&1?"0"+t:t}function mc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ko:BigInt("0x"+r)}function er(r){return mc(Qt(r))}function Ie(r){return mc(Qt(Ln(U(r)).reverse()))}function Dn(r,t){$t(t),r=pc(r);let e=Jt(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function To(r,t){return Dn(r,t).reverse()}function Ln(r){return Uint8Array.from(r)}var Tn=r=>typeof r=="bigint"&&ko<=r;function sh(r,t,e){return Tn(r)&&Tn(t)&&Tn(e)&&t<=r&&r<e}function Or(r,t,e,n){if(!sh(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Do(r){let t;for(t=0;r>ko;r>>=Ao,t+=1);return t}var Nr=r=>(Ao<<BigInt(r))-Ao;function gc(r,t,e){if($t(r,"hashLen"),$t(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let n=w=>new Uint8Array(w),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,h=()=>{c.fill(1),l.fill(0),u=0},f=(...w)=>e(l,It(c,...w)),p=(w=s)=>{l=f(o,w),c=f(),w.length!==0&&(l=f(i,w),c=f())},d=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let w=0,y=[];for(;w<t;){c=f();let I=c.slice();y.push(I),w+=c.length}return It(...y)};return(w,y)=>{h(),p(w);let I;for(;!(I=y(d()));)p();return h(),I}}function pe(r,t={},e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(t,!1),s(e,!0)}function rr(r){let t=new WeakMap;return(e,...n)=>{let s=t.get(e);if(s!==void 0)return s;let o=r(e,...n);return t.set(e,o),o}}var _t=BigInt(0),ft=BigInt(1),Ae=BigInt(2),wc=BigInt(3),xc=BigInt(4),Ec=BigInt(5),oh=BigInt(7),vc=BigInt(8),ih=BigInt(9),_c=BigInt(16);function it(r,t){let e=r%t;return e>=_t?e:t+e}function Q(r,t,e){let n=r;for(;t-- >_t;)n*=n,n%=e;return n}function bc(r,t){if(r===_t)throw new Error("invert: expected non-zero number");if(t<=_t)throw new Error("invert: expected positive modulus, got "+t);let e=it(r,t),n=t,s=_t,o=ft,i=ft,a=_t;for(;e!==_t;){let l=n/e,u=n%e,h=s-i*l,f=o-a*l;n=e,e=u,s=i,o=a,i=h,a=f}if(n!==ft)throw new Error("invert: does not exist");return it(s,t)}function Co(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function Sc(r,t){let e=(r.ORDER+ft)/xc,n=r.pow(t,e);return Co(r,n,t),n}function ah(r,t){let e=(r.ORDER-Ec)/vc,n=r.mul(t,Ae),s=r.pow(n,e),o=r.mul(t,s),i=r.mul(r.mul(o,Ae),s),a=r.mul(o,r.sub(i,r.ONE));return Co(r,a,t),a}function ch(r){let t=nr(r),e=Ic(r),n=e(t,t.neg(t.ONE)),s=e(t,n),o=e(t,t.neg(n)),i=(r+oh)/_c;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),h=a.mul(l,s),f=a.mul(l,o),p=a.eql(a.sqr(u),c),d=a.eql(a.sqr(h),c);l=a.cmov(l,u,p),u=a.cmov(f,h,d);let _=a.eql(a.sqr(u),c),w=a.cmov(l,u,_);return Co(a,w,c),w}}function Ic(r){if(r<wc)throw new Error("sqrt is not defined for small field");let t=r-ft,e=0;for(;t%Ae===_t;)t/=Ae,e++;let n=Ae,s=nr(r);for(;yc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Sc;let o=s.pow(n,t),i=(t+ft)/Ae;return function(c,l){if(c.is0(l))return l;if(yc(c,l)!==1)throw new Error("Cannot find square root");let u=e,h=c.mul(c.ONE,o),f=c.pow(l,t),p=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let d=1,_=c.sqr(f);for(;!c.eql(_,c.ONE);)if(d++,_=c.sqr(_),d===u)throw new Error("Cannot find square root");let w=ft<<BigInt(u-d-1),y=c.pow(h,w);u=d,h=c.sqr(y),f=c.mul(f,h),p=c.mul(p,y)}return p}}function lh(r){return r%xc===wc?Sc:r%vc===Ec?ah:r%_c===ih?ch(r):Ic(r)}var Ac=(r,t)=>(it(r,t)&ft)===ft,uh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Bo(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=uh.reduce((n,s)=>(n[s]="function",n),t);return pe(r,e),r}function fh(r,t,e){if(e<_t)throw new Error("invalid exponent, negatives unsupported");if(e===_t)return r.ONE;if(e===ft)return t;let n=r.ONE,s=t;for(;e>_t;)e&ft&&(n=r.mul(n,s)),s=r.sqr(s),e>>=ft;return n}function Ur(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),s=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),o=r.inv(s);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),o),n}function yc(r,t){let e=(r.ORDER-ft)/Ae,n=r.pow(t,e),s=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function hh(r,t){t!==void 0&&$t(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}var Lo=class{ORDER;BITS;BYTES;isLE;ZERO=_t;ONE=ft;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=_t)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:s,nByteLength:o}=hh(t,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return it(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return _t<=t&&t<this.ORDER}is0(t){return t===_t}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&ft)===ft}neg(t){return it(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return it(t*t,this.ORDER)}add(t,e){return it(t+e,this.ORDER)}sub(t,e){return it(t-e,this.ORDER)}mul(t,e){return it(t*e,this.ORDER)}pow(t,e){return fh(this,t,e)}div(t,e){return it(t*bc(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return bc(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=lh(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?To(t,this.BYTES):Dn(t,this.BYTES)}fromBytes(t,e=!1){U(t);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let l=new Uint8Array(s);l.set(t,o?0:l.length-t.length),t=l}if(t.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);let c=o?Ie(t):er(t);if(a&&(c=it(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Ur(this,t)}cmov(t,e,n){return n?e:t}};function nr(r,t={}){return new Lo(r,t)}function kc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Po(r){let t=kc(r);return t+Math.ceil(t/2)}function Ro(r,t,e=!1){U(r);let n=r.length,s=kc(t),o=Po(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=e?Ie(r):er(r),a=it(i,t-ft)+ft;return e?To(a,s):Dn(a,s)}var sr=BigInt(0),ke=BigInt(1);function Mr(r,t){let e=t.negate();return r?e:t}function Te(r,t){let e=Ur(r.Fp,t.map(n=>n.Z));return t.map((n,s)=>r.fromAffine(n.toAffine(e[s])))}function Cc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Oo(r,t){Cc(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),s=2**r,o=Nr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function Tc(r,t,e){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=e,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=ke);let l=t*n,u=l+Math.abs(a)-1,h=a===0,f=a<0,p=t%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:l}}var No=new WeakMap,Bc=new WeakMap;function Uo(r){return Bc.get(r)||1}function Dc(r){if(r!==sr)throw new Error("invalid wNAF")}var or=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let s=t;for(;e>sr;)e&ke&&(n=n.add(s)),s=s.double(),e>>=ke;return n}precomputeWindow(t,e){let{windows:n,windowSize:s}=Oo(e,this.bits),o=[],i=t,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Oo(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:f,offsetF:p}=Tc(n,a,i);n=c,u?o=o.add(Mr(f,e[p])):s=s.add(Mr(h,e[l]))}return Dc(n),{p:s,f:o}}wNAFUnsafe(t,e,n,s=this.ZERO){let o=Oo(t,this.bits);for(let i=0;i<o.windows&&n!==sr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Tc(n,i,o);if(n=a,!l){let h=e[c];s=s.add(u?h.negate():h)}}return Dc(n),s}getPrecomputes(t,e,n){let s=No.get(e);return s||(s=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(s=n(s)),No.set(e,s))),s}cached(t,e,n){let s=Uo(t);return this.wNAF(s,this.getPrecomputes(s,t,n),e)}unsafe(t,e,n,s){let o=Uo(t);return o===1?this._unsafeLadder(t,e,s):this.wNAFUnsafe(o,this.getPrecomputes(o,t,n),e,s)}createCache(t,e){Cc(e,this.bits),Bc.set(t,e),No.delete(t)}hasCache(t){return Uo(t)!==1}};function Pc(r,t,e,n){let s=t,o=r.ZERO,i=r.ZERO;for(;e>sr||n>sr;)e&ke&&(o=o.add(s)),n&ke&&(i=i.add(s)),s=s.double(),e>>=ke,n>>=ke;return{p1:o,p2:i}}function Lc(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Bo(t),t}else return nr(r,{isLE:e})}function Cn(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>sr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Lc(t.p,e.Fp,n),o=Lc(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:s,Fn:o}}function Bn(r,t){return function(n){let s=r(n);return{secretKey:s,publicKey:t(s)}}}var me=BigInt(0),ht=BigInt(1),Mo=BigInt(2),dh=BigInt(8);function ph(r,t,e,n){let s=r.sqr(e),o=r.sqr(n),i=r.add(r.mul(t.a,s),o),a=r.add(r.ONE,r.mul(t.d,r.mul(s,o)));return r.eql(i,a)}function Rc(r,t={}){let e=Cn("edwards",r,t,t.FpFnLE),{Fp:n,Fn:s}=e,o=e.CURVE,{h:i}=o;pe(t,{},{uvRatio:"function"});let a=Mo<<BigInt(s.BYTES*8)-ht,c=w=>n.create(w),l=t.uvRatio||((w,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,y))}}catch{return{isValid:!1,value:me}}});if(!ph(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(w,y,I=!1){let x=I?ht:me;return Or("coordinate "+w,y,x,a),y}function h(w){if(!(w instanceof d))throw new Error("EdwardsPoint expected")}let f=rr((w,y)=>{let{X:I,Y:x,Z:A}=w,R=w.is0();y==null&&(y=R?dh:n.inv(A));let M=c(I*y),F=c(x*y),v=n.mul(A,y);if(R)return{x:me,y:ht};if(v!==ht)throw new Error("invZ was invalid");return{x:M,y:F}}),p=rr(w=>{let{a:y,d:I}=o;if(w.is0())throw new Error("bad point: ZERO");let{X:x,Y:A,Z:R,T:M}=w,F=c(x*x),v=c(A*A),E=c(R*R),O=c(E*E),H=c(F*y),L=c(E*c(H+v)),g=c(O+c(I*c(F*v)));if(L!==g)throw new Error("bad point: equation left != right (1)");let b=c(x*A),m=c(R*M);if(b!==m)throw new Error("bad point: equation left != right (2)");return!0});class d{static BASE=new d(o.Gx,o.Gy,ht,c(o.Gx*o.Gy));static ZERO=new d(me,ht,ht,me);static Fp=n;static Fn=s;X;Y;Z;T;constructor(y,I,x,A){this.X=u("x",y),this.Y=u("y",I),this.Z=u("z",x,!0),this.T=u("t",A),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof d)throw new Error("extended point not allowed");let{x:I,y:x}=y||{};return u("x",I),u("y",x),new d(I,x,ht,c(I*x))}static fromBytes(y,I=!1){let x=n.BYTES,{a:A,d:R}=o;y=Ln(U(y,x,"point")),ee(I,"zip215");let M=Ln(y),F=y[x-1];M[x-1]=F&-129;let v=Ie(M),E=I?a:n.ORDER;Or("point.y",v,me,E);let O=c(v*v),H=c(O-ht),L=c(R*O-A),{isValid:g,value:b}=l(H,L);if(!g)throw new Error("bad point: invalid y coordinate");let m=(b&ht)===ht,S=(F&128)!==0;if(!I&&b===me&&S)throw new Error("bad point: x=0 and x_0=1");return S!==m&&(b=c(-b)),d.fromAffine({x:b,y:v})}static fromHex(y,I=!1){return d.fromBytes(Jt(y),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,I=!0){return _.createCache(this,y),I||this.multiply(Mo),this}assertValidity(){p(this)}equals(y){h(y);let{X:I,Y:x,Z:A}=this,{X:R,Y:M,Z:F}=y,v=c(I*F),E=c(R*A),O=c(x*F),H=c(M*A);return v===E&&O===H}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=o,{X:I,Y:x,Z:A}=this,R=c(I*I),M=c(x*x),F=c(Mo*c(A*A)),v=c(y*R),E=I+x,O=c(c(E*E)-R-M),H=v+M,L=H-F,g=v-M,b=c(O*L),m=c(H*g),S=c(O*g),k=c(L*H);return new d(b,m,k,S)}add(y){h(y);let{a:I,d:x}=o,{X:A,Y:R,Z:M,T:F}=this,{X:v,Y:E,Z:O,T:H}=y,L=c(A*v),g=c(R*E),b=c(F*x*H),m=c(M*O),S=c((A+R)*(v+E)-L-g),k=m-b,D=m+b,C=c(g-I*L),T=c(S*k),P=c(D*C),N=c(S*C),rt=c(k*D);return new d(T,P,rt,N)}subtract(y){return this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:I,f:x}=_.cached(this,y,A=>Te(d,A));return Te(d,[I,x])[0]}multiplyUnsafe(y,I=d.ZERO){if(!s.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===me?d.ZERO:this.is0()||y===ht?this:_.unsafe(this,y,x=>Te(d,x),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return _.unsafe(this,o.n).is0()}toAffine(y){return f(this,y)}clearCofactor(){return i===ht?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:I}=this.toAffine(),x=n.toBytes(I);return x[x.length-1]|=y&ht?128:0,x}toHex(){return Qt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let _=new or(d,s.BITS);return d.BASE.precompute(8),d}function Oc(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');pe(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:s,Fp:o,Fn:i}=r,a=e.randomBytes||tr,c=e.adjustScalarBytes||(v=>v),l=e.domain||((v,E,O)=>{if(ee(O,"phflag"),E.length||O)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(Ie(v))}function h(v){let E=x.secretKey;U(v,x.secretKey,"secretKey");let O=U(t(v),2*E,"hashedSecretKey"),H=c(O.slice(0,E)),L=O.slice(E,2*E),g=u(H);return{head:H,prefix:L,scalar:g}}function f(v){let{head:E,prefix:O,scalar:H}=h(v),L=s.multiply(H),g=L.toBytes();return{head:E,prefix:O,scalar:H,point:L,pointBytes:g}}function p(v){return f(v).pointBytes}function d(v=Uint8Array.of(),...E){let O=It(...E);return u(t(l(O,U(v,void 0,"context"),!!n)))}function _(v,E,O={}){v=U(v,void 0,"message"),n&&(v=n(v));let{prefix:H,scalar:L,pointBytes:g}=f(E),b=d(O.context,H,v),m=s.multiply(b).toBytes(),S=d(O.context,m,g,v),k=i.create(b+S*L);if(!i.isValid(k))throw new Error("sign failed: invalid s");let D=It(m,i.toBytes(k));return U(D,x.signature,"result")}let w={zip215:!0};function y(v,E,O,H=w){let{context:L,zip215:g}=H,b=x.signature;v=U(v,b,"signature"),E=U(E,void 0,"message"),O=U(O,x.publicKey,"publicKey"),g!==void 0&&ee(g,"zip215"),n&&(E=n(E));let m=b/2,S=v.subarray(0,m),k=Ie(v.subarray(m,b)),D,C,T;try{D=r.fromBytes(O,g),C=r.fromBytes(S,g),T=s.multiplyUnsafe(k)}catch{return!1}if(!g&&D.isSmallOrder())return!1;let P=d(L,C.toBytes(),D.toBytes(),E);return C.add(D.multiplyUnsafe(P)).subtract(T).clearCofactor().is0()}let I=o.BYTES,x={secretKey:I,publicKey:I,signature:2*I,seed:I};function A(v=a(x.seed)){return U(v,x.seed,"seed")}function R(v){return ve(v)&&v.length===i.BYTES}function M(v,E){try{return!!r.fromBytes(v,E)}catch{return!1}}let F={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:R,isValidPublicKey:M,toMontgomery(v){let{y:E}=r.fromBytes(v),O=x.publicKey,H=O===32;if(!H&&O!==57)throw new Error("only defined for 25519 and 448");let L=H?o.div(ht+E,ht-E):o.div(E-ht,E+ht);return o.toBytes(L)},toMontgomerySecret(v){let E=x.secretKey;U(v,E);let O=t(v.subarray(0,E));return c(O).subarray(0,E)}};return Object.freeze({keygen:Bn(A,p),getPublicKey:p,sign:_,verify:y,utils:F,Point:r,lengths:x})}var mh=BigInt(1),Nc=BigInt(2);var gh=BigInt(5),bh=BigInt(8),Fo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),yh={p:Fo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:bh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function wh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),s=BigInt(80),o=Fo,a=r*r%o*r%o,c=Q(a,Nc,o)*a%o,l=Q(c,mh,o)*r%o,u=Q(l,gh,o)*l%o,h=Q(u,t,o)*u%o,f=Q(h,e,o)*h%o,p=Q(f,n,o)*f%o,d=Q(p,s,o)*p%o,_=Q(d,s,o)*p%o,w=Q(_,t,o)*u%o;return{pow_p_5_8:Q(w,Nc,o)*r%o,b2:a}}function xh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Uc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Eh(r,t){let e=Fo,n=it(t*t*t,e),s=it(n*n*t,e),o=wh(r*s).pow_p_5_8,i=it(r*n*o,e),a=it(t*i*i,e),c=i,l=it(i*Uc,e),u=a===r,h=a===it(-r,e),f=a===it(-r*Uc,e);return u&&(i=c),(h||f)&&(i=l),Ac(i,e)&&(i=it(-i,e)),{isValid:u||h,value:i}}var vh=Rc(yh,{uvRatio:Eh});function _h(r){return Oc(vh,dc,Object.assign({adjustScalarBytes:xh},r))}var Mc=_h({});var Pn=32;var Ho,Sh=(async()=>{try{return await wn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Ih(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await wn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await wn.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Ah(r,t,e){return Mc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Fc(r,t,e){return Ho==null&&(Ho=await Sh),Ho?Ih(r,t,e):Ah(r,t,e)}function Rn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var On=class{type="Ed25519";raw;constructor(t){this.raw=$o(t,Pn)}toMultihash(){return Tt.digest(Qe(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return at.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let s=Fc(this.raw,e,t);return Rn(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function $c(r){return r=$o(r,Pn),new On(r)}function $o(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new kt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Th=Math.pow(2,7),Dh=Math.pow(2,14),Lh=Math.pow(2,21),qo=Math.pow(2,28),Ko=Math.pow(2,35),zo=Math.pow(2,42),Vo=Math.pow(2,49),K=128,xt=127;function J(r){if(r<Th)return 1;if(r<Dh)return 2;if(r<Lh)return 3;if(r<qo)return 4;if(r<Ko)return 5;if(r<zo)return 6;if(r<Vo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ir(r,t,e=0){switch(J(r)){case 8:t[e++]=r&255|K,r/=128;case 7:t[e++]=r&255|K,r/=128;case 6:t[e++]=r&255|K,r/=128;case 5:t[e++]=r&255|K,r/=128;case 4:t[e++]=r&255|K,r>>>=7;case 3:t[e++]=r&255|K,r>>>=7;case 2:t[e++]=r&255|K,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Ch(r,t,e=0){switch(J(r)){case 8:t.set(e++,r&255|K),r/=128;case 7:t.set(e++,r&255|K),r/=128;case 6:t.set(e++,r&255|K),r/=128;case 5:t.set(e++,r&255|K),r/=128;case 4:t.set(e++,r&255|K),r>>>=7;case 3:t.set(e++,r&255|K),r>>>=7;case 2:t.set(e++,r&255|K),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Wo(r,t){let e=r[t],n=0;if(n+=e&xt,e<K||(e=r[t+1],n+=(e&xt)<<7,e<K)||(e=r[t+2],n+=(e&xt)<<14,e<K)||(e=r[t+3],n+=(e&xt)<<21,e<K)||(e=r[t+4],n+=(e&xt)*qo,e<K)||(e=r[t+5],n+=(e&xt)*Ko,e<K)||(e=r[t+6],n+=(e&xt)*zo,e<K)||(e=r[t+7],n+=(e&xt)*Vo,e<K))return n;throw new RangeError("Could not decode varint")}function Bh(r,t){let e=r.get(t),n=0;if(n+=e&xt,e<K||(e=r.get(t+1),n+=(e&xt)<<7,e<K)||(e=r.get(t+2),n+=(e&xt)<<14,e<K)||(e=r.get(t+3),n+=(e&xt)<<21,e<K)||(e=r.get(t+4),n+=(e&xt)*qo,e<K)||(e=r.get(t+5),n+=(e&xt)*Ko,e<K)||(e=r.get(t+6),n+=(e&xt)*zo,e<K)||(e=r.get(t+7),n+=(e&xt)*Vo,e<K))return n;throw new RangeError("Could not decode varint")}function Nn(r,t,e=0){return t==null&&(t=wt(J(r))),t instanceof Uint8Array?ir(r,t,e):Ch(r,t,e)}function De(r,t=0){return r instanceof Uint8Array?Wo(r,t):Bh(r,t)}var Zo=new Float32Array([-0]),ge=new Uint8Array(Zo.buffer);function qc(r,t,e){Zo[0]=r,t[e]=ge[0],t[e+1]=ge[1],t[e+2]=ge[2],t[e+3]=ge[3]}function Kc(r,t){return ge[0]=r[t],ge[1]=r[t+1],ge[2]=r[t+2],ge[3]=r[t+3],Zo[0]}var Yo=new Float64Array([-0]),Et=new Uint8Array(Yo.buffer);function zc(r,t,e){Yo[0]=r,t[e]=Et[0],t[e+1]=Et[1],t[e+2]=Et[2],t[e+3]=Et[3],t[e+4]=Et[4],t[e+5]=Et[5],t[e+6]=Et[6],t[e+7]=Et[7]}function Vc(r,t){return Et[0]=r[t],Et[1]=r[t+1],Et[2]=r[t+2],Et[3]=r[t+3],Et[4]=r[t+4],Et[5]=r[t+5],Et[6]=r[t+6],Et[7]=r[t+7],Yo[0]}var Ph=BigInt(Number.MAX_SAFE_INTEGER),Rh=BigInt(Number.MIN_SAFE_INTEGER),Dt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Le;if(t<Ph&&t>Rh)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>Wc&&(s=0n,++n>Wc&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return Le;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):Le}},Le=new Dt(0,0);Le.toBigInt=function(){return 0n};Le.zzEncode=Le.zzDecode=function(){return this};Le.length=function(){return 1};var Wc=4294967296n;function Gc(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Zc(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function jo(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function Rt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Un(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Xo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Rt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Rt(this,4);return Un(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Rt(this,4);return Un(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Rt(this,4);let t=Kc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Rt(this,4);let t=Vc(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Rt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Zc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Rt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Rt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Dt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Rt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Rt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Rt(this,8);let t=Un(this.buf,this.pos+=4),e=Un(this.buf,this.pos+=4);return new Dt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Wo(this.buf,this.pos);return this.pos+=J(t),t}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 Fr(r){return new Xo(r instanceof Uint8Array?r:r.subarray())}function Kt(r,t,e){let n=Fr(r);return t.decode(n,void 0,e)}function Qo(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return wt(i);s+i>t&&(n=wt(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Ce=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Jo(){}var ei=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Oh=Qo();function Nh(r){return globalThis.Buffer!=null?wt(r):Oh(r)}var $r=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ce(Jo,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ce(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ri((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Mn,10,Dt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Dt.fromBigInt(t);return this._push(Mn,e.length(),e)}uint64Number(t){return this._push(ir,J(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Dt.fromBigInt(t).zzEncode();return this._push(Mn,e.length(),e)}sint64Number(t){let e=Dt.fromNumber(t).zzEncode();return this._push(Mn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ti,1,t?1:0)}fixed32(t){return this._push(Hr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Dt.fromBigInt(t);return this._push(Hr,4,e.lo)._push(Hr,4,e.hi)}fixed64Number(t){let e=Dt.fromNumber(t);return this._push(Hr,4,e.lo)._push(Hr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(qc,4,t)}double(t){return this._push(zc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ti,1,0):this.uint32(e)._push(Mh,e,t)}string(t){let e=Gc(t);return e!==0?this.uint32(e)._push(jo,e,t):this._push(ti,1,0)}fork(){return this.states=new ei(this),this.head=this.tail=new Ce(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 Ce(Jo,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Nh(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ti(r,t,e){t[e]=r&255}function Uh(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ri=class extends Ce{next;constructor(t,e){super(Uh,t,e),this.next=void 0}};function Mn(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Hr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Mh(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&($r.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Fh,t,r),this},$r.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Hh,t,r),this});function Fh(r,t,e){t.set(r,e)}function Hh(r,t,e){r.length<40?jo(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Z(r),e)}function ni(){return new $r}function zt(r,t){let e=ni();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*Vt(r,t,e){let n=Fr(r);yield*t.stream(n,void 0,"$",e)}var Fn={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Hn(r,t,e,n,s){return{name:r,type:t,encode:e,decode:n,stream:s}}function ar(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},s=function*(i){let a=i.int32();yield t(a)};return Hn("enum",Fn.VARINT,e,n,s)}function Wt(r,t,e){return Hn("message",Fn.LENGTH_DELIMITED,r,t,e)}var re=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var St;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(St||(St={}));var si;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(si||(si={}));(function(r){r.codec=()=>ar(si)})(St||(St={}));var qr;(function(r){let t;r.codec=()=>(t==null&&(t=Wt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),St.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return zt(o,r.codec())}r.encode=e;function n(o,i){return Kt(o,r.codec(),i)}r.decode=n;function s(o,i){return Vt(o,r.codec(),i)}r.stream=s})(qr||(qr={}));var oi;(function(r){let t;r.codec=()=>(t==null&&(t=Wt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),St.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return zt(o,r.codec())}r.encode=e;function n(o,i){return Kt(o,r.codec(),i)}r.decode=n;function s(o,i){return Vt(o,r.codec(),i)}r.stream=s})(oi||(oi={}));var $n=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(In(t),U(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(e.length>n?t.create().update(e).digest():e);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Xt(s)}update(t){return Je(this),this.iHash.update(t),this}digestInto(t){Je(this),U(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return t=t,t.finished=s,t.destroyed=o,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ii=(r,t,e)=>new $n(r,t).update(e).digest();ii.create=(r,t)=>new $n(r,t);var jc=(r,t)=>(r+(r>=0?t:-t)/Xc)/t;function qh(r,t,e){let[[n,s],[o,i]]=t,a=jc(i*r,e),c=jc(-s*r,e),l=r-a*n-c*o,u=-a*s-c*i,h=l<ne,f=u<ne;h&&(l=-l),f&&(u=-u);let p=Nr(Math.ceil(Do(e)/2))+cr;if(l<ne||l>=p||u<ne||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:f,k2:u}}function ci(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ai(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return ee(e.lowS,"lowS"),ee(e.prehash,"prehash"),e.format!==void 0&&ci(e.format),e}var li=class extends Error{constructor(t=""){super(t)}},be={Err:li,_tlv:{encode:(r,t)=>{let{Err:e}=be;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,s=Rr(n);if(s.length/2&128)throw new e("tlv.encode: long form length too big");let o=n>127?Rr(s.length/2|128):"";return Rr(r)+o+s+t},decode(r,t){let{Err:e}=be,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let s=t[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=be;if(r<ne)throw new t("integer: negative integers are not allowed");let e=Rr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=be;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return er(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=be,s=U(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=be,n=t.encode(2,e.encode(r.r)),s=t.encode(2,e.encode(r.s)),o=n+s;return t.encode(48,o)}},ne=BigInt(0),cr=BigInt(1),Xc=BigInt(2),qn=BigInt(3),Kh=BigInt(4);function Qc(r,t={}){let e=Cn("weierstrass",r,t),{Fp:n,Fn:s}=e,o=e.CURVE,{h:i,n:a}=o;pe(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=tl(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(L,g,b){let{x:m,y:S}=g.toAffine(),k=n.toBytes(m);if(ee(b,"isCompressed"),b){u();let D=!n.isOdd(S);return It(Jc(D),k)}else return It(Uint8Array.of(4),k,n.toBytes(S))}function f(L){U(L,void 0,"Point");let{publicKey:g,publicKeyUncompressed:b}=l,m=L.length,S=L[0],k=L.subarray(1);if(m===g&&(S===2||S===3)){let D=n.fromBytes(k);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");let C=_(D),T;try{T=n.sqrt(C)}catch(rt){let X=rt instanceof Error?": "+rt.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}u();let P=n.isOdd(T);return(S&1)===1!==P&&(T=n.neg(T)),{x:D,y:T}}else if(m===b&&S===4){let D=n.BYTES,C=n.fromBytes(k.subarray(0,D)),T=n.fromBytes(k.subarray(D,D*2));if(!w(C,T))throw new Error("bad point: is not on curve");return{x:C,y:T}}else throw new Error(`bad point: got length ${m}, expected compressed=${g} or uncompressed=${b}`)}let p=t.toBytes||h,d=t.fromBytes||f;function _(L){let g=n.sqr(L),b=n.mul(g,L);return n.add(n.add(b,n.mul(L,o.a)),o.b)}function w(L,g){let b=n.sqr(g),m=_(L);return n.eql(b,m)}if(!w(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(o.a,qn),Kh),I=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(y,I)))throw new Error("bad curve params: a or b");function x(L,g,b=!1){if(!n.isValid(g)||b&&n.is0(g))throw new Error(`bad point coordinate ${L}`);return g}function A(L){if(!(L instanceof E))throw new Error("Weierstrass Point expected")}function R(L){if(!c||!c.basises)throw new Error("no endo");return qh(L,c.basises,s.ORDER)}let M=rr((L,g)=>{let{X:b,Y:m,Z:S}=L;if(n.eql(S,n.ONE))return{x:b,y:m};let k=L.is0();g==null&&(g=k?n.ONE:n.inv(S));let D=n.mul(b,g),C=n.mul(m,g),T=n.mul(S,g);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(T,n.ONE))throw new Error("invZ was invalid");return{x:D,y:C}}),F=rr(L=>{if(L.is0()){if(t.allowInfinityPoint&&!n.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:g,y:b}=L.toAffine();if(!n.isValid(g)||!n.isValid(b))throw new Error("bad point: x or y not field elements");if(!w(g,b))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(L,g,b,m,S){return b=new E(n.mul(b.X,L),b.Y,b.Z),g=Mr(m,g),b=Mr(S,b),g.add(b)}class E{static BASE=new E(o.Gx,o.Gy,n.ONE);static ZERO=new E(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(g,b,m){this.X=x("x",g),this.Y=x("y",b,!0),this.Z=x("z",m),Object.freeze(this)}static CURVE(){return o}static fromAffine(g){let{x:b,y:m}=g||{};if(!g||!n.isValid(b)||!n.isValid(m))throw new Error("invalid affine point");if(g instanceof E)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(m)?E.ZERO:new E(b,m,n.ONE)}static fromBytes(g){let b=E.fromAffine(d(U(g,void 0,"point")));return b.assertValidity(),b}static fromHex(g){return E.fromBytes(Jt(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){return H.createCache(this,g),b||this.multiply(qn),this}assertValidity(){F(this)}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){A(g);let{X:b,Y:m,Z:S}=this,{X:k,Y:D,Z:C}=g,T=n.eql(n.mul(b,C),n.mul(k,S)),P=n.eql(n.mul(m,C),n.mul(D,S));return T&&P}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b}=o,m=n.mul(b,qn),{X:S,Y:k,Z:D}=this,C=n.ZERO,T=n.ZERO,P=n.ZERO,N=n.mul(S,S),rt=n.mul(k,k),X=n.mul(D,D),q=n.mul(S,k);return q=n.add(q,q),P=n.mul(S,D),P=n.add(P,P),C=n.mul(g,P),T=n.mul(m,X),T=n.add(C,T),C=n.sub(rt,T),T=n.add(rt,T),T=n.mul(C,T),C=n.mul(q,C),P=n.mul(m,P),X=n.mul(g,X),q=n.sub(N,X),q=n.mul(g,q),q=n.add(q,P),P=n.add(N,N),N=n.add(P,N),N=n.add(N,X),N=n.mul(N,q),T=n.add(T,N),X=n.mul(k,D),X=n.add(X,X),N=n.mul(X,q),C=n.sub(C,N),P=n.mul(X,rt),P=n.add(P,P),P=n.add(P,P),new E(C,T,P)}add(g){A(g);let{X:b,Y:m,Z:S}=this,{X:k,Y:D,Z:C}=g,T=n.ZERO,P=n.ZERO,N=n.ZERO,rt=o.a,X=n.mul(o.b,qn),q=n.mul(b,k),nt=n.mul(m,D),pt=n.mul(S,C),Ft=n.add(b,m),st=n.add(k,D);Ft=n.mul(Ft,st),st=n.add(q,nt),Ft=n.sub(Ft,st),st=n.add(b,S);let bt=n.add(k,C);return st=n.mul(st,bt),bt=n.add(q,pt),st=n.sub(st,bt),bt=n.add(m,S),T=n.add(D,C),bt=n.mul(bt,T),T=n.add(nt,pt),bt=n.sub(bt,T),N=n.mul(rt,st),T=n.mul(X,pt),N=n.add(T,N),T=n.sub(nt,N),N=n.add(nt,N),P=n.mul(T,N),nt=n.add(q,q),nt=n.add(nt,q),pt=n.mul(rt,pt),st=n.mul(X,st),nt=n.add(nt,pt),pt=n.sub(q,pt),pt=n.mul(rt,pt),st=n.add(st,pt),q=n.mul(nt,st),P=n.add(P,q),q=n.mul(bt,st),T=n.mul(Ft,T),T=n.sub(T,q),q=n.mul(Ft,nt),N=n.mul(bt,N),N=n.add(N,q),new E(T,P,N)}subtract(g){return this.add(g.negate())}is0(){return this.equals(E.ZERO)}multiply(g){let{endo:b}=t;if(!s.isValidNot0(g))throw new Error("invalid scalar: out of range");let m,S,k=D=>H.cached(this,D,C=>Te(E,C));if(b){let{k1neg:D,k1:C,k2neg:T,k2:P}=R(g),{p:N,f:rt}=k(C),{p:X,f:q}=k(P);S=rt.add(q),m=v(b.beta,N,X,D,T)}else{let{p:D,f:C}=k(g);m=D,S=C}return Te(E,[m,S])[0]}multiplyUnsafe(g){let{endo:b}=t,m=this;if(!s.isValid(g))throw new Error("invalid scalar: out of range");if(g===ne||m.is0())return E.ZERO;if(g===cr)return m;if(H.hasCache(this))return this.multiply(g);if(b){let{k1neg:S,k1:k,k2neg:D,k2:C}=R(g),{p1:T,p2:P}=Pc(E,m,k,C);return v(b.beta,T,P,S,D)}else return H.unsafe(m,g)}toAffine(g){return M(this,g)}isTorsionFree(){let{isTorsionFree:g}=t;return i===cr?!0:g?g(E,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=t;return i===cr?this:g?g(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return ee(g,"isCompressed"),this.assertValidity(),p(E,this,g)}toHex(g=!0){return Qt(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let O=s.BITS,H=new or(E,t.endo?Math.ceil(O/2):O);return E.BASE.precompute(8),E}function Jc(r){return Uint8Array.of(r?2:3)}function tl(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function zh(r,t={}){let{Fn:e}=r,n=t.randomBytes||tr,s=Object.assign(tl(r.Fp,e),{seed:Po(e.ORDER)});function o(p){try{let d=e.fromBytes(p);return e.isValidNot0(d)}catch{return!1}}function i(p,d){let{publicKey:_,publicKeyUncompressed:w}=s;try{let y=p.length;return d===!0&&y!==_||d===!1&&y!==w?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(s.seed)){return Ro(U(p,s.seed,"seed"),e.ORDER)}function c(p,d=!0){return r.BASE.multiply(e.fromBytes(p)).toBytes(d)}function l(p){let{secretKey:d,publicKey:_,publicKeyUncompressed:w}=s;if(!ve(p)||"_lengths"in e&&e._lengths||d===_)return;let y=U(p,void 0,"key").length;return y===_||y===w}function u(p,d,_=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");let w=e.fromBytes(p);return r.fromBytes(d).multiply(w).toBytes(_)}let h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},f=Bn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:h,lengths:s})}function el(r,t,e={}){In(t),pe(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let n=e.randomBytes||tr,s=e.hmac||((b,m)=>ii(t,b,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p}=zh(r,e),d={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},_=a*Xc<o.ORDER;function w(b){let m=a>>cr;return b>m}function y(b,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${b}: out of range 1..Point.Fn.ORDER`);return m}function I(){if(_)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(b,m){ci(m);let S=p.signature,k=m==="compact"?S:m==="recovered"?S+1:void 0;return U(b,k)}class A{r;s;recovery;constructor(m,S,k){if(this.r=y("r",m),this.s=y("s",S),k!=null){if(I(),![0,1,2,3].includes(k))throw new Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(m,S=d.format){x(m,S);let k;if(S==="der"){let{r:P,s:N}=be.toSig(U(m));return new A(P,N)}S==="recovered"&&(k=m[0],S="compact",m=m.subarray(1));let D=p.signature/2,C=m.subarray(0,D),T=m.subarray(D,D*2);return new A(i.fromBytes(C),i.fromBytes(T),k)}static fromHex(m,S){return this.fromBytes(Jt(m),S)}assertRecovery(){let{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new A(this.r,this.s,m)}recoverPublicKey(m){let{r:S,s:k}=this,D=this.assertRecovery(),C=D===2||D===3?S+a:S;if(!o.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let T=o.toBytes(C),P=r.fromBytes(It(Jc((D&1)===0),T)),N=i.inv(C),rt=M(U(m,void 0,"msgHash")),X=i.create(-rt*N),q=i.create(k*N),nt=r.BASE.multiplyUnsafe(X).add(P.multiplyUnsafe(q));if(nt.is0())throw new Error("invalid recovery: point at infinify");return nt.assertValidity(),nt}hasHighS(){return w(this.s)}toBytes(m=d.format){if(ci(m),m==="der")return Jt(be.hexFromSig(this));let{r:S,s:k}=this,D=i.toBytes(S),C=i.toBytes(k);return m==="recovered"?(I(),It(Uint8Array.of(this.assertRecovery()),D,C)):It(D,C)}toHex(m){return Qt(this.toBytes(m))}}let R=e.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");let S=er(m),k=m.length*8-c;return k>0?S>>BigInt(k):S},M=e.bits2int_modN||function(m){return i.create(R(m))},F=Nr(c);function v(b){return Or("num < 2^"+c,b,ne,F),i.toBytes(b)}function E(b,m){return U(b,void 0,"message"),m?U(t(b),void 0,"prehashed message"):b}function O(b,m,S){let{lowS:k,prehash:D,extraEntropy:C}=ai(S,d);b=E(b,D);let T=M(b),P=i.fromBytes(m);if(!i.isValidNot0(P))throw new Error("invalid private key");let N=[v(P),v(T)];if(C!=null&&C!==!1){let nt=C===!0?n(p.secretKey):C;N.push(U(nt,void 0,"extraEntropy"))}let rt=It(...N),X=T;function q(nt){let pt=R(nt);if(!i.isValidNot0(pt))return;let Ft=i.inv(pt),st=r.BASE.multiply(pt).toAffine(),bt=i.create(st.x);if(bt===ne)return;let cn=i.create(Ft*i.create(X+bt*P));if(cn===ne)return;let ga=(st.x===bt?0:2)|Number(st.y&cr),ba=cn;return k&&w(cn)&&(ba=i.neg(cn),ga^=1),new A(bt,ba,_?void 0:ga)}return{seed:rt,k2sig:q}}function H(b,m,S={}){let{seed:k,k2sig:D}=O(b,m,S);return gc(t.outputLen,i.BYTES,s)(k,D).toBytes(S.format)}function L(b,m,S,k={}){let{lowS:D,prehash:C,format:T}=ai(k,d);if(S=U(S,void 0,"publicKey"),m=E(m,C),!ve(b)){let P=b instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}x(b,T);try{let P=A.fromBytes(b,T),N=r.fromBytes(S);if(D&&P.hasHighS())return!1;let{r:rt,s:X}=P,q=M(m),nt=i.inv(X),pt=i.create(q*nt),Ft=i.create(rt*nt),st=r.BASE.multiplyUnsafe(pt).add(N.multiplyUnsafe(Ft));return st.is0()?!1:i.create(st.x)===rt}catch{return!1}}function g(b,m,S={}){let{prehash:k}=ai(S,d);return m=E(m,k),A.fromBytes(b,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p,Point:r,sign:H,verify:L,recoverPublicKey:g,Signature:A,hash:t})}var fi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Vh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var rl=BigInt(2);function Wh(r){let t=fi.p,e=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,h=Q(u,e,t)*u%t,f=Q(h,e,t)*u%t,p=Q(f,rl,t)*l%t,d=Q(p,s,t)*p%t,_=Q(d,o,t)*d%t,w=Q(_,a,t)*_%t,y=Q(w,c,t)*w%t,I=Q(y,a,t)*_%t,x=Q(I,e,t)*u%t,A=Q(x,i,t)*d%t,R=Q(A,n,t)*l%t,M=Q(R,rl,t);if(!ui.eql(ui.sqr(M),r))throw new Error("Cannot find square root");return M}var ui=nr(fi.p,{sqrt:Wh}),Gh=Qc(fi,{Fp:ui,endo:Vh}),lr=el(Gh,hc);function nl(r,t,e,n){let s=ue.digest(e instanceof Uint8Array?e:e.subarray());if(Rn(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),lr.verify(t,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new _r(String(o))});try{return n?.signal?.throwIfAborted(),lr.verify(t,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new _r(String(o))}}var Kn=class{type="secp256k1";raw;_key;constructor(t){this._key=ol(t),this.raw=sl(this._key)}toMultihash(){return Tt.digest(Qe(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return at.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}verify(t,e,n){return nl(this._key,e,t,n)}};function il(r){return new Kn(r)}function sl(r){return lr.Point.fromBytes(r).toBytes()}function ol(r){try{return lr.Point.fromBytes(r),r}catch(t){throw new fn(String(t))}}function al(r){let{Type:t,Data:e}=qr.decode(r.digest),n=e??new Uint8Array;switch(t){case St.Ed25519:return $c(n);case St.secp256k1:return il(n);case St.ECDSA:return Ya(n);default:throw new vr}}function Qe(r){return qr.encode({Type:St[r.type],Data:r.raw})}var hi={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},cl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ll=new globalThis.TextEncoder;function Zh(r,t){let e=hi[t],n=cl[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function Yh(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=hi[t],s=cl[t],o=r;for(;o.length>0;){let i=ll.encodeInto(o,e);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function di(r,{size:t=32,utf8Buffer:e}={}){if(!hi[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Yh(r,t,e);r=ll.encode(r)}return Zh(r,t)}var Kr={hash:r=>Number(di(r,{size:32})),hashV:(r,t)=>jh(Kr.hash(r,t))};function jh(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),Z(t,"base16")}var pi=64,Ot=class{fp;h;seed;constructor(t,e,n,s=2){if(s>pi)throw new TypeError("Invalid Fingerprint Size");let o=e.hashV(t,n),i=yt(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?ct(this.fp,t.fp):!1}};function Be(r,t){return Math.floor(Math.random()*(t-r))+r}var Pe=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");let e=Be(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Xh=500,zr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Kr,this.seed=t.seed??Be(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=Z(t));let e=new Ot(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Pe(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Pe(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[Be(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Pe(this.bucketSize));for(let a=0;a<Xh;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Pe(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=Z(t));let e=new Ot(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let o=(n^e.hash())%this.filterSize;return this.buckets[o]?.has(e)??!1}remove(t){typeof t=="string"&&(t=Z(t));let e=new Ot(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let o=(n^e.hash())%this.filterSize,i=this.buckets[o]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Qh={1:.5,2:.84,4:.95,8:.98};function Jh(r=.001){return r>.002?2:r>1e-5?4:8}function ul(r,t=.001){let e=Jh(t),n=Qh[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),pi);return{filterSize:s,bucketSize:e,fingerprintSize:o}}var zn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Kr,this.seed=t.seed??Be(0,Math.pow(2,10)),this.filterSeries=[new zr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=Z(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new zr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=Z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=Z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Vn(r,t=.001,e){return new zn({...ul(r,t),...e??{}})}function Wn(r){let t=r.getComponents(),e={},n=0;if(t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n].name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null)throw new kt(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e}var Gn=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=t,o+=u,o>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return e.set(o.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var td=45,ed=15,Zn=new Gn;function fl(r){if(!(r.length>ed))return Zn.new(r).parseWith(()=>Zn.readIPv4Addr())}function hl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>td))return Zn.new(r).parseWith(()=>Zn.readIPv6Addr())}function ur(r){return!!fl(r)}function Yn(r){return!!hl(r)}var gl=wa(ml(),1),cd=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],ld=cd.map(r=>new gl.Netmask(r));function Ei(r){for(let t of ld)if(t.contains(r))return!0;return!1}function ud(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function fd(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Ei(s)}function hd(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function dd(r){let t=r.split(":"),e=t[t.length-1];return Ei(e)}function pd(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function bl(r){if(ur(r))return Ei(r);if(ud(r))return fd(r);if(hd(r))return dd(r);if(Yn(r))return pd(r)}function yl(r){try{let t=Wn(r);switch(t.type){case"ip4":case"ip6":return bl(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function Nt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Xn=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},pr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Xn(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Xn(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var vi=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Qn(r={}){return md(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function md(r,t){t=t??{};let e=t.onEnd,n=new pr,s,o,i,a=Nt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,y)=>{o=I=>{o=null,n.push(I);try{w(r(n))}catch(x){y(x)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Nt()})}},l=w=>o!=null?o(w):(n.push(w),s),u=w=>(n=new pr,o!=null?o({error:w}):(n.push({error:w}),s)),h=w=>{if(i)return s;if(t?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},f=w=>i?s:(i=!0,w!=null?u(w):l({done:!0})),p=()=>(n=new pr,f(),{done:!0}),d=w=>(f(w),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:h,end:f,get readableLength(){return n.size},onEmpty:async w=>{let y=w?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let I,x;y!=null&&(I=new Promise((A,R)=>{x=()=>{R(new vi)},y.addEventListener("abort",x)}));try{await Promise.race([a.promise,I])}finally{x!=null&&y!=null&&y?.removeEventListener("abort",x)}}},e==null)return s;let _=s;return s={[Symbol.asyncIterator](){return this},next(){return _.next()},throw(w){return _.throw(w),e!=null&&(e(w),e=void 0),{done:!0}},return(){return _.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(w){return _.end(w),e!=null&&(e(w),e=void 0),s},get readableLength(){return _.readableLength},onEmpty:w=>_.onEmpty(w)},s}var _i=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},wl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Si(r,t){let{milliseconds:e,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=t,a,c,u=new Promise((h,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){f(wl(i));return}if(i&&(c=()=>{f(wl(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,f),e===Number.POSITIVE_INFINITY)return;let p=new _i;a=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?h():s instanceof Error?f(s):(p.message=s??`Promise timed out after ${e} milliseconds`,f(p))},e)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var gd=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function bd(r,t,e){let n,s=new Promise((o,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=gd(r),h=async(...p)=>{let d=e.multiArgs?p:p[0];if(e.filter)try{if(!await e.filter(d))return}catch(_){n(),i(_);return}c.push(d),e.count===c.length&&(n(),o(c))},f=(...p)=>{n(),i(e.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,h);for(let p of e.rejectionEvents)a.includes(p)||u(p,f)};for(let p of a)l(p,h);for(let p of e.rejectionEvents)a.includes(p)||l(p,f);e.signal&&e.signal.addEventListener("abort",()=>{f(e.signal.reason)},{once:!0}),e.resolveImmediately&&o(c)});if(s.cancel=n,typeof e.timeout=="number"){let o=Si(s,{milliseconds:e.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Jn(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=bd(r,t,e),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Ii(r,t){let e,n=function(){let s=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(s,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var ts=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function yd(r){return r.reason}async function Vr(r,t,e){if(t==null)return r;let n=e?.translateError??yd;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(t))},t.addEventListener("abort",s)})])}finally{s!=null&&t.removeEventListener("abort",s)}}var es=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Nt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Bt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function wd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var rs=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=wd(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Bt),this.cleanup())}async join(t={}){let e=new es(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Vr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var mr=class extends Ht{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Ii(this.emitEmpty.bind(this),1),this.emitIdle=Ii(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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ts;let n=new rs(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Bt)}),this.clear()}async onEmpty(t){this.size!==0&&await Jn(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Jn(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Jn(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Qn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Bt("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var gt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},se=class extends Error{static name="ValidationError";name="ValidationError"},ns=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ss=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function ki(r){return t=>W(t,r)}function Ti(r){return t=>Z(t,r)}function gr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Oe(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function xl(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Z(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Oe(n);return Ct([e,s],e.length+s.length)}function El(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=le.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Oe(n);return Ct([e,s],e.length+s.length)}function Di(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=W(t,"base32"),s=gr(e);return`${n}:${s}`}var Li=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let s=parseInt(e,10);if(isNaN(s)||s<0||s>255)throw new gt("Invalid byte value in IP address");t[n]=s}),t},vl=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=ur(e[n]),i;o&&(i=Li(e[n]),e[n]=W(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,W(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let o=parseInt(e[n],16);if(isNaN(o)||o<0||o>65535)throw new gt("Invalid byte value in IP address");s[t++]=o>>8&255,s[t++]=o&255}return s},_l=function(r){if(r.byteLength!==4)throw new gt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Sl=function(r){if(r.byteLength!==16)throw new gt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${e}"`)}};function Il(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${r}"`)}}var Ai=Object.values(Tr).map(r=>r.decoder),xd=(function(){let r=Ai[0].or(Ai[1]);return Ai.slice(2).forEach(t=>r=r.or(t)),r})();function Al(r){return xd.decode(r)}function kl(r){return t=>r.encoder.encode(t)}function Ed(r){if(parseInt(r).toString()!==r)throw new se("Value must be an integer")}function vd(r){if(r<0)throw new se("Value must be a positive integer, or zero")}function _d(r){return t=>{if(t>r)throw new se(`Value must be smaller than or equal to ${r}`)}}function Sd(...r){return t=>{for(let e of r)e(t)}}var Wr=Sd(Ed,vd,_d(65535));var dt=-1,Ci=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new ss(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},ie=new Ci,Fd=[{code:4,name:"ip4",size:32,valueToBytes:Li,bytesToValue:_l,validate:r=>{if(!ur(r))throw new se(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Oe,bytesToValue:gr,validate:Wr},{code:273,name:"udp",size:16,valueToBytes:Oe,bytesToValue:gr,validate:Wr},{code:33,name:"dccp",size:16,valueToBytes:Oe,bytesToValue:gr,validate:Wr},{code:41,name:"ip6",size:128,valueToBytes:vl,bytesToValue:Sl,stringToValue:Il,validate:r=>{if(!Yn(r))throw new se(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:dt},{code:43,name:"ipcidr",size:8,bytesToValue:ki("base10"),valueToBytes:Ti("base10")},{code:53,name:"dns",size:dt},{code:54,name:"dns4",size:dt},{code:55,name:"dns6",size:dt},{code:56,name:"dnsaddr",size:dt},{code:132,name:"sctp",size:16,valueToBytes:Oe,bytesToValue:gr,validate:Wr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:dt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:dt,bytesToValue:ki("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ti("base58btc")(r):et.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Di,valueToBytes:xl},{code:445,name:"onion3",size:296,bytesToValue:Di,valueToBytes:El},{code:446,name:"garlic64",size:dt},{code:447,name:"garlic32",size:dt},{code:448,name:"tls"},{code:449,name:"sni",size:dt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:dt,bytesToValue:kl(no),valueToBytes:Al},{code:480,name:"http"},{code:481,name:"http-path",size:dt,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:dt}];Fd.forEach(r=>{ie.addProtocol(r)});function Tl(r){let t=[],e=0;for(;e<r.length;){let n=De(r,e),s=ie.getProtocol(n),o=J(n),i=Hd(s,r,e+o),a=0;i>0&&s.size===dt&&(a=J(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??W(h)}t.push(l),e+=c}return t}function Dl(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let s=ie.getProtocol(n.code),o=J(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,s.size===dt&&(c=J(a)));let l=new Uint8Array(o+c+a),u=0;ir(n.code,l,u),u+=o,i!=null&&(s.size===dt&&(ir(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return Ct(e,t)}function Ll(r){if(r.charAt(0)!=="/")throw new gt('String multiaddr must start with "/"');let t=[],e="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(e==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ie.getProtocol(s);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",s="",e="protocol";continue}else if(a)throw new gt(`Component ${s} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new gt(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",s="",e="protocol"}}}if(s!==""&&n!=="")throw new gt("Incomplete multiaddr");return t}function Cl(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=ie.getProtocol(t.code);if(e==null)throw new gt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function Hd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:De(t,e)}var $d=Symbol.for("nodejs.util.inspect.custom"),Ki=Symbol.for("@multiformats/multiaddr");function qd(r){if(r==null&&(r="/"),Bl(r))return r.getComponents();if(r instanceof Uint8Array)return Tl(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Ll(r);if(Array.isArray(r))return r;throw new gt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ls=class r{[Ki]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=qd(t),e.validate!==!1&&Kd(this)}get bytes(){return this.#r==null&&(this.#r=Dl(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Cl(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new ns(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return ct(this.bytes,t.bytes)}[$d](){return`Multiaddr(${this.toString()})`}};function Kd(r){r.getComponents().forEach(t=>{let e=ie.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function Bl(r){return!!r?.[Ki]}function us(r){return new ls(r)}var fs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},wr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},hs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Qr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ds(r){return r[Symbol.asyncIterator]!=null}function Pl(r,t){if(r.byteLength>t)throw new wr("Message length too long")}var ms=r=>{let t=J(r),e=wt(t);return Nn(r,e),ms.bytes=t,e};ms.bytes=0;function gs(r,t){t=t??{};let e=t.lengthEncoder??ms,n=t?.maxDataLength??4194304;function*s(o){Pl(o,n);let i=e(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return ds(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}gs.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??ms,n=t?.maxDataLength??4194304;return Pl(r,n),new ut(e(r.byteLength),r)};var Ue;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ue||(Ue={}));var zi=r=>{let t=De(r);return zi.bytes=J(t),t};zi.bytes=0;function Jr(r,t){let e=new ut,n=Ue.LENGTH,s=-1,o=t?.lengthDecoder??zi,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Ue.LENGTH)try{if(s=o(e),s<0)throw new fs("Invalid message length");if(s>a)throw new wr("Message length too long");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=Ue.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new hs("Message length length too long");break}throw l}if(n===Ue.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=Ue.LENGTH}}}return ds(r)?(async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Qr("Unexpected end of input")})():(function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Qr("Unexpected end of input")})()}Jr.fromReader=(r,t)=>{let e=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}})();return Jr(n,{...t??{},onLength:o=>{e=o}})};var bs=class extends mr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Vi=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Rl(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Vi({name:t,metrics:e}):n=new Map,n}function Wd(r){return r[Symbol.asyncIterator]!=null}function Gd(r){if(Wd(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Wi=Gd;function Zd(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Ol=Zd;function Yd(r){return r[Symbol.asyncIterator]!=null}function jd(r,t){let e=0;if(Yd(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=Ol(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=t(s,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var Nl=jd;function Xd(r){return r[Symbol.asyncIterator]!=null}function Qd(r,t){return Xd(r)?(async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}})():(function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}})()}var Ul=Qd;var ys=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Me(r,t,e,n){let s=new ys(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Zi(e,"abort",h),Zi(r,t,l),Zi(r,o,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(p){c(),a(p);return}c(),i(f)},u=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.`))},h=()=>{c(),a(s)};Gi(e,"abort",h),Gi(r,t,l),Gi(r,o,u)})}function Gi(r,t,e){r!=null&&(Ml(r)?r.addEventListener(t,e):r.addListener(t,e))}function Zi(r,t,e){r!=null&&(Ml(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function Ml(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var tn="/ipfs/bitswap/1.2.0";var tt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(tt||(tt={}));var Yi;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Yi||(Yi={}));(function(r){r.codec=()=>ar(Yi)})(tt||(tt={}));var Fe;(function(r){let t;r.codec=()=>(t==null&&(t=Wt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.priority!=null&&o.priority!==0&&(i.uint32(16),i.int32(o.priority)),o.cancel!=null&&(i.uint32(24),i.bool(o.cancel)),o.wantType!=null&&(i.uint32(32),tt.codec().encode(o.wantType,i)),o.sendDontHave!=null&&(i.uint32(40),i.bool(o.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:yt(0),priority:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.priority=o.int32();break}case 3:{c.cancel=o.bool();break}case 4:{c.wantType=tt.codec().decode(o);break}case 5:{c.sendDontHave=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.priority`,value:o.int32()};break}case 3:{yield{field:`${a}.cancel`,value:o.bool()};break}case 4:{yield{field:`${a}.wantType`,value:tt.codec().decode(o)};break}case 5:{yield{field:`${a}.sendDontHave`,value:o.bool()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return zt(o,r.codec())}r.encode=e;function n(o,i){return Kt(o,r.codec(),i)}r.decode=n;function s(o,i){return Vt(o,r.codec(),i)}r.stream=s})(Fe||(Fe={}));var en;(function(r){let t;r.codec=()=>(t==null&&(t=Wt((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.entries!=null&&o.entries.length>0)for(let c of o.entries)i.uint32(10),Fe.codec().encode(c,i);o.full!=null&&(i.uint32(16),i.bool(o.full)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={entries:[]},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new re('Decode error - repeated field "entries" had too many elements');c.entries.push(Fe.codec().decode(o,o.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={entries:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let h=o.uint32();switch(h>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new re('Streaming decode error - repeated field "entries" had too many elements');for(let f of Fe.codec().stream(o,o.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...f,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:o.bool()};break}default:{o.skipType(h&7);break}}}})),t);function e(o){return zt(o,r.codec())}r.encode=e;function n(o,i){return Kt(o,r.codec(),i)}r.decode=n;function s(o,i){return Vt(o,r.codec(),i)}r.stream=s})(en||(en={}));var He;(function(r){let t;r.codec=()=>(t==null&&(t=Wt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.prefix!=null&&o.prefix.byteLength>0&&(i.uint32(10),i.bytes(o.prefix)),o.data!=null&&o.data.byteLength>0&&(i.uint32(18),i.bytes(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={prefix:yt(0),data:yt(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.prefix=o.bytes();break}case 2:{c.data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:o.bytes()};break}case 2:{yield{field:`${a}.data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return zt(o,r.codec())}r.encode=e;function n(o,i){return Kt(o,r.codec(),i)}r.decode=n;function s(o,i){return Vt(o,r.codec(),i)}r.stream=s})(He||(He={}));var Lt;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Lt||(Lt={}));var ws;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(ws||(ws={}));(function(r){r.codec=()=>ar(ws)})(Lt||(Lt={}));var $e;(function(r){let t;r.codec=()=>(t==null&&(t=Wt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.type!=null&&ws[o.type]!==0&&(i.uint32(16),Lt.codec().encode(o.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:yt(0),type:Lt.HaveBlock},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.type=Lt.codec().decode(o);break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.type`,value:Lt.codec().decode(o)};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return zt(o,r.codec())}r.encode=e;function n(o,i){return Kt(o,r.codec(),i)}r.decode=n;function s(o,i){return Vt(o,r.codec(),i)}r.stream=s})($e||($e={}));var qe;(function(r){let t;r.codec=()=>(t==null&&(t=Wt((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.wantlist!=null&&(i.uint32(10),en.codec().encode(o.wantlist,i)),o.blocks!=null&&o.blocks.length>0)for(let c of o.blocks)i.uint32(26),He.codec().encode(c,i);if(o.blockPresences!=null&&o.blockPresences.length>0)for(let c of o.blockPresences)i.uint32(34),$e.codec().encode(c,i);o.pendingBytes!=null&&o.pendingBytes!==0&&(i.uint32(40),i.int32(o.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.wantlist=en.codec().decode(o,o.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new re('Decode error - repeated field "blocks" had too many elements');c.blocks.push(He.codec().decode(o,o.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new re('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push($e.codec().decode(o,o.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=o.int32();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={blocks:0,blockPresences:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let h=o.uint32();switch(h>>>3){case 1:{yield*en.codec().stream(o,o.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new re('Streaming decode error - repeated field "blocks" had too many elements');for(let f of He.codec().stream(o,o.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...f,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new re('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of $e.codec().stream(o,o.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...f,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:o.int32()};break}default:{o.skipType(h&7);break}}}})),t);function e(o){return zt(o,r.codec())}r.encode=e;function n(o,i){return Kt(o,r.codec(),i)}r.decode=n;function s(o,i){return Vt(o,r.codec(),i)}r.stream=s})(qe||(qe={}));function Fl(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var xs=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var Jd=4193648,tp=Jd+16;function*Hl(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=qe.encode(l).byteLength,{added:h,hasMore:f,newSize:p}=ji(s,l.blocks,a,t,u,ep);a+=h,u=p;let d=f;({added:h,hasMore:f,newSize:p}=ji(n,l.blockPresences,i,t,u,rp)),i+=h,u=p;let _=f;if({added:h,hasMore:f,newSize:p}=ji(e,l.wantlist.entries,o,t,u,np),o+=h,u=p,c=!d&&!_&&!f,c||(l.wantlist.full=!1),yield qe.encode(l),c)break}}function ji(r,t,e,n,s,o){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=o(l);if(u>tp)throw new xs("Cannot send block as after encoding it is over the max message size");let h=s+u;if(h>n){a=!0;break}t.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function ep(r){return Xi(3,He.encode(r))}function rp(r){return Xi(4,$e.encode(r))}function np(r){return Xi(1,Fe.encode(r))}function Xi(r,t){let e=J(r),n=J(t.byteLength);return e+n+t.byteLength}var Es=class extends Ht{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[tn],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??1e4,this.messageSendTimeout=e.messageSendTimeout??1e4,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new bs({concurrency:e.messageSendConcurrency??50,metrics:t.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 t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t,e){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,e.remotePeer);let n=()=>{t.status==="open"?t.abort(new mn(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",t.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);s.addEventListener("abort",n),await t.close({signal:s});let o=Qn();t.addEventListener("message",i=>{o.push(i.data)}),t.addEventListener("remoteCloseWrite",()=>{o.end()}),t.addEventListener("close",i=>{i.error!=null&&o.end(i.error)});for await(let i of Jr(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=qe.decode(i);this.log("incoming new bitswap %s message from %p on stream",t.protocol,e.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:e.remotePeer,message:a,connection:e}}),s.removeEventListener("abort",n),s=AbortSignal.timeout(this.messageReceiveTimeout),s.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",e.remotePeer,t.id,a),t.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",e.remotePeer,n),t.abort(n)})}async*findProviders(t,e){e?.onProgress?.(new V("bitswap:find-providers",t));for await(let n of this.routing.findProviders(t,e)){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}e?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:n,routing:n.routing})),yield n}}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Wi(Nl(Ul(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>t.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=Fl(s.options.message,e),await s.join(n);return}await this.sendQueue.add(async o=>{let i=o.message;if(i==null)throw new kt("No message to send");this.log("sendMessage to %p",t),o.onProgress?.(new V("bitswap:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,tn,o);await a.closeRead(o);try{for(let c of Hl(i,this.maxOutgoingMessageSize))a.send(gs.single(c))||await a.onDrain(o);await a.close(o)}catch(c){this.log.error("error sending message to %p - %e",t,c),o?.onProgress?.(new V("bitswap:send-wantlist:error",{peer:t,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:t,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:e})}async connectTo(t,e){if(!this.running)throw new gn("Network isn't running");e?.onProgress?.(new V("bitswap:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Me(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(tn))return!0;throw new pn(`${t} did not support ${tn}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};var ql=Symbol.for("nodejs.util.inspect.custom"),dp=114,rn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[bn]=!0;toString(){return this.string==null&&(this.string=at.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return et.createV1(dp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ct(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ct(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[ql](){return`PeerId(${this.toString()})`}},vs=class extends rn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},_s=class extends rn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Ss=class extends rn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},pp=2336,nn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Tt.digest(Z(this.url))}[ql](){return`PeerId(${this.url})`}[bn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return et.createV1(pp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=W(t)),t.toString()===this.toString())}};var mp=114,Kl=2336;function gp(r){if(yp(r))return new vs({multihash:r});if(bp(r))try{let t=al(r);if(t.type==="Ed25519")return new _s({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Ss({multihash:r,publicKey:t})}catch{let e=W(r.digest);return new nn(new URL(e))}throw new dn("Supplied PeerID Multihash is invalid")}function zl(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==mp&&r.code!==Kl)throw new hn("Supplied PeerID CID is invalid");if(r.code===Kl){let t=W(r.multihash.digest);return new nn(new URL(t))}return gp(r.multihash)}function bp(r){return r.code===Tt.code}function yp(r){return r.code===ue.code}function Is(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var sn=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Is(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Is(this.map.values(),t=>t.key)}values(){return Is(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Qi=class extends sn{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function on(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Qi({name:t,metrics:e}):n=new sn,n}function wp(r){return r[Symbol.asyncIterator]!=null}function xp(r){if(wp(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=Ct([n,s],n.length+s.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return Ct(t,e)}var Vl=xp;var ae=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=Yt.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=Yt.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=Yt.encode(t.multihash.bytes);this.blocks.set(n,e)}};function Ep(r){let t=new Uint8Array(r.reduce((n,s)=>n+J(s),0)),e=0;for(let n of r)t=Nn(n,t,e),e+=J(n);return t}var Wl=Ep;function Ji(r){return Wl([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var As=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=e.doNotResendBlockWindow??5e3,this.maxWantListSize=e.maxWantListSize??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((t,e)=>{t.expires!=null&&t.expires<Date.now()&&this.wants.delete(e)})}addWants(t){if(t==null)return;t.full===!0&&this.wants.forEach((n,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of t.entries){let s=et.decode(n.cid),o=W(s.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,s),this.wants.delete(o);else{n.wantType===tt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,s):this.log("peer %p wanted block for %c",this.peerId,s);let i=this.wants.get(o);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===tt.WantHave&&(n.wantType==null||n.wantType===tt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??tt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??tt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let e=[...this.wants.entries()].filter(([n,s])=>s.status==="want");e.length>this.maxWantListSize&&this.truncateWants(e)}truncateWants(t){t=t.sort((n,s)=>n[1].created<s[1].created?-1:s[1].created<n[1].created?1:0).sort((n,s)=>n[1].haveBlock===!1?-1:s[1].haveBlock===!1?1:0).sort((n,s)=>n[1].priority<s[1].priority?-1:s[1].priority<n[1].priority?1:0);let e=t.length-this.maxWantListSize;for(let n=0;n<e;n++)this.wants.delete(t[n][0])}getWants(){return[...this.wants.values()]}hasWant(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async sendBlocksToPeer(t){let e=new ae,n=new Set;this.removeExpiredWants();let s=[...this.wants.entries()].filter(([o,i])=>i.status==="want");s.forEach(([o,i])=>{i.status="sending"});for(let[o,i]of s)try{let a=await Vl(this.blockstore.get(i.cid,t));if(i.status!=="sending")continue;i.wantType===tt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),e.addBlock(i.cid,{data:a,prefix:Ji(i.cid)})):(this.log("sending have for %c",i.cid),e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Lt.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),e.addBlock(i.cid,{data:a,prefix:Ji(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,e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Lt.DoNotHaveBlock})}(e.blocks.size>0||e.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0)))}};var ks=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=e.doNotResendBlockWindow,this.maxWantListSize=e.maxWantListSize,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=on({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return e.removeExpiredWants(),e.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);n==null&&(n=new As({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(e.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=[];for(let s of this.ledgerMap.values())s.hasWant(t)&&n.push(s);await Promise.all(n.map(async s=>s.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var Sp=wa(Zl(),1);var xr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(xr||(xr={}));var Ts=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Ke=class extends Ht{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Vn(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=Yt.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s.observers++,s.promise;let o=Nt(),i={promise:o.promise,observers:1,queryFilter:Vn(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,l=new mr({concurrency:this.maxProviders});l.addEventListener("failure",f=>{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)}),l.addEventListener("success",f=>{c=!0,o.resolve(f.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.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",t);for(let f=0;f<this.minProviders&&this.providers.length!==0;f++){let p=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(p)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(f=>{this.log.error("could not find new providers for %c - %e",t,f),o.reject(f)})});let u=f=>{let p=this.toFilterKey(f.detail);i.queryFilter.has(p)||(i.queryFilter.add(p),this.emitFoundProviderProgressEvent(t,f.detail,e),l.add(async()=>this.queryProvider(t,f.detail,e),{provider:f.detail}).catch(d=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,d)}))};if(this.addEventListener("provider",u),a)try{await Vr(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(f){throw a&&this.log("failed to find initial session peers for %c - %e",t,f),this.requests.delete(n),i.observers>1&&o.reject(f),f}Promise.all([...this.providers].filter(f=>{let p=this.toFilterKey(f),d=i.queryFilter.has(p);return d||i.queryFilter.add(this.toFilterKey(f)),!d}).map(async f=>l.add(async()=>this.queryProvider(t,f,e),{provider:f}))).catch(f=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,f)});let h=()=>{o.reject(new Bt(e.signal?.reason??"Session aborted")),l.abort()};e.signal?.addEventListener("abort",h);try{return await Vr(o.promise,e.signal)}finally{this.removeEventListener("provider",u),e.signal?.removeEventListener("abort",h),l.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let s=Nt(),o=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length),this.initialProviders.length>0)for(;o<e&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,"manual",n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),o++,o===e&&(this.log("session is ready with %d peer(s), only initial peers present",e),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let i of this.findNewProviders(t,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===e&&(this.log("session is ready with %d peer(s), new peers present",e),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<e)throw new Ts(`Found ${o} of ${e} ${this.name} providers for ${t}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),s.reject(i)}),s.promise}};var ta=class extends Ke{name="bitswap-session";wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e.peerId,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(t){return t.peerId.toMultihash().bytes}equals(t,e){return t.peerId.equals(e.peerId)}async convertToProvider(t,e,n){if(Ve(t))return{peerId:t,routing:e,toString:()=>`Bitswap(${t})`};if(await this.libp2p.isDialable(t)!==!1)try{let s=await this.libp2p.dial(t,n);return{peerId:s.remotePeer,routing:e,toString:()=>`Bitswap(${s.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:{id:e.peerId,multiaddrs:[],routing:e.routing},routing:e.routing}))}};function Yl(r,t){return new ta(r,t)}var Ds=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};function Tp(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=De(r);t.push(e),r=r.slice(J(e))}return t}var jl=Tp;var Ls=class extends Ht{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(t,e={}){super(),this.peers=on({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Rl({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendWantlistDebounce=e.sendWantlistDebounce??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=t.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=W(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??tt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,s)),e.onProgress!=null&&s.onProgress.push({onProgress:e.onProgress,signal:e.signal}),s.wantType===tt.WantHave&&e.wantType===tt.WantBlock&&(s.wantType=tt.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===tt.WantBlock?(await Me(this,"block",e?.signal,{filter:a=>ct(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Me(this,"presence",e?.signal,{filter:i=>ct(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers - %e",t)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Nt(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new ae;for(let[o,i]of this.wants.entries())e.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s,{onProgress:o=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(o)})})}});for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer - %e",o)}})).catch(t=>{this.log.error("error sending messages - %e",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new ae;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantHave,priority:1}),await this.network.sendMessage(e,s,n),(await Me(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&ct(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:tt.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new ae;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantBlock,priority:1}),await this.network.sendMessage(e,s,n),(await Me(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&ct(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=W(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t.remotePeer,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=jl(s.prefix),i=o[0],a=o[1],c=o[2],l=o[3],u=c===ue.code?ue:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let h=u.digest(s.data,{truncate:l});h.then!=null&&(h=await h);let f=et.create(i===0?0:1,a,h);this.log("received block from %p for %c",t.remotePeer,f),this.safeDispatchEvent("block",{detail:{sender:t.remotePeer,cid:f,block:s.data,connection:t}}),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:f,has:!0,block:s.data}});let p=W(f.multihash.bytes,"base64"),d=this.wants.get(p);d!=null&&(d.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=et.decode(s);this.log("received %s from %p for %c",o,t.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:i,has:o===Lt.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new ae(!0);for(let[s,o]of this.wants.entries())o.cancel||(e.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:tt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n,{onProgress:s=>{this.wants.forEach(({onProgress:o})=>{o.forEach(({onProgress:i})=>{i(s)})})}}),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p - %e",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Cs=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new Ds(t),this.network=new Es(t,e),this.peerWantLists=new ks({...t,network:this.network},e),this.wantList=new Ls({...t,network:this.network},e)}createSession(t={}){return Yl({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,s=xa([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",t,o)});try{let o=await this.wantList.wantBlock(t,{...e,signal:s});return e.onProgress?.(new V("bitswap:block",{cid:t,sender:o.connection.remotePeer})),o.block}finally{n.abort(),s.clear()}}async notify(t,e={}){await Promise.all([this.peerWantLists.receivedBlock(t,e),this.wantList.receivedBlock(t,e)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Xl=(r,t={})=>new Cs(r,t);var ea=class{name="bitswap";bitswap;started;constructor(t,e={}){this.bitswap=Xl(t,e),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(t,e){await this.bitswap.notify(t,e)}async retrieve(t,e={}){return this.bitswap.want(t,{...e,onProgress:function(s){if(e?.onProgress!=null)if(e.onProgress(s),s.type==="connection:open"){if(!Ve(s.detail))return;e.onProgress(new V("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:s.detail,cid:t}))}else s.type==="connection:opened"?e.onProgress(new V("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:s.detail.remotePeer,address:s.detail.remoteAddr,cid:t})):s.type==="bitswap:send-wantlist"?e.onProgress(new V("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:s.detail,cid:t})):s.type==="bitswap:block"&&e.onProgress(new V("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:s.detail.sender,cid:t}))}})}createSession(t){let e=this.bitswap.createSession(t);return{name:"bitswap-session",addPeer:async(n,s)=>{await e.addPeer(n,s)},announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function Ql(r={}){return t=>new ea(t,r)}var Dp=[6,53,56,54,55];function Jl(r){return ru("sni",r)?.value}function tu(r){let t=ru("tcp",r)?.value;return t==null?"":`:${t}`}function ru(r,t){return t.find(e=>e.name===r)}function eu(r){return r.some(({code:t})=>t===448)}function Ut(r,t){let e=nu[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var nu={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Ut(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${Ut(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Ut(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Ut(e,t)}`},http:(r,t)=>{let e=eu(t),n=Jl(t),s=tu(t);if(e&&n!=null)return`https://${n}${s}`;let o=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Ut(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Ut(e,t),s=decodeURIComponent(r.value??"");return`${n}${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Ut(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Ut(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Ut(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=eu(t),n=Jl(t),s=tu(t);if(e&&n!=null)return`wss://${n}${s}`;let o=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Ut(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Ut(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Bs(r,t){let n=us(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=nu[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return t?.assumeHttp!==!1&&Dp.includes(s.code)&&(i=i.replace(/^.*:\/\//,""),s.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var su="[a-fA-F\\d:]",xe=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${su})|(?<=${su})(?=\\s|$))`:"",Mt="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",lt="[a-fA-F\\d]{1,4}",Ps=`
|
|
2
|
+
"use strict";var HeliaBlockBrokers=(()=>{var Au=Object.create;var cn=Object.defineProperty;var Tu=Object.getOwnPropertyDescriptor;var ku=Object.getOwnPropertyNames;var Du=Object.getPrototypeOf,Lu=Object.prototype.hasOwnProperty;var ln=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),At=(r,t)=>{for(var e in t)cn(r,e,{get:t[e],enumerable:!0})},wa=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ku(t))!Lu.call(r,s)&&s!==e&&cn(r,s,{get:()=>t[s],enumerable:!(n=Tu(t,s))||n.enumerable});return r};var xa=(r,t,e)=>(e=r!=null?Au(Du(r)):{},wa(t||!r||!r.__esModule?cn(e,"default",{value:r,enumerable:!0}):e,r)),Cu=r=>wa(cn({},"__esModule",{value:!0}),r);var bi=ln(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.Netmask4Impl=void 0;fr.ip2long=ur;fr.long2ip=Zt;function Zt(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,s=r&255;return[t,e,n,s].join(".")}var od=48,id=97,ad=65;function cd(r){let t=0,e=10,n="9",s=0;r.length>1&&r[s]==="0"&&(r[s+1]==="x"||r[s+1]==="X"?(s+=2,e=16):"0"<=r[s+1]&&r[s+1]<="9"&&(s++,e=8,n="7"));let o=s;for(;s<r.length;){if("0"<=r[s]&&r[s]<=n)t=t*e+(r.charCodeAt(s)-od)>>>0;else if(e===16)if("a"<=r[s]&&r[s]<="f")t=t*e+(10+r.charCodeAt(s)-id)>>>0;else if("A"<=r[s]&&r[s]<="F")t=t*e+(10+r.charCodeAt(s)-ad)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");s++}if(s===o)throw new Error("empty octet");return[t,s]}function ur(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,s]=cd(r);r=r.substring(s),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var gi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let s=t.split("/",2);t=s[0],n=s[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=ur(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let s=32;s>=0;s--)if(this.maskLong===4294967295<<32-s>>>0){this.bitmask=s;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(ur(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Zt(this.netLong),this.mask=Zt(this.maskLong),this.hostmask=Zt(~this.maskLong),this.first=this.bitmask<=30?Zt(this.netLong+1):this.base,this.last=this.bitmask<=30?Zt(this.netLong+this.size-2):Zt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Zt(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(ur(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Zt(this.netLong+this.size*t),this.mask)}forEach(t){let e=ur(this.first),n=ur(this.last),s=0;for(;e<=n;)t(Zt(e),e,s),s++,e++}toString(){return this.base+"/"+this.bitmask}};fr.Netmask4Impl=gi});var ml=ln(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.Netmask6Impl=void 0;hr.ip6bigint=wi;hr.bigint2ip6=Re;var ld=bi(),yi=(1n<<128n)-1n;function wi(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),s=(0,ld.ip2long)(n),o=r.substring(0,e+1)+"0:0";return pl(o)&~0xffffffffn|BigInt(s)}return pl(r)}function pl(r){let t=r.indexOf("::"),e;if(t!==-1){let s=r.substring(0,t),o=r.substring(t+2),i=s===""?[]:s.split(":"),a=o===""?[]:o.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let s=0;s<8;s++){let o=e[s];if(o.length===0||o.length>4)throw new Error('Invalid IPv6: bad group "'+o+'"');let i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+o+'"');n=n<<16n|BigInt(i)}return n}function Re(r){if(r<0n||r>yi)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,s=-1,o=0;for(let i=0;i<8;i++)t[i]===0?s===-1?(s=i,o=1):o++:(o>n&&o>=2&&(e=s,n=o),s=-1,o=0);if(o>n&&o>=2&&(e=s,n=o),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var xi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let s=t.indexOf("/");s!==-1?(n=parseInt(t.substring(s+1),10),t=t.substring(0,s)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=yi>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=wi(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Re(this.netBigint),this.mask=Re(this.maskBigint),this.hostmask=Re(~this.maskBigint&yi),this.first=this.base,this.last=Re(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(wi(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(Re(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),s=this.netBigint+n-1n,o=0;for(;e<=s;)t(Re(e),Number(e),o),o++,e++}toString(){return this.base+"/"+this.bitmask}};hr.Netmask6Impl=xi});var gl=ln(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.long2ip=ye.ip2long=ye.Netmask=void 0;var Yn=bi();Object.defineProperty(ye,"ip2long",{enumerable:!0,get:function(){return Yn.ip2long}});Object.defineProperty(ye,"long2ip",{enumerable:!0,get:function(){return Yn.long2ip}});var ud=ml(),Ei=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new ud.Netmask6Impl(t,e):this._impl=new Yn.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof Yn.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};ye.Netmask=Ei});var Yl=ln((l2,Zl)=>{Zl.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var tm={};At(tm,{bitswap:()=>Jl,trustlessGateway:()=>Iu});var Bt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Tt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},un=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var fn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},hn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},dn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var pn=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},mn=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var vr=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var gn=Symbol.for("@libp2p/peer-id");function ze(r){return!!r?.[gn]}function Bu(r){return typeof r?.handleEvent=="function"}function Pu(r){return(r!==!0&&r!==!1&&r?.once)??!1}var $t=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){let s=Pu(n);super.addEventListener(t,i=>{if(s){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}Bu(e)?e.handleEvent(i):e(i)},n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:s})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==e),this.#t.set(t,s))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Ea(r){let t=new globalThis.AbortController;function e(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}var V=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var _r=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},bn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var va={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new bn("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 t}};var yn=va;var Zs={};At(Zs,{base58btc:()=>at,base58flickr:()=>Hu});var hm=new Uint8Array(0);function _a(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Yt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Sa(r){return new TextEncoder().encode(r)}function Ia(r){return new TextDecoder().decode(r)}function Ru(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var _=0,w=0,y=0,I=d.length;y!==I&&d[y]===0;)y++,_++;for(var x=(I-y)*u+1>>>0,A=new Uint8Array(x);y!==I;){for(var R=d[y],M=0,F=x-1;(R!==0||M<w)&&F!==-1;F--,M++)R+=256*A[F]>>>0,A[F]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");w=M,y++}for(var v=x-w;v!==x&&A[v]===0;)v++;for(var E=c.repeat(_);v<x;++v)E+=r.charAt(A[v]);return E}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var _=0;if(d[_]!==" "){for(var w=0,y=0;d[_]===c;)w++,_++;for(var I=(d.length-_)*l+1>>>0,x=new Uint8Array(I);d[_];){var A=e[d.charCodeAt(_)];if(A===255)return;for(var R=0,M=I-1;(A!==0||R<y)&&M!==-1;M--,R++)A+=a*x[M]>>>0,x[M]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");y=R,_++}if(d[_]!==" "){for(var F=I-y;F!==I&&x[F]===0;)F++;for(var v=new Uint8Array(w+(I-F)),E=w;F!==I;)v[E++]=x[F++];return v}}}function p(d){var _=f(d);if(_)return _;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var Ou=Ru,Nu=Ou,Ta=Nu;var zs=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Vs=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return ka(this,t)}},Ws=class{decoders;constructor(t){this.decoders=t}or(t){return ka(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ka(r,t){return new Ws({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Gs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new zs(t,e,n),this.decoder=new Vs(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ve({name:r,prefix:t,encode:e,decode:n}){return new Gs(r,t,e,n)}function ce({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Ta(e,r);return Ve({prefix:t,name:r,encode:n,decode:o=>Yt(s(o))})}function Uu(r,t,e,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Mu(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;(o.length*e&7)!==0;)o+="=";return o}function Fu(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function ot({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let s=Fu(n);return Ve({prefix:t,name:r,encode(o){return Mu(o,n,e)},decode(o){return Uu(o,s,e,r)}})}var at=ce({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Hu=ce({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ys={};At(Ys,{base32:()=>le,base32hex:()=>zu,base32hexpad:()=>Wu,base32hexpadupper:()=>Gu,base32hexupper:()=>Vu,base32pad:()=>qu,base32padupper:()=>Ku,base32upper:()=>$u,base32z:()=>Zu});var le=ot({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$u=ot({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qu=ot({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ku=ot({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),zu=ot({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vu=ot({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wu=ot({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Gu=ot({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Zu=ot({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var js={};At(js,{base36:()=>Sr,base36upper:()=>Yu});var Sr=ce({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Yu=ce({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ju=Ca,Da=128,Xu=127,Qu=~Xu,Ju=Math.pow(2,31);function Ca(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Ju;)t[e++]=r&255|Da,r/=128;for(;r&Qu;)t[e++]=r&255|Da,r>>>=7;return t[e]=r|0,Ca.bytes=e-n+1,t}var tf=Xs,ef=128,La=127;function Xs(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Xs.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&La)<<s:(i&La)*Math.pow(2,s),s+=7}while(i>=ef);return Xs.bytes=o-n,e}var rf=Math.pow(2,7),nf=Math.pow(2,14),sf=Math.pow(2,21),of=Math.pow(2,28),af=Math.pow(2,35),cf=Math.pow(2,42),lf=Math.pow(2,49),uf=Math.pow(2,56),ff=Math.pow(2,63),hf=function(r){return r<rf?1:r<nf?2:r<sf?3:r<of?4:r<af?5:r<cf?6:r<lf?7:r<uf?8:r<ff?9:10},df={encode:ju,decode:tf,encodingLength:hf},pf=df,Ir=pf;function Ar(r,t=0){return[Ir.decode(r,t),Ir.decode.bytes]}function We(r,t,e=0){return Ir.encode(r,t,e),t}function Ge(r){return Ir.encodingLength(r)}function Ye(r,t){let e=t.byteLength,n=Ge(r),s=n+Ge(e),o=new Uint8Array(s+e);return We(r,o,0),We(e,o,n),o.set(t,s),new Ze(r,e,t,o)}function xn(r){let t=Yt(r),[e,n]=Ar(t),[s,o]=Ar(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ze(e,s,i,t)}function Ba(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&_a(r.bytes,e.bytes)}}var Ze=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};function Pa(r,t){let{bytes:e,version:n}=r;return n===0?gf(e,Qs(r),t??at.encoder):bf(e,Qs(r),t??le.encoder)}var Ra=new WeakMap;function Qs(r){let t=Ra.get(r);if(t==null){let e=new Map;return Ra.set(r,e),e}return t}var et=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Tr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==yf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Ye(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Ba(t.multihash,n.multihash)}toString(t){return Pa(this,t)}toJSON(){return{"/":Pa(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??Oa(n,s,o.bytes))}else if(e[wf]===!0){let{version:n,multihash:s,code:o}=e,i=xn(s);return r.create(n,o,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Tr)throw new Error(`Version 0 CID must use dag-pb (code: ${Tr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Oa(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Tr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=Yt(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Ze(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=Ar(t.subarray(e));return e+=f,h},s=n(),o=Tr;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,s]=mf(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Qs(o).set(n,t),o}};function mf(r,t){switch(r[0]){case"Q":{let e=t??at;return[at.prefix,e.decode(`${at.prefix}${r}`)]}case at.prefix:{let e=t??at;return[at.prefix,e.decode(r)]}case le.prefix:{let e=t??le;return[le.prefix,e.decode(r)]}case Sr.prefix:{let e=t??Sr;return[Sr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function gf(r,t,e){let{prefix:n}=e;if(n!==at.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function bf(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var Tr=112,yf=18;function Oa(r,t,e){let n=Ge(r),s=n+Ge(t),o=new Uint8Array(s+e.byteLength);return We(r,o,0),We(t,o,n),o.set(e,s),o}var wf=Symbol.for("@ipld/js-cid/CID");var Js={};At(Js,{identity:()=>kt});var Na=0,xf="identity",Ua=Yt;function Ef(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Ye(Na,Ua(r))}var kt={code:Na,name:xf,encode:Ua,digest:Ef};function ct(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function yt(r=0){return new Uint8Array(r)}function wt(r=0){return new Uint8Array(r)}function Ct(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=wt(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}var Fa=Symbol.for("@achingbrain/uint8arraylist");function Ma(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function En(r){return!!r?.[Fa]}var ut=class r{bufs;length;[Fa]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(En(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(En(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Ma(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ma(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(En(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return Ct(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Ct(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!En(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<s;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let p=this.get(h+f);if(n[f]!==p){u=Math.max(1,f-a[p]);break}}if(u===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=yt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=yt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=yt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=yt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=yt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=yt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=yt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=yt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!ct(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,o)=>s+o.byteLength,0)),n.length=e,n}};var to={};At(to,{base10:()=>vf});var vf=ce({prefix:"9",name:"base10",alphabet:"0123456789"});var eo={};At(eo,{base16:()=>_f,base16upper:()=>Sf});var _f=ot({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Sf=ot({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ro={};At(ro,{base2:()=>If});var If=ot({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var no={};At(no,{base256emoji:()=>Lf});var Ha=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}"),Af=Ha.reduce((r,t,e)=>(r[e]=t,r),[]),Tf=Ha.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function kf(r){return r.reduce((t,e)=>(t+=Af[e],t),"")}function Df(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=Tf[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var Lf=Ve({prefix:"\u{1F680}",name:"base256emoji",encode:kf,decode:Df});var oo={};At(oo,{base64:()=>jt,base64pad:()=>Cf,base64url:()=>so,base64urlpad:()=>Bf});var jt=ot({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Cf=ot({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),so=ot({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bf=ot({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var io={};At(io,{base8:()=>Pf});var Pf=ot({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ao={};At(ao,{identity:()=>Rf});var Rf=Ve({prefix:"\0",name:"identity",encode:r=>Ia(r),decode:r=>Sa(r)});var Ym=new TextEncoder,jm=new TextDecoder;var uo={};At(uo,{sha256:()=>ue,sha512:()=>Mf});var Uf=20;function lo({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:s}){return new co(r,t,e,n,s)}var co=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,s,o){this.name=t,this.code=e,this.encode=n,this.minDigestLength=s??Uf,this.maxDigestLength=o}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?$a(n,this.code,e?.truncate):n.then(s=>$a(s,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function $a(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Ye(t,r)}function Ka(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var ue=lo({name:"sha2-256",code:18,encode:Ka("SHA-256")}),Mf=lo({name:"sha2-512",code:19,encode:Ka("SHA-512")});var kr={...ao,...ro,...io,...to,...eo,...Ys,...js,...Zs,...oo,...no},c0={...uo,...Js};function Va(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var za=Va("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),fo=Va("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=wt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Ff={utf8:za,"utf-8":za,hex:kr.base16,latin1:fo,ascii:fo,binary:fo,...kr},vn=Ff;function Z(r,t="utf8"){let e=vn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function W(r,t="utf8"){let e=vn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Hf=parseInt("11111",2),ho=parseInt("10000000",2),$f=parseInt("01111111",2),Wa={0:Dr,1:Dr,2:qf,3:Vf,4:Wf,5:zf,6:Kf,16:Dr,22:Dr,48:Dr};function po(r,t={offset:0}){let e=r[t.offset]&Hf;if(t.offset++,Wa[e]!=null)return Wa[e](r,t);throw new Error("No decoder for tag "+e)}function Lr(r,t){let e=0;if((r[t.offset]&ho)===ho){let n=r[t.offset]&$f,s="0x";t.offset++;for(let o=0;o<n;o++,t.offset++)s+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(s,16)}else e=r[t.offset],t.offset++;return e}function Dr(r,t){Lr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=po(r,t);if(n===null)break;e.push(n)}return e}function qf(r,t){let e=Lr(r,t),n=t.offset,s=t.offset+e,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return t.offset+=e,Uint8Array.from(o)}function Kf(r,t){let e=Lr(r,t),n=t.offset+e,s=r[t.offset];t.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function zf(r,t){return t.offset++,null}function Vf(r,t){let e=Lr(r,t),n=r[t.offset];t.offset++;let s=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function Wf(r,t){let e=Lr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Gf(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ut;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function mo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Gf(r.byteLength);return new ut(Uint8Array.from([t.byteLength|ho]),t)}function Ga(r){let t=new ut,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ut(Uint8Array.from([2]),mo(t),t)}function Za(r){let t=Uint8Array.from([0]),e=new ut(t,r);return new ut(Uint8Array.from([3]),mo(e),e)}function _n(r,t=48){let e=new ut;for(let n of r)e.append(n);return new ut(Uint8Array.from([t]),mo(e),e)}async function Ya(r,t,e,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,e.subarray());return n?.signal?.throwIfAborted(),o}var Zf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Yf=Uint8Array.from([6,5,43,129,4,0,34]),jf=Uint8Array.from([6,5,43,129,4,0,35]),Xf={ext:!0,kty:"EC",crv:"P-256"},Qf={ext:!0,kty:"EC",crv:"P-384"},Jf={ext:!0,kty:"EC",crv:"P-521"},go=32,bo=48,yo=66;function ja(r){let t=po(r);return Xa(t)}function Xa(r){let t=r[1][1][0],e=1,n,s;if(t.byteLength===go*2+1)return n=W(t.subarray(e,e+go),"base64url"),s=W(t.subarray(e+go),"base64url"),new je({...Xf,key_ops:["verify"],x:n,y:s});if(t.byteLength===bo*2+1)return n=W(t.subarray(e,e+bo),"base64url"),s=W(t.subarray(e+bo),"base64url"),new je({...Qf,key_ops:["verify"],x:n,y:s});if(t.byteLength===yo*2+1)return n=W(t.subarray(e,e+yo),"base64url"),s=W(t.subarray(e+yo),"base64url"),new je({...Jf,key_ops:["verify"],x:n,y:s});throw new Tt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Qa(r){return _n([Ga(Uint8Array.from([1])),_n([th(r.crv)],160),_n([Za(new ut(Uint8Array.from([4]),Z(r.x??"","base64url"),Z(r.y??"","base64url")))],161)]).subarray()}function th(r){if(r==="P-256")return Zf;if(r==="P-384")return Yf;if(r==="P-521")return jf;throw new Tt(`Invalid curve ${r}`)}var je=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Qa(this.jwk)),this._raw}toMultihash(){return kt.digest(Xe(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return at.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}async verify(t,e,n){return Ya(this.jwk,e,t,n)}};function ve(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function qt(r,t=""){if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${r}`)}}function U(r,t,e=""){let n=ve(r),s=r?.length,o=t!==void 0;if(!n||o&&s!==t){let i=e&&`"${e}" `,a=o?` of length ${t}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Sn(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");qt(r.outputLen),qt(r.blockLen)}function Qe(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function tc(r,t){U(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Qt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function In(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Pt(r,t){return r<<32-t|r>>>t}var ec=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",eh=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Jt(r){if(U(r),ec)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=eh[r[e]];return t}var Xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ja(r){if(r>=Xt._0&&r<=Xt._9)return r-Xt._0;if(r>=Xt.A&&r<=Xt.F)return r-(Xt.A-10);if(r>=Xt.a&&r<=Xt.f)return r-(Xt.a-10)}function te(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(ec)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let s=0,o=0;s<e;s++,o+=2){let i=Ja(r.charCodeAt(o)),a=Ja(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function It(...r){let t=0;for(let n=0;n<r.length;n++){let s=r[n];U(s),t+=s.length}let e=new Uint8Array(t);for(let n=0,s=0;n<r.length;n++){let o=r[n];e.set(o,s),s+=o.length}return e}function wo(r,t={}){let e=(s,o)=>r(o).update(s).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=s=>r(s),Object.assign(e,t),Object.freeze(e)}function Je(r=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(r))}var xo=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function rc(r,t,e){return r&t^~r&e}function nc(r,t,e){return r&t^r&e^t&e}var Cr=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,s){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=In(this.buffer)}update(t){Qe(this),U(t);let{view:e,buffer:n,blockLen:s}=this,o=t.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=In(t);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Qe(this),tc(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;e[i++]=128,Qt(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let h=i;h<s;h++)e[h]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=In(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=o,t.length=s,t.pos=a,s%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ee=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var mt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var An=BigInt(4294967295),sc=BigInt(32);function rh(r,t=!1){return t?{h:Number(r&An),l:Number(r>>sc&An)}:{h:Number(r>>sc&An)|0,l:Number(r&An)|0}}function oc(r,t=!1){let e=r.length,n=new Uint32Array(e),s=new Uint32Array(e);for(let o=0;o<e;o++){let{h:i,l:a}=rh(r[o],t);[n[o],s[o]]=[i,a]}return[n,s]}var Eo=(r,t,e)=>r>>>e,vo=(r,t,e)=>r<<32-e|t>>>e,_e=(r,t,e)=>r>>>e|t<<32-e,Se=(r,t,e)=>r<<32-e|t>>>e,Br=(r,t,e)=>r<<64-e|t>>>e-32,Pr=(r,t,e)=>r>>>e-32|t<<64-e;function Kt(r,t,e,n){let s=(t>>>0)+(n>>>0);return{h:r+e+(s/2**32|0)|0,l:s|0}}var ic=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),ac=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,cc=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),lc=(r,t,e,n,s)=>t+e+n+s+(r/2**32|0)|0,uc=(r,t,e,n,s)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(s>>>0),fc=(r,t,e,n,s,o)=>t+e+n+s+o+(r/2**32|0)|0;var sh=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]),fe=new Uint32Array(64),_o=class extends Cr{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[t,e,n,s,o,i,a,c]}set(t,e,n,s,o,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let h=0;h<16;h++,e+=4)fe[h]=t.getUint32(e,!1);for(let h=16;h<64;h++){let f=fe[h-15],p=fe[h-2],d=Pt(f,7)^Pt(f,18)^f>>>3,_=Pt(p,17)^Pt(p,19)^p>>>10;fe[h]=_+fe[h-7]+d+fe[h-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let f=Pt(a,6)^Pt(a,11)^Pt(a,25),p=u+f+rc(a,c,l)+sh[h]+fe[h]|0,_=(Pt(n,2)^Pt(n,13)^Pt(n,22))+nc(n,s,o)|0;u=l,l=c,c=a,a=i+p|0,i=o,o=s,s=n,n=p+_|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){Qt(fe)}destroy(){this.set(0,0,0,0,0,0,0,0),Qt(this.buffer)}},So=class extends _o{A=ee[0]|0;B=ee[1]|0;C=ee[2]|0;D=ee[3]|0;E=ee[4]|0;F=ee[5]|0;G=ee[6]|0;H=ee[7]|0;constructor(){super(32)}};var hc=oc(["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))),oh=hc[0],ih=hc[1],he=new Uint32Array(80),de=new Uint32Array(80),Io=class extends Cr{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:p,Gl:d,Hh:_,Hl:w}=this;return[t,e,n,s,o,i,a,c,l,u,h,f,p,d,_,w]}set(t,e,n,s,o,i,a,c,l,u,h,f,p,d,_,w){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=_|0,this.Hl=w|0}process(t,e){for(let x=0;x<16;x++,e+=4)he[x]=t.getUint32(e),de[x]=t.getUint32(e+=4);for(let x=16;x<80;x++){let A=he[x-15]|0,R=de[x-15]|0,M=_e(A,R,1)^_e(A,R,8)^Eo(A,R,7),F=Se(A,R,1)^Se(A,R,8)^vo(A,R,7),v=he[x-2]|0,E=de[x-2]|0,O=_e(v,E,19)^Br(v,E,61)^Eo(v,E,6),H=Se(v,E,19)^Pr(v,E,61)^vo(v,E,6),L=cc(F,H,de[x-7],de[x-16]),g=lc(L,M,O,he[x-7],he[x-16]);he[x]=g|0,de[x]=L|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:p,Fl:d,Gh:_,Gl:w,Hh:y,Hl:I}=this;for(let x=0;x<80;x++){let A=_e(h,f,14)^_e(h,f,18)^Br(h,f,41),R=Se(h,f,14)^Se(h,f,18)^Pr(h,f,41),M=h&p^~h&_,F=f&d^~f&w,v=uc(I,R,F,ih[x],de[x]),E=fc(v,y,A,M,oh[x],he[x]),O=v|0,H=_e(n,s,28)^Br(n,s,34)^Br(n,s,39),L=Se(n,s,28)^Pr(n,s,34)^Pr(n,s,39),g=n&o^n&a^o&a,b=s&i^s&c^i&c;y=_|0,I=w|0,_=p|0,w=d|0,p=h|0,d=f|0,{h,l:f}=Kt(l|0,u|0,E|0,O|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let m=ic(O,L,b);n=ac(m,E,H,g),s=m|0}({h:n,l:s}=Kt(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=Kt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=Kt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Kt(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=Kt(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=Kt(this.Fh|0,this.Fl|0,p|0,d|0),{h:_,l:w}=Kt(this.Gh|0,this.Gl|0,_|0,w|0),{h:y,l:I}=Kt(this.Hh|0,this.Hl|0,y|0,I|0),this.set(n,s,o,i,a,c,l,u,h,f,p,d,_,w,y,I)}roundClean(){Qt(he,de)}destroy(){Qt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ao=class extends Io{Ah=mt[0]|0;Al=mt[1]|0;Bh=mt[2]|0;Bl=mt[3]|0;Ch=mt[4]|0;Cl=mt[5]|0;Dh=mt[6]|0;Dl=mt[7]|0;Eh=mt[8]|0;El=mt[9]|0;Fh=mt[10]|0;Fl=mt[11]|0;Gh=mt[12]|0;Gl=mt[13]|0;Hh=mt[14]|0;Hl=mt[15]|0;constructor(){super(64)}};var dc=wo(()=>new So,xo(1));var pc=wo(()=>new Ao,xo(3));var ko=BigInt(0),To=BigInt(1);function re(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function mc(r){if(typeof r=="bigint"){if(!Tn(r))throw new Error("positive bigint expected, got "+r)}else qt(r);return r}function Rr(r){let t=mc(r).toString(16);return t.length&1?"0"+t:t}function gc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ko:BigInt("0x"+r)}function tr(r){return gc(Jt(r))}function Ie(r){return gc(Jt(Dn(U(r)).reverse()))}function kn(r,t){qt(t),r=mc(r);let e=te(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function Do(r,t){return kn(r,t).reverse()}function Dn(r){return Uint8Array.from(r)}var Tn=r=>typeof r=="bigint"&&ko<=r;function ah(r,t,e){return Tn(r)&&Tn(t)&&Tn(e)&&t<=r&&r<e}function Or(r,t,e,n){if(!ah(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Lo(r){let t;for(t=0;r>ko;r>>=To,t+=1);return t}var Nr=r=>(To<<BigInt(r))-To;function bc(r,t,e){if(qt(r,"hashLen"),qt(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let n=w=>new Uint8Array(w),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,h=()=>{c.fill(1),l.fill(0),u=0},f=(...w)=>e(l,It(c,...w)),p=(w=s)=>{l=f(o,w),c=f(),w.length!==0&&(l=f(i,w),c=f())},d=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let w=0,y=[];for(;w<t;){c=f();let I=c.slice();y.push(I),w+=c.length}return It(...y)};return(w,y)=>{h(),p(w);let I;for(;!(I=y(d()));)p();return h(),I}}function pe(r,t={},e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(t,!1),s(e,!0)}function er(r){let t=new WeakMap;return(e,...n)=>{let s=t.get(e);if(s!==void 0)return s;let o=r(e,...n);return t.set(e,o),o}}var _t=BigInt(0),ft=BigInt(1),Ae=BigInt(2),xc=BigInt(3),Ec=BigInt(4),vc=BigInt(5),ch=BigInt(7),_c=BigInt(8),lh=BigInt(9),Sc=BigInt(16);function it(r,t){let e=r%t;return e>=_t?e:t+e}function Q(r,t,e){let n=r;for(;t-- >_t;)n*=n,n%=e;return n}function yc(r,t){if(r===_t)throw new Error("invert: expected non-zero number");if(t<=_t)throw new Error("invert: expected positive modulus, got "+t);let e=it(r,t),n=t,s=_t,o=ft,i=ft,a=_t;for(;e!==_t;){let l=n/e,u=n%e,h=s-i*l,f=o-a*l;n=e,e=u,s=i,o=a,i=h,a=f}if(n!==ft)throw new Error("invert: does not exist");return it(s,t)}function Bo(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function Ic(r,t){let e=(r.ORDER+ft)/Ec,n=r.pow(t,e);return Bo(r,n,t),n}function uh(r,t){let e=(r.ORDER-vc)/_c,n=r.mul(t,Ae),s=r.pow(n,e),o=r.mul(t,s),i=r.mul(r.mul(o,Ae),s),a=r.mul(o,r.sub(i,r.ONE));return Bo(r,a,t),a}function fh(r){let t=rr(r),e=Ac(r),n=e(t,t.neg(t.ONE)),s=e(t,n),o=e(t,t.neg(n)),i=(r+ch)/Sc;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),h=a.mul(l,s),f=a.mul(l,o),p=a.eql(a.sqr(u),c),d=a.eql(a.sqr(h),c);l=a.cmov(l,u,p),u=a.cmov(f,h,d);let _=a.eql(a.sqr(u),c),w=a.cmov(l,u,_);return Bo(a,w,c),w}}function Ac(r){if(r<xc)throw new Error("sqrt is not defined for small field");let t=r-ft,e=0;for(;t%Ae===_t;)t/=Ae,e++;let n=Ae,s=rr(r);for(;wc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Ic;let o=s.pow(n,t),i=(t+ft)/Ae;return function(c,l){if(c.is0(l))return l;if(wc(c,l)!==1)throw new Error("Cannot find square root");let u=e,h=c.mul(c.ONE,o),f=c.pow(l,t),p=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let d=1,_=c.sqr(f);for(;!c.eql(_,c.ONE);)if(d++,_=c.sqr(_),d===u)throw new Error("Cannot find square root");let w=ft<<BigInt(u-d-1),y=c.pow(h,w);u=d,h=c.sqr(y),f=c.mul(f,h),p=c.mul(p,y)}return p}}function hh(r){return r%Ec===xc?Ic:r%_c===vc?uh:r%Sc===lh?fh(r):Ac(r)}var Tc=(r,t)=>(it(r,t)&ft)===ft,dh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Po(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=dh.reduce((n,s)=>(n[s]="function",n),t);return pe(r,e),r}function ph(r,t,e){if(e<_t)throw new Error("invalid exponent, negatives unsupported");if(e===_t)return r.ONE;if(e===ft)return t;let n=r.ONE,s=t;for(;e>_t;)e&ft&&(n=r.mul(n,s)),s=r.sqr(s),e>>=ft;return n}function Ur(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),s=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),o=r.inv(s);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),o),n}function wc(r,t){let e=(r.ORDER-ft)/Ae,n=r.pow(t,e),s=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function mh(r,t){t!==void 0&&qt(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}var Co=class{ORDER;BITS;BYTES;isLE;ZERO=_t;ONE=ft;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=_t)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:s,nByteLength:o}=mh(t,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return it(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return _t<=t&&t<this.ORDER}is0(t){return t===_t}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&ft)===ft}neg(t){return it(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return it(t*t,this.ORDER)}add(t,e){return it(t+e,this.ORDER)}sub(t,e){return it(t-e,this.ORDER)}mul(t,e){return it(t*e,this.ORDER)}pow(t,e){return ph(this,t,e)}div(t,e){return it(t*yc(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return yc(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=hh(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?Do(t,this.BYTES):kn(t,this.BYTES)}fromBytes(t,e=!1){U(t);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let l=new Uint8Array(s);l.set(t,o?0:l.length-t.length),t=l}if(t.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);let c=o?Ie(t):tr(t);if(a&&(c=it(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Ur(this,t)}cmov(t,e,n){return n?e:t}};function rr(r,t={}){return new Co(r,t)}function kc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Ro(r){let t=kc(r);return t+Math.ceil(t/2)}function Oo(r,t,e=!1){U(r);let n=r.length,s=kc(t),o=Ro(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=e?Ie(r):tr(r),a=it(i,t-ft)+ft;return e?Do(a,s):kn(a,s)}var nr=BigInt(0),Te=BigInt(1);function Mr(r,t){let e=t.negate();return r?e:t}function ke(r,t){let e=Ur(r.Fp,t.map(n=>n.Z));return t.map((n,s)=>r.fromAffine(n.toAffine(e[s])))}function Bc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function No(r,t){Bc(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),s=2**r,o=Nr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function Dc(r,t,e){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=e,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Te);let l=t*n,u=l+Math.abs(a)-1,h=a===0,f=a<0,p=t%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:l}}var Uo=new WeakMap,Pc=new WeakMap;function Mo(r){return Pc.get(r)||1}function Lc(r){if(r!==nr)throw new Error("invalid wNAF")}var sr=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let s=t;for(;e>nr;)e&Te&&(n=n.add(s)),s=s.double(),e>>=Te;return n}precomputeWindow(t,e){let{windows:n,windowSize:s}=No(e,this.bits),o=[],i=t,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=No(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:f,offsetF:p}=Dc(n,a,i);n=c,u?o=o.add(Mr(f,e[p])):s=s.add(Mr(h,e[l]))}return Lc(n),{p:s,f:o}}wNAFUnsafe(t,e,n,s=this.ZERO){let o=No(t,this.bits);for(let i=0;i<o.windows&&n!==nr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Dc(n,i,o);if(n=a,!l){let h=e[c];s=s.add(u?h.negate():h)}}return Lc(n),s}getPrecomputes(t,e,n){let s=Uo.get(e);return s||(s=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(s=n(s)),Uo.set(e,s))),s}cached(t,e,n){let s=Mo(t);return this.wNAF(s,this.getPrecomputes(s,t,n),e)}unsafe(t,e,n,s){let o=Mo(t);return o===1?this._unsafeLadder(t,e,s):this.wNAFUnsafe(o,this.getPrecomputes(o,t,n),e,s)}createCache(t,e){Bc(e,this.bits),Pc.set(t,e),Uo.delete(t)}hasCache(t){return Mo(t)!==1}};function Rc(r,t,e,n){let s=t,o=r.ZERO,i=r.ZERO;for(;e>nr||n>nr;)e&Te&&(o=o.add(s)),n&Te&&(i=i.add(s)),s=s.double(),e>>=Te,n>>=Te;return{p1:o,p2:i}}function Cc(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Po(t),t}else return rr(r,{isLE:e})}function Ln(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>nr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Cc(t.p,e.Fp,n),o=Cc(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:s,Fn:o}}function Cn(r,t){return function(n){let s=r(n);return{secretKey:s,publicKey:t(s)}}}var me=BigInt(0),ht=BigInt(1),Fo=BigInt(2),gh=BigInt(8);function bh(r,t,e,n){let s=r.sqr(e),o=r.sqr(n),i=r.add(r.mul(t.a,s),o),a=r.add(r.ONE,r.mul(t.d,r.mul(s,o)));return r.eql(i,a)}function Oc(r,t={}){let e=Ln("edwards",r,t,t.FpFnLE),{Fp:n,Fn:s}=e,o=e.CURVE,{h:i}=o;pe(t,{},{uvRatio:"function"});let a=Fo<<BigInt(s.BYTES*8)-ht,c=w=>n.create(w),l=t.uvRatio||((w,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,y))}}catch{return{isValid:!1,value:me}}});if(!bh(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(w,y,I=!1){let x=I?ht:me;return Or("coordinate "+w,y,x,a),y}function h(w){if(!(w instanceof d))throw new Error("EdwardsPoint expected")}let f=er((w,y)=>{let{X:I,Y:x,Z:A}=w,R=w.is0();y==null&&(y=R?gh:n.inv(A));let M=c(I*y),F=c(x*y),v=n.mul(A,y);if(R)return{x:me,y:ht};if(v!==ht)throw new Error("invZ was invalid");return{x:M,y:F}}),p=er(w=>{let{a:y,d:I}=o;if(w.is0())throw new Error("bad point: ZERO");let{X:x,Y:A,Z:R,T:M}=w,F=c(x*x),v=c(A*A),E=c(R*R),O=c(E*E),H=c(F*y),L=c(E*c(H+v)),g=c(O+c(I*c(F*v)));if(L!==g)throw new Error("bad point: equation left != right (1)");let b=c(x*A),m=c(R*M);if(b!==m)throw new Error("bad point: equation left != right (2)");return!0});class d{static BASE=new d(o.Gx,o.Gy,ht,c(o.Gx*o.Gy));static ZERO=new d(me,ht,ht,me);static Fp=n;static Fn=s;X;Y;Z;T;constructor(y,I,x,A){this.X=u("x",y),this.Y=u("y",I),this.Z=u("z",x,!0),this.T=u("t",A),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof d)throw new Error("extended point not allowed");let{x:I,y:x}=y||{};return u("x",I),u("y",x),new d(I,x,ht,c(I*x))}static fromBytes(y,I=!1){let x=n.BYTES,{a:A,d:R}=o;y=Dn(U(y,x,"point")),re(I,"zip215");let M=Dn(y),F=y[x-1];M[x-1]=F&-129;let v=Ie(M),E=I?a:n.ORDER;Or("point.y",v,me,E);let O=c(v*v),H=c(O-ht),L=c(R*O-A),{isValid:g,value:b}=l(H,L);if(!g)throw new Error("bad point: invalid y coordinate");let m=(b&ht)===ht,S=(F&128)!==0;if(!I&&b===me&&S)throw new Error("bad point: x=0 and x_0=1");return S!==m&&(b=c(-b)),d.fromAffine({x:b,y:v})}static fromHex(y,I=!1){return d.fromBytes(te(y),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,I=!0){return _.createCache(this,y),I||this.multiply(Fo),this}assertValidity(){p(this)}equals(y){h(y);let{X:I,Y:x,Z:A}=this,{X:R,Y:M,Z:F}=y,v=c(I*F),E=c(R*A),O=c(x*F),H=c(M*A);return v===E&&O===H}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=o,{X:I,Y:x,Z:A}=this,R=c(I*I),M=c(x*x),F=c(Fo*c(A*A)),v=c(y*R),E=I+x,O=c(c(E*E)-R-M),H=v+M,L=H-F,g=v-M,b=c(O*L),m=c(H*g),S=c(O*g),T=c(L*H);return new d(b,m,T,S)}add(y){h(y);let{a:I,d:x}=o,{X:A,Y:R,Z:M,T:F}=this,{X:v,Y:E,Z:O,T:H}=y,L=c(A*v),g=c(R*E),b=c(F*x*H),m=c(M*O),S=c((A+R)*(v+E)-L-g),T=m-b,D=m+b,C=c(g-I*L),k=c(S*T),P=c(D*C),N=c(S*C),rt=c(T*D);return new d(k,P,rt,N)}subtract(y){return this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:I,f:x}=_.cached(this,y,A=>ke(d,A));return ke(d,[I,x])[0]}multiplyUnsafe(y,I=d.ZERO){if(!s.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===me?d.ZERO:this.is0()||y===ht?this:_.unsafe(this,y,x=>ke(d,x),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return _.unsafe(this,o.n).is0()}toAffine(y){return f(this,y)}clearCofactor(){return i===ht?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:I}=this.toAffine(),x=n.toBytes(I);return x[x.length-1]|=y&ht?128:0,x}toHex(){return Jt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let _=new sr(d,s.BITS);return d.BASE.precompute(8),d}function Nc(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');pe(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:s,Fp:o,Fn:i}=r,a=e.randomBytes||Je,c=e.adjustScalarBytes||(v=>v),l=e.domain||((v,E,O)=>{if(re(O,"phflag"),E.length||O)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(Ie(v))}function h(v){let E=x.secretKey;U(v,x.secretKey,"secretKey");let O=U(t(v),2*E,"hashedSecretKey"),H=c(O.slice(0,E)),L=O.slice(E,2*E),g=u(H);return{head:H,prefix:L,scalar:g}}function f(v){let{head:E,prefix:O,scalar:H}=h(v),L=s.multiply(H),g=L.toBytes();return{head:E,prefix:O,scalar:H,point:L,pointBytes:g}}function p(v){return f(v).pointBytes}function d(v=Uint8Array.of(),...E){let O=It(...E);return u(t(l(O,U(v,void 0,"context"),!!n)))}function _(v,E,O={}){v=U(v,void 0,"message"),n&&(v=n(v));let{prefix:H,scalar:L,pointBytes:g}=f(E),b=d(O.context,H,v),m=s.multiply(b).toBytes(),S=d(O.context,m,g,v),T=i.create(b+S*L);if(!i.isValid(T))throw new Error("sign failed: invalid s");let D=It(m,i.toBytes(T));return U(D,x.signature,"result")}let w={zip215:!0};function y(v,E,O,H=w){let{context:L,zip215:g}=H,b=x.signature;v=U(v,b,"signature"),E=U(E,void 0,"message"),O=U(O,x.publicKey,"publicKey"),g!==void 0&&re(g,"zip215"),n&&(E=n(E));let m=b/2,S=v.subarray(0,m),T=Ie(v.subarray(m,b)),D,C,k;try{D=r.fromBytes(O,g),C=r.fromBytes(S,g),k=s.multiplyUnsafe(T)}catch{return!1}if(!g&&D.isSmallOrder())return!1;let P=d(L,C.toBytes(),D.toBytes(),E);return C.add(D.multiplyUnsafe(P)).subtract(k).clearCofactor().is0()}let I=o.BYTES,x={secretKey:I,publicKey:I,signature:2*I,seed:I};function A(v=a(x.seed)){return U(v,x.seed,"seed")}function R(v){return ve(v)&&v.length===i.BYTES}function M(v,E){try{return!!r.fromBytes(v,E)}catch{return!1}}let F={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:R,isValidPublicKey:M,toMontgomery(v){let{y:E}=r.fromBytes(v),O=x.publicKey,H=O===32;if(!H&&O!==57)throw new Error("only defined for 25519 and 448");let L=H?o.div(ht+E,ht-E):o.div(E-ht,E+ht);return o.toBytes(L)},toMontgomerySecret(v){let E=x.secretKey;U(v,E);let O=t(v.subarray(0,E));return c(O).subarray(0,E)}};return Object.freeze({keygen:Cn(A,p),getPublicKey:p,sign:_,verify:y,utils:F,Point:r,lengths:x})}var yh=BigInt(1),Uc=BigInt(2);var wh=BigInt(5),xh=BigInt(8),Ho=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Eh={p:Ho,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function vh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),s=BigInt(80),o=Ho,a=r*r%o*r%o,c=Q(a,Uc,o)*a%o,l=Q(c,yh,o)*r%o,u=Q(l,wh,o)*l%o,h=Q(u,t,o)*u%o,f=Q(h,e,o)*h%o,p=Q(f,n,o)*f%o,d=Q(p,s,o)*p%o,_=Q(d,s,o)*p%o,w=Q(_,t,o)*u%o;return{pow_p_5_8:Q(w,Uc,o)*r%o,b2:a}}function _h(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Mc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Sh(r,t){let e=Ho,n=it(t*t*t,e),s=it(n*n*t,e),o=vh(r*s).pow_p_5_8,i=it(r*n*o,e),a=it(t*i*i,e),c=i,l=it(i*Mc,e),u=a===r,h=a===it(-r,e),f=a===it(-r*Mc,e);return u&&(i=c),(h||f)&&(i=l),Tc(i,e)&&(i=it(-i,e)),{isValid:u||h,value:i}}var Ih=Oc(Eh,{uvRatio:Sh});function Ah(r){return Nc(Ih,pc,Object.assign({adjustScalarBytes:_h},r))}var Fc=Ah({});var Bn=32;var $o,Th=(async()=>{try{return await yn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function kh(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await yn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await yn.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Dh(r,t,e){return Fc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Hc(r,t,e){return $o==null&&($o=await Th),$o?kh(r,t,e):Dh(r,t,e)}function Pn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Rn=class{type="Ed25519";raw;constructor(t){this.raw=qo(t,Bn)}toMultihash(){return kt.digest(Xe(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return at.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let s=Hc(this.raw,e,t);return Pn(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function qc(r){return r=qo(r,Bn),new Rn(r)}function qo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Tt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Ch=Math.pow(2,7),Bh=Math.pow(2,14),Ph=Math.pow(2,21),Ko=Math.pow(2,28),zo=Math.pow(2,35),Vo=Math.pow(2,42),Wo=Math.pow(2,49),z=128,xt=127;function J(r){if(r<Ch)return 1;if(r<Bh)return 2;if(r<Ph)return 3;if(r<Ko)return 4;if(r<zo)return 5;if(r<Vo)return 6;if(r<Wo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function or(r,t,e=0){switch(J(r)){case 8:t[e++]=r&255|z,r/=128;case 7:t[e++]=r&255|z,r/=128;case 6:t[e++]=r&255|z,r/=128;case 5:t[e++]=r&255|z,r/=128;case 4:t[e++]=r&255|z,r>>>=7;case 3:t[e++]=r&255|z,r>>>=7;case 2:t[e++]=r&255|z,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Rh(r,t,e=0){switch(J(r)){case 8:t.set(e++,r&255|z),r/=128;case 7:t.set(e++,r&255|z),r/=128;case 6:t.set(e++,r&255|z),r/=128;case 5:t.set(e++,r&255|z),r/=128;case 4:t.set(e++,r&255|z),r>>>=7;case 3:t.set(e++,r&255|z),r>>>=7;case 2:t.set(e++,r&255|z),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Go(r,t){let e=r[t],n=0;if(n+=e&xt,e<z||(e=r[t+1],n+=(e&xt)<<7,e<z)||(e=r[t+2],n+=(e&xt)<<14,e<z)||(e=r[t+3],n+=(e&xt)<<21,e<z)||(e=r[t+4],n+=(e&xt)*Ko,e<z)||(e=r[t+5],n+=(e&xt)*zo,e<z)||(e=r[t+6],n+=(e&xt)*Vo,e<z)||(e=r[t+7],n+=(e&xt)*Wo,e<z))return n;throw new RangeError("Could not decode varint")}function Oh(r,t){let e=r.get(t),n=0;if(n+=e&xt,e<z||(e=r.get(t+1),n+=(e&xt)<<7,e<z)||(e=r.get(t+2),n+=(e&xt)<<14,e<z)||(e=r.get(t+3),n+=(e&xt)<<21,e<z)||(e=r.get(t+4),n+=(e&xt)*Ko,e<z)||(e=r.get(t+5),n+=(e&xt)*zo,e<z)||(e=r.get(t+6),n+=(e&xt)*Vo,e<z)||(e=r.get(t+7),n+=(e&xt)*Wo,e<z))return n;throw new RangeError("Could not decode varint")}function On(r,t,e=0){return t==null&&(t=wt(J(r))),t instanceof Uint8Array?or(r,t,e):Rh(r,t,e)}function De(r,t=0){return r instanceof Uint8Array?Go(r,t):Oh(r,t)}var Yo=new Float32Array([-0]),ge=new Uint8Array(Yo.buffer);function Kc(r,t,e){Yo[0]=r,t[e]=ge[0],t[e+1]=ge[1],t[e+2]=ge[2],t[e+3]=ge[3]}function zc(r,t){return ge[0]=r[t],ge[1]=r[t+1],ge[2]=r[t+2],ge[3]=r[t+3],Yo[0]}var jo=new Float64Array([-0]),Et=new Uint8Array(jo.buffer);function Vc(r,t,e){jo[0]=r,t[e]=Et[0],t[e+1]=Et[1],t[e+2]=Et[2],t[e+3]=Et[3],t[e+4]=Et[4],t[e+5]=Et[5],t[e+6]=Et[6],t[e+7]=Et[7]}function Wc(r,t){return Et[0]=r[t],Et[1]=r[t+1],Et[2]=r[t+2],Et[3]=r[t+3],Et[4]=r[t+4],Et[5]=r[t+5],Et[6]=r[t+6],Et[7]=r[t+7],jo[0]}var Nh=BigInt(Number.MAX_SAFE_INTEGER),Uh=BigInt(Number.MIN_SAFE_INTEGER),Dt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Le;if(t<Nh&&t>Uh)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>Gc&&(s=0n,++n>Gc&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return Le;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):Le}},Le=new Dt(0,0);Le.toBigInt=function(){return 0n};Le.zzEncode=Le.zzDecode=function(){return this};Le.length=function(){return 1};var Gc=4294967296n;function Zc(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Yc(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Xo(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function Rt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Nn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Qo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Rt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Rt(this,4);return Nn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Rt(this,4);return Nn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Rt(this,4);let t=zc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Rt(this,4);let t=Wc(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Rt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Yc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Rt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Rt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Dt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Rt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Rt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Rt(this,8);let t=Nn(this.buf,this.pos+=4),e=Nn(this.buf,this.pos+=4);return new Dt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Go(this.buf,this.pos);return this.pos+=J(t),t}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 Fr(r){return new Qo(r instanceof Uint8Array?r:r.subarray())}function zt(r,t,e){let n=Fr(r);return t.decode(n,void 0,e)}function Jo(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return wt(i);s+i>t&&(n=wt(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Ce=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ti(){}var ri=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Mh=Jo();function Fh(r){return globalThis.Buffer!=null?wt(r):Mh(r)}var $r=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ce(ti,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ce(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ni((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Un,10,Dt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Dt.fromBigInt(t);return this._push(Un,e.length(),e)}uint64Number(t){return this._push(or,J(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Dt.fromBigInt(t).zzEncode();return this._push(Un,e.length(),e)}sint64Number(t){let e=Dt.fromNumber(t).zzEncode();return this._push(Un,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ei,1,t?1:0)}fixed32(t){return this._push(Hr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Dt.fromBigInt(t);return this._push(Hr,4,e.lo)._push(Hr,4,e.hi)}fixed64Number(t){let e=Dt.fromNumber(t);return this._push(Hr,4,e.lo)._push(Hr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Kc,4,t)}double(t){return this._push(Vc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ei,1,0):this.uint32(e)._push($h,e,t)}string(t){let e=Zc(t);return e!==0?this.uint32(e)._push(Xo,e,t):this._push(ei,1,0)}fork(){return this.states=new ri(this),this.head=this.tail=new Ce(ti,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 Ce(ti,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Fh(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ei(r,t,e){t[e]=r&255}function Hh(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ni=class extends Ce{next;constructor(t,e){super(Hh,t,e),this.next=void 0}};function Un(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Hr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function $h(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&($r.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(qh,t,r),this},$r.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Kh,t,r),this});function qh(r,t,e){t.set(r,e)}function Kh(r,t,e){r.length<40?Xo(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Z(r),e)}function si(){return new $r}function Vt(r,t){let e=si();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*Wt(r,t,e){let n=Fr(r);yield*t.stream(n,void 0,"$",e)}var Mn={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Fn(r,t,e,n,s){return{name:r,type:t,encode:e,decode:n,stream:s}}function ir(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},s=function*(i){let a=i.int32();yield t(a)};return Fn("enum",Mn.VARINT,e,n,s)}function Gt(r,t,e){return Fn("message",Mn.LENGTH_DELIMITED,r,t,e)}var ne=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var St;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(St||(St={}));var oi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(oi||(oi={}));(function(r){r.codec=()=>ir(oi)})(St||(St={}));var qr;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),St.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(qr||(qr={}));var ii;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),St.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(ii||(ii={}));var Hn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(Sn(t),U(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(e.length>n?t.create().update(e).digest():e);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Qt(s)}update(t){return Qe(this),this.iHash.update(t),this}digestInto(t){Qe(this),U(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return t=t,t.finished=s,t.destroyed=o,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ai=(r,t,e)=>new Hn(r,t).update(e).digest();ai.create=(r,t)=>new Hn(r,t);var Xc=(r,t)=>(r+(r>=0?t:-t)/Qc)/t;function Vh(r,t,e){let[[n,s],[o,i]]=t,a=Xc(i*r,e),c=Xc(-s*r,e),l=r-a*n-c*o,u=-a*s-c*i,h=l<se,f=u<se;h&&(l=-l),f&&(u=-u);let p=Nr(Math.ceil(Lo(e)/2))+ar;if(l<se||l>=p||u<se||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:f,k2:u}}function li(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ci(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return re(e.lowS,"lowS"),re(e.prehash,"prehash"),e.format!==void 0&&li(e.format),e}var ui=class extends Error{constructor(t=""){super(t)}},be={Err:ui,_tlv:{encode:(r,t)=>{let{Err:e}=be;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,s=Rr(n);if(s.length/2&128)throw new e("tlv.encode: long form length too big");let o=n>127?Rr(s.length/2|128):"";return Rr(r)+o+s+t},decode(r,t){let{Err:e}=be,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let s=t[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=be;if(r<se)throw new t("integer: negative integers are not allowed");let e=Rr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=be;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return tr(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=be,s=U(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=be,n=t.encode(2,e.encode(r.r)),s=t.encode(2,e.encode(r.s)),o=n+s;return t.encode(48,o)}},se=BigInt(0),ar=BigInt(1),Qc=BigInt(2),$n=BigInt(3),Wh=BigInt(4);function Jc(r,t={}){let e=Ln("weierstrass",r,t),{Fp:n,Fn:s}=e,o=e.CURVE,{h:i,n:a}=o;pe(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=el(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(L,g,b){let{x:m,y:S}=g.toAffine(),T=n.toBytes(m);if(re(b,"isCompressed"),b){u();let D=!n.isOdd(S);return It(tl(D),T)}else return It(Uint8Array.of(4),T,n.toBytes(S))}function f(L){U(L,void 0,"Point");let{publicKey:g,publicKeyUncompressed:b}=l,m=L.length,S=L[0],T=L.subarray(1);if(m===g&&(S===2||S===3)){let D=n.fromBytes(T);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");let C=_(D),k;try{k=n.sqrt(C)}catch(rt){let X=rt instanceof Error?": "+rt.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}u();let P=n.isOdd(k);return(S&1)===1!==P&&(k=n.neg(k)),{x:D,y:k}}else if(m===b&&S===4){let D=n.BYTES,C=n.fromBytes(T.subarray(0,D)),k=n.fromBytes(T.subarray(D,D*2));if(!w(C,k))throw new Error("bad point: is not on curve");return{x:C,y:k}}else throw new Error(`bad point: got length ${m}, expected compressed=${g} or uncompressed=${b}`)}let p=t.toBytes||h,d=t.fromBytes||f;function _(L){let g=n.sqr(L),b=n.mul(g,L);return n.add(n.add(b,n.mul(L,o.a)),o.b)}function w(L,g){let b=n.sqr(g),m=_(L);return n.eql(b,m)}if(!w(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(o.a,$n),Wh),I=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(y,I)))throw new Error("bad curve params: a or b");function x(L,g,b=!1){if(!n.isValid(g)||b&&n.is0(g))throw new Error(`bad point coordinate ${L}`);return g}function A(L){if(!(L instanceof E))throw new Error("Weierstrass Point expected")}function R(L){if(!c||!c.basises)throw new Error("no endo");return Vh(L,c.basises,s.ORDER)}let M=er((L,g)=>{let{X:b,Y:m,Z:S}=L;if(n.eql(S,n.ONE))return{x:b,y:m};let T=L.is0();g==null&&(g=T?n.ONE:n.inv(S));let D=n.mul(b,g),C=n.mul(m,g),k=n.mul(S,g);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(k,n.ONE))throw new Error("invZ was invalid");return{x:D,y:C}}),F=er(L=>{if(L.is0()){if(t.allowInfinityPoint&&!n.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:g,y:b}=L.toAffine();if(!n.isValid(g)||!n.isValid(b))throw new Error("bad point: x or y not field elements");if(!w(g,b))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(L,g,b,m,S){return b=new E(n.mul(b.X,L),b.Y,b.Z),g=Mr(m,g),b=Mr(S,b),g.add(b)}class E{static BASE=new E(o.Gx,o.Gy,n.ONE);static ZERO=new E(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(g,b,m){this.X=x("x",g),this.Y=x("y",b,!0),this.Z=x("z",m),Object.freeze(this)}static CURVE(){return o}static fromAffine(g){let{x:b,y:m}=g||{};if(!g||!n.isValid(b)||!n.isValid(m))throw new Error("invalid affine point");if(g instanceof E)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(m)?E.ZERO:new E(b,m,n.ONE)}static fromBytes(g){let b=E.fromAffine(d(U(g,void 0,"point")));return b.assertValidity(),b}static fromHex(g){return E.fromBytes(te(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){return H.createCache(this,g),b||this.multiply($n),this}assertValidity(){F(this)}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){A(g);let{X:b,Y:m,Z:S}=this,{X:T,Y:D,Z:C}=g,k=n.eql(n.mul(b,C),n.mul(T,S)),P=n.eql(n.mul(m,C),n.mul(D,S));return k&&P}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b}=o,m=n.mul(b,$n),{X:S,Y:T,Z:D}=this,C=n.ZERO,k=n.ZERO,P=n.ZERO,N=n.mul(S,S),rt=n.mul(T,T),X=n.mul(D,D),q=n.mul(S,T);return q=n.add(q,q),P=n.mul(S,D),P=n.add(P,P),C=n.mul(g,P),k=n.mul(m,X),k=n.add(C,k),C=n.sub(rt,k),k=n.add(rt,k),k=n.mul(C,k),C=n.mul(q,C),P=n.mul(m,P),X=n.mul(g,X),q=n.sub(N,X),q=n.mul(g,q),q=n.add(q,P),P=n.add(N,N),N=n.add(P,N),N=n.add(N,X),N=n.mul(N,q),k=n.add(k,N),X=n.mul(T,D),X=n.add(X,X),N=n.mul(X,q),C=n.sub(C,N),P=n.mul(X,rt),P=n.add(P,P),P=n.add(P,P),new E(C,k,P)}add(g){A(g);let{X:b,Y:m,Z:S}=this,{X:T,Y:D,Z:C}=g,k=n.ZERO,P=n.ZERO,N=n.ZERO,rt=o.a,X=n.mul(o.b,$n),q=n.mul(b,T),nt=n.mul(m,D),pt=n.mul(S,C),Ht=n.add(b,m),st=n.add(T,D);Ht=n.mul(Ht,st),st=n.add(q,nt),Ht=n.sub(Ht,st),st=n.add(b,S);let bt=n.add(T,C);return st=n.mul(st,bt),bt=n.add(q,pt),st=n.sub(st,bt),bt=n.add(m,S),k=n.add(D,C),bt=n.mul(bt,k),k=n.add(nt,pt),bt=n.sub(bt,k),N=n.mul(rt,st),k=n.mul(X,pt),N=n.add(k,N),k=n.sub(nt,N),N=n.add(nt,N),P=n.mul(k,N),nt=n.add(q,q),nt=n.add(nt,q),pt=n.mul(rt,pt),st=n.mul(X,st),nt=n.add(nt,pt),pt=n.sub(q,pt),pt=n.mul(rt,pt),st=n.add(st,pt),q=n.mul(nt,st),P=n.add(P,q),q=n.mul(bt,st),k=n.mul(Ht,k),k=n.sub(k,q),q=n.mul(Ht,nt),N=n.mul(bt,N),N=n.add(N,q),new E(k,P,N)}subtract(g){return this.add(g.negate())}is0(){return this.equals(E.ZERO)}multiply(g){let{endo:b}=t;if(!s.isValidNot0(g))throw new Error("invalid scalar: out of range");let m,S,T=D=>H.cached(this,D,C=>ke(E,C));if(b){let{k1neg:D,k1:C,k2neg:k,k2:P}=R(g),{p:N,f:rt}=T(C),{p:X,f:q}=T(P);S=rt.add(q),m=v(b.beta,N,X,D,k)}else{let{p:D,f:C}=T(g);m=D,S=C}return ke(E,[m,S])[0]}multiplyUnsafe(g){let{endo:b}=t,m=this;if(!s.isValid(g))throw new Error("invalid scalar: out of range");if(g===se||m.is0())return E.ZERO;if(g===ar)return m;if(H.hasCache(this))return this.multiply(g);if(b){let{k1neg:S,k1:T,k2neg:D,k2:C}=R(g),{p1:k,p2:P}=Rc(E,m,T,C);return v(b.beta,k,P,S,D)}else return H.unsafe(m,g)}toAffine(g){return M(this,g)}isTorsionFree(){let{isTorsionFree:g}=t;return i===ar?!0:g?g(E,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=t;return i===ar?this:g?g(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return re(g,"isCompressed"),this.assertValidity(),p(E,this,g)}toHex(g=!0){return Jt(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let O=s.BITS,H=new sr(E,t.endo?Math.ceil(O/2):O);return E.BASE.precompute(8),E}function tl(r){return Uint8Array.of(r?2:3)}function el(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Gh(r,t={}){let{Fn:e}=r,n=t.randomBytes||Je,s=Object.assign(el(r.Fp,e),{seed:Ro(e.ORDER)});function o(p){try{let d=e.fromBytes(p);return e.isValidNot0(d)}catch{return!1}}function i(p,d){let{publicKey:_,publicKeyUncompressed:w}=s;try{let y=p.length;return d===!0&&y!==_||d===!1&&y!==w?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(s.seed)){return Oo(U(p,s.seed,"seed"),e.ORDER)}function c(p,d=!0){return r.BASE.multiply(e.fromBytes(p)).toBytes(d)}function l(p){let{secretKey:d,publicKey:_,publicKeyUncompressed:w}=s;if(!ve(p)||"_lengths"in e&&e._lengths||d===_)return;let y=U(p,void 0,"key").length;return y===_||y===w}function u(p,d,_=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");let w=e.fromBytes(p);return r.fromBytes(d).multiply(w).toBytes(_)}let h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},f=Cn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:h,lengths:s})}function rl(r,t,e={}){Sn(t),pe(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let n=e.randomBytes||Je,s=e.hmac||((b,m)=>ai(t,b,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p}=Gh(r,e),d={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},_=a*Qc<o.ORDER;function w(b){let m=a>>ar;return b>m}function y(b,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${b}: out of range 1..Point.Fn.ORDER`);return m}function I(){if(_)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(b,m){li(m);let S=p.signature,T=m==="compact"?S:m==="recovered"?S+1:void 0;return U(b,T)}class A{r;s;recovery;constructor(m,S,T){if(this.r=y("r",m),this.s=y("s",S),T!=null){if(I(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(m,S=d.format){x(m,S);let T;if(S==="der"){let{r:P,s:N}=be.toSig(U(m));return new A(P,N)}S==="recovered"&&(T=m[0],S="compact",m=m.subarray(1));let D=p.signature/2,C=m.subarray(0,D),k=m.subarray(D,D*2);return new A(i.fromBytes(C),i.fromBytes(k),T)}static fromHex(m,S){return this.fromBytes(te(m),S)}assertRecovery(){let{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new A(this.r,this.s,m)}recoverPublicKey(m){let{r:S,s:T}=this,D=this.assertRecovery(),C=D===2||D===3?S+a:S;if(!o.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let k=o.toBytes(C),P=r.fromBytes(It(tl((D&1)===0),k)),N=i.inv(C),rt=M(U(m,void 0,"msgHash")),X=i.create(-rt*N),q=i.create(T*N),nt=r.BASE.multiplyUnsafe(X).add(P.multiplyUnsafe(q));if(nt.is0())throw new Error("invalid recovery: point at infinify");return nt.assertValidity(),nt}hasHighS(){return w(this.s)}toBytes(m=d.format){if(li(m),m==="der")return te(be.hexFromSig(this));let{r:S,s:T}=this,D=i.toBytes(S),C=i.toBytes(T);return m==="recovered"?(I(),It(Uint8Array.of(this.assertRecovery()),D,C)):It(D,C)}toHex(m){return Jt(this.toBytes(m))}}let R=e.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");let S=tr(m),T=m.length*8-c;return T>0?S>>BigInt(T):S},M=e.bits2int_modN||function(m){return i.create(R(m))},F=Nr(c);function v(b){return Or("num < 2^"+c,b,se,F),i.toBytes(b)}function E(b,m){return U(b,void 0,"message"),m?U(t(b),void 0,"prehashed message"):b}function O(b,m,S){let{lowS:T,prehash:D,extraEntropy:C}=ci(S,d);b=E(b,D);let k=M(b),P=i.fromBytes(m);if(!i.isValidNot0(P))throw new Error("invalid private key");let N=[v(P),v(k)];if(C!=null&&C!==!1){let nt=C===!0?n(p.secretKey):C;N.push(U(nt,void 0,"extraEntropy"))}let rt=It(...N),X=k;function q(nt){let pt=R(nt);if(!i.isValidNot0(pt))return;let Ht=i.inv(pt),st=r.BASE.multiply(pt).toAffine(),bt=i.create(st.x);if(bt===se)return;let an=i.create(Ht*i.create(X+bt*P));if(an===se)return;let ba=(st.x===bt?0:2)|Number(st.y&ar),ya=an;return T&&w(an)&&(ya=i.neg(an),ba^=1),new A(bt,ya,_?void 0:ba)}return{seed:rt,k2sig:q}}function H(b,m,S={}){let{seed:T,k2sig:D}=O(b,m,S);return bc(t.outputLen,i.BYTES,s)(T,D).toBytes(S.format)}function L(b,m,S,T={}){let{lowS:D,prehash:C,format:k}=ci(T,d);if(S=U(S,void 0,"publicKey"),m=E(m,C),!ve(b)){let P=b instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}x(b,k);try{let P=A.fromBytes(b,k),N=r.fromBytes(S);if(D&&P.hasHighS())return!1;let{r:rt,s:X}=P,q=M(m),nt=i.inv(X),pt=i.create(q*nt),Ht=i.create(rt*nt),st=r.BASE.multiplyUnsafe(pt).add(N.multiplyUnsafe(Ht));return st.is0()?!1:i.create(st.x)===rt}catch{return!1}}function g(b,m,S={}){let{prehash:T}=ci(S,d);return m=E(m,T),A.fromBytes(b,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p,Point:r,sign:H,verify:L,recoverPublicKey:g,Signature:A,hash:t})}var hi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Zh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var nl=BigInt(2);function Yh(r){let t=hi.p,e=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,h=Q(u,e,t)*u%t,f=Q(h,e,t)*u%t,p=Q(f,nl,t)*l%t,d=Q(p,s,t)*p%t,_=Q(d,o,t)*d%t,w=Q(_,a,t)*_%t,y=Q(w,c,t)*w%t,I=Q(y,a,t)*_%t,x=Q(I,e,t)*u%t,A=Q(x,i,t)*d%t,R=Q(A,n,t)*l%t,M=Q(R,nl,t);if(!fi.eql(fi.sqr(M),r))throw new Error("Cannot find square root");return M}var fi=rr(hi.p,{sqrt:Yh}),jh=Jc(hi,{Fp:fi,endo:Zh}),cr=rl(jh,dc);function sl(r,t,e,n){let s=ue.digest(e instanceof Uint8Array?e:e.subarray());if(Pn(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),cr.verify(t,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new _r(String(o))});try{return n?.signal?.throwIfAborted(),cr.verify(t,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new _r(String(o))}}var qn=class{type="secp256k1";raw;_key;constructor(t){this._key=il(t),this.raw=ol(this._key)}toMultihash(){return kt.digest(Xe(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return at.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}verify(t,e,n){return sl(this._key,e,t,n)}};function al(r){return new qn(r)}function ol(r){return cr.Point.fromBytes(r).toBytes()}function il(r){try{return cr.Point.fromBytes(r),r}catch(t){throw new un(String(t))}}function cl(r){let{Type:t,Data:e}=qr.decode(r.digest),n=e??new Uint8Array;switch(t){case St.Ed25519:return qc(n);case St.secp256k1:return al(n);case St.ECDSA:return ja(n);default:throw new vr}}function Xe(r){return qr.encode({Type:St[r.type],Data:r.raw})}var di={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},ll={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ul=new globalThis.TextEncoder;function Xh(r,t){let e=di[t],n=ll[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function Qh(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=di[t],s=ll[t],o=r;for(;o.length>0;){let i=ul.encodeInto(o,e);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function pi(r,{size:t=32,utf8Buffer:e}={}){if(!di[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Qh(r,t,e);r=ul.encode(r)}return Xh(r,t)}var Kr={hash:r=>Number(pi(r,{size:32})),hashV:(r,t)=>Jh(Kr.hash(r,t))};function Jh(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),Z(t,"base16")}var mi=64,Ot=class{fp;h;seed;constructor(t,e,n,s=2){if(s>mi)throw new TypeError("Invalid Fingerprint Size");let o=e.hashV(t,n),i=yt(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?ct(this.fp,t.fp):!1}};function Be(r,t){return Math.floor(Math.random()*(t-r))+r}var Pe=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");let e=Be(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var td=500,zr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Kr,this.seed=t.seed??Be(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=Z(t));let e=new Ot(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Pe(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Pe(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[Be(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Pe(this.bucketSize));for(let a=0;a<td;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Pe(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=Z(t));let e=new Ot(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let o=(n^e.hash())%this.filterSize;return this.buckets[o]?.has(e)??!1}remove(t){typeof t=="string"&&(t=Z(t));let e=new Ot(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let o=(n^e.hash())%this.filterSize,i=this.buckets[o]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ed={1:.5,2:.84,4:.95,8:.98};function rd(r=.001){return r>.002?2:r>1e-5?4:8}function fl(r,t=.001){let e=rd(t),n=ed[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),mi);return{filterSize:s,bucketSize:e,fingerprintSize:o}}var Kn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Kr,this.seed=t.seed??Be(0,Math.pow(2,10)),this.filterSeries=[new zr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=Z(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new zr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=Z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=Z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function zn(r,t=.001,e){return new Kn({...fl(r,t),...e??{}})}function Vn(r){let t=r.getComponents(),e={},n=0;if(t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n].name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null)throw new Tt(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e}var Wn=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=t,o+=u,o>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return e.set(o.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var nd=45,sd=15,Gn=new Wn;function hl(r){if(!(r.length>sd))return Gn.new(r).parseWith(()=>Gn.readIPv4Addr())}function dl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>nd))return Gn.new(r).parseWith(()=>Gn.readIPv6Addr())}function lr(r){return!!hl(r)}function Zn(r){return!!dl(r)}var bl=xa(gl(),1),fd=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],hd=fd.map(r=>new bl.Netmask(r));function vi(r){for(let t of hd)if(t.contains(r))return!0;return!1}function dd(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function pd(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return vi(s)}function md(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function gd(r){let t=r.split(":"),e=t[t.length-1];return vi(e)}function bd(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function yl(r){if(lr(r))return vi(r);if(dd(r))return pd(r);if(md(r))return gd(r);if(Zn(r))return bd(r)}function wl(r){try{let t=Vn(r);switch(t.type){case"ip4":case"ip6":return yl(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function Nt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var jn=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},dr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new jn(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new jn(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var _i=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Xn(r={}){return yd(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function yd(r,t){t=t??{};let e=t.onEnd,n=new dr,s,o,i,a=Nt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,y)=>{o=I=>{o=null,n.push(I);try{w(r(n))}catch(x){y(x)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Nt()})}},l=w=>o!=null?o(w):(n.push(w),s),u=w=>(n=new dr,o!=null?o({error:w}):(n.push({error:w}),s)),h=w=>{if(i)return s;if(t?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},f=w=>i?s:(i=!0,w!=null?u(w):l({done:!0})),p=()=>(n=new dr,f(),{done:!0}),d=w=>(f(w),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:h,end:f,get readableLength(){return n.size},onEmpty:async w=>{let y=w?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let I,x;y!=null&&(I=new Promise((A,R)=>{x=()=>{R(new _i)},y.addEventListener("abort",x)}));try{await Promise.race([a.promise,I])}finally{x!=null&&y!=null&&y?.removeEventListener("abort",x)}}},e==null)return s;let _=s;return s={[Symbol.asyncIterator](){return this},next(){return _.next()},throw(w){return _.throw(w),e!=null&&(e(w),e=void 0),{done:!0}},return(){return _.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(w){return _.end(w),e!=null&&(e(w),e=void 0),s},get readableLength(){return _.readableLength},onEmpty:w=>_.onEmpty(w)},s}var Si=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},xl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Ii(r,t){let{milliseconds:e,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=t,a,c,u=new Promise((h,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){f(xl(i));return}if(i&&(c=()=>{f(xl(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,f),e===Number.POSITIVE_INFINITY)return;let p=new Si;a=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?h():s instanceof Error?f(s):(p.message=s??`Promise timed out after ${e} milliseconds`,f(p))},e)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var wd=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function xd(r,t,e){let n,s=new Promise((o,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=wd(r),h=async(...p)=>{let d=e.multiArgs?p:p[0];if(e.filter)try{if(!await e.filter(d))return}catch(_){n(),i(_);return}c.push(d),e.count===c.length&&(n(),o(c))},f=(...p)=>{n(),i(e.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,h);for(let p of e.rejectionEvents)a.includes(p)||u(p,f)};for(let p of a)l(p,h);for(let p of e.rejectionEvents)a.includes(p)||l(p,f);e.signal&&e.signal.addEventListener("abort",()=>{f(e.signal.reason)},{once:!0}),e.resolveImmediately&&o(c)});if(s.cancel=n,typeof e.timeout=="number"){let o=Ii(s,{milliseconds:e.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Qn(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=xd(r,t,e),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Ai(r,t){let e,n=function(){let s=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(s,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Jn=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function Ed(r){return r.reason}async function ts(r,t,e){if(t==null)return r;let n=e?.translateError??Ed;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(t))},t.addEventListener("abort",s)})])}finally{s!=null&&t.removeEventListener("abort",s)}}var es=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Nt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Bt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function vd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var rs=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=vd(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Bt),this.cleanup())}async join(t={}){let e=new es(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await ts(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var pr=class extends $t{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Ai(this.emitEmpty.bind(this),1),this.emitIdle=Ai(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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Jn;let n=new rs(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Bt)}),this.clear()}async onEmpty(t){this.size!==0&&await Qn(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Qn(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Qn(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Xn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Bt("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var gt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},oe=class extends Error{static name="ValidationError";name="ValidationError"},ns=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ss=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function ki(r){return t=>W(t,r)}function Di(r){return t=>Z(t,r)}function mr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Oe(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function El(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Z(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Oe(n);return Ct([e,s],e.length+s.length)}function vl(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=le.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Oe(n);return Ct([e,s],e.length+s.length)}function Li(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=W(t,"base32"),s=mr(e);return`${n}:${s}`}var Ci=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let s=parseInt(e,10);if(isNaN(s)||s<0||s>255)throw new gt("Invalid byte value in IP address");t[n]=s}),t},_l=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=lr(e[n]),i;o&&(i=Ci(e[n]),e[n]=W(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,W(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let o=parseInt(e[n],16);if(isNaN(o)||o<0||o>65535)throw new gt("Invalid byte value in IP address");s[t++]=o>>8&255,s[t++]=o&255}return s},Sl=function(r){if(r.byteLength!==4)throw new gt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Il=function(r){if(r.byteLength!==16)throw new gt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${e}"`)}};function Al(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${r}"`)}}var Ti=Object.values(kr).map(r=>r.decoder),_d=(function(){let r=Ti[0].or(Ti[1]);return Ti.slice(2).forEach(t=>r=r.or(t)),r})();function Tl(r){return _d.decode(r)}function kl(r){return t=>r.encoder.encode(t)}function Sd(r){if(parseInt(r).toString()!==r)throw new oe("Value must be an integer")}function Id(r){if(r<0)throw new oe("Value must be a positive integer, or zero")}function Ad(r){return t=>{if(t>r)throw new oe(`Value must be smaller than or equal to ${r}`)}}function Td(...r){return t=>{for(let e of r)e(t)}}var Vr=Td(Sd,Id,Ad(65535));var dt=-1,Bi=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new ss(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},ie=new Bi,$d=[{code:4,name:"ip4",size:32,valueToBytes:Ci,bytesToValue:Sl,validate:r=>{if(!lr(r))throw new oe(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Oe,bytesToValue:mr,validate:Vr},{code:273,name:"udp",size:16,valueToBytes:Oe,bytesToValue:mr,validate:Vr},{code:33,name:"dccp",size:16,valueToBytes:Oe,bytesToValue:mr,validate:Vr},{code:41,name:"ip6",size:128,valueToBytes:_l,bytesToValue:Il,stringToValue:Al,validate:r=>{if(!Zn(r))throw new oe(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:dt},{code:43,name:"ipcidr",size:8,bytesToValue:ki("base10"),valueToBytes:Di("base10")},{code:53,name:"dns",size:dt},{code:54,name:"dns4",size:dt},{code:55,name:"dns6",size:dt},{code:56,name:"dnsaddr",size:dt},{code:132,name:"sctp",size:16,valueToBytes:Oe,bytesToValue:mr,validate:Vr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:dt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:dt,bytesToValue:ki("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Di("base58btc")(r):et.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Li,valueToBytes:El},{code:445,name:"onion3",size:296,bytesToValue:Li,valueToBytes:vl},{code:446,name:"garlic64",size:dt},{code:447,name:"garlic32",size:dt},{code:448,name:"tls"},{code:449,name:"sni",size:dt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:dt,bytesToValue:kl(so),valueToBytes:Tl},{code:480,name:"http"},{code:481,name:"http-path",size:dt,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:dt}];$d.forEach(r=>{ie.addProtocol(r)});function Dl(r){let t=[],e=0;for(;e<r.length;){let n=De(r,e),s=ie.getProtocol(n),o=J(n),i=qd(s,r,e+o),a=0;i>0&&s.size===dt&&(a=J(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??W(h)}t.push(l),e+=c}return t}function Ll(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let s=ie.getProtocol(n.code),o=J(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,s.size===dt&&(c=J(a)));let l=new Uint8Array(o+c+a),u=0;or(n.code,l,u),u+=o,i!=null&&(s.size===dt&&(or(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return Ct(e,t)}function Cl(r){if(r.charAt(0)!=="/")throw new gt('String multiaddr must start with "/"');let t=[],e="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(e==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ie.getProtocol(s);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",s="",e="protocol";continue}else if(a)throw new gt(`Component ${s} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new gt(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",s="",e="protocol"}}}if(s!==""&&n!=="")throw new gt("Incomplete multiaddr");return t}function Bl(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=ie.getProtocol(t.code);if(e==null)throw new gt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function qd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:De(t,e)}var Kd=Symbol.for("nodejs.util.inspect.custom"),zi=Symbol.for("@multiformats/multiaddr");function zd(r){if(r==null&&(r="/"),Pl(r))return r.getComponents();if(r instanceof Uint8Array)return Dl(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Cl(r);if(Array.isArray(r))return r;throw new gt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var us=class r{[zi]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=zd(t),e.validate!==!1&&Vd(this)}get bytes(){return this.#r==null&&(this.#r=Ll(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Bl(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new ns(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return ct(this.bytes,t.bytes)}[Kd](){return`Multiaddr(${this.toString()})`}};function Vd(r){r.getComponents().forEach(t=>{let e=ie.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function Pl(r){return!!r?.[zi]}function fs(r){return new us(r)}var hs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},yr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ds=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Xr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ps(r){return r[Symbol.asyncIterator]!=null}function Rl(r,t){if(r.byteLength>t)throw new yr("Message length too long")}var gs=r=>{let t=J(r),e=wt(t);return On(r,e),gs.bytes=t,e};gs.bytes=0;function bs(r,t){t=t??{};let e=t.lengthEncoder??gs,n=t?.maxDataLength??4194304;function*s(o){Rl(o,n);let i=e(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return ps(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}bs.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??gs,n=t?.maxDataLength??4194304;return Rl(r,n),new ut(e(r.byteLength),r)};var Ue;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ue||(Ue={}));var Vi=r=>{let t=De(r);return Vi.bytes=J(t),t};Vi.bytes=0;function Qr(r,t){let e=new ut,n=Ue.LENGTH,s=-1,o=t?.lengthDecoder??Vi,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Ue.LENGTH)try{if(s=o(e),s<0)throw new hs("Invalid message length");if(s>a)throw new yr("Message length too long");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=Ue.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new ds("Message length length too long");break}throw l}if(n===Ue.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=Ue.LENGTH}}}return ps(r)?(async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Xr("Unexpected end of input")})():(function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Xr("Unexpected end of input")})()}Qr.fromReader=(r,t)=>{let e=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}})();return Qr(n,{...t??{},onLength:o=>{e=o}})};var ys=class extends pr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Wi=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ol(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Wi({name:t,metrics:e}):n=new Map,n}function Zd(r){return r[Symbol.asyncIterator]!=null}function Yd(r){if(Zd(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Gi=Yd;function jd(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Nl=jd;function Xd(r){return r[Symbol.asyncIterator]!=null}function Qd(r,t){let e=0;if(Xd(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=Nl(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=t(s,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var Ul=Qd;function Jd(r){return r[Symbol.asyncIterator]!=null}function tp(r,t){return Jd(r)?(async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}})():(function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}})()}var Ml=tp;var ws=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Me(r,t,e,n){let s=new ws(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Yi(e,"abort",h),Yi(r,t,l),Yi(r,o,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(p){c(),a(p);return}c(),i(f)},u=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.`))},h=()=>{c(),a(s)};Zi(e,"abort",h),Zi(r,t,l),Zi(r,o,u)})}function Zi(r,t,e){r!=null&&(Fl(r)?r.addEventListener(t,e):r.addListener(t,e))}function Yi(r,t,e){r!=null&&(Fl(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function Fl(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Jr="/ipfs/bitswap/1.2.0";var tt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(tt||(tt={}));var ji;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ji||(ji={}));(function(r){r.codec=()=>ir(ji)})(tt||(tt={}));var Fe;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.priority!=null&&o.priority!==0&&(i.uint32(16),i.int32(o.priority)),o.cancel!=null&&(i.uint32(24),i.bool(o.cancel)),o.wantType!=null&&(i.uint32(32),tt.codec().encode(o.wantType,i)),o.sendDontHave!=null&&(i.uint32(40),i.bool(o.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:yt(0),priority:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.priority=o.int32();break}case 3:{c.cancel=o.bool();break}case 4:{c.wantType=tt.codec().decode(o);break}case 5:{c.sendDontHave=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.priority`,value:o.int32()};break}case 3:{yield{field:`${a}.cancel`,value:o.bool()};break}case 4:{yield{field:`${a}.wantType`,value:tt.codec().decode(o)};break}case 5:{yield{field:`${a}.sendDontHave`,value:o.bool()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(Fe||(Fe={}));var tn;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.entries!=null&&o.entries.length>0)for(let c of o.entries)i.uint32(10),Fe.codec().encode(c,i);o.full!=null&&(i.uint32(16),i.bool(o.full)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={entries:[]},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new ne('Decode error - repeated field "entries" had too many elements');c.entries.push(Fe.codec().decode(o,o.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={entries:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let h=o.uint32();switch(h>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new ne('Streaming decode error - repeated field "entries" had too many elements');for(let f of Fe.codec().stream(o,o.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...f,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:o.bool()};break}default:{o.skipType(h&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(tn||(tn={}));var He;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.prefix!=null&&o.prefix.byteLength>0&&(i.uint32(10),i.bytes(o.prefix)),o.data!=null&&o.data.byteLength>0&&(i.uint32(18),i.bytes(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={prefix:yt(0),data:yt(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.prefix=o.bytes();break}case 2:{c.data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:o.bytes()};break}case 2:{yield{field:`${a}.data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(He||(He={}));var Lt;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Lt||(Lt={}));var xs;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(xs||(xs={}));(function(r){r.codec=()=>ir(xs)})(Lt||(Lt={}));var $e;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.type!=null&&xs[o.type]!==0&&(i.uint32(16),Lt.codec().encode(o.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:yt(0),type:Lt.HaveBlock},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.type=Lt.codec().decode(o);break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.type`,value:Lt.codec().decode(o)};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})($e||($e={}));var qe;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.wantlist!=null&&(i.uint32(10),tn.codec().encode(o.wantlist,i)),o.blocks!=null&&o.blocks.length>0)for(let c of o.blocks)i.uint32(26),He.codec().encode(c,i);if(o.blockPresences!=null&&o.blockPresences.length>0)for(let c of o.blockPresences)i.uint32(34),$e.codec().encode(c,i);o.pendingBytes!=null&&o.pendingBytes!==0&&(i.uint32(40),i.int32(o.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.wantlist=tn.codec().decode(o,o.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new ne('Decode error - repeated field "blocks" had too many elements');c.blocks.push(He.codec().decode(o,o.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new ne('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push($e.codec().decode(o,o.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=o.int32();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={blocks:0,blockPresences:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let h=o.uint32();switch(h>>>3){case 1:{yield*tn.codec().stream(o,o.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new ne('Streaming decode error - repeated field "blocks" had too many elements');for(let f of He.codec().stream(o,o.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...f,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new ne('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of $e.codec().stream(o,o.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...f,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:o.int32()};break}default:{o.skipType(h&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(qe||(qe={}));function Hl(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var Es=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var ep=4193648,rp=ep+16;function*$l(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=qe.encode(l).byteLength,{added:h,hasMore:f,newSize:p}=Xi(s,l.blocks,a,t,u,np);a+=h,u=p;let d=f;({added:h,hasMore:f,newSize:p}=Xi(n,l.blockPresences,i,t,u,sp)),i+=h,u=p;let _=f;if({added:h,hasMore:f,newSize:p}=Xi(e,l.wantlist.entries,o,t,u,op),o+=h,u=p,c=!d&&!_&&!f,c||(l.wantlist.full=!1),yield qe.encode(l),c)break}}function Xi(r,t,e,n,s,o){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=o(l);if(u>rp)throw new Es("Cannot send block as after encoding it is over the max message size");let h=s+u;if(h>n){a=!0;break}t.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function np(r){return Qi(3,He.encode(r))}function sp(r){return Qi(4,$e.encode(r))}function op(r){return Qi(1,Fe.encode(r))}function Qi(r,t){let e=J(r),n=J(t.byteLength);return e+n+t.byteLength}var vs=class extends $t{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[Jr],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??1e4,this.messageSendTimeout=e.messageSendTimeout??1e4,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new ys({concurrency:e.messageSendConcurrency??50,metrics:t.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 t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t,e){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,e.remotePeer);let n=()=>{t.status==="open"?t.abort(new pn(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",t.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);s.addEventListener("abort",n),await t.close({signal:s});let o=Xn();t.addEventListener("message",i=>{o.push(i.data)}),t.addEventListener("remoteCloseWrite",()=>{o.end()}),t.addEventListener("close",i=>{i.error!=null&&o.end(i.error)});for await(let i of Qr(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=qe.decode(i);this.log("incoming new bitswap %s message from %p on stream",t.protocol,e.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:e.remotePeer,message:a,connection:e}}),s.removeEventListener("abort",n),s=AbortSignal.timeout(this.messageReceiveTimeout),s.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",e.remotePeer,t.id,a),t.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",e.remotePeer,n),t.abort(n)})}async*findProviders(t,e){e?.onProgress?.(new V("bitswap:find-providers",t));for await(let n of this.routing.findProviders(t,e)){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}e?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:n,routing:n.routing})),yield n}}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Gi(Ul(Ml(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>t.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=Hl(s.options.message,e),await s.join(n);return}await this.sendQueue.add(async o=>{let i=o.message;if(i==null)throw new Tt("No message to send");this.log("sendMessage to %p",t),o.onProgress?.(new V("bitswap:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,Jr,o);await a.closeRead(o);try{for(let c of $l(i,this.maxOutgoingMessageSize))a.send(bs.single(c))||await a.onDrain(o);await a.close(o)}catch(c){this.log.error("error sending message to %p - %e",t,c),o?.onProgress?.(new V("bitswap:send-wantlist:error",{peer:t,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:t,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:e})}async connectTo(t,e){if(!this.running)throw new mn("Network isn't running");e?.onProgress?.(new V("bitswap:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Me(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(Jr))return!0;throw new dn(`${t} did not support ${Jr}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};var Kl=Symbol.for("nodejs.util.inspect.custom"),mp=114,en=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[gn]=!0;toString(){return this.string==null&&(this.string=at.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return et.createV1(mp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ct(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ct(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Kl](){return`PeerId(${this.toString()})`}},_s=class extends en{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Ss=class extends en{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Is=class extends en{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},gp=2336,rn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=kt.digest(Z(this.url))}[Kl](){return`PeerId(${this.url})`}[gn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return et.createV1(gp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=W(t)),t.toString()===this.toString())}};var bp=114,zl=2336;function yp(r){if(xp(r))return new _s({multihash:r});if(wp(r))try{let t=cl(r);if(t.type==="Ed25519")return new Ss({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Is({multihash:r,publicKey:t})}catch{let e=W(r.digest);return new rn(new URL(e))}throw new hn("Supplied PeerID Multihash is invalid")}function Vl(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==bp&&r.code!==zl)throw new fn("Supplied PeerID CID is invalid");if(r.code===zl){let t=W(r.multihash.digest);return new rn(new URL(t))}return yp(r.multihash)}function wp(r){return r.code===kt.code}function xp(r){return r.code===ue.code}function As(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var nn=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return As(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return As(this.map.values(),t=>t.key)}values(){return As(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ji=class extends nn{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function sn(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ji({name:t,metrics:e}):n=new nn,n}function Ep(r){return r[Symbol.asyncIterator]!=null}function vp(r){if(Ep(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=Ct([n,s],n.length+s.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return Ct(t,e)}var Wl=vp;var ae=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=jt.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=jt.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=jt.encode(t.multihash.bytes);this.blocks.set(n,e)}};function _p(r){let t=new Uint8Array(r.reduce((n,s)=>n+J(s),0)),e=0;for(let n of r)t=On(n,t,e),e+=J(n);return t}var Gl=_p;function ta(r){return Gl([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Ts=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=e.doNotResendBlockWindow??5e3,this.maxWantListSize=e.maxWantListSize??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((t,e)=>{t.expires!=null&&t.expires<Date.now()&&this.wants.delete(e)})}addWants(t){if(t==null)return;t.full===!0&&this.wants.forEach((n,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of t.entries){let s=et.decode(n.cid),o=W(s.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,s),this.wants.delete(o);else{n.wantType===tt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,s):this.log("peer %p wanted block for %c",this.peerId,s);let i=this.wants.get(o);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===tt.WantHave&&(n.wantType==null||n.wantType===tt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??tt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??tt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let e=[...this.wants.entries()].filter(([n,s])=>s.status==="want");e.length>this.maxWantListSize&&this.truncateWants(e)}truncateWants(t){t=t.sort((n,s)=>n[1].created<s[1].created?-1:s[1].created<n[1].created?1:0).sort((n,s)=>n[1].haveBlock===!1?-1:s[1].haveBlock===!1?1:0).sort((n,s)=>n[1].priority<s[1].priority?-1:s[1].priority<n[1].priority?1:0);let e=t.length-this.maxWantListSize;for(let n=0;n<e;n++)this.wants.delete(t[n][0])}getWants(){return[...this.wants.values()]}hasWant(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async sendBlocksToPeer(t){let e=new ae,n=new Set;this.removeExpiredWants();let s=[...this.wants.entries()].filter(([o,i])=>i.status==="want");s.forEach(([o,i])=>{i.status="sending"});for(let[o,i]of s)try{let a=await Wl(this.blockstore.get(i.cid,t));if(i.status!=="sending")continue;i.wantType===tt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),e.addBlock(i.cid,{data:a,prefix:ta(i.cid)})):(this.log("sending have for %c",i.cid),e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Lt.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),e.addBlock(i.cid,{data:a,prefix:ta(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,e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Lt.DoNotHaveBlock})}(e.blocks.size>0||e.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0)))}};var ks=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=e.doNotResendBlockWindow,this.maxWantListSize=e.maxWantListSize,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=sn({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return e.removeExpiredWants(),e.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);n==null&&(n=new Ts({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(e.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=[];for(let s of this.ledgerMap.values())s.hasWant(t)&&n.push(s);await Promise.all(n.map(async s=>s.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var Ap=xa(Yl(),1);var wr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(wr||(wr={}));var Ds=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Ke=class extends $t{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=zn(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=jt.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s.observers++,s.promise;let o=Nt(),i={promise:o.promise,observers:1,queryFilter:zn(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,l=new pr({concurrency:this.maxProviders});l.addEventListener("failure",f=>{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)}),l.addEventListener("success",f=>{c=!0,o.resolve(f.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.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",t);for(let f=0;f<this.minProviders&&this.providers.length!==0;f++){let p=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(p)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(f=>{this.log.error("could not find new providers for %c - %e",t,f),o.reject(f)})});let u=f=>{let p=this.toFilterKey(f.detail);i.queryFilter.has(p)||(i.queryFilter.add(p),this.emitFoundProviderProgressEvent(t,f.detail,e),l.add(async()=>this.queryProvider(t,f.detail,e),{provider:f.detail}).catch(d=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,d)}))};if(this.addEventListener("provider",u),a)try{await ts(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(f){throw a&&this.log("failed to find initial session peers for %c - %e",t,f),this.requests.delete(n),i.observers>1&&o.reject(f),f}Promise.all([...this.providers].filter(f=>{let p=this.toFilterKey(f),d=i.queryFilter.has(p);return d||i.queryFilter.add(this.toFilterKey(f)),!d}).map(async f=>l.add(async()=>this.queryProvider(t,f,e),{provider:f}))).catch(f=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,f)});let h=()=>{o.reject(new Bt(e.signal?.reason??"Session aborted")),l.abort()};e.signal?.addEventListener("abort",h);try{return await o.promise}finally{this.removeEventListener("provider",u),e.signal?.removeEventListener("abort",h),l.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let s=Nt(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let u=await i.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",o,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),o++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),s.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",o,e,this.providers.length),this.providers.length<e)throw new Ds(`Found ${o} of ${e} ${this.name} providers for ${t}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),s.reject(i)}),s.promise}};var ea=class extends Ke{name="bitswap-session";wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e.peerId,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),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(t,e={}){for await(let n of this.network.findProviders(t,e))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(t){return t.peerId.toMultihash().bytes}equals(t,e){return t.peerId.equals(e.peerId)}async convertToProvider(t,e,n){if(ze(t))return{peerId:t,routing:e,toString:()=>`Bitswap(${t})`};if(await this.libp2p.isDialable(t)!==!1)try{let s=await this.libp2p.dial(t,n);return{peerId:s.remotePeer,routing:e,toString:()=>`Bitswap(${s.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:{id:e.peerId,multiaddrs:[],routing:e.routing},routing:e.routing}))}};function jl(r,t){return new ea(r,t)}var Ls=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};function Lp(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=De(r);t.push(e),r=r.slice(J(e))}return t}var Xl=Lp;var Cs=class extends $t{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(t,e={}){super(),this.peers=sn({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Ol({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendWantlistDebounce=e.sendWantlistDebounce??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=t.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=W(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??tt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,s)),e.onProgress!=null&&s.onProgress.push({onProgress:e.onProgress,signal:e.signal}),s.wantType===tt.WantHave&&e.wantType===tt.WantBlock&&(s.wantType=tt.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===tt.WantBlock?(await Me(this,"block",e?.signal,{filter:a=>ct(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Me(this,"presence",e?.signal,{filter:i=>ct(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers - %e",t)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Nt(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new ae;for(let[o,i]of this.wants.entries())e.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s,{onProgress:o=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(o)})})}});for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer - %e",o)}})).catch(t=>{this.log.error("error sending messages - %e",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new ae;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantHave,priority:1}),await this.network.sendMessage(e,s,n),(await Me(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&ct(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:tt.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new ae;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantBlock,priority:1}),await this.network.sendMessage(e,s,n),(await Me(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&ct(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=W(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t.remotePeer,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=Xl(s.prefix),i=o[0],a=o[1],c=o[2],l=o[3],u=c===ue.code?ue:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let h=u.digest(s.data,{truncate:l});h.then!=null&&(h=await h);let f=et.create(i===0?0:1,a,h);this.log("received block from %p for %c",t.remotePeer,f),this.safeDispatchEvent("block",{detail:{sender:t.remotePeer,cid:f,block:s.data,connection:t}}),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:f,has:!0,block:s.data}});let p=W(f.multihash.bytes,"base64"),d=this.wants.get(p);d!=null&&(d.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=et.decode(s);this.log("received %s from %p for %c",o,t.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:i,has:o===Lt.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new ae(!0);for(let[s,o]of this.wants.entries())o.cancel||(e.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:tt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n,{onProgress:s=>{this.wants.forEach(({onProgress:o})=>{o.forEach(({onProgress:i})=>{i(s)})})}}),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p - %e",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Bs=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new Ls(t),this.network=new vs(t,e),this.peerWantLists=new ks({...t,network:this.network},e),this.wantList=new Cs({...t,network:this.network},e)}createSession(t={}){return jl({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,s=Ea([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",t,o)});try{let o=await this.wantList.wantBlock(t,{...e,signal:s});return e.onProgress?.(new V("bitswap:block",{cid:t,sender:o.connection.remotePeer})),o.block}finally{n.abort(),s.clear()}}async notify(t,e={}){await Promise.all([this.peerWantLists.receivedBlock(t,e),this.wantList.receivedBlock(t,e)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Ql=(r,t={})=>new Bs(r,t);var ra=class{name="bitswap";bitswap;started;constructor(t,e={}){this.bitswap=Ql(t,e),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(t,e){await this.bitswap.notify(t,e)}async retrieve(t,e={}){return this.bitswap.want(t,{...e,onProgress:function(s){if(e?.onProgress!=null)if(e.onProgress(s),s.type==="connection:open"){if(!ze(s.detail))return;e.onProgress(new V("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:s.detail,cid:t}))}else s.type==="connection:opened"?e.onProgress(new V("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:s.detail.remotePeer,address:s.detail.remoteAddr,cid:t})):s.type==="bitswap:send-wantlist"?e.onProgress(new V("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:s.detail,cid:t})):s.type==="bitswap:block"&&e.onProgress(new V("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:s.detail.sender,cid:t}))}})}createSession(t){let e=this.bitswap.createSession(t);return{name:"bitswap-session",addPeer:async(n,s)=>{await e.addPeer(n,s)},announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function Jl(r={}){return t=>new ra(t,r)}var Cp=[6,53,56,54,55];function tu(r){return nu("sni",r)?.value}function eu(r){let t=nu("tcp",r)?.value;return t==null?"":`:${t}`}function nu(r,t){return t.find(e=>e.name===r)}function ru(r){return r.some(({code:t})=>t===448)}function Mt(r,t){let e=su[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var su={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Mt(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${Mt(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Mt(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Mt(e,t)}`},http:(r,t)=>{let e=ru(t),n=tu(t),s=eu(t);if(e&&n!=null)return`https://${n}${s}`;let o=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Mt(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Mt(e,t),s=decodeURIComponent(r.value??"");return`${n}${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Mt(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Mt(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Mt(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=ru(t),n=tu(t),s=eu(t);if(e&&n!=null)return`wss://${n}${s}`;let o=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Mt(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Mt(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Ps(r,t){let n=fs(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=su[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return t?.assumeHttp!==!1&&Cp.includes(s.code)&&(i=i.replace(/^.*:\/\//,""),s.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var ou="[a-fA-F\\d:]",xe=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${ou})|(?<=${ou})(?=\\s|$))`:"",Ft="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",lt="[a-fA-F\\d]{1,4}",Rs=`
|
|
3
3
|
(?:
|
|
4
4
|
(?:${lt}:){7}(?:${lt}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
5
|
-
(?:${lt}:){6}(?:${
|
|
6
|
-
(?:${lt}:){5}(?::${
|
|
7
|
-
(?:${lt}:){4}(?:(?::${lt}){0,1}:${
|
|
8
|
-
(?:${lt}:){3}(?:(?::${lt}){0,2}:${
|
|
9
|
-
(?:${lt}:){2}(?:(?::${lt}){0,3}:${
|
|
10
|
-
(?:${lt}:){1}(?:(?::${lt}){0,4}:${
|
|
11
|
-
(?::(?:(?::${lt}){0,5}:${
|
|
5
|
+
(?:${lt}:){6}(?:${Ft}|:${lt}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
|
|
6
|
+
(?:${lt}:){5}(?::${Ft}|(?::${lt}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
|
|
7
|
+
(?:${lt}:){4}(?:(?::${lt}){0,1}:${Ft}|(?::${lt}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
|
|
8
|
+
(?:${lt}:){3}(?:(?::${lt}){0,2}:${Ft}|(?::${lt}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
|
|
9
|
+
(?:${lt}:){2}(?:(?::${lt}){0,3}:${Ft}|(?::${lt}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
|
|
10
|
+
(?:${lt}:){1}(?:(?::${lt}){0,4}:${Ft}|(?::${lt}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
11
|
+
(?::(?:(?::${lt}){0,5}:${Ft}|(?::${lt}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
12
12
|
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
13
|
-
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),
|
|
13
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Bp=new RegExp(`(?:^${Ft}$)|(?:^${Rs}$)`),Pp=new RegExp(`^${Ft}$`),Rp=new RegExp(`^${Rs}$`),na=r=>r&&r.exact?Bp:new RegExp(`(?:${xe(r)}${Ft}${xe(r)})|(?:${xe(r)}${Rs}${xe(r)})`,"g");na.v4=r=>r&&r.exact?Pp:new RegExp(`${xe(r)}${Ft}${xe(r)}`,"g");na.v6=r=>r&&r.exact?Rp:new RegExp(`${xe(r)}${Rs}${xe(r)}`,"g");var sa=na;function oa(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function iu(){return!1}var{toString:Op}=Object.prototype;function ia(r){return Op.call(r)==="[object RegExp]"}var au={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function aa(r,t={}){if(!ia(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(au).map(s=>(typeof t[s]=="boolean"?t[s]:r[s])?au[s]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function ca(r,t,{timeout:e}={}){try{return oa(()=>aa(r).test(t),{timeout:e})()}catch(n){if(iu(n))return!1;throw n}}var Np=15,Up=45,cu={timeout:400};function la(r){return r.length>Up?!1:ca(sa.v6({exact:!0}),r,cu)}function lu(r){return r.length>Np?!1:ca(sa.v4({exact:!0}),r,cu)}var uu={http:"80",https:"443",ws:"80",wss:"443"},Mp=["http","https","ws","wss"];function fu(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:s,port:o,path:i}=Fp(r),a=[Hp(s,e),$p(o,n),qp(n)];i!=null&&a.push(Kp(i));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return fs(c)}function Fp(r){let[t]=r.split(":");Mp.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:s,pathname:o,search:i}=new URL(r);if(s==null||s===""){let c=zp(t);c!=null&&(s=c),c==null&&e==="http:"&&(s="80")}let a;return o!=null&&o!==""&&o!=="/"&&(o.startsWith("/")&&(o=o.substring(1)),a=o),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:t,hostname:n,port:s,path:a}}function Hp(r,t){if(!(r==null||r==="")){if(lu(r))return["ip4",r];if(la(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(la(e))return["ip6",e]}return[t,r]}}function $p(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function qp(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function Kp(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function zp(r){if(!(r==null||r===""||uu[r]==null))return uu[r]}var Y=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),B=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),hu=r=>({match:t=>r.match(t)===!1?t:!1}),$=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),vt=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1}}),K=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function j(...r){function t(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:r,matches:e,exactMatch:n}}var Vp=B(421),KE=j(Vp),Ns=B(54),Us=B(55),Ms=B(56),fa=B(53),zE=j(Ns,$(B(421))),VE=j(Us,$(B(421))),WE=j(Ms,$(B(421))),du=j(vt(fa,Ms,Ns,Us),$(B(421))),pu=K(B(4),$(B(43))),mu=K($(B(42)),B(41),$(B(43))),ha=vt(pu,mu),xr=vt(ha,fa,Ns,Us,Ms),GE=j(vt(ha,K(vt(fa,Ms,Ns,Us),$(B(421))))),ZE=j(pu),YE=j(mu),jE=j(ha),da=K(xr,B(6)),on=K(xr,B(273)),XE=j(K(da,$(B(421)))),QE=j(on),pa=K(on,Y(460),$(B(421))),Fs=K(on,Y(461),$(B(421))),Wp=vt(pa,Fs),JE=j(pa),tv=j(Fs),ua=vt(xr,da,on,pa,Fs),gu=vt(K(ua,Y(477),$(B(421)))),ev=j(gu),bu=vt(K(ua,Y(478),$(B(421))),K(ua,Y(448),$(B(449)),Y(477),$(B(421)))),rv=j(bu),yu=K(on,Y(280),$(B(466)),$(B(466)),$(B(421))),nv=j(yu),wu=K(Fs,Y(465),$(B(466)),$(B(466)),$(B(421))),sv=j(wu),Os=vt(gu,bu,K(da,$(B(421))),K(Wp,$(B(421))),K(xr,$(B(421))),yu,wu,B(421)),ov=j(Os),Gp=K($(Os),Y(290),hu(Y(281)),$(B(421))),iv=j(Gp),Zp=vt(K(Os,Y(290),Y(281),$(B(421))),K(Os,Y(281),$(B(421))),K(Y(281),$(B(421)))),av=j(Zp),Yp=K(xr,vt(K(B(6,"80")),K(B(6),Y(480)),Y(480)),$(B(481)),$(B(421))),xu=j(Yp),jp=K(xr,vt(K(B(6,"443")),K(B(6,"443"),Y(480)),K(B(6),Y(443)),K(B(6),Y(448),Y(480)),K(Y(448),Y(480)),Y(448),Y(443)),$(B(481)),$(B(421))),Eu=j(jp),Xp=vt(K(B(777),$(B(421)))),cv=j(Xp),Qp=vt(K(B(400),$(B(421)))),lv=j(Qp);function ma(r,t,e){return r.filter(n=>{if(Eu.matches(n)||t&&xu.matches(n))return e||du.matches(n)?!0:wl(n)===!1;if(!t&&e){let{host:s}=Vn(n);if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*Hs(r,t,e,n,s,o={}){for await(let i of t.findProviders(r,o)){let a=ma(i.multiaddrs,n,s);if(a.length===0)continue;let c=new URL(Ps(a[0]));yield new Er(c,{logger:e,transformRequestInit:o.transformRequestInit,routing:i.routing})}}async function vu(r,t,e){let{signal:n,log:s}=e??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>t)throw s?.error("content-length header (%d) is greater than the limit (%d)",c,t),r.body!=null&&await r.body.cancel().catch(l=>{s?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${t}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new ut;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>t)throw new Error(`Response body is greater than the limit (${t}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{s?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var Jp=2336,Er=class{url;peer;#t=0;#e=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;routing;constructor(t,{logger:e,transformRequestInit:n,routing:s}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=s,this.peer=Vl(et.createV1(Jp,kt.digest(Z(this.url.toString()))))}#o(t){let e=t.multihash.bytes;return jt.encode(e)}async getRawBlock(t,e={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${t.toString()}`;let s=e.maxSize??_u;if(n.search="?format=raw",e.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let o=this.#o(t),i=new AbortController,a=()=>{i.abort()};e.signal?.addEventListener("abort",a);try{let c=this.#n.get(o);if(c==null){this.#t++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l,h=new Headers(u.headers);this.log(`sending request
|
|
14
14
|
%s %s HTTP/1.1
|
|
15
15
|
%s
|
|
16
16
|
`,u.method??"GET",n,[...h.entries()].map(([f,p])=>`${f}: ${p}`).join(`
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
HTTP/1.1 %d %s
|
|
19
19
|
%s
|
|
20
20
|
`,f.status,f.statusText,[...f.headers.entries()].map(([d,_])=>`${d}: ${_}`).join(`
|
|
21
|
-
`)),!f.ok)throw this.#e++,new Error(`Unable to fetch raw block for CID ${t} from gateway ${this.url}, received ${f.status} ${f.statusText}`);e.onProgress?.(new V("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:
|
|
21
|
+
`)),!f.ok)throw this.#e++,new Error(`Unable to fetch raw block for CID ${t} from gateway ${this.url}, received ${f.status} ${f.statusText}`);e.onProgress?.(new V("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:fu(n.toString()),cid:t})),e.onProgress?.(new V("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:t}));let p=await vu(f,s,{signal:i.signal,log:this.log});return e.onProgress?.(new V("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:t})),this.#s++,p}),this.#n.set(o,c)}return await c}catch(c){throw signal?.aborted===!0?new Error(`Fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`Unable to fetch raw block for CID ${t} - ${c.message}`))}finally{e.signal?.removeEventListener("abort",a),this.#n.delete(o)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#s/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var ga=class extends Ke{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??$s,this.allowLocal=e.allowLocal??qs,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url),n?.onProgress?.(new V("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}));let s;try{s=await e.getRawBlock(t,n),this.log.trace("got block for %c from %s",t,e.url)}finally{n?.onProgress?.(new V("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}))}return await n.validateFn?.(s),s}async*findNewProviders(t,e={}){yield*Hs(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toFilterKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e,n){if(ze(t))return;let s=ma(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(s.length===0)return;let o=Ps(s[0]);return new Er(o,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:e})}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new V("trustless-gateway:found-provider",{type:"trustless-gateway",cid:t,url:e.url.toJSON(),routing:e.routing}))}};function Su(r,t){return new ga(r,t)}var Ks=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??$s,this.allowLocal=e.allowLocal??qs,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let s of Hs(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,s.url);try{await e.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s - %e",t,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s - %e",t,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${s.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,s.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return Su({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var $s=!1,qs=!1,_u=2097152;function Iu(r={}){return t=>new Ks(t,r)}return Cu(tm);})();
|
|
22
22
|
/*! Bundled license information:
|
|
23
23
|
|
|
24
24
|
@noble/hashes/utils.js:
|