@helia/block-brokers 5.1.4-080e4f91 → 5.1.4-397f2d86
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 +30 -5
- package/dist/index.min.js.map +4 -4
- package/dist/src/bitswap.d.ts.map +1 -1
- package/dist/src/bitswap.js +50 -10
- package/dist/src/bitswap.js.map +1 -1
- package/dist/src/trustless-gateway/index.d.ts +2 -2
- package/dist/src/trustless-gateway/index.d.ts.map +1 -1
- package/dist/src/trustless-gateway/index.js.map +1 -1
- package/dist/src/trustless-gateway/session.d.ts.map +1 -1
- package/dist/src/trustless-gateway/session.js +19 -2
- package/dist/src/trustless-gateway/session.js.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.d.ts +6 -3
- package/dist/src/trustless-gateway/trustless-gateway.d.ts.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.js +39 -4
- package/dist/src/trustless-gateway/trustless-gateway.js.map +1 -1
- package/package.json +10 -10
- package/src/bitswap.ts +51 -13
- package/src/trustless-gateway/index.ts +4 -2
- package/src/trustless-gateway/session.ts +20 -2
- package/src/trustless-gateway/trustless-gateway.ts +51 -7
package/dist/index.min.js
CHANGED
|
@@ -1,12 +1,37 @@
|
|
|
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 jo=Object.create;var _t=Object.defineProperty;var Zo=Object.getOwnPropertyDescriptor;var Jo=Object.getOwnPropertyNames;var Yo=Object.getPrototypeOf,ei=Object.prototype.hasOwnProperty;var cs=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),$=(r,e)=>{for(var t in e)_t(r,t,{get:e[t],enumerable:!0})},ls=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Jo(e))!ei.call(r,s)&&s!==t&&_t(r,s,{get:()=>e[s],enumerable:!(n=Zo(e,s))||n.enumerable});return r};var us=(r,e,t)=>(t=r!=null?jo(Yo(r)):{},ls(e||!r||!r.__esModule?_t(t,"default",{value:r,enumerable:!0}):t,r)),ti=r=>ls(_t({},"__esModule",{value:!0}),r);var Qs=cs(at=>{(function(){var r,e,t,n,s,o,i,a;a=function(c){var l,f,h,u;return l=(c&255<<24)>>>24,f=(c&255<<16)>>>16,h=(c&65280)>>>8,u=c&255,[l,f,h,u].join(".")},i=function(c){var l,f,h,u,d,p;for(l=[],h=u=0;u<=3&&c.length!==0;h=++u){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),d=p[0],f=p[1],c=c.substring(f),l.push(d)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),s=t("A"),e=function(c){var l,f,h,u,d;for(u=0,l=10,f="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,f="7")),d=h;h<c.length;){if("0"<=c[h]&&c[h]<=f)u=u*l+(t(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")u=u*l+(10+t(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")u=u*l+(10+t(c[h])-s)>>>0;else break;else break;if(u>4294967295)throw new Error("too large");h++}if(h===d)throw new Error("empty octet");return[u,h]},r=(function(){function c(l,f){var h,u,d,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(f||(p=l.split("/",2),l=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(b){throw h=b,new Error("Invalid mask: "+f)}for(u=d=32;d>=0;u=--d)if(this.maskLong===4294967295<<32-u>>>0){this.bitmask=u;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(b){throw h=b,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var f,h,u;for(u=i(this.first),h=i(this.last),f=0;u<=h;)l(a(u),u,f),f++,u++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),at.ip2long=i,at.long2ip=a,at.Netmask=r}).call(at)});var Do=cs((vp,Io)=>{Io.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Yc={};$(Yc,{bitswap:()=>ko,trustlessGateway:()=>Ko});var G=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ke=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var vt=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}};var St=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},It=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var ri=Symbol.for("@libp2p/peer-id");function Dt(r){return!!r?.[ri]}var te=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function hs(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var k=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Rr={};$(Rr,{base58btc:()=>X,base58flickr:()=>li});var il=new Uint8Array(0);function fs(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ne(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 ds(r){return new TextEncoder().encode(r)}function ps(r){return new TextDecoder().decode(r)}function ni(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,w=0,L=0,B=p.length;L!==B&&p[L]===0;)L++,b++;for(var A=(B-L)*f+1>>>0,z=new Uint8Array(A);L!==B;){for(var H=p[L],le=0,q=A-1;(H!==0||le<w)&&q!==-1;q--,le++)H+=256*z[q]>>>0,z[q]=H%a>>>0,H=H/a>>>0;if(H!==0)throw new Error("Non-zero carry");w=le,L++}for(var re=A-w;re!==A&&z[re]===0;)re++;for(var Et=c.repeat(b);re<A;++re)Et+=r.charAt(z[re]);return Et}function u(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var w=0,L=0;p[b]===c;)w++,b++;for(var B=(p.length-b)*l+1>>>0,A=new Uint8Array(B);p[b];){var z=t[p.charCodeAt(b)];if(z===255)return;for(var H=0,le=B-1;(z!==0||H<L)&&le!==-1;le--,H++)z+=a*A[le]>>>0,A[le]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");L=H,b++}if(p[b]!==" "){for(var q=B-L;q!==B&&A[q]===0;)q++;for(var re=new Uint8Array(w+(B-q)),Et=w;q!==B;)re[Et++]=A[q++];return re}}}function d(p){var b=u(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:u,decode:d}}var si=ni,oi=si,gs=oi;var kr=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Cr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ws(this,e)}},Pr=class{decoders;constructor(e){this.decoders=e}or(e){return ws(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ws(r,e){return new Pr({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Nr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new kr(e,t,n),this.decoder=new Cr(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ce({name:r,prefix:e,encode:t,decode:n}){return new Nr(r,e,t,n)}function ue({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=gs(t,r);return Ce({prefix:e,name:r,encode:n,decode:o=>ne(s(o))})}function ii(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function ai(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function ci(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function D({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=ci(n);return Ce({prefix:e,name:r,encode(o){return ai(o,n,t)},decode(o){return ii(o,s,t,r)}})}var X=ue({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),li=ue({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fr={};$(Fr,{base32:()=>he,base32hex:()=>di,base32hexpad:()=>mi,base32hexpadupper:()=>gi,base32hexupper:()=>pi,base32pad:()=>hi,base32padupper:()=>fi,base32upper:()=>ui,base32z:()=>wi});var he=D({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ui=D({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hi=D({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fi=D({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),di=D({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pi=D({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),mi=D({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gi=D({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),wi=D({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Or={};$(Or,{base36:()=>Je,base36upper:()=>bi});var Je=ue({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bi=ue({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var yi=xs,bs=128,xi=127,Ei=~xi,_i=Math.pow(2,31);function xs(r,e,t){e=e||[],t=t||0;for(var n=t;r>=_i;)e[t++]=r&255|bs,r/=128;for(;r&Ei;)e[t++]=r&255|bs,r>>>=7;return e[t]=r|0,xs.bytes=t-n+1,e}var vi=Mr,Si=128,ys=127;function Mr(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Mr.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&ys)<<s:(i&ys)*Math.pow(2,s),s+=7}while(i>=Si);return Mr.bytes=o-n,t}var Ii=Math.pow(2,7),Di=Math.pow(2,14),Li=Math.pow(2,21),Ti=Math.pow(2,28),Ai=Math.pow(2,35),ki=Math.pow(2,42),Ci=Math.pow(2,49),Pi=Math.pow(2,56),Ni=Math.pow(2,63),Ri=function(r){return r<Ii?1:r<Di?2:r<Li?3:r<Ti?4:r<Ai?5:r<ki?6:r<Ci?7:r<Pi?8:r<Ni?9:10},Fi={encode:yi,decode:vi,encodingLength:Ri},Oi=Fi,Ye=Oi;function et(r,e=0){return[Ye.decode(r,e),Ye.decode.bytes]}function Pe(r,e,t=0){return Ye.encode(r,e,t),e}function Ne(r){return Ye.encodingLength(r)}function Fe(r,e){let t=e.byteLength,n=Ne(r),s=n+Ne(t),o=new Uint8Array(s+t);return Pe(r,o,0),Pe(t,o,n),o.set(e,s),new Re(r,t,e,o)}function Ur(r){let e=ne(r),[t,n]=et(e),[s,o]=et(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Re(t,s,i,e)}function Es(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&fs(r.bytes,t.bytes)}}var Re=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function _s(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ui(t,Br(r),e??X.encoder);default:return Bi(t,Br(r),e??he.encoder)}}var vs=new WeakMap;function Br(r){let e=vs.get(r);if(e==null){let t=new Map;return vs.set(r,t),t}return e}var Q=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==tt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==zi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Fe(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Es(e.multihash,n.multihash)}toString(e){return _s(this,e)}toJSON(){return{"/":_s(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Ss(n,s,o.bytes))}else if(t[$i]===!0){let{version:n,multihash:s,code:o}=t,i=Ur(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==tt)throw new Error(`Version 0 CID must use dag-pb (code: ${tt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Ss(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,tt,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=ne(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Re(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,u]=et(e.subarray(t));return t+=u,h},s=n(),o=tt;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,f=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,s]=Mi(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Br(o).set(n,e),o}};function Mi(r,e){switch(r[0]){case"Q":{let t=e??X;return[X.prefix,t.decode(`${X.prefix}${r}`)]}case X.prefix:{let t=e??X;return[X.prefix,t.decode(r)]}case he.prefix:{let t=e??he;return[he.prefix,t.decode(r)]}case Je.prefix:{let t=e??Je;return[Je.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ui(r,e,t){let{prefix:n}=t;if(n!==X.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Bi(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var tt=112,zi=18;function Ss(r,e,t){let n=Ne(r),s=n+Ne(e),o=new Uint8Array(s+t.byteLength);return Pe(r,o,0),Pe(e,o,n),o.set(t,s),o}var $i=Symbol.for("@ipld/js-cid/CID");var zr={};$(zr,{identity:()=>Vi});var Is=0,Wi="identity",Ds=ne;function Hi(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Fe(Is,Ds(r))}var Vi={code:Is,name:Wi,encode:Ds,digest:Hi};function K(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function N(r=0){return new Uint8Array(r)}function R(r=0){return new Uint8Array(r)}function j(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=R(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Ts=Symbol.for("@achingbrain/uint8arraylist");function Ls(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Tt(r){return!!r?.[Ts]}var fe=class r{bufs;length;[Ts]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Tt(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Tt(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Ls(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ls(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Tt(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return j(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:j(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],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,e>=c)continue;let l=e>=a&&e<c,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Tt(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let 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,f;for(let h=t;h<=c;h+=f){f=0;for(let u=l;u>=0;u--){let d=this.get(h+u);if(n[u]!==d){f=Math.max(1,u-a[d]);break}}if(f===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!K(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var $r={};$($r,{base10:()=>qi});var qi=ue({prefix:"9",name:"base10",alphabet:"0123456789"});var Wr={};$(Wr,{base16:()=>Gi,base16upper:()=>Xi});var Gi=D({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xi=D({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Hr={};$(Hr,{base2:()=>Qi});var Qi=D({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vr={};$(Vr,{base256emoji:()=>Yi});var As=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}"),Ki=As.reduce((r,e,t)=>(r[t]=e,r),[]),ji=As.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Zi(r){return r.reduce((e,t)=>(e+=Ki[t],e),"")}function Ji(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=ji[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Yi=Ce({prefix:"\u{1F680}",name:"base256emoji",encode:Zi,decode:Ji});var Gr={};$(Gr,{base64:()=>se,base64pad:()=>ea,base64url:()=>qr,base64urlpad:()=>ta});var se=D({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ea=D({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),qr=D({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ta=D({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Xr={};$(Xr,{base8:()=>ra});var ra=D({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qr={};$(Qr,{identity:()=>na});var na=Ce({prefix:"\0",name:"identity",encode:r=>ps(r),decode:r=>ds(r)});var Hl=new TextEncoder,Vl=new TextDecoder;var Zr={};$(Zr,{sha256:()=>At,sha512:()=>aa});var ia=20;function jr({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Kr(r,e,t,n,s)}var Kr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??ia,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ks(n,this.code,t?.truncate):n.then(s=>ks(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ks(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Fe(e,r)}function Ps(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var At=jr({name:"sha2-256",code:18,encode:Ps("SHA-256")}),aa=jr({name:"sha2-512",code:19,encode:Ps("SHA-512")});var rt={...Qr,...Hr,...Xr,...$r,...Wr,...Fr,...Or,...Rr,...Gr,...Vr},ru={...Zr,...zr};function Rs(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ns=Rs("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Jr=Rs("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=R(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ca={utf8:Ns,"utf-8":Ns,hex:rt.base16,latin1:Jr,ascii:Jr,binary:Jr,...rt},kt=ca;function C(r,e="utf8"){let t=kt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function F(r,e="utf8"){let t=kt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var la=Math.pow(2,7),ua=Math.pow(2,14),ha=Math.pow(2,21),Yr=Math.pow(2,28),en=Math.pow(2,35),tn=Math.pow(2,42),rn=Math.pow(2,49),y=128,O=127;function S(r){if(r<la)return 1;if(r<ua)return 2;if(r<ha)return 3;if(r<Yr)return 4;if(r<en)return 5;if(r<tn)return 6;if(r<rn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Me(r,e,t=0){switch(S(r)){case 8:e[t++]=r&255|y,r/=128;case 7:e[t++]=r&255|y,r/=128;case 6:e[t++]=r&255|y,r/=128;case 5:e[t++]=r&255|y,r/=128;case 4:e[t++]=r&255|y,r>>>=7;case 3:e[t++]=r&255|y,r>>>=7;case 2:e[t++]=r&255|y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function fa(r,e,t=0){switch(S(r)){case 8:e.set(t++,r&255|y),r/=128;case 7:e.set(t++,r&255|y),r/=128;case 6:e.set(t++,r&255|y),r/=128;case 5:e.set(t++,r&255|y),r/=128;case 4:e.set(t++,r&255|y),r>>>=7;case 3:e.set(t++,r&255|y),r>>>=7;case 2:e.set(t++,r&255|y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function nn(r,e){let t=r[e],n=0;if(n+=t&O,t<y||(t=r[e+1],n+=(t&O)<<7,t<y)||(t=r[e+2],n+=(t&O)<<14,t<y)||(t=r[e+3],n+=(t&O)<<21,t<y)||(t=r[e+4],n+=(t&O)*Yr,t<y)||(t=r[e+5],n+=(t&O)*en,t<y)||(t=r[e+6],n+=(t&O)*tn,t<y)||(t=r[e+7],n+=(t&O)*rn,t<y))return n;throw new RangeError("Could not decode varint")}function da(r,e){let t=r.get(e),n=0;if(n+=t&O,t<y||(t=r.get(e+1),n+=(t&O)<<7,t<y)||(t=r.get(e+2),n+=(t&O)<<14,t<y)||(t=r.get(e+3),n+=(t&O)<<21,t<y)||(t=r.get(e+4),n+=(t&O)*Yr,t<y)||(t=r.get(e+5),n+=(t&O)*en,t<y)||(t=r.get(e+6),n+=(t&O)*tn,t<y)||(t=r.get(e+7),n+=(t&O)*rn,t<y))return n;throw new RangeError("Could not decode varint")}function Ct(r,e,t=0){return e==null&&(e=R(S(r))),e instanceof Uint8Array?Me(r,e,t):fa(r,e,t)}function me(r,e=0){return r instanceof Uint8Array?nn(r,e):da(r,e)}var on=new Float32Array([-0]),de=new Uint8Array(on.buffer);function Fs(r,e,t){on[0]=r,e[t]=de[0],e[t+1]=de[1],e[t+2]=de[2],e[t+3]=de[3]}function Os(r,e){return de[0]=r[e],de[1]=r[e+1],de[2]=r[e+2],de[3]=r[e+3],on[0]}var an=new Float64Array([-0]),M=new Uint8Array(an.buffer);function Ms(r,e,t){an[0]=r,e[t]=M[0],e[t+1]=M[1],e[t+2]=M[2],e[t+3]=M[3],e[t+4]=M[4],e[t+5]=M[5],e[t+6]=M[6],e[t+7]=M[7]}function Us(r,e){return M[0]=r[e],M[1]=r[e+1],M[2]=r[e+2],M[3]=r[e+3],M[4]=r[e+4],M[5]=r[e+5],M[6]=r[e+6],M[7]=r[e+7],an[0]}var pa=BigInt(Number.MAX_SAFE_INTEGER),ma=BigInt(Number.MIN_SAFE_INTEGER),W=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ge;if(e<pa&&e>ma)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Bs&&(s=0n,++n>Bs&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return ge;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ge}},ge=new W(0,0);ge.toBigInt=function(){return 0n};ge.zzEncode=ge.zzDecode=function(){return this};ge.length=function(){return 1};var Bs=4294967296n;function zs(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function $s(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&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 cn(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function Z(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Pt(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var ln=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Z(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Z(this,4);return Pt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Z(this,4);return Pt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Z(this,4);let e=Os(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Z(this,4);let e=Us(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Z(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return $s(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Z(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Z(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new W(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Z(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Z(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Z(this,8);let e=Pt(this.buf,this.pos+=4),t=Pt(this.buf,this.pos+=4);return new W(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=nn(this.buf,this.pos);return this.pos+=S(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function un(r){return new ln(r instanceof Uint8Array?r:r.subarray())}function we(r,e,t){let n=un(r);return e.decode(n,void 0,t)}function hn(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return R(i);s+i>e&&(n=R(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var be=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function fn(){}var pn=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ga=hn();function wa(r){return globalThis.Buffer!=null?R(r):ga(r)}var st=class{len;head;tail;states;constructor(){this.len=0,this.head=new be(fn,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new be(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new mn((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Nt,10,W.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=W.fromBigInt(e);return this._push(Nt,t.length(),t)}uint64Number(e){return this._push(Me,S(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=W.fromBigInt(e).zzEncode();return this._push(Nt,t.length(),t)}sint64Number(e){let t=W.fromNumber(e).zzEncode();return this._push(Nt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(dn,1,e?1:0)}fixed32(e){return this._push(nt,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=W.fromBigInt(e);return this._push(nt,4,t.lo)._push(nt,4,t.hi)}fixed64Number(e){let t=W.fromNumber(e);return this._push(nt,4,t.lo)._push(nt,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Fs,4,e)}double(e){return this._push(Ms,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(dn,1,0):this.uint32(t)._push(ya,t,e)}string(e){let t=zs(e);return t!==0?this.uint32(t)._push(cn,t,e):this._push(dn,1,0)}fork(){return this.states=new pn(this),this.head=this.tail=new be(fn,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 be(fn,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=wa(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function dn(r,e,t){e[t]=r&255}function ba(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var mn=class extends be{next;constructor(e,t){super(ba,e,t),this.next=void 0}};function Nt(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function nt(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function ya(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(st.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(xa,e,r),this},st.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Ea,e,r),this});function xa(r,e,t){e.set(r,t)}function Ea(r,e,t){r.length<40?cn(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(C(r),t)}function gn(){return new st}function ye(r,e){let t=gn();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Ue;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ue||(Ue={}));function Rt(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ft(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return Rt("enum",Ue.VARINT,t,n)}function xe(r,e){return Rt("message",Ue.LENGTH_DELIMITED,r,e)}var Be=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var wn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Hs={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Vs=new globalThis.TextEncoder;function _a(r,e){let t=wn[e],n=Hs[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function va(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=wn[e],s=Hs[e],o=r;for(;o.length>0;){let i=Vs.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function bn(r,{size:e=32,utf8Buffer:t}={}){if(!wn[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return va(r,e,t);r=Vs.encode(r)}return _a(r,e)}var ot={hash:r=>Number(bn(r,{size:32})),hashV:(r,e)=>Sa(ot.hash(r,e))};function Sa(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),C(e,"base16")}var yn=64,J=class{fp;h;seed;constructor(e,t,n,s=2){if(s>yn)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=N(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?K(this.fp,e.fp):!1}};function Ee(r,e){return Math.floor(Math.random()*(e-r))+r}var _e=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof J))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof J))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof J))throw new TypeError("Invalid Fingerprint");let t=Ee(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof J))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Ia=500,it=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??ot,this.seed=e.seed??Ee(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=C(e));let t=new J(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new _e(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new _e(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Ee(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new _e(this.bucketSize));for(let a=0;a<Ia;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new _e(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=C(e));let t=new J(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=C(e));let t=new J(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Da={1:.5,2:.84,4:.95,8:.98};function La(r=.001){return r>.002?2:r>1e-5?4:8}function qs(r,e=.001){let t=La(e),n=Da[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),yn);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Ot=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??ot,this.seed=e.seed??Ee(0,Math.pow(2,10)),this.filterSeries=[new it({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=C(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new it({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=C(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=C(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Mt(r,e=.001,t){return new Ot({...qs(r,e),...t??{}})}function Ut(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new ke(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var Bt=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,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 f=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let u=Number.parseInt(h,e);if(!Number.isNaN(u))return u});if(f===void 0)break;if(o*=e,o+=f,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[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];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ta=45,Aa=15,zt=new Bt;function Gs(r){if(!(r.length>Aa))return zt.new(r).parseWith(()=>zt.readIPv4Addr())}function Xs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ta))return zt.new(r).parseWith(()=>zt.readIPv6Addr())}function ze(r){return!!Gs(r)}function $t(r){return!!Xs(r)}var Ks=us(Qs(),1),ka=["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"],Ca=ka.map(r=>new Ks.Netmask(r));function xn(r){for(let e of Ca)if(e.contains(r))return!0;return!1}function Pa(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Na(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return xn(s)}function Ra(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Fa(r){let e=r.split(":"),t=e[e.length-1];return xn(t)}function Oa(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 js(r){if(ze(r))return xn(r);if(Pa(r))return Na(r);if(Ra(r))return Fa(r);if($t(r))return Oa(r)}function Zs(r){try{let e=Ut(r);switch(e.type){case"ip4":case"ip6":return js(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function Y(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Wt=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},$e=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Wt(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Wt(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var En=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ht(r={}){return Ma(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ma(r,e){e=e??{};let t=e.onEnd,n=new $e,s,o,i,a=Y(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,L)=>{o=B=>{o=null,n.push(B);try{w(r(n))}catch(A){L(A)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Y()})}},l=w=>o!=null?o(w):(n.push(w),s),f=w=>(n=new $e,o!=null?o({error:w}):(n.push({error:w}),s)),h=w=>{if(i)return s;if(e?.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})},u=w=>i?s:(i=!0,w!=null?f(w):l({done:!0})),d=()=>(n=new $e,u(),{done:!0}),p=w=>(u(w),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:h,end:u,get readableLength(){return n.size},onEmpty:async w=>{let L=w?.signal;if(L?.throwIfAborted(),n.isEmpty())return;let B,A;L!=null&&(B=new Promise((z,H)=>{A=()=>{H(new En)},L.addEventListener("abort",A)}));try{await Promise.race([a.promise,B])}finally{A!=null&&L!=null&&L?.removeEventListener("abort",A)}}},t==null)return s;let b=s;return s={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(w){return b.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(w){return b.end(w),t!=null&&(t(w),t=void 0),s},get readableLength(){return b.readableLength},onEmpty:w=>b.onEmpty(w)},s}var _n=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Js=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function vn(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,f=new Promise((h,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){u(Js(i));return}if(i&&(c=()=>{u(Js(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,u),t===Number.POSITIVE_INFINITY)return;let d=new _n;a=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(p){u(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?h():s instanceof Error?u(s):(d.message=s??`Promise timed out after ${t} milliseconds`,u(d))},t)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},f}var Ua=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Ba(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=Ua(r),h=async(...d)=>{let p=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(p))return}catch(b){n(),i(b);return}c.push(p),t.count===c.length&&(n(),o(c))},u=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)f(d,h);for(let d of t.rejectionEvents)a.includes(d)||f(d,u)};for(let d of a)l(d,h);for(let d of t.rejectionEvents)a.includes(d)||l(d,u);t.signal&&t.signal.addEventListener("abort",()=>{u(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=vn(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Vt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Ba(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Sn(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var qt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function za(r){return r.reason}async function ct(r,e,t){if(e==null)return r;let n=t?.translateError??za;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var Gt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Y(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new G)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function $a(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Xt=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=$a(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new G),this.cleanup())}async join(e={}){let t=new Gt(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await ct(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var We=class extends te{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Sn(this.emitEmpty.bind(this),1),this.emitIdle=Sn(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new qt;let n=new Xt(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let 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(e=>{e.abort(new G)}),this.clear()}async onEmpty(e){this.size!==0&&await Vt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Vt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Vt(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ht({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new G("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var P=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},oe=class extends Error{static name="ValidationError";name="ValidationError"},Qt=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Kt=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Dn(r){return e=>F(e,r)}function Ln(r){return e=>C(e,r)}function He(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function ve(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ys(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=C(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=ve(n);return j([t,s],t.length+s.length)}function eo(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=he.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=ve(n);return j([t,s],t.length+s.length)}function Tn(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=F(e,"base32"),s=He(t);return`${n}:${s}`}var An=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new P("Invalid byte value in IP address");e[n]=s}),e},to=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=ze(t[n]),i;o&&(i=An(t[n]),t[n]=F(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,F(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new P("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},ro=function(r){if(r.byteLength!==4)throw new P("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},no=function(r){if(r.byteLength!==16)throw new P("IPv6 address was incorrect length");let e=[];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")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new P(`Invalid IPv6 address "${t}"`)}};function so(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new P(`Invalid IPv6 address "${r}"`)}}var In=Object.values(rt).map(r=>r.decoder),Wa=(function(){let r=In[0].or(In[1]);return In.slice(2).forEach(e=>r=r.or(e)),r})();function oo(r){return Wa.decode(r)}function io(r){return e=>r.encoder.encode(e)}function Ha(r){if(parseInt(r).toString()!==r)throw new oe("Value must be an integer")}function Va(r){if(r<0)throw new oe("Value must be a positive integer, or zero")}function qa(r){return e=>{if(e>r)throw new oe(`Value must be smaller than or equal to ${r}`)}}function Ga(...r){return e=>{for(let t of r)t(e)}}var lt=Ga(Ha,Va,qa(65535));var T=-1,kn=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Kt(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},ae=new kn,ac=[{code:4,name:"ip4",size:32,valueToBytes:An,bytesToValue:ro,validate:r=>{if(!ze(r))throw new oe(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ve,bytesToValue:He,validate:lt},{code:273,name:"udp",size:16,valueToBytes:ve,bytesToValue:He,validate:lt},{code:33,name:"dccp",size:16,valueToBytes:ve,bytesToValue:He,validate:lt},{code:41,name:"ip6",size:128,valueToBytes:to,bytesToValue:no,stringToValue:so,validate:r=>{if(!$t(r))throw new oe(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:T},{code:43,name:"ipcidr",size:8,bytesToValue:Dn("base10"),valueToBytes:Ln("base10")},{code:53,name:"dns",size:T},{code:54,name:"dns4",size:T},{code:55,name:"dns6",size:T},{code:56,name:"dnsaddr",size:T},{code:132,name:"sctp",size:16,valueToBytes:ve,bytesToValue:He,validate:lt},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:T,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:T,bytesToValue:Dn("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ln("base58btc")(r):Q.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Tn,valueToBytes:Ys},{code:445,name:"onion3",size:296,bytesToValue:Tn,valueToBytes:eo},{code:446,name:"garlic64",size:T},{code:447,name:"garlic32",size:T},{code:448,name:"tls"},{code:449,name:"sni",size:T},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:T,bytesToValue:io(qr),valueToBytes:oo},{code:480,name:"http"},{code:481,name:"http-path",size:T,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:T}];ac.forEach(r=>{ae.addProtocol(r)});function ao(r){let e=[],t=0;for(;t<r.length;){let n=me(r,t),s=ae.getProtocol(n),o=S(n),i=cc(s,r,t+o),a=0;i>0&&s.size===T&&(a=S(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let f=t+o+a,h=r.subarray(f,f+i);l.value=s.bytesToValue?.(h)??F(h)}e.push(l),t+=c}return e}function co(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=ae.getProtocol(n.code),o=S(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??C(n.value),a=i.byteLength,s.size===T&&(c=S(a)));let l=new Uint8Array(o+c+a),f=0;Me(n.code,l,f),f+=o,i!=null&&(s.size===T&&(Me(a,l,f),f+=c),l.set(i,f)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return j(t,e)}function lo(r){if(r.charAt(0)!=="/")throw new P('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ae.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new P(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new P(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new P("Incomplete multiaddr");return e}function uo(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ae.getProtocol(e.code);if(t==null)throw new P(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function cc(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:me(e,t)}var lc=Symbol.for("nodejs.util.inspect.custom"),Wn=Symbol.for("@multiformats/multiaddr");function uc(r){if(r==null&&(r="/"),ho(r))return r.getComponents();if(r instanceof Uint8Array)return ao(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),lo(r);if(Array.isArray(r))return r;throw new P("Must be a string, Uint8Array, Component[], or another Multiaddr")}var er=class r{[Wn]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=uc(e),t.validate!==!1&&hc(this)}get bytes(){return this.#r==null&&(this.#r=co(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=uo(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Qt(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return K(this.bytes,e.bytes)}[lc](){return`Multiaddr(${this.toString()})`}};function hc(r){r.getComponents().forEach(e=>{let t=ae.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function ho(r){return!!r?.[Wn]}function fo(r){return new er(r)}var tr=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ge=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},rr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},mt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function nr(r){return r[Symbol.asyncIterator]!=null}function po(r,e){if(r.byteLength>e)throw new Ge("Message length too long")}var or=r=>{let e=S(r),t=R(e);return Ct(r,t),or.bytes=e,t};or.bytes=0;function ir(r,e){e=e??{};let t=e.lengthEncoder??or,n=e?.maxDataLength??4194304;function*s(o){po(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return nr(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}ir.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??or,n=e?.maxDataLength??4194304;return po(r,n),new fe(t(r.byteLength),r)};var Ie;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ie||(Ie={}));var Hn=r=>{let e=me(r);return Hn.bytes=S(e),e};Hn.bytes=0;function gt(r,e){let t=new fe,n=Ie.LENGTH,s=-1,o=e?.lengthDecoder??Hn,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ie.LENGTH)try{if(s=o(t),s<0)throw new tr("Invalid message length");if(s>a)throw new Ge("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Ie.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new rr("Message length length too long");break}throw l}if(n===Ie.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Ie.LENGTH}}}return nr(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new mt("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new mt("Unexpected end of input")})()}gt.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return gt(n,{...e??{},onLength:o=>{t=o}})};var ar=class extends We{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Vn=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function mo(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Vn({name:e,metrics:t}):n=new Map,n}function pc(r){return r[Symbol.asyncIterator]!=null}function mc(r){if(pc(r))return(async()=>{for await(let e of r);})();for(let e of r);}var qn=mc;function gc(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var go=gc;function wc(r){return r[Symbol.asyncIterator]!=null}function bc(r,e){let t=0;if(wc(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=go(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var wo=bc;function yc(r){return r[Symbol.asyncIterator]!=null}function xc(r,e){return yc(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var bo=xc;var cr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function De(r,e,t,n){let s=new cr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Xn(t,"abort",h),Xn(r,e,l),Xn(r,o,f)}let l=u=>{try{if(n?.filter?.(u)===!1)return}catch(d){c(),a(d);return}c(),i(u)},f=u=>{if(c(),u instanceof Error){a(u);return}a(u.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)};Gn(t,"abort",h),Gn(r,e,l),Gn(r,o,f)})}function Gn(r,e,t){r!=null&&(yo(r)?r.addEventListener(e,t):r.addListener(e,t))}function Xn(r,e,t){r!=null&&(yo(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function yo(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var wt="/ipfs/bitswap/1.2.0";var I;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(I||(I={}));var Qn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Qn||(Qn={}));(function(r){r.codec=()=>Ft(Qn)})(I||(I={}));var Xe;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),I.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={cid:N(0),priority:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.cid=t.bytes();break}case 2:{o.priority=t.int32();break}case 3:{o.cancel=t.bool();break}case 4:{o.wantType=I.codec().decode(t);break}case 5:{o.sendDontHave=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Xe||(Xe={}));var lr;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let o of t.entries)n.uint32(10),Xe.codec().encode(o,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={entries:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new Be('Decode error - map field "entries" had too many elements');o.entries.push(Xe.codec().decode(t,t.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(lr||(lr={}));var Qe;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={prefix:N(0),data:N(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.prefix=t.bytes();break}case 2:{o.data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Qe||(Qe={}));var V;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(V||(V={}));var ur;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(ur||(ur={}));(function(r){r.codec=()=>Ft(ur)})(V||(V={}));var Ke;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&ur[t.type]!==0&&(n.uint32(16),V.codec().encode(t.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={cid:N(0),type:V.HaveBlock},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.cid=t.bytes();break}case 2:{o.type=V.codec().decode(t);break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Ke||(Ke={}));var Le;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),lr.codec().encode(t.wantlist,n)),t.blocks!=null)for(let o of t.blocks)n.uint32(26),Qe.codec().encode(o,n);if(t.blockPresences!=null)for(let o of t.blockPresences)n.uint32(34),Ke.codec().encode(o,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.wantlist=lr.codec().decode(t,t.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&o.blocks.length===s.limits.blocks)throw new Be('Decode error - map field "blocks" had too many elements');o.blocks.push(Qe.codec().decode(t,t.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&o.blockPresences.length===s.limits.blockPresences)throw new Be('Decode error - map field "blockPresences" had too many elements');o.blockPresences.push(Ke.codec().decode(t,t.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=t.int32();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Le||(Le={}));function xo(r,e){for(let[t,n]of e.wantlist.entries()){let s=r.wantlist.get(t);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(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var hr=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Ec=4193648,_c=Ec+16;function*Eo(r,e){let t=[...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},f=Le.encode(l).byteLength,{added:h,hasMore:u,newSize:d}=Kn(s,l.blocks,a,e,f,vc);a+=h,f=d;let p=u;({added:h,hasMore:u,newSize:d}=Kn(n,l.blockPresences,i,e,f,Sc)),i+=h,f=d;let b=u;if({added:h,hasMore:u,newSize:d}=Kn(t,l.wantlist.entries,o,e,f,Ic),o+=h,f=d,c=!p&&!b&&!u,c||(l.wantlist.full=!1),yield Le.encode(l),c)break}}function Kn(r,e,t,n,s,o){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],f=o(l);if(f>_c)throw new hr("Cannot send block as after encoding it is over the max message size");let h=s+f;if(h>n){a=!0;break}e.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function vc(r){return jn(3,Qe.encode(r))}function Sc(r){return jn(4,Ke.encode(r))}function Ic(r){return jn(1,Xe.encode(r))}function jn(r,e){let t=S(r),n=S(e.byteLength);return t+n+e.byteLength}var fr=class extends te{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[wt],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new ar({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new St(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);s.addEventListener("abort",n),await e.close({signal:s});let o=Ht();e.addEventListener("message",i=>{o.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{o.end()}),e.addEventListener("close",i=>{i.error!=null&&o.end(i.error)});for await(let i of gt(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Le.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a}}),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",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new k("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new k("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await qn(wo(bo(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>e.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=xo(s.options.message,t),await s.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let i=o?.message;if(i==null)throw new ke("No message to send");this.log("sendMessage to %p",e),o?.onProgress?.(new k("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,wt,o);await a.closeRead();try{for(let c of Eo(i,this.maxOutgoingMessageSize))a.send(ir.single(c))||await a.onDrain(o);await a.close(o)}catch(c){o?.onProgress?.(new k("bitswap:network:send-wantlist:error",{peer:e,error:c})),this.log.error("error sending message to %p - %e",e,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new It("Network isn't running");t?.onProgress?.(new k("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),De(this.libp2p,"peer:identify",t?.signal,{filter:s=>{if(!s.detail.peerId.equals(e))return!1;if(s.detail.protocols.includes(wt))return!0;throw new vt(`${e} did not support ${wt}`)}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function dr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var bt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return dr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return dr(this.map.values(),e=>e.key)}values(){return dr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Zn=class extends bt{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function yt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Zn({name:e,metrics:t}):n=new bt,n}function Rc(r){return r[Symbol.asyncIterator]!=null}function Fc(r){if(Rc(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=j([n,s],n.length+s.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return j(e,t)}var vo=Fc;var ce=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=se.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=se.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=se.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Oc(r){let e=new Uint8Array(r.reduce((n,s)=>n+S(s),0)),t=0;for(let n of r)e=Ct(n,e,t),t+=S(n);return e}var So=Oc;function Jn(r){return So([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var pr=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of e.entries){let s=Q.decode(n.cid),o=F(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===I.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===I.WantHave&&(n.wantType==null||n.wantType===I.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??I.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??I.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,s])=>s.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.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 t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=F(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new ce,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 vo(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===I.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:a,prefix:Jn(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:V.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:a,prefix:Jn(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:V.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0)))}};var mr=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=yt({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new pr({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let s of this.ledgerMap.values())s.hasWant(e)&&n.push(s);await Promise.all(n.map(async s=>s.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var Bc=us(Do(),1);var je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(je||(je={}));var gr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Te=class extends te{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Mt(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=se.encode(e.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",e),s.observers++,s.promise;let o=Y(),i={promise:o.promise,observers:1,queryFilter:Mt(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,l=new We({concurrency:this.maxProviders});l.addEventListener("failure",u=>{this.log.error("error querying provider %s, evicting from session - %e",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),l.addEventListener("success",u=>{c=!0,o.resolve(u.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(u=>{this.log.error("could not find new providers for %c - %e",e,u),o.reject(u)})});let f=u=>{let d=this.toFilterKey(u.detail);i.queryFilter.has(d)||(i.queryFilter.add(d),this.emitFoundProviderProgressEvent(e,u.detail,t),l.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,p)}))};if(this.addEventListener("provider",f),a)try{await ct(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(u){throw a&&this.log("failed to find initial session peers for %c - %e",e,u),this.requests.delete(n),i.observers>1&&o.reject(u),u}Promise.all([...this.providers].filter(u=>{let d=this.toFilterKey(u),p=i.queryFilter.has(d);return p||i.queryFilter.add(this.toFilterKey(u)),!p}).map(async u=>l.add(async()=>this.queryProvider(e,u,t),{provider:u}))).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,u)});let h=()=>{o.reject(new G(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",h);try{return await ct(o.promise,t.signal)}finally{this.removeEventListener("provider",f),t.signal?.removeEventListener("abort",h),l.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let s=Y(),o=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length),this.initialProviders.length>0)for(;o<t&&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===t&&(this.log("session is ready with %d peer(s), only initial peers present",t),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(e,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===t&&(this.log("session is ready with %d peer(s), new peers present",t),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<t)throw new gr(`Found ${o} of ${t} ${this.name} providers for ${e}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),s.reject(i)}),s.promise}};var Yn=class extends Te{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let s=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.toMultihash().bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Dt(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let s=await this.libp2p.dial(e,n);return{peerId:s.remotePeer,routing:t,toString:()=>`Bitswap(${s.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new k("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function Lo(r,e){return new Yn(r,e)}var wr=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};function Hc(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=me(r);e.push(t),r=r.slice(S(t))}return e}var To=Hc;var br=class extends te{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),this.peers=yt({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=mo({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,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(e,t){let n=F(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??I.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===I.WantHave&&t.wantType===I.WantBlock&&(s.wantType=I.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===I.WantBlock?(await De(this,"block",t?.signal,{filter:a=>K(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await De(this,"presence",t?.signal,{filter:i=>K(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=Y(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,s=new ce;for(let[o,i]of this.wants.entries())t.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(e,s);for(let o of n)t.add(o)}catch(o){this.log.error("error sending full wantlist to new peer - %e",o)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=F(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let s=new ce;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:I.WantHave,priority:1}),await this.network.sendMessage(t,s),(await De(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&K(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:I.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new ce;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:I.WantBlock,priority:1}),await this.network.sendMessage(t,s),(await De(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&K(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=F(e.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let s of t.blocks){if(s.prefix==null||s.data==null)continue;let o=To(s.prefix),i=o[0],a=o[1],c=o[2],l=o[3],f=c===At.code?At:await this.hashLoader?.getHasher(c);if(f==null){this.log.error("unknown hash algorithm",c);continue}let h=f.digest(s.data,{truncate:l});h.then!=null&&(h=await h);let u=Q.create(i===0?0:1,a,h);this.log("received block from %p for %c",e,u),this.safeDispatchEvent("block",{detail:{sender:e,cid:u,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:u,has:!0,block:s.data}});let d=F(u.multihash.bytes,"base64"),p=this.wants.get(d);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:s,type:o}of t.blockPresences){let i=Q.decode(s);this.log("received %s from %p for %c",o,e,i),this.safeDispatchEvent("presence",{detail:{sender:e,cid:i,has:o===V.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new ce(!0);for(let[s,o]of this.wants.entries())o.cancel||(t.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:I.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(s){this.log.error("error sending full wantlist to new peer %p - %e",e,s)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var yr=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new wr(e),this.network=new fr(e,t),this.peerWantLists=new mr({...e,network:this.network},t),this.wantList=new br({...e,network:this.network},t)}createSession(e={}){return Lo({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,s=hs([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,o)});try{let o=await this.wantList.wantBlock(e,{...t,signal:s});return t.onProgress?.(new k("bitswap:block",{cid:e,sender:o.sender})),o.block}finally{n.abort(),s.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Ao=(r,e={})=>new yr(r,e);var es=class{name="bitswap";bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=Ao(e,{hashLoader:{getHasher:async s=>n(s)},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,s)=>{await t.addPeer(n,s)},announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>t.retrieve(n,s)}}};function ko(r={}){return e=>new es(e,r)}var Vc=[6,53,56,54,55];function Co(r){return Ro("sni",r)?.value}function Po(r){let e=Ro("tcp",r)?.value;return e==null?"":`:${e}`}function Ro(r,e){return e.find(t=>t.name===r)}function No(r){return r.some(({code:e})=>e===448)}function ee(r,e){let t=Fo[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var Fo={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${ee(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${ee(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ee(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ee(t,e)}`},http:(r,e)=>{let t=No(e),n=Co(e),s=Po(e);if(t&&n!=null)return`https://${n}${s}`;let o=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ee(i,e);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ee(t,e),s=decodeURIComponent(r.value??"");return`${n}${s}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ee(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ee(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ee(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=No(e),n=Co(e),s=Po(e);if(t&&n!=null)return`wss://${n}${s}`;let o=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ee(i,e);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ee(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function xr(r,e){let n=fo(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=Fo[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return e?.assumeHttp!==!1&&Vc.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 _=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),m=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Oo=r=>({match:e=>r.match(e)===!1?e:!1}),g=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),U=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),x=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function v(...r){function e(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 t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var qc=m(421),Um=v(qc),_r=m(54),vr=m(55),Sr=m(56),rs=m(53),Bm=v(_r,g(m(421))),zm=v(vr,g(m(421))),$m=v(Sr,g(m(421))),Mo=v(U(rs,Sr,_r,vr),g(m(421))),Uo=x(m(4),g(m(43))),Bo=x(g(m(42)),m(41),g(m(43))),ns=U(Uo,Bo),Ae=U(ns,rs,_r,vr,Sr),Wm=v(U(ns,x(U(rs,Sr,_r,vr),g(m(421))))),Hm=v(Uo),Vm=v(Bo),qm=v(ns),ss=x(Ae,m(6)),xt=x(Ae,m(273)),Gm=v(x(ss,g(m(421)))),Xm=v(xt),os=x(xt,_(460),g(m(421))),Ir=x(xt,_(461),g(m(421))),Gc=U(os,Ir),Qm=v(os),Km=v(Ir),ts=U(Ae,ss,xt,os,Ir),zo=U(x(ts,_(477),g(m(421)))),jm=v(zo),$o=U(x(ts,_(478),g(m(421))),x(ts,_(448),g(m(449)),_(477),g(m(421)))),Zm=v($o),Wo=x(xt,_(280),g(m(466)),g(m(466)),g(m(421))),Jm=v(Wo),Ho=x(Ir,_(465),g(m(466)),g(m(466)),g(m(421))),Ym=v(Ho),Er=U(zo,$o,x(ss,g(m(421))),x(Gc,g(m(421))),x(Ae,g(m(421))),Wo,Ho,m(421)),eg=v(Er),Xc=x(g(Er),_(290),Oo(_(281)),g(m(421))),tg=v(Xc),Qc=U(x(Er,_(290),_(281),g(m(421))),x(Er,_(281),g(m(421))),x(_(281),g(m(421)))),rg=v(Qc),Kc=U(x(Ae,m(6),_(480),g(m(421))),x(Ae,_(480),g(m(421)))),Vo=v(Kc),jc=x(Ae,U(x(m(6,"443"),_(480)),x(m(6),_(443)),x(m(6),_(448),_(480)),x(_(448),_(480)),_(448),_(443)),g(m(421))),qo=v(jc),Zc=U(x(m(777),g(m(421)))),ng=v(Zc),Jc=U(x(m(400),g(m(421)))),sg=v(Jc);function is(r,e,t){return r.filter(n=>{if(qo.matches(n)||e&&Vo.matches(n))return t||Mo.matches(n)?!0:Zs(n)===!1;if(!e&&t){let{host:s}=Ut(n);if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*Dr(r,e,t,n,s,o={}){for await(let i of e.findProviders(r,o)){let a=is(i.multiaddrs,n,s);if(a.length===0)continue;let c=new URL(xr(a[0]));yield new Ze(c,{logger:t,transformRequestInit:o.transformRequestInit,routing:i.routing})}}async function Go(r,e,t){let{signal:n,log:s}=t??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>e)throw s?.error("content-length header (%d) is greater than the limit (%d)",c,e),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 (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new fe;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>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{s?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var Ze=class{url;#e=0;#t=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;routing;constructor(e,{logger:t,transformRequestInit:n,routing:s}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=s}#o(e){let t=e.multihash.bytes;return se.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=Xo}={}){let s=new URL(this.url.toString());if(s.pathname=`/ipfs/${e.toString()}`,s.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#o(e),i=new AbortController,a=()=>{i.abort()};t?.addEventListener("abort",a);try{let c=this.#n.get(o);if(c==null){this.#e++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},f=this.transformRequestInit!=null?await this.transformRequestInit(l):l,h=new Headers(f.headers);this.log(`sending request
|
|
2
|
+
"use strict";var HeliaBlockBrokers=(()=>{var Su=Object.create;var cn=Object.defineProperty;var Iu=Object.getOwnPropertyDescriptor;var Au=Object.getOwnPropertyNames;var ku=Object.getPrototypeOf,Tu=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})},ba=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Au(t))!Tu.call(r,s)&&s!==e&&cn(r,s,{get:()=>t[s],enumerable:!(n=Iu(t,s))||n.enumerable});return r};var ya=(r,t,e)=>(e=r!=null?Su(ku(r)):{},ba(t||!r||!r.__esModule?cn(e,"default",{value:r,enumerable:!0}):e,r)),Du=r=>ba(cn({},"__esModule",{value:!0}),r);var mi=ln(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.Netmask4Impl=void 0;fr.ip2long=ur;fr.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 ed=48,rd=97,nd=65;function sd(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)-ed)>>>0;else if(e===16)if("a"<=r[s]&&r[s]<="f")t=t*e+(10+r.charCodeAt(s)-rd)>>>0;else if("A"<=r[s]&&r[s]<="F")t=t*e+(10+r.charCodeAt(s)-nd)>>>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]=sd(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 pi=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=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):(ur(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=ur(this.first),n=ur(this.last),s=0;for(;e<=n;)t(Gt(e),e,s),s++,e++}toString(){return this.base+"/"+this.bitmask}};fr.Netmask4Impl=pi});var dl=ln(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.Netmask6Impl=void 0;hr.ip6bigint=bi;hr.bigint2ip6=Pe;var od=mi(),gi=(1n<<128n)-1n;function bi(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,od.ip2long)(n),o=r.substring(0,e+1)+"0:0";return hl(o)&~0xffffffffn|BigInt(s)}return hl(r)}function hl(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 Pe(r){if(r<0n||r>gi)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 yi=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=gi>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=bi(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Pe(this.netBigint),this.mask=Pe(this.maskBigint),this.hostmask=Pe(~this.maskBigint&gi),this.first=this.base,this.last=Pe(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):(bi(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(Pe(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(Pe(e),Number(e),o),o++,e++}toString(){return this.base+"/"+this.bitmask}};hr.Netmask6Impl=yi});var pl=ln(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.Netmask=void 0;var id=mi(),ad=dl(),wi=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 id.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}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()}};Yn.Netmask=wi});var Gl=ln((a2,Wl)=>{Wl.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:()=>Xl,trustlessGateway:()=>_u});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"}},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 Er=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]}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 wa(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 vr=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 xa={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=xa;var Ws={};At(Ws,{base58btc:()=>at,base58flickr:()=>Nu});var um=new Uint8Array(0);function Ea(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 va(r){return new TextEncoder().encode(r)}function _a(r){return new TextDecoder().decode(r)}function Lu(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 Cu=Lu,Bu=Cu,Ia=Bu;var qs=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")}},Ks=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 Aa(this,t)}},zs=class{decoders;constructor(t){this.decoders=t}or(t){return Aa(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 Aa(r,t){return new zs({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Vs=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 qs(t,e,n),this.decoder=new Ks(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 Vs(r,t,e,n)}function ce({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Ia(e,r);return Ve({prefix:t,name:r,encode:n,decode:o=>Zt(s(o))})}function Pu(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 Ru(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 Ou(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=Ou(n);return Ve({prefix:t,name:r,encode(o){return Ru(o,n,e)},decode(o){return Pu(o,s,e,r)}})}var at=ce({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nu=ce({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Gs={};At(Gs,{base32:()=>le,base32hex:()=>Hu,base32hexpad:()=>qu,base32hexpadupper:()=>Ku,base32hexupper:()=>$u,base32pad:()=>Mu,base32padupper:()=>Fu,base32upper:()=>Uu,base32z:()=>zu});var le=ot({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Uu=ot({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Mu=ot({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Fu=ot({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Hu=ot({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),$u=ot({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),qu=ot({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ku=ot({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zu=ot({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Zs={};At(Zs,{base36:()=>_r,base36upper:()=>Vu});var _r=ce({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Vu=ce({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Wu=Da,ka=128,Gu=127,Zu=~Gu,Yu=Math.pow(2,31);function Da(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Yu;)t[e++]=r&255|ka,r/=128;for(;r&Zu;)t[e++]=r&255|ka,r>>>=7;return t[e]=r|0,Da.bytes=e-n+1,t}var ju=Ys,Xu=128,Ta=127;function Ys(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ys.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&Ta)<<s:(i&Ta)*Math.pow(2,s),s+=7}while(i>=Xu);return Ys.bytes=o-n,e}var Qu=Math.pow(2,7),Ju=Math.pow(2,14),tf=Math.pow(2,21),ef=Math.pow(2,28),rf=Math.pow(2,35),nf=Math.pow(2,42),sf=Math.pow(2,49),of=Math.pow(2,56),af=Math.pow(2,63),cf=function(r){return r<Qu?1:r<Ju?2:r<tf?3:r<ef?4:r<rf?5:r<nf?6:r<sf?7:r<of?8:r<af?9:10},lf={encode:Wu,decode:ju,encodingLength:cf},uf=lf,Sr=uf;function Ir(r,t=0){return[Sr.decode(r,t),Sr.decode.bytes]}function We(r,t,e=0){return Sr.encode(r,t,e),t}function Ge(r){return Sr.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=Zt(r),[e,n]=Ir(t),[s,o]=Ir(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 La(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ea(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 Ca(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return hf(e,js(r),t??at.encoder);default:return df(e,js(r),t??le.encoder)}}var Ba=new WeakMap;function js(r){let t=Ba.get(r);if(t==null){let e=new Map;return Ba.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!==Ar)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==pf)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&&La(t.multihash,n.multihash)}toString(t){return Ca(this,t)}toJSON(){return{"/":Ca(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??Pa(n,s,o.bytes))}else if(e[mf]===!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!==Ar)throw new Error(`Version 0 CID must use dag-pb (code: ${Ar}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Pa(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Ar,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 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]=Ir(t.subarray(e));return e+=f,h},s=n(),o=Ar;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]=ff(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 js(o).set(n,t),o}};function ff(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 _r.prefix:{let e=t??_r;return[_r.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 hf(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 df(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 Ar=112,pf=18;function Pa(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 mf=Symbol.for("@ipld/js-cid/CID");var Xs={};At(Xs,{identity:()=>Tt});var Ra=0,gf="identity",Oa=Zt;function bf(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(Ra,Oa(r))}var Tt={code:Ra,name:gf,encode:Oa,digest:bf};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 Ua=Symbol.for("@achingbrain/uint8arraylist");function Na(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?.[Ua]}var ut=class r{bufs;length;[Ua]=!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=Na(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Na(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 Qs={};At(Qs,{base10:()=>yf});var yf=ce({prefix:"9",name:"base10",alphabet:"0123456789"});var Js={};At(Js,{base16:()=>wf,base16upper:()=>xf});var wf=ot({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xf=ot({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var to={};At(to,{base2:()=>Ef});var Ef=ot({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var eo={};At(eo,{base256emoji:()=>Af});var Ma=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}"),vf=Ma.reduce((r,t,e)=>(r[e]=t,r),[]),_f=Ma.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Sf(r){return r.reduce((t,e)=>(t+=vf[e],t),"")}function If(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=_f[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var Af=Ve({prefix:"\u{1F680}",name:"base256emoji",encode:Sf,decode:If});var no={};At(no,{base64:()=>Yt,base64pad:()=>kf,base64url:()=>ro,base64urlpad:()=>Tf});var Yt=ot({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kf=ot({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ro=ot({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Tf=ot({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var so={};At(so,{base8:()=>Df});var Df=ot({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var oo={};At(oo,{identity:()=>Lf});var Lf=Ve({prefix:"\0",name:"identity",encode:r=>_a(r),decode:r=>va(r)});var Gm=new TextEncoder,Zm=new TextDecoder;var co={};At(co,{sha256:()=>ue,sha512:()=>Rf});var Pf=20;function ao({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:s}){return new io(r,t,e,n,s)}var io=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,s,o){this.name=t,this.code=e,this.encode=n,this.minDigestLength=s??Pf,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?Fa(n,this.code,e?.truncate):n.then(s=>Fa(s,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Fa(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 $a(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var ue=ao({name:"sha2-256",code:18,encode:$a("SHA-256")}),Rf=ao({name:"sha2-512",code:19,encode:$a("SHA-512")});var kr={...oo,...to,...so,...Qs,...Js,...Gs,...Zs,...Ws,...no,...eo},i0={...co,...Xs};function Ka(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var qa=Ka("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),lo=Ka("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}),Of={utf8:qa,"utf-8":qa,hex:kr.base16,latin1:lo,ascii:lo,binary:lo,...kr},vn=Of;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 Nf=parseInt("11111",2),uo=parseInt("10000000",2),Uf=parseInt("01111111",2),za={0:Tr,1:Tr,2:Mf,3:$f,4:qf,5:Hf,6:Ff,16:Tr,22:Tr,48:Tr};function fo(r,t={offset:0}){let e=r[t.offset]&Nf;if(t.offset++,za[e]!=null)return za[e](r,t);throw new Error("No decoder for tag "+e)}function Dr(r,t){let e=0;if((r[t.offset]&uo)===uo){let n=r[t.offset]&Uf,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 Tr(r,t){Dr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=fo(r,t);if(n===null)break;e.push(n)}return e}function Mf(r,t){let e=Dr(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 Ff(r,t){let e=Dr(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 Hf(r,t){return t.offset++,null}function $f(r,t){let e=Dr(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 qf(r,t){let e=Dr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Kf(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 ho(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Kf(r.byteLength);return new ut(Uint8Array.from([t.byteLength|uo]),t)}function Va(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]),ho(t),t)}function Wa(r){let t=Uint8Array.from([0]),e=new ut(t,r);return new ut(Uint8Array.from([3]),ho(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]),ho(e),e)}async function Ga(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]),Vf=Uint8Array.from([6,5,43,129,4,0,34]),Wf=Uint8Array.from([6,5,43,129,4,0,35]),Gf={ext:!0,kty:"EC",crv:"P-256"},Zf={ext:!0,kty:"EC",crv:"P-384"},Yf={ext:!0,kty:"EC",crv:"P-521"},po=32,mo=48,go=66;function Za(r){let t=fo(r);return Ya(t)}function Ya(r){let t=r[1][1][0],e=1,n,s;if(t.byteLength===po*2+1)return n=W(t.subarray(e,e+po),"base64url"),s=W(t.subarray(e+po),"base64url"),new je({...Gf,key_ops:["verify"],x:n,y:s});if(t.byteLength===mo*2+1)return n=W(t.subarray(e,e+mo),"base64url"),s=W(t.subarray(e+mo),"base64url"),new je({...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 je({...Yf,key_ops:["verify"],x:n,y:s});throw new kt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function ja(r){return _n([Va(Uint8Array.from([1])),_n([jf(r.crv)],160),_n([Wa(new ut(Uint8Array.from([4]),Z(r.x??"","base64url"),Z(r.y??"","base64url")))],161)]).subarray()}function jf(r){if(r==="P-256")return zf;if(r==="P-384")return Vf;if(r==="P-521")return Wf;throw new kt(`Invalid curve ${r}`)}var je=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=ja(this.jwk)),this._raw}toMultihash(){return Tt.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 Ga(this.jwk,e,t,n)}};function Ee(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=Ee(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");$t(r.outputLen),$t(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 Qa(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 In(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Pt(r,t){return r<<32-t|r>>>t}var Ja=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Xf=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Qt(r){if(U(r),Ja)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Xf[r[e]];return t}var jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Xa(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(Ja)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=Xa(r.charCodeAt(o)),a=Xa(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 bo(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 yo=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function tc(r,t,e){return r&t^~r&e}function ec(r,t,e){return r&t^r&e^t&e}var Lr=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),Qa(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=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()}},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 An=BigInt(4294967295),rc=BigInt(32);function Qf(r,t=!1){return t?{h:Number(r&An),l:Number(r>>rc&An)}:{h:Number(r>>rc&An)|0,l:Number(r&An)|0}}function nc(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}=Qf(r[o],t);[n[o],s[o]]=[i,a]}return[n,s]}var wo=(r,t,e)=>r>>>e,xo=(r,t,e)=>r<<32-e|t>>>e,ve=(r,t,e)=>r>>>e|t<<32-e,_e=(r,t,e)=>r<<32-e|t>>>e,Cr=(r,t,e)=>r<<64-e|t>>>e-32,Br=(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 sc=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),oc=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ic=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),ac=(r,t,e,n,s)=>t+e+n+s+(r/2**32|0)|0,cc=(r,t,e,n,s)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(s>>>0),lc=(r,t,e,n,s,o)=>t+e+n+s+o+(r/2**32|0)|0;var th=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),Eo=class extends Lr{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+tc(a,c,l)+th[h]+fe[h]|0,_=(Pt(n,2)^Pt(n,13)^Pt(n,22))+ec(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)}},vo=class extends Eo{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 uc=nc(["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))),eh=uc[0],rh=uc[1],he=new Uint32Array(80),de=new Uint32Array(80),_o=class extends Lr{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=ve(A,R,1)^ve(A,R,8)^wo(A,R,7),F=_e(A,R,1)^_e(A,R,8)^xo(A,R,7),v=he[x-2]|0,E=de[x-2]|0,O=ve(v,E,19)^Cr(v,E,61)^wo(v,E,6),H=_e(v,E,19)^Br(v,E,61)^xo(v,E,6),L=ic(F,H,de[x-7],de[x-16]),g=ac(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=ve(h,f,14)^ve(h,f,18)^Cr(h,f,41),R=_e(h,f,14)^_e(h,f,18)^Br(h,f,41),M=h&p^~h&_,F=f&d^~f&w,v=cc(I,R,F,rh[x],de[x]),E=lc(v,y,A,M,eh[x],he[x]),O=v|0,H=ve(n,s,28)^Cr(n,s,34)^Cr(n,s,39),L=_e(n,s,28)^Br(n,s,34)^Br(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=sc(O,L,b);n=oc(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)}},So=class extends _o{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 fc=bo(()=>new vo,yo(1));var hc=bo(()=>new So,yo(3));var Ao=BigInt(0),Io=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 dc(r){if(typeof r=="bigint"){if(!kn(r))throw new Error("positive bigint expected, got "+r)}else $t(r);return r}function Pr(r){let t=dc(r).toString(16);return t.length&1?"0"+t:t}function pc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ao:BigInt("0x"+r)}function tr(r){return pc(Qt(r))}function Se(r){return pc(Qt(Dn(U(r)).reverse()))}function Tn(r,t){$t(t),r=dc(r);let e=Jt(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function ko(r,t){return Tn(r,t).reverse()}function Dn(r){return Uint8Array.from(r)}var kn=r=>typeof r=="bigint"&&Ao<=r;function nh(r,t,e){return kn(r)&&kn(t)&&kn(e)&&t<=r&&r<e}function Rr(r,t,e,n){if(!nh(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function To(r){let t;for(t=0;r>Ao;r>>=Io,t+=1);return t}var Or=r=>(Io<<BigInt(r))-Io;function mc(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 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),Ie=BigInt(2),yc=BigInt(3),wc=BigInt(4),xc=BigInt(5),sh=BigInt(7),Ec=BigInt(8),oh=BigInt(9),vc=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 gc(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 Lo(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function _c(r,t){let e=(r.ORDER+ft)/wc,n=r.pow(t,e);return Lo(r,n,t),n}function ih(r,t){let e=(r.ORDER-xc)/Ec,n=r.mul(t,Ie),s=r.pow(n,e),o=r.mul(t,s),i=r.mul(r.mul(o,Ie),s),a=r.mul(o,r.sub(i,r.ONE));return Lo(r,a,t),a}function ah(r){let t=rr(r),e=Sc(r),n=e(t,t.neg(t.ONE)),s=e(t,n),o=e(t,t.neg(n)),i=(r+sh)/vc;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 Lo(a,w,c),w}}function Sc(r){if(r<yc)throw new Error("sqrt is not defined for small field");let t=r-ft,e=0;for(;t%Ie===_t;)t/=Ie,e++;let n=Ie,s=rr(r);for(;bc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return _c;let o=s.pow(n,t),i=(t+ft)/Ie;return function(c,l){if(c.is0(l))return l;if(bc(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 ch(r){return r%wc===yc?_c:r%Ec===xc?ih:r%vc===oh?ah(r):Sc(r)}var Ic=(r,t)=>(it(r,t)&ft)===ft,lh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Co(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=lh.reduce((n,s)=>(n[s]="function",n),t);return pe(r,e),r}function uh(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 Nr(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 bc(r,t){let e=(r.ORDER-ft)/Ie,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 fh(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 Do=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}=fh(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 uh(this,t,e)}div(t,e){return it(t*gc(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 gc(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=ch(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?ko(t,this.BYTES):Tn(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?Se(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 Nr(this,t)}cmov(t,e,n){return n?e:t}};function rr(r,t={}){return new Do(r,t)}function Ac(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 Bo(r){let t=Ac(r);return t+Math.ceil(t/2)}function Po(r,t,e=!1){U(r);let n=r.length,s=Ac(t),o=Bo(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=e?Se(r):tr(r),a=it(i,t-ft)+ft;return e?ko(a,s):Tn(a,s)}var nr=BigInt(0),Ae=BigInt(1);function Ur(r,t){let e=t.negate();return r?e:t}function ke(r,t){let e=Nr(r.Fp,t.map(n=>n.Z));return t.map((n,s)=>r.fromAffine(n.toAffine(e[s])))}function Lc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Ro(r,t){Lc(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),s=2**r,o=Or(r),i=BigInt(r);return{windows:e,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function kc(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+=Ae);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 Oo=new WeakMap,Cc=new WeakMap;function No(r){return Cc.get(r)||1}function Tc(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&Ae&&(n=n.add(s)),s=s.double(),e>>=Ae;return n}precomputeWindow(t,e){let{windows:n,windowSize:s}=Ro(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=Ro(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:f,offsetF:p}=kc(n,a,i);n=c,u?o=o.add(Ur(f,e[p])):s=s.add(Ur(h,e[l]))}return Tc(n),{p:s,f:o}}wNAFUnsafe(t,e,n,s=this.ZERO){let o=Ro(t,this.bits);for(let i=0;i<o.windows&&n!==nr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=kc(n,i,o);if(n=a,!l){let h=e[c];s=s.add(u?h.negate():h)}}return Tc(n),s}getPrecomputes(t,e,n){let s=Oo.get(e);return s||(s=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(s=n(s)),Oo.set(e,s))),s}cached(t,e,n){let s=No(t);return this.wNAF(s,this.getPrecomputes(s,t,n),e)}unsafe(t,e,n,s){let o=No(t);return o===1?this._unsafeLadder(t,e,s):this.wNAFUnsafe(o,this.getPrecomputes(o,t,n),e,s)}createCache(t,e){Lc(e,this.bits),Cc.set(t,e),Oo.delete(t)}hasCache(t){return No(t)!==1}};function Bc(r,t,e,n){let s=t,o=r.ZERO,i=r.ZERO;for(;e>nr||n>nr;)e&Ae&&(o=o.add(s)),n&Ae&&(i=i.add(s)),s=s.double(),e>>=Ae,n>>=Ae;return{p1:o,p2:i}}function Dc(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Co(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=Dc(t.p,e.Fp,n),o=Dc(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),Uo=BigInt(2),hh=BigInt(8);function dh(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 Pc(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=Uo<<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(!dh(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 Rr("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?hh: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")),ee(I,"zip215");let M=Dn(y),F=y[x-1];M[x-1]=F&-129;let v=Se(M),E=I?a:n.ORDER;Rr("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(Uo),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(Uo*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=>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 Qt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let _=new sr(d,s.BITS);return d.BASE.precompute(8),d}function Rc(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(ee(O,"phflag"),E.length||O)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(Se(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=Se(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 Ee(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 ph=BigInt(1),Oc=BigInt(2);var mh=BigInt(5),gh=BigInt(8),Mo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),bh={p:Mo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:gh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function yh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),s=BigInt(80),o=Mo,a=r*r%o*r%o,c=Q(a,Oc,o)*a%o,l=Q(c,ph,o)*r%o,u=Q(l,mh,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,Oc,o)*r%o,b2:a}}function wh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Nc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function xh(r,t){let e=Mo,n=it(t*t*t,e),s=it(n*n*t,e),o=yh(r*s).pow_p_5_8,i=it(r*n*o,e),a=it(t*i*i,e),c=i,l=it(i*Nc,e),u=a===r,h=a===it(-r,e),f=a===it(-r*Nc,e);return u&&(i=c),(h||f)&&(i=l),Ic(i,e)&&(i=it(-i,e)),{isValid:u||h,value:i}}var Eh=Pc(bh,{uvRatio:xh});function vh(r){return Rc(Eh,hc,Object.assign({adjustScalarBytes:wh},r))}var Uc=vh({});var Bn=32;var Fo,_h=(async()=>{try{return await yn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Sh(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 Ih(r,t,e){return Uc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Mc(r,t,e){return Fo==null&&(Fo=await _h),Fo?Sh(r,t,e):Ih(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=Ho(t,Bn)}toMultihash(){return Tt.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=Mc(this.raw,e,t);return Pn(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Hc(r){return r=Ho(r,Bn),new Rn(r)}function Ho(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 kh=Math.pow(2,7),Th=Math.pow(2,14),Dh=Math.pow(2,21),$o=Math.pow(2,28),qo=Math.pow(2,35),Ko=Math.pow(2,42),zo=Math.pow(2,49),K=128,xt=127;function J(r){if(r<kh)return 1;if(r<Th)return 2;if(r<Dh)return 3;if(r<$o)return 4;if(r<qo)return 5;if(r<Ko)return 6;if(r<zo)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|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 Lh(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 Vo(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)*$o,e<K)||(e=r[t+5],n+=(e&xt)*qo,e<K)||(e=r[t+6],n+=(e&xt)*Ko,e<K)||(e=r[t+7],n+=(e&xt)*zo,e<K))return n;throw new RangeError("Could not decode varint")}function Ch(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)*$o,e<K)||(e=r.get(t+5),n+=(e&xt)*qo,e<K)||(e=r.get(t+6),n+=(e&xt)*Ko,e<K)||(e=r.get(t+7),n+=(e&xt)*zo,e<K))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):Lh(r,t,e)}function Te(r,t=0){return r instanceof Uint8Array?Vo(r,t):Ch(r,t)}var Go=new Float32Array([-0]),ge=new Uint8Array(Go.buffer);function $c(r,t,e){Go[0]=r,t[e]=ge[0],t[e+1]=ge[1],t[e+2]=ge[2],t[e+3]=ge[3]}function qc(r,t){return ge[0]=r[t],ge[1]=r[t+1],ge[2]=r[t+2],ge[3]=r[t+3],Go[0]}var Zo=new Float64Array([-0]),Et=new Uint8Array(Zo.buffer);function Kc(r,t,e){Zo[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 zc(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],Zo[0]}var Bh=BigInt(Number.MAX_SAFE_INTEGER),Ph=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 De;if(t<Bh&&t>Ph)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>Vc&&(s=0n,++n>Vc&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return De;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):De}},De=new Dt(0,0);De.toBigInt=function(){return 0n};De.zzEncode=De.zzDecode=function(){return this};De.length=function(){return 1};var Vc=4294967296n;function Wc(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 Gc(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 Yo(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 jo=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=qc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Rt(this,4);let t=zc(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 Gc(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=Vo(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 Mr(r){return new jo(r instanceof Uint8Array?r:r.subarray())}function Kt(r,t,e){let n=Mr(r);return t.decode(n,void 0,e)}function Xo(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 Le=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Qo(){}var ti=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Rh=Xo();function Oh(r){return globalThis.Buffer!=null?wt(r):Rh(r)}var Hr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Le(Qo,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Le(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ei((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(Jo,1,t?1:0)}fixed32(t){return this._push(Fr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Dt.fromBigInt(t);return this._push(Fr,4,e.lo)._push(Fr,4,e.hi)}fixed64Number(t){let e=Dt.fromNumber(t);return this._push(Fr,4,e.lo)._push(Fr,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($c,4,t)}double(t){return this._push(Kc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Jo,1,0):this.uint32(e)._push(Uh,e,t)}string(t){let e=Wc(t);return e!==0?this.uint32(e)._push(Yo,e,t):this._push(Jo,1,0)}fork(){return this.states=new ti(this),this.head=this.tail=new Le(Qo,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 Le(Qo,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=Oh(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Jo(r,t,e){t[e]=r&255}function Nh(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ei=class extends Le{next;constructor(t,e){super(Nh,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 Fr(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 Uh(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Hr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Mh,t,r),this},Hr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Fh,t,r),this});function Mh(r,t,e){t.set(r,e)}function Fh(r,t,e){r.length<40?Yo(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Z(r),e)}function ri(){return new Hr}function zt(r,t){let e=ri();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*Vt(r,t,e){let n=Mr(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 Wt(r,t,e){return Fn("message",Mn.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 ni;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ni||(ni={}));(function(r){r.codec=()=>ir(ni)})(St||(St={}));var $r;(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})($r||($r={}));var si;(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})(si||(si={}));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),Xt(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()}},oi=(r,t,e)=>new Hn(r,t).update(e).digest();oi.create=(r,t)=>new Hn(r,t);var Yc=(r,t)=>(r+(r>=0?t:-t)/jc)/t;function $h(r,t,e){let[[n,s],[o,i]]=t,a=Yc(i*r,e),c=Yc(-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=Or(Math.ceil(To(e)/2))+ar;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 ai(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ii(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&&ai(e.format),e}var ci=class extends Error{constructor(t=""){super(t)}},be={Err:ci,_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=Pr(n);if(s.length/2&128)throw new e("tlv.encode: long form length too big");let o=n>127?Pr(s.length/2|128):"";return Pr(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=Pr(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)}},ne=BigInt(0),ar=BigInt(1),jc=BigInt(2),$n=BigInt(3),qh=BigInt(4);function Xc(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=Jc(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(Qc(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,$n),qh),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 $h(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 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=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=Ur(m,g),b=Ur(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($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: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,$n),{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,$n),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=>ke(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 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===ne||m.is0())return E.ZERO;if(g===ar)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}=Bc(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===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 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 sr(E,t.endo?Math.ceil(O/2):O);return E.BASE.precompute(8),E}function Qc(r){return Uint8Array.of(r?2:3)}function Jc(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Kh(r,t={}){let{Fn:e}=r,n=t.randomBytes||Je,s=Object.assign(Jc(r.Fp,e),{seed:Bo(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 Po(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(!Ee(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 tl(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)=>oi(t,b,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p}=Kh(r,e),d={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},_=a*jc<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){ai(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(Qc((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(ai(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=tr(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=Or(c);function v(b){return Rr("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}=ii(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 an=i.create(Ft*i.create(X+bt*P));if(an===ne)return;let ma=(st.x===bt?0:2)|Number(st.y&ar),ga=an;return k&&w(an)&&(ga=i.neg(an),ma^=1),new A(bt,ga,_?void 0:ma)}return{seed:rt,k2sig:q}}function H(b,m,S={}){let{seed:k,k2sig:D}=O(b,m,S);return mc(t.outputLen,i.BYTES,s)(k,D).toBytes(S.format)}function L(b,m,S,k={}){let{lowS:D,prehash:C,format:T}=ii(k,d);if(S=U(S,void 0,"publicKey"),m=E(m,C),!Ee(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}=ii(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 ui={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 el=BigInt(2);function Vh(r){let t=ui.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,el,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,el,t);if(!li.eql(li.sqr(M),r))throw new Error("Cannot find square root");return M}var li=rr(ui.p,{sqrt:Vh}),Wh=Xc(ui,{Fp:li,endo:zh}),cr=tl(Wh,fc);function rl(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 vr(String(o))});try{return n?.signal?.throwIfAborted(),cr.verify(t,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new vr(String(o))}}var qn=class{type="secp256k1";raw;_key;constructor(t){this._key=sl(t),this.raw=nl(this._key)}toMultihash(){return Tt.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 rl(this._key,e,t,n)}};function ol(r){return new qn(r)}function nl(r){return cr.Point.fromBytes(r).toBytes()}function sl(r){try{return cr.Point.fromBytes(r),r}catch(t){throw new un(String(t))}}function il(r){let{Type:t,Data:e}=$r.decode(r.digest),n=e??new Uint8Array;switch(t){case St.Ed25519:return Hc(n);case St.secp256k1:return ol(n);case St.ECDSA:return Za(n);default:throw new Er}}function Xe(r){return $r.encode({Type:St[r.type],Data:r.raw})}var fi={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},al={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},cl=new globalThis.TextEncoder;function Gh(r,t){let e=fi[t],n=al[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function Zh(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=fi[t],s=al[t],o=r;for(;o.length>0;){let i=cl.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 hi(r,{size:t=32,utf8Buffer:e}={}){if(!fi[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 Zh(r,t,e);r=cl.encode(r)}return Gh(r,t)}var qr={hash:r=>Number(hi(r,{size:32})),hashV:(r,t)=>Yh(qr.hash(r,t))};function Yh(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),Z(t,"base16")}var di=64,Ot=class{fp;h;seed;constructor(t,e,n,s=2){if(s>di)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 Ce(r,t){return Math.floor(Math.random()*(t-r))+r}var Be=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=Ce(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 jh=500,Kr=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??qr,this.seed=t.seed??Ce(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 Be(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Be(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[Ce(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Be(this.bucketSize));for(let a=0;a<jh;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 Be(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}},Xh={1:.5,2:.84,4:.95,8:.98};function Qh(r=.001){return r>.002?2:r>1e-5?4:8}function ll(r,t=.001){let e=Qh(t),n=Xh[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),di);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??qr,this.seed=t.seed??Ce(0,Math.pow(2,10)),this.filterSeries=[new Kr({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 Kr({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({...ll(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 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 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 Jh=45,td=15,Gn=new Wn;function ul(r){if(!(r.length>td))return Gn.new(r).parseWith(()=>Gn.readIPv4Addr())}function fl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Jh))return Gn.new(r).parseWith(()=>Gn.readIPv6Addr())}function lr(r){return!!ul(r)}function Zn(r){return!!fl(r)}var ml=ya(pl(),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 ml.Netmask(r));function xi(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 xi(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 xi(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 gl(r){if(lr(r))return xi(r);if(ud(r))return fd(r);if(hd(r))return dd(r);if(Zn(r))return pd(r)}function bl(r){try{let t=Vn(r);switch(t.type){case"ip4":case"ip6":return gl(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 Ei=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 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 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 Ei)},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 vi=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},yl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function _i(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(yl(i));return}if(i&&(c=()=>{f(yl(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,f),e===Number.POSITIVE_INFINITY)return;let p=new vi;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=_i(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=bd(r,t,e),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Si(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 yd(r){return r.reason}async function zr(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 ts=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 es=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 ts(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 zr(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 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=Si(this.emitEmpty.bind(this),1),this.emitIdle=Si(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 es(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"},se=class extends Error{static name="ValidationError";name="ValidationError"},rs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ns=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Ai(r){return t=>W(t,r)}function ki(r){return t=>Z(t,r)}function mr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Re(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function wl(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=Re(n);return Ct([e,s],e.length+s.length)}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!==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=Re(n);return Ct([e,s],e.length+s.length)}function Ti(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 Di=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},El=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=Di(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},vl=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(".")},_l=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 Sl(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 Ii=Object.values(kr).map(r=>r.decoder),xd=(function(){let r=Ii[0].or(Ii[1]);return Ii.slice(2).forEach(t=>r=r.or(t)),r})();function Il(r){return xd.decode(r)}function Al(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 Vr=Sd(Ed,vd,_d(65535));var dt=-1,Li=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 ns(`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 Li,Fd=[{code:4,name:"ip4",size:32,valueToBytes:Di,bytesToValue:vl,validate:r=>{if(!lr(r))throw new se(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Re,bytesToValue:mr,validate:Vr},{code:273,name:"udp",size:16,valueToBytes:Re,bytesToValue:mr,validate:Vr},{code:33,name:"dccp",size:16,valueToBytes:Re,bytesToValue:mr,validate:Vr},{code:41,name:"ip6",size:128,valueToBytes:El,bytesToValue:_l,stringToValue:Sl,validate:r=>{if(!Zn(r))throw new se(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:dt},{code:43,name:"ipcidr",size:8,bytesToValue:Ai("base10"),valueToBytes:ki("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:Re,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:Ai("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ki("base58btc")(r):et.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ti,valueToBytes:wl},{code:445,name:"onion3",size:296,bytesToValue:Ti,valueToBytes:xl},{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:Al(ro),valueToBytes:Il},{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 kl(r){let t=[],e=0;for(;e<r.length;){let n=Te(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 Tl(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 Dl(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 Ll(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:Te(t,e)}var $d=Symbol.for("nodejs.util.inspect.custom"),qi=Symbol.for("@multiformats/multiaddr");function qd(r){if(r==null&&(r="/"),Cl(r))return r.getComponents();if(r instanceof Uint8Array)return kl(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Dl(r);if(Array.isArray(r))return r;throw new gt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var cs=class r{[qi]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=qd(t),e.validate!==!1&&Kd(this)}get bytes(){return this.#r==null&&(this.#r=Tl(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Ll(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 rs(`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 Cl(r){return!!r?.[qi]}function ls(r){return new cs(r)}var us=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},yr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},fs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Xr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function hs(r){return r[Symbol.asyncIterator]!=null}function Bl(r,t){if(r.byteLength>t)throw new yr("Message length too long")}var ps=r=>{let t=J(r),e=wt(t);return On(r,e),ps.bytes=t,e};ps.bytes=0;function ms(r,t){t=t??{};let e=t.lengthEncoder??ps,n=t?.maxDataLength??4194304;function*s(o){Bl(o,n);let i=e(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return hs(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}ms.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??ps,n=t?.maxDataLength??4194304;return Bl(r,n),new ut(e(r.byteLength),r)};var Ne;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ne||(Ne={}));var Ki=r=>{let t=Te(r);return Ki.bytes=J(t),t};Ki.bytes=0;function Qr(r,t){let e=new ut,n=Ne.LENGTH,s=-1,o=t?.lengthDecoder??Ki,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Ne.LENGTH)try{if(s=o(e),s<0)throw new us("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=Ne.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new fs("Message length length too long");break}throw l}if(n===Ne.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=Ne.LENGTH}}}return hs(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 gs=class extends pr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var zi=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 Pl(r){let{name:t,metrics:e}=r,n;return e!=null?n=new zi({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 Vi=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 Rl=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=Rl(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 Ol=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 Nl=Qd;var bs=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Ue(r,t,e,n){let s=new bs(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(){Gi(e,"abort",h),Gi(r,t,l),Gi(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)};Wi(e,"abort",h),Wi(r,t,l),Wi(r,o,u)})}function Wi(r,t,e){r!=null&&(Ul(r)?r.addEventListener(t,e):r.addListener(t,e))}function Gi(r,t,e){r!=null&&(Ul(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function Ul(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 Zi;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Zi||(Zi={}));(function(r){r.codec=()=>ir(Zi)})(tt||(tt={}));var Me;(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})(Me||(Me={}));var tn;(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),Me.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(Me.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 Me.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})(tn||(tn={}));var Fe;(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})(Fe||(Fe={}));var Lt;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Lt||(Lt={}));var ys;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(ys||(ys={}));(function(r){r.codec=()=>ir(ys)})(Lt||(Lt={}));var He;(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&&ys[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})(He||(He={}));var $e;(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),tn.codec().encode(o.wantlist,i)),o.blocks!=null&&o.blocks.length>0)for(let c of o.blocks)i.uint32(26),Fe.codec().encode(c,i);if(o.blockPresences!=null&&o.blockPresences.length>0)for(let c of o.blockPresences)i.uint32(34),He.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 re('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Fe.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(He.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 re('Streaming decode error - repeated field "blocks" had too many elements');for(let f of Fe.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 He.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})($e||($e={}));function Ml(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 ws=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var Jd=4193648,tp=Jd+16;function*Fl(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=$e.encode(l).byteLength,{added:h,hasMore:f,newSize:p}=Yi(s,l.blocks,a,t,u,ep);a+=h,u=p;let d=f;({added:h,hasMore:f,newSize:p}=Yi(n,l.blockPresences,i,t,u,rp)),i+=h,u=p;let _=f;if({added:h,hasMore:f,newSize:p}=Yi(e,l.wantlist.entries,o,t,u,np),o+=h,u=p,c=!d&&!_&&!f,c||(l.wantlist.full=!1),yield $e.encode(l),c)break}}function Yi(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 ws("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 ji(3,Fe.encode(r))}function rp(r){return ji(4,He.encode(r))}function np(r){return ji(1,Me.encode(r))}function ji(r,t){let e=J(r),n=J(t.byteLength);return e+n+t.byteLength}var xs=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??[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 gs({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=$e.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 Vi(Ol(Nl(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=Ml(s.options.message,e),await s.join({signal:n?.signal});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:network:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,Jr,o);await a.closeRead(o);try{for(let c of Fl(i,this.maxOutgoingMessageSize))a.send(ms.single(c))||await a.onDrain(o);await a.close(o)}catch(c){o?.onProgress?.(new V("bitswap:network:send-wantlist:error",{peer:t,error:c})),this.log.error("error sending message to %p - %e",t,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:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Ue(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 $l=Symbol.for("nodejs.util.inspect.custom"),dp=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(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")}[$l](){return`PeerId(${this.toString()})`}},Es=class extends en{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},vs=class extends en{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},_s=class extends en{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},pp=2336,rn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Tt.digest(Z(this.url))}[$l](){return`PeerId(${this.url})`}[gn]=!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,ql=2336;function gp(r){if(yp(r))return new Es({multihash:r});if(bp(r))try{let t=il(r);if(t.type==="Ed25519")return new vs({multihash:r,publicKey:t});if(t.type==="secp256k1")return new _s({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 Kl(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==mp&&r.code!==ql)throw new fn("Supplied PeerID CID is invalid");if(r.code===ql){let t=W(r.multihash.digest);return new rn(new URL(t))}return gp(r.multihash)}function bp(r){return r.code===Tt.code}function yp(r){return r.code===ue.code}function Ss(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 Ss(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 Ss(this.map.values(),t=>t.key)}values(){return Ss(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Xi=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 Xi({name:t,metrics:e}):n=new nn,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 zl=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=On(n,t,e),e+=J(n);return t}var Vl=Ep;function Qi(r){return Vl([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Is=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 zl(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:Qi(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:Qi(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 As=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 Is({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=ya(Gl(),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 ks=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var qe=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=zn(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: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 zr(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 zr(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 ks(`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 Ji=class extends qe{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(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 Zl(r,t){return new Ji(r,t)}var Ts=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=Te(r);t.push(e),r=r.slice(J(e))}return t}var Yl=Tp;var Ds=class extends Ht{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(t,e={}){super(),this.peers=sn({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Pl({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 Ue(this,"block",e?.signal,{filter:a=>ct(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Ue(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 Ue(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 Ue(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=Yl(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),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 Ls=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 Ts(t),this.network=new xs(t,e),this.peerWantLists=new As({...t,network:this.network},e),this.wantList=new Ds({...t,network:this.network},e)}createSession(t={}){return Zl({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,s=wa([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 jl=(r,t={})=>new Ls(r,t);var ta=class{name="bitswap";bitswap;started;constructor(t,e={}){this.bitswap=jl(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:n=>{if(e?.onProgress!=null)if(e.onProgress(n),n.type==="connection:open"){if(!ze(n.detail))return;e.onProgress(new V("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:n.detail,cid:t}))}else n.type==="connection:opened"?e.onProgress(new V("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:n.detail.remotePeer,address:n.detail.remoteAddr,cid:t})):n.type==="connection:open-stream"?e.onProgress(new V("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:n.detail.connection.remotePeer,cid:t})):n.type==="bitswap:block"&&e.onProgress(new V("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:n.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 Xl(r={}){return t=>new ta(t,r)}var Dp=[6,53,56,54,55];function Ql(r){return eu("sni",r)?.value}function Jl(r){let t=eu("tcp",r)?.value;return t==null?"":`:${t}`}function eu(r,t){return t.find(e=>e.name===r)}function tu(r){return r.some(({code:t})=>t===448)}function Ut(r,t){let e=ru[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 ru={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=tu(t),n=Ql(t),s=Jl(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=tu(t),n=Ql(t),s=Jl(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 Cs(r,t){let n=ls(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=ru[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 nu="[a-fA-F\\d:]",we=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${nu})|(?<=${nu})(?=\\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}",Bs=`
|
|
3
|
+
(?:
|
|
4
|
+
(?:${lt}:){7}(?:${lt}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
5
|
+
(?:${lt}:){6}(?:${Mt}|:${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}(?::${Mt}|(?::${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}:${Mt}|(?::${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}:${Mt}|(?::${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}:${Mt}|(?::${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}:${Mt}|(?::${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}:${Mt}|(?::${lt}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
12
|
+
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
13
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Lp=new RegExp(`(?:^${Mt}$)|(?:^${Bs}$)`),Cp=new RegExp(`^${Mt}$`),Bp=new RegExp(`^${Bs}$`),ea=r=>r&&r.exact?Lp:new RegExp(`(?:${we(r)}${Mt}${we(r)})|(?:${we(r)}${Bs}${we(r)})`,"g");ea.v4=r=>r&&r.exact?Cp:new RegExp(`${we(r)}${Mt}${we(r)}`,"g");ea.v6=r=>r&&r.exact?Bp:new RegExp(`${we(r)}${Bs}${we(r)}`,"g");var ra=ea;function na(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function su(){return!1}var{toString:Pp}=Object.prototype;function sa(r){return Pp.call(r)==="[object RegExp]"}var ou={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function oa(r,t={}){if(!sa(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(ou).map(s=>(typeof t[s]=="boolean"?t[s]:r[s])?ou[s]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function ia(r,t,{timeout:e}={}){try{return na(()=>oa(r).test(t),{timeout:e})()}catch(n){if(su(n))return!1;throw n}}var Rp=15,Op=45,iu={timeout:400};function aa(r){return r.length>Op?!1:ia(ra.v6({exact:!0}),r,iu)}function au(r){return r.length>Rp?!1:ia(ra.v4({exact:!0}),r,iu)}var cu={http:"80",https:"443",ws:"80",wss:"443"},Np=["http","https","ws","wss"];function lu(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:s,port:o,path:i}=Up(r),a=[Mp(s,e),Fp(o,n),Hp(n)];i!=null&&a.push($p(i));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return ls(c)}function Up(r){let[t]=r.split(":");Np.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=qp(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 Mp(r,t){if(!(r==null||r==="")){if(au(r))return["ip4",r];if(aa(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(aa(e))return["ip6",e]}return[t,r]}}function Fp(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function Hp(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function $p(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function qp(r){if(!(r==null||r===""||cu[r]==null))return cu[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)}}),uu=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}}),z=(...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 Kp=B(421),$E=j(Kp),Rs=B(54),Os=B(55),Ns=B(56),la=B(53),qE=j(Rs,$(B(421))),KE=j(Os,$(B(421))),zE=j(Ns,$(B(421))),fu=j(vt(la,Ns,Rs,Os),$(B(421))),hu=z(B(4),$(B(43))),du=z($(B(42)),B(41),$(B(43))),ua=vt(hu,du),Ke=vt(ua,la,Rs,Os,Ns),VE=j(vt(ua,z(vt(la,Ns,Rs,Os),$(B(421))))),WE=j(hu),GE=j(du),ZE=j(ua),fa=z(Ke,B(6)),on=z(Ke,B(273)),YE=j(z(fa,$(B(421)))),jE=j(on),ha=z(on,Y(460),$(B(421))),Us=z(on,Y(461),$(B(421))),zp=vt(ha,Us),XE=j(ha),QE=j(Us),ca=vt(Ke,fa,on,ha,Us),pu=vt(z(ca,Y(477),$(B(421)))),JE=j(pu),mu=vt(z(ca,Y(478),$(B(421))),z(ca,Y(448),$(B(449)),Y(477),$(B(421)))),tv=j(mu),gu=z(on,Y(280),$(B(466)),$(B(466)),$(B(421))),ev=j(gu),bu=z(Us,Y(465),$(B(466)),$(B(466)),$(B(421))),rv=j(bu),Ps=vt(pu,mu,z(fa,$(B(421))),z(zp,$(B(421))),z(Ke,$(B(421))),gu,bu,B(421)),nv=j(Ps),Vp=z($(Ps),Y(290),uu(Y(281)),$(B(421))),sv=j(Vp),Wp=vt(z(Ps,Y(290),Y(281),$(B(421))),z(Ps,Y(281),$(B(421))),z(Y(281),$(B(421)))),ov=j(Wp),Gp=vt(z(Ke,B(6),Y(480),$(B(421))),z(Ke,Y(480),$(B(421)))),yu=j(Gp),Zp=z(Ke,vt(z(B(6,"443"),Y(480)),z(B(6),Y(443)),z(B(6),Y(448),Y(480)),z(Y(448),Y(480)),Y(448),Y(443)),$(B(421))),wu=j(Zp),Yp=vt(z(B(777),$(B(421)))),iv=j(Yp),jp=vt(z(B(400),$(B(421)))),av=j(jp);function da(r,t,e){return r.filter(n=>{if(wu.matches(n)||t&&yu.matches(n))return e||fu.matches(n)?!0:bl(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*Ms(r,t,e,n,s,o={}){for await(let i of t.findProviders(r,o)){let a=da(i.multiaddrs,n,s);if(a.length===0)continue;let c=new URL(Cs(a[0]));yield new xr(c,{logger:e,transformRequestInit:o.transformRequestInit,routing:i.routing})}}async function xu(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 Xp=2336,xr=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=Kl(et.createV1(Xp,Tt.digest(Z(this.url.toString()))))}#o(t){let e=t.multihash.bytes;return Yt.encode(e)}async getRawBlock(t,e={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${t.toString()}`;let s=e.maxSize??Eu;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
|
|
3
14
|
%s %s HTTP/1.1
|
|
4
15
|
%s
|
|
5
|
-
`,
|
|
6
|
-
`)),c=fetch(
|
|
16
|
+
`,u.method??"GET",n,[...h.entries()].map(([f,p])=>`${f}: ${p}`).join(`
|
|
17
|
+
`)),e.onProgress?.(new V("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:t})),c=fetch(n.toString(),u).then(async f=>{if(this.log(`received response
|
|
7
18
|
HTTP/1.1 %d %s
|
|
8
19
|
%s
|
|
9
|
-
`,
|
|
10
|
-
`)),!
|
|
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:lu(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 xu(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 pa=class extends qe{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??Fs,this.allowLocal=e.allowLocal??Hs,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*Ms(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=da(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(s.length===0)return;let o=Cs(s[0]);return new xr(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 vu(r,t){return new pa(r,t)}var $s=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??Fs,this.allowLocal=e.allowLocal??Hs,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let s of Ms(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 vu({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Fs=!1,Hs=!1,Eu=2097152;function _u(r={}){return t=>new $s(t,r)}return Du(Qp);})();
|
|
22
|
+
/*! Bundled license information:
|
|
23
|
+
|
|
24
|
+
@noble/hashes/utils.js:
|
|
25
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
26
|
+
|
|
27
|
+
@noble/curves/utils.js:
|
|
28
|
+
@noble/curves/abstract/modular.js:
|
|
29
|
+
@noble/curves/abstract/curve.js:
|
|
30
|
+
@noble/curves/abstract/edwards.js:
|
|
31
|
+
@noble/curves/ed25519.js:
|
|
32
|
+
@noble/curves/abstract/weierstrass.js:
|
|
33
|
+
@noble/curves/secp256k1.js:
|
|
34
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
35
|
+
*/
|
|
11
36
|
return HeliaBlockBrokers}));
|
|
12
37
|
//# sourceMappingURL=index.min.js.map
|