@helia/bitswap 3.2.3-070b7528 → 3.2.3-f6cc7640
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/dist/src/network.d.ts.map +1 -1
- package/dist/src/network.js +2 -0
- package/dist/src/network.js.map +1 -1
- package/dist/src/pb/message.d.ts +5 -5
- package/dist/src/pb/message.d.ts.map +1 -1
- package/package.json +13 -13
- package/src/network.ts +2 -0
- package/src/pb/message.ts +5 -5
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 Fn=Object.create;var qe=Object.defineProperty;var Un=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,On=Object.prototype.hasOwnProperty;var Wn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),D=(r,e)=>{for(var t in e)qe(r,t,{get:e[t],enumerable:!0})},Br=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Rn(e))!On.call(r,i)&&i!==t&&qe(r,i,{get:()=>e[i],enumerable:!(n=Un(e,i))||n.enumerable});return r};var Hn=(r,e,t)=>(t=r!=null?Fn(zn(r)):{},Br(e||!r||!r.__esModule?qe(t,"default",{value:r,enumerable:!0}):t,r)),qn=r=>Br(qe({},"__esModule",{value:!0}),r);var Mn=Wn((Uh,Nn)=>{Nn.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 so={};D(so,{createBitswap:()=>no});var F=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var $e=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Ve=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}};var Ge=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Xe=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var $n=Symbol.for("@libp2p/peer-id");function Fr(r){return!!r?.[$n]}function Vn(r){return typeof r?.handleEvent=="function"}function Gn(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=Gn(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))}Vn(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 Ur(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 Ft={};D(Ft,{base58btc:()=>U,base58flickr:()=>jn});var uo=new Uint8Array(0);function Rr(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 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 zr(r){return new TextEncoder().encode(r)}function Or(r){return new TextDecoder().decode(r)}function Xn(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 He=c.repeat(b);H<v;++H)He+=r.charAt(I[H]);return He}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)),He=m;B!==A;)H[He++]=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 Qn=Xn,Kn=Qn,Hr=Kn;var Nt=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")}},Mt=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 qr(this,e)}},Ct=class{decoders;constructor(e){this.decoders=e}or(e){return qr(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 qr(r,e){return new Ct({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Bt=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 Nt(e,t,n),this.decoder=new Mt(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function fe({name:r,prefix:e,encode:t,decode:n}){return new Bt(r,e,t,n)}function Z({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=Hr(t,r);return fe({prefix:e,name:r,encode:n,decode:s=>q(i(s))})}function Zn(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 Yn(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 Jn(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=Jn(n);return fe({prefix:e,name:r,encode(s){return Yn(s,n,t)},decode(s){return Zn(s,i,t,r)}})}var U=Z({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jn=Z({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ut={};D(Ut,{base32:()=>pe,base32hex:()=>ns,base32hexpad:()=>is,base32hexpadupper:()=>os,base32hexupper:()=>ss,base32pad:()=>ts,base32padupper:()=>rs,base32upper:()=>es,base32z:()=>as});var pe=y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),es=y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ts=y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rs=y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ns=y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ss=y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),is=y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),os=y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),as=y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Rt={};D(Rt,{base36:()=>Le,base36upper:()=>cs});var Le=Z({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cs=Z({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ls=Gr,$r=128,hs=127,us=~hs,ds=Math.pow(2,31);function Gr(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ds;)e[t++]=r&255|$r,r/=128;for(;r&us;)e[t++]=r&255|$r,r>>>=7;return e[t]=r|0,Gr.bytes=t-n+1,e}var fs=zt,ps=128,Vr=127;function zt(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw zt.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&Vr)<<i:(o&Vr)*Math.pow(2,i),i+=7}while(o>=ps);return zt.bytes=s-n,t}var ms=Math.pow(2,7),gs=Math.pow(2,14),bs=Math.pow(2,21),ws=Math.pow(2,28),ys=Math.pow(2,35),xs=Math.pow(2,42),Es=Math.pow(2,49),vs=Math.pow(2,56),_s=Math.pow(2,63),Ss=function(r){return r<ms?1:r<gs?2:r<bs?3:r<ws?4:r<ys?5:r<xs?6:r<Es?7:r<vs?8:r<_s?9:10},ks={encode:ls,decode:fs,encodingLength:Ss},Ls=ks,Ae=Ls;function Te(r,e=0){return[Ae.decode(r,e),Ae.decode.bytes]}function me(r,e,t=0){return Ae.encode(r,e,t),e}function ge(r){return Ae.encodingLength(r)}function we(r,e){let t=e.byteLength,n=ge(r),i=n+ge(t),s=new Uint8Array(i+t);return me(r,s,0),me(t,s,n),s.set(e,i),new be(r,t,e,s)}function Ot(r){let e=q(r),[t,n]=Te(e),[i,s]=Te(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new be(t,i,o,e)}function Xr(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Rr(r.bytes,t.bytes)}}var be=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};function Qr(r,e){let{bytes:t,version:n}=r;return n===0?Ts(t,Wt(r),e??U.encoder):Is(t,Wt(r),e??pe.encoder)}var Kr=new WeakMap;function Wt(r){let e=Kr.get(r);if(e==null){let t=new Map;return Kr.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=i,this["/"]=i}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!==Ie)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ds)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=we(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&&Xr(e.multihash,n.multihash)}toString(e){return Qr(this,e)}toJSON(){return{"/":Qr(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??Zr(n,i,s.bytes))}else if(t[Ps]===!0){let{version:n,multihash:i,code:s}=t,o=Ot(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!==Ie)throw new Error(`Version 0 CID must use dag-pb (code: ${Ie}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=Zr(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ie,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 be(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]=Te(e.subarray(t));return t+=h,d},i=n(),s=Ie;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]=As(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 Wt(s).set(n,e),s}};function As(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 pe.prefix:{let t=e??pe;return[pe.prefix,t.decode(r)]}case Le.prefix:{let t=e??Le;return[Le.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 Ts(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 Is(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 Ie=112,Ds=18;function Zr(r,e,t){let n=ge(r),i=n+ge(e),s=new Uint8Array(i+t.byteLength);return me(r,s,0),me(e,s,n),s.set(t,i),s}var Ps=Symbol.for("@ipld/js-cid/CID");var Ht={};D(Ht,{identity:()=>Cs});var Yr=0,Ns="identity",Jr=q;function Ms(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 we(Yr,Jr(r))}var Cs={code:Yr,name:Ns,encode:Jr,digest:Ms};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 xe(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 t}var en=Symbol.for("@achingbrain/uint8arraylist");function jr(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 Ke(r){return!!r?.[en]}var Ee=class r{bufs;length;[en]=!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(Ke(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(Ke(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=jr(this.bufs,e);return t.buf[t.index]}set(e,t){let n=jr(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(Ke(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 xe(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:xe(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(!Ke(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 qt={};D(qt,{base10:()=>Bs});var Bs=Z({prefix:"9",name:"base10",alphabet:"0123456789"});var $t={};D($t,{base16:()=>Fs,base16upper:()=>Us});var Fs=y({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Us=y({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Vt={};D(Vt,{base2:()=>Rs});var Rs=y({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Gt={};D(Gt,{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}"),zs=tn.reduce((r,e,t)=>(r[t]=e,r),[]),Os=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 Ws(r){return r.reduce((e,t)=>(e+=zs[t],e),"")}function Hs(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=Os[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var qs=fe({prefix:"\u{1F680}",name:"base256emoji",encode:Ws,decode:Hs});var Xt={};D(Xt,{base64:()=>J,base64pad:()=>$s,base64url:()=>Vs,base64urlpad:()=>Gs});var J=y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$s=y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Vs=y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Gs=y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qt={};D(Qt,{base8:()=>Xs});var Xs=y({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Kt={};D(Kt,{identity:()=>Qs});var Qs=fe({prefix:"\0",name:"identity",encode:r=>Or(r),decode:r=>zr(r)});var Ko=new TextEncoder,Zo=new TextDecoder;var Jt={};D(Jt,{sha256:()=>Ze,sha512:()=>Js});var Ys=20;function Yt({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new Zt(r,e,t,n,i)}var Zt=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??Ys,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 we(e,r)}function sn(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ze=Yt({name:"sha2-256",code:18,encode:sn("SHA-256")}),Js=Yt({name:"sha2-512",code:19,encode:sn("SHA-512")});var jt={...Kt,...Vt,...Qt,...qt,...$t,...Ut,...Rt,...Ft,...Xt,...Gt},ca={...Jt,...Ht};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))),er=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}),js={utf8:on,"utf-8":on,hex:jt.base16,latin1:er,ascii:er,binary:er,...jt},Ye=js;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 ei=Math.pow(2,7),ti=Math.pow(2,14),ri=Math.pow(2,21),tr=Math.pow(2,28),rr=Math.pow(2,35),nr=Math.pow(2,42),sr=Math.pow(2,49),g=128,k=127;function E(r){if(r<ei)return 1;if(r<ti)return 2;if(r<ri)return 3;if(r<tr)return 4;if(r<rr)return 5;if(r<nr)return 6;if(r<sr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ir(r,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 ni(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 or(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)*tr,t<g)||(t=r[e+5],n+=(t&k)*rr,t<g)||(t=r[e+6],n+=(t&k)*nr,t<g)||(t=r[e+7],n+=(t&k)*sr,t<g))return n;throw new RangeError("Could not decode varint")}function si(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)*tr,t<g)||(t=r.get(e+5),n+=(t&k)*rr,t<g)||(t=r.get(e+6),n+=(t&k)*nr,t<g)||(t=r.get(e+7),n+=(t&k)*sr,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?ir(r,e,t):ni(r,e,t)}function je(r,e=0){return r instanceof Uint8Array?or(r,e):si(r,e)}var ar=new Float32Array([-0]),Y=new Uint8Array(ar.buffer);function ln(r,e,t){ar[0]=r,e[t]=Y[0],e[t+1]=Y[1],e[t+2]=Y[2],e[t+3]=Y[3]}function hn(r,e){return Y[0]=r[e],Y[1]=r[e+1],Y[2]=r[e+2],Y[3]=r[e+3],ar[0]}var cr=new Float64Array([-0]),L=new Uint8Array(cr.buffer);function un(r,e,t){cr[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 dn(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],cr[0]}var ii=BigInt(Number.MAX_SAFE_INTEGER),oi=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 j;if(e<ii&&e>oi)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>fn&&(i=0n,++n>fn&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(e){if(e===0)return j;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):j}},j=new P(0,0);j.toBigInt=function(){return 0n};j.zzEncode=j.zzDecode=function(){return this};j.length=function(){return 1};var fn=4294967296n;function pn(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 mn(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 lr(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 R(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function et(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var hr=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,R(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 R(this,4);return et(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw R(this,4);return et(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw R(this,4);let e=hn(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw R(this,4);let e=dn(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 R(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return mn(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw R(this,e);this.pos+=e}else do if(this.pos>=this.len)throw R(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 R(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 R(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 R(this,8);let e=et(this.buf,this.pos+=4),t=et(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=or(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 De(r){return new hr(r instanceof Uint8Array?r:r.subarray())}function ee(r,e,t){let n=De(r);return e.decode(n,void 0,t)}function ur(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 te=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function dr(){}var pr=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ai=ur();function ci(r){return globalThis.Buffer!=null?S(r):ai(r)}var Ne=class{len;head;tail;states;constructor(){this.len=0,this.head=new te(dr,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new te(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new mr((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(tt,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(tt,t.length(),t)}uint64Number(e){return this._push(ir,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(tt,t.length(),t)}sint64Number(e){let t=P.fromNumber(e).zzEncode();return this._push(tt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fr,1,e?1:0)}fixed32(e){return this._push(Pe,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=P.fromBigInt(e);return this._push(Pe,4,t.lo)._push(Pe,4,t.hi)}fixed64Number(e){let t=P.fromNumber(e);return this._push(Pe,4,t.lo)._push(Pe,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(ln,4,e)}double(e){return this._push(un,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(fr,1,0):this.uint32(t)._push(hi,t,e)}string(e){let t=pn(e);return t!==0?this.uint32(t)._push(lr,t,e):this._push(fr,1,0)}fork(){return this.states=new pr(this),this.head=this.tail=new te(dr,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 te(dr,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 fr(r,e,t){e[t]=r&255}function li(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var mr=class extends te{next;constructor(e,t){super(li,e,t),this.next=void 0}};function tt(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 Pe(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 hi(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Ne.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(ui,e,r),this},Ne.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(di,e,r),this});function ui(r,e,t){e.set(r,t)}function di(r,e,t){r.length<40?lr(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(C(r),t)}function gr(){return new Ne}function re(r,e){let t=gr();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ne(r,e,t){let n=De(r);yield*e.stream(n,void 0,"$",t)}var rt={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function nt(r,e,t,n,i){return{name:r,type:e,encode:t,decode:n,stream:i}}function st(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 nt("enum",rt.VARINT,t,n,i)}function se(r,e,t){return nt("message",rt.LENGTH_DELIMITED,r,e,t)}var X=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var br={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},bn={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},wn=new globalThis.TextEncoder;function fi(r,e){let t=br[e],n=bn[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function pi(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=br[e],i=bn[e],s=r;for(;s.length>0;){let o=wn.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 wr(r,{size:e=32,utf8Buffer:t}={}){if(!br[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 pi(r,e,t);r=wn.encode(r)}return fi(r,e)}var Me={hash:r=>Number(wr(r,{size:32})),hashV:(r,e)=>mi(Me.hash(r,e))};function mi(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),C(e,"base16")}var yr=64,z=class{fp;h;seed;constructor(e,t,n,i=2){if(i>yr)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 ie(r,e){return Math.floor(Math.random()*(e-r))+r}var oe=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof z))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof z))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 z))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 z))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var gi=500,Ce=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??Me,this.seed=e.seed??ie(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=C(e));let t=new z(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 oe(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new oe(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let s=[n,i],o=s[ie(0,s.length-1)];this.buckets[o]==null&&(this.buckets[o]=new oe(this.bucketSize));for(let a=0;a<gi;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 oe(this.bucketSize)),this.buckets[o].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=C(e));let t=new z(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 z(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}},bi={1:.5,2:.84,4:.95,8:.98};function wi(r=.001){return r>.002?2:r>1e-5?4:8}function yn(r,e=.001){let t=wi(e),n=bi[t],i=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),yr);return{filterSize:i,bucketSize:t,fingerprintSize:s}}var it=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??Me,this.seed=e.seed??ie(0,Math.pow(2,10)),this.filterSeries=[new Ce({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 Ce({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 ot(r,e=.001,t){return new it({...yn(r,e),...t??{}})}function O(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var at=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 at(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 at(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 xr=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ct(r={}){return yi(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 yi(r,e){e=e??{};let t=e.onEnd,n=new ve,i,s,o,a=O(),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=O()})}},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 xr)},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 Er=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},xn=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function vr(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(xn(o));return}if(o&&(c=()=>{h(xn(o))},o.addEventListener("abort",c,{once:!0})),r.then(d,h),t===Number.POSITIVE_INFINITY)return;let f=new Er;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 xi=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 Ei(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}=xi(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=vr(i,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return i}function lt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Ei(r,e,t),i=n.then(s=>s[0]);return i.cancel=n.cancel,i}function _r(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 ht=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function vi(r){return r.reason}async function ut(r,e,t){if(e==null)return r;let n=t?.translateError??vi;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 dt=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=O(),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 _i(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ft=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=_i(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new F),this.cleanup())}async join(e){let t=new dt(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 ut(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{this.recipients.forEach(n=>{n.onProgress?.(t)})}}),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=_r(this.emitEmpty.bind(this),1),this.emitIdle=_r(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 ht;let n=new ft(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 lt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await lt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await lt(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=ct({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 pt=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Se=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},mt=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Be=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function gt(r){return r[Symbol.asyncIterator]!=null}function En(r,e){if(r.byteLength>e)throw new Se("Message length too long")}var wt=r=>{let e=E(r),t=S(e);return Je(r,t),wt.bytes=e,t};wt.bytes=0;function yt(r,e){e=e??{};let t=e.lengthEncoder??wt,n=e?.maxDataLength??4194304;function*i(s){En(s,n);let o=t(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return gt(r)?(async function*(){for await(let s of r)yield*i(s)})():(function*(){for(let s of r)yield*i(s)})()}yt.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??wt,n=e?.maxDataLength??4194304;return En(r,n),new Ee(t(r.byteLength),r)};var ae;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ae||(ae={}));var Sr=r=>{let e=je(r);return Sr.bytes=E(e),e};Sr.bytes=0;function Fe(r,e){let t=new Ee,n=ae.LENGTH,i=-1,s=e?.lengthDecoder??Sr,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===ae.LENGTH)try{if(i=s(t),i<0)throw new pt("Invalid message length");if(i>a)throw new Se("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(i),n=ae.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>o)throw new mt("Message length length too long");break}throw l}if(n===ae.DATA){if(t.byteLength<i)break;let l=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(l),yield l,n=ae.LENGTH}}}return gt(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Be("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Be("Unexpected end of input")})()}Fe.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 Fe(n,{...e??{},onLength:s=>{t=s}})};var xt=class extends _e{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var kr=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 vn(r){let{name:e,metrics:t}=r,n;return t!=null?n=new kr({name:e,metrics:t}):n=new Map,n}function Li(r){return r[Symbol.asyncIterator]!=null}function Ai(r){if(Li(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Lr=Ai;function Ti(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 _n=Ti;function Ii(r){return r[Symbol.asyncIterator]!=null}function Di(r,e){let t=0;if(Ii(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=_n(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 Sn=Di;function Pi(r){return r[Symbol.asyncIterator]!=null}function Ni(r,e){return Pi(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 kn=Ni;var Et=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function ce(r,e,t,n){let i=new Et(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(){Tr(t,"abort",d),Tr(r,e,l),Tr(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)};Ar(t,"abort",d),Ar(r,e,l),Ar(r,s,u)})}function Ar(r,e,t){r!=null&&(Ln(r)?r.addEventListener(e,t):r.addListener(e,t))}function Tr(r,e,t){r!=null&&(Ln(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Ln(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Ue="/ipfs/bitswap/1.2.0";var w;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(w||(w={}));var Ir;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Ir||(Ir={}));(function(r){r.codec=()=>st(Ir)})(w||(w={}));var le;(function(r){let e;r.codec=()=>(e==null&&(e=se((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 re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(le||(le={}));var Re;(function(r){let e;r.codec=()=>(e==null&&(e=se((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),le.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(le.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 le.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 re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(Re||(Re={}));var he;(function(r){let e;r.codec=()=>(e==null&&(e=se((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 re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(he||(he={}));var N;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(N||(N={}));var vt;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(vt||(vt={}));(function(r){r.codec=()=>st(vt)})(N||(N={}));var ue;(function(r){let e;r.codec=()=>(e==null&&(e=se((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&&vt[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 re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(ue||(ue={}));var de;(function(r){let e;r.codec=()=>(e==null&&(e=se((s,o,a={})=>{if(a.lengthDelimited!==!1&&o.fork(),s.wantlist!=null&&(o.uint32(10),Re.codec().encode(s.wantlist,o)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)o.uint32(26),he.codec().encode(c,o);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)o.uint32(34),ue.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=Re.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(he.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(ue.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*Re.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 he.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 ue.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 re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(de||(de={}));function An(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 _t=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Mi=4193648,Ci=Mi+16;function*Tn(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=de.encode(l).byteLength,{added:d,hasMore:h,newSize:f}=Dr(i,l.blocks,a,e,u,Bi);a+=d,u=f;let p=h;({added:d,hasMore:h,newSize:f}=Dr(n,l.blockPresences,o,e,u,Fi)),o+=d,u=f;let b=h;if({added:d,hasMore:h,newSize:f}=Dr(t,l.wantlist.entries,s,e,u,Ui),s+=d,u=f,c=!p&&!b&&!h,c||(l.wantlist.full=!1),yield de.encode(l),c)break}}function Dr(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>Ci)throw new _t("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 Bi(r){return Pr(3,he.encode(r))}function Fi(r){return Pr(4,ue.encode(r))}function Ui(r){return Pr(1,le.encode(r))}function Pr(r,e){let t=E(r),n=E(e.byteLength);return t+n+e.byteLength}var St=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??[Ue],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 xt({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 Ge(`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=ct();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 Fe(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=de.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 Lr(Sn(kn(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=An(i.options.message,t),await i.join(n);return}await this.sendQueue.add(async s=>{let o=s.message;if(o==null)throw new $e("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,Ue,s);await a.closeRead(s);try{for(let c of Tn(o,this.maxOutgoingMessageSize))a.send(yt.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 Xe("Network isn't running");t?.onProgress?.(new T("bitswap:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),ce(this.libp2p,"peer:identify",t?.signal,{filter:i=>{if(!i.detail.peerId.equals(e))return!1;if(i.detail.protocols.includes(Ue))return!0;throw new Ve(`${e} did not support ${Ue}`)}})]);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 kt(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 ze=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 kt(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 kt(this.map.values(),e=>e.key)}values(){return kt(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Nr=class extends ze{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 Oe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Nr({name:e,metrics:t}):n=new ze,n}function Xi(r){return r[Symbol.asyncIterator]!=null}function Qi(r){if(Xi(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=xe([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return xe(e,t)}var Dn=Qi;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 Ki(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 Pn=Ki;function Mr(r){return Pn([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Lt=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 Dn(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:Mr(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:Mr(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 At=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=Oe({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 Lt({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 Ji=Hn(Mn(),1);var ke;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ke||(ke={}));var Tt=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var We=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=ot(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=O(),o={promise:s.promise,observers:1,queryFilter:ot(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 ut(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=O(),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 Tt(`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 Cr=class extends We{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(Fr(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 Cn(r,e){return new Cr(r,e)}var It=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 ro(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 Bn=ro;var Dt=class extends W{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Oe({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=vn({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 ce(this,"block",t?.signal,{filter:a=>V(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await ce(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=O(),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 ce(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 ce(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=Bn(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 Pt=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 It(e),this.network=new St(e,t),this.peerWantLists=new At({...e,network:this.network},t),this.wantList=new Dt({...e,network:this.network},t)}createSession(e={}){return Cn({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,i=Ur([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 no=(r,e={})=>new Pt(r,e);return qn(so);})();
|
|
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);})();
|
|
3
3
|
return HeliaBitswap}));
|
|
4
4
|
//# sourceMappingURL=index.min.js.map
|