@helia/bitswap 3.2.3-6f8165b5 → 3.2.3-73a28eda
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 +1 -1
- package/dist/index.min.js.map +4 -4
- package/package.json +3 -3
package/dist/index.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBitswap = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaBitswap=(()=>{var pi=Object.create;var xt=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var bi=Object.getPrototypeOf,wi=Object.prototype.hasOwnProperty;var yi=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),_=(r,e)=>{for(var t in e)xt(r,t,{get:e[t],enumerable:!0})},ds=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gi(e))!wi.call(r,s)&&s!==t&&xt(r,s,{get:()=>e[s],enumerable:!(n=mi(e,s))||n.enumerable});return r};var xi=(r,e,t)=>(t=r!=null?pi(bi(r)):{},ds(e||!r||!r.__esModule?xt(t,"default",{value:r,enumerable:!0}):t,r)),vi=r=>ds(xt({},"__esModule",{value:!0}),r);var ui=yi((lw,hi)=>{hi.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 hu={};_(hu,{createBitswap:()=>lu});var O=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var vt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Et=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"}},_t=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Ei=Symbol.for("@libp2p/peer-id");function fs(r){return!!r?.[Ei]}function Si(r){return typeof r?.handleEvent=="function"}function _i(r){return(r!==!0&&r!==!1&&r?.once)??!1}var W=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let s=_i(n);super.addEventListener(e,i=>{if(s){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Si(t)?t.handleEvent(i):t(i)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:s})}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))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function ps(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}};function ms(r=0){return new Uint8Array(r)}function gs(r=0){return new Uint8Array(r)}function bs(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var br={};_(br,{base10:()=>Ci});var yu=new Uint8Array(0);function ws(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 j(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 ys(r){return new TextEncoder().encode(r)}function xs(r){return new TextDecoder().decode(r)}function Ai(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),h=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function p(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var f=0,m=0,g=0,x=l.length;g!==x&&l[g]===0;)g++,f++;for(var w=(x-g)*d+1>>>0,b=new Uint8Array(w);g!==x;){for(var E=l[g],A=0,v=w-1;(E!==0||A<m)&&v!==-1;v--,A++)E+=256*b[v]>>>0,b[v]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");m=A,g++}for(var S=w-m;S!==w&&b[S]===0;)S++;for(var C=c.repeat(f);S<w;++S)C+=r.charAt(b[S]);return C}function u(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var f=0;if(l[f]!==" "){for(var m=0,g=0;l[f]===c;)m++,f++;for(var x=(l.length-f)*h+1>>>0,w=new Uint8Array(x);l[f];){var b=t[l.charCodeAt(f)];if(b===255)return;for(var E=0,A=x-1;(b!==0||E<g)&&A!==-1;A--,E++)b+=a*w[A]>>>0,w[A]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");g=E,f++}if(l[f]!==" "){for(var v=x-g;v!==x&&w[v]===0;)v++;for(var S=new Uint8Array(m+(x-v)),C=m;v!==x;)S[C++]=w[v++];return S}}}function y(l){var f=u(l);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:u,decode:y}}var ki=Ai,Li=ki,Es=Li;var fr=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")}},pr=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 Ss(this,e)}},mr=class{decoders;constructor(e){this.decoders=e}or(e){return Ss(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 Ss(r,e){return new mr({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gr=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 fr(e,t,n),this.decoder=new pr(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Se({name:r,prefix:e,encode:t,decode:n}){return new gr(r,e,t,n)}function te({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Es(t,r);return Se({prefix:e,name:r,encode:n,decode:o=>j(s(o))})}function Di(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 h=0;h<s;++h){let d=e[r[h]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|d,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 Ii(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 Ti(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function D({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Ti(n);return Se({prefix:e,name:r,encode(o){return Ii(o,n,t)},decode(o){return Di(o,s,t,r)}})}var Ci=te({prefix:"9",name:"base10",alphabet:"0123456789"});var wr={};_(wr,{base16:()=>Ni,base16upper:()=>Mi});var Ni=D({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Mi=D({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yr={};_(yr,{base2:()=>Ui});var Ui=D({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var xr={};_(xr,{base256emoji:()=>Ri});var _s=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}"),Pi=_s.reduce((r,e,t)=>(r[t]=e,r),[]),Bi=_s.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function zi(r){return r.reduce((e,t)=>(e+=Pi[t],e),"")}function Fi(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Bi[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Ri=Se({prefix:"\u{1F680}",name:"base256emoji",encode:zi,decode:Fi});var vr={};_(vr,{base32:()=>_e,base32hex:()=>Vi,base32hexpad:()=>Hi,base32hexpadupper:()=>Gi,base32hexupper:()=>Wi,base32pad:()=>$i,base32padupper:()=>qi,base32upper:()=>Oi,base32z:()=>Xi});var _e=D({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Oi=D({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$i=D({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qi=D({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vi=D({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Wi=D({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hi=D({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Gi=D({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xi=D({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Er={};_(Er,{base36:()=>Xe,base36upper:()=>Ji});var Xe=te({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ji=te({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sr={};_(Sr,{base58btc:()=>H,base58flickr:()=>ji});var H=te({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ji=te({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var _r={};_(_r,{base64:()=>Qi,base64pad:()=>Ki,base64url:()=>Zi,base64urlpad:()=>Yi});var Qi=D({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ki=D({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zi=D({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yi=D({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ar={};_(Ar,{base8:()=>ea});var ea=D({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var kr={};_(kr,{identity:()=>ta});var ta=Se({prefix:"\0",name:"identity",encode:r=>xs(r),decode:r=>ys(r)});var Pu=new TextEncoder,Bu=new TextDecoder;var Dr={};_(Dr,{identity:()=>_a});var sa=Ls,As=128,oa=127,ia=~oa,aa=Math.pow(2,31);function Ls(r,e,t){e=e||[],t=t||0;for(var n=t;r>=aa;)e[t++]=r&255|As,r/=128;for(;r&ia;)e[t++]=r&255|As,r>>>=7;return e[t]=r|0,Ls.bytes=t-n+1,e}var ca=Lr,la=128,ks=127;function Lr(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Lr.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&ks)<<s:(i&ks)*Math.pow(2,s),s+=7}while(i>=la);return Lr.bytes=o-n,t}var ha=Math.pow(2,7),ua=Math.pow(2,14),da=Math.pow(2,21),fa=Math.pow(2,28),pa=Math.pow(2,35),ma=Math.pow(2,42),ga=Math.pow(2,49),ba=Math.pow(2,56),wa=Math.pow(2,63),ya=function(r){return r<ha?1:r<ua?2:r<da?3:r<fa?4:r<pa?5:r<ma?6:r<ga?7:r<ba?8:r<wa?9:10},xa={encode:sa,decode:ca,encodingLength:ya},va=xa,Je=va;function je(r,e=0){return[Je.decode(r,e),Je.decode.bytes]}function Ae(r,e,t=0){return Je.encode(r,e,t),e}function ke(r){return Je.encodingLength(r)}function De(r,e){let t=e.byteLength,n=ke(r),s=n+ke(t),o=new Uint8Array(s+t);return Ae(r,o,0),Ae(t,o,n),o.set(e,s),new Le(r,t,e,o)}function Ds(r){let e=j(r),[t,n]=je(e),[s,o]=je(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Le(t,s,i,e)}function Is(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ws(r.bytes,t.bytes)}}var Le=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var Ts=0,Ea="identity",Cs=j;function Sa(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 De(Ts,Cs(r))}var _a={code:Ts,name:Ea,encode:Cs,digest:Sa};var Cr={};_(Cr,{sha256:()=>ka,sha512:()=>La});var Aa=20;function Tr({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Ir(r,e,t,n,s)}var Ir=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??Aa,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?Ns(n,this.code,t?.truncate):n.then(s=>Ns(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ns(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 De(e,r)}function Us(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ka=Tr({name:"sha2-256",code:18,encode:Us("SHA-256")}),La=Tr({name:"sha2-512",code:19,encode:Us("SHA-512")});function Ps(r,e){let{bytes:t,version:n}=r;return n===0?Ia(t,Nr(r),e??H.encoder):Ta(t,Nr(r),e??_e.encoder)}var Bs=new WeakMap;function Nr(r){let e=Bs.get(r);if(e==null){let t=new Map;return Bs.set(r,t),t}return e}var kt=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!==Ke)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ca)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=De(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&&Is(e.multihash,n.multihash)}toString(e){return Ps(this,e)}toJSON(){return{"/":Ps(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??zs(n,s,o.bytes))}else if(t[Na]===!0){let{version:n,multihash:s,code:o}=t,i=Ds(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!==Ke)throw new Error(`Version 0 CID must use dag-pb (code: ${Ke}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=zs(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ke,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=j(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 Le(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[p,u]=je(e.subarray(t));return t+=u,p},s=n(),o=Ke;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(),h=t+c,d=h-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:d,size:h}}static parse(e,t){let[n,s]=Da(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 Nr(o).set(n,e),o}};function Da(r,e){switch(r[0]){case"Q":{let t=e??H;return[H.prefix,t.decode(`${H.prefix}${r}`)]}case H.prefix:{let t=e??H;return[H.prefix,t.decode(r)]}case _e.prefix:{let t=e??_e;return[_e.prefix,t.decode(r)]}case Xe.prefix:{let t=e??Xe;return[Xe.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 Ia(r,e,t){let{prefix:n}=t;if(n!==H.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 Ta(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 Ke=112,Ca=18;function zs(r,e,t){let n=ke(r),s=n+ke(e),o=new Uint8Array(s+t.byteLength);return Ae(r,o,0),Ae(e,o,n),o.set(t,s),o}var Na=Symbol.for("@ipld/js-cid/CID");var Mr={...kr,...yr,...Ar,...br,...wr,...vr,...Er,...Sr,..._r,...xr},sd={...Cr,...Dr};function Rs(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Fs=Rs("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ur=Rs("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=gs(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Ma={utf8:Fs,"utf-8":Fs,hex:Mr.base16,latin1:Ur,ascii:Ur,binary:Ur,...Mr},Os=Ma;function G(r,e="utf8"){let t=Os[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Pr={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},$s={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},qs=new globalThis.TextEncoder;function Ua(r,e){let t=Pr[e],n=$s[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function Pa(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Pr[e],s=$s[e],o=r;for(;o.length>0;){let i=qs.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 Br(r,{size:e=32,utf8Buffer:t}={}){if(!Pr[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 Pa(r,e,t);r=qs.encode(r)}return Ua(r,e)}var Ze={hash:r=>Number(Br(r,{size:32})),hashV:(r,e)=>Ba(Ze.hash(r,e))};function Ba(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),G(e,"base16")}var zr=64,$=class{fp;h;seed;constructor(e,t,n,s=2){if(s>zr)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=ms(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?bs(this.fp,e.fp):!1}};function ie(r,e){return Math.floor(Math.random()*(e-r))+r}var ae=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof $))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof $))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 $))throw new TypeError("Invalid Fingerprint");let t=ie(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof $))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var za=500,Ye=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??Ze,this.seed=e.seed??ie(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=G(e));let t=new $(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 ae(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new ae(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[ie(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new ae(this.bucketSize));for(let a=0;a<za;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 ae(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=G(e));let t=new $(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=G(e));let t=new $(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}},Fa={1:.5,2:.84,4:.95,8:.98};function Ra(r=.001){return r>.002?2:r>1e-5?4:8}function Vs(r,e=.001){let t=Ra(e),n=Fa[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),zr);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Lt=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??Ze,this.seed=e.seed??ie(0,Math.pow(2,10)),this.filterSeries=[new Ye({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=G(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 Ye({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=G(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=G(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 Dt(r,e=.001,t){return new Lt({...Vs(r,e),...t??{}})}function ce(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function z(r=0){return new Uint8Array(r)}function M(r=0){return new Uint8Array(r)}var Oa=Math.pow(2,7),$a=Math.pow(2,14),qa=Math.pow(2,21),Fr=Math.pow(2,28),Rr=Math.pow(2,35),Or=Math.pow(2,42),$r=Math.pow(2,49),k=128,U=127;function N(r){if(r<Oa)return 1;if(r<$a)return 2;if(r<qa)return 3;if(r<Fr)return 4;if(r<Rr)return 5;if(r<Or)return 6;if(r<$r)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function qr(r,e,t=0){switch(N(r)){case 8:e[t++]=r&255|k,r/=128;case 7:e[t++]=r&255|k,r/=128;case 6:e[t++]=r&255|k,r/=128;case 5:e[t++]=r&255|k,r/=128;case 4:e[t++]=r&255|k,r>>>=7;case 3:e[t++]=r&255|k,r>>>=7;case 2:e[t++]=r&255|k,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Va(r,e,t=0){switch(N(r)){case 8:e.set(t++,r&255|k),r/=128;case 7:e.set(t++,r&255|k),r/=128;case 6:e.set(t++,r&255|k),r/=128;case 5:e.set(t++,r&255|k),r/=128;case 4:e.set(t++,r&255|k),r>>>=7;case 3:e.set(t++,r&255|k),r>>>=7;case 2:e.set(t++,r&255|k),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Vr(r,e){let t=r[e],n=0;if(n+=t&U,t<k||(t=r[e+1],n+=(t&U)<<7,t<k)||(t=r[e+2],n+=(t&U)<<14,t<k)||(t=r[e+3],n+=(t&U)<<21,t<k)||(t=r[e+4],n+=(t&U)*Fr,t<k)||(t=r[e+5],n+=(t&U)*Rr,t<k)||(t=r[e+6],n+=(t&U)*Or,t<k)||(t=r[e+7],n+=(t&U)*$r,t<k))return n;throw new RangeError("Could not decode varint")}function Wa(r,e){let t=r.get(e),n=0;if(n+=t&U,t<k||(t=r.get(e+1),n+=(t&U)<<7,t<k)||(t=r.get(e+2),n+=(t&U)<<14,t<k)||(t=r.get(e+3),n+=(t&U)<<21,t<k)||(t=r.get(e+4),n+=(t&U)*Fr,t<k)||(t=r.get(e+5),n+=(t&U)*Rr,t<k)||(t=r.get(e+6),n+=(t&U)*Or,t<k)||(t=r.get(e+7),n+=(t&U)*$r,t<k))return n;throw new RangeError("Could not decode varint")}function It(r,e,t=0){return e==null&&(e=M(N(r))),e instanceof Uint8Array?qr(r,e,t):Va(r,e,t)}function Tt(r,e=0){return r instanceof Uint8Array?Vr(r,e):Wa(r,e)}function Ha(r){return r.buffer instanceof ArrayBuffer}function Hs(r){return Ha(r)?r:r.slice()}function Ga(r){return r?.buffer instanceof ArrayBuffer}function Gs(r){if(Ga(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ie(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=M(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return Gs(t)}var Jr={};_(Jr,{base10:()=>ec});var Vd=new Uint8Array(0);function Xs(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 Q(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return le(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return le(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Js(r){return new TextEncoder().encode(r)}function js(r){return new TextDecoder().decode(r)}function Xa(r){return r?.buffer instanceof ArrayBuffer}function le(r){return Xa(r)?r:r.slice()}function Ja(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),h=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function p(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var f=0,m=0,g=0,x=l.length;g!==x&&l[g]===0;)g++,f++;for(var w=(x-g)*d+1>>>0,b=new Uint8Array(w);g!==x;){for(var E=l[g],A=0,v=w-1;(E!==0||A<m)&&v!==-1;v--,A++)E+=256*b[v]>>>0,b[v]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");m=A,g++}for(var S=w-m;S!==w&&b[S]===0;)S++;for(var C=c.repeat(f);S<w;++S)C+=r.charAt(b[S]);return C}function u(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var f=0;if(l[f]!==" "){for(var m=0,g=0;l[f]===c;)m++,f++;for(var x=(l.length-f)*h+1>>>0,w=new Uint8Array(x);l[f];){var b=t[l.charCodeAt(f)];if(b===255)return;for(var E=0,A=x-1;(b!==0||E<g)&&A!==-1;A--,E++)b+=a*w[A]>>>0,w[A]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");g=E,f++}if(l[f]!==" "){for(var v=x-g;v!==x&&w[v]===0;)v++;for(var S=new Uint8Array(m+(x-v)),C=m;v!==x;)S[C++]=w[v++];return S}}}function y(l){var f=u(l);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:u,decode:y}}var ja=Ja,Qa=ja,Ks=Qa;var Wr=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")}},Hr=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 Zs(this,e)}},Gr=class{decoders;constructor(e){this.decoders=e}or(e){return Zs(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 Zs(r,e){return new Gr({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Xr=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 Wr(e,t,n),this.decoder=new Hr(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Te({name:r,prefix:e,encode:t,decode:n}){return new Xr(r,e,t,n)}function re({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Ks(t,r);return Te({prefix:e,name:r,encode:n,decode:o=>Q(s(o))})}function Ka(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 h=0;h<s;++h){let d=e[r[h]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|d,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 Za(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 Ya(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=Ya(n);return Te({prefix:e,name:r,encode(o){return Za(o,n,t)},decode(o){return Ka(o,s,t,r)}})}var ec=re({prefix:"9",name:"base10",alphabet:"0123456789"});var jr={};_(jr,{base16:()=>tc,base16upper:()=>rc});var tc=I({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rc=I({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Qr={};_(Qr,{base2:()=>nc});var nc=I({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Kr={};_(Kr,{base256emoji:()=>cc});var Ys=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}"),sc=Ys.reduce((r,e,t)=>(r[t]=e,r),[]),oc=Ys.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function ic(r){return r.reduce((e,t)=>(e+=sc[t],e),"")}function ac(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=oc[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var cc=Te({prefix:"\u{1F680}",name:"base256emoji",encode:ic,decode:ac});var Zr={};_(Zr,{base32:()=>Ce,base32hex:()=>dc,base32hexpad:()=>pc,base32hexpadupper:()=>mc,base32hexupper:()=>fc,base32pad:()=>hc,base32padupper:()=>uc,base32upper:()=>lc,base32z:()=>gc});var Ce=I({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),lc=I({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hc=I({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),uc=I({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),dc=I({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fc=I({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pc=I({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mc=I({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gc=I({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Yr={};_(Yr,{base36:()=>et,base36upper:()=>bc});var et=re({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bc=re({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var en={};_(en,{base58btc:()=>X,base58flickr:()=>wc});var X=re({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),wc=re({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var tn={};_(tn,{base64:()=>he,base64pad:()=>yc,base64url:()=>xc,base64urlpad:()=>vc});var he=I({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),yc=I({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xc=I({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vc=I({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var rn={};_(rn,{base8:()=>Ec});var Ec=I({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var nn={};_(nn,{identity:()=>Sc});var Sc=Te({prefix:"\0",name:"identity",encode:r=>js(r),decode:r=>Js(r)});var of=new TextEncoder,af=new TextDecoder;var on={};_(on,{identity:()=>Gc});var kc=ro,eo=128,Lc=127,Dc=~Lc,Ic=Math.pow(2,31);function ro(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Ic;)e[t++]=r&255|eo,r/=128;for(;r&Dc;)e[t++]=r&255|eo,r>>>=7;return e[t]=r|0,ro.bytes=t-n+1,e}var Tc=sn,Cc=128,to=127;function sn(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw sn.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&to)<<s:(i&to)*Math.pow(2,s),s+=7}while(i>=Cc);return sn.bytes=o-n,t}var Nc=Math.pow(2,7),Mc=Math.pow(2,14),Uc=Math.pow(2,21),Pc=Math.pow(2,28),Bc=Math.pow(2,35),zc=Math.pow(2,42),Fc=Math.pow(2,49),Rc=Math.pow(2,56),Oc=Math.pow(2,63),$c=function(r){return r<Nc?1:r<Mc?2:r<Uc?3:r<Pc?4:r<Bc?5:r<zc?6:r<Fc?7:r<Rc?8:r<Oc?9:10},qc={encode:kc,decode:Tc,encodingLength:$c},Vc=qc,tt=Vc;function rt(r,e=0){return[tt.decode(r,e),tt.decode.bytes]}function Ne(r,e,t=0){return tt.encode(r,e,t),e}function Me(r){return tt.encodingLength(r)}function Pe(r,e){let t=e.byteLength,n=Me(r),s=n+Me(t),o=new Uint8Array(s+t);return Ne(r,o,0),Ne(t,o,n),o.set(e,s),new Ue(r,t,e,o)}function no(r){let e=Q(r),[t,n]=rt(e),[s,o]=rt(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ue(t,s,i,e)}function so(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Xs(r.bytes,t.bytes)}}var Ue=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=le(n),this.bytes=le(s)}};var oo=0,Wc="identity",io=Q;function Hc(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 Pe(oo,io(r))}var Gc={code:oo,name:Wc,encode:io,digest:Hc};var ln={};_(ln,{sha256:()=>Nt,sha512:()=>Jc});var Xc=20;function cn({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new an(r,e,t,n,s)}var an=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??Xc,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?ao(n,this.code,t?.truncate):n.then(s=>ao(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ao(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 Pe(e,r)}function lo(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Nt=cn({name:"sha2-256",code:18,encode:lo("SHA-256")}),Jc=cn({name:"sha2-512",code:19,encode:lo("SHA-512")});function ho(r,e){let{bytes:t,version:n}=r;return n===0?Qc(t,hn(r),e??X.encoder):Kc(t,hn(r),e??Ce.encoder)}var uo=new WeakMap;function hn(r){let e=uo.get(r);if(e==null){let t=new Map;return uo.set(r,t),t}return e}var K=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=le(s),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==st)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Zc)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=Pe(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&&so(e.multihash,n.multihash)}toString(e){return ho(this,e)}toJSON(){return{"/":ho(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??fo(n,s,o.bytes))}else if(t[Yc]===!0){let{version:n,multihash:s,code:o}=t,i=no(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!==st)throw new Error(`Version 0 CID must use dag-pb (code: ${st}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=fo(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,st,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=Q(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 Ue(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[p,u]=rt(e.subarray(t));return t+=u,p},s=n(),o=st;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(),h=t+c,d=h-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:d,size:h}}static parse(e,t){let[n,s]=jc(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 hn(o).set(n,e),o}};function jc(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 Ce.prefix:{let t=e??Ce;return[Ce.prefix,t.decode(r)]}case et.prefix:{let t=e??et;return[et.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 Qc(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 Kc(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 st=112,Zc=18;function fo(r,e,t){let n=Me(r),s=n+Me(e),o=new Uint8Array(s+t.byteLength);return Ne(r,o,0),Ne(e,o,n),o.set(t,s),o}var Yc=Symbol.for("@ipld/js-cid/CID");var un={...nn,...Qr,...rn,...Jr,...jr,...Zr,...Yr,...en,...tn,...Kr},If={...ln,...on};function mo(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var po=mo("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),dn=mo("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=M(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),el={utf8:po,"utf-8":po,hex:un.base16,latin1:dn,ascii:dn,binary:dn,...un},Mt=el;function go(r,e="utf8"){let t=Mt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ne(r,e="utf8"){let t=Mt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function q(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ut=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}},Be=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ut(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 Ut(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 fn=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Pt(r={}){return tl(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 tl(r,e){e=e??{};let t=e.onEnd,n=new Be,s,o,i,a=q(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{o=x=>{o=null,n.push(x);try{m(r(n))}catch(w){g(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=q()})}},h=m=>o!=null?o(m):(n.push(m),s),d=m=>(n=new Be,o!=null?o({error:m}):(n.push({error:m}),s)),p=m=>{if(i)return s;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:m})},u=m=>i?s:(i=!0,m!=null?d(m):h({done:!0})),y=()=>(n=new Be,u(),{done:!0}),l=m=>(u(m),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:y,throw:l,push:p,end:u,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,w;g!=null&&(x=new Promise((b,E)=>{w=()=>{E(new fn)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,x])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},t==null)return s;let f=s;return s={[Symbol.asyncIterator](){return this},next(){return f.next()},throw(m){return f.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return f.return(),t!=null&&(t(),t=void 0),{done:!0}},push:p,end(m){return f.end(m),t!=null&&(t(m),t=void 0),s},get readableLength(){return f.readableLength},onEmpty:m=>f.onEmpty(m)},s}var pn=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},bo=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function mn(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,d=new Promise((p,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){u(bo(i));return}if(i&&(c=()=>{u(bo(i))},i.addEventListener("abort",c,{once:!0})),r.then(p,u),t===Number.POSITIVE_INFINITY)return;let y=new pn;a=o.setTimeout.call(void 0,()=>{if(n){try{p(n())}catch(l){u(l)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?p():s instanceof Error?u(s):(y.message=s??`Promise timed out after ${t} milliseconds`,u(y))},t)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},d}var rl=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 nl(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:h,removeListener:d}=rl(r),p=async(...y)=>{let l=t.multiArgs?y:y[0];if(t.filter)try{if(!await t.filter(l))return}catch(f){n(),i(f);return}c.push(l),t.count===c.length&&(n(),o(c))},u=(...y)=>{n(),i(t.rejectionMultiArgs?y:y[0])};n=()=>{for(let y of a)d(y,p);for(let y of t.rejectionEvents)a.includes(y)||d(y,u)};for(let y of a)h(y,p);for(let y of t.rejectionEvents)a.includes(y)||h(y,u);t.signal&&t.signal.addEventListener("abort",()=>{u(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=mn(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Bt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=nl(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function gn(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 zt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function sl(r){return r.reason}async function Ft(r,e,t){if(e==null)return r;let n=t?.translateError??sl;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 Rt=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=q(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new O)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ol(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ot=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=ol(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new O),this.cleanup())}async join(e){let t=new Rt(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ft(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var ze=class extends W{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=gn(this.emitEmpty.bind(this),1),this.emitIdle=gn(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 zt;let n=new Ot(e,t);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new O)}),this.clear()}async onEmpty(e){this.size!==0&&await Bt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Bt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Bt(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=Pt({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 O("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 $t=class extends ze{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var bn=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 bn({name:e,metrics:t}):n=new Map,n}function il(r){return r[Symbol.asyncIterator]!=null}function al(r){if(il(r))return(async()=>{for await(let e of r);})();for(let e of r);}var wn=al;var xo=Symbol.for("@achingbrain/uint8arraylist");function yo(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 qt(r){return!!r?.[xo]}var Fe=class r{bufs;length;[xo]=!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(qt(n)){t+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}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(qt(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=yo(this.bufs,e);return t.buf[t.index]}set(e,t){let n=yo(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(qt(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 Ie(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ie(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 h=e>=a&&e<c,d=t>a&&t<=c;if(h&&d){if(e===a&&t===c){n.push(i);break}let p=e-a;n.push(i.subarray(p,p+(t-e)));break}if(h){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(d){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(!qt(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 p=0;p<o;p++)i[p]=-1;for(let p=0;p<s;p++)i[n[p]]=p;let a=i,c=this.byteLength-n.byteLength,h=n.byteLength-1,d;for(let p=t;p<=c;p+=d){d=0;for(let u=h;u>=0;u--){let y=this.get(p+u);if(n[u]!==y){d=Math.max(1,u-a[y]);break}}if(d===0)return p}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=M(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=z(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=z(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=z(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=M(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=z(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=z(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=z(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=z(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=z(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(!ce(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var Vt=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Re=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Wt=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},ot=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ht(r){return r[Symbol.asyncIterator]!=null}function vo(r,e){if(r.byteLength>e)throw new Re("Message length too long")}var Xt=r=>{let e=N(r),t=M(e);return It(r,t),Xt.bytes=e,t};Xt.bytes=0;function Jt(r,e){e=e??{};let t=e.lengthEncoder??Xt,n=e?.maxDataLength??4194304;function*s(o){vo(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Ht(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}Jt.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Xt,n=e?.maxDataLength??4194304;return vo(r,n),new Fe(t(r.byteLength),r)};var ue;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ue||(ue={}));var yn=r=>{let e=Tt(r);return yn.bytes=N(e),e};yn.bytes=0;function it(r,e){let t=new Fe,n=ue.LENGTH,s=-1,o=e?.lengthDecoder??yn,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===ue.LENGTH)try{if(s=o(t),s<0)throw new Vt("Invalid message length");if(s>a)throw new Re("Message length too long");let h=o.bytes;t.consume(h),e?.onLength!=null&&e.onLength(s),n=ue.DATA}catch(h){if(h instanceof RangeError){if(t.byteLength>i)throw new Wt("Message length length too long");break}throw h}if(n===ue.DATA){if(t.byteLength<s)break;let h=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(h),yield h,n=ue.LENGTH}}}return Ht(r)?(async function*(){for await(let h of r)t.append(h),yield*c();if(t.byteLength>0)throw new ot("Unexpected end of input")})():(function*(){for(let h of r)t.append(h),yield*c();if(t.byteLength>0)throw new ot("Unexpected end of input")})()}it.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 it(n,{...e??{},onLength:o=>{t=o}})};function hl(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 Eo=hl;function ul(r){return r[Symbol.asyncIterator]!=null}function dl(r,e){let t=0;if(ul(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=Eo(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 So=dl;function fl(r){return r[Symbol.asyncIterator]!=null}function pl(r,e){return fl(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 _o=pl;var jt=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 jt(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(){vn(t,"abort",p),vn(r,e,h),vn(r,o,d)}let h=u=>{try{if(n?.filter?.(u)===!1)return}catch(y){c(),a(y);return}c(),i(u)},d=u=>{if(c(),u instanceof Error){a(u);return}a(u.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},p=()=>{c(),a(s)};xn(t,"abort",p),xn(r,e,h),xn(r,o,d)})}function xn(r,e,t){r!=null&&(Ao(r)?r.addEventListener(e,t):r.addListener(e,t))}function vn(r,e,t){r!=null&&(Ao(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Ao(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var at="/ipfs/bitswap/1.2.0";var En=new Float32Array([-0]),se=new Uint8Array(En.buffer);function ko(r,e,t){En[0]=r,e[t]=se[0],e[t+1]=se[1],e[t+2]=se[2],e[t+3]=se[3]}function Lo(r,e){return se[0]=r[e],se[1]=r[e+1],se[2]=r[e+2],se[3]=r[e+3],En[0]}var Sn=new Float64Array([-0]),P=new Uint8Array(Sn.buffer);function Do(r,e,t){Sn[0]=r,e[t]=P[0],e[t+1]=P[1],e[t+2]=P[2],e[t+3]=P[3],e[t+4]=P[4],e[t+5]=P[5],e[t+6]=P[6],e[t+7]=P[7]}function Io(r,e){return P[0]=r[e],P[1]=r[e+1],P[2]=r[e+2],P[3]=r[e+3],P[4]=r[e+4],P[5]=r[e+5],P[6]=r[e+6],P[7]=r[e+7],Sn[0]}var ml=BigInt(Number.MAX_SAFE_INTEGER),gl=BigInt(Number.MIN_SAFE_INTEGER),F=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 fe;if(e<ml&&e>gl)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>To&&(s=0n,++n>To&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return fe;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):fe}},fe=new F(0,0);fe.toBigInt=function(){return 0n};fe.zzEncode=fe.zzDecode=function(){return this};fe.length=function(){return 1};var To=4294967296n;function Co(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 No(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 _n(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 V(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Qt(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var An=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Hs(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,V(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 V(this,4);return Qt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw V(this,4);return Qt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw V(this,4);let e=Lo(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw V(this,4);let e=Io(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 V(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return No(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw V(this,e);this.pos+=e}else do if(this.pos>=this.len)throw V(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 F(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 V(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 V(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 V(this,8);let e=Qt(this.buf,this.pos+=4),t=Qt(this.buf,this.pos+=4);return new F(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=Vr(this.buf,this.pos);return this.pos+=N(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 ct(r){return new An(r instanceof Uint8Array?r:r.subarray())}function pe(r,e,t){let n=ct(r);return e.decode(n,void 0,t)}function kn(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return M(i);s+i>e&&(n=M(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var me=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ln(){}var In=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},bl=kn();function wl(r){return globalThis.Buffer!=null?M(r):bl(r)}var ht=class{len;head;tail;states;constructor(){this.len=0,this.head=new me(Ln,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new me(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Tn((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(Kt,10,F.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=F.fromBigInt(e);return this._push(Kt,t.length(),t)}uint64Number(e){return this._push(qr,N(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=F.fromBigInt(e).zzEncode();return this._push(Kt,t.length(),t)}sint64Number(e){let t=F.fromNumber(e).zzEncode();return this._push(Kt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Dn,1,e?1:0)}fixed32(e){return this._push(lt,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=F.fromBigInt(e);return this._push(lt,4,t.lo)._push(lt,4,t.hi)}fixed64Number(e){let t=F.fromNumber(e);return this._push(lt,4,t.lo)._push(lt,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(ko,4,e)}double(e){return this._push(Do,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Dn,1,0):this.uint32(t)._push(xl,t,e)}string(e){let t=Co(e);return t!==0?this.uint32(t)._push(_n,t,e):this._push(Dn,1,0)}fork(){return this.states=new In(this),this.head=this.tail=new me(Ln,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 me(Ln,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=wl(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Dn(r,e,t){e[t]=r&255}function yl(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Tn=class extends me{next;constructor(e,t){super(yl,e,t),this.next=void 0}};function Kt(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 lt(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 xl(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ht.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(vl,e,r),this},ht.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(El,e,r),this});function vl(r,e,t){e.set(r,t)}function El(r,e,t){r.length<40?_n(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(go(r),t)}function Cn(){return new ht}function ge(r,e){let t=Cn();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*be(r,e,t){let n=ct(r);yield*e.stream(n,void 0,"$",t)}var Zt={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Yt(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function er(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i){let a=i.int32();yield e(a)};return Yt("enum",Zt.VARINT,t,n,s)}function we(r,e,t){return Yt("message",Zt.LENGTH_DELIMITED,r,e,t)}var Z=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var L;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(L||(L={}));var Nn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Nn||(Nn={}));(function(r){r.codec=()=>er(Nn)})(L||(L={}));var ye;(function(r){let e;r.codec=()=>(e==null&&(e=we((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.priority!=null&&o.priority!==0&&(i.uint32(16),i.int32(o.priority)),o.cancel!=null&&(i.uint32(24),i.bool(o.cancel)),o.wantType!=null&&(i.uint32(32),L.codec().encode(o.wantType,i)),o.sendDontHave!=null&&(i.uint32(40),i.bool(o.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:z(0),priority:0},h=i==null?o.len:o.pos+i;for(;o.pos<h;){let d=o.uint32();switch(d>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.priority=o.int32();break}case 3:{c.cancel=o.bool();break}case 4:{c.wantType=L.codec().decode(o);break}case 5:{c.sendDontHave=o.bool();break}default:{o.skipType(d&7);break}}}return c},function*(o,i,a,c={}){let h=i==null?o.len:o.pos+i;for(;o.pos<h;){let d=o.uint32();switch(d>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.priority`,value:o.int32()};break}case 3:{yield{field:`${a}.cancel`,value:o.bool()};break}case 4:{yield{field:`${a}.wantType`,value:L.codec().decode(o)};break}case 5:{yield{field:`${a}.sendDontHave`,value:o.bool()};break}default:{o.skipType(d&7);break}}}})),e);function t(o){return ge(o,r.codec())}r.encode=t;function n(o,i){return pe(o,r.codec(),i)}r.decode=n;function s(o,i){return be(o,r.codec(),i)}r.stream=s})(ye||(ye={}));var ut;(function(r){let e;r.codec=()=>(e==null&&(e=we((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.entries!=null&&o.entries.length>0)for(let c of o.entries)i.uint32(10),ye.codec().encode(c,i);o.full!=null&&(i.uint32(16),i.bool(o.full)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={entries:[]},h=i==null?o.len:o.pos+i;for(;o.pos<h;){let d=o.uint32();switch(d>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new Z('Decode error - repeated field "entries" had too many elements');c.entries.push(ye.codec().decode(o,o.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=o.bool();break}default:{o.skipType(d&7);break}}}return c},function*(o,i,a,c={}){let h={entries:0},d=i==null?o.len:o.pos+i;for(;o.pos<d;){let p=o.uint32();switch(p>>>3){case 1:{if(c.limits?.entries!=null&&h.entries===c.limits.entries)throw new Z('Streaming decode error - repeated field "entries" had too many elements');for(let u of ye.codec().stream(o,o.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...u,index:h.entries};h.entries++;break}case 2:{yield{field:`${a}.full`,value:o.bool()};break}default:{o.skipType(p&7);break}}}})),e);function t(o){return ge(o,r.codec())}r.encode=t;function n(o,i){return pe(o,r.codec(),i)}r.decode=n;function s(o,i){return be(o,r.codec(),i)}r.stream=s})(ut||(ut={}));var xe;(function(r){let e;r.codec=()=>(e==null&&(e=we((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.prefix!=null&&o.prefix.byteLength>0&&(i.uint32(10),i.bytes(o.prefix)),o.data!=null&&o.data.byteLength>0&&(i.uint32(18),i.bytes(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={prefix:z(0),data:z(0)},h=i==null?o.len:o.pos+i;for(;o.pos<h;){let d=o.uint32();switch(d>>>3){case 1:{c.prefix=o.bytes();break}case 2:{c.data=o.bytes();break}default:{o.skipType(d&7);break}}}return c},function*(o,i,a,c={}){let h=i==null?o.len:o.pos+i;for(;o.pos<h;){let d=o.uint32();switch(d>>>3){case 1:{yield{field:`${a}.prefix`,value:o.bytes()};break}case 2:{yield{field:`${a}.data`,value:o.bytes()};break}default:{o.skipType(d&7);break}}}})),e);function t(o){return ge(o,r.codec())}r.encode=t;function n(o,i){return pe(o,r.codec(),i)}r.decode=n;function s(o,i){return be(o,r.codec(),i)}r.stream=s})(xe||(xe={}));var R;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(R||(R={}));var tr;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(tr||(tr={}));(function(r){r.codec=()=>er(tr)})(R||(R={}));var ve;(function(r){let e;r.codec=()=>(e==null&&(e=we((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.type!=null&&tr[o.type]!==0&&(i.uint32(16),R.codec().encode(o.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:z(0),type:R.HaveBlock},h=i==null?o.len:o.pos+i;for(;o.pos<h;){let d=o.uint32();switch(d>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.type=R.codec().decode(o);break}default:{o.skipType(d&7);break}}}return c},function*(o,i,a,c={}){let h=i==null?o.len:o.pos+i;for(;o.pos<h;){let d=o.uint32();switch(d>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.type`,value:R.codec().decode(o)};break}default:{o.skipType(d&7);break}}}})),e);function t(o){return ge(o,r.codec())}r.encode=t;function n(o,i){return pe(o,r.codec(),i)}r.decode=n;function s(o,i){return be(o,r.codec(),i)}r.stream=s})(ve||(ve={}));var Ee;(function(r){let e;r.codec=()=>(e==null&&(e=we((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.wantlist!=null&&(i.uint32(10),ut.codec().encode(o.wantlist,i)),o.blocks!=null&&o.blocks.length>0)for(let c of o.blocks)i.uint32(26),xe.codec().encode(c,i);if(o.blockPresences!=null&&o.blockPresences.length>0)for(let c of o.blockPresences)i.uint32(34),ve.codec().encode(c,i);o.pendingBytes!=null&&o.pendingBytes!==0&&(i.uint32(40),i.int32(o.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},h=i==null?o.len:o.pos+i;for(;o.pos<h;){let d=o.uint32();switch(d>>>3){case 1:{c.wantlist=ut.codec().decode(o,o.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new Z('Decode error - repeated field "blocks" had too many elements');c.blocks.push(xe.codec().decode(o,o.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new Z('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(ve.codec().decode(o,o.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=o.int32();break}default:{o.skipType(d&7);break}}}return c},function*(o,i,a,c={}){let h={blocks:0,blockPresences:0},d=i==null?o.len:o.pos+i;for(;o.pos<d;){let p=o.uint32();switch(p>>>3){case 1:{yield*ut.codec().stream(o,o.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&h.blocks===c.limits.blocks)throw new Z('Streaming decode error - repeated field "blocks" had too many elements');for(let u of xe.codec().stream(o,o.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...u,index:h.blocks};h.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&h.blockPresences===c.limits.blockPresences)throw new Z('Streaming decode error - repeated field "blockPresences" had too many elements');for(let u of ve.codec().stream(o,o.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...u,index:h.blockPresences};h.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:o.int32()};break}default:{o.skipType(p&7);break}}}})),e);function t(o){return ge(o,r.codec())}r.encode=t;function n(o,i){return pe(o,r.codec(),i)}r.decode=n;function s(o,i){return be(o,r.codec(),i)}r.stream=s})(Ee||(Ee={}));function Uo(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 rr=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Sl=4193648,_l=Sl+16;function*Po(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 h={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=Ee.encode(h).byteLength,{added:p,hasMore:u,newSize:y}=Mn(s,h.blocks,a,e,d,Al);a+=p,d=y;let l=u;({added:p,hasMore:u,newSize:y}=Mn(n,h.blockPresences,i,e,d,kl)),i+=p,d=y;let f=u;if({added:p,hasMore:u,newSize:y}=Mn(t,h.wantlist.entries,o,e,d,Ll),o+=p,d=y,c=!l&&!f&&!u,c||(h.wantlist.full=!1),yield Ee.encode(h),c)break}}function Mn(r,e,t,n,s,o){let i=0,a=!1;for(let c=t;c<r.length;c++){let h=r[c],d=o(h);if(d>_l)throw new rr("Cannot send block as after encoding it is over the max message size");let p=s+d;if(p>n){a=!0;break}e.push(h),i++,s=p}return{hasMore:a,added:i,newSize:s}}function Al(r){return Un(3,xe.encode(r))}function kl(r){return Un(4,ve.encode(r))}function Ll(r){return Un(1,ye.encode(r))}function Un(r,e){let t=N(r),n=N(e.byteLength);return t+n+e.byteLength}var nr=class extends W{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[at],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new $t({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=Pt();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 it(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ee.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),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 wn(So(_o(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=Uo(s.options.message,t),await s.join(n);return}await this.sendQueue.add(async o=>{let i=o.message;if(i==null)throw new vt("No message to send");this.log("sendMessage to %p",e),o.onProgress?.(new B("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,at,o);await a.closeRead(o);try{for(let c of Po(i,this.maxOutgoingMessageSize))a.send(Jt.single(c))||await a.onDrain(o);await a.close(o)}catch(c){this.log.error("error sending message to %p - %e",e,c),o?.onProgress?.(new B("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new _t("Network isn't running");t?.onProgress?.(new B("bitswap: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(at))return!0;throw new Et(`${e} did not support ${at}`)}})]);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)}};var Xm=new Uint8Array(0);function Pn(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 zl(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),h=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function p(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var f=0,m=0,g=0,x=l.length;g!==x&&l[g]===0;)g++,f++;for(var w=(x-g)*d+1>>>0,b=new Uint8Array(w);g!==x;){for(var E=l[g],A=0,v=w-1;(E!==0||A<m)&&v!==-1;v--,A++)E+=256*b[v]>>>0,b[v]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");m=A,g++}for(var S=w-m;S!==w&&b[S]===0;)S++;for(var C=c.repeat(f);S<w;++S)C+=r.charAt(b[S]);return C}function u(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var f=0;if(l[f]!==" "){for(var m=0,g=0;l[f]===c;)m++,f++;for(var x=(l.length-f)*h+1>>>0,w=new Uint8Array(x);l[f];){var b=t[l.charCodeAt(f)];if(b===255)return;for(var E=0,A=x-1;(b!==0||E<g)&&A!==-1;A--,E++)b+=a*w[A]>>>0,w[A]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");g=E,f++}if(l[f]!==" "){for(var v=x-g;v!==x&&w[v]===0;)v++;for(var S=new Uint8Array(m+(x-v)),C=m;v!==x;)S[C++]=w[v++];return S}}}function y(l){var f=u(l);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:u,decode:y}}var Fl=zl,Rl=Fl,zo=Rl;var Bn=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")}},zn=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 Fo(this,e)}},Fn=class{decoders;constructor(e){this.decoders=e}or(e){return Fo(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 Fo(r,e){return new Fn({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Rn=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 Bn(e,t,n),this.decoder=new zn(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ol({name:r,prefix:e,encode:t,decode:n}){return new Rn(r,e,t,n)}function On({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=zo(t,r);return Ol({prefix:e,name:r,encode:n,decode:o=>Pn(s(o))})}var $l=On({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),eg=On({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ql=127,rg=~ql,ng=Math.pow(2,31);var sg=Math.pow(2,7),og=Math.pow(2,14),ig=Math.pow(2,21),ag=Math.pow(2,28),cg=Math.pow(2,35),lg=Math.pow(2,42),hg=Math.pow(2,49),ug=Math.pow(2,56),dg=Math.pow(2,63);function sr(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 dt=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 sr(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 sr(this.map.values(),e=>e.key)}values(){return sr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var $n=class extends dt{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 ft(r){let{name:e,metrics:t}=r,n;return t!=null?n=new $n({name:e,metrics:t}):n=new dt,n}function Hl(r){return r[Symbol.asyncIterator]!=null}function Gl(r){if(Hl(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=Ie([n,s],n.length+s.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ie(e,t)}var Ro=Gl;var Y=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=he.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=he.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=he.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Xl(r){let e=new Uint8Array(r.reduce((n,s)=>n+N(s),0)),t=0;for(let n of r)e=It(n,e,t),t+=N(n);return e}var Oo=Xl;function qn(r){return Oo([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var or=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of e.entries){let s=K.decode(n.cid),o=ne(s.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,s),this.wants.delete(o);else{n.wantType===L.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,s):this.log("peer %p wanted block for %c",this.peerId,s);let i=this.wants.get(o);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===L.WantHave&&(n.wantType==null||n.wantType===L.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??L.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??L.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,s])=>s.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,s)=>n[1].created<s[1].created?-1:s[1].created<n[1].created?1:0).sort((n,s)=>n[1].haveBlock===!1?-1:s[1].haveBlock===!1?1:0).sort((n,s)=>n[1].priority<s[1].priority?-1:s[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=ne(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new Y,n=new Set;this.removeExpiredWants();let s=[...this.wants.entries()].filter(([o,i])=>i.status==="want");s.forEach(([o,i])=>{i.status="sending"});for(let[o,i]of s)try{let a=await Ro(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===L.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:a,prefix:qn(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:R.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:a,prefix:qn(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:R.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0)))}};var ir=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=ft({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new or({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let s of this.ledgerMap.values())s.hasWant(e)&&n.push(s);await Promise.all(n.map(async s=>s.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var Xn={};_(Xn,{base10:()=>eh});var rb=new Uint8Array(0);function $o(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 ee(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 qo(r){return new TextEncoder().encode(r)}function Vo(r){return new TextDecoder().decode(r)}function Jl(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),h=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function p(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var f=0,m=0,g=0,x=l.length;g!==x&&l[g]===0;)g++,f++;for(var w=(x-g)*d+1>>>0,b=new Uint8Array(w);g!==x;){for(var E=l[g],A=0,v=w-1;(E!==0||A<m)&&v!==-1;v--,A++)E+=256*b[v]>>>0,b[v]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");m=A,g++}for(var S=w-m;S!==w&&b[S]===0;)S++;for(var C=c.repeat(f);S<w;++S)C+=r.charAt(b[S]);return C}function u(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var f=0;if(l[f]!==" "){for(var m=0,g=0;l[f]===c;)m++,f++;for(var x=(l.length-f)*h+1>>>0,w=new Uint8Array(x);l[f];){var b=t[l.charCodeAt(f)];if(b===255)return;for(var E=0,A=x-1;(b!==0||E<g)&&A!==-1;A--,E++)b+=a*w[A]>>>0,w[A]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");g=E,f++}if(l[f]!==" "){for(var v=x-g;v!==x&&w[v]===0;)v++;for(var S=new Uint8Array(m+(x-v)),C=m;v!==x;)S[C++]=w[v++];return S}}}function y(l){var f=u(l);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:u,decode:y}}var jl=Jl,Ql=jl,Ho=Ql;var Vn=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")}},Wn=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 Go(this,e)}},Hn=class{decoders;constructor(e){this.decoders=e}or(e){return Go(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 Go(r,e){return new Hn({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Gn=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 Vn(e,t,n),this.decoder=new Wn(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function $e({name:r,prefix:e,encode:t,decode:n}){return new Gn(r,e,t,n)}function oe({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Ho(t,r);return $e({prefix:e,name:r,encode:n,decode:o=>ee(s(o))})}function Kl(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 h=0;h<s;++h){let d=e[r[h]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|d,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 Zl(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 Yl(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function T({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Yl(n);return $e({prefix:e,name:r,encode(o){return Zl(o,n,t)},decode(o){return Kl(o,s,t,r)}})}var eh=oe({prefix:"9",name:"base10",alphabet:"0123456789"});var Jn={};_(Jn,{base16:()=>th,base16upper:()=>rh});var th=T({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rh=T({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var jn={};_(jn,{base2:()=>nh});var nh=T({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Qn={};_(Qn,{base256emoji:()=>ch});var Xo=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}"),sh=Xo.reduce((r,e,t)=>(r[t]=e,r),[]),oh=Xo.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function ih(r){return r.reduce((e,t)=>(e+=sh[t],e),"")}function ah(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=oh[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var ch=$e({prefix:"\u{1F680}",name:"base256emoji",encode:ih,decode:ah});var Kn={};_(Kn,{base32:()=>qe,base32hex:()=>dh,base32hexpad:()=>ph,base32hexpadupper:()=>mh,base32hexupper:()=>fh,base32pad:()=>hh,base32padupper:()=>uh,base32upper:()=>lh,base32z:()=>gh});var qe=T({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),lh=T({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hh=T({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),uh=T({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),dh=T({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fh=T({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ph=T({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mh=T({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gh=T({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Zn={};_(Zn,{base36:()=>pt,base36upper:()=>bh});var pt=oe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bh=oe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Yn={};_(Yn,{base58btc:()=>J,base58flickr:()=>wh});var J=oe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),wh=oe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var es={};_(es,{base64:()=>yh,base64pad:()=>xh,base64url:()=>vh,base64urlpad:()=>Eh});var yh=T({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),xh=T({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vh=T({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Eh=T({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ts={};_(ts,{base8:()=>Sh});var Sh=T({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var rs={};_(rs,{identity:()=>_h});var _h=$e({prefix:"\0",name:"identity",encode:r=>Vo(r),decode:r=>qo(r)});var wb=new TextEncoder,yb=new TextDecoder;var ss={};_(ss,{identity:()=>Xh});var Lh=Qo,Jo=128,Dh=127,Ih=~Dh,Th=Math.pow(2,31);function Qo(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Th;)e[t++]=r&255|Jo,r/=128;for(;r&Ih;)e[t++]=r&255|Jo,r>>>=7;return e[t]=r|0,Qo.bytes=t-n+1,e}var Ch=ns,Nh=128,jo=127;function ns(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ns.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&jo)<<s:(i&jo)*Math.pow(2,s),s+=7}while(i>=Nh);return ns.bytes=o-n,t}var Mh=Math.pow(2,7),Uh=Math.pow(2,14),Ph=Math.pow(2,21),Bh=Math.pow(2,28),zh=Math.pow(2,35),Fh=Math.pow(2,42),Rh=Math.pow(2,49),Oh=Math.pow(2,56),$h=Math.pow(2,63),qh=function(r){return r<Mh?1:r<Uh?2:r<Ph?3:r<Bh?4:r<zh?5:r<Fh?6:r<Rh?7:r<Oh?8:r<$h?9:10},Vh={encode:Lh,decode:Ch,encodingLength:qh},Wh=Vh,mt=Wh;function gt(r,e=0){return[mt.decode(r,e),mt.decode.bytes]}function Ve(r,e,t=0){return mt.encode(r,e,t),e}function We(r){return mt.encodingLength(r)}function Ge(r,e){let t=e.byteLength,n=We(r),s=n+We(t),o=new Uint8Array(s+t);return Ve(r,o,0),Ve(t,o,n),o.set(e,s),new He(r,t,e,o)}function Ko(r){let e=ee(r),[t,n]=gt(e),[s,o]=gt(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new He(t,s,i,e)}function Zo(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&$o(r.bytes,t.bytes)}}var He=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var Yo=0,Hh="identity",ei=ee;function Gh(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 Ge(Yo,ei(r))}var Xh={code:Yo,name:Hh,encode:ei,digest:Gh};var as={};_(as,{sha256:()=>jh,sha512:()=>Qh});var Jh=20;function is({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new os(r,e,t,n,s)}var os=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??Jh,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?ti(n,this.code,t?.truncate):n.then(s=>ti(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ti(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 Ge(e,r)}function ni(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var jh=is({name:"sha2-256",code:18,encode:ni("SHA-256")}),Qh=is({name:"sha2-512",code:19,encode:ni("SHA-512")});function si(r,e){let{bytes:t,version:n}=r;return n===0?Zh(t,cs(r),e??J.encoder):Yh(t,cs(r),e??qe.encoder)}var oi=new WeakMap;function cs(r){let e=oi.get(r);if(e==null){let t=new Map;return oi.set(r,t),t}return e}var cr=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!==wt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==eu)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=Ge(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&&Zo(e.multihash,n.multihash)}toString(e){return si(this,e)}toJSON(){return{"/":si(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??ii(n,s,o.bytes))}else if(t[tu]===!0){let{version:n,multihash:s,code:o}=t,i=Ko(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!==wt)throw new Error(`Version 0 CID must use dag-pb (code: ${wt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=ii(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,wt,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=ee(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 He(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[p,u]=gt(e.subarray(t));return t+=u,p},s=n(),o=wt;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(),h=t+c,d=h-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:d,size:h}}static parse(e,t){let[n,s]=Kh(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 cs(o).set(n,e),o}};function Kh(r,e){switch(r[0]){case"Q":{let t=e??J;return[J.prefix,t.decode(`${J.prefix}${r}`)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(r)]}case qe.prefix:{let t=e??qe;return[qe.prefix,t.decode(r)]}case pt.prefix:{let t=e??pt;return[pt.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 Zh(r,e,t){let{prefix:n}=t;if(n!==J.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 Yh(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 wt=112,eu=18;function ii(r,e,t){let n=We(r),s=n+We(e),o=new Uint8Array(s+t.byteLength);return Ve(r,o,0),Ve(e,o,n),o.set(t,s),o}var tu=Symbol.for("@ipld/js-cid/CID");var ls={...rs,...jn,...ts,...Xn,...Jn,...Kn,...Zn,...Yn,...es,...Qn},$b={...as,...ss};function ai(r=0){return new Uint8Array(r)}function li(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ci=li("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),hs=li("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=ai(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Gb={utf8:ci,"utf-8":ci,hex:ls.base16,latin1:hs,ascii:hs,binary:hs,...ls};var su=xi(ui(),1);var Oe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Oe||(Oe={}));var lr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var yt=class extends W{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Dt(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=he.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=q(),i={promise:o.promise,observers:1,queryFilter:Dt(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,h=new ze({concurrency:this.maxProviders});h.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)}),h.addEventListener("success",u=>{c=!0,o.resolve(u.detail.result)}),h.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let y=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(y)}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 d=u=>{let y=this.toFilterKey(u.detail);i.queryFilter.has(y)||(i.queryFilter.add(y),this.emitFoundProviderProgressEvent(e,u.detail,t),h.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,l)}))};if(this.addEventListener("provider",d),a)try{await Ft(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(u){throw a&&this.log("failed to find initial session peers for %c - %e",e,u),this.requests.delete(n),i.observers>1&&o.reject(u),u}Promise.all([...this.providers].filter(u=>{let y=this.toFilterKey(u),l=i.queryFilter.has(y);return l||i.queryFilter.add(this.toFilterKey(u)),!l}).map(async u=>h.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 p=()=>{o.reject(new O(t.signal?.reason??"Session aborted")),h.abort()};t.signal?.addEventListener("abort",p);try{return await o.promise}finally{this.removeEventListener("provider",d),t.signal?.removeEventListener("abort",p),h.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let s=q(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let h=i.initialProviders.pop();if(h==null)continue;let d=await i.convertToProvider(h,"manual",n);d!=null&&(yield d)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let h of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(h)&&(this.log("found %d providers, %d in session",o,this.providers.length),this.providers.push(h),this.safeDispatchEvent("provider",{detail:h}),o++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",o,t,this.providers.length),this.providers.length<t)throw new lr(`Found ${o} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),s.reject(i)}),s.promise}};var us=class extends yt{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let s=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.toMultihash().bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(fs(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let s=await this.libp2p.dial(e,n);return{peerId:s.remotePeer,routing:t,toString:()=>`Bitswap(${s.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new B("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function di(r,e){return new us(r,e)}var hr=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 cu(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Tt(r);e.push(t),r=r.slice(N(t))}return e}var fi=cu;var ur=class extends W{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=ft({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=wo({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=ne(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??L.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,s)),t.onProgress!=null&&s.onProgress.push({onProgress:t.onProgress,signal:t.signal}),s.wantType===L.WantHave&&t.wantType===L.WantBlock&&(s.wantType=L.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===L.WantBlock?(await de(this,"block",t?.signal,{filter:a=>ce(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await de(this,"presence",t?.signal,{filter:i=>ce(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),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.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=q(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,s=new Y;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,{onProgress:o=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(o)})})}});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=ne(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let s=new Y;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:L.WantHave,priority:1}),await this.network.sendMessage(t,s,n),(await de(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&ce(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:L.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new Y;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:L.WantBlock,priority:1}),await this.network.sendMessage(t,s,n),(await de(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&ce(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=ne(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.remotePeer,t.blocks.length);let n=!1;for(let s of t.blocks){if(s.prefix==null||s.data==null)continue;let o=fi(s.prefix),i=o[0],a=o[1],c=o[2],h=o[3],d=c===Nt.code?Nt:await this.getHasher(c);if(d==null){this.log.error("unknown hash algorithm",c);continue}let p=d.digest(s.data,{truncate:h});p.then!=null&&(p=await p);let u=K.create(i===0?0:1,a,p);this.log("received block from %p for %c",e.remotePeer,u),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:u,block:s.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:u,has:!0,block:s.data}});let y=ne(u.multihash.bytes,"base64"),l=this.wants.get(y);l!=null&&(l.cancel=!0,n=!0)}for(let{cid:s,type:o}of t.blockPresences){let i=K.decode(s);this.log("received %s from %p for %c",o,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:o===R.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Y(!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:L.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:s=>{this.wants.forEach(({onProgress:o})=>{o.forEach(({onProgress:i})=>{i(s)})})}}),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 dr=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 hr(e),this.network=new nr(e,t),this.peerWantLists=new ir({...e,network:this.network},t),this.wantList=new ur({...e,network:this.network},t)}createSession(e={}){return di({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,s=ps([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.connection.remotePeer})),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 lu=(r,e={})=>new dr(r,e);return vi(hu);})();
|
|
2
|
+
"use strict";var HeliaBitswap=(()=>{var zn=Object.create;var $e=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var Hn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var $n=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),D=(r,e)=>{for(var t in e)$e(r,t,{get:e[t],enumerable:!0})},Fr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Wn(e))!qn.call(r,i)&&i!==t&&$e(r,i,{get:()=>e[i],enumerable:!(n=On(e,i))||n.enumerable});return r};var Vn=(r,e,t)=>(t=r!=null?zn(Hn(r)):{},Fr(e||!r||!r.__esModule?$e(t,"default",{value:r,enumerable:!0}):t,r)),Gn=r=>Fr($e({},"__esModule",{value:!0}),r);var Fn=$n(($h,Bn)=>{Bn.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 i(s,o){t[s]=o,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var o=t[s];if(o!==void 0)return o;if((o=n[s])!==void 0)return i(s,o),o},set:function(s,o){t[s]!==void 0?t[s]=o:i(s,o)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var ho={};D(ho,{createBitswap:()=>lo});var F=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Ve=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Ge=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}};var Xe=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Qe=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Xn=Symbol.for("@libp2p/peer-id");function Ur(r){return!!r?.[Xn]}function Qn(r){return typeof r?.handleEvent=="function"}function Kn(r){return(r!==!0&&r!==!1&&r?.once)??!1}var W=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let i=Kn(n);super.addEventListener(e,o=>{if(i){let a=this.#e.get(o.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(o.type,a))}Qn(t)?t.handleEvent(o):t(o)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:i})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==t),this.#e.set(e,i))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function Rr(r){let e=new globalThis.AbortController;function t(){let s=r.filter(o=>o?.aborted===!0).map(o=>o?.reason).pop();e.abort(s);for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}var T=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Ut={};D(Ut,{base58btc:()=>U,base58flickr:()=>ns});var wo=new Uint8Array(0);function zr(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 q(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return J(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return J(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Or(r){return new TextEncoder().encode(r)}function Wr(r){return new TextDecoder().decode(r)}function Zn(r){return r?.buffer instanceof ArrayBuffer}function J(r){return Zn(r)?r:r.slice()}function Yn(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 i=0;i<r.length;i++){var s=r.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,m=0,x=0,A=p.length;x!==A&&p[x]===0;)x++,b++;for(var v=(A-x)*u+1>>>0,I=new Uint8Array(v);x!==A;){for(var M=p[x],K=0,B=v-1;(M!==0||K<m)&&B!==-1;B--,K++)M+=256*I[B]>>>0,I[B]=M%a>>>0,M=M/a>>>0;if(M!==0)throw new Error("Non-zero carry");m=K,x++}for(var H=v-m;H!==v&&I[H]===0;)H++;for(var qe=c.repeat(b);H<v;++H)qe+=r.charAt(I[H]);return qe}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var m=0,x=0;p[b]===c;)m++,b++;for(var A=(p.length-b)*l+1>>>0,v=new Uint8Array(A);p[b];){var I=t[p.charCodeAt(b)];if(I===255)return;for(var M=0,K=A-1;(I!==0||M<x)&&K!==-1;K--,M++)I+=a*v[K]>>>0,v[K]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");x=M,b++}if(p[b]!==" "){for(var B=A-x;B!==A&&v[B]===0;)B++;for(var H=new Uint8Array(m+(A-B)),qe=m;B!==A;)H[qe++]=v[B++];return H}}}function f(p){var b=h(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var Jn=Yn,jn=Jn,qr=jn;var Mt=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")}},Ct=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,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 $r(this,e)}},Bt=class{decoders;constructor(e){this.decoders=e}or(e){return $r(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 $r(r,e){return new Bt({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ft=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Mt(e,t,n),this.decoder=new Ct(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function pe({name:r,prefix:e,encode:t,decode:n}){return new Ft(r,e,t,n)}function Z({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=qr(t,r);return pe({prefix:e,name:r,encode:n,decode:s=>q(i(s))})}function es(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),o=0,a=0,c=0;for(let l=0;l<i;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,o+=t,o>=8&&(o-=8,s[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return s}function ts(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o!==0&&(s+=e[i&a<<t-o]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function rs(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function y({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let i=rs(n);return pe({prefix:e,name:r,encode(s){return ts(s,n,t)},decode(s){return es(s,i,t,r)}})}var U=Z({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ns=Z({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Rt={};D(Rt,{base32:()=>me,base32hex:()=>as,base32hexpad:()=>ls,base32hexpadupper:()=>hs,base32hexupper:()=>cs,base32pad:()=>is,base32padupper:()=>os,base32upper:()=>ss,base32z:()=>us});var me=y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ss=y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),is=y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),os=y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),as=y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),cs=y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ls=y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hs=y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),us=y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var zt={};D(zt,{base36:()=>Ae,base36upper:()=>ds});var Ae=Z({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ds=Z({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fs=Xr,Vr=128,ps=127,ms=~ps,gs=Math.pow(2,31);function Xr(r,e,t){e=e||[],t=t||0;for(var n=t;r>=gs;)e[t++]=r&255|Vr,r/=128;for(;r&ms;)e[t++]=r&255|Vr,r>>>=7;return e[t]=r|0,Xr.bytes=t-n+1,e}var bs=Ot,ws=128,Gr=127;function Ot(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw Ot.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&Gr)<<i:(o&Gr)*Math.pow(2,i),i+=7}while(o>=ws);return Ot.bytes=s-n,t}var ys=Math.pow(2,7),xs=Math.pow(2,14),Es=Math.pow(2,21),vs=Math.pow(2,28),_s=Math.pow(2,35),Ss=Math.pow(2,42),ks=Math.pow(2,49),Ls=Math.pow(2,56),As=Math.pow(2,63),Ts=function(r){return r<ys?1:r<xs?2:r<Es?3:r<vs?4:r<_s?5:r<Ss?6:r<ks?7:r<Ls?8:r<As?9:10},Is={encode:fs,decode:bs,encodingLength:Ts},Ds=Is,Te=Ds;function Ie(r,e=0){return[Te.decode(r,e),Te.decode.bytes]}function ge(r,e,t=0){return Te.encode(r,e,t),e}function be(r){return Te.encodingLength(r)}function ye(r,e){let t=e.byteLength,n=be(r),i=n+be(t),s=new Uint8Array(i+t);return ge(r,s,0),ge(t,s,n),s.set(e,i),new we(r,t,e,s)}function Wt(r){let e=q(r),[t,n]=Ie(e),[i,s]=Ie(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new we(t,i,o,e)}function Qr(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&zr(r.bytes,t.bytes)}}var we=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=J(n),this.bytes=J(i)}};function Kr(r,e){let{bytes:t,version:n}=r;return n===0?Ns(t,Ht(r),e??U.encoder):Ms(t,Ht(r),e??me.encoder)}var Zr=new WeakMap;function Ht(r){let e=Zr.get(r);if(e==null){let t=new Map;return Zr.set(r,t),t}return e}var $=class r{code;version;multihash;bytes;"/";constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=J(i),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==De)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Cs)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=ye(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&&Qr(e.multihash,n.multihash)}toString(e){return Kr(this,e)}toJSON(){return{"/":Kr(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:i,multihash:s,bytes:o}=t;return new r(n,i,s,o??Yr(n,i,s.bytes))}else if(t[Bs]===!0){let{version:n,multihash:i,code:s}=t,o=Wt(i);return r.create(n,s,o)}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!==De)throw new Error(`Version 0 CID must use dag-pb (code: ${De}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=Yr(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,De,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,i=q(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new we(t.multihashCode,t.digestSize,s,i);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=Ie(e.subarray(t));return t+=h,d},i=n(),s=De;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),l=t+c,u=l-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,i]=Ps(e,t),s=r.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ht(s).set(n,e),s}};function Ps(r,e){switch(r[0]){case"Q":{let t=e??U;return[U.prefix,t.decode(`${U.prefix}${r}`)]}case U.prefix:{let t=e??U;return[U.prefix,t.decode(r)]}case me.prefix:{let t=e??me;return[me.prefix,t.decode(r)]}case Ae.prefix:{let t=e??Ae;return[Ae.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 Ns(r,e,t){let{prefix:n}=t;if(n!==U.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i}function Ms(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i}var De=112,Cs=18;function Yr(r,e,t){let n=be(r),i=n+be(e),s=new Uint8Array(i+t.byteLength);return ge(r,s,0),ge(e,s,n),s.set(t,i),s}var Bs=Symbol.for("@ipld/js-cid/CID");var qt={};D(qt,{identity:()=>Rs});var Jr=0,Fs="identity",jr=q;function Us(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 ye(Jr,jr(r))}var Rs={code:Jr,name:Fs,encode:jr,digest:Us};function V(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 _(r=0){return new Uint8Array(r)}function S(r=0){return new Uint8Array(r)}function zs(r){return r?.buffer instanceof ArrayBuffer}function en(r){if(zs(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ee(r,e){e==null&&(e=r.reduce((i,s)=>i+s.length,0));let t=S(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return en(t)}var $t={};D($t,{base10:()=>Os});var Os=Z({prefix:"9",name:"base10",alphabet:"0123456789"});var Vt={};D(Vt,{base16:()=>Ws,base16upper:()=>Hs});var Ws=y({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Hs=y({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Gt={};D(Gt,{base2:()=>qs});var qs=y({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Xt={};D(Xt,{base256emoji:()=>Qs});var tn=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}"),$s=tn.reduce((r,e,t)=>(r[t]=e,r),[]),Vs=tn.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Gs(r){return r.reduce((e,t)=>(e+=$s[t],e),"")}function Xs(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=Vs[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var Qs=pe({prefix:"\u{1F680}",name:"base256emoji",encode:Gs,decode:Xs});var Qt={};D(Qt,{base64:()=>j,base64pad:()=>Ks,base64url:()=>Zs,base64urlpad:()=>Ys});var j=y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ks=y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zs=y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ys=y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Kt={};D(Kt,{base8:()=>Js});var Js=y({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Zt={};D(Zt,{identity:()=>js});var js=pe({prefix:"\0",name:"identity",encode:r=>Wr(r),decode:r=>Or(r)});var Zo=new TextEncoder,Yo=new TextDecoder;var jt={};D(jt,{sha256:()=>Ze,sha512:()=>ni});var ri=20;function Jt({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new Yt(r,e,t,n,i)}var Yt=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??ri,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?rn(n,this.code,t?.truncate):n.then(i=>rn(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function rn(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 ye(e,r)}function sn(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ze=Jt({name:"sha2-256",code:18,encode:sn("SHA-256")}),ni=Jt({name:"sha2-512",code:19,encode:sn("SHA-512")});var er={...Zt,...Gt,...Kt,...$t,...Vt,...Rt,...zt,...Ut,...Qt,...Xt},la={...jt,...qt};function an(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var on=an("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),tr=an("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=S(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),si={utf8:on,"utf-8":on,hex:er.base16,latin1:tr,ascii:tr,binary:tr,...er},Ye=si;function C(r,e="utf8"){let t=Ye[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function G(r,e="utf8"){let t=Ye[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ii=Math.pow(2,7),oi=Math.pow(2,14),ai=Math.pow(2,21),rr=Math.pow(2,28),nr=Math.pow(2,35),sr=Math.pow(2,42),ir=Math.pow(2,49),g=128,k=127;function E(r){if(r<ii)return 1;if(r<oi)return 2;if(r<ai)return 3;if(r<rr)return 4;if(r<nr)return 5;if(r<sr)return 6;if(r<ir)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function or(r,e,t=0){switch(E(r)){case 8:e[t++]=r&255|g,r/=128;case 7:e[t++]=r&255|g,r/=128;case 6:e[t++]=r&255|g,r/=128;case 5:e[t++]=r&255|g,r/=128;case 4:e[t++]=r&255|g,r>>>=7;case 3:e[t++]=r&255|g,r>>>=7;case 2:e[t++]=r&255|g,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function ci(r,e,t=0){switch(E(r)){case 8:e.set(t++,r&255|g),r/=128;case 7:e.set(t++,r&255|g),r/=128;case 6:e.set(t++,r&255|g),r/=128;case 5:e.set(t++,r&255|g),r/=128;case 4:e.set(t++,r&255|g),r>>>=7;case 3:e.set(t++,r&255|g),r>>>=7;case 2:e.set(t++,r&255|g),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ar(r,e){let t=r[e],n=0;if(n+=t&k,t<g||(t=r[e+1],n+=(t&k)<<7,t<g)||(t=r[e+2],n+=(t&k)<<14,t<g)||(t=r[e+3],n+=(t&k)<<21,t<g)||(t=r[e+4],n+=(t&k)*rr,t<g)||(t=r[e+5],n+=(t&k)*nr,t<g)||(t=r[e+6],n+=(t&k)*sr,t<g)||(t=r[e+7],n+=(t&k)*ir,t<g))return n;throw new RangeError("Could not decode varint")}function li(r,e){let t=r.get(e),n=0;if(n+=t&k,t<g||(t=r.get(e+1),n+=(t&k)<<7,t<g)||(t=r.get(e+2),n+=(t&k)<<14,t<g)||(t=r.get(e+3),n+=(t&k)<<21,t<g)||(t=r.get(e+4),n+=(t&k)*rr,t<g)||(t=r.get(e+5),n+=(t&k)*nr,t<g)||(t=r.get(e+6),n+=(t&k)*sr,t<g)||(t=r.get(e+7),n+=(t&k)*ir,t<g))return n;throw new RangeError("Could not decode varint")}function Je(r,e,t=0){return e==null&&(e=S(E(r))),e instanceof Uint8Array?or(r,e,t):ci(r,e,t)}function je(r,e=0){return r instanceof Uint8Array?ar(r,e):li(r,e)}var cr={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},ln={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},hn=new globalThis.TextEncoder;function hi(r,e){let t=cr[e],n=ln[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function ui(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=cr[e],i=ln[e],s=r;for(;s.length>0;){let o=hn.encodeInto(s,t);s=s.slice(o.read);for(let a=0;a<o.written;a++)i^=BigInt(t[a]),i=BigInt.asUintN(e,i*n)}return i}function lr(r,{size:e=32,utf8Buffer:t}={}){if(!cr[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 ui(r,e,t);r=hn.encode(r)}return hi(r,e)}var Pe={hash:r=>Number(lr(r,{size:32})),hashV:(r,e)=>di(Pe.hash(r,e))};function di(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),C(e,"base16")}var hr=64,R=class{fp;h;seed;constructor(e,t,n,i=2){if(i>hr)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),o=_(i);for(let a=0;a<o.length;a++)o[a]=s[a];o.length===0&&(o[0]=7),this.fp=o,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?V(this.fp,e.fp):!1}};function ee(r,e){return Math.floor(Math.random()*(e-r))+r}var te=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof R))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof R))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 R))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 R))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var fi=500,Ne=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??Pe,this.seed=e.seed??ee(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=C(e));let t=new R(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new te(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new te(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let s=[n,i],o=s[ee(0,s.length-1)];this.buckets[o]==null&&(this.buckets[o]=new te(this.bucketSize));for(let a=0;a<fi;a++){let c=this.buckets[o].swap(t);if(c!=null&&(o=(o^c.hash())%this.filterSize,this.buckets[o]==null&&(this.buckets[o]=new te(this.bucketSize)),this.buckets[o].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=C(e));let t=new R(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=C(e));let t=new R(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let s=(n^t.hash())%this.filterSize,o=this.buckets[s]?.remove(t)??!1;return o&&this.count--,o}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},pi={1:.5,2:.84,4:.95,8:.98};function mi(r=.001){return r>.002?2:r>1e-5?4:8}function un(r,e=.001){let t=mi(e),n=pi[t],i=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),hr);return{filterSize:i,bucketSize:t,fingerprintSize:s}}var et=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??Pe,this.seed=e.seed??ee(0,Math.pow(2,10)),this.filterSeries=[new Ne({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=C(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Ne({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=C(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=C(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function tt(r,e=.001,t){return new et({...un(r,e),...t??{}})}function gi(r){return r.buffer instanceof ArrayBuffer}function dn(r){return gi(r)?r:r.slice()}function z(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var rt=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}},ve=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new rt(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 rt(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 ur=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function nt(r={}){return bi(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 bi(r,e){e=e??{};let t=e.onEnd,n=new ve,i,s,o,a=z(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((m,x)=>{s=A=>{s=null,n.push(A);try{m(r(n))}catch(v){x(v)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=z()})}},l=m=>s!=null?s(m):(n.push(m),i),u=m=>(n=new ve,s!=null?s({error:m}):(n.push({error:m}),i)),d=m=>{if(o)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},h=m=>o?i:(o=!0,m!=null?u(m):l({done:!0})),f=()=>(n=new ve,h(),{done:!0}),p=m=>(h(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:f,throw:p,push:d,end:h,get readableLength(){return n.size},onEmpty:async m=>{let x=m?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let A,v;x!=null&&(A=new Promise((I,M)=>{v=()=>{M(new ur)},x.addEventListener("abort",v)}));try{await Promise.race([a.promise,A])}finally{v!=null&&x!=null&&x?.removeEventListener("abort",v)}}},t==null)return i;let b=i;return i={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(m){return b.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(m){return b.end(m),t!=null&&(t(m),t=void 0),i},get readableLength(){return b.readableLength},onEmpty:m=>b.onEmpty(m)},i}var dr=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},fn=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function fr(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout},signal:o}=e,a,c,u=new Promise((d,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(o?.aborted){h(fn(o));return}if(o&&(c=()=>{h(fn(o))},o.addEventListener("abort",c,{once:!0})),r.then(d,h),t===Number.POSITIVE_INFINITY)return;let f=new dr;a=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){h(p)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?d():i instanceof Error?h(i):(f.message=i??`Promise timed out after ${t} milliseconds`,h(f))},t)}).finally(()=>{u.clear(),c&&o&&o.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var wi=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 yi(r,e,t){let n,i=new Promise((s,o)=>{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}=wi(r),d=async(...f)=>{let p=t.multiArgs?f:f[0];if(t.filter)try{if(!await t.filter(p))return}catch(b){n(),o(b);return}c.push(p),t.count===c.length&&(n(),s(c))},h=(...f)=>{n(),o(t.rejectionMultiArgs?f:f[0])};n=()=>{for(let f of a)u(f,d);for(let f of t.rejectionEvents)a.includes(f)||u(f,h)};for(let f of a)l(f,d);for(let f of t.rejectionEvents)a.includes(f)||l(f,h);t.signal&&t.signal.addEventListener("abort",()=>{h(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(i.cancel=n,typeof t.timeout=="number"){let s=fr(i,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return i}function st(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=yi(r,e,t),i=n.then(s=>s[0]);return i.cancel=n.cancel,i}function pr(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var it=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function xi(r){return r.reason}async function ot(r,e,t){if(e==null)return r;let n=t?.translateError??xi;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((s,o)=>{i=()=>{o(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var at=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=z(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new F)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ei(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ct=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Ei(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new F),this.cleanup())}async join(e){let t=new at(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await ot(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var _e=class extends W{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=pr(this.emitEmpty.bind(this),1),this.emitIdle=pr(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 it;let n=new ct(e,t);this.enqueue(n),this.safeDispatchEvent("add");let i=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});return this.tryToStartAnother(),i}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new F)}),this.clear()}async onEmpty(e){this.size!==0&&await st(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await st(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await st(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=nt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},o=()=>{n()},a=()=>{n(new F("Queue aborted"))};this.addEventListener("completed",i),this.addEventListener("failure",s),this.addEventListener("idle",o),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",i),this.removeEventListener("failure",s),this.removeEventListener("idle",o),e?.signal?.removeEventListener("abort",a),n()}}};var lt=class extends _e{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var mr=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 pn(r){let{name:e,metrics:t}=r,n;return t!=null?n=new mr({name:e,metrics:t}):n=new Map,n}function vi(r){return r[Symbol.asyncIterator]!=null}function _i(r){if(vi(r))return(async()=>{for await(let e of r);})();for(let e of r);}var gr=_i;var gn=Symbol.for("@achingbrain/uint8arraylist");function mn(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function ht(r){return!!r?.[gn]}var Se=class r{bufs;length;[gn]=!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(ht(n)){t+=n.byteLength;for(let i of n.bufs)this.bufs.push(i)}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(ht(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=mn(this.bufs,e);return t.buf[t.index]}set(e,t){let n=mn(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(ht(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:i}=this._subList(e,t);return Ee(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:Ee(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),s=new r;return s.length=i,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=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(o);break}let d=e-a;n.push(o.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(u){if(t===c){n.push(o);break}n.push(o.subarray(0,t-a));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ht(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 i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let d=0;d<s;d++)o[d]=-1;for(let d=0;d<i;d++)o[n[d]]=d;let a=o,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let h=l;h>=0;h--){let f=this.get(d+h);if(n[h]!==f){u=Math.max(1,h-a[f]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=S(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 i=_(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,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 i=_(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,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 i=_(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,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=S(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 i=_(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,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 i=_(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,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 i=_(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,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 i=_(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,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 i=_(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,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(!V(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((i,s)=>i+s.byteLength,0)),n.length=t,n}};var ut=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ke=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},dt=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Me=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ft(r){return r[Symbol.asyncIterator]!=null}function bn(r,e){if(r.byteLength>e)throw new ke("Message length too long")}var mt=r=>{let e=E(r),t=S(e);return Je(r,t),mt.bytes=e,t};mt.bytes=0;function gt(r,e){e=e??{};let t=e.lengthEncoder??mt,n=e?.maxDataLength??4194304;function*i(s){bn(s,n);let o=t(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return ft(r)?(async function*(){for await(let s of r)yield*i(s)})():(function*(){for(let s of r)yield*i(s)})()}gt.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??mt,n=e?.maxDataLength??4194304;return bn(r,n),new Se(t(r.byteLength),r)};var re;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(re||(re={}));var br=r=>{let e=je(r);return br.bytes=E(e),e};br.bytes=0;function Ce(r,e){let t=new Se,n=re.LENGTH,i=-1,s=e?.lengthDecoder??br,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===re.LENGTH)try{if(i=s(t),i<0)throw new ut("Invalid message length");if(i>a)throw new ke("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(i),n=re.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>o)throw new dt("Message length length too long");break}throw l}if(n===re.DATA){if(t.byteLength<i)break;let l=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(l),yield l,n=re.LENGTH}}}return ft(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Me("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Me("Unexpected end of input")})()}Ce.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Ce(n,{...e??{},onLength:s=>{t=s}})};function Li(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var wn=Li;function Ai(r){return r[Symbol.asyncIterator]!=null}function Ti(r,e){let t=0;if(Ai(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=wn(r),{value:i,done:s}=n.next();if(s===!0)return(function*(){})();let o=e(i,t++);if(typeof o.then=="function")return(async function*(){yield await o;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield o;for(let c of n)yield a(c,t++)})()}var yn=Ti;function Ii(r){return r[Symbol.asyncIterator]!=null}function Di(r,e){return Ii(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 xn=Di;var bt=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function ne(r,e,t,n){let i=new bt(n?.errorMessage);n?.errorCode!=null&&(i.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(i):new Promise((o,a)=>{function c(){yr(t,"abort",d),yr(r,e,l),yr(r,s,u)}let l=h=>{try{if(n?.filter?.(h)===!1)return}catch(f){c(),a(f);return}c(),o(h)},u=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.`))},d=()=>{c(),a(i)};wr(t,"abort",d),wr(r,e,l),wr(r,s,u)})}function wr(r,e,t){r!=null&&(En(r)?r.addEventListener(e,t):r.addListener(e,t))}function yr(r,e,t){r!=null&&(En(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function En(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Be="/ipfs/bitswap/1.2.0";var xr=new Float32Array([-0]),Y=new Uint8Array(xr.buffer);function vn(r,e,t){xr[0]=r,e[t]=Y[0],e[t+1]=Y[1],e[t+2]=Y[2],e[t+3]=Y[3]}function _n(r,e){return Y[0]=r[e],Y[1]=r[e+1],Y[2]=r[e+2],Y[3]=r[e+3],xr[0]}var Er=new Float64Array([-0]),L=new Uint8Array(Er.buffer);function Sn(r,e,t){Er[0]=r,e[t]=L[0],e[t+1]=L[1],e[t+2]=L[2],e[t+3]=L[3],e[t+4]=L[4],e[t+5]=L[5],e[t+6]=L[6],e[t+7]=L[7]}function kn(r,e){return L[0]=r[e],L[1]=r[e+1],L[2]=r[e+2],L[3]=r[e+3],L[4]=r[e+4],L[5]=r[e+5],L[6]=r[e+6],L[7]=r[e+7],Er[0]}var Pi=BigInt(Number.MAX_SAFE_INTEGER),Ni=BigInt(Number.MIN_SAFE_INTEGER),P=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 se;if(e<Pi&&e>Ni)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>Ln&&(i=0n,++n>Ln&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(e){if(e===0)return se;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)}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):se}},se=new P(0,0);se.toBigInt=function(){return 0n};se.zzEncode=se.zzDecode=function(){return this};se.length=function(){return 1};var Ln=4294967296n;function An(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 Tn(r,e,t){if(t-e<1)return"";let i,s=[],o=0,a;for(;e<t;)a=r[e++],a<128?s[o++]=a:a>191&&a<224?s[o++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[o++]=55296+(a>>10),s[o++]=56320+(a&1023)):s[o++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,o>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,s)),o=0);return i!=null?(o>0&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))}function vr(r,e,t){let n=t,i,s;for(let o=0;o<r.length;++o)i=r.charCodeAt(o),i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&((s=r.charCodeAt(o+1))&64512)===56320?(i=65536+((i&1023)<<10)+(s&1023),++o,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}function O(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function wt(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var _r=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=dn(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,O(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 O(this,4);return wt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw O(this,4);return wt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw O(this,4);let e=_n(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw O(this,4);let e=kn(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 O(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Tn(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw O(this,e);this.pos+=e}else do if(this.pos>=this.len)throw O(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 P(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 O(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 O(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 O(this,8);let e=wt(this.buf,this.pos+=4),t=wt(this.buf,this.pos+=4);return new P(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=ar(this.buf,this.pos);return this.pos+=E(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 Fe(r){return new _r(r instanceof Uint8Array?r:r.subarray())}function ie(r,e,t){let n=Fe(r);return e.decode(n,void 0,t)}function Sr(r){let e=r??8192,t=e>>>1,n,i=e;return function(o){if(o<1||o>t)return S(o);i+o>e&&(n=S(e),i=0);let a=n.subarray(i,i+=o);return(i&7)!==0&&(i=(i|7)+1),a}}var oe=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function kr(){}var Ar=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Mi=Sr();function Ci(r){return globalThis.Buffer!=null?S(r):Mi(r)}var Re=class{len;head;tail;states;constructor(){this.len=0,this.head=new oe(kr,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new oe(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Tr((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(yt,10,P.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=P.fromBigInt(e);return this._push(yt,t.length(),t)}uint64Number(e){return this._push(or,E(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=P.fromBigInt(e).zzEncode();return this._push(yt,t.length(),t)}sint64Number(e){let t=P.fromNumber(e).zzEncode();return this._push(yt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Lr,1,e?1:0)}fixed32(e){return this._push(Ue,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=P.fromBigInt(e);return this._push(Ue,4,t.lo)._push(Ue,4,t.hi)}fixed64Number(e){let t=P.fromNumber(e);return this._push(Ue,4,t.lo)._push(Ue,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(vn,4,e)}double(e){return this._push(Sn,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Lr,1,0):this.uint32(t)._push(Fi,t,e)}string(e){let t=An(e);return t!==0?this.uint32(t)._push(vr,t,e):this._push(Lr,1,0)}fork(){return this.states=new Ar(this),this.head=this.tail=new oe(kr,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 oe(kr,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=Ci(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Lr(r,e,t){e[t]=r&255}function Bi(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Tr=class extends oe{next;constructor(e,t){super(Bi,e,t),this.next=void 0}};function yt(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 Ue(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 Fi(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Re.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Ui,e,r),this},Re.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Ri,e,r),this});function Ui(r,e,t){e.set(r,t)}function Ri(r,e,t){r.length<40?vr(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(C(r),t)}function Ir(){return new Re}function ae(r,e){let t=Ir();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ce(r,e,t){let n=Fe(r);yield*e.stream(n,void 0,"$",t)}var xt={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Et(r,e,t,n,i){return{name:r,type:e,encode:t,decode:n,stream:i}}function vt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,a){let c=e(o);a.int32(c)},n=function(o){let a=o.int32();return e(a)},i=function*(o){let a=o.int32();yield e(a)};return Et("enum",xt.VARINT,t,n,i)}function le(r,e,t){return Et("message",xt.LENGTH_DELIMITED,r,e,t)}var X=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var w;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(w||(w={}));var Dr;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Dr||(Dr={}));(function(r){r.codec=()=>vt(Dr)})(w||(w={}));var he;(function(r){let e;r.codec=()=>(e==null&&(e=le((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.cid!=null&&s.cid.byteLength>0&&(o.uint32(10),o.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(o.uint32(16),o.int32(s.priority)),s.cancel!=null&&(o.uint32(24),o.bool(s.cancel)),s.wantType!=null&&(o.uint32(32),w.codec().encode(s.wantType,o)),s.sendDontHave!=null&&(o.uint32(40),o.bool(s.sendDontHave)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={cid:_(0),priority:0},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=w.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,o,a,c={}){let l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:w.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return ae(s,r.codec())}r.encode=t;function n(s,o){return ie(s,r.codec(),o)}r.decode=n;function i(s,o){return ce(s,r.codec(),o)}r.stream=i})(he||(he={}));var ze;(function(r){let e;r.codec=()=>(e==null&&(e=le((s,o,a={})=>{if(a.lengthDelimited!==!1&&o.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)o.uint32(10),he.codec().encode(c,o);s.full!=null&&(o.uint32(16),o.bool(s.full)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={entries:[]},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new X('Decode error - repeated field "entries" had too many elements');c.entries.push(he.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,o,a,c={}){let l={entries:0},u=o==null?s.len:s.pos+o;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new X('Streaming decode error - repeated field "entries" had too many elements');for(let h of he.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...h,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return ae(s,r.codec())}r.encode=t;function n(s,o){return ie(s,r.codec(),o)}r.decode=n;function i(s,o){return ce(s,r.codec(),o)}r.stream=i})(ze||(ze={}));var ue;(function(r){let e;r.codec=()=>(e==null&&(e=le((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(o.uint32(10),o.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(o.uint32(18),o.bytes(s.data)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={prefix:_(0),data:_(0)},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,o,a,c={}){let l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return ae(s,r.codec())}r.encode=t;function n(s,o){return ie(s,r.codec(),o)}r.decode=n;function i(s,o){return ce(s,r.codec(),o)}r.stream=i})(ue||(ue={}));var N;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(N||(N={}));var _t;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(_t||(_t={}));(function(r){r.codec=()=>vt(_t)})(N||(N={}));var de;(function(r){let e;r.codec=()=>(e==null&&(e=le((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.cid!=null&&s.cid.byteLength>0&&(o.uint32(10),o.bytes(s.cid)),s.type!=null&&_t[s.type]!==0&&(o.uint32(16),N.codec().encode(s.type,o)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={cid:_(0),type:N.HaveBlock},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=N.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,o,a,c={}){let l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:N.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return ae(s,r.codec())}r.encode=t;function n(s,o){return ie(s,r.codec(),o)}r.decode=n;function i(s,o){return ce(s,r.codec(),o)}r.stream=i})(de||(de={}));var fe;(function(r){let e;r.codec=()=>(e==null&&(e=le((s,o,a={})=>{if(a.lengthDelimited!==!1&&o.fork(),s.wantlist!=null&&(o.uint32(10),ze.codec().encode(s.wantlist,o)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)o.uint32(26),ue.codec().encode(c,o);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)o.uint32(34),de.codec().encode(c,o);s.pendingBytes!=null&&s.pendingBytes!==0&&(o.uint32(40),o.int32(s.pendingBytes)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=ze.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new X('Decode error - repeated field "blocks" had too many elements');c.blocks.push(ue.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new X('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(de.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,o,a,c={}){let l={blocks:0,blockPresences:0},u=o==null?s.len:s.pos+o;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield*ze.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new X('Streaming decode error - repeated field "blocks" had too many elements');for(let h of ue.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...h,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new X('Streaming decode error - repeated field "blockPresences" had too many elements');for(let h of de.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...h,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return ae(s,r.codec())}r.encode=t;function n(s,o){return ie(s,r.codec(),o)}r.decode=n;function i(s,o){return ce(s,r.codec(),o)}r.stream=i})(fe||(fe={}));function Dn(r,e){for(let[t,n]of e.wantlist.entries()){let i=r.wantlist.get(t);i!=null&&(i.priority>n.priority&&(n.priority=i.priority),n.cancel=n.cancel??i.cancel,n.wantType=n.wantType??i.wantType,n.sendDontHave=n.sendDontHave??i.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 St=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var zi=4193648,Oi=zi+16;function*Pn(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],i=[...r.blocks.values()],s=0,o=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=fe.encode(l).byteLength,{added:d,hasMore:h,newSize:f}=Pr(i,l.blocks,a,e,u,Wi);a+=d,u=f;let p=h;({added:d,hasMore:h,newSize:f}=Pr(n,l.blockPresences,o,e,u,Hi)),o+=d,u=f;let b=h;if({added:d,hasMore:h,newSize:f}=Pr(t,l.wantlist.entries,s,e,u,qi),s+=d,u=f,c=!p&&!b&&!h,c||(l.wantlist.full=!1),yield fe.encode(l),c)break}}function Pr(r,e,t,n,i,s){let o=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=s(l);if(u>Oi)throw new St("Cannot send block as after encoding it is over the max message size");let d=i+u;if(d>n){a=!0;break}e.push(l),o++,i=d}return{hasMore:a,added:o,newSize:i}}function Wi(r){return Nr(3,ue.encode(r))}function Hi(r){return Nr(4,de.encode(r))}function qi(r){return Nr(1,he.encode(r))}function Nr(r,e){let t=E(r),n=E(e.byteLength);return t+n+e.byteLength}var kt=class extends W{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Be],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new lt({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 Xe(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},i=AbortSignal.timeout(this.messageReceiveTimeout);i.addEventListener("abort",n),await e.close({signal:i});let s=nt();e.addEventListener("message",o=>{s.push(o.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",o=>{o.error!=null&&s.end(o.error)});for await(let o of Ce(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=fe.decode(o);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),i.removeEventListener("abort",n),i=AbortSignal.timeout(this.messageReceiveTimeout),i.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 T("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 T("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(i=>{this.log.error("could not connect to supplied provider - %e",i)}))),await gr(yn(xn(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 i=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(i!=null){i.options.message=Dn(i.options.message,t),await i.join(n);return}await this.sendQueue.add(async s=>{let o=s.message;if(o==null)throw new Ve("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new T("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Be,s);await a.closeRead(s);try{for(let c of Pn(o,this.maxOutgoingMessageSize))a.send(gt.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new T("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(o.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Qe("Network isn't running");t?.onProgress?.(new T("bitswap:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),ne(this.libp2p,"peer:identify",t?.signal,{filter:i=>{if(!i.detail.peerId.equals(e))return!1;if(i.detail.protocols.includes(Be))return!0;throw new Ge(`${e} did not support ${Be}`)}})]);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 Lt(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}var Oe=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 Lt(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 Lt(this.map.values(),e=>e.key)}values(){return Lt(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Mr=class extends Oe{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 We(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Mr({name:e,metrics:t}):n=new Oe,n}function ji(r){return r[Symbol.asyncIterator]!=null}function eo(r){if(ji(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=Ee([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ee(e,t)}var Mn=eo;var Q=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=j.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=j.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=j.encode(e.multihash.bytes);this.blocks.set(n,t)}};function to(r){let e=new Uint8Array(r.reduce((n,i)=>n+E(i),0)),t=0;for(let n of r)e=Je(n,e,t),t+=E(n);return e}var Cn=to;function Cr(r){return Cn([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var At=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,i)=>{n.status==="want"&&this.wants.delete(i)});for(let n of e.entries){let i=$.decode(n.cid),s=G(i.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,i),this.wants.delete(s);else{n.wantType===w.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,i):this.log("peer %p wanted block for %c",this.peerId,i);let o=this.wants.get(s);if(o!=null){let a=o.status==="sent"||o.status==="sending",c=o.wantType===w.WantHave&&(n.wantType==null||n.wantType===w.WantBlock);a&&c&&(o.status="want"),o.priority=n.priority,o.wantType=n.wantType??w.WantBlock,o.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:i,priority:n.priority,wantType:n.wantType??w.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,i])=>i.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,i)=>n[1].created<i[1].created?-1:i[1].created<n[1].created?1:0).sort((n,i)=>n[1].haveBlock===!1?-1:i[1].haveBlock===!1?1:0).sort((n,i)=>n[1].priority<i[1].priority?-1:i[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=G(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new Q,n=new Set;this.removeExpiredWants();let i=[...this.wants.entries()].filter(([s,o])=>o.status==="want");i.forEach(([s,o])=>{o.status="sending"});for(let[s,o]of i)try{let a=await Mn(this.blockstore.get(o.cid,e));if(o.status!=="sending")continue;o.wantType===w.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),t.addBlock(o.cid,{data:a,prefix:Cr(o.cid)})):(this.log("sending have for %c",o.cid),t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:N.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),t.addBlock(o.cid,{data:a,prefix:Cr(o.cid)})),o.status="sent",o.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(o.status="want",o.haveBlock=!1,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:N.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,o)=>s+o.data.byteLength,0)))}};var Tt=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=We({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(i=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,i)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new At({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((i,s)=>i+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let i of this.ledgerMap.values())i.hasWant(e)&&n.push(i);await Promise.all(n.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var so=Vn(Fn(),1);var Le;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Le||(Le={}));var It=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var He=class extends W{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=tt(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=j.encode(e.multihash.bytes),i=this.requests.get(n);if(i!=null)return this.log("join existing request for %c",e),i.observers++,i.promise;let s=z(),o={promise:s.promise,observers:1,queryFilter:tt(this.cidPeerFilterSize)};this.requests.set(n,o);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,l=new _e({concurrency:this.maxProviders});l.addEventListener("failure",h=>{this.log.error("error querying provider %s, evicting from session - %e",h.detail.job.options.provider,h.detail.error),this.evict(h.detail.job.options.provider)}),l.addEventListener("success",h=>{c=!0,s.resolve(h.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let h=0;h<this.minProviders&&this.providers.length!==0;h++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(h=>{this.log.error("could not find new providers for %c - %e",e,h),s.reject(h)})});let u=h=>{let f=this.toFilterKey(h.detail);o.queryFilter.has(f)||(o.queryFilter.add(f),this.emitFoundProviderProgressEvent(e,h.detail,t),l.add(async()=>this.queryProvider(e,h.detail,t),{provider:h.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,p)}))};if(this.addEventListener("provider",u),a)try{await ot(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(h){throw a&&this.log("failed to find initial session peers for %c - %e",e,h),this.requests.delete(n),o.observers>1&&s.reject(h),h}Promise.all([...this.providers].filter(h=>{let f=this.toFilterKey(h),p=o.queryFilter.has(f);return p||o.queryFilter.add(this.toFilterKey(h)),!p}).map(async h=>l.add(async()=>this.queryProvider(e,h,t),{provider:h}))).catch(h=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,h)});let d=()=>{s.reject(new F(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",d);try{return await s.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",d),l.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let i=z(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let o=this,a=async function*(){for(;o.initialProviders.length>0;){let l=o.initialProviders.pop();if(l==null)continue;let u=await o.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*o.findNewProviders(e,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new It(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(o=>{this.log.error("error searching routing for potential session peers for %c - %e",e,o),i.reject(o)}),i.promise}};var Br=class extends He{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let i=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,i.has?"has":"does not have",e),i.has){if(i.block!=null)return i.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.toMultihash().bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Ur(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let i=await this.libp2p.dial(e,n);return{peerId:i.remotePeer,routing:t,toString:()=>`Bitswap(${i.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new T("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function Un(r,e){return new Br(r,e)}var Dt=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 co(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=je(r);e.push(t),r=r.slice(E(t))}return e}var Rn=co;var Pt=class extends W{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=We({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=pn({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(i=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,i)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(i=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,i)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=G(e.multihash.bytes,"base64"),i=this.wants.get(n);i==null&&(i={cid:e,priority:t.priority??1,wantType:t.wantType??w.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,i)),t.onProgress!=null&&i.onProgress.push({onProgress:t.onProgress,signal:t.signal}),i.wantType===w.WantHave&&t.wantType===w.WantBlock&&(i.wantType=w.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===w.WantBlock?(await ne(this,"block",t?.signal,{filter:a=>V(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await ne(this,"presence",t?.signal,{filter:o=>V(e.multihash.digest,o.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),i.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=z(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,i=new Q;for(let[s,o]of this.wants.entries())t.has(s)||o.cancel||(n.add(s),i.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:o.priority,wantType:o.wantType,cancel:o.cancel,sendDontHave:o.sendDontHave}));if(i.wantlist.size!==0)try{await this.network.sendMessage(e,i,{onProgress:s=>{this.wants.forEach(({onProgress:o})=>{o.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=G(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let i=new Q;return i.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:w.WantHave,priority:1}),await this.network.sendMessage(t,i,n),(await ne(this,"presence",n.signal,{filter:o=>t.equals(o.detail.sender)&&V(e.multihash.digest,o.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:w.WantBlock})}async wantSessionBlock(e,t,n={}){let i=new Q;return i.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:w.WantBlock,priority:1}),await this.network.sendMessage(t,i,n),(await ne(this,"presence",n.signal,{filter:o=>t.equals(o.detail.sender)&&V(e.multihash.digest,o.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=G(e.multihash.bytes,"base64"),i=this.wants.get(n);i!=null&&(i.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let i of t.blocks){if(i.prefix==null||i.data==null)continue;let s=Rn(i.prefix),o=s[0],a=s[1],c=s[2],l=s[3],u=c===Ze.code?Ze:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let d=u.digest(i.data,{truncate:l});d.then!=null&&(d=await d);let h=$.create(o===0?0:1,a,d);this.log("received block from %p for %c",e.remotePeer,h),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:h,block:i.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:h,has:!0,block:i.data}});let f=G(h.multihash.bytes,"base64"),p=this.wants.get(f);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:i,type:s}of t.blockPresences){let o=$.decode(i);this.log("received %s from %p for %c",s,e.remotePeer,o),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:o,has:s===N.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Q(!0);for(let[i,s]of this.wants.entries())s.cancel||(t.add(i),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:w.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:i=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:o})=>{o(i)})})}}),this.peers.set(e,t)}catch(i){this.log.error("error sending full wantlist to new peer %p - %e",e,i)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Nt=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 Dt(e),this.network=new kt(e,t),this.peerWantLists=new Tt({...e,network:this.network},t),this.wantList=new Pt({...e,network:this.network},t)}createSession(e={}){return Un({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,i=Rr([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:i}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:i});return t.onProgress?.(new T("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),i.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 lo=(r,e={})=>new Nt(r,e);return Gn(ho);})();
|
|
3
3
|
return HeliaBitswap}));
|
|
4
4
|
//# sourceMappingURL=index.min.js.map
|