@helia/block-brokers 5.0.12 → 5.0.13-b0033ca2
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 +5 -5
- package/dist/index.min.js.map +3 -3
- package/package.json +4 -4
- package/dist/typedoc-urls.json +0 -10
package/dist/index.min.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
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 Yo=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,ri=Object.prototype.hasOwnProperty;var ls=(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})},us=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ei(e))!ri.call(r,s)&&s!==t&&_t(r,s,{get:()=>e[s],enumerable:!(n=Yo(e,s))||n.enumerable});return r};var hs=(r,e,t)=>(t=r!=null?Jo(ti(r)):{},us(e||!r||!r.__esModule?_t(t,"default",{value:r,enumerable:!0}):t,r)),ni=r=>us(_t({},"__esModule",{value:!0}),r);var js=ls(at=>{(function(){var r,e,t,n,s,o,i,a;a=function(c){var l,u,h,f;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,f=c&255,[l,u,h,f].join(".")},i=function(c){var l,u,h,f,d,m;for(l=[],h=f=0;f<=3&&c.length!==0;h=++f){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=e(c),d=m[0],u=m[1],c=c.substring(u),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,u,h,f,d;for(f=0,l=10,u="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,u="7")),d=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)f=f*l+(t(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")f=f*l+(10+t(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")f=f*l+(10+t(c[h])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");h++}if(h===d)throw new Error("empty octet");return[f,h]},r=(function(){function c(l,u){var h,f,d,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(m=l.split("/",2),l=m[0],u=m[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(b){throw h=b,new Error("Invalid mask: "+u)}for(f=d=32;d>=0;f=--d)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(u||u===0)this.bitmask=parseInt(u,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: "+u);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 u,h,f;for(f=i(this.first),h=i(this.last),u=0;f<=h;)l(a(f),f,u),u++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),at.ip2long=i,at.long2ip=a,at.Netmask=r}).call(at)});var To=ls((Ep,Lo)=>{Lo.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 el={};$(el,{bitswap:()=>Po,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 si=Symbol.for("@libp2p/peer-id");function Dt(r){return!!r?.[si]}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 fs(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.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 B=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Nr={};$(Nr,{base58btc:()=>X,base58flickr:()=>hi});var al=new Uint8Array(0);function ds(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 ps(r){return new TextEncoder().encode(r)}function ms(r){return new TextDecoder().decode(r)}function oi(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),u=Math.log(256)/Math.log(a);function h(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var b=0,w=0,L=0,F=m.length;L!==F&&m[L]===0;)L++,b++;for(var A=(F-L)*u+1>>>0,z=new Uint8Array(A);L!==F;){for(var V=m[L],le=0,W=A-1;(V!==0||le<w)&&W!==-1;W--,le++)V+=256*z[W]>>>0,z[W]=V%a>>>0,V=V/a>>>0;if(V!==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 f(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var b=0;if(m[b]!==" "){for(var w=0,L=0;m[b]===c;)w++,b++;for(var F=(m.length-b)*l+1>>>0,A=new Uint8Array(F);m[b];){var z=t[m.charCodeAt(b)];if(z===255)return;for(var V=0,le=F-1;(z!==0||V<L)&&le!==-1;le--,V++)z+=a*A[le]>>>0,A[le]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");L=V,b++}if(m[b]!==" "){for(var W=F-L;W!==F&&A[W]===0;)W++;for(var re=new Uint8Array(w+(F-W)),Et=w;W!==F;)re[Et++]=A[W++];return re}}}function d(m){var b=f(m);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var ii=oi,ai=ii,ws=ai;var Ar=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")}},kr=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 bs(this,e)}},Cr=class{decoders;constructor(e){this.decoders=e}or(e){return bs(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 bs(r,e){return new Cr({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Pr=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 Ar(e,t,n),this.decoder=new kr(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 Pr(r,e,t,n)}function ue({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=ws(t,r);return Ce({prefix:e,name:r,encode:n,decode:o=>ne(s(o))})}function ci(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 u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,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 li(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 ui(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function I({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=ui(n);return Ce({prefix:e,name:r,encode(o){return li(o,n,t)},decode(o){return ci(o,s,t,r)}})}var X=ue({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hi=ue({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mr={};$(Mr,{base32:()=>he,base32hex:()=>mi,base32hexpad:()=>wi,base32hexpadupper:()=>bi,base32hexupper:()=>gi,base32pad:()=>di,base32padupper:()=>pi,base32upper:()=>fi,base32z:()=>yi});var he=I({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fi=I({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),di=I({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pi=I({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mi=I({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gi=I({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wi=I({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),bi=I({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yi=I({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Or={};$(Or,{base36:()=>Je,base36upper:()=>xi});var Je=ue({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xi=ue({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ei=Es,ys=128,_i=127,vi=~_i,Si=Math.pow(2,31);function Es(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Si;)e[t++]=r&255|ys,r/=128;for(;r&vi;)e[t++]=r&255|ys,r>>>=7;return e[t]=r|0,Es.bytes=t-n+1,e}var Ii=Ur,Di=128,xs=127;function Ur(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ur.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&xs)<<s:(i&xs)*Math.pow(2,s),s+=7}while(i>=Di);return Ur.bytes=o-n,t}var Li=Math.pow(2,7),Ti=Math.pow(2,14),Ai=Math.pow(2,21),ki=Math.pow(2,28),Ci=Math.pow(2,35),Pi=Math.pow(2,42),Ni=Math.pow(2,49),Mi=Math.pow(2,56),Oi=Math.pow(2,63),Ui=function(r){return r<Li?1:r<Ti?2:r<Ai?3:r<ki?4:r<Ci?5:r<Pi?6:r<Ni?7:r<Mi?8:r<Oi?9:10},Ri={encode:Ei,decode:Ii,encodingLength:Ui},Fi=Ri,Ye=Fi;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 Oe(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 Me(r,t,e,o)}function Rr(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 Me(t,s,i,e)}function _s(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ds(r.bytes,t.bytes)}}var Me=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function vs(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return zi(t,Fr(r),e??X.encoder);default:return $i(t,Fr(r),e??he.encoder)}}var Ss=new WeakMap;function Fr(r){let e=Ss.get(r);if(e==null){let t=new Map;return Ss.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!==Hi)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=Oe(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&&_s(e.multihash,n.multihash)}toString(e){return vs(this,e)}toJSON(){return{"/":vs(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??Is(n,s,o.bytes))}else if(t[Vi]===!0){let{version:n,multihash:s,code:o}=t,i=Rr(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=Is(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 Me(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,f]=et(e.subarray(t));return t+=f,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,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Bi(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 Fr(o).set(n,e),o}};function Bi(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 zi(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 $i(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,Hi=18;function Is(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 Vi=Symbol.for("@ipld/js-cid/CID");var Br={};$(Br,{identity:()=>Gi});var Ds=0,qi="identity",Ls=ne;function Wi(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 Oe(Ds,Ls(r))}var Gi={code:Ds,name:qi,encode:Ls,digest:Wi};function j(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 P(r=0){return new Uint8Array(r)}function N(r=0){return new Uint8Array(r)}function Z(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=N(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var As=Symbol.for("@achingbrain/uint8arraylist");function Ts(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?.[As]}var fe=class r{bufs;length;[As]=!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=Ts(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ts(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 Z(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Z(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,u=t>a&&t<=c;if(l&&u){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(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!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,u;for(let h=t;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let d=this.get(h+f);if(n[f]!==d){u=Math.max(1,f-a[d]);break}}if(u===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=N(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=P(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=P(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=P(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=N(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=P(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=P(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=P(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=P(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=P(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(!j(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 zr={};$(zr,{base10:()=>Xi});var Xi=ue({prefix:"9",name:"base10",alphabet:"0123456789"});var $r={};$($r,{base16:()=>Qi,base16upper:()=>ji});var Qi=I({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ji=I({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Hr={};$(Hr,{base2:()=>Zi});var Zi=I({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vr={};$(Vr,{base256emoji:()=>ta});var ks=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=ks.reduce((r,e,t)=>(r[t]=e,r),[]),Ji=ks.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Yi(r){return r.reduce((e,t)=>(e+=Ki[t],e),"")}function ea(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 ta=Ce({prefix:"\u{1F680}",name:"base256emoji",encode:Yi,decode:ea});var Wr={};$(Wr,{base64:()=>se,base64pad:()=>ra,base64url:()=>qr,base64urlpad:()=>na});var se=I({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ra=I({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),qr=I({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),na=I({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Gr={};$(Gr,{base8:()=>sa});var sa=I({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Xr={};$(Xr,{identity:()=>oa});var oa=Ce({prefix:"\0",name:"identity",encode:r=>ms(r),decode:r=>ps(r)});var ql=new TextEncoder,Wl=new TextDecoder;var Zr={};$(Zr,{sha256:()=>At,sha512:()=>la});var ca=20;function jr({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Qr(r,e,t,n,s)}var Qr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??ca,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?Cs(n,this.code,t?.truncate):n.then(s=>Cs(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Cs(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 Oe(e,r)}function Ns(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var At=jr({name:"sha2-256",code:18,encode:Ns("SHA-256")}),la=jr({name:"sha2-512",code:19,encode:Ns("SHA-512")});var rt={...Xr,...Hr,...Gr,...zr,...$r,...Mr,...Or,...Nr,...Wr,...Vr},nu={...Zr,...Br};function Os(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ms=Os("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Kr=Os("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=N(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ua={utf8:Ms,"utf-8":Ms,hex:rt.base16,latin1:Kr,ascii:Kr,binary:Kr,...rt},kt=ua;function k(r,e="utf8"){let t=kt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function M(r,e="utf8"){let t=kt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ha=Math.pow(2,7),fa=Math.pow(2,14),da=Math.pow(2,21),Jr=Math.pow(2,28),Yr=Math.pow(2,35),en=Math.pow(2,42),tn=Math.pow(2,49),y=128,O=127;function S(r){if(r<ha)return 1;if(r<fa)return 2;if(r<da)return 3;if(r<Jr)return 4;if(r<Yr)return 5;if(r<en)return 6;if(r<tn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Re(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 pa(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 rn(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)*Jr,t<y)||(t=r[e+5],n+=(t&O)*Yr,t<y)||(t=r[e+6],n+=(t&O)*en,t<y)||(t=r[e+7],n+=(t&O)*tn,t<y))return n;throw new RangeError("Could not decode varint")}function ma(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)*Jr,t<y)||(t=r.get(e+5),n+=(t&O)*Yr,t<y)||(t=r.get(e+6),n+=(t&O)*en,t<y)||(t=r.get(e+7),n+=(t&O)*tn,t<y))return n;throw new RangeError("Could not decode varint")}function Ct(r,e,t=0){return e==null&&(e=N(S(r))),e instanceof Uint8Array?Re(r,e,t):pa(r,e,t)}function me(r,e=0){return r instanceof Uint8Array?rn(r,e):ma(r,e)}var sn=new Float32Array([-0]),de=new Uint8Array(sn.buffer);function Us(r,e,t){sn[0]=r,e[t]=de[0],e[t+1]=de[1],e[t+2]=de[2],e[t+3]=de[3]}function Rs(r,e){return de[0]=r[e],de[1]=r[e+1],de[2]=r[e+2],de[3]=r[e+3],sn[0]}var on=new Float64Array([-0]),U=new Uint8Array(on.buffer);function Fs(r,e,t){on[0]=r,e[t]=U[0],e[t+1]=U[1],e[t+2]=U[2],e[t+3]=U[3],e[t+4]=U[4],e[t+5]=U[5],e[t+6]=U[6],e[t+7]=U[7]}function Bs(r,e){return U[0]=r[e],U[1]=r[e+1],U[2]=r[e+2],U[3]=r[e+3],U[4]=r[e+4],U[5]=r[e+5],U[6]=r[e+6],U[7]=r[e+7],on[0]}var ga=BigInt(Number.MAX_SAFE_INTEGER),wa=BigInt(Number.MIN_SAFE_INTEGER),H=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<ga&&e>wa)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>zs&&(s=0n,++n>zs&&(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 H(0,0);ge.toBigInt=function(){return 0n};ge.zzEncode=ge.zzDecode=function(){return this};ge.length=function(){return 1};var zs=4294967296n;function $s(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 Hs(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 an(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 K(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 cn=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,K(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 K(this,4);return Pt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw K(this,4);return Pt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw K(this,4);let e=Rs(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw K(this,4);let e=Bs(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 K(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Hs(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw K(this,e);this.pos+=e}else do if(this.pos>=this.len)throw K(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 H(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 K(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 K(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 K(this,8);let e=Pt(this.buf,this.pos+=4),t=Pt(this.buf,this.pos+=4);return new H(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=rn(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 ln(r){return new cn(r instanceof Uint8Array?r:r.subarray())}function we(r,e,t){let n=ln(r);return e.decode(n,void 0,t)}function un(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return N(i);s+i>e&&(n=N(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 hn(){}var dn=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ba=un();function ya(r){return globalThis.Buffer!=null?N(r):ba(r)}var st=class{len;head;tail;states;constructor(){this.len=0,this.head=new be(hn,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 pn((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,H.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=H.fromBigInt(e);return this._push(Nt,t.length(),t)}uint64Number(e){return this._push(Re,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=H.fromBigInt(e).zzEncode();return this._push(Nt,t.length(),t)}sint64Number(e){let t=H.fromNumber(e).zzEncode();return this._push(Nt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fn,1,e?1:0)}fixed32(e){return this._push(nt,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=H.fromBigInt(e);return this._push(nt,4,t.lo)._push(nt,4,t.hi)}fixed64Number(e){let t=H.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(Us,4,e)}double(e){return this._push(Fs,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(fn,1,0):this.uint32(t)._push(Ea,t,e)}string(e){let t=$s(e);return t!==0?this.uint32(t)._push(an,t,e):this._push(fn,1,0)}fork(){return this.states=new dn(this),this.head=this.tail=new be(hn,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(hn,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=ya(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function fn(r,e,t){e[t]=r&255}function xa(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var pn=class extends be{next;constructor(e,t){super(xa,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 Ea(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(_a,e,r),this},st.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(va,e,r),this});function _a(r,e,t){e.set(r,t)}function va(r,e,t){r.length<40?an(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(k(r),t)}function mn(){return new st}function ye(r,e){let t=mn();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Fe;(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"})(Fe||(Fe={}));function Mt(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ot(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 Mt("enum",Fe.VARINT,t,n)}function xe(r,e){return Mt("message",Fe.LENGTH_DELIMITED,r,e)}var Be=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var gn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},qs={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ws=new globalThis.TextEncoder;function Sa(r,e){let t=gn[e],n=qs[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function Ia(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=gn[e],s=qs[e],o=r;for(;o.length>0;){let i=Ws.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 wn(r,{size:e=32,utf8Buffer:t}={}){if(!gn[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 Ia(r,e,t);r=Ws.encode(r)}return Sa(r,e)}var ot={hash:r=>Number(wn(r,{size:32})),hashV:(r,e)=>Da(ot.hash(r,e))};function Da(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),k(e,"base16")}var bn=64,J=class{fp;h;seed;constructor(e,t,n,s=2){if(s>bn)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=P(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?j(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 La=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=k(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<La;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=k(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=k(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}},Ta={1:.5,2:.84,4:.95,8:.98};function Aa(r=.001){return r>.002?2:r>1e-5?4:8}function Gs(r,e=.001){let t=Aa(e),n=Ta[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),bn);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Ut=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=k(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=k(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=k(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 yn(r,e=.001,t){return new Ut({...Gs(r,e),...t??{}})}function Rt(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 Ft=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 u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=e,o+=u,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 ka=45,Ca=15,Bt=new Ft;function Xs(r){if(!(r.length>Ca))return Bt.new(r).parseWith(()=>Bt.readIPv4Addr())}function Qs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ka))return Bt.new(r).parseWith(()=>Bt.readIPv6Addr())}function ze(r){return!!Xs(r)}function zt(r){return!!Qs(r)}var Zs=hs(js(),1),Pa=["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"],Na=Pa.map(r=>new Zs.Netmask(r));function xn(r){for(let e of Na)if(e.contains(r))return!0;return!1}function Ma(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Oa(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 Ua(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Ra(r){let e=r.split(":"),t=e[e.length-1];return xn(t)}function Fa(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 Ks(r){if(ze(r))return xn(r);if(Ma(r))return Oa(r);if(Ua(r))return Ra(r);if(zt(r))return Fa(r)}function Js(r){try{let e=Rt(r);switch(e.type){case"ip4":case"ip6":return Ks(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 $t=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 $t(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 $t(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 Ba(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 Ba(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=F=>{o=null,n.push(F);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),u=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})},f=w=>i?s:(i=!0,w!=null?u(w):l({done:!0})),d=()=>(n=new $e,f(),{done:!0}),m=w=>(f(w),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:m,push:h,end:f,get readableLength(){return n.size},onEmpty:async w=>{let L=w?.signal;if(L?.throwIfAborted(),n.isEmpty())return;let F,A;L!=null&&(F=new Promise((z,V)=>{A=()=>{V(new En)},L.addEventListener("abort",A)}));try{await Promise.race([a.promise,F])}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 extends Error{constructor(e){super(e),this.name="TimeoutError"}},vn=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Ys=r=>globalThis.DOMException===void 0?new vn(r):new DOMException(r),eo=r=>{let e=r.reason===void 0?Ys("This operation was aborted."):r.reason;return e instanceof Error?e:Ys(e)};function Sn(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&h(eo(d)),a=()=>{h(eo(d))},d.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,h);return}let f=new _n;i=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){h(d)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?u():s instanceof Error?h(s):(f.message=s??`Promise timed out after ${t} milliseconds`,h(f))},t),(async()=>{try{u(await r)}catch(d){h(d)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},l}var za=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 $a(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:u}=za(r),h=async(...d)=>{let m=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(m))return}catch(b){n(),i(b);return}c.push(m),t.count===c.length&&(n(),o(c))},f=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,h);for(let d of t.rejectionEvents)a.includes(d)||u(d,f)};for(let d of a)l(d,h);for(let d of t.rejectionEvents)a.includes(d)||l(d,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=Sn(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=$a(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function In(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 Ha(r){return r.reason}async function ct(r,e,t){if(e==null)return r;let n=t?.translateError??Ha;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 Wt=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 Va(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Gt=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Va(),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 Wt(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 He=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=In(this.emitEmpty.bind(this),1),this.emitIdle=In(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 Gt(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 C=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},oe=class extends Error{static name="ValidationError";name="ValidationError"},Xt=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Qt=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Ln(r){return e=>M(e,r)}function Tn(r){return e=>k(e,r)}function Ve(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 to(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=k(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 Z([t,s],t.length+s.length)}function ro(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 Z([t,s],t.length+s.length)}function An(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=M(e,"base32"),s=Ve(t);return`${n}:${s}`}var kn=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 C("Invalid byte value in IP address");e[n]=s}),e},no=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=kn(t[n]),t[n]=M(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,M(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 C("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},so=function(r){if(r.byteLength!==4)throw new C("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},oo=function(r){if(r.byteLength!==16)throw new C("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 C(`Invalid IPv6 address "${t}"`)}};function io(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new C(`Invalid IPv6 address "${r}"`)}}var Dn=Object.values(rt).map(r=>r.decoder),qa=(function(){let r=Dn[0].or(Dn[1]);return Dn.slice(2).forEach(e=>r=r.or(e)),r})();function ao(r){return qa.decode(r)}function co(r){return e=>r.encoder.encode(e)}function Wa(r){if(parseInt(r).toString()!==r)throw new oe("Value must be an integer")}function Ga(r){if(r<0)throw new oe("Value must be a positive integer, or zero")}function Xa(r){return e=>{if(e>r)throw new oe(`Value must be smaller than or equal to ${r}`)}}function Qa(...r){return e=>{for(let t of r)t(e)}}var lt=Qa(Wa,Ga,Xa(65535));var T=-1,Cn=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 Qt(`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 Cn,lc=[{code:4,name:"ip4",size:32,valueToBytes:kn,bytesToValue:so,validate:r=>{if(!ze(r))throw new oe(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ve,bytesToValue:Ve,validate:lt},{code:273,name:"udp",size:16,valueToBytes:ve,bytesToValue:Ve,validate:lt},{code:33,name:"dccp",size:16,valueToBytes:ve,bytesToValue:Ve,validate:lt},{code:41,name:"ip6",size:128,valueToBytes:no,bytesToValue:oo,stringToValue:io,validate:r=>{if(!zt(r))throw new oe(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:T},{code:43,name:"ipcidr",size:8,bytesToValue:Ln("base10"),valueToBytes:Tn("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:Ve,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:Ln("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Tn("base58btc")(r):Q.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:An,valueToBytes:to},{code:445,name:"onion3",size:296,bytesToValue:An,valueToBytes:ro},{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:co(qr),valueToBytes:ao},{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}];lc.forEach(r=>{ae.addProtocol(r)});function lo(r){let e=[],t=0;for(;t<r.length;){let n=me(r,t),s=ae.getProtocol(n),o=S(n),i=uc(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 u=t+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??M(h)}e.push(l),t+=c}return e}function uo(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)??k(n.value),a=i.byteLength,s.size===T&&(c=S(a)));let l=new Uint8Array(o+c+a),u=0;Re(n.code,l,u),u+=o,i!=null&&(s.size===T&&(Re(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Z(t,e)}function ho(r){if(r.charAt(0)!=="/")throw new C('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 C(`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 C(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new C("Incomplete multiaddr");return e}function fo(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ae.getProtocol(e.code);if(t==null)throw new C(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function uc(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:me(e,t)}var hc=Symbol.for("nodejs.util.inspect.custom"),Vn=Symbol.for("@multiformats/multiaddr");function fc(r){if(r==null&&(r="/"),po(r))return r.getComponents();if(r instanceof Uint8Array)return lo(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ho(r);if(Array.isArray(r))return r;throw new C("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Yt=class r{[Vn]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=fc(e),t.validate!==!1&&dc(this)}get bytes(){return this.#r==null&&(this.#r=uo(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=fo(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 Xt(`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 j(this.bytes,e.bytes)}[hc](){return`Multiaddr(${this.toString()})`}};function dc(r){r.getComponents().forEach(e=>{let t=ae.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function po(r){return!!r?.[Vn]}function mo(r){return new Yt(r)}var er=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ge=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},tr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},mt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function rr(r){return r[Symbol.asyncIterator]!=null}function go(r,e){if(r.byteLength>e)throw new Ge("Message length too long")}var sr=r=>{let e=S(r),t=N(e);return Ct(r,t),sr.bytes=e,t};sr.bytes=0;function or(r,e){e=e??{};let t=e.lengthEncoder??sr,n=e?.maxDataLength??4194304;function*s(o){go(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return rr(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}or.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??sr,n=e?.maxDataLength??4194304;return go(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 qn=r=>{let e=me(r);return qn.bytes=S(e),e};qn.bytes=0;function gt(r,e){let t=new fe,n=Ie.LENGTH,s=-1,o=e?.lengthDecoder??qn,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 er("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 tr("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 rr(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 ir=class extends He{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Wn=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 wo(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Wn({name:e,metrics:t}):n=new Map,n}function gc(r){return r[Symbol.asyncIterator]!=null}function wc(r){if(gc(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Gn=wc;function bc(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 bo=bc;function yc(r){return r[Symbol.asyncIterator]!=null}function xc(r,e){let t=0;if(yc(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=bo(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 yo=xc;function Ec(r){return r[Symbol.asyncIterator]!=null}function _c(r,e){return Ec(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 xo=_c;var ar=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 ar(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(){Qn(t,"abort",h),Qn(r,e,l),Qn(r,o,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){c(),a(d);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)};Xn(t,"abort",h),Xn(r,e,l),Xn(r,o,u)})}function Xn(r,e,t){r!=null&&(Eo(r)?r.addEventListener(e,t):r.addListener(e,t))}function Qn(r,e,t){r!=null&&(Eo(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Eo(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var wt="/ipfs/bitswap/1.2.0";var D;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(D||(D={}));var jn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(jn||(jn={}));(function(r){r.codec=()=>Ot(jn)})(D||(D={}));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),D.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:P(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=D.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 cr;(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)})(cr||(cr={}));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:P(0),data:P(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 q;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(q||(q={}));var lr;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(lr||(lr={}));(function(r){r.codec=()=>Ot(lr)})(q||(q={}));var je;(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&&lr[t.type]!==0&&(n.uint32(16),q.codec().encode(t.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={cid:P(0),type:q.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=q.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)})(je||(je={}));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),cr.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),je.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=cr.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(je.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 _o(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 ur=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var vc=4193648,Sc=vc+16;function*vo(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},u=Le.encode(l).byteLength,{added:h,hasMore:f,newSize:d}=Zn(s,l.blocks,a,e,u,Ic);a+=h,u=d;let m=f;({added:h,hasMore:f,newSize:d}=Zn(n,l.blockPresences,i,e,u,Dc)),i+=h,u=d;let b=f;if({added:h,hasMore:f,newSize:d}=Zn(t,l.wantlist.entries,o,e,u,Lc),o+=h,u=d,c=!m&&!b&&!f,c||(l.wantlist.full=!1),yield Le.encode(l),c)break}}function Zn(r,e,t,n,s,o){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=o(l);if(u>Sc)throw new ur("Cannot send block as after encoding it is over the max message size");let h=s+u;if(h>n){a=!0;break}e.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function Ic(r){return Kn(3,Qe.encode(r))}function Dc(r){return Kn(4,je.encode(r))}function Lc(r){return Kn(1,Xe.encode(r))}function Kn(r,e){let t=S(r),n=S(e.byteLength);return t+n+e.byteLength}var hr=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 ir({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 B("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 B("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 Gn(yo(xo(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=_o(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 B("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,wt,o);await a.closeRead();try{for(let c of vo(i,this.maxOutgoingMessageSize))a.send(or.single(c))||await a.onDrain(o);await a.close(o)}catch(c){o?.onProgress?.(new B("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 B("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 fr(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 fr(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 fr(this.map.values(),e=>e.key)}values(){return fr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Jn=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 Jn({name:e,metrics:t}):n=new bt,n}function Uc(r){return r[Symbol.asyncIterator]!=null}function Rc(r){if(Uc(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=Z([n,s],n.length+s.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Z(e,t)}var Io=Rc;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 Fc(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 Do=Fc;function Yn(r){return Do([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var dr=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;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}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)}async sendBlocksToPeer(e){let t=new ce,n=new Set;for(let[s,o]of this.wants.entries())try{let i=await Io(this.blockstore.get(o.cid,e));o.wantType===D.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),t.addBlock(o.cid,{data:i,prefix:Yn(o.cid)})):(this.log("sending have for %c",o.cid),t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:q.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),t.addBlock(o.cid,{data:i,prefix:Yn(o.cid)}))}catch(i){if(i.name!=="NotFoundError")throw i;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDoNotHave===!0)continue;o.sentDoNotHave=!0,t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:q.DoNotHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,o)=>s+o.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var pr=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,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.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new dr({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let s of t.wantlist.entries){let o=Q.decode(s.cid),i=M(o.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,o),n.wants.delete(i)):(s.wantType===D.WantHave?this.log("peer %p wanted block presence for %c",e,o):this.log("peer %p wanted block for %c",e,o),n.wants.set(i,{cid:o,priority:s.priority,wantType:s.wantType??D.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=M(e.multihash.bytes,"base64"),s=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&s.push(o);await Promise.all(s.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var $c=hs(To(),1);var Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));var mr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Te=class extends te{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=yn(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;let o=Y();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));try{await ct(this.initialPeerSearchComplete,t.signal),u&&this.log("found initial session peers for %c",e)}catch(h){throw u&&this.log("failed to find initial session peers for %c - %e",e,h),this.requests.delete(n),o.reject(h),h}}let i=!1,a=new He({concurrency:this.maxProviders});a.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)}),a.addEventListener("success",u=>{i=!0,o.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(i){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 h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}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 c=u=>{a.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(h=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,h)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.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 l=()=>{o.reject(new G(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",l);try{return await ct(o.promise,t.signal)}finally{this.removeEventListener("provider",c),t.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(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.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}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",t,this.maxProviders,e),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,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"),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"),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 mr(`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 es=class extends Te{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,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 n.id}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}async convertToProvider(e,t){return Dt(e)?e:(await this.libp2p.dial(e,t)).remotePeer}};function Ao(r,e){return new es(r,e)}var gr=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 qc(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 ko=qc;var wr=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=wo({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=M(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??D.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===D.WantHave&&t.wantType===D.WantBlock&&(s.wantType=D.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===D.WantBlock?(await De(this,"block",t?.signal,{filter:a=>j(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await De(this,"presence",t?.signal,{filter:i=>j(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=M(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:D.WantHave,priority:1}),await this.network.sendMessage(t,s),(await De(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&j(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:D.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new ce;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:D.WantBlock,priority:1}),await this.network.sendMessage(t,s),(await De(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&j(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=M(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=ko(s.prefix),i=o[0],a=o[1],c=o[2],l=o[3],u=c===At.code?At:await this.hashLoader?.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=Q.create(i===0?0:1,a,h);this.log("received block from %p for %c",e,f),this.safeDispatchEvent("block",{detail:{sender:e,cid:f,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:f,has:!0,block:s.data}});let d=M(f.multihash.bytes,"base64"),m=this.wants.get(d);m!=null&&(m.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===q.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:D.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 br=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 gr(e),this.network=new hr(e,t),this.peerWantLists=new pr({...e,network:this.network},t),this.wantList=new wr({...e,network:this.network},t)}createSession(e={}){return Ao({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,s=fs([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 B("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 Co=(r,e={})=>new br(r,e);var ts=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=Co(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{announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>t.retrieve(n,s)}}};function Po(r={}){return e=>new ts(e,r)}var Wc=[6,53,56,54,55];function No(r){return Uo("sni",r)?.value}function Mo(r){let e=Uo("tcp",r)?.value;return e==null?"":`:${e}`}function Uo(r,e){return e.find(t=>t.name===r)}function Oo(r){return r.some(({code:e})=>e===448)}function ee(r,e){let t=Ro[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 Ro={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=Oo(e),n=No(e),s=Mo(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=Oo(e),n=No(e),s=Mo(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 yr(r,e){let n=mo(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=Ro[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return e?.assumeHttp!==!1&&Wc.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)}}),p=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Fo=r=>({match:e=>r.match(e)===!1?e:!1}),g=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),R=(...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 Gc=p(421),Om=v(Gc),Er=p(54),_r=p(55),vr=p(56),ns=p(53),Um=v(Er,g(p(421))),Rm=v(_r,g(p(421))),Fm=v(vr,g(p(421))),Bo=v(R(ns,vr,Er,_r),g(p(421))),zo=x(p(4),g(p(43))),$o=x(g(p(42)),p(41),g(p(43))),ss=R(zo,$o),Ae=R(ss,ns,Er,_r,vr),Bm=v(R(ss,x(R(ns,vr,Er,_r),g(p(421))))),zm=v(zo),$m=v($o),Hm=v(ss),os=x(Ae,p(6)),xt=x(Ae,p(273)),Vm=v(x(os,g(p(421)))),qm=v(xt),is=x(xt,_(460),g(p(421))),Sr=x(xt,_(461),g(p(421))),Xc=R(is,Sr),Wm=v(is),Gm=v(Sr),rs=R(Ae,os,xt,is,Sr),Ho=R(x(rs,_(477),g(p(421)))),Xm=v(Ho),Vo=R(x(rs,_(478),g(p(421))),x(rs,_(448),g(p(449)),_(477),g(p(421)))),Qm=v(Vo),qo=x(xt,_(280),g(p(466)),g(p(466)),g(p(421))),jm=v(qo),Wo=x(Sr,_(465),g(p(466)),g(p(466)),g(p(421))),Zm=v(Wo),xr=R(Ho,Vo,x(os,g(p(421))),x(Xc,g(p(421))),x(Ae,g(p(421))),qo,Wo,p(421)),Km=v(xr),Qc=x(g(xr),_(290),Fo(_(281)),g(p(421))),Jm=v(Qc),jc=R(x(xr,_(290),_(281),g(p(421))),x(xr,_(281),g(p(421))),x(_(281),g(p(421)))),Ym=v(jc),Zc=R(x(Ae,p(6),_(480),g(p(421))),x(Ae,_(480),g(p(421)))),Go=v(Zc),Kc=x(Ae,R(x(p(6,"443"),_(480)),x(p(6),_(443)),x(p(6),_(448),_(480)),x(_(448),_(480)),_(448),_(443)),g(p(421))),Xo=v(Kc),Jc=R(x(p(777),g(p(421)))),eg=v(Jc),Yc=R(x(p(400),g(p(421)))),tg=v(Yc);function as(r,e,t){return r.filter(n=>{if(Xo.matches(n)||e&&Go.matches(n))return t||Bo.matches(n)?!0:Js(n)===!1;if(!e&&t){let{host:s}=Rt(n);if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*Ir(r,e,t,n,s,o={}){for await(let i of e.findProviders(r,o)){let a=as(i.multiaddrs,n,s);if(a.length===0)continue;let c=yr(a[0]),l={type:"trustless-gateway",cid:r,url:c.toString(),routing:i.routing};o?.onProgress?.(new B("trustless-gateway:found-provider",l)),yield new Ke(c,{logger:t,transformRequestInit:o.transformRequestInit})}}async function Qo(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 Ke=class{url;#e=0;#t=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;constructor(e,{logger:t,transformRequestInit:n}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#o(e){let t=e.multihash.bytes;return se.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=jo}={}){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"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l,h=new Headers(u.headers);this.log(`sending request
|
|
2
|
+
"use strict";var HeliaBlockBrokers=(()=>{var Jo=Object.create;var _t=Object.defineProperty;var Yo=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,ri=Object.prototype.hasOwnProperty;var ls=(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})},us=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ei(e))!ri.call(r,s)&&s!==t&&_t(r,s,{get:()=>e[s],enumerable:!(n=Yo(e,s))||n.enumerable});return r};var hs=(r,e,t)=>(t=r!=null?Jo(ti(r)):{},us(e||!r||!r.__esModule?_t(t,"default",{value:r,enumerable:!0}):t,r)),ni=r=>us(_t({},"__esModule",{value:!0}),r);var js=ls(at=>{(function(){var r,e,t,n,s,o,i,a;a=function(c){var l,f,u,h;return l=(c&255<<24)>>>24,f=(c&255<<16)>>>16,u=(c&65280)>>>8,h=c&255,[l,f,u,h].join(".")},i=function(c){var l,f,u,h,d,m;for(l=[],u=h=0;h<=3&&c.length!==0;u=++h){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=e(c),d=m[0],f=m[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,u,h,d;for(h=0,l=10,f="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,f="7")),d=u;u<c.length;){if("0"<=c[u]&&c[u]<=f)h=h*l+(t(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")h=h*l+(10+t(c[u])-o)>>>0;else if("A"<=c[u]&&c[u]<="F")h=h*l+(10+t(c[u])-s)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");u++}if(u===d)throw new Error("empty octet");return[h,u]},r=(function(){function c(l,f){var u,h,d,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(f||(m=l.split("/",2),l=m[0],f=m[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(w){throw u=w,new Error("Invalid mask: "+f)}for(h=d=32;d>=0;h=--d)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;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(w){throw u=w,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,u,h;for(h=i(this.first),u=i(this.last),f=0;h<=u;)l(a(h),h,f),f++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),at.ip2long=i,at.long2ip=a,at.Netmask=r}).call(at)});var To=ls((Ep,Lo)=>{Lo.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 el={};$(el,{bitswap:()=>Po,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 si=Symbol.for("@libp2p/peer-id");function Dt(r){return!!r?.[si]}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 fs(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 B=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Nr={};$(Nr,{base58btc:()=>X,base58flickr:()=>hi});var al=new Uint8Array(0);function ds(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 ps(r){return new TextEncoder().encode(r)}function ms(r){return new TextDecoder().decode(r)}function oi(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 u(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var w=0,b=0,L=0,F=m.length;L!==F&&m[L]===0;)L++,w++;for(var A=(F-L)*f+1>>>0,z=new Uint8Array(A);L!==F;){for(var V=m[L],le=0,W=A-1;(V!==0||le<b)&&W!==-1;W--,le++)V+=256*z[W]>>>0,z[W]=V%a>>>0,V=V/a>>>0;if(V!==0)throw new Error("Non-zero carry");b=le,L++}for(var re=A-b;re!==A&&z[re]===0;)re++;for(var Et=c.repeat(w);re<A;++re)Et+=r.charAt(z[re]);return Et}function h(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var w=0;if(m[w]!==" "){for(var b=0,L=0;m[w]===c;)b++,w++;for(var F=(m.length-w)*l+1>>>0,A=new Uint8Array(F);m[w];){var z=t[m.charCodeAt(w)];if(z===255)return;for(var V=0,le=F-1;(z!==0||V<L)&&le!==-1;le--,V++)z+=a*A[le]>>>0,A[le]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");L=V,w++}if(m[w]!==" "){for(var W=F-L;W!==F&&A[W]===0;)W++;for(var re=new Uint8Array(b+(F-W)),Et=b;W!==F;)re[Et++]=A[W++];return re}}}function d(m){var w=h(m);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:d}}var ii=oi,ai=ii,bs=ai;var Ar=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")}},kr=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)}},Cr=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 Cr({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Pr=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 Ar(e,t,n),this.decoder=new kr(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 Pr(r,e,t,n)}function ue({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=bs(t,r);return Ce({prefix:e,name:r,encode:n,decode:o=>ne(s(o))})}function ci(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 li(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 ui(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function I({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=ui(n);return Ce({prefix:e,name:r,encode(o){return li(o,n,t)},decode(o){return ci(o,s,t,r)}})}var X=ue({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hi=ue({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mr={};$(Mr,{base32:()=>he,base32hex:()=>mi,base32hexpad:()=>bi,base32hexpadupper:()=>wi,base32hexupper:()=>gi,base32pad:()=>di,base32padupper:()=>pi,base32upper:()=>fi,base32z:()=>yi});var he=I({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fi=I({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),di=I({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pi=I({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mi=I({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gi=I({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),bi=I({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wi=I({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yi=I({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Or={};$(Or,{base36:()=>Je,base36upper:()=>xi});var Je=ue({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xi=ue({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ei=Es,ys=128,_i=127,vi=~_i,Si=Math.pow(2,31);function Es(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Si;)e[t++]=r&255|ys,r/=128;for(;r&vi;)e[t++]=r&255|ys,r>>>=7;return e[t]=r|0,Es.bytes=t-n+1,e}var Ii=Ur,Di=128,xs=127;function Ur(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ur.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&xs)<<s:(i&xs)*Math.pow(2,s),s+=7}while(i>=Di);return Ur.bytes=o-n,t}var Li=Math.pow(2,7),Ti=Math.pow(2,14),Ai=Math.pow(2,21),ki=Math.pow(2,28),Ci=Math.pow(2,35),Pi=Math.pow(2,42),Ni=Math.pow(2,49),Mi=Math.pow(2,56),Oi=Math.pow(2,63),Ui=function(r){return r<Li?1:r<Ti?2:r<Ai?3:r<ki?4:r<Ci?5:r<Pi?6:r<Ni?7:r<Mi?8:r<Oi?9:10},Ri={encode:Ei,decode:Ii,encodingLength:Ui},Fi=Ri,Ye=Fi;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 Oe(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 Me(r,t,e,o)}function Rr(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 Me(t,s,i,e)}function _s(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ds(r.bytes,t.bytes)}}var Me=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function vs(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return zi(t,Fr(r),e??X.encoder);default:return $i(t,Fr(r),e??he.encoder)}}var Ss=new WeakMap;function Fr(r){let e=Ss.get(r);if(e==null){let t=new Map;return Ss.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!==Hi)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=Oe(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&&_s(e.multihash,n.multihash)}toString(e){return vs(this,e)}toJSON(){return{"/":vs(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??Is(n,s,o.bytes))}else if(t[Vi]===!0){let{version:n,multihash:s,code:o}=t,i=Rr(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=Is(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 Me(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[u,h]=et(e.subarray(t));return t+=h,u},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]=Bi(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 Fr(o).set(n,e),o}};function Bi(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 zi(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 $i(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,Hi=18;function Is(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 Vi=Symbol.for("@ipld/js-cid/CID");var Br={};$(Br,{identity:()=>Gi});var Ds=0,qi="identity",Ls=ne;function Wi(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 Oe(Ds,Ls(r))}var Gi={code:Ds,name:qi,encode:Ls,digest:Wi};function j(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 P(r=0){return new Uint8Array(r)}function N(r=0){return new Uint8Array(r)}function Z(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=N(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var As=Symbol.for("@achingbrain/uint8arraylist");function Ts(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?.[As]}var fe=class r{bufs;length;[As]=!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=Ts(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ts(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 Z(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Z(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 u=e-a;n.push(i.subarray(u,u+(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 u=0;u<o;u++)i[u]=-1;for(let u=0;u<s;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let u=t;u<=c;u+=f){f=0;for(let h=l;h>=0;h--){let d=this.get(u+h);if(n[h]!==d){f=Math.max(1,h-a[d]);break}}if(f===0)return u}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=N(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=P(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=P(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=P(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=N(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=P(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=P(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=P(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=P(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=P(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(!j(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 zr={};$(zr,{base10:()=>Xi});var Xi=ue({prefix:"9",name:"base10",alphabet:"0123456789"});var $r={};$($r,{base16:()=>Qi,base16upper:()=>ji});var Qi=I({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ji=I({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Hr={};$(Hr,{base2:()=>Zi});var Zi=I({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vr={};$(Vr,{base256emoji:()=>ta});var ks=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=ks.reduce((r,e,t)=>(r[t]=e,r),[]),Ji=ks.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Yi(r){return r.reduce((e,t)=>(e+=Ki[t],e),"")}function ea(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 ta=Ce({prefix:"\u{1F680}",name:"base256emoji",encode:Yi,decode:ea});var Wr={};$(Wr,{base64:()=>se,base64pad:()=>ra,base64url:()=>qr,base64urlpad:()=>na});var se=I({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ra=I({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),qr=I({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),na=I({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Gr={};$(Gr,{base8:()=>sa});var sa=I({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Xr={};$(Xr,{identity:()=>oa});var oa=Ce({prefix:"\0",name:"identity",encode:r=>ms(r),decode:r=>ps(r)});var ql=new TextEncoder,Wl=new TextDecoder;var Zr={};$(Zr,{sha256:()=>At,sha512:()=>la});var ca=20;function jr({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Qr(r,e,t,n,s)}var Qr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??ca,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?Cs(n,this.code,t?.truncate):n.then(s=>Cs(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Cs(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 Oe(e,r)}function Ns(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var At=jr({name:"sha2-256",code:18,encode:Ns("SHA-256")}),la=jr({name:"sha2-512",code:19,encode:Ns("SHA-512")});var rt={...Xr,...Hr,...Gr,...zr,...$r,...Mr,...Or,...Nr,...Wr,...Vr},nu={...Zr,...Br};function Os(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ms=Os("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Kr=Os("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=N(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ua={utf8:Ms,"utf-8":Ms,hex:rt.base16,latin1:Kr,ascii:Kr,binary:Kr,...rt},kt=ua;function k(r,e="utf8"){let t=kt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function M(r,e="utf8"){let t=kt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ha=Math.pow(2,7),fa=Math.pow(2,14),da=Math.pow(2,21),Jr=Math.pow(2,28),Yr=Math.pow(2,35),en=Math.pow(2,42),tn=Math.pow(2,49),y=128,O=127;function S(r){if(r<ha)return 1;if(r<fa)return 2;if(r<da)return 3;if(r<Jr)return 4;if(r<Yr)return 5;if(r<en)return 6;if(r<tn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Re(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 pa(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 rn(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)*Jr,t<y)||(t=r[e+5],n+=(t&O)*Yr,t<y)||(t=r[e+6],n+=(t&O)*en,t<y)||(t=r[e+7],n+=(t&O)*tn,t<y))return n;throw new RangeError("Could not decode varint")}function ma(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)*Jr,t<y)||(t=r.get(e+5),n+=(t&O)*Yr,t<y)||(t=r.get(e+6),n+=(t&O)*en,t<y)||(t=r.get(e+7),n+=(t&O)*tn,t<y))return n;throw new RangeError("Could not decode varint")}function Ct(r,e,t=0){return e==null&&(e=N(S(r))),e instanceof Uint8Array?Re(r,e,t):pa(r,e,t)}function me(r,e=0){return r instanceof Uint8Array?rn(r,e):ma(r,e)}var sn=new Float32Array([-0]),de=new Uint8Array(sn.buffer);function Us(r,e,t){sn[0]=r,e[t]=de[0],e[t+1]=de[1],e[t+2]=de[2],e[t+3]=de[3]}function Rs(r,e){return de[0]=r[e],de[1]=r[e+1],de[2]=r[e+2],de[3]=r[e+3],sn[0]}var on=new Float64Array([-0]),U=new Uint8Array(on.buffer);function Fs(r,e,t){on[0]=r,e[t]=U[0],e[t+1]=U[1],e[t+2]=U[2],e[t+3]=U[3],e[t+4]=U[4],e[t+5]=U[5],e[t+6]=U[6],e[t+7]=U[7]}function Bs(r,e){return U[0]=r[e],U[1]=r[e+1],U[2]=r[e+2],U[3]=r[e+3],U[4]=r[e+4],U[5]=r[e+5],U[6]=r[e+6],U[7]=r[e+7],on[0]}var ga=BigInt(Number.MAX_SAFE_INTEGER),ba=BigInt(Number.MIN_SAFE_INTEGER),H=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<ga&&e>ba)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>zs&&(s=0n,++n>zs&&(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 H(0,0);ge.toBigInt=function(){return 0n};ge.zzEncode=ge.zzDecode=function(){return this};ge.length=function(){return 1};var zs=4294967296n;function $s(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 Hs(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 an(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 K(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 cn=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,K(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 K(this,4);return Pt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw K(this,4);return Pt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw K(this,4);let e=Rs(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw K(this,4);let e=Bs(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 K(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Hs(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw K(this,e);this.pos+=e}else do if(this.pos>=this.len)throw K(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 H(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 K(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 K(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 K(this,8);let e=Pt(this.buf,this.pos+=4),t=Pt(this.buf,this.pos+=4);return new H(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=rn(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 ln(r){return new cn(r instanceof Uint8Array?r:r.subarray())}function be(r,e,t){let n=ln(r);return e.decode(n,void 0,t)}function un(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return N(i);s+i>e&&(n=N(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var we=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function hn(){}var dn=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},wa=un();function ya(r){return globalThis.Buffer!=null?N(r):wa(r)}var st=class{len;head;tail;states;constructor(){this.len=0,this.head=new we(hn,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new we(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new pn((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,H.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=H.fromBigInt(e);return this._push(Nt,t.length(),t)}uint64Number(e){return this._push(Re,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=H.fromBigInt(e).zzEncode();return this._push(Nt,t.length(),t)}sint64Number(e){let t=H.fromNumber(e).zzEncode();return this._push(Nt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fn,1,e?1:0)}fixed32(e){return this._push(nt,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=H.fromBigInt(e);return this._push(nt,4,t.lo)._push(nt,4,t.hi)}fixed64Number(e){let t=H.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(Us,4,e)}double(e){return this._push(Fs,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(fn,1,0):this.uint32(t)._push(Ea,t,e)}string(e){let t=$s(e);return t!==0?this.uint32(t)._push(an,t,e):this._push(fn,1,0)}fork(){return this.states=new dn(this),this.head=this.tail=new we(hn,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 we(hn,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=ya(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function fn(r,e,t){e[t]=r&255}function xa(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var pn=class extends we{next;constructor(e,t){super(xa,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 Ea(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(_a,e,r),this},st.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(va,e,r),this});function _a(r,e,t){e.set(r,t)}function va(r,e,t){r.length<40?an(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(k(r),t)}function mn(){return new st}function ye(r,e){let t=mn();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Fe;(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"})(Fe||(Fe={}));function Mt(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ot(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 Mt("enum",Fe.VARINT,t,n)}function xe(r,e){return Mt("message",Fe.LENGTH_DELIMITED,r,e)}var Be=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var gn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},qs={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ws=new globalThis.TextEncoder;function Sa(r,e){let t=gn[e],n=qs[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function Ia(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=gn[e],s=qs[e],o=r;for(;o.length>0;){let i=Ws.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(!gn[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 Ia(r,e,t);r=Ws.encode(r)}return Sa(r,e)}var ot={hash:r=>Number(bn(r,{size:32})),hashV:(r,e)=>Da(ot.hash(r,e))};function Da(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),k(e,"base16")}var wn=64,J=class{fp;h;seed;constructor(e,t,n,s=2){if(s>wn)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=P(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?j(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 La=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=k(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<La;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=k(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=k(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}},Ta={1:.5,2:.84,4:.95,8:.98};function Aa(r=.001){return r>.002?2:r>1e-5?4:8}function Gs(r,e=.001){let t=Aa(e),n=Ta[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),wn);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Ut=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=k(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=k(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=k(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 yn(r,e=.001,t){return new Ut({...Gs(r,e),...t??{}})}function Rt(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 Ft=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 u=this.readChar();if(u===void 0)return;let h=Number.parseInt(u,e);if(!Number.isNaN(h))return h});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 ka=45,Ca=15,Bt=new Ft;function Xs(r){if(!(r.length>Ca))return Bt.new(r).parseWith(()=>Bt.readIPv4Addr())}function Qs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ka))return Bt.new(r).parseWith(()=>Bt.readIPv6Addr())}function ze(r){return!!Xs(r)}function zt(r){return!!Qs(r)}var Zs=hs(js(),1),Pa=["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"],Na=Pa.map(r=>new Zs.Netmask(r));function xn(r){for(let e of Na)if(e.contains(r))return!0;return!1}function Ma(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Oa(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 Ua(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Ra(r){let e=r.split(":"),t=e[e.length-1];return xn(t)}function Fa(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 Ks(r){if(ze(r))return xn(r);if(Ma(r))return Oa(r);if(Ua(r))return Ra(r);if(zt(r))return Fa(r)}function Js(r){try{let e=Rt(r);switch(e.type){case"ip4":case"ip6":return Ks(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 $t=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 $t(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 $t(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 Ba(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 Ba(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((b,L)=>{o=F=>{o=null,n.push(F);try{b(r(n))}catch(A){L(A)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Y()})}},l=b=>o!=null?o(b):(n.push(b),s),f=b=>(n=new $e,o!=null?o({error:b}):(n.push({error:b}),s)),u=b=>{if(i)return s;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},h=b=>i?s:(i=!0,b!=null?f(b):l({done:!0})),d=()=>(n=new $e,h(),{done:!0}),m=b=>(h(b),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:m,push:u,end:h,get readableLength(){return n.size},onEmpty:async b=>{let L=b?.signal;if(L?.throwIfAborted(),n.isEmpty())return;let F,A;L!=null&&(F=new Promise((z,V)=>{A=()=>{V(new En)},L.addEventListener("abort",A)}));try{await Promise.race([a.promise,F])}finally{A!=null&&L!=null&&L?.removeEventListener("abort",A)}}},t==null)return s;let w=s;return s={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(b){return w.throw(b),t!=null&&(t(b),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(b){return w.end(b),t!=null&&(t(b),t=void 0),s},get readableLength(){return w.readableLength},onEmpty:b=>w.onEmpty(b)},s}var _n=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},vn=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Ys=r=>globalThis.DOMException===void 0?new vn(r):new DOMException(r),eo=r=>{let e=r.reason===void 0?Ys("This operation was aborted."):r.reason;return e instanceof Error?e:Ys(e)};function Sn(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=e,i,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&u(eo(d)),a=()=>{u(eo(d))},d.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let h=new _n;i=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(d){u(d)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?f():s instanceof Error?u(s):(h.message=s??`Promise timed out after ${t} milliseconds`,u(h))},t),(async()=>{try{f(await r)}catch(d){u(d)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},l}var za=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 $a(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}=za(r),u=async(...d)=>{let m=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(m))return}catch(w){n(),i(w);return}c.push(m),t.count===c.length&&(n(),o(c))},h=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)f(d,u);for(let d of t.rejectionEvents)a.includes(d)||f(d,h)};for(let d of a)l(d,u);for(let d of t.rejectionEvents)a.includes(d)||l(d,h);t.signal&&t.signal.addEventListener("abort",()=>{h(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=Sn(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=$a(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function In(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 Ha(r){return r.reason}async function ct(r,e,t){if(e==null)return r;let n=t?.translateError??Ha;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 Wt=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 Va(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Gt=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Va(),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 Wt(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 He=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=In(this.emitEmpty.bind(this),1),this.emitIdle=In(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 Gt(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 C=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},oe=class extends Error{static name="ValidationError";name="ValidationError"},Xt=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Qt=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Ln(r){return e=>M(e,r)}function Tn(r){return e=>k(e,r)}function Ve(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 to(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=k(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 Z([t,s],t.length+s.length)}function ro(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 Z([t,s],t.length+s.length)}function An(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=M(e,"base32"),s=Ve(t);return`${n}:${s}`}var kn=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 C("Invalid byte value in IP address");e[n]=s}),e},no=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=kn(t[n]),t[n]=M(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,M(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 C("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},so=function(r){if(r.byteLength!==4)throw new C("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},oo=function(r){if(r.byteLength!==16)throw new C("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 C(`Invalid IPv6 address "${t}"`)}};function io(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new C(`Invalid IPv6 address "${r}"`)}}var Dn=Object.values(rt).map(r=>r.decoder),qa=(function(){let r=Dn[0].or(Dn[1]);return Dn.slice(2).forEach(e=>r=r.or(e)),r})();function ao(r){return qa.decode(r)}function co(r){return e=>r.encoder.encode(e)}function Wa(r){if(parseInt(r).toString()!==r)throw new oe("Value must be an integer")}function Ga(r){if(r<0)throw new oe("Value must be a positive integer, or zero")}function Xa(r){return e=>{if(e>r)throw new oe(`Value must be smaller than or equal to ${r}`)}}function Qa(...r){return e=>{for(let t of r)t(e)}}var lt=Qa(Wa,Ga,Xa(65535));var T=-1,Cn=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 Qt(`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 Cn,lc=[{code:4,name:"ip4",size:32,valueToBytes:kn,bytesToValue:so,validate:r=>{if(!ze(r))throw new oe(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ve,bytesToValue:Ve,validate:lt},{code:273,name:"udp",size:16,valueToBytes:ve,bytesToValue:Ve,validate:lt},{code:33,name:"dccp",size:16,valueToBytes:ve,bytesToValue:Ve,validate:lt},{code:41,name:"ip6",size:128,valueToBytes:no,bytesToValue:oo,stringToValue:io,validate:r=>{if(!zt(r))throw new oe(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:T},{code:43,name:"ipcidr",size:8,bytesToValue:Ln("base10"),valueToBytes:Tn("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:Ve,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:Ln("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Tn("base58btc")(r):Q.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:An,valueToBytes:to},{code:445,name:"onion3",size:296,bytesToValue:An,valueToBytes:ro},{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:co(qr),valueToBytes:ao},{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}];lc.forEach(r=>{ae.addProtocol(r)});function lo(r){let e=[],t=0;for(;t<r.length;){let n=me(r,t),s=ae.getProtocol(n),o=S(n),i=uc(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,u=r.subarray(f,f+i);l.value=s.bytesToValue?.(u)??M(u)}e.push(l),t+=c}return e}function uo(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)??k(n.value),a=i.byteLength,s.size===T&&(c=S(a)));let l=new Uint8Array(o+c+a),f=0;Re(n.code,l,f),f+=o,i!=null&&(s.size===T&&(Re(a,l,f),f+=c),l.set(i,f)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Z(t,e)}function ho(r){if(r.charAt(0)!=="/")throw new C('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 C(`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 C(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new C("Incomplete multiaddr");return e}function fo(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ae.getProtocol(e.code);if(t==null)throw new C(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function uc(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:me(e,t)}var hc=Symbol.for("nodejs.util.inspect.custom"),Vn=Symbol.for("@multiformats/multiaddr");function fc(r){if(r==null&&(r="/"),po(r))return r.getComponents();if(r instanceof Uint8Array)return lo(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ho(r);if(Array.isArray(r))return r;throw new C("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Yt=class r{[Vn]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=fc(e),t.validate!==!1&&dc(this)}get bytes(){return this.#r==null&&(this.#r=uo(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=fo(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 Xt(`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 j(this.bytes,e.bytes)}[hc](){return`Multiaddr(${this.toString()})`}};function dc(r){r.getComponents().forEach(e=>{let t=ae.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function po(r){return!!r?.[Vn]}function mo(r){return new Yt(r)}var er=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ge=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},tr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},mt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function rr(r){return r[Symbol.asyncIterator]!=null}function go(r,e){if(r.byteLength>e)throw new Ge("Message length too long")}var sr=r=>{let e=S(r),t=N(e);return Ct(r,t),sr.bytes=e,t};sr.bytes=0;function or(r,e){e=e??{};let t=e.lengthEncoder??sr,n=e?.maxDataLength??4194304;function*s(o){go(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return rr(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}or.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??sr,n=e?.maxDataLength??4194304;return go(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 qn=r=>{let e=me(r);return qn.bytes=S(e),e};qn.bytes=0;function gt(r,e){let t=new fe,n=Ie.LENGTH,s=-1,o=e?.lengthDecoder??qn,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 er("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 tr("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 rr(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 ir=class extends He{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Wn=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 bo(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Wn({name:e,metrics:t}):n=new Map,n}function gc(r){return r[Symbol.asyncIterator]!=null}function bc(r){if(gc(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Gn=bc;function wc(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 wo=wc;function yc(r){return r[Symbol.asyncIterator]!=null}function xc(r,e){let t=0;if(yc(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=wo(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 yo=xc;function Ec(r){return r[Symbol.asyncIterator]!=null}function _c(r,e){return Ec(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 xo=_c;var ar=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 ar(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(){Qn(t,"abort",u),Qn(r,e,l),Qn(r,o,f)}let l=h=>{try{if(n?.filter?.(h)===!1)return}catch(d){c(),a(d);return}c(),i(h)},f=h=>{if(c(),h instanceof Error){a(h);return}a(h.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.`))},u=()=>{c(),a(s)};Xn(t,"abort",u),Xn(r,e,l),Xn(r,o,f)})}function Xn(r,e,t){r!=null&&(Eo(r)?r.addEventListener(e,t):r.addListener(e,t))}function Qn(r,e,t){r!=null&&(Eo(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Eo(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var bt="/ipfs/bitswap/1.2.0";var D;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(D||(D={}));var jn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(jn||(jn={}));(function(r){r.codec=()=>Ot(jn)})(D||(D={}));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),D.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:P(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=D.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)=>be(t,r.codec(),n)})(Xe||(Xe={}));var cr;(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)=>be(t,r.codec(),n)})(cr||(cr={}));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:P(0),data:P(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)=>be(t,r.codec(),n)})(Qe||(Qe={}));var q;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(q||(q={}));var lr;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(lr||(lr={}));(function(r){r.codec=()=>Ot(lr)})(q||(q={}));var je;(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&&lr[t.type]!==0&&(n.uint32(16),q.codec().encode(t.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={cid:P(0),type:q.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=q.codec().decode(t);break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>be(t,r.codec(),n)})(je||(je={}));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),cr.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),je.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=cr.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(je.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)=>be(t,r.codec(),n)})(Le||(Le={}));function _o(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 ur=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var vc=4193648,Sc=vc+16;function*vo(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:u,hasMore:h,newSize:d}=Zn(s,l.blocks,a,e,f,Ic);a+=u,f=d;let m=h;({added:u,hasMore:h,newSize:d}=Zn(n,l.blockPresences,i,e,f,Dc)),i+=u,f=d;let w=h;if({added:u,hasMore:h,newSize:d}=Zn(t,l.wantlist.entries,o,e,f,Lc),o+=u,f=d,c=!m&&!w&&!h,c||(l.wantlist.full=!1),yield Le.encode(l),c)break}}function Zn(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>Sc)throw new ur("Cannot send block as after encoding it is over the max message size");let u=s+f;if(u>n){a=!0;break}e.push(l),i++,s=u}return{hasMore:a,added:i,newSize:s}}function Ic(r){return Kn(3,Qe.encode(r))}function Dc(r){return Kn(4,je.encode(r))}function Lc(r){return Kn(1,Xe.encode(r))}function Kn(r,e){let t=S(r),n=S(e.byteLength);return t+n+e.byteLength}var hr=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??[bt],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 ir({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 B("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 B("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 Gn(yo(xo(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=_o(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 B("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,bt,o);await a.closeRead();try{for(let c of vo(i,this.maxOutgoingMessageSize))a.send(or.single(c))||await a.onDrain(o);await a.close(o)}catch(c){o?.onProgress?.(new B("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 B("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(bt))return!0;throw new vt(`${e} did not support ${bt}`)}})]);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 fr(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 wt=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 fr(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 fr(this.map.values(),e=>e.key)}values(){return fr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Jn=class extends wt{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 Jn({name:e,metrics:t}):n=new wt,n}function Uc(r){return r[Symbol.asyncIterator]!=null}function Rc(r){if(Uc(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=Z([n,s],n.length+s.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Z(e,t)}var Io=Rc;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 Fc(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 Do=Fc;function Yn(r){return Do([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var dr=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;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}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)}async sendBlocksToPeer(e){let t=new ce,n=new Set;for(let[s,o]of this.wants.entries())try{let i=await Io(this.blockstore.get(o.cid,e));o.wantType===D.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),t.addBlock(o.cid,{data:i,prefix:Yn(o.cid)})):(this.log("sending have for %c",o.cid),t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:q.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),t.addBlock(o.cid,{data:i,prefix:Yn(o.cid)}))}catch(i){if(i.name!=="NotFoundError")throw i;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDoNotHave===!0)continue;o.sentDoNotHave=!0,t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:q.DoNotHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,o)=>s+o.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var pr=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,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.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new dr({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let s of t.wantlist.entries){let o=Q.decode(s.cid),i=M(o.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,o),n.wants.delete(i)):(s.wantType===D.WantHave?this.log("peer %p wanted block presence for %c",e,o):this.log("peer %p wanted block for %c",e,o),n.wants.set(i,{cid:o,priority:s.priority,wantType:s.wantType??D.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=M(e.multihash.bytes,"base64"),s=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&s.push(o);await Promise.all(s.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var $c=hs(To(),1);var Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));var mr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Te=class extends te{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=yn(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};if(this.requests.set(n,i),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));try{await ct(this.initialPeerSearchComplete,t.signal),u&&this.log("found initial session peers for %c",e)}catch(h){throw u&&this.log("failed to find initial session peers for %c - %e",e,h),this.requests.delete(n),i.observers>1&&o.reject(h),h}}let a=!1,c=new He({concurrency:this.maxProviders});c.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)}),c.addEventListener("success",u=>{a=!0,o.resolve(u.detail.result)}),c.addEventListener("idle",()=>{if(a){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 h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}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 l=u=>{c.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(h=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,h)})};this.addEventListener("provider",l),Promise.all([...this.providers].map(async u=>c.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 f=()=>{o.reject(new G(t.signal?.reason??"Session aborted")),c.abort()};t.signal?.addEventListener("abort",f);try{return await ct(o.promise,t.signal)}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",f),c.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(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.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}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",t,this.maxProviders,e),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,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"),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"),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 mr(`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 es=class extends Te{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,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 n.id}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}async convertToProvider(e,t){return Dt(e)?e:(await this.libp2p.dial(e,t)).remotePeer}};function Ao(r,e){return new es(r,e)}var gr=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 qc(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 ko=qc;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=bo({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=M(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??D.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===D.WantHave&&t.wantType===D.WantBlock&&(s.wantType=D.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===D.WantBlock?(await De(this,"block",t?.signal,{filter:a=>j(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await De(this,"presence",t?.signal,{filter:i=>j(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=M(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:D.WantHave,priority:1}),await this.network.sendMessage(t,s),(await De(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&j(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:D.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new ce;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:D.WantBlock,priority:1}),await this.network.sendMessage(t,s),(await De(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&j(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=M(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=ko(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 u=f.digest(s.data,{truncate:l});u.then!=null&&(u=await u);let h=Q.create(i===0?0:1,a,u);this.log("received block from %p for %c",e,h),this.safeDispatchEvent("block",{detail:{sender:e,cid:h,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:h,has:!0,block:s.data}});let d=M(h.multihash.bytes,"base64"),m=this.wants.get(d);m!=null&&(m.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===q.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:D.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 wr=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 gr(e),this.network=new hr(e,t),this.peerWantLists=new pr({...e,network:this.network},t),this.wantList=new br({...e,network:this.network},t)}createSession(e={}){return Ao({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,s=fs([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 B("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 Co=(r,e={})=>new wr(r,e);var ts=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=Co(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{announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>t.retrieve(n,s)}}};function Po(r={}){return e=>new ts(e,r)}var Wc=[6,53,56,54,55];function No(r){return Uo("sni",r)?.value}function Mo(r){let e=Uo("tcp",r)?.value;return e==null?"":`:${e}`}function Uo(r,e){return e.find(t=>t.name===r)}function Oo(r){return r.some(({code:e})=>e===448)}function ee(r,e){let t=Ro[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 Ro={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=Oo(e),n=No(e),s=Mo(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=Oo(e),n=No(e),s=Mo(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 yr(r,e){let n=mo(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=Ro[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return e?.assumeHttp!==!1&&Wc.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)}}),p=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Fo=r=>({match:e=>r.match(e)===!1?e:!1}),g=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),R=(...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 Gc=p(421),Om=v(Gc),Er=p(54),_r=p(55),vr=p(56),ns=p(53),Um=v(Er,g(p(421))),Rm=v(_r,g(p(421))),Fm=v(vr,g(p(421))),Bo=v(R(ns,vr,Er,_r),g(p(421))),zo=x(p(4),g(p(43))),$o=x(g(p(42)),p(41),g(p(43))),ss=R(zo,$o),Ae=R(ss,ns,Er,_r,vr),Bm=v(R(ss,x(R(ns,vr,Er,_r),g(p(421))))),zm=v(zo),$m=v($o),Hm=v(ss),os=x(Ae,p(6)),xt=x(Ae,p(273)),Vm=v(x(os,g(p(421)))),qm=v(xt),is=x(xt,_(460),g(p(421))),Sr=x(xt,_(461),g(p(421))),Xc=R(is,Sr),Wm=v(is),Gm=v(Sr),rs=R(Ae,os,xt,is,Sr),Ho=R(x(rs,_(477),g(p(421)))),Xm=v(Ho),Vo=R(x(rs,_(478),g(p(421))),x(rs,_(448),g(p(449)),_(477),g(p(421)))),Qm=v(Vo),qo=x(xt,_(280),g(p(466)),g(p(466)),g(p(421))),jm=v(qo),Wo=x(Sr,_(465),g(p(466)),g(p(466)),g(p(421))),Zm=v(Wo),xr=R(Ho,Vo,x(os,g(p(421))),x(Xc,g(p(421))),x(Ae,g(p(421))),qo,Wo,p(421)),Km=v(xr),Qc=x(g(xr),_(290),Fo(_(281)),g(p(421))),Jm=v(Qc),jc=R(x(xr,_(290),_(281),g(p(421))),x(xr,_(281),g(p(421))),x(_(281),g(p(421)))),Ym=v(jc),Zc=R(x(Ae,p(6),_(480),g(p(421))),x(Ae,_(480),g(p(421)))),Go=v(Zc),Kc=x(Ae,R(x(p(6,"443"),_(480)),x(p(6),_(443)),x(p(6),_(448),_(480)),x(_(448),_(480)),_(448),_(443)),g(p(421))),Xo=v(Kc),Jc=R(x(p(777),g(p(421)))),eg=v(Jc),Yc=R(x(p(400),g(p(421)))),tg=v(Yc);function as(r,e,t){return r.filter(n=>{if(Xo.matches(n)||e&&Go.matches(n))return t||Bo.matches(n)?!0:Js(n)===!1;if(!e&&t){let{host:s}=Rt(n);if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*Ir(r,e,t,n,s,o={}){for await(let i of e.findProviders(r,o)){let a=as(i.multiaddrs,n,s);if(a.length===0)continue;let c=yr(a[0]),l={type:"trustless-gateway",cid:r,url:c.toString(),routing:i.routing};o?.onProgress?.(new B("trustless-gateway:found-provider",l)),yield new Ke(c,{logger:t,transformRequestInit:o.transformRequestInit})}}async function Qo(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 Ke=class{url;#e=0;#t=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;constructor(e,{logger:t,transformRequestInit:n}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#o(e){let t=e.multihash.bytes;return se.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=jo}={}){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,u=new Headers(f.headers);this.log(`sending request
|
|
3
3
|
%s %s HTTP/1.1
|
|
4
4
|
%s
|
|
5
|
-
`,
|
|
6
|
-
`)),c=fetch(s.toString(),
|
|
5
|
+
`,f.method??"GET",s,[...u.entries()].map(([h,d])=>`${h}: ${d}`).join(`
|
|
6
|
+
`)),c=fetch(s.toString(),f).then(async h=>{if(this.log(`received response
|
|
7
7
|
HTTP/1.1 %d %s
|
|
8
8
|
%s
|
|
9
|
-
`,
|
|
10
|
-
`)),!
|
|
9
|
+
`,h.status,h.statusText,[...h.headers.entries()].map(([m,w])=>`${m}: ${w}`).join(`
|
|
10
|
+
`)),!h.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, recieved ${h.status} ${h.statusText}`);let d=await Qo(h,n,{signal:i.signal,log:this.log});return this.#s++,d}),this.#n.set(o,c)}return await c}catch(c){throw t?.aborted===!0?new Error(`Fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`Unable to fetch raw block for CID ${e} - ${c.message}`))}finally{t?.removeEventListener("abort",a),this.#n.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#s/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var cs=class extends Te{routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Dr,this.allowLocal=t.allowLocal??Lr,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let s=await t.getRawBlock(e,n);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(s),s}async*findNewProviders(e,t={}){yield*Ir(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t){if(Dt(e))return;let n=as(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(n.length===0)return;let s=yr(n[0]);return new Ke(s,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function Zo(r,e){return new cs(r,e)}var Tr=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Dr,this.allowLocal=t.allowLocal??Lr,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let s of Ir(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,s.url);try{let o=await s.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,s.url);try{await t.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s - %e",e,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s - %e",e,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${s.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,s.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return Zo({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Dr=!1,Lr=!1,jo=2097152;function Ko(r={}){return e=>new Tr(e,r)}return ni(el);})();
|
|
11
11
|
return HeliaBlockBrokers}));
|
|
12
12
|
//# sourceMappingURL=index.min.js.map
|