helia 1.0.1 → 1.0.2
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/package.json +2 -2
package/dist/index.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Helia = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Helia=(()=>{var Ju=Object.create;var gr=Object.defineProperty;var Zu=Object.getOwnPropertyDescriptor;var Yu=Object.getOwnPropertyNames;var el=Object.getPrototypeOf,tl=Object.prototype.hasOwnProperty;var S=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),V=(r,e)=>{for(var t in e)gr(r,t,{get:e[t],enumerable:!0})},Eo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Yu(e))!tl.call(r,i)&&i!==t&&gr(r,i,{get:()=>e[i],enumerable:!(n=Zu(e,i))||n.enumerable});return r};var U=(r,e,t)=>(t=r!=null?Ju(el(r)):{},Eo(e||!r||!r.__esModule?gr(t,"default",{value:r,enumerable:!0}):t,r)),rl=r=>Eo(gr({},"__esModule",{value:!0}),r);var Vo=S((vp,qo)=>{qo.exports=Ho;var Wo=128,Wl=127,Hl=~Wl,ql=Math.pow(2,31);function Ho(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ql;)e[t++]=r&255|Wo,r/=128;for(;r&Hl;)e[t++]=r&255|Wo,r>>>=7;return e[t]=r|0,Ho.bytes=t-n+1,e}});var Qo=S((xp,Go)=>{Go.exports=Gn;var Vl=128,jo=127;function Gn(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw Gn.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&jo)<<i:(s&jo)*Math.pow(2,i),i+=7}while(s>=Vl);return Gn.bytes=o-n,t}});var Xo=S((kp,Ko)=>{var jl=Math.pow(2,7),Gl=Math.pow(2,14),Ql=Math.pow(2,21),Kl=Math.pow(2,28),Xl=Math.pow(2,35),Jl=Math.pow(2,42),Zl=Math.pow(2,49),Yl=Math.pow(2,56),ef=Math.pow(2,63);Ko.exports=function(r){return r<jl?1:r<Gl?2:r<Ql?3:r<Kl?4:r<Xl?5:r<Jl?6:r<Zl?7:r<Yl?8:r<ef?9:10}});var Zo=S((Ep,Jo)=>{Jo.exports={encode:Vo(),decode:Qo(),encodingLength:Xo()}});var ts=S((Sp,es)=>{"use strict";var Yo=Zo();es.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Yo.decode(r);e.push(t),r=r.slice(Yo.decode.bytes)}return e}});var is=S((Tp,ns)=>{ns.exports=Qn;var rs=128,tf=127,rf=~tf,nf=Math.pow(2,31);function Qn(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Qn.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=nf;)e[t++]=r&255|rs,r/=128;for(;r&rf;)e[t++]=r&255|rs,r>>>=7;return e[t]=r|0,Qn.bytes=t-n+1,e}});var as=S((Ap,ss)=>{ss.exports=Kn;var of=128,os=127;function Kn(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a||i>49)throw Kn.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&os)<<i:(s&os)*Math.pow(2,i),i+=7}while(s>=of);return Kn.bytes=o-n,t}});var us=S((Bp,cs)=>{var sf=Math.pow(2,7),af=Math.pow(2,14),cf=Math.pow(2,21),uf=Math.pow(2,28),lf=Math.pow(2,35),ff=Math.pow(2,42),hf=Math.pow(2,49),df=Math.pow(2,56),pf=Math.pow(2,63);cs.exports=function(r){return r<sf?1:r<af?2:r<cf?3:r<uf?4:r<lf?5:r<ff?6:r<hf?7:r<df?8:r<pf?9:10}});var fs=S((Cp,ls)=>{ls.exports={encode:is(),decode:as(),encodingLength:us()}});var ps=S((Pp,ds)=>{var pt=1e3,mt=pt*60,yt=mt*60,je=yt*24,yf=je*7,gf=je*365.25;ds.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return wf(r);if(t==="number"&&isFinite(r))return e.long?_f(r):bf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function wf(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*gf;case"weeks":case"week":case"w":return t*yf;case"days":case"day":case"d":return t*je;case"hours":case"hour":case"hrs":case"hr":case"h":return t*yt;case"minutes":case"minute":case"mins":case"min":case"m":return t*mt;case"seconds":case"second":case"secs":case"sec":case"s":return t*pt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function bf(r){var e=Math.abs(r);return e>=je?Math.round(r/je)+"d":e>=yt?Math.round(r/yt)+"h":e>=mt?Math.round(r/mt)+"m":e>=pt?Math.round(r/pt)+"s":r+"ms"}function _f(r){var e=Math.abs(r);return e>=je?_r(r,e,je,"day"):e>=yt?_r(r,e,yt,"hour"):e>=mt?_r(r,e,mt,"minute"):e>=pt?_r(r,e,pt,"second"):r+" ms"}function _r(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var ys=S((Ip,ms)=>{function vf(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=ps(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let h=0;for(let d=0;d<l.length;d++)h=(h<<5)-h+l.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(l){let h,d=null,v,y;function g(...k){if(!g.enabled)return;let I=g,O=Number(new Date),ne=O-(h||O);I.diff=ne,I.prev=h,I.curr=O,h=O,k[0]=t.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let $=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(ie,Q)=>{if(ie==="%%")return"%";$++;let oe=t.formatters[Q];if(typeof oe=="function"){let ct=k[$];ie=oe.call(I,ct),k.splice($,1),$--}return ie}),t.formatArgs.call(I,k),(I.log||t.log).apply(I,k)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(v!==t.namespaces&&(v=t.namespaces,y=t.enabled(l)),y),set:k=>{d=k}}),typeof t.init=="function"&&t.init(g),g}function n(l,h){let d=t(this.namespace+(typeof h>"u"?":":h)+l);return d.log=this.log,d}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let h,d=(typeof l=="string"?l:"").split(/[\s,]+/),v=d.length;for(h=0;h<v;h++)d[h]&&(l=d[h].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.slice(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function o(){let l=[...t.names.map(a),...t.skips.map(a).map(h=>"-"+h)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let h,d;for(h=0,d=t.skips.length;h<d;h++)if(t.skips[h].test(l))return!1;for(h=0,d=t.names.length;h<d;h++)if(t.names[h].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}ms.exports=vf});var gs=S((K,vr)=>{K.formatArgs=kf;K.save=Ef;K.load=Sf;K.useColors=xf;K.storage=Tf();K.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();K.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function xf(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function kf(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vr.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}K.log=console.debug||console.log||(()=>{});function Ef(r){try{r?K.storage.setItem("debug",r):K.storage.removeItem("debug")}catch{}}function Sf(){let r;try{r=K.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Tf(){try{return localStorage}catch{}}vr.exports=ys()(K);var{formatters:Af}=vr.exports;Af.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var bs=S((Qp,ws)=>{"use strict";ws.exports=If;function If(r,e){for(var t=new Array(arguments.length-1),n=0,i=2,o=!0;i<arguments.length;)t[n++]=arguments[i++];return new Promise(function(a,c){t[n]=function(l){if(o)if(o=!1,l)c(l);else{for(var h=new Array(arguments.length-1),d=0;d<h.length;)h[d++]=arguments[d];a.apply(null,h)}};try{r.apply(e||null,t)}catch(u){o&&(o=!1,c(u))}})}});var ks=S(xs=>{"use strict";var kr=xs;kr.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&e.charAt(t)==="=";)++n;return Math.ceil(e.length*3)/4-n};var wt=new Array(64),vs=new Array(123);for(he=0;he<64;)vs[wt[he]=he<26?he+65:he<52?he+71:he<62?he-4:he-59|43]=he++;var he;kr.encode=function(e,t,n){for(var i=null,o=[],s=0,a=0,c;t<n;){var u=e[t++];switch(a){case 0:o[s++]=wt[u>>2],c=(u&3)<<4,a=1;break;case 1:o[s++]=wt[c|u>>4],c=(u&15)<<2,a=2;break;case 2:o[s++]=wt[c|u>>6],o[s++]=wt[u&63],a=0;break}s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0)}return a&&(o[s++]=wt[c],o[s++]=61,a===1&&(o[s++]=61)),i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))};var _s="invalid encoding";kr.decode=function(e,t,n){for(var i=n,o=0,s,a=0;a<e.length;){var c=e.charCodeAt(a++);if(c===61&&o>1)break;if((c=vs[c])===void 0)throw Error(_s);switch(o){case 0:s=c,o=1;break;case 1:t[n++]=s<<2|(c&48)>>4,s=c,o=2;break;case 2:t[n++]=(s&15)<<4|(c&60)>>2,s=c,o=3;break;case 3:t[n++]=(s&3)<<6|c,o=0;break}}if(o===1)throw Error(_s);return n-i};kr.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var Ss=S((Xp,Es)=>{"use strict";Es.exports=Er;function Er(){this._listeners={}}Er.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this};Er.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i<n.length;)n[i].fn===t?n.splice(i,1):++i;return this};Er.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<t.length;)t[i].fn.apply(t[i++].ctx,n)}return this}});var Is=S((Jp,Ps)=>{"use strict";Ps.exports=Ts(Ts);function Ts(r){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),n=t[3]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3]}function o(c,u,l){e[0]=c,u[l]=t[3],u[l+1]=t[2],u[l+2]=t[1],u[l+3]=t[0]}r.writeFloatLE=n?i:o,r.writeFloatBE=n?o:i;function s(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],e[0]}function a(c,u){return t[3]=c[u],t[2]=c[u+1],t[1]=c[u+2],t[0]=c[u+3],e[0]}r.readFloatLE=n?s:a,r.readFloatBE=n?a:s}():function(){function e(n,i,o,s){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,o,s);else if(isNaN(i))n(2143289344,o,s);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,o,s);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,o,s);else{var c=Math.floor(Math.log(i)/Math.LN2),u=Math.round(i*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,o,s)}}r.writeFloatLE=e.bind(null,As),r.writeFloatBE=e.bind(null,Bs);function t(n,i,o){var s=n(i,o),a=(s>>31)*2+1,c=s>>>23&255,u=s&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}r.readFloatLE=t.bind(null,Cs),r.readFloatBE=t.bind(null,Ls)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),t=new Uint8Array(e.buffer),n=t[7]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3],u[l+4]=t[4],u[l+5]=t[5],u[l+6]=t[6],u[l+7]=t[7]}function o(c,u,l){e[0]=c,u[l]=t[7],u[l+1]=t[6],u[l+2]=t[5],u[l+3]=t[4],u[l+4]=t[3],u[l+5]=t[2],u[l+6]=t[1],u[l+7]=t[0]}r.writeDoubleLE=n?i:o,r.writeDoubleBE=n?o:i;function s(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],t[4]=c[u+4],t[5]=c[u+5],t[6]=c[u+6],t[7]=c[u+7],e[0]}function a(c,u){return t[7]=c[u],t[6]=c[u+1],t[5]=c[u+2],t[4]=c[u+3],t[3]=c[u+4],t[2]=c[u+5],t[1]=c[u+6],t[0]=c[u+7],e[0]}r.readDoubleLE=n?s:a,r.readDoubleBE=n?a:s}():function(){function e(n,i,o,s,a,c){var u=s<0?1:0;if(u&&(s=-s),s===0)n(0,a,c+i),n(1/s>0?0:2147483648,a,c+o);else if(isNaN(s))n(0,a,c+i),n(2146959360,a,c+o);else if(s>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+o);else{var l;if(s<22250738585072014e-324)l=s/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+o);else{var h=Math.floor(Math.log(s)/Math.LN2);h===1024&&(h=1023),l=s*Math.pow(2,-h),n(l*4503599627370496>>>0,a,c+i),n((u<<31|h+1023<<20|l*1048576&1048575)>>>0,a,c+o)}}}r.writeDoubleLE=e.bind(null,As,0,4),r.writeDoubleBE=e.bind(null,Bs,4,0);function t(n,i,o,s,a){var c=n(s,a+i),u=n(s,a+o),l=(u>>31)*2+1,h=u>>>20&2047,d=4294967296*(u&1048575)+c;return h===2047?d?NaN:l*(1/0):h===0?l*5e-324*d:l*Math.pow(2,h-1075)*(d+4503599627370496)}r.readDoubleLE=t.bind(null,Cs,0,4),r.readDoubleBE=t.bind(null,Ls,4,0)}(),r}function As(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 Bs(r,e,t){e[t]=r>>>24,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255}function Cs(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function Ls(r,e){return(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}});var Ns=S((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(r){}return null}});var Ms=S(Ds=>{"use strict";var Jn=Ds;Jn.length=function(e){for(var t=0,n=0,i=0;i<e.length;++i)n=e.charCodeAt(i),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(i+1)&64512)===56320?(++i,t+=4):t+=3;return t};Jn.read=function(e,t,n){var i=n-t;if(i<1)return"";for(var o=null,s=[],a=0,c;t<n;)c=e[t++],c<128?s[a++]=c:c>191&&c<224?s[a++]=(c&31)<<6|e[t++]&63:c>239&&c<365?(c=((c&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[a++]=55296+(c>>10),s[a++]=56320+(c&1023)):s[a++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0);return o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};Jn.write=function(e,t,n){for(var i=n,o,s,a=0;a<e.length;++a)o=e.charCodeAt(a),o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(a+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++a,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128);return n-i}});var Os=S((Yp,Fs)=>{"use strict";Fs.exports=Nf;function Nf(r,e,t){var n=t||8192,i=n>>>1,o=null,s=n;return function(c){if(c<1||c>i)return r(c);s+c>n&&(o=r(n),s=0);var u=e.call(o,s,s+=c);return s&7&&(s=(s|7)+1),u}}});var Rs=S((em,Us)=>{"use strict";Us.exports=R;var Wt=Xe();function R(r,e){this.lo=r>>>0,this.hi=e>>>0}var Ke=R.zero=new R(0,0);Ke.toNumber=function(){return 0};Ke.zzEncode=Ke.zzDecode=function(){return this};Ke.length=function(){return 1};var Df=R.zeroHash="\0\0\0\0\0\0\0\0";R.fromNumber=function(e){if(e===0)return Ke;var t=e<0;t&&(e=-e);var 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)};R.from=function(e){if(typeof e=="number")return R.fromNumber(e);if(Wt.isString(e))if(Wt.Long)e=Wt.Long.fromString(e);else return R.fromNumber(parseInt(e,10));return e.low||e.high?new R(e.low>>>0,e.high>>>0):Ke};R.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};R.prototype.toLong=function(e){return Wt.Long?new Wt.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var De=String.prototype.charCodeAt;R.fromHash=function(e){return e===Df?Ke:new R((De.call(e,0)|De.call(e,1)<<8|De.call(e,2)<<16|De.call(e,3)<<24)>>>0,(De.call(e,4)|De.call(e,5)<<8|De.call(e,6)<<16|De.call(e,7)<<24)>>>0)};R.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};R.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};R.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};R.prototype.length=function(){var 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}});var Xe=S(Zn=>{"use strict";var _=Zn;_.asPromise=bs();_.base64=ks();_.EventEmitter=Ss();_.float=Is();_.inquire=Ns();_.utf8=Ms();_.pool=Os();_.LongBits=Rs();_.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);_.global=_.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||Zn;_.emptyArray=Object.freeze?Object.freeze([]):[];_.emptyObject=Object.freeze?Object.freeze({}):{};_.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};_.isString=function(e){return typeof e=="string"||e instanceof String};_.isObject=function(e){return e&&typeof e=="object"};_.isset=_.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};_.Buffer=function(){try{var r=_.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();_._Buffer_from=null;_._Buffer_allocUnsafe=null;_.newBuffer=function(e){return typeof e=="number"?_.Buffer?_._Buffer_allocUnsafe(e):new _.Array(e):_.Buffer?_._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};_.Array=typeof Uint8Array<"u"?Uint8Array:Array;_.Long=_.global.dcodeIO&&_.global.dcodeIO.Long||_.global.Long||_.inquire("long");_.key2Re=/^true|false|0|1$/;_.key32Re=/^-?(?:0|[1-9][0-9]*)$/;_.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;_.longToHash=function(e){return e?_.LongBits.from(e).toHash():_.LongBits.zeroHash};_.longFromHash=function(e,t){var n=_.LongBits.fromHash(e);return _.Long?_.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function zs(r,e,t){for(var n=Object.keys(e),i=0;i<n.length;++i)(r[n[i]]===void 0||!t)&&(r[n[i]]=e[n[i]]);return r}_.merge=zs;_.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function $s(r){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&zs(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return r},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}_.newError=$s;_.ProtocolError=$s("ProtocolError");_.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var i=Object.keys(this),o=i.length-1;o>-1;--o)if(t[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};_.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}};_.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};_._configure=function(){var r=_.Buffer;if(!r){_._Buffer_from=_._Buffer_allocUnsafe=null;return}_._Buffer_from=r.from!==Uint8Array.from&&r.from||function(t,n){return new r(t,n)},_._Buffer_allocUnsafe=r.allocUnsafe||function(t){return new r(t)}}});var ti=S((rm,js)=>{"use strict";js.exports=M;var we=Xe(),ei,qs=we.LongBits,Mf=we.utf8;function de(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function M(r){this.buf=r,this.pos=0,this.len=r.length}var Ws=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new M(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new M(e);throw Error("illegal buffer")},Vs=function(){return we.Buffer?function(t){return(M.create=function(i){return we.Buffer.isBuffer(i)?new ei(i):Ws(i)})(t)}:Ws};M.create=Vs();M.prototype._slice=we.Array.prototype.subarray||we.Array.prototype.slice;M.prototype.uint32=function(){var e=4294967295;return function(){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,de(this,10);return e}}();M.prototype.int32=function(){return this.uint32()|0};M.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Yn(){var r=new qs(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw de(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw de(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}M.prototype.bool=function(){return this.uint32()!==0};function Sr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}M.prototype.fixed32=function(){if(this.pos+4>this.len)throw de(this,4);return Sr(this.buf,this.pos+=4)};M.prototype.sfixed32=function(){if(this.pos+4>this.len)throw de(this,4);return Sr(this.buf,this.pos+=4)|0};function Hs(){if(this.pos+8>this.len)throw de(this,8);return new qs(Sr(this.buf,this.pos+=4),Sr(this.buf,this.pos+=4))}M.prototype.float=function(){if(this.pos+4>this.len)throw de(this,4);var e=we.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};M.prototype.double=function(){if(this.pos+8>this.len)throw de(this,4);var e=we.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};M.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw de(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)};M.prototype.string=function(){var e=this.bytes();return Mf.read(e,0,e.length)};M.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw de(this,e);this.pos+=e}else do if(this.pos>=this.len)throw de(this);while(this.buf[this.pos++]&128);return this};M.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};M._configure=function(r){ei=r,M.create=Vs(),ei._configure();var e=we.Long?"toLong":"toNumber";we.merge(M.prototype,{int64:function(){return Yn.call(this)[e](!1)},uint64:function(){return Yn.call(this)[e](!0)},sint64:function(){return Yn.call(this).zzDecode()[e](!1)},fixed64:function(){return Hs.call(this)[e](!0)},sfixed64:function(){return Hs.call(this)[e](!1)}})}});var Xs=S((nm,Ks)=>{"use strict";Ks.exports=Je;var Qs=ti();(Je.prototype=Object.create(Qs.prototype)).constructor=Je;var Gs=Xe();function Je(r){Qs.call(this,r)}Je._configure=function(){Gs.Buffer&&(Je.prototype._slice=Gs.Buffer.prototype.slice)};Je.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Je._configure()});var ci=S((im,ea)=>{"use strict";ea.exports=T;var ce=Xe(),ri,Tr=ce.LongBits,Js=ce.base64,Zs=ce.utf8;function Ht(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function ii(){}function Ff(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function T(){this.len=0,this.head=new Ht(ii,0,0),this.tail=this.head,this.states=null}var Ys=function(){return ce.Buffer?function(){return(T.create=function(){return new ri})()}:function(){return new T}};T.create=Ys();T.alloc=function(e){return new ce.Array(e)};ce.Array!==Array&&(T.alloc=ce.pool(T.alloc,ce.Array.prototype.subarray));T.prototype._push=function(e,t,n){return this.tail=this.tail.next=new Ht(e,t,n),this.len+=t,this};function oi(r,e,t){e[t]=r&255}function Of(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function si(r,e){this.len=r,this.next=void 0,this.val=e}si.prototype=Object.create(Ht.prototype);si.prototype.fn=Of;T.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new si((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};T.prototype.int32=function(e){return e<0?this._push(ai,10,Tr.fromNumber(e)):this.uint32(e)};T.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function ai(r,e,t){for(;r.hi;)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}T.prototype.uint64=function(e){var t=Tr.from(e);return this._push(ai,t.length(),t)};T.prototype.int64=T.prototype.uint64;T.prototype.sint64=function(e){var t=Tr.from(e).zzEncode();return this._push(ai,t.length(),t)};T.prototype.bool=function(e){return this._push(oi,1,e?1:0)};function ni(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}T.prototype.fixed32=function(e){return this._push(ni,4,e>>>0)};T.prototype.sfixed32=T.prototype.fixed32;T.prototype.fixed64=function(e){var t=Tr.from(e);return this._push(ni,4,t.lo)._push(ni,4,t.hi)};T.prototype.sfixed64=T.prototype.fixed64;T.prototype.float=function(e){return this._push(ce.float.writeFloatLE,4,e)};T.prototype.double=function(e){return this._push(ce.float.writeDoubleLE,8,e)};var Uf=ce.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i<e.length;++i)t[n+i]=e[i]};T.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(oi,1,0);if(ce.isString(e)){var n=T.alloc(t=Js.length(e));Js.decode(e,n,0),e=n}return this.uint32(t)._push(Uf,t,e)};T.prototype.string=function(e){var t=Zs.length(e);return t?this.uint32(t)._push(Zs.write,t,e):this._push(oi,1,0)};T.prototype.fork=function(){return this.states=new Ff(this),this.head=this.tail=new Ht(ii,0,0),this.len=0,this};T.prototype.reset=function(){return this.states?(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 Ht(ii,0,0),this.len=0),this};T.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};T.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};T._configure=function(r){ri=r,T.create=Ys(),ri._configure()}});var na=S((om,ra)=>{"use strict";ra.exports=be;var ta=ci();(be.prototype=Object.create(ta.prototype)).constructor=be;var Me=Xe();function be(){ta.call(this)}be._configure=function(){be.alloc=Me._Buffer_allocUnsafe,be.writeBytesBuffer=Me.Buffer&&Me.Buffer.prototype instanceof Uint8Array&&Me.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i<e.length;)t[n++]=e[i++]}};be.prototype.bytes=function(e){Me.isString(e)&&(e=Me._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(be.writeBytesBuffer,t,e),this};function Rf(r,e,t){r.length<40?Me.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}be.prototype.string=function(e){var t=Me.Buffer.byteLength(e);return this.uint32(t),t&&this._push(Rf,t,e),this};be._configure()});var Or=S((vy,wa)=>{"use strict";function ga(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function th(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return ga(r,t)}catch{t.message=r.message,t.stack=r.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(r)),ga(new i,t)}}wa.exports=th});var Ea=S((Ry,ka)=>{"use strict";ka.exports=function(){return Date.now()}});var Ta=S((zy,Sa)=>{"use strict";var zr=Ea(),vi=class{constructor(e,t,n){let i=this;this._started=zr(),this._rescheduled=0,this._scheduled=t,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(zr()-i._started),i._schedule(i._scheduled)):(i._triggered=!0,e.apply(null,i._args))},this._timer=setTimeout(this._timerWrapper,t)}reschedule(e){e||(e=this._scheduled);let t=zr();t+e-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(e)):this._triggered?this._schedule(e):(this._started=t,this._rescheduled=e)}_schedule(e){this._triggered=!1,this._started=zr(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function lh(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let r;if(arguments.length>0){r=new Array(arguments.length-2);for(var e=0;e<r.length;e++)r[e]=arguments[e+2]}return new vi(arguments[0],arguments[1],r)}Sa.exports=lh});var Ca=S(($y,Ba)=>{"use strict";var{AbortController:fh}=globalThis,Aa=Ta(),Vt=class extends fh{constructor(e){super(),this._ms=e,this._timer=Aa(()=>this.abort(),e),Object.setPrototypeOf(this,Vt.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=Aa(()=>this.abort(),this._ms)}};Ba.exports={TimeoutController:Vt}});var Qr=S((Sg,Ai)=>{"use strict";var St=typeof Reflect=="object"?Reflect:null,Ma=St&&typeof St.apply=="function"?St.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},jr;St&&typeof St.ownKeys=="function"?jr=St.ownKeys:Object.getOwnPropertySymbols?jr=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:jr=function(e){return Object.getOwnPropertyNames(e)};function Eh(r){console&&console.warn&&console.warn(r)}var Oa=Number.isNaN||function(e){return e!==e};function L(){L.init.call(this)}Ai.exports=L;Ai.exports.once=Bh;L.EventEmitter=L;L.prototype._events=void 0;L.prototype._eventsCount=0;L.prototype._maxListeners=void 0;var Fa=10;function Gr(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(L,"defaultMaxListeners",{enumerable:!0,get:function(){return Fa},set:function(r){if(typeof r!="number"||r<0||Oa(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");Fa=r}});L.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};L.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Oa(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Ua(r){return r._maxListeners===void 0?L.defaultMaxListeners:r._maxListeners}L.prototype.getMaxListeners=function(){return Ua(this)};L.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(c===void 0)return!1;if(typeof c=="function")Ma(c,this,t);else for(var u=c.length,l=Ha(c,u),n=0;n<u;++n)Ma(l[n],this,t);return!0};function Ra(r,e,t,n){var i,o,s;if(Gr(t),o=r._events,o===void 0?(o=r._events=Object.create(null),r._eventsCount=0):(o.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),o=r._events),s=o[e]),s===void 0)s=o[e]=t,++r._eventsCount;else if(typeof s=="function"?s=o[e]=n?[t,s]:[s,t]:n?s.unshift(t):s.push(t),i=Ua(r),i>0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=s.length,Eh(a)}return r}L.prototype.addListener=function(e,t){return Ra(this,e,t,!1)};L.prototype.on=L.prototype.addListener;L.prototype.prependListener=function(e,t){return Ra(this,e,t,!0)};function Sh(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function za(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=Sh.bind(n);return i.listener=t,n.wrapFn=i,i}L.prototype.once=function(e,t){return Gr(t),this.on(e,za(this,e,t)),this};L.prototype.prependOnceListener=function(e,t){return Gr(t),this.prependListener(e,za(this,e,t)),this};L.prototype.removeListener=function(e,t){var n,i,o,s,a;if(Gr(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():Th(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};L.prototype.off=L.prototype.removeListener;L.prototype.removeAllListeners=function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this};function $a(r,e,t){var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?t?[i.listener||i]:[i]:t?Ah(i):Ha(i,i.length)}L.prototype.listeners=function(e){return $a(this,e,!0)};L.prototype.rawListeners=function(e){return $a(this,e,!1)};L.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):Wa.call(r,e)};L.prototype.listenerCount=Wa;function Wa(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}L.prototype.eventNames=function(){return this._eventsCount>0?jr(this._events):[]};function Ha(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function Th(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function Ah(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function Bh(r,e){return new Promise(function(t,n){function i(s){r.removeListener(e,o),n(s)}function o(){typeof r.removeListener=="function"&&r.removeListener("error",i),t([].slice.call(arguments))}qa(r,e,o,{once:!0}),e!=="error"&&Ch(r,i,{once:!0})})}function Ch(r,e,t){typeof r.on=="function"&&qa(r,"error",e,t)}function qa(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function i(o){n.once&&r.removeEventListener(e,i),t(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var Ya=S((Ja,Za)=>{"use strict";var qh=Math.exp;Ja=Za.exports=function(e){if(typeof e!="number")throw new Error("must provide a timespan to the moving average constructor");if(e<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let t,n=0,i=0,o=0,s,a={};function c(u,l){return 1-qh(-(u-l)/e)}return a.push=function(l,h){if(s){let d=c(l,s),v=h-t,y=d*v;t=d*h+(1-d)*t,n=(1-d)*(n+v*y),i=Math.sqrt(n),o=t+d*v}else t=h;s=l},a.movingAverage=function(){return t},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return o},a}});var ic=S((rw,Ri)=>{function nc(r){let e=new globalThis.AbortController;function t(){e.abort();for(let n of r)!n||!n.removeEventListener||n.removeEventListener("abort",t)}for(let n of r)if(!(!n||!n.addEventListener)){if(n.aborted){t();break}n.addEventListener("abort",t)}return e.signal}Ri.exports=nc;Ri.exports.anySignal=nc});var cc=S((gw,$i)=>{"use strict";var Xh=Object.prototype.hasOwnProperty,q="~";function Zt(){}Object.create&&(Zt.prototype=Object.create(null),new Zt().__proto__||(q=!1));function Jh(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function ac(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Jh(t,n||r,i),s=q?q+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function en(r,e){--r._eventsCount===0?r._events=new Zt:delete r._events[e]}function H(){this._events=new Zt,this._eventsCount=0}H.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Xh.call(t,n)&&e.push(q?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};H.prototype.listeners=function(e){var t=q?q+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};H.prototype.listenerCount=function(e){var t=q?q+e:e,n=this._events[t];return n?n.fn?1:n.length:0};H.prototype.emit=function(e,t,n,i,o,s){var a=q?q+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,h;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c.fn.apply(c.context,l)}else{var d=c.length,v;for(h=0;h<d;h++)switch(c[h].once&&this.removeListener(e,c[h].fn,void 0,!0),u){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,t);break;case 3:c[h].fn.call(c[h].context,t,n);break;case 4:c[h].fn.call(c[h].context,t,n,i);break;default:if(!l)for(v=1,l=new Array(u-1);v<u;v++)l[v-1]=arguments[v];c[h].fn.apply(c[h].context,l)}}return!0};H.prototype.on=function(e,t,n){return ac(this,e,t,n,!1)};H.prototype.once=function(e,t,n){return ac(this,e,t,n,!0)};H.prototype.removeListener=function(e,t,n,i){var o=q?q+e:e;if(!this._events[o])return this;if(!t)return en(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&en(this,o);else{for(var a=0,c=[],u=s.length;a<u;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:en(this,o)}return this};H.prototype.removeAllListeners=function(e){var t;return e?(t=q?q+e:e,this._events[t]&&en(this,t)):(this._events=new Zt,this._eventsCount=0),this};H.prototype.off=H.prototype.removeListener;H.prototype.addListener=H.prototype.on;H.prefixed=q;H.EventEmitter=H;typeof $i<"u"&&($i.exports=H)});var rp={};V(rp,{createHelia:()=>tp});var Mn={};V(Mn,{identity:()=>Dn});var ip=new Uint8Array(0);var So=(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},xe=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")};var To=r=>new TextEncoder().encode(r),Ao=r=>new TextDecoder().decode(r);var nl=Po,Co=128,il=127,ol=~il,sl=Math.pow(2,31);function Po(r,e,t){e=e||[],t=t||0;for(var n=t;r>=sl;)e[t++]=r&255|Co,r/=128;for(;r&ol;)e[t++]=r&255|Co,r>>>=7;return e[t]=r|0,Po.bytes=t-n+1,e}var al=Nn,cl=128,Lo=127;function Nn(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw Nn.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&Lo)<<i:(s&Lo)*Math.pow(2,i),i+=7}while(s>=cl);return Nn.bytes=o-n,t}var ul=Math.pow(2,7),ll=Math.pow(2,14),fl=Math.pow(2,21),hl=Math.pow(2,28),dl=Math.pow(2,35),pl=Math.pow(2,42),ml=Math.pow(2,49),yl=Math.pow(2,56),gl=Math.pow(2,63),wl=function(r){return r<ul?1:r<ll?2:r<fl?3:r<hl?4:r<dl?5:r<pl?6:r<ml?7:r<yl?8:r<gl?9:10},bl={encode:nl,decode:al,encodingLength:wl},_l=bl,Ot=_l;var Ut=(r,e=0)=>[Ot.decode(r,e),Ot.decode.bytes],ut=(r,e,t=0)=>(Ot.encode(r,e,t),e),lt=r=>Ot.encodingLength(r);var qe=(r,e)=>{let t=e.byteLength,n=lt(r),i=n+lt(t),o=new Uint8Array(i+t);return ut(r,o,0),ut(t,o,n),o.set(e,i),new ft(r,t,e,o)},br=r=>{let e=xe(r),[t,n]=Ut(e),[i,o]=Ut(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new ft(t,i,s,e)},Io=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&So(r.bytes,t.bytes)}},ft=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var No=0,vl="identity",Do=xe,xl=r=>qe(No,Do(r)),Dn={code:No,name:vl,encode:Do,digest:xl};var Rn={};V(Rn,{sha256:()=>Ve,sha512:()=>Un});var On=({name:r,code:e,encode:t})=>new Fn(r,e,t),Fn=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?qe(this.code,t):t.then(n=>qe(this.code,n))}else throw Error("Unknown type, must be binary type")}};var Fo=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Ve=On({name:"sha2-256",code:18,encode:Fo("SHA-256")}),Un=On({name:"sha2-512",code:19,encode:Fo("SHA-512")});var qn={};V(qn,{base58btc:()=>E,base58flickr:()=>Bl});function kl(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 o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var g=0,k=0,I=0,O=y.length;I!==O&&y[I]===0;)I++,g++;for(var ne=(O-I)*l+1>>>0,$=new Uint8Array(ne);I!==O;){for(var fe=y[I],ie=0,Q=ne-1;(fe!==0||ie<k)&&Q!==-1;Q--,ie++)fe+=256*$[Q]>>>0,$[Q]=fe%a>>>0,fe=fe/a>>>0;if(fe!==0)throw new Error("Non-zero carry");k=ie,I++}for(var oe=ne-k;oe!==ne&&$[oe]===0;)oe++;for(var ct=c.repeat(g);oe<ne;++oe)ct+=r.charAt($[oe]);return ct}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var g=0;if(y[g]!==" "){for(var k=0,I=0;y[g]===c;)k++,g++;for(var O=(y.length-g)*u+1>>>0,ne=new Uint8Array(O);y[g];){var $=t[y.charCodeAt(g)];if($===255)return;for(var fe=0,ie=O-1;($!==0||fe<I)&&ie!==-1;ie--,fe++)$+=a*ne[ie]>>>0,ne[ie]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");I=fe,g++}if(y[g]!==" "){for(var Q=O-I;Q!==O&&ne[Q]===0;)Q++;for(var oe=new Uint8Array(k+(O-Q)),ct=k;Q!==O;)oe[ct++]=ne[Q++];return oe}}}function v(y){var g=d(y);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:v}}var El=kl,Sl=El,Oo=Sl;var zn=class{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")}},$n=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),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 Uo(this,e)}},Wn=class{constructor(e){this.decoders=e}or(e){return Uo(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Uo=(r,e)=>new Wn({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Hn=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new zn(e,t,n),this.decoder=new $n(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},dt=({name:r,prefix:e,encode:t,decode:n})=>new Hn(r,e,t,n),Ie=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=Oo(t,e);return dt({prefix:r,name:e,encode:n,decode:o=>xe(i(o))})},Tl=(r,e,t,n)=>{let i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),a=0,c=0,u=0;for(let l=0;l<o;++l){let h=i[r[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},Al=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,o+=e[i&a>>s];if(s&&(o+=e[i&a<<t-s]),n)for(;o.length*t&7;)o+="=";return o},D=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>dt({prefix:e,name:r,encode(i){return Al(i,n,t)},decode(i){return Tl(i,n,t,r)}});var E=Ie({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bl=Ie({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Vn={};V(Vn,{base32:()=>j,base32hex:()=>Il,base32hexpad:()=>Dl,base32hexpadupper:()=>Ml,base32hexupper:()=>Nl,base32pad:()=>Ll,base32padupper:()=>Pl,base32upper:()=>Cl,base32z:()=>Fl});var j=D({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cl=D({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ll=D({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Pl=D({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Il=D({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Nl=D({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Dl=D({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ml=D({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Fl=D({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ro=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return Ul(t,jn(r),e||E.encoder);default:return Rl(t,jn(r),e||j.encoder)}};var zo=new WeakMap,jn=r=>{let e=zo.get(r);if(e==null){let t=new Map;return zo.set(r,t),t}return e},x=class{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!==Rt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==zl)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return x.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=qe(e,t);return x.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 x.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&Io(e.multihash,n.multihash)}toString(e){return Ro(this,e)}toJSON(){return{"/":Ro(this)}}link(){return this}get[Symbol.toStringTag](){return"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 x)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new x(n,i,o,s||$o(n,i,o.bytes))}else if(t[$l]===!0){let{version:n,multihash:i,code:o}=t,s=br(i);return x.create(n,o,s)}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!==Rt)throw new Error(`Version 0 CID must use dag-pb (code: ${Rt}) block encoding`);return new x(e,t,n,n.bytes)}case 1:{let i=$o(e,t,n.bytes);return new x(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return x.create(0,Rt,e)}static createV1(e,t){return x.create(1,e,t)}static decode(e){let[t,n]=x.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=x.inspectBytes(e),n=t.size-t.multihashSize,i=xe(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new ft(t.multihashCode,t.digestSize,o,i);return[t.version===0?x.createV0(s):x.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=Ut(e.subarray(t));return t+=d,h},i=n(),o=Rt;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=Ol(e,t),o=x.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return jn(o).set(n,e),o}},Ol=(r,e)=>{switch(r[0]){case"Q":{let t=e||E;return[E.prefix,t.decode(`${E.prefix}${r}`)]}case E.prefix:{let t=e||E;return[E.prefix,t.decode(r)]}case j.prefix:{let t=e||j;return[j.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},Ul=(r,e,t)=>{let{prefix:n}=t;if(n!==E.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i},Rl=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i},Rt=112,zl=18,$o=(r,e,t)=>{let n=lt(r),i=n+lt(e),o=new Uint8Array(i+t.byteLength);return ut(r,o,0),ut(e,o,n),o.set(t,i),o},$l=Symbol.for("@ipld/js-cid/CID");var ca=U(ts(),1);var zt=U(fs(),1);function mf(r){let e=new Uint8Array(r.reduce((n,i)=>n+zt.default.encodingLength(i),0)),t=0;for(let n of r)e=zt.encode(n,e,t),t+=zt.default.encodingLength(n);return e}var hs=mf;var se=U(gs(),1);var Xn={};V(Xn,{base64:()=>$t,base64pad:()=>Bf,base64url:()=>Cf,base64urlpad:()=>Lf});var $t=D({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Bf=D({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Cf=D({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Lf=D({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});se.default.formatters.b=r=>r==null?"undefined":E.baseEncode(r);se.default.formatters.t=r=>r==null?"undefined":j.baseEncode(r);se.default.formatters.m=r=>r==null?"undefined":$t.baseEncode(r);se.default.formatters.p=r=>r==null?"undefined":r.toString();se.default.formatters.c=r=>r==null?"undefined":r.toString();se.default.formatters.k=r=>r==null?"undefined":r.toString();function Pf(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function gt(r){let e=Pf(`${r}:trace`);return se.default.enabled(`${r}:trace`)&&se.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,se.default)(`${r}:trace`)),Object.assign((0,se.default)(r),{error:(0,se.default)(`${r}:error`),trace:e})}function Ge(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 Qe=class{constructor(e,t,n){this._refCounter=1,this.cid=e,this.priority=t??1,this.wantType=n}inc(){this._refCounter+=1}dec(){this._refCounter=Math.max(0,this._refCounter-1)}hasRefs(){return this._refCounter>0}get[Symbol.toStringTag](){return`WantlistEntry <key: ${this.cid.toString(E)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(e){return this._refCounter===e._refCounter&&this.cid.equals(e.cid)&&this.priority===e.priority&&this.wantType===e.wantType}};var Ne=class{constructor(e,t,n,i,o){this.entry=new Qe(e,t,n),this.cancel=!!i,this.sendDontHave=!!o}get cid(){return this.entry.cid}set cid(e){this.entry.cid=e}get priority(){return this.entry.priority}set priority(e){this.entry.priority=e}get wantType(){return this.entry.wantType}set wantType(e){this.entry.wantType=e}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(E)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(e){return this.cancel===e.cancel&&this.sendDontHave===e.sendDontHave&&this.wantType===e.wantType&&this.entry.equals(e.entry)}};var ae=(r,e)=>{let t=["bitswap"];return e!=null&&t.push(e),r!=null&&t.push(`${r.toString().slice(0,8)}`),gt(t.join(":"))};var xr=(r,e)=>{if(r.size!==e.size)return!1;for(let[t,n]of r){let i=e.get(t);if(i===void 0||n instanceof Uint8Array&&i instanceof Uint8Array&&!Ge(n,i)||n instanceof Ne&&i instanceof Ne&&!n.equals(i))return!1}return!0};var ui=U(ti(),1),ia=U(Xs(),1),oa=U(Xe(),1),li=U(ci(),1),sa=U(na(),1);function zf(){oa.default._configure(),ui.default._configure(ia.default),li.default._configure(sa.default)}zf();var aa=["uint64","int64","sint64","fixed64","sfixed64"];function $f(r){for(let e of aa){if(r[e]==null)continue;let t=r[e];r[e]=function(){return BigInt(t.call(this).toString())}}return r}function fi(r){return $f(new ui.default(r))}function Wf(r){for(let e of aa){if(r[e]==null)continue;let t=r[e];r[e]=function(n){return t.call(this,n.toString())}}return r}function hi(){return Wf(li.default.create())}function Ze(r,e){let t=fi(r instanceof Uint8Array?r:r.subarray());return e.decode(t)}function Ye(r,e){let t=hi();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var bt;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(bt||(bt={}));function Ar(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Br(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return Ar("enum",bt.VARINT,t,n)}function et(r,e){return Ar("message",bt.LENGTH_DELIMITED,r,e)}var G;(function(r){let e;(function(a){let c;(function(d){d.Block="Block",d.Have="Have"})(c=a.WantType||(a.WantType={}));let u;(function(d){d[d.Block=0]="Block",d[d.Have=1]="Have"})(u||(u={})),function(d){d.codec=()=>Br(u)}(c=a.WantType||(a.WantType={}));let l;(function(d){let v;d.codec=()=>(v==null&&(v=et((y,g,k={})=>{k.lengthDelimited!==!1&&g.fork(),y.block!=null&&y.block.byteLength>0&&(g.uint32(10),g.bytes(y.block)),y.priority!=null&&y.priority!==0&&(g.uint32(16),g.int32(y.priority)),y.cancel!=null&&y.cancel!==!1&&(g.uint32(24),g.bool(y.cancel)),y.wantType!=null&&u[y.wantType]!==0&&(g.uint32(32),r.Wantlist.WantType.codec().encode(y.wantType,g)),y.sendDontHave!=null&&y.sendDontHave!==!1&&(g.uint32(40),g.bool(y.sendDontHave)),k.lengthDelimited!==!1&&g.ldelim()},(y,g)=>{let k={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},I=g==null?y.len:y.pos+g;for(;y.pos<I;){let O=y.uint32();switch(O>>>3){case 1:k.block=y.bytes();break;case 2:k.priority=y.int32();break;case 3:k.cancel=y.bool();break;case 4:k.wantType=r.Wantlist.WantType.codec().decode(y);break;case 5:k.sendDontHave=y.bool();break;default:y.skipType(O&7);break}}return k})),v),d.encode=y=>Ye(y,d.codec()),d.decode=y=>Ze(y,d.codec())})(l=a.Entry||(a.Entry={}));let h;a.codec=()=>(h==null&&(h=et((d,v,y={})=>{if(y.lengthDelimited!==!1&&v.fork(),d.entries!=null)for(let g of d.entries)v.uint32(10),r.Wantlist.Entry.codec().encode(g,v);d.full!=null&&d.full!==!1&&(v.uint32(16),v.bool(d.full)),y.lengthDelimited!==!1&&v.ldelim()},(d,v)=>{let y={entries:[],full:!1},g=v==null?d.len:d.pos+v;for(;d.pos<g;){let k=d.uint32();switch(k>>>3){case 1:y.entries.push(r.Wantlist.Entry.codec().decode(d,d.uint32()));break;case 2:y.full=d.bool();break;default:d.skipType(k&7);break}}return y})),h),a.encode=d=>Ye(d,a.codec()),a.decode=d=>Ze(d,a.codec())})(e=r.Wantlist||(r.Wantlist={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=et((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.prefix!=null&&u.prefix.byteLength>0&&(l.uint32(10),l.bytes(u.prefix)),u.data!=null&&u.data.byteLength>0&&(l.uint32(18),l.bytes(u.data)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={prefix:new Uint8Array(0),data:new Uint8Array(0)},d=l==null?u.len:u.pos+l;for(;u.pos<d;){let v=u.uint32();switch(v>>>3){case 1:h.prefix=u.bytes();break;case 2:h.data=u.bytes();break;default:u.skipType(v&7);break}}return h})),c),a.encode=u=>Ye(u,a.codec()),a.decode=u=>Ze(u,a.codec())})(t=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(i||(i={})),function(a){a.codec=()=>Br(i)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let o;(function(a){let c;a.codec=()=>(c==null&&(c=et((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.cid!=null&&u.cid.byteLength>0&&(l.uint32(10),l.bytes(u.cid)),u.type!=null&&i[u.type]!==0&&(l.uint32(16),r.BlockPresenceType.codec().encode(u.type,l)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={cid:new Uint8Array(0),type:n.Have},d=l==null?u.len:u.pos+l;for(;u.pos<d;){let v=u.uint32();switch(v>>>3){case 1:h.cid=u.bytes();break;case 2:h.type=r.BlockPresenceType.codec().decode(u);break;default:u.skipType(v&7);break}}return h})),c),a.encode=u=>Ye(u,a.codec()),a.decode=u=>Ze(u,a.codec())})(o=r.BlockPresence||(r.BlockPresence={}));let s;r.codec=()=>(s==null&&(s=et((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let l of a.blocks)c.uint32(18),c.bytes(l);if(a.payload!=null)for(let l of a.payload)c.uint32(26),r.Block.codec().encode(l,c);if(a.blockPresences!=null)for(let l of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(l,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={blocks:[],payload:[],blockPresences:[],pendingBytes:0},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:u.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:u.blocks.push(a.bytes());break;case 3:u.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:u.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:u.pendingBytes=a.int32();break;default:a.skipType(h&7);break}}return u})),s),r.encode=a=>Ye(a,r.codec()),r.decode=a=>Ze(a,r.codec())})(G||(G={}));var Cr=class extends Error{constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var Hf,B=class{constructor(e){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}get empty(){return this.blocks.size===0&&this.wantlist.size===0&&this.blockPresences.size===0}addEntry(e,t,n,i,o){n==null&&(n=B.WantType.Block);let s=e.toString(E),a=this.wantlist.get(s);a!=null?(a.wantType===n&&(a.priority=t),i===!0&&(a.cancel=!!i),o===!0&&(a.sendDontHave=!!o),n===B.WantType.Block&&a.wantType===B.WantType.Have&&(a.wantType=n)):this.wantlist.set(s,new Ne(e,t,n,i,o))}addBlock(e,t){let n=e.toString(E);this.blocks.set(n,t)}addHave(e){let t=e.toString(E);this.blockPresences.has(t)||this.blockPresences.set(t,B.BlockPresenceType.Have)}addDontHave(e){let t=e.toString(E);this.blockPresences.has(t)||this.blockPresences.set(t,B.BlockPresenceType.DontHave)}cancel(e){let t=e.toString(E);this.wantlist.delete(t),this.addEntry(e,0,B.WantType.Block,!0,!1)}setPendingBytes(e){this.pendingBytes=e}serializeToBitswap100(){return G.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),cancel:!!e.cancel,wantType:G.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}serializeToBitswap110(){let e={wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),wantType:t.wantType,cancel:!!t.cancel,sendDontHave:!!t.sendDontHave})),full:!!this.full},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[t,n]of this.blocks.entries()){let i=x.parse(t),o=i.version,s=i.code,a=i.multihash.code,c=i.multihash.digest.length,u=hs([o,s,a,c]);e.payload.push({prefix:u,data:n})}for(let[t,n]of this.blockPresences)e.blockPresences.push({cid:x.parse(t).bytes,type:n});return this.pendingBytes>0&&(e.pendingBytes=this.pendingBytes),G.encode(e)}equals(e){return!(this.full!==e.full||this.pendingBytes!==e.pendingBytes||!xr(this.wantlist,e.wantlist)||!xr(this.blocks,e.blocks)||!xr(this.blockPresences,e.blockPresences))}get[Symbol.toStringTag](){let e=Array.from(this.wantlist.keys()),t=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${e}, blocks: ${t}>`}};Hf=B;B.Entry=Ne;B.WantType={Block:G.Wantlist.WantType.Block,Have:G.Wantlist.WantType.Have};B.BlockPresenceType={Have:G.BlockPresenceType.Have,DontHave:G.BlockPresenceType.DontHave};B.deserialize=async(r,e)=>{let t=G.decode(r),n=t.wantlist?.full===!0,i=new B(n);return t.wantlist?.entries.forEach(o=>{if(o.block==null)return;let s=x.decode(o.block);i.addEntry(s,o.priority??0,o.wantType,!!o.cancel,!!o.sendDontHave)}),t.blockPresences.forEach(o=>{if(o.cid==null)return;let s=x.decode(o.cid);o.type===B.BlockPresenceType.Have?i.addHave(s):i.addDontHave(s)}),t.blocks.length>0?(await Promise.all(t.blocks.map(async o=>{let s=await Ve.digest(o),a=x.createV0(s);i.addBlock(a,o)})),i):(t.payload.length>0&&(await Promise.all(t.payload.map(async o=>{if(o.prefix==null||o.data==null)return;let s=(0,ca.default)(o.prefix),a=s[0],c=s[1],u=s[2],l=u===Ve.code?Ve:await e?.getHasher(u);if(l==null)throw new Cr("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let h=await l.digest(o.data),d=x.create(a,c,h);i.addBlock(d,o.data)})),i.setPendingBytes(t.pendingBytes)),i)};B.blockPresenceSize=r=>r.bytes.length+1;var di=class extends Map{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 Fe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new di({name:e,metrics:t}):n=new Map,n}var ua={Block:G.Wantlist.WantType.Block,Have:G.Wantlist.WantType.Have},qf=(r,e)=>Array.prototype.slice.call(e,0).sort((t,n)=>{let i=r(t),o=r(n);return i<o?-1:i>o?1:0}),ke=class{constructor(e,t){this.set=t!=null?Fe({name:"ipfs_bitswap_wantlist",metrics:t.metrics}):new Map,this._stats=e}get length(){return this.set.size}add(e,t,n){let i=e.toString(E),o=this.set.get(i);o!=null?(o.inc(),o.priority=t,o.wantType===ua.Have&&n===ua.Block&&(o.wantType=n)):(this.set.set(i,new Qe(e,t,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(e){let t=e.toString(E),n=this.set.get(t);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(t),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(e){this.set.has(e)&&this.set.delete(e)}forEach(e){this.set.forEach(e)}entries(){return this.set.entries()}sortedEntries(){return new Map(qf(e=>e[1].key,Array.from(this.set.entries())))}contains(e){let t=e.toString(E);return this.set.has(t)}get(e){let t=e.toString(E);return this.set.get(t)}};ke.Entry=Qe;var la=Math.pow(2,31)-1,fa=1e3,ha=1;var da=Vf;function Vf(r,e,t){var n=null,i=null,o=function(){n&&(clearTimeout(n),i=null,n=null)},s=function(){var c=i;o(),c&&c()},a=function(){if(!e)return r.apply(this,arguments);var c=this,u=arguments,l=t&&!n;if(o(),i=function(){r.apply(c,u)},n=setTimeout(function(){if(n=null,!l){var h=i;return i=null,h()}},e),l)return i()};return a.cancel=o,a.flush=s,a}var Lr=class{constructor(e,t,n){this.peerId=t,this.network=n,this.refcnt=1,this._entries=[],this._log=ae(e,"msgqueue"),this.sendEntries=da(this.sendEntries.bind(this),ha)}addMessage(e,t={}){e.empty||this.send(e,t)}addEntries(e,t={}){this._entries=this._entries.concat(e),this.sendEntries(t)}sendEntries(e={}){if(this._entries.length===0)return;let t=new B(!1);this._entries.forEach(n=>{n.cancel===!0?t.cancel(n.cid):t.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(t,e)}async send(e,t={}){try{await this.network.connectTo(this.peerId,t)}catch(n){this._log.error("cant connect to peer %p: %s",this.peerId,n.message);return}this._log("sending message to peer %p",this.peerId),this.network.sendMessage(this.peerId,e,t).catch(n=>{this._log.error("send error",n)})}};var Pr=class{constructor(e,t,n,i){this.peers=Fe({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new ke(n,i),this.network=t,this._peerId=e,this._log=ae(e,"want")}_addEntries(e,t,n,i={}){let o=e.map((s,a)=>new B.Entry(s,la-a,B.WantType.Block,t));o.forEach(s=>{s.cancel?n===!0?this.wantlist.removeForce(s.cid.toString(E)):this.wantlist.remove(s.cid):(this._log("adding to wantlist"),this.wantlist.add(s.cid,s.priority))});for(let s of this.peers.values())s.addEntries(o,i)}_startPeerHandler(e){let t=this.peers.get(e.toString());if(t!=null){t.refcnt++;return}t=new Lr(this._peerId,e,this.network);let n=new B(!0);for(let i of this.wantlist.entries())n.addEntry(i[1].cid,i[1].priority);return t.addMessage(n),this.peers.set(e.toString(),t),t}_stopPeerHandler(e){let t=this.peers.get(e.toString());t!=null&&(t.refcnt--,!(t.refcnt>0)&&this.peers.delete(e.toString()))}wantBlocks(e,t={}){this._addEntries(e,!1,!1,t),t.signal?.addEventListener("abort",()=>{this.cancelWants(e)})}unwantBlocks(e){this._log("unwant blocks: %s",e.length),this._addEntries(e,!0,!0)}cancelWants(e){this._log("cancel wants: %s",e.length),this._addEntries(e,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(e){this._startPeerHandler(e)}disconnected(e){this._stopPeerHandler(e)}start(){}stop(){this.peers.forEach(e=>{this.disconnected(e.peerId)})}};function tt(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Ee(r=0){return globalThis.Buffer?.alloc!=null?tt(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function pe(r=0){return globalThis.Buffer?.allocUnsafe!=null?tt(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function mi(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=pe(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return tt(t)}var ma=Symbol.for("@achingbrain/uint8arraylist");function pa(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 Ir(r){return!!r?.[ma]}var _e=class{constructor(...e){Object.defineProperty(this,ma,{value:!0}),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(Ir(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ir(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=pa(this.bufs,e);return t.buf[t.index]}set(e,t){let n=pa(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(Ir(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 mi(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:mi(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new _e;return o.length=i,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=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(s);break}let h=e-a;n.push(s.subarray(h,h+(t-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ir(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 o=256,s=new Int32Array(o);for(let h=0;h<o;h++)s[h]=-1;for(let h=0;h<i;h++)s[n[h]]=h;let a=s,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let h=t;h<=c;h+=l){l=0;for(let d=u;d>=0;d--){let v=this.get(h+d);if(n[d]!==v){l=Math.max(1,d-a[v]);break}}if(l===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=pe(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=Ee(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=Ee(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=Ee(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=pe(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=Ee(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=Ee(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=Ee(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=Ee(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=Ee(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof _e)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ge(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new _e;return n.bufs=e,t==null&&(t=e.reduce((i,o)=>i+o.byteLength,0)),n.length=t,n}};function Nr(r){return r instanceof Uint8Array?{get(e){return r[e]},set(e,t){r[e]=t}}:{get(e){return r.get(e)},set(e,t){r.set(e,t)}}}var ya=4294967296,X=class{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(e===!0)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)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),t=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new X(n,t)}zzEncode(){let e=this.hi>>31,t=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new X(t,n)}toBytes(e,t=0){let n=Nr(e);for(;this.hi>0;)n.set(t++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(t++,this.lo&127|128),this.lo=this.lo>>>7;n.set(t++,this.lo)}static fromBigInt(e){if(e===0n)return new X;let t=e<0;t&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return t&&(n=~n>>>0,i=~i>>>0,++i>ya&&(i=0,++n>ya&&(n=0))),new X(n,i)}static fromNumber(e){if(e===0)return new X;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 X(i,n)}static fromBytes(e,t=0){let n=Nr(e),i=new X,o=0;if(e.length-t>4){for(;o<4;++o)if(i.lo=(i.lo|(n.get(t)&127)<<o*7)>>>0,n.get(t++)<128)return i;if(i.lo=(i.lo|(n.get(t)&127)<<28)>>>0,i.hi=(i.hi|(n.get(t)&127)>>4)>>>0,n.get(t++)<128)return i;o=0}else for(;o<4;++o){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(n.get(t)&127)<<o*7)>>>0,n.get(t++)<128)return i}if(e.length-t>4){for(;o<5;++o)if(i.hi=(i.hi|(n.get(t)&127)<<o*7+3)>>>0,n.get(t++)<128)return i}else if(t<e.byteLength)for(;o<5;++o){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(n.get(t)&127)<<o*7+3)>>>0,n.get(t++)<128)return i}throw RangeError("invalid varint encoding")}};var jf=Math.pow(2,7),Gf=Math.pow(2,14),Qf=Math.pow(2,21),Kf=Math.pow(2,28),Xf=Math.pow(2,35),Jf=Math.pow(2,42),Zf=Math.pow(2,49),Yf=Math.pow(2,56),eh=Math.pow(2,63),rt={encodingLength(r){return r<jf?1:r<Gf?2:r<Qf?3:r<Kf?4:r<Xf?5:r<Jf?6:r<Zf?7:r<Yf?8:r<eh?9:10},encode(r,e,t=0){if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=pe(rt.encodingLength(r))),X.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return X.fromBytes(r,e).toNumber(!0)}};function Dr(r){return r[Symbol.asyncIterator]!=null}var Mr=r=>{let e=rt.encodingLength(r),t=pe(e);return rt.encode(r,t),Mr.bytes=e,t};Mr.bytes=0;function Fr(r,e){e=e??{};let t=e.lengthEncoder??Mr;function*n(i){let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Dr(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}Fr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Mr;return new _e(t(r.byteLength),r)};var _t=U(Or(),1);var rh=8,nh=1024*1024*4,nt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(nt||(nt={}));var yi=r=>{let e=rt.decode(r);return yi.bytes=rt.encodingLength(e),e};yi.bytes=0;function qt(r,e){let t=new _e,n=nt.LENGTH,i=-1,o=e?.lengthDecoder??yi,s=e?.maxLengthLength??rh,a=e?.maxDataLength??nh;function*c(){for(;t.byteLength>0;){if(n===nt.LENGTH)try{if(i=o(t),i<0)throw(0,_t.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,_t.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;t.consume(u),e?.onLength!=null&&e.onLength(i),n=nt.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>s)throw(0,_t.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===nt.DATA){if(t.byteLength<i)break;let u=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(u),yield u,n=nt.LENGTH}}}return Dr(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,_t.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,_t.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}qt.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:o,value:s}=await r.next(t);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}}();return qt(n,{...e??{},onLength:o=>{t=o}})};var Ur=class{constructor(e){if(!(e>0)||e-1&e)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}},vt=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ur(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 Ur(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()}};function xt(r={}){return oh(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 oh(r,e){e=e??{};let t=e.onEnd,n=new vt,i,o,s,a=async()=>n.isEmpty()?s?{done:!0}:await new Promise((g,k)=>{o=I=>{o=null,n.push(I);try{g(r(n))}catch(O){k(O)}return i}}):r(n),c=g=>o!=null?o(g):(n.push(g),i),u=g=>(n=new vt,o!=null?o({error:g}):(n.push({error:g}),i)),l=g=>{if(s)return i;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:g})},h=g=>s?i:(s=!0,g!=null?u(g):c({done:!0})),d=()=>(n=new vt,h(),{done:!0}),v=g=>(h(g),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:d,throw:v,push:l,end:h,get readableLength(){return n.size}},t==null)return i;let y=i;return i={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(g){return y.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return y.end(g),t!=null&&(t(g),t=void 0),i},get readableLength(){return y.readableLength}},i}function sh(r){return r[Symbol.asyncIterator]!=null}function ah(...r){let e=[];for(let t of r)sh(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=xt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let i of n)t.push(i)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Rr=ah;function wi(r,...e){if(r==null)throw new Error("Empty pipeline");if(gi(r)){let n=r;r=()=>n.source}else if(_a(r)||ba(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&gi(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)gi(t[n])&&(t[n]=uh(t[n]));return ch(...t)}var ch=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},ba=r=>r?.[Symbol.asyncIterator]!=null,_a=r=>r?.[Symbol.iterator]!=null,gi=r=>r==null?!1:r.sink!=null&&r.source!=null,uh=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=xt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let i,o=r.source;if(ba(o))i=async function*(){yield*o,n.end()};else if(_a(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Rr(n,i())}return r.source};var bi=Symbol.for("@libp2p/topology");var va=()=>{},_i=class{constructor(e){this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??va,this.onDisconnect=e.onDisconnect??va}get[Symbol.toStringTag](){return bi.toString()}get[bi](){return!0}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};function xa(r){return new _i(r)}var Ia=U(Ca(),1);var jt=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function La(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Pa(r,e,t){let n=t??{},i=La(r);async function*o(){let s,a=()=>{s?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:h}=n;throw new jt(l,h)}let u=new Promise((l,h)=>{s=()=>{let{abortMessage:d,abortCode:v}=n;h(new jt(d,v))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&await n.onAbort(r),typeof i.return=="function")try{let h=i.return();h instanceof Promise&&h.catch(d=>{n.onReturnError!=null&&n.onReturnError(d)})}catch(h){n.onReturnError!=null&&n.onReturnError(h)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}var C=class extends Event{constructor(e,t){super(e),this.detail=t}};function hh(r){return r[Symbol.asyncIterator]!=null}function dh(r,e){return hh(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 kt=dh;async function Gt(r){for await(let e of r);}function ph(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 Et=ph;function mh(r){return r[Symbol.asyncIterator]!=null}function yh(r,e){if(mh(r))return async function*(){for await(let a of r)yield e(a)}();let t=Et(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of t)yield e(a)}();let s=e;return function*(){yield o;for(let a of t)yield s(a)}()}var xi=yh;var ki="/ipfs/bitswap/1.0.0",Ei="/ipfs/bitswap/1.1.0",Si="/ipfs/bitswap/1.2.0",wh=32,bh=128,_h=3e4,$r=class{constructor(e,t,n,i={}){this._log=ae(e.peerId,"network"),this._libp2p=e,this._bitswap=t,this._protocols=[ki],i.b100Only!==!0&&(this._protocols.unshift(Ei),this._protocols.unshift(Si)),this._stats=n,this._running=!1,this._onPeerConnect=this._onPeerConnect.bind(this),this._onPeerDisconnect=this._onPeerDisconnect.bind(this),this._onConnection=this._onConnection.bind(this),this._hashLoader=i.hashLoader??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=i.maxInboundStreams??wh,this._maxOutboundStreams=i.maxOutboundStreams??bh,this._incomingStreamTimeout=i.incomingStreamTimeout??_h}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let e=xa({onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect});this._registrarIds=[];for(let t of this._protocols)this._registrarIds.push(await this._libp2p.register(t,e));this._libp2p.getConnections().forEach(t=>{this._onPeerConnect(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=[]}}_onConnection(e){if(!this._running)return;let{stream:t,connection:n}=e,i=new Ia.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",t.stat.protocol,n.remotePeer),await wi(Pa(t.source,i.signal),o=>qt(o),async o=>{for await(let s of o){try{let a=await B.deserialize(s.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,a)}catch(a){this._bitswap._receiveError(a);break}i.reset()}})}).catch(o=>{this._log(o),t.abort(o)}).finally(()=>{i.clear(),t.close()})}_onPeerConnect(e){this._bitswap._onPeerConnected(e)}_onPeerDisconnect(e){this._bitswap._onPeerDisconnected(e)}findProviders(e,t={}){return t.onProgress?.(new C("bitswap:network:find-providers",e)),this._libp2p.contentRouting.findProviders(e,t)}async findAndConnect(e,t){await Gt(kt(xi(this.findProviders(e,t),async n=>await this.connectTo(n.id,t).catch(i=>{this._log.error(i)})),3)).catch(n=>{this._log.error(n)})}async provide(e,t={}){t.onProgress?.(new C("bitswap:network:provide",e)),await this._libp2p.contentRouting.provide(e,t)}async sendMessage(e,t,n={}){if(!this._running)throw new Error("network isn't running");let i=e.toString();this._log("sendMessage to %s",i,t),n.onProgress?.(new C("bitswap:network:send-wantlist",e)),await this._writeMessage(e,t,n),this._updateSentStats(e,t.blocks)}async connectTo(e,t={}){if(!this._running)throw new Error("network isn't running");return t.onProgress?.(new C("bitswap:network:dial",e)),await this._libp2p.dial(e,t)}_updateSentStats(e,t){let n=e.toString();if(this._stats!=null){for(let i of t.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",t.size)}}async _writeMessage(e,t,n={}){let i=await this._libp2p.dialProtocol(e,[Si,Ei,ki]);try{let o;switch(i.stat.protocol){case ki:o=t.serializeToBitswap100();break;case Ei:case Si:o=t.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${i.stat.protocol}`)}await wi([o],s=>Fr(s),i)}catch(o){n.onProgress?.(new C("bitswap:network:send-wantlist:error",{peer:e,error:o})),this._log(o)}finally{i.close()}}};var Wr=class{constructor(e){this.partner=e,this.wantlist=new ke,this.exchangeCount=0,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=e}wants(e,t,n){this.wantlist.add(e,t,n)}cancelWant(e){this.wantlist.remove(e)}wantlistContains(e){return this.wantlist.get(e)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var Qt=class extends Map{constructor(e,t){super(),this._cmp=t??this._defaultSort,this._keys=[];for(let[n,i]of e??[])this.set(n,i)}update(e){if(e<0||e>=this._keys.length)return;let t=this._keys[e];this._keys.splice(e,1);let n=this._find(t);this._keys.splice(n,0,t)}set(e,t){if(this.has(e)){let i=this.indexOf(e);this._keys.splice(i,1)}super.set(e,t);let n=this._find(e);return this._keys.splice(n,0,e),this}clear(){super.clear(),this._keys=[]}delete(e){if(!this.has(e))return!1;let t=this.indexOf(e);return this._keys.splice(t,1),super.delete(e)}indexOf(e){if(!this.has(e))return-1;let t=this._find(e);if(this._keys[t]===e)return t;for(let n=1;n<this._keys.length;n++){if(this._keys[t+n]===e)return t+n;if(this._keys[t-n]===e)return t-n}return-1}_find(e){let t=0,n=this._keys.length;for(;t<n;){let i=t+n>>>1,o=this._kCmp(this._keys[i],e);if(o<0)t=i+1;else if(o>0)n=i;else return i}return t}*keys(){for(let e of this._keys)yield e}*values(){for(let e of this._keys)yield this.get(e)}*entries(){for(let e of this._keys)yield[e,this.get(e)]}*[Symbol.iterator](){yield*this.entries()}forEach(e,t=this){if(e!=null)for(let n of this._keys){let i=this.get(n);if(i==null)throw new Error("Value cannot be undefined");e.apply(t,[[n,i]])}}_defaultSort(e,t){return e[0]<t[0]?-1:t[0]<e[0]?1:0}_kCmp(e,t){return this._cmp([e,this.get(e)],[t,this.get(t)])}};var vh={hasNewInfo(){return!1},merge(){}},Hr=class{constructor(e=vh){this._taskMerger=e,this._byPeer=new Qt([],qr.compare)}pushTasks(e,t){let n=this._byPeer.get(e.toString());n==null&&(n=new qr(e,this._taskMerger)),n.pushTasks(t),this._byPeer.set(e.toString(),n)}popTasks(e){let t=this._head();if(t===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:i}=t.popTasks(e);if(n.length===0)return{tasks:n,pendingSize:i};let o=t.peerId;return t.isIdle()?this._byPeer.delete(o.toString()):this._byPeer.update(0),{peerId:o,tasks:n,pendingSize:i}}_head(){if(this._byPeer.size!==0)for(let[,e]of this._byPeer)return e}remove(e,t){this._byPeer.get(t.toString())?.remove(e)}tasksDone(e,t){let n=this._byPeer.get(e.toString());if(n==null)return;let i=this._byPeer.indexOf(e.toString());for(let o of t)n.taskDone(o);this._byPeer.update(i)}},qr=class{constructor(e,t){this.peerId=e,this._taskMerger=t,this._activeTotalSize=0,this._pending=new Ti,this._active=new Set}pushTasks(e){for(let t of e)this._pushTask(t)}_pushTask(e){if(!this._taskHasMoreInfoThanActiveTasks(e))return;let t=this._pending.get(e.topic);if(t!=null){e.priority>t.priority&&this._pending.updatePriority(e.topic,e.priority),this._taskMerger.merge(e,t);return}this._pending.add(e)}_taskHasMoreInfoThanActiveTasks(e){let t=[];for(let n of this._active)n.topic===e.topic&&t.push(n);return t.length===0?!0:this._taskMerger.hasNewInfo(e,t)}popTasks(e){let t=0,n=[],i=this._pending.tasks();for(let o=0;o<i.length&&t<e;o++){let s=i[o];n.push(s),t+=s.size,this._pending.delete(s.topic),this._activeTotalSize+=s.size,this._active.add(s)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(e){this._active.has(e)&&(this._activeTotalSize-=e.size,this._active.delete(e))}remove(e){this._pending.delete(e)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(e,t){return e[1]._pending.length===0?1:t[1]._pending.length===0?-1:e[1]._activeTotalSize===t[1]._activeTotalSize?t[1]._pending.length-e[1]._pending.length:e[1]._activeTotalSize-t[1]._activeTotalSize}},Ti=class{constructor(){this._tasks=new Qt([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((e,t)=>e+t.task.size,0)}get(e){return this._tasks?.get(e)?.task}add(e){this._tasks.set(e.topic,{created:Date.now(),task:e})}delete(e){this._tasks.delete(e)}tasks(){return[...this._tasks.values()].map(e=>e.task)}updatePriority(e,t){let n=this._tasks.get(e);if(n==null)return;let i=this._tasks.indexOf(e);n.task.priority=t,this._tasks.update(i)}_compare(e,t){return e[1].task.priority===t[1].task.priority?e[1].created-t[1].created:t[1].task.priority-e[1].task.priority}};var Na={hasNewInfo(r,e){let t=!1,n=!1;for(let i of e)i.data.haveBlock&&(t=!0),i.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!t&&r.data.haveBlock)},merge(r,e){let t=r.data,n=e.data;!n.haveBlock&&t.haveBlock&&(n.haveBlock=t.haveBlock,n.blockSize=t.blockSize),!n.isWantBlock&&t.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||t.haveBlock)&&(n.haveBlock=t.haveBlock,e.size=r.size)),n.isWantBlock&&n.haveBlock&&(e.size=n.blockSize)}};var Da=B.WantType,xh=16*1024,kh=1024,Vr=class{constructor(e,t,n,i,o,s={}){this._log=ae(e,"engine"),this.blockstore=t,this.network=n,this._stats=i,this._opts=this._processOpts(s),this.ledgerMap=Fe({name:"ipfs_bitswap_ledger_map",metrics:o.metrics}),this._running=!1,this._requestQueue=new Hr(Na)}_processOpts(e){return{maxSizeReplaceHasWithBlock:kh,targetMessageSize:xh,...e}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(e=>{this._log.error("error processing stats",e)})})}async _processTasks(){if(!this._running)return;let{peerId:e,tasks:t,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(t.length===0)return;let i=new B(!1);i.setPendingBytes(n);let o=[],s=new Map;for(let c of t){let u=x.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(o.push(u),s.set(c.topic,c.data)):i.addHave(u):i.addDontHave(u)}let a=await this._getBlocks(o);for(let[c,u]of s){let l=x.parse(c),h=a.get(c);h!=null?i.addBlock(l,h):u.sendDontHave&&i.addDontHave(l)}if(i.empty){e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks();return}try{e!=null&&await this.network.sendMessage(e,i);for(let[c,u]of a.entries())e!=null&&this.messageSent(e,x.parse(c),u)}catch(c){this._log.error(c)}e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks()}wantlistForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.partner)}receivedBlocks(e){if(e.length!==0){for(let t of this.ledgerMap.values())for(let{cid:n,block:i}of e){let o=t.wantlistContains(n);if(o==null)continue;let s=i.length,a=this._sendAsBlock(o.wantType,s),c=s;a||(c=B.blockPresenceSize(o.cid)),this._requestQueue.pushTasks(t.partner,[{topic:o.cid.toString(E),priority:o.priority,size:c,data:{blockSize:s,isWantBlock:a,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(e,t){let n=this._findOrCreate(e);if(t.empty)return;if(t.full&&(n.wantlist=new ke),this._updateBlockAccounting(t.blocks,n),t.wantlist.size===0){this._scheduleProcessTasks();return}let i=[],o=[];t.wantlist.forEach(s=>{s.cancel?(n.cancelWant(s.cid),i.push(s.cid)):(n.wants(s.cid,s.priority,s.wantType),o.push(s))}),this._cancelWants(e,i),await this._addWants(e,o),this._scheduleProcessTasks()}_cancelWants(e,t){for(let n of t)this._requestQueue.remove(n.toString(E),e)}async _addWants(e,t){let n=await this._getBlockSizes(t.map(o=>o.cid)),i=[];for(let o of t){let s=o.cid.toString(E),a=n.get(s);if(a==null)o.sendDontHave&&i.push({topic:s,priority:o.priority,size:B.blockPresenceSize(o.cid),data:{isWantBlock:o.wantType===Da.Block,blockSize:0,haveBlock:!1,sendDontHave:o.sendDontHave}});else{let c=this._sendAsBlock(o.wantType,a),u=a;c||(u=B.blockPresenceSize(o.cid)),i.push({topic:s,priority:o.priority,size:u,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:o.sendDontHave}})}this._requestQueue.pushTasks(e,i)}}_sendAsBlock(e,t){return e===Da.Block||t<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(e){let t=await this._getBlocks(e);return new Map([...t].map(([n,i])=>[n,i.length]))}async _getBlocks(e){let t=new Map;return await Promise.all(e.map(async n=>{try{let i=await this.blockstore.get(n);t.set(n.toString(E),i)}catch(i){i.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,i)}})),t}_updateBlockAccounting(e,t){for(let n of e.values())this._log("got block (%s bytes)",n.length),t.receivedBytes(n.length)}messageSent(e,t,n){let i=this._findOrCreate(e);i.sentBytes(n.length),i.wantlist.remove(t)}numBytesSentTo(e){return this._findOrCreate(e).accounting.bytesSent}numBytesReceivedFrom(e){return this._findOrCreate(e).accounting.bytesRecv}peerDisconnected(e){this.ledgerMap.delete(e.toString())}_findOrCreate(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return n;let i=new Wr(e);return this.ledgerMap.set(t,i),this._stats!=null&&this._stats.push(t,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var Xa=U(Qr(),1);var Bi={};V(Bi,{identity:()=>Lh});var Lh=dt({prefix:"\0",name:"identity",encode:r=>Ao(r),decode:r=>To(r)});var Ci={};V(Ci,{base2:()=>Ph});var Ph=D({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Li={};V(Li,{base8:()=>Ih});var Ih=D({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Pi={};V(Pi,{base10:()=>Nh});var Nh=Ie({prefix:"9",name:"base10",alphabet:"0123456789"});var Ii={};V(Ii,{base16:()=>Dh,base16upper:()=>Mh});var Dh=D({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Mh=D({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ni={};V(Ni,{base36:()=>Kt,base36upper:()=>Fh});var Kt=Ie({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Fh=Ie({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Di={};V(Di,{base256emoji:()=>$h});var Va=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}"),Oh=Va.reduce((r,e,t)=>(r[t]=e,r),[]),Uh=Va.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Rh(r){return r.reduce((e,t)=>(e+=Oh[t],e),"")}function zh(r){let e=[];for(let t of r){let n=Uh[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var $h=dt({prefix:"\u{1F680}",name:"base256emoji",encode:Rh,decode:zh});var Kr=85;var Mg=new TextEncoder,Fg=new TextDecoder;var Fi={...Bi,...Ci,...Li,...Pi,...Ii,...Vn,...Ni,...qn,...Xn,...Di},$g={...Rn,...Mn};function Ga(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ja=Ga("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Oi=Ga("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=pe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Hh={utf8:ja,"utf-8":ja,hex:Fi.base16,latin1:Oi,ascii:Oi,binary:Oi,...Fi},Xr=Hh;function it(r,e="utf8"){let t=Xr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var Qa=r=>`unwant:${it(r.multihash.bytes,"base64")}`,Ka=r=>`block:${it(r.multihash.bytes,"base64")}`,Jr=class extends Xa.EventEmitter{constructor(e){super(),this.setMaxListeners(fa),this._log=ae(e,"notif")}hasBlock(e,t){let n=Ka(e);this._log(n),this.emit(n,t)}async wantBlock(e,t={}){if(e==null)throw new Error("Not a valid cid");let n=Ka(e),i=Qa(e);return this._log(`wantBlock:${e}`),await new Promise((o,s)=>{let a=()=>{this.removeListener(n,c),t.onProgress?.(new C("bitswap:want-block:unwant",e)),s(new Error(`Block for ${e} unwanted`))},c=u=>{this.removeListener(i,a),t.onProgress?.(new C("bitswap:want-block:block",e)),o(u)};this.once(i,a),this.once(n,c),t.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),s(new Error(`Want for ${e} aborted`))})})}unwantBlock(e){let t=Qa(e);this._log(t),this.emit(t)}};var rc=U(Qr(),1);var ec=U(Qr(),1),Ui=U(Ya(),1),Xt=class extends ec.EventEmitter{constructor(e,t){super(),this._options=t,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),e.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(i=>{(this._movingAverages[n][i]=(0,Ui.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}stop(){this._timeout!=null&&clearTimeout(this._timeout)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}push(e,t){this._enabled&&(this._queue.push([e,t,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout!=null&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let e=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-e),0)}_update(){if(this._timeout=void 0,this._queue.length>0){let e;for(;this._queue.length>0;){let t=e=this._queue.shift();t!=null&&this._applyOp(t)}e!=null&&this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let t=e-this._frequencyLastTime;t>0&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,t,e)}),this._frequencyLastTime=e}_updateFrequencyFor(e,t,n){let i=this._frequencyAccumulators[e]??0;this._frequencyAccumulators[e]=0;let o=i/t*1e3,s=this._movingAverages[e];s==null&&(s=this._movingAverages[e]={}),this._options.movingAverageIntervals.forEach(a=>{let c=s[a];c==null&&(c=s[a]=(0,Ui.default)(a)),c.push(n,o)})}_applyOp(e){let t=e[0],n=e[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,t)||(this._stats[t]=BigInt(0)),this._stats[t]=BigInt(this._stats[t])+BigInt(n),this._frequencyAccumulators[t]==null&&(this._frequencyAccumulators[t]=0),this._frequencyAccumulators[t]+=n}};var tc={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},Zr=class extends rc.EventEmitter{constructor(e,t=[],n=tc){super();let i=Object.assign({},tc,n);if(typeof i.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof i.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=t,this._options=i,this._enabled=this._options.enabled,this._global=new Xt(t,i),this._global.on("update",o=>this.emit("update",o)),this._peers=Fe({name:"ipfs_bitswap_stats_peers",metrics:e.metrics})}enable(){this._enabled=!0,this._options.enabled=!0,this._global.enable()}disable(){this._enabled=!1,this._options.enabled=!1,this._global.disable()}stop(){this._enabled=!1,this._global.stop();for(let e of this._peers)e[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(e){let t=e.toString();return this._peers.get(t)}push(e,t,n){if(this._enabled&&(this._global.push(t,n),e!=null)){let i=this._peers.get(e);i==null&&(i=new Xt(this._initialCounters,this._options),this._peers.set(e,i)),i.push(t,n)}}disconnected(e){let t=e.toString(),n=this._peers.get(t);n!=null&&(n.stop(),this._peers.delete(t))}};var oc=U(ic(),1);function Vh(r){return r[Symbol.asyncIterator]!=null}function jh(r,e){if(Vh(r))return async function*(){for await(let a of r)await e(a),yield a}();let t=Et(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();if(typeof e(n)?.then=="function")return async function*(){yield n;for await(let a of t)await e(a),yield a}();let s=e;return function*(){yield n;for(let a of t)s(a),yield a}()}var Jt=jh;var Gh={async getHasher(){throw new Error("Not implemented")}},Qh={maxInboundStreams:32,maxOutboundStreams:128,incomingStreamTimeout:3e4,hashLoader:Gh,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},Kh=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],Yr=class{constructor(e,t,n={}){this._libp2p=e,this._log=ae(this.peerId),this._options=Object.assign({},Qh,n),this.stats=new Zr(e,Kh,{enabled:this._options.statsEnabled,computeThrottleTimeout:this._options.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:this._options.statsComputeThrottleMaxQueueSize}),this.network=new $r(e,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=t,this.engine=new Vr(this.peerId,t,this.network,this.stats,e),this.wm=new Pr(this.peerId,this.network,this.stats,e),this.notifications=new Jr(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(e,t){try{await this.engine.messageReceived(e,t)}catch{this._log("failed to receive message",t)}if(t.blocks.size===0)return;let n=[];for(let[i,o]of t.blocks.entries()){let s=x.parse(i);n.push({wasWanted:this.wm.wantlist.contains(s),cid:s,data:o})}this.wm.cancelWants(n.filter(({wasWanted:i})=>i).map(({cid:i})=>i)),await Promise.all(n.map(async({cid:i,wasWanted:o,data:s})=>{await this._handleReceivedBlock(e,i,s,o)}))}async _handleReceivedBlock(e,t,n,i){this._log("received block");let o=await this.blockstore.has(t);this._updateReceiveCounters(e.toString(),t,n,o),i&&await this.put(t,n)}_updateReceiveCounters(e,t,n,i){this.stats.push(e,"blocksReceived",1),this.stats.push(e,"dataReceived",n.length),i&&(this.stats.push(e,"dupBlksReceived",1),this.stats.push(e,"dupDataReceived",n.length))}_receiveError(e){this._log.error("ReceiveError",e)}_onPeerConnected(e){this.wm.connected(e)}_onPeerDisconnected(e){this.wm.disconnected(e),this.engine.peerDisconnected(e),this.stats.disconnected(e)}enableStats(){this.stats.enable()}disableStats(){this.stats.disable()}wantlistForPeer(e,t){return this.engine.wantlistForPeer(e)}ledgerForPeer(e){return this.engine.ledgerForPeer(e)}async want(e,t={}){let n=async(c,u)=>(this.wm.wantBlocks([c],u),await this.notifications.wantBlock(c,u)),i=!1,o=async(c,u)=>{try{return await this.blockstore.get(c,u)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l;return i||(i=!0,this.network.findAndConnect(c,u).catch(h=>{this._log.error(h)})),await n(c,u)}},s=new AbortController,a=t.signal!=null?(0,oc.anySignal)([t.signal,s.signal]):s.signal;try{return await Promise.race([this.notifications.wantBlock(e,{...t,signal:a}),o(e,{...t,signal:a})])}finally{s.abort()}}unwant(e){let t=Array.isArray(e)?e:[e];this.wm.unwantBlocks(t),t.forEach(n=>{this.notifications.unwantBlock(n)})}cancelWants(e){this.wm.cancelWants(Array.isArray(e)?e:[e])}async put(e,t,n){await this.blockstore.put(e,t),this.notify(e,t)}async*putMany(e,t){yield*this.blockstore.putMany(Jt(e,({cid:n,block:i})=>{this.notify(n,i)}),t)}notify(e,t,n={}){this.notifications.hasBlock(e,t),this.engine.receivedBlocks([{cid:e,block:t}]),this.network.provide(e,n).catch(i=>{this._log.error("Failed to provide: %s",i.message)})}getWantlist(){return this.wm.wantlist.entries()}get peers(){return this.engine.peers()}async start(){this.wm.start(),await this.network.start(),this.engine.start(),this.started=!0}async stop(){this.stats.stop(),this.wm.stop(),await this.network.stop(),this.engine.stop(),this.started=!1}};var sc=(r,e,t={})=>new Yr(r,e,t);async function*zi(r,e){for await(let t of r)await e(t)&&(yield t)}var gc=U(cc(),1);var Yt=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Wi=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},uc=r=>globalThis.DOMException===void 0?new Wi(r):new DOMException(r),lc=r=>{let e=r.reason===void 0?uc("This operation was aborted."):r.reason;return e instanceof Error?e:uc(e)};function Hi(r,e,t,n){let i,o=new Promise((s,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(lc(c)),c.addEventListener("abort",()=>{a(lc(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{s(t())}catch(l){a(l)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new Yt(c);typeof r.cancel=="function"&&r.cancel(),a(u)},e),(async()=>{try{s(await r)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return o.clear=()=>{clearTimeout(i),i=void 0},o}function qi(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var ot=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Se,er=class{constructor(){Se.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&ot(this,Se,"f")[this.size-1].priority>=t.priority){ot(this,Se,"f").push(n);return}let i=qi(ot(this,Se,"f"),n,(o,s)=>s.priority-o.priority);ot(this,Se,"f").splice(i,0,n)}dequeue(){let e=ot(this,Se,"f").shift();return e?.run}filter(e){return ot(this,Se,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return ot(this,Se,"f").length}};Se=new WeakMap;var N=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},b=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},F,rr,nr,Ue,an,ir,tn,me,tr,J,rn,Z,or,Oe,nn,fc,hc,mc,dc,pc,on,Vi,ji,cn,yc,sn,un=class extends Error{},Te=class extends gc.default{constructor(e){var t,n,i,o;if(super(),F.add(this),rr.set(this,void 0),nr.set(this,void 0),Ue.set(this,0),an.set(this,void 0),ir.set(this,void 0),tn.set(this,0),me.set(this,void 0),tr.set(this,void 0),J.set(this,void 0),rn.set(this,void 0),Z.set(this,0),or.set(this,void 0),Oe.set(this,void 0),nn.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:er,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);N(this,rr,e.carryoverConcurrencyCount,"f"),N(this,nr,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),N(this,an,e.intervalCap,"f"),N(this,ir,e.interval,"f"),N(this,J,new e.queueClass,"f"),N(this,rn,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,N(this,nn,e.throwOnTimeout===!0,"f"),N(this,Oe,e.autoStart===!1,"f")}get concurrency(){return b(this,or,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);N(this,or,e,"f"),b(this,F,"m",cn).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:b(this,nn,"f"),...t},new Promise((n,i)=>{b(this,J,"f").enqueue(async()=>{var o,s,a;N(this,Z,(s=b(this,Z,"f"),s++,s),"f"),N(this,Ue,(a=b(this,Ue,"f"),a++,a),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new un("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=Hi(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,b(this,F,"m",yc).call(this,t.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Yt&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{b(this,F,"m",mc).call(this)}},t),this.emit("add"),b(this,F,"m",on).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return b(this,Oe,"f")?(N(this,Oe,!1,"f"),b(this,F,"m",cn).call(this),this):this}pause(){N(this,Oe,!0,"f")}clear(){N(this,J,new(b(this,rn,"f")),"f")}async onEmpty(){b(this,J,"f").size!==0&&await b(this,F,"m",sn).call(this,"empty")}async onSizeLessThan(e){b(this,J,"f").size<e||await b(this,F,"m",sn).call(this,"next",()=>b(this,J,"f").size<e)}async onIdle(){b(this,Z,"f")===0&&b(this,J,"f").size===0||await b(this,F,"m",sn).call(this,"idle")}get size(){return b(this,J,"f").size}sizeBy(e){return b(this,J,"f").filter(e).length}get pending(){return b(this,Z,"f")}get isPaused(){return b(this,Oe,"f")}};rr=new WeakMap,nr=new WeakMap,Ue=new WeakMap,an=new WeakMap,ir=new WeakMap,tn=new WeakMap,me=new WeakMap,tr=new WeakMap,J=new WeakMap,rn=new WeakMap,Z=new WeakMap,or=new WeakMap,Oe=new WeakMap,nn=new WeakMap,F=new WeakSet,fc=function(){return b(this,nr,"f")||b(this,Ue,"f")<b(this,an,"f")},hc=function(){return b(this,Z,"f")<b(this,or,"f")},mc=function(){var e;N(this,Z,(e=b(this,Z,"f"),e--,e),"f"),b(this,F,"m",on).call(this),this.emit("next")},dc=function(){b(this,F,"m",ji).call(this),b(this,F,"m",Vi).call(this),N(this,tr,void 0,"f")},pc=function(){let e=Date.now();if(b(this,me,"f")===void 0){let t=b(this,tn,"f")-e;if(t<0)N(this,Ue,b(this,rr,"f")?b(this,Z,"f"):0,"f");else return b(this,tr,"f")===void 0&&N(this,tr,setTimeout(()=>{b(this,F,"m",dc).call(this)},t),"f"),!0}return!1},on=function(){if(b(this,J,"f").size===0)return b(this,me,"f")&&clearInterval(b(this,me,"f")),N(this,me,void 0,"f"),this.emit("empty"),b(this,Z,"f")===0&&this.emit("idle"),!1;if(!b(this,Oe,"f")){let e=!b(this,F,"a",pc);if(b(this,F,"a",fc)&&b(this,F,"a",hc)){let t=b(this,J,"f").dequeue();return t?(this.emit("active"),t(),e&&b(this,F,"m",Vi).call(this),!0):!1}}return!1},Vi=function(){b(this,nr,"f")||b(this,me,"f")!==void 0||(N(this,me,setInterval(()=>{b(this,F,"m",ji).call(this)},b(this,ir,"f")),"f"),N(this,tn,Date.now()+b(this,ir,"f"),"f"))},ji=function(){b(this,Ue,"f")===0&&b(this,Z,"f")===0&&b(this,me,"f")&&(clearInterval(b(this,me,"f")),N(this,me,void 0,"f")),N(this,Ue,b(this,rr,"f")?b(this,Z,"f"):0,"f"),b(this,F,"m",cn).call(this)},cn=function(){for(;b(this,F,"m",on).call(this););},yc=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new un("The task was aborted."))},{once:!0})})},sn=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};var Gi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Qi=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},wc=r=>globalThis.DOMException===void 0?new Qi(r):new DOMException(r),bc=r=>{let e=r.reason===void 0?wc("This operation was aborted."):r.reason;return e instanceof Error?e:wc(e)};function Ki(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,a=new Promise((c,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){c(r);return}if(e.signal){let{signal:h}=e;h.aborted&&u(bc(h)),h.addEventListener("abort",()=>{u(bc(h))})}let l=new Gi;s=o.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?c():i instanceof Error?u(i):(l.message=i??`Promise timed out after ${t} milliseconds`,u(l))},t),(async()=>{try{c(await r)}catch(h){u(h)}finally{o.clearTimeout.call(void 0,s)}})()});return a.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},a}var _c=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var Xi="lock:worker:request-read",Ji="lock:worker:release-read",Zi="lock:master:grant-read",Yi="lock:worker:request-write",eo="lock:worker:release-write",to="lock:master:grant-write";var Re={},Tt=r=>{r.addEventListener("message",e=>{Tt.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Tt.dispatchEvent("message",r,e)})};Tt.addEventListener=(r,e)=>{Re[r]==null&&(Re[r]=[]),Re[r].push(e)};Tt.removeEventListener=(r,e)=>{Re[r]!=null&&(Re[r]=Re[r].filter(t=>t===e))};Tt.dispatchEvent=function(r,e,t){Re[r]!=null&&Re[r].forEach(n=>n(e,t))};var ro=Tt;var vc=(r,e,t,n,i)=>(o,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(o.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let h={type:l.data.type,name:l.data.name,identifier:l.data.identifier};h.type===n&&h.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)}))}}))},xc=(r,e,t,n)=>async()=>{let i=_c();return globalThis.postMessage({type:e,identifier:i,name:r}),await new Promise(o=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===i&&(globalThis.removeEventListener("message",s),o(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",s)})},Zh={singleProcess:!1},kc=r=>{if(r=Object.assign({},Zh,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return ro.addEventListener("message",vc(t,"requestReadLock",Xi,Ji,Zi)),ro.addEventListener("message",vc(t,"requestWriteLock",Yi,eo,to)),t}return{isWorker:!0,readLock:t=>xc(t,Xi,Zi,Ji),writeLock:t=>xc(t,Yi,to,eo)}};var st={},ze;async function no(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>await Ki((async()=>await new Promise(i=>{t(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var Yh=(r,e)=>{if(ze.isWorker===!0)return{readLock:ze.readLock(r,e),writeLock:ze.writeLock(r,e)};let t=new Te({concurrency:1}),n;return{async readLock(){if(n!=null)return await no(n,e);n=new Te({concurrency:e.concurrency,autoStart:!1});let i=n,o=no(n,e);return t.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await o},async writeLock(){return n=null,await no(t,e)}}},ed={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function io(r){let e=Object.assign({},ed,r);return ze==null&&(ze=kc(e),ze.isWorker!==!0&&(ze.addEventListener("requestReadLock",t=>{st[t.data.name]!=null&&st[t.data.name].readLock().then(async n=>await t.data.handler().finally(()=>n()))}),ze.addEventListener("requestWriteLock",async t=>{st[t.data.name]!=null&&st[t.data.name].writeLock().then(async n=>await t.data.handler().finally(()=>n()))}))),st[e.name]==null&&(st[e.name]=Yh(e.name,e)),st[e.name]}var ln=class{constructor(e,t,n={}){this.child=e,this.bitswap=n.bitswap,this.pins=t,this.lock=io({singleProcess:n.holdGcLock})}unwrap(){return this.child}async put(e,t,n={}){let i=await this.lock.readLock();try{return await this.child.has(e)?(n.onProgress?.(new C("blocks:put:duplicate",e)),e):(this.bitswap?.isStarted()===!0&&(n.onProgress?.(new C("blocks:put:bitswap:notify",e)),this.bitswap.notify(e,t,n)),n.onProgress?.(new C("blocks:put:blockstore:put",e)),await this.child.put(e,t,n))}finally{i()}}async*putMany(e,t={}){let n=await this.lock.readLock();try{let i=zi(e,async({cid:s})=>{let a=await this.child.has(s);return a&&t.onProgress?.(new C("blocks:put-many:duplicate",s)),!a}),o=Jt(i,({cid:s,block:a})=>{t.onProgress?.(new C("blocks:put-many:bitswap:notify",s)),this.bitswap?.notify(s,a,t)});t.onProgress?.(new C("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}finally{n()}}async get(e,t={}){let n=await this.lock.readLock();try{if(this.bitswap?.isStarted()!=null&&!await this.child.has(e)){t.onProgress?.(new C("blocks:get:bitswap:get",e));let i=await this.bitswap.want(e,t);return t.onProgress?.(new C("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),i}return t.onProgress?.(new C("blocks:get:blockstore:get",e)),await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){let n=await this.lock.readLock();try{t.onProgress?.(new C("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Jt(e,async i=>{if(this.bitswap?.isStarted()===!0&&!await this.child.has(i)){t.onProgress?.(new C("blocks:get-many:bitswap:get",i));let o=await this.bitswap.want(i,t);t.onProgress?.(new C("blocks:get-many:blockstore:put",i)),await this.child.put(i,o,t)}}))}finally{n()}}async delete(e,t={}){let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");t.onProgress?.(new C("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){let n=await this.lock.writeLock();try{let i=this;t.onProgress?.(new C("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new Error("CID was pinned");yield o}}(),t)}finally{n()}}async has(e,t={}){let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){let t=await this.lock.readLock();try{e.onProgress?.(new C("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}finally{t()}}};var Ec=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");function fn(r,e="utf8"){let t=Xr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?tt(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var Ae="/",Sc=new TextEncoder().encode(Ae),hn=Sc[0],P=class{constructor(e,t){if(typeof e=="string")this._buf=fn(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==hn)throw new Error("Invalid key")}toString(e="utf8"){return it(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new P(e.join(Ae))}static random(){return new P(Ec().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new P(e):typeof e.uint8Array=="function"?new P(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Sc),this._buf[0]!==hn){let e=new Uint8Array(this._buf.byteLength+1);e.fill(hn,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===hn;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return t.length<n.length}reverse(){return P.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ae).slice(1)}type(){return td(this.baseNamespace())}name(){return rd(this.baseNamespace())}instance(e){return new P(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ae)||(e+=Ae),e+=this.type(),new P(e)}parent(){let e=this.list();return e.length===1?new P(Ae):new P(e.slice(0,-1).join(Ae))}child(e){return this.toString()===Ae?e:e.toString()===Ae?this:new P(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return P.withNamespaces([...this.namespaces(),...nd(e.map(t=>t.namespaces()))])}};function td(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function rd(r){let e=r.split(":");return e[e.length-1]}function nd(r){return[].concat(...r)}var id=["string","number","bigint","symbol"],od=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Tc(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(id.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(sd(r))return"Buffer";let t=ad(r);return t||"Object"}function sd(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function ad(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(od.includes(e))return e}var f=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};f.uint=new f(0,"uint",!0);f.negint=new f(1,"negint",!0);f.bytes=new f(2,"bytes",!0);f.string=new f(3,"string",!0);f.array=new f(4,"array",!1);f.map=new f(5,"map",!1);f.tag=new f(6,"tag",!1);f.float=new f(7,"float",!0);f.false=new f(7,"false",!0);f.true=new f(7,"true",!0);f.null=new f(7,"null",!0);f.undefined=new f(7,"undefined",!0);f.break=new f(7,"break",!0);var p=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var At=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",cd=new TextDecoder,ud=new TextEncoder;function dn(r){return At&&globalThis.Buffer.isBuffer(r)}function sr(r){return r instanceof Uint8Array?dn(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Lc=At?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Bc(r,e,t):(r,e,t)=>t-e>64?cd.decode(r.subarray(e,t)):Bc(r,e,t),pn=At?r=>r.length>64?globalThis.Buffer.from(r):Ac(r):r=>r.length>64?ud.encode(r):Ac(r),ve=r=>Uint8Array.from(r),Bt=At?(r,e,t)=>dn(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Pc=At?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),sr(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},Ic=At?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Nc(r,e){if(dn(r)&&dn(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Ac(r,e=1/0){let t,n=r.length,i=null,o=[];for(let s=0;s<n;++s){if(t=r.charCodeAt(s),t>55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return o}function Bc(r,e,t){let n=[];for(;e<t;){let i=r[e],o=null,s=i>239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(o=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(o=l))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return oo(n)}var Cc=4096;function oo(r){let e=r.length;if(e<=Cc)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Cc));return t}var ld=256,ar=class{constructor(e=ld){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Ic(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Bt(n,0,this.cursor)}else t=Pc(this.chunks,this.cursor);return e&&this.reset(),t}};var w="CBOR decode error:",Ct="CBOR encode error:",cr=[];cr[23]=1;cr[24]=2;cr[25]=3;cr[26]=5;cr[27]=9;function Be(r,e,t){if(r.length-e<t)throw new Error(`${w} not enough data for type`)}var z=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Y(r,e,t){Be(r,e,1);let n=r[e];if(t.strict===!0&&n<z[0])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return n}function ee(r,e,t){Be(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<z[1])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return n}function te(r,e,t){Be(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<z[2])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return n}function re(r,e,t){Be(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&o<z[3])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${w} integers outside of the safe integer range are not supported`)}function Dc(r,e,t,n){return new p(f.uint,Y(r,e+1,n),2)}function Mc(r,e,t,n){return new p(f.uint,ee(r,e+1,n),3)}function Fc(r,e,t,n){return new p(f.uint,te(r,e+1,n),5)}function Oc(r,e,t,n){return new p(f.uint,re(r,e+1,n),9)}function ue(r,e){return W(r,0,e.value)}function W(r,e,t){if(t<z[0]){let n=Number(t);r.push([e|n])}else if(t<z[1]){let n=Number(t);r.push([e|24,n])}else if(t<z[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<z[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<z[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${w} encountered BigInt larger than allowable range`)}}ue.encodedSize=function(e){return W.encodedSize(e.value)};W.encodedSize=function(e){return e<z[0]?1:e<z[1]?2:e<z[2]?3:e<z[3]?5:9};ue.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Uc(r,e,t,n){return new p(f.negint,-1-Y(r,e+1,n),2)}function Rc(r,e,t,n){return new p(f.negint,-1-ee(r,e+1,n),3)}function zc(r,e,t,n){return new p(f.negint,-1-te(r,e+1,n),5)}var so=BigInt(-1),$c=BigInt(1);function Wc(r,e,t,n){let i=re(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new p(f.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${w} integers outside of the safe integer range are not supported`);return new p(f.negint,so-BigInt(i),9)}function mn(r,e){let t=e.value,n=typeof t=="bigint"?t*so-$c:t*-1-1;W(r,e.type.majorEncoded,n)}mn.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*so-$c:t*-1-1;return n<z[0]?1:n<z[1]?2:n<z[2]?3:n<z[3]?5:9};mn.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ur(r,e,t,n){Be(r,e,t+n);let i=Bt(r,e+t,e+t+n);return new p(f.bytes,i,t+n)}function Hc(r,e,t,n){return ur(r,e,1,t)}function qc(r,e,t,n){return ur(r,e,2,Y(r,e+1,n))}function Vc(r,e,t,n){return ur(r,e,3,ee(r,e+1,n))}function jc(r,e,t,n){return ur(r,e,5,te(r,e+1,n))}function Gc(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer bytes lengths not supported`);return ur(r,e,9,i)}function yn(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===f.string?pn(r.value):r.value),r.encodedBytes}function Lt(r,e){let t=yn(e);W(r,e.type.majorEncoded,t.length),r.push(t)}Lt.encodedSize=function(e){let t=yn(e);return W.encodedSize(t.length)+t.length};Lt.compareTokens=function(e,t){return hd(yn(e),yn(t))};function hd(r,e){return r.length<e.length?-1:r.length>e.length?1:Nc(r,e)}function lr(r,e,t,n,i){let o=t+n;Be(r,e,o);let s=new p(f.string,Lc(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=Bt(r,e+t,e+o)),s}function Qc(r,e,t,n){return lr(r,e,1,t,n)}function Kc(r,e,t,n){return lr(r,e,2,Y(r,e+1,n),n)}function Xc(r,e,t,n){return lr(r,e,3,ee(r,e+1,n),n)}function Jc(r,e,t,n){return lr(r,e,5,te(r,e+1,n),n)}function Zc(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer string lengths not supported`);return lr(r,e,9,i,n)}var Yc=Lt;function Pt(r,e,t,n){return new p(f.array,n,t)}function eu(r,e,t,n){return Pt(r,e,1,t)}function tu(r,e,t,n){return Pt(r,e,2,Y(r,e+1,n))}function ru(r,e,t,n){return Pt(r,e,3,ee(r,e+1,n))}function nu(r,e,t,n){return Pt(r,e,5,te(r,e+1,n))}function iu(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer array lengths not supported`);return Pt(r,e,9,i)}function ou(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return Pt(r,e,1,1/0)}function gn(r,e){W(r,f.array.majorEncoded,e.value)}gn.compareTokens=ue.compareTokens;gn.encodedSize=function(e){return W.encodedSize(e.value)};function It(r,e,t,n){return new p(f.map,n,t)}function su(r,e,t,n){return It(r,e,1,t)}function au(r,e,t,n){return It(r,e,2,Y(r,e+1,n))}function cu(r,e,t,n){return It(r,e,3,ee(r,e+1,n))}function uu(r,e,t,n){return It(r,e,5,te(r,e+1,n))}function lu(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer map lengths not supported`);return It(r,e,9,i)}function fu(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return It(r,e,1,1/0)}function wn(r,e){W(r,f.map.majorEncoded,e.value)}wn.compareTokens=ue.compareTokens;wn.encodedSize=function(e){return W.encodedSize(e.value)};function hu(r,e,t,n){return new p(f.tag,t,1)}function du(r,e,t,n){return new p(f.tag,Y(r,e+1,n),2)}function pu(r,e,t,n){return new p(f.tag,ee(r,e+1,n),3)}function mu(r,e,t,n){return new p(f.tag,te(r,e+1,n),5)}function yu(r,e,t,n){return new p(f.tag,re(r,e+1,n),9)}function bn(r,e){W(r,f.tag.majorEncoded,e.value)}bn.compareTokens=ue.compareTokens;bn.encodedSize=function(e){return W.encodedSize(e.value)};var wd=20,bd=21,_d=22,vd=23;function gu(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${w} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new p(f.null,null,1):new p(f.undefined,void 0,1)}function wu(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return new p(f.break,void 0,1)}function ao(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${w} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${w} Infinity values are not supported`)}return new p(f.float,r,e)}function bu(r,e,t,n){return ao(co(r,e+1),3,n)}function _u(r,e,t,n){return ao(uo(r,e+1),5,n)}function vu(r,e,t,n){return ao(Su(r,e+1),9,n)}function _n(r,e,t){let n=e.value;if(n===!1)r.push([f.float.majorEncoded|wd]);else if(n===!0)r.push([f.float.majorEncoded|bd]);else if(n===null)r.push([f.float.majorEncoded|_d]);else if(n===void 0)r.push([f.float.majorEncoded|vd]);else{let i,o=!1;(!t||t.float64!==!0)&&(ku(n),i=co(ye,1),n===i||Number.isNaN(n)?(ye[0]=249,r.push(ye.slice(0,3)),o=!0):(Eu(n),i=uo(ye,1),n===i&&(ye[0]=250,r.push(ye.slice(0,5)),o=!0))),o||(xd(n),i=Su(ye,1),ye[0]=251,r.push(ye.slice(0,9)))}}_n.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){ku(n);let i=co(ye,1);if(n===i||Number.isNaN(n))return 3;if(Eu(n),i=uo(ye,1),n===i)return 5}return 9};var xu=new ArrayBuffer(9),le=new DataView(xu,1),ye=new Uint8Array(xu,0);function ku(r){if(r===1/0)le.setUint16(0,31744,!1);else if(r===-1/0)le.setUint16(0,64512,!1);else if(Number.isNaN(r))le.setUint16(0,32256,!1);else{le.setFloat32(0,r);let e=le.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)le.setUint16(0,31744,!1);else if(t===0)le.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?le.setUint16(0,0):i<-14?le.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):le.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function co(r,e){if(r.length-e<2)throw new Error(`${w} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function Eu(r){le.setFloat32(0,r,!1)}function uo(r,e){if(r.length-e<4)throw new Error(`${w} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function xd(r){le.setFloat64(0,r,!1)}function Su(r,e){if(r.length-e<8)throw new Error(`${w} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}_n.compareTokens=ue.compareTokens;function A(r,e,t){throw new Error(`${w} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function vn(r){return()=>{throw new Error(`${w} ${r}`)}}var m=[];for(let r=0;r<=23;r++)m[r]=A;m[24]=Dc;m[25]=Mc;m[26]=Fc;m[27]=Oc;m[28]=A;m[29]=A;m[30]=A;m[31]=A;for(let r=32;r<=55;r++)m[r]=A;m[56]=Uc;m[57]=Rc;m[58]=zc;m[59]=Wc;m[60]=A;m[61]=A;m[62]=A;m[63]=A;for(let r=64;r<=87;r++)m[r]=Hc;m[88]=qc;m[89]=Vc;m[90]=jc;m[91]=Gc;m[92]=A;m[93]=A;m[94]=A;m[95]=vn("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)m[r]=Qc;m[120]=Kc;m[121]=Xc;m[122]=Jc;m[123]=Zc;m[124]=A;m[125]=A;m[126]=A;m[127]=vn("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)m[r]=eu;m[152]=tu;m[153]=ru;m[154]=nu;m[155]=iu;m[156]=A;m[157]=A;m[158]=A;m[159]=ou;for(let r=160;r<=183;r++)m[r]=su;m[184]=au;m[185]=cu;m[186]=uu;m[187]=lu;m[188]=A;m[189]=A;m[190]=A;m[191]=fu;for(let r=192;r<=215;r++)m[r]=hu;m[216]=du;m[217]=pu;m[218]=mu;m[219]=yu;m[220]=A;m[221]=A;m[222]=A;m[223]=A;for(let r=224;r<=243;r++)m[r]=vn("simple values are not supported");m[244]=A;m[245]=A;m[246]=A;m[247]=gu;m[248]=vn("simple values are not supported");m[249]=bu;m[250]=_u;m[251]=vu;m[252]=A;m[253]=A;m[254]=A;m[255]=wu;var ge=[];for(let r=0;r<24;r++)ge[r]=new p(f.uint,r,1);for(let r=-1;r>=-24;r--)ge[31-r]=new p(f.negint,r,1);ge[64]=new p(f.bytes,new Uint8Array(0),1);ge[96]=new p(f.string,"",1);ge[128]=new p(f.array,0,1);ge[160]=new p(f.map,0,1);ge[244]=new p(f.false,!1,1);ge[245]=new p(f.true,!0,1);ge[246]=new p(f.null,null,1);function Tu(r){switch(r.type){case f.false:return ve([244]);case f.true:return ve([245]);case f.null:return ve([246]);case f.bytes:return r.value.length?void 0:ve([64]);case f.string:return r.value===""?ve([96]):void 0;case f.array:return r.value===0?ve([128]):void 0;case f.map:return r.value===0?ve([160]):void 0;case f.uint:return r.value<24?ve([Number(r.value)]):void 0;case f.negint:if(r.value>=-24)return ve([31-Number(r.value)])}}var Ed={float64:!1,mapSorter:Ad,quickEncodeToken:Tu};function Sd(){let r=[];return r[f.uint.major]=ue,r[f.negint.major]=mn,r[f.bytes.major]=Lt,r[f.string.major]=Yc,r[f.array.major]=gn,r[f.map.major]=wn,r[f.tag.major]=bn,r[f.float.major]=_n,r}var Au=Sd(),lo=new ar,Nt=class{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Ct} object contains circular references`);return new Nt(t,e)}},$e={null:new p(f.null,null),undefined:new p(f.undefined,void 0),true:new p(f.true,!0),false:new p(f.false,!1),emptyArray:new p(f.array,0),emptyMap:new p(f.map,0)},We={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new p(f.float,r):r>=0?new p(f.uint,r):new p(f.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new p(f.uint,r):new p(f.negint,r)},Uint8Array(r,e,t,n){return new p(f.bytes,r)},string(r,e,t,n){return new p(f.string,r)},boolean(r,e,t,n){return r?$e.true:$e.false},null(r,e,t,n){return $e.null},undefined(r,e,t,n){return $e.undefined},ArrayBuffer(r,e,t,n){return new p(f.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new p(f.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[$e.emptyArray,new p(f.break)]:$e.emptyArray;n=Nt.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=xn(s,t,n);return t.addBreakTokens?[new p(f.array,r.length),i,new p(f.break)]:[new p(f.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[$e.emptyMap,new p(f.break)]:$e.emptyMap;n=Nt.createCheck(n,r);let a=[],c=0;for(let u of o)a[c++]=[xn(u,t,n),xn(i?r.get(u):r[u],t,n)];return Td(a,t),t.addBreakTokens?[new p(f.map,s),a,new p(f.break)]:[new p(f.map,s),a]}};We.Map=We.Object;We.Buffer=We.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))We[`${r}Array`]=We.DataView;function xn(r,e={},t){let n=Tc(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||We[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=We[n];if(!o)throw new Error(`${Ct} unsupported type: ${n}`);return o(r,n,e,t)}function Td(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Ad(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=Au[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function Bu(r,e,t,n){if(Array.isArray(e))for(let i of e)Bu(r,i,t,n);else t[e.type.major](r,e,n)}function Cu(r,e,t){let n=xn(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new ar(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return sr(a.chunks[0])}}return lo.reset(),Bu(lo,n,e,t),lo.toBytes(!0)}function kn(r,e){return e=Object.assign({},Ed,e),Cu(r,Au,e)}var Bd={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},fo=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=ge[e];if(t===void 0){let n=m[e];if(!n)throw new Error(`${w} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},fr=Symbol.for("DONE"),En=Symbol.for("BREAK");function Cd(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=hr(e,t);if(o===En){if(r.value===1/0)break;throw new Error(`${w} got unexpected break to lengthed array`)}if(o===fr)throw new Error(`${w} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function Ld(r,e,t){let n=t.useMaps===!0,i=n?void 0:{},o=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=hr(e,t);if(a===En){if(r.value===1/0)break;throw new Error(`${w} got unexpected break to lengthed map`)}if(a===fr)throw new Error(`${w} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${w} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&o.has(a)||!n&&a in i))throw new Error(`${w} found repeat map key "${a}"`);let c=hr(e,t);if(c===fr)throw new Error(`${w} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?o.set(a,c):i[a]=c}return n?o:i}function hr(r,e){if(r.done())return fr;let t=r.next();if(t.type===f.break)return En;if(t.type.terminal)return t.value;if(t.type===f.array)return Cd(t,r,e);if(t.type===f.map)return Ld(t,r,e);if(t.type===f.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=hr(r,e);return e.tags[t.value](n)}throw new Error(`${w} tag not supported (${t.value})`)}throw new Error("unsupported")}function Ce(r,e){if(!(r instanceof Uint8Array))throw new Error(`${w} data to decode must be a Uint8Array`);e=Object.assign({},Bd,e);let t=e.tokenizer||new fo(r,e),n=hr(t,e);if(n===fr)throw new Error(`${w} did not find any content to decode`);if(n===En)throw new Error(`${w} got unexpected break`);if(!t.done())throw new Error(`${w} too many terminals, data makes no sense`);return n}function ho(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Pd=new TextDecoder;function po(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function Sn(r,e){let t;[t,e]=po(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function Pu(r,e){let t;return[t,e]=po(r,e),[t&7,t>>3,e]}function Id(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=Pu(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Sn(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=Sn(r,n),e.Name=Pd.decode(s)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=po(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Iu(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let a,c;if([a,c,t]=Pu(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Sn(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,t]=Sn(r,t),n.push(Id(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var Jb=new TextEncoder,Zb=2**32,Yb=2**31;var r0=new TextEncoder;var Nu=112;function Du(r){let e=Iu(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let i={};try{i.Hash=x.decode(n.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(i.Name=n.Name),n.Tsize!==void 0&&(i.Tsize=n.Tsize),i})),t}var Mu=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===f.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===f.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[f.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[f.negint.major](e,t){this[f.uint.major](e,t)}[f.bytes.major](e,t){throw new Error(`${Ct} unsupported type: Uint8Array`)}[f.string.major](e,t){this.prefix(e);let n=pn(JSON.stringify(t.value));e.push(n.length>32?sr(n):n)}[f.array.major](e,t){this.prefix(e),this.inRecursive.push({type:f.array,elements:0}),e.push([91])}[f.map.major](e,t){this.prefix(e),this.inRecursive.push({type:f.map,elements:0}),e.push([123])}[f.tag.major](e,t){}[f.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===f.array)e.push([93]);else if(s.type===f.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Ct} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],o=!1;for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s),!o&&(i[s]===46||i[s]===101||i[s]===69)&&(o=!0);o||(i.push(46),i.push(48)),e.push(i)}};var Dt=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}done(){return this.pos>=this.data.length}ch(){return this.data[this.pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this.pos]}expect(e){if(this.data.length-this.pos<e.length)throw new Error(`${w} unexpected end of input at position ${this.pos}`);for(let t=0;t<e.length;t++)if(this.data[this.pos++]!==e[t])throw new Error(`${w} unexpected token at position ${this.pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this.pos,t=!1,n=!1,i=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this.pos++;else break}};if(this.ch()===45&&(t=!0,this.pos++),this.ch()===48)if(this.pos++,this.ch()===46)this.pos++,n=!0;else return new p(f.uint,0,this.pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this.pos===e+1)throw new Error(`${w} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${w} unexpected token at position ${this.pos}`);n=!0,this.pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this.pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this.pos++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),s=parseFloat(o);return n?new p(f.float,s,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new p(s>=0?f.uint:f.negint,s,this.pos-e):new p(s>=0?f.uint:f.negint,BigInt(o),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${w} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let o=this.pos,s=0;o<this.data.length&&s<65536;o++,s++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this.pos,o));return this.pos=o+1,new p(f.string,c,s)}}let e=this.pos,t=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${w} unexpected end of unicode escape sequence at position ${this.pos}`);let o=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${w} unexpected unicode escape character at position ${this.pos}`);o=o*16+a,this.pos++}return o},i=()=>{let o=this.ch(),s=null,a=o>239?4:o>223?3:o>191?2:1;if(this.pos+a>this.data.length)throw new Error(`${w} unexpected unicode sequence at position ${this.pos}`);let c,u,l,h;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this.pos+1],(c&192)===128&&(h=(o&31)<<6|c&63,h>127&&(s=h));break;case 3:c=this.data[this.pos+1],u=this.data[this.pos+2],(c&192)===128&&(u&192)===128&&(h=(o&15)<<12|(c&63)<<6|u&63,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:c=this.data[this.pos+1],u=this.data[this.pos+2],l=this.data[this.pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(h=(o&15)<<18|(c&63)<<12|(u&63)<<6|l&63,h>65535&&h<1114112&&(s=h))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this.pos+=a};for(;!this.done();){let o=this.ch(),s;switch(o){case 92:if(this.pos++,this.done())throw new Error(`${w} unexpected string termination at position ${this.pos}`);switch(s=this.ch(),this.pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${w} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new p(f.string,oo(t),this.pos-e);default:if(o<32)throw new Error(`${w} invalid control character at position ${this.pos}`);o<128?(t.push(o),this.pos++):i()}}throw new Error(`${w} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new p(f.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new p(f.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new p(f.null,null,4);case 102:return this.expect([102,97,108,115,101]),new p(f.false,!1,5);case 116:return this.expect([116,114,117,101]),new p(f.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${w} unexpected character at position ${this.pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this.pos++,this.skipWhitespace(),new p(f.break,void 0,1);if(this.ch()!==44)throw new Error(`${w} unexpected character at position ${this.pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this.pos++,this.skipWhitespace(),new p(f.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this.pos++,this.skipWhitespace(),new p(f.break,void 0,1);if(this.ch()!==44)throw new Error(`${w} unexpected character at position ${this.pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this.pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this.pos++,this.skipWhitespace(),new p(f.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${w} unexpected character at position ${this.pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${w} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function mo(r,e){return e=Object.assign({tokenizer:new Dt(r,e)},e),Ce(r,e)}var Fu={codec:Nu,async*walk(r){yield*Du(r).Links.map(t=>t.Hash)}},Ou={codec:Kr,async*walk(){}},Uu=42,Ru={codec:113,async*walk(r){let e=[],t=[];t[Uu]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let i=x.decode(n.subarray(1));return e.push(i),i},Ce(r,{tags:t}),yield*e}},yo=class extends Dt{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===f.map){let t=this._next();if(t.type===f.string&&t.value==="/"){let n=this._next();if(n.type===f.string){if(this._next().type!==f.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new p(f.tag,42,0)}if(n.type===f.map){let i=this._next();if(i.type===f.string&&i.value==="bytes"){let o=this._next();if(o.type===f.string){for(let a=0;a<2;a++)if(this._next().type!==f.break)throw new Error("Invalid encoded Bytes form");let s=$t.decode(`m${o.value}`);return new p(f.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},zu={codec:297,async*walk(r){let e=[],t=[];t[Uu]=n=>{let i=x.parse(n);return e.push(i),i},mo(r,{tags:t,tokenizer:new yo(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}};var Tn=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Mt,go,$u,Md=[Ou,Fu,Ru,zu],qu="/pin/",Vu="/pinned-block/",wo=Kt,Wu=1;function Hu(r){return r.version===0&&(r=r.toV1()),new P(`${qu}${r.toString(wo)}`)}var An=class{constructor(e,t,n){Mt.add(this),this.datastore=e,this.blockstore=t,this.dagWalkers={},[...Md,...n].forEach(i=>{this.dagWalkers[i.codec]=i})}async add(e,t={}){let n=Hu(e);if(await this.datastore.has(n))throw new Error("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Error("Depth must be greater than or equal to 0");let o=new Te({concurrency:Wu});o.add(async()=>{await Tn(this,Mt,"m",go).call(this,e,o,c=>{c.pinnedBy.find(u=>Ge(u,e.bytes))==null&&(c.pinCount++,c.pinnedBy.push(e.bytes))},{...t,depth:i})});let s=ho();o.on("error",c=>{o.clear(),s.reject(c)}),await Promise.race([o.onIdle(),s.promise]);let a={depth:i,metadata:t.metadata??{}};return await this.datastore.put(n,kn(a),t),{cid:e,...a}}async rm(e,t={}){let n=Hu(e),i=await this.datastore.get(n,t),o=Ce(i);await this.datastore.delete(n,t);let s=new Te({concurrency:Wu});return s.add(async()=>{await Tn(this,Mt,"m",go).call(this,e,s,a=>{a.pinCount--,a.pinnedBy=a.pinnedBy.filter(c=>Ge(c,e.bytes))},{...t,depth:o.depth})}),await s.onIdle(),{cid:e,...o}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:qu+(e.cid!=null?`${e.cid.toString(Kt)}`:"")},e)){let i=x.parse(t.toString().substring(5),Kt),o=Ce(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new P(`${Vu}${wo.encode(e.multihash.bytes)}`);return await this.datastore.has(n,t)}};Mt=new WeakSet,go=async function r(e,t,n,i){if(i.depth===-1)return;let o=this.dagWalkers[e.code];if(o==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.blockstore.get(e);await Tn(this,Mt,"m",$u).call(this,e,n,i);for await(let a of o.walk(s))t.add(async()=>{await Tn(this,Mt,"m",r).call(this,a,t,n,{...i,depth:i.depth-1})})},$u=async function(e,t,n){let i=new P(`${Vu}${wo.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=Ce(await this.datastore.get(i,n))}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}if(t(o),o.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,kn(o),n)};var bo=new P("/version"),ju=1;async function Gu(r){if(!await r.has(bo)){await r.put(bo,fn(`${ju}`));return}let e=await r.get(bo),t=it(e);if(parseInt(t,10)!==ju)throw new Error("Unknown datastore version, a datastore migration may be required")}var Qu=U(Or(),1);function Bn(r){return r=r??new Error("Not Found"),(0,Qu.default)(r,"ERR_NOT_FOUND")}var Ku="SHARDING";function Od(r){return r[Symbol.asyncIterator]!=null}function Ud(r){if(Od(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var _o=Ud;function Rd(r){return r[Symbol.asyncIterator]!=null}function zd(r,e){return Rd(r)?async function*(){yield*(await _o(r)).sort(e)}():function*(){yield*_o(r).sort(e)}()}var Cn=zd;function $d(r){return r[Symbol.asyncIterator]!=null}function Wd(r){if($d(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ln=Wd;function Hd(r){return r[Symbol.asyncIterator]!=null}function qd(r,e){if(Hd(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Et(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){await o&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let s=e;return function*(){o===!0&&(yield n);for(let a of t)s(a)&&(yield a)}()}var He=qd;var Le=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:i}of e)await this.put(n,i,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await Ln(this.putMany(e,n)),e=[],await Ln(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let i=e.prefix;n=He(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>He(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cn(i,o),n)),e.offset!=null){let i=0,o=e.offset;n=He(n,()=>i++>=o)}return e.limit!=null&&(n=kt(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=He(n,o=>o.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>He(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cn(i,o),n)),e.offset!=null){let i=e.offset,o=0;n=He(n,()=>o++>=i)}return e.limit!=null&&(n=kt(n,e.limit)),n}};var pr=class extends Le{constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw Bn();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new P(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new P(e)}};var g1=new P(Ku);var C1=gt("datastore:core:tiered");var Pn={};V(Pn,{abortedError:()=>Yd,closeFailedError:()=>Qd,deleteFailedError:()=>Jd,getFailedError:()=>Xd,hasFailedError:()=>Zd,notFoundError:()=>vo,openFailedError:()=>Gd,putFailedError:()=>Kd});var Pe=U(Or(),1);function Gd(r){return r=r??new Error("Open failed"),(0,Pe.default)(r,"ERR_OPEN_FAILED")}function Qd(r){return r=r??new Error("Close failed"),(0,Pe.default)(r,"ERR_CLOSE_FAILED")}function Kd(r){return r=r??new Error("Put failed"),(0,Pe.default)(r,"ERR_PUT_FAILED")}function Xd(r){return r=r??new Error("Get failed"),(0,Pe.default)(r,"ERR_GET_FAILED")}function Jd(r){return r=r??new Error("Delete failed"),(0,Pe.default)(r,"ERR_DELETE_FAILED")}function Zd(r){return r=r??new Error("Has failed"),(0,Pe.default)(r,"ERR_HAS_FAILED")}function vo(r){return r=r??new Error("Not Found"),(0,Pe.default)(r,"ERR_NOT_FOUND")}function Yd(r){return r=r??new Error("Aborted"),(0,Pe.default)(r,"ERR_ABORTED")}var mr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:i}of e)await this.put(n,i,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async delete(e,t){await Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var yr=class extends mr{constructor(){super(),this.data=new Map}put(e,t){return this.data.set(j.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(j.encode(e.multihash.bytes));if(t==null)throw vo();return t}has(e){return this.data.has(j.encode(e.multihash.bytes))}async delete(e){this.data.delete(j.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:x.createV1(Kr,br(j.decode(e))),block:t}}};var J1={...Pn};var ep=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},xo=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Ft,ko=gt("helia"),In=class{constructor(e){Ft.set(this,void 0);let t=[Ve,Un,Dn,...e.hashers??[]],n=e.datastore??new pr,i=e.blockstore??new yr,o=e.libp2p??new Proxy({},{get(s,a){let c=()=>{};if(["start","stop"].includes(a.toString()))return c;if(a==="isProxy")return!0;throw new Error("Please configure Helia with a libp2p instance")},set(){throw new Error("Please configure Helia with a libp2p instance")}});e.libp2p!=null&&ep(this,Ft,sc(o,i,{hashLoader:{getHasher:async s=>{let a=t.find(c=>c.code===s||c.name===s);if(a!=null)return await Promise.resolve(a);throw new Error(`Could not load hasher for code/name "${s}"`)}}}),"f"),this.pins=new An(n,i,e.dagWalkers??[]),this.libp2p=o,this.blockstore=new ln(i,this.pins,{bitswap:xo(this,Ft,"f"),holdGcLock:e.holdGcLock}),this.datastore=n}async start(){await Gu(this.datastore),await xo(this,Ft,"f")?.start(),await this.libp2p.start()}async stop(){await this.libp2p.stop(),await xo(this,Ft,"f")?.stop()}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();ko("gc start"),await Gt(i.deleteMany(async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new C("helia:gc:deleted",o))}catch(s){ko.error("Error during gc",s),e.onProgress?.(new C("helia:gc:error",s))}}()))}finally{t()}ko("gc finished")}};Ft=new WeakMap;async function tp(r={}){let e=new In(r);return r.start!==!1&&await e.start(),e}return rl(rp);})();
|
|
2
|
+
"use strict";var Helia=(()=>{var Xu=Object.create;var gr=Object.defineProperty;var Ju=Object.getOwnPropertyDescriptor;var Zu=Object.getOwnPropertyNames;var Yu=Object.getPrototypeOf,el=Object.prototype.hasOwnProperty;var S=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),V=(r,e)=>{for(var t in e)gr(r,t,{get:e[t],enumerable:!0})},ko=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zu(e))!el.call(r,i)&&i!==t&&gr(r,i,{get:()=>e[i],enumerable:!(n=Ju(e,i))||n.enumerable});return r};var U=(r,e,t)=>(t=r!=null?Xu(Yu(r)):{},ko(e||!r||!r.__esModule?gr(t,"default",{value:r,enumerable:!0}):t,r)),tl=r=>ko(gr({},"__esModule",{value:!0}),r);var qo=S((_p,Ho)=>{Ho.exports=Wo;var $o=128,$l=127,Wl=~$l,Hl=Math.pow(2,31);function Wo(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Hl;)e[t++]=r&255|$o,r/=128;for(;r&Wl;)e[t++]=r&255|$o,r>>>=7;return e[t]=r|0,Wo.bytes=t-n+1,e}});var Go=S((vp,jo)=>{jo.exports=jn;var ql=128,Vo=127;function jn(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw jn.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&Vo)<<i:(s&Vo)*Math.pow(2,i),i+=7}while(s>=ql);return jn.bytes=o-n,t}});var Ko=S((xp,Qo)=>{var Vl=Math.pow(2,7),jl=Math.pow(2,14),Gl=Math.pow(2,21),Ql=Math.pow(2,28),Kl=Math.pow(2,35),Xl=Math.pow(2,42),Jl=Math.pow(2,49),Zl=Math.pow(2,56),Yl=Math.pow(2,63);Qo.exports=function(r){return r<Vl?1:r<jl?2:r<Gl?3:r<Ql?4:r<Kl?5:r<Xl?6:r<Jl?7:r<Zl?8:r<Yl?9:10}});var Jo=S((kp,Xo)=>{Xo.exports={encode:qo(),decode:Go(),encodingLength:Ko()}});var es=S((Ep,Yo)=>{"use strict";var Zo=Jo();Yo.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Zo.decode(r);e.push(t),r=r.slice(Zo.decode.bytes)}return e}});var ns=S((Sp,rs)=>{rs.exports=Gn;var ts=128,ef=127,tf=~ef,rf=Math.pow(2,31);function Gn(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Gn.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=rf;)e[t++]=r&255|ts,r/=128;for(;r&tf;)e[t++]=r&255|ts,r>>>=7;return e[t]=r|0,Gn.bytes=t-n+1,e}});var ss=S((Tp,os)=>{os.exports=Qn;var nf=128,is=127;function Qn(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a||i>49)throw Qn.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&is)<<i:(s&is)*Math.pow(2,i),i+=7}while(s>=nf);return Qn.bytes=o-n,t}});var cs=S((Ap,as)=>{var of=Math.pow(2,7),sf=Math.pow(2,14),af=Math.pow(2,21),cf=Math.pow(2,28),uf=Math.pow(2,35),lf=Math.pow(2,42),ff=Math.pow(2,49),hf=Math.pow(2,56),df=Math.pow(2,63);as.exports=function(r){return r<of?1:r<sf?2:r<af?3:r<cf?4:r<uf?5:r<lf?6:r<ff?7:r<hf?8:r<df?9:10}});var ls=S((Bp,us)=>{us.exports={encode:ns(),decode:ss(),encodingLength:cs()}});var ds=S((Lp,hs)=>{var mt=1e3,yt=mt*60,gt=yt*60,Ge=gt*24,mf=Ge*7,yf=Ge*365.25;hs.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return gf(r);if(t==="number"&&isFinite(r))return e.long?bf(r):wf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function gf(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*yf;case"weeks":case"week":case"w":return t*mf;case"days":case"day":case"d":return t*Ge;case"hours":case"hour":case"hrs":case"hr":case"h":return t*gt;case"minutes":case"minute":case"mins":case"min":case"m":return t*yt;case"seconds":case"second":case"secs":case"sec":case"s":return t*mt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function wf(r){var e=Math.abs(r);return e>=Ge?Math.round(r/Ge)+"d":e>=gt?Math.round(r/gt)+"h":e>=yt?Math.round(r/yt)+"m":e>=mt?Math.round(r/mt)+"s":r+"ms"}function bf(r){var e=Math.abs(r);return e>=Ge?_r(r,e,Ge,"day"):e>=gt?_r(r,e,gt,"hour"):e>=yt?_r(r,e,yt,"minute"):e>=mt?_r(r,e,mt,"second"):r+" ms"}function _r(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var ms=S((Pp,ps)=>{function _f(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=ds(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let h=0;for(let d=0;d<l.length;d++)h=(h<<5)-h+l.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(l){let h,d=null,v,y;function g(...k){if(!g.enabled)return;let I=g,O=Number(new Date),ne=O-(h||O);I.diff=ne,I.prev=h,I.curr=O,h=O,k[0]=t.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let $=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(ie,Q)=>{if(ie==="%%")return"%";$++;let oe=t.formatters[Q];if(typeof oe=="function"){let ut=k[$];ie=oe.call(I,ut),k.splice($,1),$--}return ie}),t.formatArgs.call(I,k),(I.log||t.log).apply(I,k)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(v!==t.namespaces&&(v=t.namespaces,y=t.enabled(l)),y),set:k=>{d=k}}),typeof t.init=="function"&&t.init(g),g}function n(l,h){let d=t(this.namespace+(typeof h>"u"?":":h)+l);return d.log=this.log,d}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let h,d=(typeof l=="string"?l:"").split(/[\s,]+/),v=d.length;for(h=0;h<v;h++)d[h]&&(l=d[h].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.slice(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function o(){let l=[...t.names.map(a),...t.skips.map(a).map(h=>"-"+h)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let h,d;for(h=0,d=t.skips.length;h<d;h++)if(t.skips[h].test(l))return!1;for(h=0,d=t.names.length;h<d;h++)if(t.names[h].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}ps.exports=_f});var ys=S((K,vr)=>{K.formatArgs=xf;K.save=kf;K.load=Ef;K.useColors=vf;K.storage=Sf();K.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();K.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function vf(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function xf(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vr.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}K.log=console.debug||console.log||(()=>{});function kf(r){try{r?K.storage.setItem("debug",r):K.storage.removeItem("debug")}catch{}}function Ef(){let r;try{r=K.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Sf(){try{return localStorage}catch{}}vr.exports=ms()(K);var{formatters:Tf}=vr.exports;Tf.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ws=S((Gp,gs)=>{"use strict";gs.exports=Pf;function Pf(r,e){for(var t=new Array(arguments.length-1),n=0,i=2,o=!0;i<arguments.length;)t[n++]=arguments[i++];return new Promise(function(a,c){t[n]=function(l){if(o)if(o=!1,l)c(l);else{for(var h=new Array(arguments.length-1),d=0;d<h.length;)h[d++]=arguments[d];a.apply(null,h)}};try{r.apply(e||null,t)}catch(u){o&&(o=!1,c(u))}})}});var xs=S(vs=>{"use strict";var kr=vs;kr.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&e.charAt(t)==="=";)++n;return Math.ceil(e.length*3)/4-n};var bt=new Array(64),_s=new Array(123);for(he=0;he<64;)_s[bt[he]=he<26?he+65:he<52?he+71:he<62?he-4:he-59|43]=he++;var he;kr.encode=function(e,t,n){for(var i=null,o=[],s=0,a=0,c;t<n;){var u=e[t++];switch(a){case 0:o[s++]=bt[u>>2],c=(u&3)<<4,a=1;break;case 1:o[s++]=bt[c|u>>4],c=(u&15)<<2,a=2;break;case 2:o[s++]=bt[c|u>>6],o[s++]=bt[u&63],a=0;break}s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0)}return a&&(o[s++]=bt[c],o[s++]=61,a===1&&(o[s++]=61)),i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))};var bs="invalid encoding";kr.decode=function(e,t,n){for(var i=n,o=0,s,a=0;a<e.length;){var c=e.charCodeAt(a++);if(c===61&&o>1)break;if((c=_s[c])===void 0)throw Error(bs);switch(o){case 0:s=c,o=1;break;case 1:t[n++]=s<<2|(c&48)>>4,s=c,o=2;break;case 2:t[n++]=(s&15)<<4|(c&60)>>2,s=c,o=3;break;case 3:t[n++]=(s&3)<<6|c,o=0;break}}if(o===1)throw Error(bs);return n-i};kr.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var Es=S((Kp,ks)=>{"use strict";ks.exports=Er;function Er(){this._listeners={}}Er.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this};Er.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i<n.length;)n[i].fn===t?n.splice(i,1):++i;return this};Er.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<t.length;)t[i].fn.apply(t[i++].ctx,n)}return this}});var Ps=S((Xp,Ls)=>{"use strict";Ls.exports=Ss(Ss);function Ss(r){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),n=t[3]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3]}function o(c,u,l){e[0]=c,u[l]=t[3],u[l+1]=t[2],u[l+2]=t[1],u[l+3]=t[0]}r.writeFloatLE=n?i:o,r.writeFloatBE=n?o:i;function s(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],e[0]}function a(c,u){return t[3]=c[u],t[2]=c[u+1],t[1]=c[u+2],t[0]=c[u+3],e[0]}r.readFloatLE=n?s:a,r.readFloatBE=n?a:s}():function(){function e(n,i,o,s){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,o,s);else if(isNaN(i))n(2143289344,o,s);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,o,s);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,o,s);else{var c=Math.floor(Math.log(i)/Math.LN2),u=Math.round(i*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,o,s)}}r.writeFloatLE=e.bind(null,Ts),r.writeFloatBE=e.bind(null,As);function t(n,i,o){var s=n(i,o),a=(s>>31)*2+1,c=s>>>23&255,u=s&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}r.readFloatLE=t.bind(null,Bs),r.readFloatBE=t.bind(null,Cs)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),t=new Uint8Array(e.buffer),n=t[7]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3],u[l+4]=t[4],u[l+5]=t[5],u[l+6]=t[6],u[l+7]=t[7]}function o(c,u,l){e[0]=c,u[l]=t[7],u[l+1]=t[6],u[l+2]=t[5],u[l+3]=t[4],u[l+4]=t[3],u[l+5]=t[2],u[l+6]=t[1],u[l+7]=t[0]}r.writeDoubleLE=n?i:o,r.writeDoubleBE=n?o:i;function s(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],t[4]=c[u+4],t[5]=c[u+5],t[6]=c[u+6],t[7]=c[u+7],e[0]}function a(c,u){return t[7]=c[u],t[6]=c[u+1],t[5]=c[u+2],t[4]=c[u+3],t[3]=c[u+4],t[2]=c[u+5],t[1]=c[u+6],t[0]=c[u+7],e[0]}r.readDoubleLE=n?s:a,r.readDoubleBE=n?a:s}():function(){function e(n,i,o,s,a,c){var u=s<0?1:0;if(u&&(s=-s),s===0)n(0,a,c+i),n(1/s>0?0:2147483648,a,c+o);else if(isNaN(s))n(0,a,c+i),n(2146959360,a,c+o);else if(s>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+o);else{var l;if(s<22250738585072014e-324)l=s/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+o);else{var h=Math.floor(Math.log(s)/Math.LN2);h===1024&&(h=1023),l=s*Math.pow(2,-h),n(l*4503599627370496>>>0,a,c+i),n((u<<31|h+1023<<20|l*1048576&1048575)>>>0,a,c+o)}}}r.writeDoubleLE=e.bind(null,Ts,0,4),r.writeDoubleBE=e.bind(null,As,4,0);function t(n,i,o,s,a){var c=n(s,a+i),u=n(s,a+o),l=(u>>31)*2+1,h=u>>>20&2047,d=4294967296*(u&1048575)+c;return h===2047?d?NaN:l*(1/0):h===0?l*5e-324*d:l*Math.pow(2,h-1075)*(d+4503599627370496)}r.readDoubleLE=t.bind(null,Bs,0,4),r.readDoubleBE=t.bind(null,Cs,4,0)}(),r}function Ts(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 As(r,e,t){e[t]=r>>>24,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255}function Bs(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function Cs(r,e){return(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}});var Is=S((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(r){}return null}});var Ds=S(Ns=>{"use strict";var Xn=Ns;Xn.length=function(e){for(var t=0,n=0,i=0;i<e.length;++i)n=e.charCodeAt(i),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(i+1)&64512)===56320?(++i,t+=4):t+=3;return t};Xn.read=function(e,t,n){var i=n-t;if(i<1)return"";for(var o=null,s=[],a=0,c;t<n;)c=e[t++],c<128?s[a++]=c:c>191&&c<224?s[a++]=(c&31)<<6|e[t++]&63:c>239&&c<365?(c=((c&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[a++]=55296+(c>>10),s[a++]=56320+(c&1023)):s[a++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0);return o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};Xn.write=function(e,t,n){for(var i=n,o,s,a=0;a<e.length;++a)o=e.charCodeAt(a),o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(a+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++a,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128);return n-i}});var Fs=S((Zp,Ms)=>{"use strict";Ms.exports=If;function If(r,e,t){var n=t||8192,i=n>>>1,o=null,s=n;return function(c){if(c<1||c>i)return r(c);s+c>n&&(o=r(n),s=0);var u=e.call(o,s,s+=c);return s&7&&(s=(s|7)+1),u}}});var Us=S((Yp,Os)=>{"use strict";Os.exports=R;var Ht=Je();function R(r,e){this.lo=r>>>0,this.hi=e>>>0}var Xe=R.zero=new R(0,0);Xe.toNumber=function(){return 0};Xe.zzEncode=Xe.zzDecode=function(){return this};Xe.length=function(){return 1};var Nf=R.zeroHash="\0\0\0\0\0\0\0\0";R.fromNumber=function(e){if(e===0)return Xe;var t=e<0;t&&(e=-e);var 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)};R.from=function(e){if(typeof e=="number")return R.fromNumber(e);if(Ht.isString(e))if(Ht.Long)e=Ht.Long.fromString(e);else return R.fromNumber(parseInt(e,10));return e.low||e.high?new R(e.low>>>0,e.high>>>0):Xe};R.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};R.prototype.toLong=function(e){return Ht.Long?new Ht.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var De=String.prototype.charCodeAt;R.fromHash=function(e){return e===Nf?Xe:new R((De.call(e,0)|De.call(e,1)<<8|De.call(e,2)<<16|De.call(e,3)<<24)>>>0,(De.call(e,4)|De.call(e,5)<<8|De.call(e,6)<<16|De.call(e,7)<<24)>>>0)};R.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};R.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};R.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};R.prototype.length=function(){var 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}});var Je=S(Jn=>{"use strict";var _=Jn;_.asPromise=ws();_.base64=xs();_.EventEmitter=Es();_.float=Ps();_.inquire=Is();_.utf8=Ds();_.pool=Fs();_.LongBits=Us();_.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);_.global=_.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||Jn;_.emptyArray=Object.freeze?Object.freeze([]):[];_.emptyObject=Object.freeze?Object.freeze({}):{};_.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};_.isString=function(e){return typeof e=="string"||e instanceof String};_.isObject=function(e){return e&&typeof e=="object"};_.isset=_.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};_.Buffer=function(){try{var r=_.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();_._Buffer_from=null;_._Buffer_allocUnsafe=null;_.newBuffer=function(e){return typeof e=="number"?_.Buffer?_._Buffer_allocUnsafe(e):new _.Array(e):_.Buffer?_._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};_.Array=typeof Uint8Array<"u"?Uint8Array:Array;_.Long=_.global.dcodeIO&&_.global.dcodeIO.Long||_.global.Long||_.inquire("long");_.key2Re=/^true|false|0|1$/;_.key32Re=/^-?(?:0|[1-9][0-9]*)$/;_.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;_.longToHash=function(e){return e?_.LongBits.from(e).toHash():_.LongBits.zeroHash};_.longFromHash=function(e,t){var n=_.LongBits.fromHash(e);return _.Long?_.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function Rs(r,e,t){for(var n=Object.keys(e),i=0;i<n.length;++i)(r[n[i]]===void 0||!t)&&(r[n[i]]=e[n[i]]);return r}_.merge=Rs;_.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function zs(r){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&Rs(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return r},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}_.newError=zs;_.ProtocolError=zs("ProtocolError");_.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var i=Object.keys(this),o=i.length-1;o>-1;--o)if(t[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};_.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}};_.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};_._configure=function(){var r=_.Buffer;if(!r){_._Buffer_from=_._Buffer_allocUnsafe=null;return}_._Buffer_from=r.from!==Uint8Array.from&&r.from||function(t,n){return new r(t,n)},_._Buffer_allocUnsafe=r.allocUnsafe||function(t){return new r(t)}}});var ei=S((tm,Vs)=>{"use strict";Vs.exports=M;var we=Je(),Yn,Hs=we.LongBits,Df=we.utf8;function de(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function M(r){this.buf=r,this.pos=0,this.len=r.length}var $s=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new M(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new M(e);throw Error("illegal buffer")},qs=function(){return we.Buffer?function(t){return(M.create=function(i){return we.Buffer.isBuffer(i)?new Yn(i):$s(i)})(t)}:$s};M.create=qs();M.prototype._slice=we.Array.prototype.subarray||we.Array.prototype.slice;M.prototype.uint32=function(){var e=4294967295;return function(){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,de(this,10);return e}}();M.prototype.int32=function(){return this.uint32()|0};M.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Zn(){var r=new Hs(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw de(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw de(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}M.prototype.bool=function(){return this.uint32()!==0};function Sr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}M.prototype.fixed32=function(){if(this.pos+4>this.len)throw de(this,4);return Sr(this.buf,this.pos+=4)};M.prototype.sfixed32=function(){if(this.pos+4>this.len)throw de(this,4);return Sr(this.buf,this.pos+=4)|0};function Ws(){if(this.pos+8>this.len)throw de(this,8);return new Hs(Sr(this.buf,this.pos+=4),Sr(this.buf,this.pos+=4))}M.prototype.float=function(){if(this.pos+4>this.len)throw de(this,4);var e=we.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};M.prototype.double=function(){if(this.pos+8>this.len)throw de(this,4);var e=we.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};M.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw de(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)};M.prototype.string=function(){var e=this.bytes();return Df.read(e,0,e.length)};M.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw de(this,e);this.pos+=e}else do if(this.pos>=this.len)throw de(this);while(this.buf[this.pos++]&128);return this};M.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};M._configure=function(r){Yn=r,M.create=qs(),Yn._configure();var e=we.Long?"toLong":"toNumber";we.merge(M.prototype,{int64:function(){return Zn.call(this)[e](!1)},uint64:function(){return Zn.call(this)[e](!0)},sint64:function(){return Zn.call(this).zzDecode()[e](!1)},fixed64:function(){return Ws.call(this)[e](!0)},sfixed64:function(){return Ws.call(this)[e](!1)}})}});var Ks=S((rm,Qs)=>{"use strict";Qs.exports=Ze;var Gs=ei();(Ze.prototype=Object.create(Gs.prototype)).constructor=Ze;var js=Je();function Ze(r){Gs.call(this,r)}Ze._configure=function(){js.Buffer&&(Ze.prototype._slice=js.Buffer.prototype.slice)};Ze.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Ze._configure()});var ai=S((nm,Ys)=>{"use strict";Ys.exports=T;var ce=Je(),ti,Tr=ce.LongBits,Xs=ce.base64,Js=ce.utf8;function qt(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function ni(){}function Mf(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function T(){this.len=0,this.head=new qt(ni,0,0),this.tail=this.head,this.states=null}var Zs=function(){return ce.Buffer?function(){return(T.create=function(){return new ti})()}:function(){return new T}};T.create=Zs();T.alloc=function(e){return new ce.Array(e)};ce.Array!==Array&&(T.alloc=ce.pool(T.alloc,ce.Array.prototype.subarray));T.prototype._push=function(e,t,n){return this.tail=this.tail.next=new qt(e,t,n),this.len+=t,this};function ii(r,e,t){e[t]=r&255}function Ff(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function oi(r,e){this.len=r,this.next=void 0,this.val=e}oi.prototype=Object.create(qt.prototype);oi.prototype.fn=Ff;T.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new oi((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};T.prototype.int32=function(e){return e<0?this._push(si,10,Tr.fromNumber(e)):this.uint32(e)};T.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function si(r,e,t){for(;r.hi;)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}T.prototype.uint64=function(e){var t=Tr.from(e);return this._push(si,t.length(),t)};T.prototype.int64=T.prototype.uint64;T.prototype.sint64=function(e){var t=Tr.from(e).zzEncode();return this._push(si,t.length(),t)};T.prototype.bool=function(e){return this._push(ii,1,e?1:0)};function ri(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}T.prototype.fixed32=function(e){return this._push(ri,4,e>>>0)};T.prototype.sfixed32=T.prototype.fixed32;T.prototype.fixed64=function(e){var t=Tr.from(e);return this._push(ri,4,t.lo)._push(ri,4,t.hi)};T.prototype.sfixed64=T.prototype.fixed64;T.prototype.float=function(e){return this._push(ce.float.writeFloatLE,4,e)};T.prototype.double=function(e){return this._push(ce.float.writeDoubleLE,8,e)};var Of=ce.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i<e.length;++i)t[n+i]=e[i]};T.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(ii,1,0);if(ce.isString(e)){var n=T.alloc(t=Xs.length(e));Xs.decode(e,n,0),e=n}return this.uint32(t)._push(Of,t,e)};T.prototype.string=function(e){var t=Js.length(e);return t?this.uint32(t)._push(Js.write,t,e):this._push(ii,1,0)};T.prototype.fork=function(){return this.states=new Mf(this),this.head=this.tail=new qt(ni,0,0),this.len=0,this};T.prototype.reset=function(){return this.states?(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 qt(ni,0,0),this.len=0),this};T.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};T.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};T._configure=function(r){ti=r,T.create=Zs(),ti._configure()}});var ra=S((im,ta)=>{"use strict";ta.exports=be;var ea=ai();(be.prototype=Object.create(ea.prototype)).constructor=be;var Me=Je();function be(){ea.call(this)}be._configure=function(){be.alloc=Me._Buffer_allocUnsafe,be.writeBytesBuffer=Me.Buffer&&Me.Buffer.prototype instanceof Uint8Array&&Me.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i<e.length;)t[n++]=e[i++]}};be.prototype.bytes=function(e){Me.isString(e)&&(e=Me._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(be.writeBytesBuffer,t,e),this};function Uf(r,e,t){r.length<40?Me.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}be.prototype.string=function(e){var t=Me.Buffer.byteLength(e);return this.uint32(t),t&&this._push(Uf,t,e),this};be._configure()});var Or=S((_y,ga)=>{"use strict";function ya(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function eh(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return ya(r,t)}catch{t.message=r.message,t.stack=r.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(r)),ya(new i,t)}}ga.exports=eh});var ka=S((Uy,xa)=>{"use strict";xa.exports=function(){return Date.now()}});var Sa=S((Ry,Ea)=>{"use strict";var zr=ka(),_i=class{constructor(e,t,n){let i=this;this._started=zr(),this._rescheduled=0,this._scheduled=t,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(zr()-i._started),i._schedule(i._scheduled)):(i._triggered=!0,e.apply(null,i._args))},this._timer=setTimeout(this._timerWrapper,t)}reschedule(e){e||(e=this._scheduled);let t=zr();t+e-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(e)):this._triggered?this._schedule(e):(this._started=t,this._rescheduled=e)}_schedule(e){this._triggered=!1,this._started=zr(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function uh(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let r;if(arguments.length>0){r=new Array(arguments.length-2);for(var e=0;e<r.length;e++)r[e]=arguments[e+2]}return new _i(arguments[0],arguments[1],r)}Ea.exports=uh});var Ba=S((zy,Aa)=>{"use strict";var{AbortController:lh}=globalThis,Ta=Sa(),jt=class extends lh{constructor(e){super(),this._ms=e,this._timer=Ta(()=>this.abort(),e),Object.setPrototypeOf(this,jt.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=Ta(()=>this.abort(),this._ms)}};Aa.exports={TimeoutController:jt}});var Qr=S((Eg,Ti)=>{"use strict";var Tt=typeof Reflect=="object"?Reflect:null,Da=Tt&&typeof Tt.apply=="function"?Tt.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},jr;Tt&&typeof Tt.ownKeys=="function"?jr=Tt.ownKeys:Object.getOwnPropertySymbols?jr=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:jr=function(e){return Object.getOwnPropertyNames(e)};function Sh(r){console&&console.warn&&console.warn(r)}var Fa=Number.isNaN||function(e){return e!==e};function L(){L.init.call(this)}Ti.exports=L;Ti.exports.once=Ch;L.EventEmitter=L;L.prototype._events=void 0;L.prototype._eventsCount=0;L.prototype._maxListeners=void 0;var Ma=10;function Gr(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(L,"defaultMaxListeners",{enumerable:!0,get:function(){return Ma},set:function(r){if(typeof r!="number"||r<0||Fa(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");Ma=r}});L.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};L.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Fa(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Oa(r){return r._maxListeners===void 0?L.defaultMaxListeners:r._maxListeners}L.prototype.getMaxListeners=function(){return Oa(this)};L.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(c===void 0)return!1;if(typeof c=="function")Da(c,this,t);else for(var u=c.length,l=Wa(c,u),n=0;n<u;++n)Da(l[n],this,t);return!0};function Ua(r,e,t,n){var i,o,s;if(Gr(t),o=r._events,o===void 0?(o=r._events=Object.create(null),r._eventsCount=0):(o.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),o=r._events),s=o[e]),s===void 0)s=o[e]=t,++r._eventsCount;else if(typeof s=="function"?s=o[e]=n?[t,s]:[s,t]:n?s.unshift(t):s.push(t),i=Oa(r),i>0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=s.length,Sh(a)}return r}L.prototype.addListener=function(e,t){return Ua(this,e,t,!1)};L.prototype.on=L.prototype.addListener;L.prototype.prependListener=function(e,t){return Ua(this,e,t,!0)};function Th(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Ra(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=Th.bind(n);return i.listener=t,n.wrapFn=i,i}L.prototype.once=function(e,t){return Gr(t),this.on(e,Ra(this,e,t)),this};L.prototype.prependOnceListener=function(e,t){return Gr(t),this.prependListener(e,Ra(this,e,t)),this};L.prototype.removeListener=function(e,t){var n,i,o,s,a;if(Gr(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():Ah(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};L.prototype.off=L.prototype.removeListener;L.prototype.removeAllListeners=function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this};function za(r,e,t){var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?t?[i.listener||i]:[i]:t?Bh(i):Wa(i,i.length)}L.prototype.listeners=function(e){return za(this,e,!0)};L.prototype.rawListeners=function(e){return za(this,e,!1)};L.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):$a.call(r,e)};L.prototype.listenerCount=$a;function $a(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}L.prototype.eventNames=function(){return this._eventsCount>0?jr(this._events):[]};function Wa(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function Ah(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function Bh(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function Ch(r,e){return new Promise(function(t,n){function i(s){r.removeListener(e,o),n(s)}function o(){typeof r.removeListener=="function"&&r.removeListener("error",i),t([].slice.call(arguments))}Ha(r,e,o,{once:!0}),e!=="error"&&Lh(r,i,{once:!0})})}function Lh(r,e,t){typeof r.on=="function"&&Ha(r,"error",e,t)}function Ha(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function i(o){n.once&&r.removeEventListener(e,i),t(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var Za=S((Xa,Ja)=>{"use strict";var Vh=Math.exp;Xa=Ja.exports=function(e){if(typeof e!="number")throw new Error("must provide a timespan to the moving average constructor");if(e<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let t,n=0,i=0,o=0,s,a={};function c(u,l){return 1-Vh(-(u-l)/e)}return a.push=function(l,h){if(s){let d=c(l,s),v=h-t,y=d*v;t=d*h+(1-d)*t,n=(1-d)*(n+v*y),i=Math.sqrt(n),o=t+d*v}else t=h;s=l},a.movingAverage=function(){return t},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return o},a}});var nc=S((tw,Ui)=>{function rc(r){let e=new globalThis.AbortController;function t(){e.abort();for(let n of r)!n||!n.removeEventListener||n.removeEventListener("abort",t)}for(let n of r)if(!(!n||!n.addEventListener)){if(n.aborted){t();break}n.addEventListener("abort",t)}return e.signal}Ui.exports=rc;Ui.exports.anySignal=rc});var ac=S((yw,zi)=>{"use strict";var Jh=Object.prototype.hasOwnProperty,q="~";function Zt(){}Object.create&&(Zt.prototype=Object.create(null),new Zt().__proto__||(q=!1));function Zh(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function sc(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Zh(t,n||r,i),s=q?q+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function en(r,e){--r._eventsCount===0?r._events=new Zt:delete r._events[e]}function H(){this._events=new Zt,this._eventsCount=0}H.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Jh.call(t,n)&&e.push(q?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};H.prototype.listeners=function(e){var t=q?q+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};H.prototype.listenerCount=function(e){var t=q?q+e:e,n=this._events[t];return n?n.fn?1:n.length:0};H.prototype.emit=function(e,t,n,i,o,s){var a=q?q+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,h;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c.fn.apply(c.context,l)}else{var d=c.length,v;for(h=0;h<d;h++)switch(c[h].once&&this.removeListener(e,c[h].fn,void 0,!0),u){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,t);break;case 3:c[h].fn.call(c[h].context,t,n);break;case 4:c[h].fn.call(c[h].context,t,n,i);break;default:if(!l)for(v=1,l=new Array(u-1);v<u;v++)l[v-1]=arguments[v];c[h].fn.apply(c[h].context,l)}}return!0};H.prototype.on=function(e,t,n){return sc(this,e,t,n,!1)};H.prototype.once=function(e,t,n){return sc(this,e,t,n,!0)};H.prototype.removeListener=function(e,t,n,i){var o=q?q+e:e;if(!this._events[o])return this;if(!t)return en(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&en(this,o);else{for(var a=0,c=[],u=s.length;a<u;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:en(this,o)}return this};H.prototype.removeAllListeners=function(e){var t;return e?(t=q?q+e:e,this._events[t]&&en(this,t)):(this._events=new Zt,this._eventsCount=0),this};H.prototype.off=H.prototype.removeListener;H.prototype.addListener=H.prototype.on;H.prefixed=q;H.EventEmitter=H;typeof zi<"u"&&(zi.exports=H)});var tp={};V(tp,{createHelia:()=>ep});var Dn={};V(Dn,{identity:()=>Nn});var np=new Uint8Array(0);var Eo=(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},xe=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")};var So=r=>new TextEncoder().encode(r),To=r=>new TextDecoder().decode(r);var rl=Lo,Bo=128,nl=127,il=~nl,ol=Math.pow(2,31);function Lo(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ol;)e[t++]=r&255|Bo,r/=128;for(;r&il;)e[t++]=r&255|Bo,r>>>=7;return e[t]=r|0,Lo.bytes=t-n+1,e}var sl=In,al=128,Co=127;function In(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw In.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&Co)<<i:(s&Co)*Math.pow(2,i),i+=7}while(s>=al);return In.bytes=o-n,t}var cl=Math.pow(2,7),ul=Math.pow(2,14),ll=Math.pow(2,21),fl=Math.pow(2,28),hl=Math.pow(2,35),dl=Math.pow(2,42),pl=Math.pow(2,49),ml=Math.pow(2,56),yl=Math.pow(2,63),gl=function(r){return r<cl?1:r<ul?2:r<ll?3:r<fl?4:r<hl?5:r<dl?6:r<pl?7:r<ml?8:r<yl?9:10},wl={encode:rl,decode:sl,encodingLength:gl},bl=wl,Ut=bl;var Rt=(r,e=0)=>[Ut.decode(r,e),Ut.decode.bytes],lt=(r,e,t=0)=>(Ut.encode(r,e,t),e),ft=r=>Ut.encodingLength(r);var Ve=(r,e)=>{let t=e.byteLength,n=ft(r),i=n+ft(t),o=new Uint8Array(i+t);return lt(r,o,0),lt(t,o,n),o.set(e,i),new ht(r,t,e,o)},br=r=>{let e=xe(r),[t,n]=Rt(e),[i,o]=Rt(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new ht(t,i,s,e)},Po=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Eo(r.bytes,t.bytes)}},ht=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var Io=0,_l="identity",No=xe,vl=r=>Ve(Io,No(r)),Nn={code:Io,name:_l,encode:No,digest:vl};var Un={};V(Un,{sha256:()=>je,sha512:()=>On});var Fn=({name:r,code:e,encode:t})=>new Mn(r,e,t),Mn=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Ve(this.code,t):t.then(n=>Ve(this.code,n))}else throw Error("Unknown type, must be binary type")}};var Mo=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),je=Fn({name:"sha2-256",code:18,encode:Mo("SHA-256")}),On=Fn({name:"sha2-512",code:19,encode:Mo("SHA-512")});var Hn={};V(Hn,{base58btc:()=>E,base58flickr:()=>Al});function xl(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 o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var g=0,k=0,I=0,O=y.length;I!==O&&y[I]===0;)I++,g++;for(var ne=(O-I)*l+1>>>0,$=new Uint8Array(ne);I!==O;){for(var fe=y[I],ie=0,Q=ne-1;(fe!==0||ie<k)&&Q!==-1;Q--,ie++)fe+=256*$[Q]>>>0,$[Q]=fe%a>>>0,fe=fe/a>>>0;if(fe!==0)throw new Error("Non-zero carry");k=ie,I++}for(var oe=ne-k;oe!==ne&&$[oe]===0;)oe++;for(var ut=c.repeat(g);oe<ne;++oe)ut+=r.charAt($[oe]);return ut}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var g=0;if(y[g]!==" "){for(var k=0,I=0;y[g]===c;)k++,g++;for(var O=(y.length-g)*u+1>>>0,ne=new Uint8Array(O);y[g];){var $=t[y.charCodeAt(g)];if($===255)return;for(var fe=0,ie=O-1;($!==0||fe<I)&&ie!==-1;ie--,fe++)$+=a*ne[ie]>>>0,ne[ie]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");I=fe,g++}if(y[g]!==" "){for(var Q=O-I;Q!==O&&ne[Q]===0;)Q++;for(var oe=new Uint8Array(k+(O-Q)),ut=k;Q!==O;)oe[ut++]=ne[Q++];return oe}}}function v(y){var g=d(y);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:v}}var kl=xl,El=kl,Fo=El;var Rn=class{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{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),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 Oo(this,e)}},$n=class{constructor(e){this.decoders=e}or(e){return Oo(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Oo=(r,e)=>new $n({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Wn=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Rn(e,t,n),this.decoder=new zn(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},pt=({name:r,prefix:e,encode:t,decode:n})=>new Wn(r,e,t,n),Ie=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=Fo(t,e);return pt({prefix:r,name:e,encode:n,decode:o=>xe(i(o))})},Sl=(r,e,t,n)=>{let i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),a=0,c=0,u=0;for(let l=0;l<o;++l){let h=i[r[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},Tl=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,o+=e[i&a>>s];if(s&&(o+=e[i&a<<t-s]),n)for(;o.length*t&7;)o+="=";return o},D=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>pt({prefix:e,name:r,encode(i){return Tl(i,n,t)},decode(i){return Sl(i,n,t,r)}});var E=Ie({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Al=Ie({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qn={};V(qn,{base32:()=>j,base32hex:()=>Pl,base32hexpad:()=>Nl,base32hexpadupper:()=>Dl,base32hexupper:()=>Il,base32pad:()=>Cl,base32padupper:()=>Ll,base32upper:()=>Bl,base32z:()=>Ml});var j=D({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bl=D({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Cl=D({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ll=D({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Pl=D({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Il=D({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nl=D({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Dl=D({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ml=D({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Uo=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return Ol(t,Vn(r),e||E.encoder);default:return Ul(t,Vn(r),e||j.encoder)}};var Ro=new WeakMap,Vn=r=>{let e=Ro.get(r);if(e==null){let t=new Map;return Ro.set(r,t),t}return e},x=class{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!==zt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Rl)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return x.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=Ve(e,t);return x.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 x.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&Po(e.multihash,n.multihash)}toString(e){return Uo(this,e)}toJSON(){return{"/":Uo(this)}}link(){return this}get[Symbol.toStringTag](){return"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 x)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new x(n,i,o,s||zo(n,i,o.bytes))}else if(t[zl]===!0){let{version:n,multihash:i,code:o}=t,s=br(i);return x.create(n,o,s)}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!==zt)throw new Error(`Version 0 CID must use dag-pb (code: ${zt}) block encoding`);return new x(e,t,n,n.bytes)}case 1:{let i=zo(e,t,n.bytes);return new x(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return x.create(0,zt,e)}static createV1(e,t){return x.create(1,e,t)}static decode(e){let[t,n]=x.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=x.inspectBytes(e),n=t.size-t.multihashSize,i=xe(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new ht(t.multihashCode,t.digestSize,o,i);return[t.version===0?x.createV0(s):x.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=Rt(e.subarray(t));return t+=d,h},i=n(),o=zt;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=Fl(e,t),o=x.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Vn(o).set(n,e),o}},Fl=(r,e)=>{switch(r[0]){case"Q":{let t=e||E;return[E.prefix,t.decode(`${E.prefix}${r}`)]}case E.prefix:{let t=e||E;return[E.prefix,t.decode(r)]}case j.prefix:{let t=e||j;return[j.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},Ol=(r,e,t)=>{let{prefix:n}=t;if(n!==E.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i},Ul=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i},zt=112,Rl=18,zo=(r,e,t)=>{let n=ft(r),i=n+ft(e),o=new Uint8Array(i+t.byteLength);return lt(r,o,0),lt(e,o,n),o.set(t,i),o},zl=Symbol.for("@ipld/js-cid/CID");var aa=U(es(),1);var $t=U(ls(),1);function pf(r){let e=new Uint8Array(r.reduce((n,i)=>n+$t.default.encodingLength(i),0)),t=0;for(let n of r)e=$t.encode(n,e,t),t+=$t.default.encodingLength(n);return e}var fs=pf;var se=U(ys(),1);var Kn={};V(Kn,{base64:()=>Wt,base64pad:()=>Af,base64url:()=>Bf,base64urlpad:()=>Cf});var Wt=D({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Af=D({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Bf=D({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Cf=D({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});se.default.formatters.b=r=>r==null?"undefined":E.baseEncode(r);se.default.formatters.t=r=>r==null?"undefined":j.baseEncode(r);se.default.formatters.m=r=>r==null?"undefined":Wt.baseEncode(r);se.default.formatters.p=r=>r==null?"undefined":r.toString();se.default.formatters.c=r=>r==null?"undefined":r.toString();se.default.formatters.k=r=>r==null?"undefined":r.toString();function Lf(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function wt(r){let e=Lf(`${r}:trace`);return se.default.enabled(`${r}:trace`)&&se.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,se.default)(`${r}:trace`)),Object.assign((0,se.default)(r),{error:(0,se.default)(`${r}:error`),trace:e})}function Qe(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 Ke=class{constructor(e,t,n){this._refCounter=1,this.cid=e,this.priority=t??1,this.wantType=n}inc(){this._refCounter+=1}dec(){this._refCounter=Math.max(0,this._refCounter-1)}hasRefs(){return this._refCounter>0}get[Symbol.toStringTag](){return`WantlistEntry <key: ${this.cid.toString(E)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(e){return this._refCounter===e._refCounter&&this.cid.equals(e.cid)&&this.priority===e.priority&&this.wantType===e.wantType}};var Ne=class{constructor(e,t,n,i,o){this.entry=new Ke(e,t,n),this.cancel=!!i,this.sendDontHave=!!o}get cid(){return this.entry.cid}set cid(e){this.entry.cid=e}get priority(){return this.entry.priority}set priority(e){this.entry.priority=e}get wantType(){return this.entry.wantType}set wantType(e){this.entry.wantType=e}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(E)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(e){return this.cancel===e.cancel&&this.sendDontHave===e.sendDontHave&&this.wantType===e.wantType&&this.entry.equals(e.entry)}};var ae=(r,e)=>{let t=["bitswap"];return e!=null&&t.push(e),r!=null&&t.push(`${r.toString().slice(0,8)}`),wt(t.join(":"))};var xr=(r,e)=>{if(r.size!==e.size)return!1;for(let[t,n]of r){let i=e.get(t);if(i===void 0||n instanceof Uint8Array&&i instanceof Uint8Array&&!Qe(n,i)||n instanceof Ne&&i instanceof Ne&&!n.equals(i))return!1}return!0};var ci=U(ei(),1),na=U(Ks(),1),ia=U(Je(),1),ui=U(ai(),1),oa=U(ra(),1);function Rf(){ia.default._configure(),ci.default._configure(na.default),ui.default._configure(oa.default)}Rf();var sa=["uint64","int64","sint64","fixed64","sfixed64"];function zf(r){for(let e of sa){if(r[e]==null)continue;let t=r[e];r[e]=function(){return BigInt(t.call(this).toString())}}return r}function li(r){return zf(new ci.default(r))}function $f(r){for(let e of sa){if(r[e]==null)continue;let t=r[e];r[e]=function(n){return t.call(this,n.toString())}}return r}function fi(){return $f(ui.default.create())}function Ye(r,e){let t=li(r instanceof Uint8Array?r:r.subarray());return e.decode(t)}function et(r,e){let t=fi();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var _t;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(_t||(_t={}));function Ar(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Br(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return Ar("enum",_t.VARINT,t,n)}function tt(r,e){return Ar("message",_t.LENGTH_DELIMITED,r,e)}var G;(function(r){let e;(function(a){let c;(function(d){d.Block="Block",d.Have="Have"})(c=a.WantType||(a.WantType={}));let u;(function(d){d[d.Block=0]="Block",d[d.Have=1]="Have"})(u||(u={})),function(d){d.codec=()=>Br(u)}(c=a.WantType||(a.WantType={}));let l;(function(d){let v;d.codec=()=>(v==null&&(v=tt((y,g,k={})=>{k.lengthDelimited!==!1&&g.fork(),y.block!=null&&y.block.byteLength>0&&(g.uint32(10),g.bytes(y.block)),y.priority!=null&&y.priority!==0&&(g.uint32(16),g.int32(y.priority)),y.cancel!=null&&y.cancel!==!1&&(g.uint32(24),g.bool(y.cancel)),y.wantType!=null&&u[y.wantType]!==0&&(g.uint32(32),r.Wantlist.WantType.codec().encode(y.wantType,g)),y.sendDontHave!=null&&y.sendDontHave!==!1&&(g.uint32(40),g.bool(y.sendDontHave)),k.lengthDelimited!==!1&&g.ldelim()},(y,g)=>{let k={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},I=g==null?y.len:y.pos+g;for(;y.pos<I;){let O=y.uint32();switch(O>>>3){case 1:k.block=y.bytes();break;case 2:k.priority=y.int32();break;case 3:k.cancel=y.bool();break;case 4:k.wantType=r.Wantlist.WantType.codec().decode(y);break;case 5:k.sendDontHave=y.bool();break;default:y.skipType(O&7);break}}return k})),v),d.encode=y=>et(y,d.codec()),d.decode=y=>Ye(y,d.codec())})(l=a.Entry||(a.Entry={}));let h;a.codec=()=>(h==null&&(h=tt((d,v,y={})=>{if(y.lengthDelimited!==!1&&v.fork(),d.entries!=null)for(let g of d.entries)v.uint32(10),r.Wantlist.Entry.codec().encode(g,v);d.full!=null&&d.full!==!1&&(v.uint32(16),v.bool(d.full)),y.lengthDelimited!==!1&&v.ldelim()},(d,v)=>{let y={entries:[],full:!1},g=v==null?d.len:d.pos+v;for(;d.pos<g;){let k=d.uint32();switch(k>>>3){case 1:y.entries.push(r.Wantlist.Entry.codec().decode(d,d.uint32()));break;case 2:y.full=d.bool();break;default:d.skipType(k&7);break}}return y})),h),a.encode=d=>et(d,a.codec()),a.decode=d=>Ye(d,a.codec())})(e=r.Wantlist||(r.Wantlist={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=tt((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.prefix!=null&&u.prefix.byteLength>0&&(l.uint32(10),l.bytes(u.prefix)),u.data!=null&&u.data.byteLength>0&&(l.uint32(18),l.bytes(u.data)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={prefix:new Uint8Array(0),data:new Uint8Array(0)},d=l==null?u.len:u.pos+l;for(;u.pos<d;){let v=u.uint32();switch(v>>>3){case 1:h.prefix=u.bytes();break;case 2:h.data=u.bytes();break;default:u.skipType(v&7);break}}return h})),c),a.encode=u=>et(u,a.codec()),a.decode=u=>Ye(u,a.codec())})(t=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(i||(i={})),function(a){a.codec=()=>Br(i)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let o;(function(a){let c;a.codec=()=>(c==null&&(c=tt((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.cid!=null&&u.cid.byteLength>0&&(l.uint32(10),l.bytes(u.cid)),u.type!=null&&i[u.type]!==0&&(l.uint32(16),r.BlockPresenceType.codec().encode(u.type,l)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={cid:new Uint8Array(0),type:n.Have},d=l==null?u.len:u.pos+l;for(;u.pos<d;){let v=u.uint32();switch(v>>>3){case 1:h.cid=u.bytes();break;case 2:h.type=r.BlockPresenceType.codec().decode(u);break;default:u.skipType(v&7);break}}return h})),c),a.encode=u=>et(u,a.codec()),a.decode=u=>Ye(u,a.codec())})(o=r.BlockPresence||(r.BlockPresence={}));let s;r.codec=()=>(s==null&&(s=tt((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let l of a.blocks)c.uint32(18),c.bytes(l);if(a.payload!=null)for(let l of a.payload)c.uint32(26),r.Block.codec().encode(l,c);if(a.blockPresences!=null)for(let l of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(l,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={blocks:[],payload:[],blockPresences:[],pendingBytes:0},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:u.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:u.blocks.push(a.bytes());break;case 3:u.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:u.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:u.pendingBytes=a.int32();break;default:a.skipType(h&7);break}}return u})),s),r.encode=a=>et(a,r.codec()),r.decode=a=>Ye(a,r.codec())})(G||(G={}));var Cr=class extends Error{constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var Wf,B=class{constructor(e){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}get empty(){return this.blocks.size===0&&this.wantlist.size===0&&this.blockPresences.size===0}addEntry(e,t,n,i,o){n==null&&(n=B.WantType.Block);let s=e.toString(E),a=this.wantlist.get(s);a!=null?(a.wantType===n&&(a.priority=t),i===!0&&(a.cancel=!!i),o===!0&&(a.sendDontHave=!!o),n===B.WantType.Block&&a.wantType===B.WantType.Have&&(a.wantType=n)):this.wantlist.set(s,new Ne(e,t,n,i,o))}addBlock(e,t){let n=e.toString(E);this.blocks.set(n,t)}addHave(e){let t=e.toString(E);this.blockPresences.has(t)||this.blockPresences.set(t,B.BlockPresenceType.Have)}addDontHave(e){let t=e.toString(E);this.blockPresences.has(t)||this.blockPresences.set(t,B.BlockPresenceType.DontHave)}cancel(e){let t=e.toString(E);this.wantlist.delete(t),this.addEntry(e,0,B.WantType.Block,!0,!1)}setPendingBytes(e){this.pendingBytes=e}serializeToBitswap100(){return G.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),cancel:!!e.cancel,wantType:G.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}serializeToBitswap110(){let e={wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),wantType:t.wantType,cancel:!!t.cancel,sendDontHave:!!t.sendDontHave})),full:!!this.full},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[t,n]of this.blocks.entries()){let i=x.parse(t),o=i.version,s=i.code,a=i.multihash.code,c=i.multihash.digest.length,u=fs([o,s,a,c]);e.payload.push({prefix:u,data:n})}for(let[t,n]of this.blockPresences)e.blockPresences.push({cid:x.parse(t).bytes,type:n});return this.pendingBytes>0&&(e.pendingBytes=this.pendingBytes),G.encode(e)}equals(e){return!(this.full!==e.full||this.pendingBytes!==e.pendingBytes||!xr(this.wantlist,e.wantlist)||!xr(this.blocks,e.blocks)||!xr(this.blockPresences,e.blockPresences))}get[Symbol.toStringTag](){let e=Array.from(this.wantlist.keys()),t=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${e}, blocks: ${t}>`}};Wf=B;B.Entry=Ne;B.WantType={Block:G.Wantlist.WantType.Block,Have:G.Wantlist.WantType.Have};B.BlockPresenceType={Have:G.BlockPresenceType.Have,DontHave:G.BlockPresenceType.DontHave};B.deserialize=async(r,e)=>{let t=G.decode(r),n=t.wantlist?.full===!0,i=new B(n);return t.wantlist?.entries.forEach(o=>{if(o.block==null)return;let s=x.decode(o.block);i.addEntry(s,o.priority??0,o.wantType,!!o.cancel,!!o.sendDontHave)}),t.blockPresences.forEach(o=>{if(o.cid==null)return;let s=x.decode(o.cid);o.type===B.BlockPresenceType.Have?i.addHave(s):i.addDontHave(s)}),t.blocks.length>0?(await Promise.all(t.blocks.map(async o=>{let s=await je.digest(o),a=x.createV0(s);i.addBlock(a,o)})),i):(t.payload.length>0&&(await Promise.all(t.payload.map(async o=>{if(o.prefix==null||o.data==null)return;let s=(0,aa.default)(o.prefix),a=s[0],c=s[1],u=s[2],l=u===je.code?je:await e?.getHasher(u);if(l==null)throw new Cr("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let h=await l.digest(o.data),d=x.create(a,c,h);i.addBlock(d,o.data)})),i.setPendingBytes(t.pendingBytes)),i)};B.blockPresenceSize=r=>r.bytes.length+1;var hi=class extends Map{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 Fe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new hi({name:e,metrics:t}):n=new Map,n}var ca={Block:G.Wantlist.WantType.Block,Have:G.Wantlist.WantType.Have},Hf=(r,e)=>Array.prototype.slice.call(e,0).sort((t,n)=>{let i=r(t),o=r(n);return i<o?-1:i>o?1:0}),ke=class{constructor(e,t){this.set=t!=null?Fe({name:"ipfs_bitswap_wantlist",metrics:t.metrics}):new Map,this._stats=e}get length(){return this.set.size}add(e,t,n){let i=e.toString(E),o=this.set.get(i);o!=null?(o.inc(),o.priority=t,o.wantType===ca.Have&&n===ca.Block&&(o.wantType=n)):(this.set.set(i,new Ke(e,t,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(e){let t=e.toString(E),n=this.set.get(t);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(t),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(e){this.set.has(e)&&this.set.delete(e)}forEach(e){this.set.forEach(e)}entries(){return this.set.entries()}sortedEntries(){return new Map(Hf(e=>e[1].key,Array.from(this.set.entries())))}contains(e){let t=e.toString(E);return this.set.has(t)}get(e){let t=e.toString(E);return this.set.get(t)}};ke.Entry=Ke;var ua=Math.pow(2,31)-1,la=1e3,fa=1;var ha=qf;function qf(r,e,t){var n=null,i=null,o=function(){n&&(clearTimeout(n),i=null,n=null)},s=function(){var c=i;o(),c&&c()},a=function(){if(!e)return r.apply(this,arguments);var c=this,u=arguments,l=t&&!n;if(o(),i=function(){r.apply(c,u)},n=setTimeout(function(){if(n=null,!l){var h=i;return i=null,h()}},e),l)return i()};return a.cancel=o,a.flush=s,a}var Lr=class{constructor(e,t,n){this.peerId=t,this.network=n,this.refcnt=1,this._entries=[],this._log=ae(e,"msgqueue"),this.sendEntries=ha(this.sendEntries.bind(this),fa)}addMessage(e,t={}){e.empty||this.send(e,t)}addEntries(e,t={}){this._entries=this._entries.concat(e),this.sendEntries(t)}sendEntries(e={}){if(this._entries.length===0)return;let t=new B(!1);this._entries.forEach(n=>{n.cancel===!0?t.cancel(n.cid):t.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(t,e)}async send(e,t={}){try{await this.network.connectTo(this.peerId,t)}catch(n){this._log.error("cant connect to peer %p: %s",this.peerId,n.message);return}this._log("sending message to peer %p",this.peerId),this.network.sendMessage(this.peerId,e,t).catch(n=>{this._log.error("send error",n)})}};var Pr=class{constructor(e,t,n,i){this.peers=Fe({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new ke(n,i),this.network=t,this._peerId=e,this._log=ae(e,"want")}_addEntries(e,t,n,i={}){let o=e.map((s,a)=>new B.Entry(s,ua-a,B.WantType.Block,t));o.forEach(s=>{s.cancel?n===!0?this.wantlist.removeForce(s.cid.toString(E)):this.wantlist.remove(s.cid):(this._log("adding to wantlist"),this.wantlist.add(s.cid,s.priority))});for(let s of this.peers.values())s.addEntries(o,i)}_startPeerHandler(e){let t=this.peers.get(e.toString());if(t!=null){t.refcnt++;return}t=new Lr(this._peerId,e,this.network);let n=new B(!0);for(let i of this.wantlist.entries())n.addEntry(i[1].cid,i[1].priority);return t.addMessage(n),this.peers.set(e.toString(),t),t}_stopPeerHandler(e){let t=this.peers.get(e.toString());t!=null&&(t.refcnt--,!(t.refcnt>0)&&this.peers.delete(e.toString()))}wantBlocks(e,t={}){this._addEntries(e,!1,!1,t),t.signal?.addEventListener("abort",()=>{this.cancelWants(e)})}unwantBlocks(e){this._log("unwant blocks: %s",e.length),this._addEntries(e,!0,!0)}cancelWants(e){this._log("cancel wants: %s",e.length),this._addEntries(e,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(e){this._startPeerHandler(e)}disconnected(e){this._stopPeerHandler(e)}start(){}stop(){this.peers.forEach(e=>{this.disconnected(e.peerId)})}};function rt(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Ee(r=0){return globalThis.Buffer?.alloc!=null?rt(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function pe(r=0){return globalThis.Buffer?.allocUnsafe!=null?rt(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function pi(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=pe(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return rt(t)}var pa=Symbol.for("@achingbrain/uint8arraylist");function da(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 Ir(r){return!!r?.[pa]}var _e=class{constructor(...e){Object.defineProperty(this,pa,{value:!0}),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(Ir(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ir(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=da(this.bufs,e);return t.buf[t.index]}set(e,t){let n=da(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(Ir(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 pi(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:pi(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new _e;return o.length=i,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=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(s);break}let h=e-a;n.push(s.subarray(h,h+(t-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ir(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 o=256,s=new Int32Array(o);for(let h=0;h<o;h++)s[h]=-1;for(let h=0;h<i;h++)s[n[h]]=h;let a=s,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let h=t;h<=c;h+=l){l=0;for(let d=u;d>=0;d--){let v=this.get(h+d);if(n[d]!==v){l=Math.max(1,d-a[v]);break}}if(l===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=pe(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=Ee(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=Ee(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=Ee(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=pe(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=Ee(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=Ee(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=Ee(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=Ee(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=Ee(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof _e)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Qe(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new _e;return n.bufs=e,t==null&&(t=e.reduce((i,o)=>i+o.byteLength,0)),n.length=t,n}};function Nr(r){return r instanceof Uint8Array?{get(e){return r[e]},set(e,t){r[e]=t}}:{get(e){return r.get(e)},set(e,t){r.set(e,t)}}}var ma=4294967296,X=class{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(e===!0)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)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),t=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new X(n,t)}zzEncode(){let e=this.hi>>31,t=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new X(t,n)}toBytes(e,t=0){let n=Nr(e);for(;this.hi>0;)n.set(t++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(t++,this.lo&127|128),this.lo=this.lo>>>7;n.set(t++,this.lo)}static fromBigInt(e){if(e===0n)return new X;let t=e<0;t&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return t&&(n=~n>>>0,i=~i>>>0,++i>ma&&(i=0,++n>ma&&(n=0))),new X(n,i)}static fromNumber(e){if(e===0)return new X;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 X(i,n)}static fromBytes(e,t=0){let n=Nr(e),i=new X,o=0;if(e.length-t>4){for(;o<4;++o)if(i.lo=(i.lo|(n.get(t)&127)<<o*7)>>>0,n.get(t++)<128)return i;if(i.lo=(i.lo|(n.get(t)&127)<<28)>>>0,i.hi=(i.hi|(n.get(t)&127)>>4)>>>0,n.get(t++)<128)return i;o=0}else for(;o<4;++o){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(n.get(t)&127)<<o*7)>>>0,n.get(t++)<128)return i}if(e.length-t>4){for(;o<5;++o)if(i.hi=(i.hi|(n.get(t)&127)<<o*7+3)>>>0,n.get(t++)<128)return i}else if(t<e.byteLength)for(;o<5;++o){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(n.get(t)&127)<<o*7+3)>>>0,n.get(t++)<128)return i}throw RangeError("invalid varint encoding")}};var Vf=Math.pow(2,7),jf=Math.pow(2,14),Gf=Math.pow(2,21),Qf=Math.pow(2,28),Kf=Math.pow(2,35),Xf=Math.pow(2,42),Jf=Math.pow(2,49),Zf=Math.pow(2,56),Yf=Math.pow(2,63),nt={encodingLength(r){return r<Vf?1:r<jf?2:r<Gf?3:r<Qf?4:r<Kf?5:r<Xf?6:r<Jf?7:r<Zf?8:r<Yf?9:10},encode(r,e,t=0){if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=pe(nt.encodingLength(r))),X.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return X.fromBytes(r,e).toNumber(!0)}};function Dr(r){return r[Symbol.asyncIterator]!=null}var Mr=r=>{let e=nt.encodingLength(r),t=pe(e);return nt.encode(r,t),Mr.bytes=e,t};Mr.bytes=0;function Fr(r,e){e=e??{};let t=e.lengthEncoder??Mr;function*n(i){let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Dr(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}Fr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Mr;return new _e(t(r.byteLength),r)};var vt=U(Or(),1);var th=8,rh=1024*1024*4,it;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(it||(it={}));var mi=r=>{let e=nt.decode(r);return mi.bytes=nt.encodingLength(e),e};mi.bytes=0;function Vt(r,e){let t=new _e,n=it.LENGTH,i=-1,o=e?.lengthDecoder??mi,s=e?.maxLengthLength??th,a=e?.maxDataLength??rh;function*c(){for(;t.byteLength>0;){if(n===it.LENGTH)try{if(i=o(t),i<0)throw(0,vt.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,vt.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;t.consume(u),e?.onLength!=null&&e.onLength(i),n=it.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>s)throw(0,vt.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===it.DATA){if(t.byteLength<i)break;let u=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(u),yield u,n=it.LENGTH}}}return Dr(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,vt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,vt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Vt.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:o,value:s}=await r.next(t);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}}();return Vt(n,{...e??{},onLength:o=>{t=o}})};var Ur=class{constructor(e){if(!(e>0)||e-1&e)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}},xt=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ur(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 Ur(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()}};function kt(r={}){return ih(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 ih(r,e){e=e??{};let t=e.onEnd,n=new xt,i,o,s,a=async()=>n.isEmpty()?s?{done:!0}:await new Promise((g,k)=>{o=I=>{o=null,n.push(I);try{g(r(n))}catch(O){k(O)}return i}}):r(n),c=g=>o!=null?o(g):(n.push(g),i),u=g=>(n=new xt,o!=null?o({error:g}):(n.push({error:g}),i)),l=g=>{if(s)return i;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:g})},h=g=>s?i:(s=!0,g!=null?u(g):c({done:!0})),d=()=>(n=new xt,h(),{done:!0}),v=g=>(h(g),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:d,throw:v,push:l,end:h,get readableLength(){return n.size}},t==null)return i;let y=i;return i={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(g){return y.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return y.end(g),t!=null&&(t(g),t=void 0),i},get readableLength(){return y.readableLength}},i}function oh(r){return r[Symbol.asyncIterator]!=null}function sh(...r){let e=[];for(let t of r)oh(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=kt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let i of n)t.push(i)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Rr=sh;function gi(r,...e){if(r==null)throw new Error("Empty pipeline");if(yi(r)){let n=r;r=()=>n.source}else if(ba(r)||wa(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&yi(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)yi(t[n])&&(t[n]=ch(t[n]));return ah(...t)}var ah=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},wa=r=>r?.[Symbol.asyncIterator]!=null,ba=r=>r?.[Symbol.iterator]!=null,yi=r=>r==null?!1:r.sink!=null&&r.source!=null,ch=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=kt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let i,o=r.source;if(wa(o))i=async function*(){yield*o,n.end()};else if(ba(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Rr(n,i())}return r.source};var wi=Symbol.for("@libp2p/topology");var _a=()=>{},bi=class{constructor(e){this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??_a,this.onDisconnect=e.onDisconnect??_a}get[Symbol.toStringTag](){return wi.toString()}get[wi](){return!0}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};function va(r){return new bi(r)}var Pa=U(Ba(),1);var Gt=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ca(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function La(r,e,t){let n=t??{},i=Ca(r);async function*o(){let s,a=()=>{s?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:h}=n;throw new Gt(l,h)}let u=new Promise((l,h)=>{s=()=>{let{abortMessage:d,abortCode:v}=n;h(new Gt(d,v))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&await n.onAbort(r),typeof i.return=="function")try{let h=i.return();h instanceof Promise&&h.catch(d=>{n.onReturnError!=null&&n.onReturnError(d)})}catch(h){n.onReturnError!=null&&n.onReturnError(h)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}var C=class extends Event{constructor(e,t){super(e),this.detail=t}};function fh(r){return r[Symbol.asyncIterator]!=null}function hh(r,e){return fh(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 Et=hh;function dh(r){return r[Symbol.asyncIterator]!=null}function ph(r){if(dh(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Oe=ph;function mh(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 St=mh;function yh(r){return r[Symbol.asyncIterator]!=null}function gh(r,e){if(yh(r))return async function*(){for await(let a of r)yield e(a)}();let t=St(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of t)yield e(a)}();let s=e;return function*(){yield o;for(let a of t)yield s(a)}()}var vi=gh;var xi="/ipfs/bitswap/1.0.0",ki="/ipfs/bitswap/1.1.0",Ei="/ipfs/bitswap/1.2.0",bh=32,_h=128,vh=3e4,$r=class{constructor(e,t,n,i={}){this._log=ae(e.peerId,"network"),this._libp2p=e,this._bitswap=t,this._protocols=[xi],i.b100Only!==!0&&(this._protocols.unshift(ki),this._protocols.unshift(Ei)),this._stats=n,this._running=!1,this._onPeerConnect=this._onPeerConnect.bind(this),this._onPeerDisconnect=this._onPeerDisconnect.bind(this),this._onConnection=this._onConnection.bind(this),this._hashLoader=i.hashLoader??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=i.maxInboundStreams??bh,this._maxOutboundStreams=i.maxOutboundStreams??_h,this._incomingStreamTimeout=i.incomingStreamTimeout??vh}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let e=va({onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect});this._registrarIds=[];for(let t of this._protocols)this._registrarIds.push(await this._libp2p.register(t,e));this._libp2p.getConnections().forEach(t=>{this._onPeerConnect(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=[]}}_onConnection(e){if(!this._running)return;let{stream:t,connection:n}=e,i=new Pa.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",t.stat.protocol,n.remotePeer),await gi(La(t.source,i.signal),o=>Vt(o),async o=>{for await(let s of o){try{let a=await B.deserialize(s.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,a)}catch(a){this._bitswap._receiveError(a);break}i.reset()}})}).catch(o=>{this._log(o),t.abort(o)}).finally(()=>{i.clear(),t.close()})}_onPeerConnect(e){this._bitswap._onPeerConnected(e)}_onPeerDisconnect(e){this._bitswap._onPeerDisconnected(e)}findProviders(e,t={}){return t.onProgress?.(new C("bitswap:network:find-providers",e)),this._libp2p.contentRouting.findProviders(e,t)}async findAndConnect(e,t){await Oe(Et(vi(this.findProviders(e,t),async n=>await this.connectTo(n.id,t).catch(i=>{this._log.error(i)})),3)).catch(n=>{this._log.error(n)})}async provide(e,t={}){t.onProgress?.(new C("bitswap:network:provide",e)),await this._libp2p.contentRouting.provide(e,t)}async sendMessage(e,t,n={}){if(!this._running)throw new Error("network isn't running");let i=e.toString();this._log("sendMessage to %s",i,t),n.onProgress?.(new C("bitswap:network:send-wantlist",e)),await this._writeMessage(e,t,n),this._updateSentStats(e,t.blocks)}async connectTo(e,t={}){if(!this._running)throw new Error("network isn't running");return t.onProgress?.(new C("bitswap:network:dial",e)),await this._libp2p.dial(e,t)}_updateSentStats(e,t){let n=e.toString();if(this._stats!=null){for(let i of t.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",t.size)}}async _writeMessage(e,t,n={}){let i=await this._libp2p.dialProtocol(e,[Ei,ki,xi]);try{let o;switch(i.stat.protocol){case xi:o=t.serializeToBitswap100();break;case ki:case Ei:o=t.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${i.stat.protocol}`)}await gi([o],s=>Fr(s),i)}catch(o){n.onProgress?.(new C("bitswap:network:send-wantlist:error",{peer:e,error:o})),this._log(o)}finally{i.close()}}};var Wr=class{constructor(e){this.partner=e,this.wantlist=new ke,this.exchangeCount=0,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=e}wants(e,t,n){this.wantlist.add(e,t,n)}cancelWant(e){this.wantlist.remove(e)}wantlistContains(e){return this.wantlist.get(e)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var Qt=class extends Map{constructor(e,t){super(),this._cmp=t??this._defaultSort,this._keys=[];for(let[n,i]of e??[])this.set(n,i)}update(e){if(e<0||e>=this._keys.length)return;let t=this._keys[e];this._keys.splice(e,1);let n=this._find(t);this._keys.splice(n,0,t)}set(e,t){if(this.has(e)){let i=this.indexOf(e);this._keys.splice(i,1)}super.set(e,t);let n=this._find(e);return this._keys.splice(n,0,e),this}clear(){super.clear(),this._keys=[]}delete(e){if(!this.has(e))return!1;let t=this.indexOf(e);return this._keys.splice(t,1),super.delete(e)}indexOf(e){if(!this.has(e))return-1;let t=this._find(e);if(this._keys[t]===e)return t;for(let n=1;n<this._keys.length;n++){if(this._keys[t+n]===e)return t+n;if(this._keys[t-n]===e)return t-n}return-1}_find(e){let t=0,n=this._keys.length;for(;t<n;){let i=t+n>>>1,o=this._kCmp(this._keys[i],e);if(o<0)t=i+1;else if(o>0)n=i;else return i}return t}*keys(){for(let e of this._keys)yield e}*values(){for(let e of this._keys)yield this.get(e)}*entries(){for(let e of this._keys)yield[e,this.get(e)]}*[Symbol.iterator](){yield*this.entries()}forEach(e,t=this){if(e!=null)for(let n of this._keys){let i=this.get(n);if(i==null)throw new Error("Value cannot be undefined");e.apply(t,[[n,i]])}}_defaultSort(e,t){return e[0]<t[0]?-1:t[0]<e[0]?1:0}_kCmp(e,t){return this._cmp([e,this.get(e)],[t,this.get(t)])}};var xh={hasNewInfo(){return!1},merge(){}},Hr=class{constructor(e=xh){this._taskMerger=e,this._byPeer=new Qt([],qr.compare)}pushTasks(e,t){let n=this._byPeer.get(e.toString());n==null&&(n=new qr(e,this._taskMerger)),n.pushTasks(t),this._byPeer.set(e.toString(),n)}popTasks(e){let t=this._head();if(t===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:i}=t.popTasks(e);if(n.length===0)return{tasks:n,pendingSize:i};let o=t.peerId;return t.isIdle()?this._byPeer.delete(o.toString()):this._byPeer.update(0),{peerId:o,tasks:n,pendingSize:i}}_head(){if(this._byPeer.size!==0)for(let[,e]of this._byPeer)return e}remove(e,t){this._byPeer.get(t.toString())?.remove(e)}tasksDone(e,t){let n=this._byPeer.get(e.toString());if(n==null)return;let i=this._byPeer.indexOf(e.toString());for(let o of t)n.taskDone(o);this._byPeer.update(i)}},qr=class{constructor(e,t){this.peerId=e,this._taskMerger=t,this._activeTotalSize=0,this._pending=new Si,this._active=new Set}pushTasks(e){for(let t of e)this._pushTask(t)}_pushTask(e){if(!this._taskHasMoreInfoThanActiveTasks(e))return;let t=this._pending.get(e.topic);if(t!=null){e.priority>t.priority&&this._pending.updatePriority(e.topic,e.priority),this._taskMerger.merge(e,t);return}this._pending.add(e)}_taskHasMoreInfoThanActiveTasks(e){let t=[];for(let n of this._active)n.topic===e.topic&&t.push(n);return t.length===0?!0:this._taskMerger.hasNewInfo(e,t)}popTasks(e){let t=0,n=[],i=this._pending.tasks();for(let o=0;o<i.length&&t<e;o++){let s=i[o];n.push(s),t+=s.size,this._pending.delete(s.topic),this._activeTotalSize+=s.size,this._active.add(s)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(e){this._active.has(e)&&(this._activeTotalSize-=e.size,this._active.delete(e))}remove(e){this._pending.delete(e)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(e,t){return e[1]._pending.length===0?1:t[1]._pending.length===0?-1:e[1]._activeTotalSize===t[1]._activeTotalSize?t[1]._pending.length-e[1]._pending.length:e[1]._activeTotalSize-t[1]._activeTotalSize}},Si=class{constructor(){this._tasks=new Qt([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((e,t)=>e+t.task.size,0)}get(e){return this._tasks?.get(e)?.task}add(e){this._tasks.set(e.topic,{created:Date.now(),task:e})}delete(e){this._tasks.delete(e)}tasks(){return[...this._tasks.values()].map(e=>e.task)}updatePriority(e,t){let n=this._tasks.get(e);if(n==null)return;let i=this._tasks.indexOf(e);n.task.priority=t,this._tasks.update(i)}_compare(e,t){return e[1].task.priority===t[1].task.priority?e[1].created-t[1].created:t[1].task.priority-e[1].task.priority}};var Ia={hasNewInfo(r,e){let t=!1,n=!1;for(let i of e)i.data.haveBlock&&(t=!0),i.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!t&&r.data.haveBlock)},merge(r,e){let t=r.data,n=e.data;!n.haveBlock&&t.haveBlock&&(n.haveBlock=t.haveBlock,n.blockSize=t.blockSize),!n.isWantBlock&&t.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||t.haveBlock)&&(n.haveBlock=t.haveBlock,e.size=r.size)),n.isWantBlock&&n.haveBlock&&(e.size=n.blockSize)}};var Na=B.WantType,kh=16*1024,Eh=1024,Vr=class{constructor(e,t,n,i,o,s={}){this._log=ae(e,"engine"),this.blockstore=t,this.network=n,this._stats=i,this._opts=this._processOpts(s),this.ledgerMap=Fe({name:"ipfs_bitswap_ledger_map",metrics:o.metrics}),this._running=!1,this._requestQueue=new Hr(Ia)}_processOpts(e){return{maxSizeReplaceHasWithBlock:Eh,targetMessageSize:kh,...e}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(e=>{this._log.error("error processing stats",e)})})}async _processTasks(){if(!this._running)return;let{peerId:e,tasks:t,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(t.length===0)return;let i=new B(!1);i.setPendingBytes(n);let o=[],s=new Map;for(let c of t){let u=x.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(o.push(u),s.set(c.topic,c.data)):i.addHave(u):i.addDontHave(u)}let a=await this._getBlocks(o);for(let[c,u]of s){let l=x.parse(c),h=a.get(c);h!=null?i.addBlock(l,h):u.sendDontHave&&i.addDontHave(l)}if(i.empty){e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks();return}try{e!=null&&await this.network.sendMessage(e,i);for(let[c,u]of a.entries())e!=null&&this.messageSent(e,x.parse(c),u)}catch(c){this._log.error(c)}e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks()}wantlistForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.partner)}receivedBlocks(e){if(e.length!==0){for(let t of this.ledgerMap.values())for(let{cid:n,block:i}of e){let o=t.wantlistContains(n);if(o==null)continue;let s=i.length,a=this._sendAsBlock(o.wantType,s),c=s;a||(c=B.blockPresenceSize(o.cid)),this._requestQueue.pushTasks(t.partner,[{topic:o.cid.toString(E),priority:o.priority,size:c,data:{blockSize:s,isWantBlock:a,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(e,t){let n=this._findOrCreate(e);if(t.empty)return;if(t.full&&(n.wantlist=new ke),this._updateBlockAccounting(t.blocks,n),t.wantlist.size===0){this._scheduleProcessTasks();return}let i=[],o=[];t.wantlist.forEach(s=>{s.cancel?(n.cancelWant(s.cid),i.push(s.cid)):(n.wants(s.cid,s.priority,s.wantType),o.push(s))}),this._cancelWants(e,i),await this._addWants(e,o),this._scheduleProcessTasks()}_cancelWants(e,t){for(let n of t)this._requestQueue.remove(n.toString(E),e)}async _addWants(e,t){let n=await this._getBlockSizes(t.map(o=>o.cid)),i=[];for(let o of t){let s=o.cid.toString(E),a=n.get(s);if(a==null)o.sendDontHave&&i.push({topic:s,priority:o.priority,size:B.blockPresenceSize(o.cid),data:{isWantBlock:o.wantType===Na.Block,blockSize:0,haveBlock:!1,sendDontHave:o.sendDontHave}});else{let c=this._sendAsBlock(o.wantType,a),u=a;c||(u=B.blockPresenceSize(o.cid)),i.push({topic:s,priority:o.priority,size:u,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:o.sendDontHave}})}this._requestQueue.pushTasks(e,i)}}_sendAsBlock(e,t){return e===Na.Block||t<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(e){let t=await this._getBlocks(e);return new Map([...t].map(([n,i])=>[n,i.length]))}async _getBlocks(e){let t=new Map;return await Promise.all(e.map(async n=>{try{let i=await this.blockstore.get(n);t.set(n.toString(E),i)}catch(i){i.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,i)}})),t}_updateBlockAccounting(e,t){for(let n of e.values())this._log("got block (%s bytes)",n.length),t.receivedBytes(n.length)}messageSent(e,t,n){let i=this._findOrCreate(e);i.sentBytes(n.length),i.wantlist.remove(t)}numBytesSentTo(e){return this._findOrCreate(e).accounting.bytesSent}numBytesReceivedFrom(e){return this._findOrCreate(e).accounting.bytesRecv}peerDisconnected(e){this.ledgerMap.delete(e.toString())}_findOrCreate(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return n;let i=new Wr(e);return this.ledgerMap.set(t,i),this._stats!=null&&this._stats.push(t,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var Ka=U(Qr(),1);var Ai={};V(Ai,{identity:()=>Ph});var Ph=pt({prefix:"\0",name:"identity",encode:r=>To(r),decode:r=>So(r)});var Bi={};V(Bi,{base2:()=>Ih});var Ih=D({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ci={};V(Ci,{base8:()=>Nh});var Nh=D({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Li={};V(Li,{base10:()=>Dh});var Dh=Ie({prefix:"9",name:"base10",alphabet:"0123456789"});var Pi={};V(Pi,{base16:()=>Mh,base16upper:()=>Fh});var Mh=D({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Fh=D({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ii={};V(Ii,{base36:()=>Kt,base36upper:()=>Oh});var Kt=Ie({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Oh=Ie({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ni={};V(Ni,{base256emoji:()=>Wh});var qa=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}"),Uh=qa.reduce((r,e,t)=>(r[t]=e,r),[]),Rh=qa.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function zh(r){return r.reduce((e,t)=>(e+=Uh[t],e),"")}function $h(r){let e=[];for(let t of r){let n=Rh[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Wh=pt({prefix:"\u{1F680}",name:"base256emoji",encode:zh,decode:$h});var Kr=85;var Dg=new TextEncoder,Mg=new TextDecoder;var Mi={...Ai,...Bi,...Ci,...Li,...Pi,...qn,...Ii,...Hn,...Kn,...Ni},zg={...Un,...Dn};function ja(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Va=ja("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Fi=ja("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=pe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),qh={utf8:Va,"utf-8":Va,hex:Mi.base16,latin1:Fi,ascii:Fi,binary:Fi,...Mi},Xr=qh;function ot(r,e="utf8"){let t=Xr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var Ga=r=>`unwant:${ot(r.multihash.bytes,"base64")}`,Qa=r=>`block:${ot(r.multihash.bytes,"base64")}`,Jr=class extends Ka.EventEmitter{constructor(e){super(),this.setMaxListeners(la),this._log=ae(e,"notif")}hasBlock(e,t){let n=Qa(e);this._log(n),this.emit(n,t)}async wantBlock(e,t={}){if(e==null)throw new Error("Not a valid cid");let n=Qa(e),i=Ga(e);return this._log(`wantBlock:${e}`),await new Promise((o,s)=>{let a=()=>{this.removeListener(n,c),t.onProgress?.(new C("bitswap:want-block:unwant",e)),s(new Error(`Block for ${e} unwanted`))},c=u=>{this.removeListener(i,a),t.onProgress?.(new C("bitswap:want-block:block",e)),o(u)};this.once(i,a),this.once(n,c),t.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),s(new Error(`Want for ${e} aborted`))})})}unwantBlock(e){let t=Ga(e);this._log(t),this.emit(t)}};var tc=U(Qr(),1);var Ya=U(Qr(),1),Oi=U(Za(),1),Xt=class extends Ya.EventEmitter{constructor(e,t){super(),this._options=t,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),e.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(i=>{(this._movingAverages[n][i]=(0,Oi.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}stop(){this._timeout!=null&&clearTimeout(this._timeout)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}push(e,t){this._enabled&&(this._queue.push([e,t,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout!=null&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let e=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-e),0)}_update(){if(this._timeout=void 0,this._queue.length>0){let e;for(;this._queue.length>0;){let t=e=this._queue.shift();t!=null&&this._applyOp(t)}e!=null&&this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let t=e-this._frequencyLastTime;t>0&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,t,e)}),this._frequencyLastTime=e}_updateFrequencyFor(e,t,n){let i=this._frequencyAccumulators[e]??0;this._frequencyAccumulators[e]=0;let o=i/t*1e3,s=this._movingAverages[e];s==null&&(s=this._movingAverages[e]={}),this._options.movingAverageIntervals.forEach(a=>{let c=s[a];c==null&&(c=s[a]=(0,Oi.default)(a)),c.push(n,o)})}_applyOp(e){let t=e[0],n=e[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,t)||(this._stats[t]=BigInt(0)),this._stats[t]=BigInt(this._stats[t])+BigInt(n),this._frequencyAccumulators[t]==null&&(this._frequencyAccumulators[t]=0),this._frequencyAccumulators[t]+=n}};var ec={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},Zr=class extends tc.EventEmitter{constructor(e,t=[],n=ec){super();let i=Object.assign({},ec,n);if(typeof i.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof i.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=t,this._options=i,this._enabled=this._options.enabled,this._global=new Xt(t,i),this._global.on("update",o=>this.emit("update",o)),this._peers=Fe({name:"ipfs_bitswap_stats_peers",metrics:e.metrics})}enable(){this._enabled=!0,this._options.enabled=!0,this._global.enable()}disable(){this._enabled=!1,this._options.enabled=!1,this._global.disable()}stop(){this._enabled=!1,this._global.stop();for(let e of this._peers)e[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(e){let t=e.toString();return this._peers.get(t)}push(e,t,n){if(this._enabled&&(this._global.push(t,n),e!=null)){let i=this._peers.get(e);i==null&&(i=new Xt(this._initialCounters,this._options),this._peers.set(e,i)),i.push(t,n)}}disconnected(e){let t=e.toString(),n=this._peers.get(t);n!=null&&(n.stop(),this._peers.delete(t))}};var ic=U(nc(),1);function jh(r){return r[Symbol.asyncIterator]!=null}function Gh(r,e){if(jh(r))return async function*(){for await(let a of r)await e(a),yield a}();let t=St(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();if(typeof e(n)?.then=="function")return async function*(){yield n;for await(let a of t)await e(a),yield a}();let s=e;return function*(){yield n;for(let a of t)s(a),yield a}()}var Jt=Gh;var Qh={async getHasher(){throw new Error("Not implemented")}},Kh={maxInboundStreams:32,maxOutboundStreams:128,incomingStreamTimeout:3e4,hashLoader:Qh,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},Xh=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],Yr=class{constructor(e,t,n={}){this._libp2p=e,this._log=ae(this.peerId),this._options=Object.assign({},Kh,n),this.stats=new Zr(e,Xh,{enabled:this._options.statsEnabled,computeThrottleTimeout:this._options.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:this._options.statsComputeThrottleMaxQueueSize}),this.network=new $r(e,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=t,this.engine=new Vr(this.peerId,t,this.network,this.stats,e),this.wm=new Pr(this.peerId,this.network,this.stats,e),this.notifications=new Jr(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(e,t){try{await this.engine.messageReceived(e,t)}catch{this._log("failed to receive message",t)}if(t.blocks.size===0)return;let n=[];for(let[i,o]of t.blocks.entries()){let s=x.parse(i);n.push({wasWanted:this.wm.wantlist.contains(s),cid:s,data:o})}this.wm.cancelWants(n.filter(({wasWanted:i})=>i).map(({cid:i})=>i)),await Promise.all(n.map(async({cid:i,wasWanted:o,data:s})=>{await this._handleReceivedBlock(e,i,s,o)}))}async _handleReceivedBlock(e,t,n,i){this._log("received block");let o=await this.blockstore.has(t);this._updateReceiveCounters(e.toString(),t,n,o),i&&await this.put(t,n)}_updateReceiveCounters(e,t,n,i){this.stats.push(e,"blocksReceived",1),this.stats.push(e,"dataReceived",n.length),i&&(this.stats.push(e,"dupBlksReceived",1),this.stats.push(e,"dupDataReceived",n.length))}_receiveError(e){this._log.error("ReceiveError",e)}_onPeerConnected(e){this.wm.connected(e)}_onPeerDisconnected(e){this.wm.disconnected(e),this.engine.peerDisconnected(e),this.stats.disconnected(e)}enableStats(){this.stats.enable()}disableStats(){this.stats.disable()}wantlistForPeer(e,t){return this.engine.wantlistForPeer(e)}ledgerForPeer(e){return this.engine.ledgerForPeer(e)}async want(e,t={}){let n=async(c,u)=>(this.wm.wantBlocks([c],u),await this.notifications.wantBlock(c,u)),i=!1,o=async(c,u)=>{try{return await this.blockstore.get(c,u)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l;return i||(i=!0,this.network.findAndConnect(c,u).catch(h=>{this._log.error(h)})),await n(c,u)}},s=new AbortController,a=t.signal!=null?(0,ic.anySignal)([t.signal,s.signal]):s.signal;try{return await Promise.race([this.notifications.wantBlock(e,{...t,signal:a}),o(e,{...t,signal:a})])}finally{s.abort()}}unwant(e){let t=Array.isArray(e)?e:[e];this.wm.unwantBlocks(t),t.forEach(n=>{this.notifications.unwantBlock(n)})}cancelWants(e){this.wm.cancelWants(Array.isArray(e)?e:[e])}async put(e,t,n){await this.blockstore.put(e,t),this.notify(e,t)}async*putMany(e,t){yield*this.blockstore.putMany(Jt(e,({cid:n,block:i})=>{this.notify(n,i)}),t)}notify(e,t,n={}){this.notifications.hasBlock(e,t),this.engine.receivedBlocks([{cid:e,block:t}]),this.network.provide(e,n).catch(i=>{this._log.error("Failed to provide: %s",i.message)})}getWantlist(){return this.wm.wantlist.entries()}get peers(){return this.engine.peers()}async start(){this.wm.start(),await this.network.start(),this.engine.start(),this.started=!0}async stop(){this.stats.stop(),this.wm.stop(),await this.network.stop(),this.engine.stop(),this.started=!1}};var oc=(r,e,t={})=>new Yr(r,e,t);async function*Ri(r,e){for await(let t of r)await e(t)&&(yield t)}var yc=U(ac(),1);var Yt=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},$i=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},cc=r=>globalThis.DOMException===void 0?new $i(r):new DOMException(r),uc=r=>{let e=r.reason===void 0?cc("This operation was aborted."):r.reason;return e instanceof Error?e:cc(e)};function Wi(r,e,t,n){let i,o=new Promise((s,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(uc(c)),c.addEventListener("abort",()=>{a(uc(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{s(t())}catch(l){a(l)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new Yt(c);typeof r.cancel=="function"&&r.cancel(),a(u)},e),(async()=>{try{s(await r)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return o.clear=()=>{clearTimeout(i),i=void 0},o}function Hi(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var st=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Se,er=class{constructor(){Se.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&st(this,Se,"f")[this.size-1].priority>=t.priority){st(this,Se,"f").push(n);return}let i=Hi(st(this,Se,"f"),n,(o,s)=>s.priority-o.priority);st(this,Se,"f").splice(i,0,n)}dequeue(){let e=st(this,Se,"f").shift();return e?.run}filter(e){return st(this,Se,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return st(this,Se,"f").length}};Se=new WeakMap;var N=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},b=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},F,rr,nr,Re,an,ir,tn,me,tr,J,rn,Z,or,Ue,nn,lc,fc,pc,hc,dc,on,qi,Vi,cn,mc,sn,un=class extends Error{},Te=class extends yc.default{constructor(e){var t,n,i,o;if(super(),F.add(this),rr.set(this,void 0),nr.set(this,void 0),Re.set(this,0),an.set(this,void 0),ir.set(this,void 0),tn.set(this,0),me.set(this,void 0),tr.set(this,void 0),J.set(this,void 0),rn.set(this,void 0),Z.set(this,0),or.set(this,void 0),Ue.set(this,void 0),nn.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:er,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);N(this,rr,e.carryoverConcurrencyCount,"f"),N(this,nr,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),N(this,an,e.intervalCap,"f"),N(this,ir,e.interval,"f"),N(this,J,new e.queueClass,"f"),N(this,rn,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,N(this,nn,e.throwOnTimeout===!0,"f"),N(this,Ue,e.autoStart===!1,"f")}get concurrency(){return b(this,or,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);N(this,or,e,"f"),b(this,F,"m",cn).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:b(this,nn,"f"),...t},new Promise((n,i)=>{b(this,J,"f").enqueue(async()=>{var o,s,a;N(this,Z,(s=b(this,Z,"f"),s++,s),"f"),N(this,Re,(a=b(this,Re,"f"),a++,a),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new un("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=Wi(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,b(this,F,"m",mc).call(this,t.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Yt&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{b(this,F,"m",pc).call(this)}},t),this.emit("add"),b(this,F,"m",on).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return b(this,Ue,"f")?(N(this,Ue,!1,"f"),b(this,F,"m",cn).call(this),this):this}pause(){N(this,Ue,!0,"f")}clear(){N(this,J,new(b(this,rn,"f")),"f")}async onEmpty(){b(this,J,"f").size!==0&&await b(this,F,"m",sn).call(this,"empty")}async onSizeLessThan(e){b(this,J,"f").size<e||await b(this,F,"m",sn).call(this,"next",()=>b(this,J,"f").size<e)}async onIdle(){b(this,Z,"f")===0&&b(this,J,"f").size===0||await b(this,F,"m",sn).call(this,"idle")}get size(){return b(this,J,"f").size}sizeBy(e){return b(this,J,"f").filter(e).length}get pending(){return b(this,Z,"f")}get isPaused(){return b(this,Ue,"f")}};rr=new WeakMap,nr=new WeakMap,Re=new WeakMap,an=new WeakMap,ir=new WeakMap,tn=new WeakMap,me=new WeakMap,tr=new WeakMap,J=new WeakMap,rn=new WeakMap,Z=new WeakMap,or=new WeakMap,Ue=new WeakMap,nn=new WeakMap,F=new WeakSet,lc=function(){return b(this,nr,"f")||b(this,Re,"f")<b(this,an,"f")},fc=function(){return b(this,Z,"f")<b(this,or,"f")},pc=function(){var e;N(this,Z,(e=b(this,Z,"f"),e--,e),"f"),b(this,F,"m",on).call(this),this.emit("next")},hc=function(){b(this,F,"m",Vi).call(this),b(this,F,"m",qi).call(this),N(this,tr,void 0,"f")},dc=function(){let e=Date.now();if(b(this,me,"f")===void 0){let t=b(this,tn,"f")-e;if(t<0)N(this,Re,b(this,rr,"f")?b(this,Z,"f"):0,"f");else return b(this,tr,"f")===void 0&&N(this,tr,setTimeout(()=>{b(this,F,"m",hc).call(this)},t),"f"),!0}return!1},on=function(){if(b(this,J,"f").size===0)return b(this,me,"f")&&clearInterval(b(this,me,"f")),N(this,me,void 0,"f"),this.emit("empty"),b(this,Z,"f")===0&&this.emit("idle"),!1;if(!b(this,Ue,"f")){let e=!b(this,F,"a",dc);if(b(this,F,"a",lc)&&b(this,F,"a",fc)){let t=b(this,J,"f").dequeue();return t?(this.emit("active"),t(),e&&b(this,F,"m",qi).call(this),!0):!1}}return!1},qi=function(){b(this,nr,"f")||b(this,me,"f")!==void 0||(N(this,me,setInterval(()=>{b(this,F,"m",Vi).call(this)},b(this,ir,"f")),"f"),N(this,tn,Date.now()+b(this,ir,"f"),"f"))},Vi=function(){b(this,Re,"f")===0&&b(this,Z,"f")===0&&b(this,me,"f")&&(clearInterval(b(this,me,"f")),N(this,me,void 0,"f")),N(this,Re,b(this,rr,"f")?b(this,Z,"f"):0,"f"),b(this,F,"m",cn).call(this)},cn=function(){for(;b(this,F,"m",on).call(this););},mc=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new un("The task was aborted."))},{once:!0})})},sn=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};var ji=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Gi=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},gc=r=>globalThis.DOMException===void 0?new Gi(r):new DOMException(r),wc=r=>{let e=r.reason===void 0?gc("This operation was aborted."):r.reason;return e instanceof Error?e:gc(e)};function Qi(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,a=new Promise((c,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){c(r);return}if(e.signal){let{signal:h}=e;h.aborted&&u(wc(h)),h.addEventListener("abort",()=>{u(wc(h))})}let l=new ji;s=o.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?c():i instanceof Error?u(i):(l.message=i??`Promise timed out after ${t} milliseconds`,u(l))},t),(async()=>{try{c(await r)}catch(h){u(h)}finally{o.clearTimeout.call(void 0,s)}})()});return a.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},a}var bc=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var Ki="lock:worker:request-read",Xi="lock:worker:release-read",Ji="lock:master:grant-read",Zi="lock:worker:request-write",Yi="lock:worker:release-write",eo="lock:master:grant-write";var ze={},At=r=>{r.addEventListener("message",e=>{At.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{At.dispatchEvent("message",r,e)})};At.addEventListener=(r,e)=>{ze[r]==null&&(ze[r]=[]),ze[r].push(e)};At.removeEventListener=(r,e)=>{ze[r]!=null&&(ze[r]=ze[r].filter(t=>t===e))};At.dispatchEvent=function(r,e,t){ze[r]!=null&&ze[r].forEach(n=>n(e,t))};var to=At;var _c=(r,e,t,n,i)=>(o,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(o.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let h={type:l.data.type,name:l.data.name,identifier:l.data.identifier};h.type===n&&h.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)}))}}))},vc=(r,e,t,n)=>async()=>{let i=bc();return globalThis.postMessage({type:e,identifier:i,name:r}),await new Promise(o=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===i&&(globalThis.removeEventListener("message",s),o(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",s)})},Yh={singleProcess:!1},xc=r=>{if(r=Object.assign({},Yh,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return to.addEventListener("message",_c(t,"requestReadLock",Ki,Xi,Ji)),to.addEventListener("message",_c(t,"requestWriteLock",Zi,Yi,eo)),t}return{isWorker:!0,readLock:t=>vc(t,Ki,Ji,Xi),writeLock:t=>vc(t,Zi,eo,Yi)}};var at={},$e;async function ro(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>await Qi((async()=>await new Promise(i=>{t(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var ed=(r,e)=>{if($e.isWorker===!0)return{readLock:$e.readLock(r,e),writeLock:$e.writeLock(r,e)};let t=new Te({concurrency:1}),n;return{async readLock(){if(n!=null)return await ro(n,e);n=new Te({concurrency:e.concurrency,autoStart:!1});let i=n,o=ro(n,e);return t.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await o},async writeLock(){return n=null,await ro(t,e)}}},td={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function no(r){let e=Object.assign({},td,r);return $e==null&&($e=xc(e),$e.isWorker!==!0&&($e.addEventListener("requestReadLock",t=>{at[t.data.name]!=null&&at[t.data.name].readLock().then(async n=>await t.data.handler().finally(()=>n()))}),$e.addEventListener("requestWriteLock",async t=>{at[t.data.name]!=null&&at[t.data.name].writeLock().then(async n=>await t.data.handler().finally(()=>n()))}))),at[e.name]==null&&(at[e.name]=ed(e.name,e)),at[e.name]}var ln=class{constructor(e,t,n={}){this.child=e,this.bitswap=n.bitswap,this.pins=t,this.lock=no({singleProcess:n.holdGcLock})}unwrap(){return this.child}async put(e,t,n={}){let i=await this.lock.readLock();try{return await this.child.has(e)?(n.onProgress?.(new C("blocks:put:duplicate",e)),e):(this.bitswap?.isStarted()===!0&&(n.onProgress?.(new C("blocks:put:bitswap:notify",e)),this.bitswap.notify(e,t,n)),n.onProgress?.(new C("blocks:put:blockstore:put",e)),await this.child.put(e,t,n))}finally{i()}}async*putMany(e,t={}){let n=await this.lock.readLock();try{let i=Ri(e,async({cid:s})=>{let a=await this.child.has(s);return a&&t.onProgress?.(new C("blocks:put-many:duplicate",s)),!a}),o=Jt(i,({cid:s,block:a})=>{t.onProgress?.(new C("blocks:put-many:bitswap:notify",s)),this.bitswap?.notify(s,a,t)});t.onProgress?.(new C("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}finally{n()}}async get(e,t={}){let n=await this.lock.readLock();try{if(this.bitswap?.isStarted()!=null&&!await this.child.has(e)){t.onProgress?.(new C("blocks:get:bitswap:get",e));let i=await this.bitswap.want(e,t);return t.onProgress?.(new C("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),i}return t.onProgress?.(new C("blocks:get:blockstore:get",e)),await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){let n=await this.lock.readLock();try{t.onProgress?.(new C("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Jt(e,async i=>{if(this.bitswap?.isStarted()===!0&&!await this.child.has(i)){t.onProgress?.(new C("blocks:get-many:bitswap:get",i));let o=await this.bitswap.want(i,t);t.onProgress?.(new C("blocks:get-many:blockstore:put",i)),await this.child.put(i,o,t)}}))}finally{n()}}async delete(e,t={}){let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");t.onProgress?.(new C("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){let n=await this.lock.writeLock();try{let i=this;t.onProgress?.(new C("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new Error("CID was pinned");yield o}}(),t)}finally{n()}}async has(e,t={}){let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){let t=await this.lock.readLock();try{e.onProgress?.(new C("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}finally{t()}}};var kc=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");function fn(r,e="utf8"){let t=Xr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?rt(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var Ae="/",Ec=new TextEncoder().encode(Ae),hn=Ec[0],P=class{constructor(e,t){if(typeof e=="string")this._buf=fn(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==hn)throw new Error("Invalid key")}toString(e="utf8"){return ot(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new P(e.join(Ae))}static random(){return new P(kc().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new P(e):typeof e.uint8Array=="function"?new P(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Ec),this._buf[0]!==hn){let e=new Uint8Array(this._buf.byteLength+1);e.fill(hn,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===hn;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return t.length<n.length}reverse(){return P.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ae).slice(1)}type(){return rd(this.baseNamespace())}name(){return nd(this.baseNamespace())}instance(e){return new P(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ae)||(e+=Ae),e+=this.type(),new P(e)}parent(){let e=this.list();return e.length===1?new P(Ae):new P(e.slice(0,-1).join(Ae))}child(e){return this.toString()===Ae?e:e.toString()===Ae?this:new P(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return P.withNamespaces([...this.namespaces(),...id(e.map(t=>t.namespaces()))])}};function rd(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function nd(r){let e=r.split(":");return e[e.length-1]}function id(r){return[].concat(...r)}var od=["string","number","bigint","symbol"],sd=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Sc(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(od.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(ad(r))return"Buffer";let t=cd(r);return t||"Object"}function ad(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function cd(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(sd.includes(e))return e}var f=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};f.uint=new f(0,"uint",!0);f.negint=new f(1,"negint",!0);f.bytes=new f(2,"bytes",!0);f.string=new f(3,"string",!0);f.array=new f(4,"array",!1);f.map=new f(5,"map",!1);f.tag=new f(6,"tag",!1);f.float=new f(7,"float",!0);f.false=new f(7,"false",!0);f.true=new f(7,"true",!0);f.null=new f(7,"null",!0);f.undefined=new f(7,"undefined",!0);f.break=new f(7,"break",!0);var p=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Bt=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ud=new TextDecoder,ld=new TextEncoder;function dn(r){return Bt&&globalThis.Buffer.isBuffer(r)}function sr(r){return r instanceof Uint8Array?dn(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Cc=Bt?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Ac(r,e,t):(r,e,t)=>t-e>64?ud.decode(r.subarray(e,t)):Ac(r,e,t),pn=Bt?r=>r.length>64?globalThis.Buffer.from(r):Tc(r):r=>r.length>64?ld.encode(r):Tc(r),ve=r=>Uint8Array.from(r),Ct=Bt?(r,e,t)=>dn(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Lc=Bt?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),sr(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},Pc=Bt?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Ic(r,e){if(dn(r)&&dn(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Tc(r,e=1/0){let t,n=r.length,i=null,o=[];for(let s=0;s<n;++s){if(t=r.charCodeAt(s),t>55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return o}function Ac(r,e,t){let n=[];for(;e<t;){let i=r[e],o=null,s=i>239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(o=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(o=l))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return io(n)}var Bc=4096;function io(r){let e=r.length;if(e<=Bc)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Bc));return t}var fd=256,ar=class{constructor(e=fd){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Pc(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Ct(n,0,this.cursor)}else t=Lc(this.chunks,this.cursor);return e&&this.reset(),t}};var w="CBOR decode error:",Lt="CBOR encode error:",cr=[];cr[23]=1;cr[24]=2;cr[25]=3;cr[26]=5;cr[27]=9;function Be(r,e,t){if(r.length-e<t)throw new Error(`${w} not enough data for type`)}var z=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Y(r,e,t){Be(r,e,1);let n=r[e];if(t.strict===!0&&n<z[0])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return n}function ee(r,e,t){Be(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<z[1])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return n}function te(r,e,t){Be(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<z[2])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return n}function re(r,e,t){Be(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&o<z[3])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${w} integers outside of the safe integer range are not supported`)}function Nc(r,e,t,n){return new p(f.uint,Y(r,e+1,n),2)}function Dc(r,e,t,n){return new p(f.uint,ee(r,e+1,n),3)}function Mc(r,e,t,n){return new p(f.uint,te(r,e+1,n),5)}function Fc(r,e,t,n){return new p(f.uint,re(r,e+1,n),9)}function ue(r,e){return W(r,0,e.value)}function W(r,e,t){if(t<z[0]){let n=Number(t);r.push([e|n])}else if(t<z[1]){let n=Number(t);r.push([e|24,n])}else if(t<z[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<z[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<z[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${w} encountered BigInt larger than allowable range`)}}ue.encodedSize=function(e){return W.encodedSize(e.value)};W.encodedSize=function(e){return e<z[0]?1:e<z[1]?2:e<z[2]?3:e<z[3]?5:9};ue.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Oc(r,e,t,n){return new p(f.negint,-1-Y(r,e+1,n),2)}function Uc(r,e,t,n){return new p(f.negint,-1-ee(r,e+1,n),3)}function Rc(r,e,t,n){return new p(f.negint,-1-te(r,e+1,n),5)}var oo=BigInt(-1),zc=BigInt(1);function $c(r,e,t,n){let i=re(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new p(f.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${w} integers outside of the safe integer range are not supported`);return new p(f.negint,oo-BigInt(i),9)}function mn(r,e){let t=e.value,n=typeof t=="bigint"?t*oo-zc:t*-1-1;W(r,e.type.majorEncoded,n)}mn.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*oo-zc:t*-1-1;return n<z[0]?1:n<z[1]?2:n<z[2]?3:n<z[3]?5:9};mn.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ur(r,e,t,n){Be(r,e,t+n);let i=Ct(r,e+t,e+t+n);return new p(f.bytes,i,t+n)}function Wc(r,e,t,n){return ur(r,e,1,t)}function Hc(r,e,t,n){return ur(r,e,2,Y(r,e+1,n))}function qc(r,e,t,n){return ur(r,e,3,ee(r,e+1,n))}function Vc(r,e,t,n){return ur(r,e,5,te(r,e+1,n))}function jc(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer bytes lengths not supported`);return ur(r,e,9,i)}function yn(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===f.string?pn(r.value):r.value),r.encodedBytes}function Pt(r,e){let t=yn(e);W(r,e.type.majorEncoded,t.length),r.push(t)}Pt.encodedSize=function(e){let t=yn(e);return W.encodedSize(t.length)+t.length};Pt.compareTokens=function(e,t){return dd(yn(e),yn(t))};function dd(r,e){return r.length<e.length?-1:r.length>e.length?1:Ic(r,e)}function lr(r,e,t,n,i){let o=t+n;Be(r,e,o);let s=new p(f.string,Cc(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=Ct(r,e+t,e+o)),s}function Gc(r,e,t,n){return lr(r,e,1,t,n)}function Qc(r,e,t,n){return lr(r,e,2,Y(r,e+1,n),n)}function Kc(r,e,t,n){return lr(r,e,3,ee(r,e+1,n),n)}function Xc(r,e,t,n){return lr(r,e,5,te(r,e+1,n),n)}function Jc(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer string lengths not supported`);return lr(r,e,9,i,n)}var Zc=Pt;function It(r,e,t,n){return new p(f.array,n,t)}function Yc(r,e,t,n){return It(r,e,1,t)}function eu(r,e,t,n){return It(r,e,2,Y(r,e+1,n))}function tu(r,e,t,n){return It(r,e,3,ee(r,e+1,n))}function ru(r,e,t,n){return It(r,e,5,te(r,e+1,n))}function nu(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer array lengths not supported`);return It(r,e,9,i)}function iu(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return It(r,e,1,1/0)}function gn(r,e){W(r,f.array.majorEncoded,e.value)}gn.compareTokens=ue.compareTokens;gn.encodedSize=function(e){return W.encodedSize(e.value)};function Nt(r,e,t,n){return new p(f.map,n,t)}function ou(r,e,t,n){return Nt(r,e,1,t)}function su(r,e,t,n){return Nt(r,e,2,Y(r,e+1,n))}function au(r,e,t,n){return Nt(r,e,3,ee(r,e+1,n))}function cu(r,e,t,n){return Nt(r,e,5,te(r,e+1,n))}function uu(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer map lengths not supported`);return Nt(r,e,9,i)}function lu(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return Nt(r,e,1,1/0)}function wn(r,e){W(r,f.map.majorEncoded,e.value)}wn.compareTokens=ue.compareTokens;wn.encodedSize=function(e){return W.encodedSize(e.value)};function fu(r,e,t,n){return new p(f.tag,t,1)}function hu(r,e,t,n){return new p(f.tag,Y(r,e+1,n),2)}function du(r,e,t,n){return new p(f.tag,ee(r,e+1,n),3)}function pu(r,e,t,n){return new p(f.tag,te(r,e+1,n),5)}function mu(r,e,t,n){return new p(f.tag,re(r,e+1,n),9)}function bn(r,e){W(r,f.tag.majorEncoded,e.value)}bn.compareTokens=ue.compareTokens;bn.encodedSize=function(e){return W.encodedSize(e.value)};var bd=20,_d=21,vd=22,xd=23;function yu(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${w} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new p(f.null,null,1):new p(f.undefined,void 0,1)}function gu(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return new p(f.break,void 0,1)}function so(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${w} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${w} Infinity values are not supported`)}return new p(f.float,r,e)}function wu(r,e,t,n){return so(ao(r,e+1),3,n)}function bu(r,e,t,n){return so(co(r,e+1),5,n)}function _u(r,e,t,n){return so(Eu(r,e+1),9,n)}function _n(r,e,t){let n=e.value;if(n===!1)r.push([f.float.majorEncoded|bd]);else if(n===!0)r.push([f.float.majorEncoded|_d]);else if(n===null)r.push([f.float.majorEncoded|vd]);else if(n===void 0)r.push([f.float.majorEncoded|xd]);else{let i,o=!1;(!t||t.float64!==!0)&&(xu(n),i=ao(ye,1),n===i||Number.isNaN(n)?(ye[0]=249,r.push(ye.slice(0,3)),o=!0):(ku(n),i=co(ye,1),n===i&&(ye[0]=250,r.push(ye.slice(0,5)),o=!0))),o||(kd(n),i=Eu(ye,1),ye[0]=251,r.push(ye.slice(0,9)))}}_n.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){xu(n);let i=ao(ye,1);if(n===i||Number.isNaN(n))return 3;if(ku(n),i=co(ye,1),n===i)return 5}return 9};var vu=new ArrayBuffer(9),le=new DataView(vu,1),ye=new Uint8Array(vu,0);function xu(r){if(r===1/0)le.setUint16(0,31744,!1);else if(r===-1/0)le.setUint16(0,64512,!1);else if(Number.isNaN(r))le.setUint16(0,32256,!1);else{le.setFloat32(0,r);let e=le.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)le.setUint16(0,31744,!1);else if(t===0)le.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?le.setUint16(0,0):i<-14?le.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):le.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function ao(r,e){if(r.length-e<2)throw new Error(`${w} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function ku(r){le.setFloat32(0,r,!1)}function co(r,e){if(r.length-e<4)throw new Error(`${w} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function kd(r){le.setFloat64(0,r,!1)}function Eu(r,e){if(r.length-e<8)throw new Error(`${w} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}_n.compareTokens=ue.compareTokens;function A(r,e,t){throw new Error(`${w} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function vn(r){return()=>{throw new Error(`${w} ${r}`)}}var m=[];for(let r=0;r<=23;r++)m[r]=A;m[24]=Nc;m[25]=Dc;m[26]=Mc;m[27]=Fc;m[28]=A;m[29]=A;m[30]=A;m[31]=A;for(let r=32;r<=55;r++)m[r]=A;m[56]=Oc;m[57]=Uc;m[58]=Rc;m[59]=$c;m[60]=A;m[61]=A;m[62]=A;m[63]=A;for(let r=64;r<=87;r++)m[r]=Wc;m[88]=Hc;m[89]=qc;m[90]=Vc;m[91]=jc;m[92]=A;m[93]=A;m[94]=A;m[95]=vn("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)m[r]=Gc;m[120]=Qc;m[121]=Kc;m[122]=Xc;m[123]=Jc;m[124]=A;m[125]=A;m[126]=A;m[127]=vn("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)m[r]=Yc;m[152]=eu;m[153]=tu;m[154]=ru;m[155]=nu;m[156]=A;m[157]=A;m[158]=A;m[159]=iu;for(let r=160;r<=183;r++)m[r]=ou;m[184]=su;m[185]=au;m[186]=cu;m[187]=uu;m[188]=A;m[189]=A;m[190]=A;m[191]=lu;for(let r=192;r<=215;r++)m[r]=fu;m[216]=hu;m[217]=du;m[218]=pu;m[219]=mu;m[220]=A;m[221]=A;m[222]=A;m[223]=A;for(let r=224;r<=243;r++)m[r]=vn("simple values are not supported");m[244]=A;m[245]=A;m[246]=A;m[247]=yu;m[248]=vn("simple values are not supported");m[249]=wu;m[250]=bu;m[251]=_u;m[252]=A;m[253]=A;m[254]=A;m[255]=gu;var ge=[];for(let r=0;r<24;r++)ge[r]=new p(f.uint,r,1);for(let r=-1;r>=-24;r--)ge[31-r]=new p(f.negint,r,1);ge[64]=new p(f.bytes,new Uint8Array(0),1);ge[96]=new p(f.string,"",1);ge[128]=new p(f.array,0,1);ge[160]=new p(f.map,0,1);ge[244]=new p(f.false,!1,1);ge[245]=new p(f.true,!0,1);ge[246]=new p(f.null,null,1);function Su(r){switch(r.type){case f.false:return ve([244]);case f.true:return ve([245]);case f.null:return ve([246]);case f.bytes:return r.value.length?void 0:ve([64]);case f.string:return r.value===""?ve([96]):void 0;case f.array:return r.value===0?ve([128]):void 0;case f.map:return r.value===0?ve([160]):void 0;case f.uint:return r.value<24?ve([Number(r.value)]):void 0;case f.negint:if(r.value>=-24)return ve([31-Number(r.value)])}}var Sd={float64:!1,mapSorter:Bd,quickEncodeToken:Su};function Td(){let r=[];return r[f.uint.major]=ue,r[f.negint.major]=mn,r[f.bytes.major]=Pt,r[f.string.major]=Zc,r[f.array.major]=gn,r[f.map.major]=wn,r[f.tag.major]=bn,r[f.float.major]=_n,r}var Tu=Td(),uo=new ar,Dt=class{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Lt} object contains circular references`);return new Dt(t,e)}},We={null:new p(f.null,null),undefined:new p(f.undefined,void 0),true:new p(f.true,!0),false:new p(f.false,!1),emptyArray:new p(f.array,0),emptyMap:new p(f.map,0)},He={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new p(f.float,r):r>=0?new p(f.uint,r):new p(f.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new p(f.uint,r):new p(f.negint,r)},Uint8Array(r,e,t,n){return new p(f.bytes,r)},string(r,e,t,n){return new p(f.string,r)},boolean(r,e,t,n){return r?We.true:We.false},null(r,e,t,n){return We.null},undefined(r,e,t,n){return We.undefined},ArrayBuffer(r,e,t,n){return new p(f.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new p(f.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[We.emptyArray,new p(f.break)]:We.emptyArray;n=Dt.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=xn(s,t,n);return t.addBreakTokens?[new p(f.array,r.length),i,new p(f.break)]:[new p(f.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[We.emptyMap,new p(f.break)]:We.emptyMap;n=Dt.createCheck(n,r);let a=[],c=0;for(let u of o)a[c++]=[xn(u,t,n),xn(i?r.get(u):r[u],t,n)];return Ad(a,t),t.addBreakTokens?[new p(f.map,s),a,new p(f.break)]:[new p(f.map,s),a]}};He.Map=He.Object;He.Buffer=He.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))He[`${r}Array`]=He.DataView;function xn(r,e={},t){let n=Sc(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||He[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=He[n];if(!o)throw new Error(`${Lt} unsupported type: ${n}`);return o(r,n,e,t)}function Ad(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Bd(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=Tu[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function Au(r,e,t,n){if(Array.isArray(e))for(let i of e)Au(r,i,t,n);else t[e.type.major](r,e,n)}function Bu(r,e,t){let n=xn(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new ar(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return sr(a.chunks[0])}}return uo.reset(),Au(uo,n,e,t),uo.toBytes(!0)}function kn(r,e){return e=Object.assign({},Sd,e),Bu(r,Tu,e)}var Cd={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},lo=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=ge[e];if(t===void 0){let n=m[e];if(!n)throw new Error(`${w} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},fr=Symbol.for("DONE"),En=Symbol.for("BREAK");function Ld(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=hr(e,t);if(o===En){if(r.value===1/0)break;throw new Error(`${w} got unexpected break to lengthed array`)}if(o===fr)throw new Error(`${w} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function Pd(r,e,t){let n=t.useMaps===!0,i=n?void 0:{},o=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=hr(e,t);if(a===En){if(r.value===1/0)break;throw new Error(`${w} got unexpected break to lengthed map`)}if(a===fr)throw new Error(`${w} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${w} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&o.has(a)||!n&&a in i))throw new Error(`${w} found repeat map key "${a}"`);let c=hr(e,t);if(c===fr)throw new Error(`${w} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?o.set(a,c):i[a]=c}return n?o:i}function hr(r,e){if(r.done())return fr;let t=r.next();if(t.type===f.break)return En;if(t.type.terminal)return t.value;if(t.type===f.array)return Ld(t,r,e);if(t.type===f.map)return Pd(t,r,e);if(t.type===f.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=hr(r,e);return e.tags[t.value](n)}throw new Error(`${w} tag not supported (${t.value})`)}throw new Error("unsupported")}function Ce(r,e){if(!(r instanceof Uint8Array))throw new Error(`${w} data to decode must be a Uint8Array`);e=Object.assign({},Cd,e);let t=e.tokenizer||new lo(r,e),n=hr(t,e);if(n===fr)throw new Error(`${w} did not find any content to decode`);if(n===En)throw new Error(`${w} got unexpected break`);if(!t.done())throw new Error(`${w} too many terminals, data makes no sense`);return n}function fo(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Id=new TextDecoder;function ho(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function Sn(r,e){let t;[t,e]=ho(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function Lu(r,e){let t;return[t,e]=ho(r,e),[t&7,t>>3,e]}function Nd(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=Lu(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Sn(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=Sn(r,n),e.Name=Id.decode(s)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=ho(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Pu(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let a,c;if([a,c,t]=Lu(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Sn(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,t]=Sn(r,t),n.push(Nd(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var Xb=new TextEncoder,Jb=2**32,Zb=2**31;var t0=new TextEncoder;var Iu=112;function Nu(r){let e=Pu(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let i={};try{i.Hash=x.decode(n.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(i.Name=n.Name),n.Tsize!==void 0&&(i.Tsize=n.Tsize),i})),t}var Du=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===f.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===f.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[f.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[f.negint.major](e,t){this[f.uint.major](e,t)}[f.bytes.major](e,t){throw new Error(`${Lt} unsupported type: Uint8Array`)}[f.string.major](e,t){this.prefix(e);let n=pn(JSON.stringify(t.value));e.push(n.length>32?sr(n):n)}[f.array.major](e,t){this.prefix(e),this.inRecursive.push({type:f.array,elements:0}),e.push([91])}[f.map.major](e,t){this.prefix(e),this.inRecursive.push({type:f.map,elements:0}),e.push([123])}[f.tag.major](e,t){}[f.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===f.array)e.push([93]);else if(s.type===f.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Lt} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],o=!1;for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s),!o&&(i[s]===46||i[s]===101||i[s]===69)&&(o=!0);o||(i.push(46),i.push(48)),e.push(i)}};var Mt=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}done(){return this.pos>=this.data.length}ch(){return this.data[this.pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this.pos]}expect(e){if(this.data.length-this.pos<e.length)throw new Error(`${w} unexpected end of input at position ${this.pos}`);for(let t=0;t<e.length;t++)if(this.data[this.pos++]!==e[t])throw new Error(`${w} unexpected token at position ${this.pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this.pos,t=!1,n=!1,i=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this.pos++;else break}};if(this.ch()===45&&(t=!0,this.pos++),this.ch()===48)if(this.pos++,this.ch()===46)this.pos++,n=!0;else return new p(f.uint,0,this.pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this.pos===e+1)throw new Error(`${w} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${w} unexpected token at position ${this.pos}`);n=!0,this.pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this.pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this.pos++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),s=parseFloat(o);return n?new p(f.float,s,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new p(s>=0?f.uint:f.negint,s,this.pos-e):new p(s>=0?f.uint:f.negint,BigInt(o),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${w} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let o=this.pos,s=0;o<this.data.length&&s<65536;o++,s++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this.pos,o));return this.pos=o+1,new p(f.string,c,s)}}let e=this.pos,t=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${w} unexpected end of unicode escape sequence at position ${this.pos}`);let o=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${w} unexpected unicode escape character at position ${this.pos}`);o=o*16+a,this.pos++}return o},i=()=>{let o=this.ch(),s=null,a=o>239?4:o>223?3:o>191?2:1;if(this.pos+a>this.data.length)throw new Error(`${w} unexpected unicode sequence at position ${this.pos}`);let c,u,l,h;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this.pos+1],(c&192)===128&&(h=(o&31)<<6|c&63,h>127&&(s=h));break;case 3:c=this.data[this.pos+1],u=this.data[this.pos+2],(c&192)===128&&(u&192)===128&&(h=(o&15)<<12|(c&63)<<6|u&63,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:c=this.data[this.pos+1],u=this.data[this.pos+2],l=this.data[this.pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(h=(o&15)<<18|(c&63)<<12|(u&63)<<6|l&63,h>65535&&h<1114112&&(s=h))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this.pos+=a};for(;!this.done();){let o=this.ch(),s;switch(o){case 92:if(this.pos++,this.done())throw new Error(`${w} unexpected string termination at position ${this.pos}`);switch(s=this.ch(),this.pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${w} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new p(f.string,io(t),this.pos-e);default:if(o<32)throw new Error(`${w} invalid control character at position ${this.pos}`);o<128?(t.push(o),this.pos++):i()}}throw new Error(`${w} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new p(f.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new p(f.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new p(f.null,null,4);case 102:return this.expect([102,97,108,115,101]),new p(f.false,!1,5);case 116:return this.expect([116,114,117,101]),new p(f.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${w} unexpected character at position ${this.pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this.pos++,this.skipWhitespace(),new p(f.break,void 0,1);if(this.ch()!==44)throw new Error(`${w} unexpected character at position ${this.pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this.pos++,this.skipWhitespace(),new p(f.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this.pos++,this.skipWhitespace(),new p(f.break,void 0,1);if(this.ch()!==44)throw new Error(`${w} unexpected character at position ${this.pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this.pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this.pos++,this.skipWhitespace(),new p(f.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${w} unexpected character at position ${this.pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${w} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function po(r,e){return e=Object.assign({tokenizer:new Mt(r,e)},e),Ce(r,e)}var Mu={codec:Iu,async*walk(r){yield*Nu(r).Links.map(t=>t.Hash)}},Fu={codec:Kr,async*walk(){}},Ou=42,Uu={codec:113,async*walk(r){let e=[],t=[];t[Ou]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let i=x.decode(n.subarray(1));return e.push(i),i},Ce(r,{tags:t}),yield*e}},mo=class extends Mt{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===f.map){let t=this._next();if(t.type===f.string&&t.value==="/"){let n=this._next();if(n.type===f.string){if(this._next().type!==f.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new p(f.tag,42,0)}if(n.type===f.map){let i=this._next();if(i.type===f.string&&i.value==="bytes"){let o=this._next();if(o.type===f.string){for(let a=0;a<2;a++)if(this._next().type!==f.break)throw new Error("Invalid encoded Bytes form");let s=Wt.decode(`m${o.value}`);return new p(f.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Ru={codec:297,async*walk(r){let e=[],t=[];t[Ou]=n=>{let i=x.parse(n);return e.push(i),i},po(r,{tags:t,tokenizer:new mo(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}};var Tn=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Ft,yo,zu,Fd=[Fu,Mu,Uu,Ru],Hu="/pin/",qu="/pinned-block/",go=Kt,$u=1;function Wu(r){return r.version===0&&(r=r.toV1()),new P(`${Hu}${r.toString(go)}`)}var An=class{constructor(e,t,n){Ft.add(this),this.datastore=e,this.blockstore=t,this.dagWalkers={},[...Fd,...n].forEach(i=>{this.dagWalkers[i.codec]=i})}async add(e,t={}){let n=Wu(e);if(await this.datastore.has(n))throw new Error("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Error("Depth must be greater than or equal to 0");let o=new Te({concurrency:$u});o.add(async()=>{await Tn(this,Ft,"m",yo).call(this,e,o,c=>{c.pinnedBy.find(u=>Qe(u,e.bytes))==null&&(c.pinCount++,c.pinnedBy.push(e.bytes))},{...t,depth:i})});let s=fo();o.on("error",c=>{o.clear(),s.reject(c)}),await Promise.race([o.onIdle(),s.promise]);let a={depth:i,metadata:t.metadata??{}};return await this.datastore.put(n,kn(a),t),{cid:e,...a}}async rm(e,t={}){let n=Wu(e),i=await this.datastore.get(n,t),o=Ce(i);await this.datastore.delete(n,t);let s=new Te({concurrency:$u});return s.add(async()=>{await Tn(this,Ft,"m",yo).call(this,e,s,a=>{a.pinCount--,a.pinnedBy=a.pinnedBy.filter(c=>Qe(c,e.bytes))},{...t,depth:o.depth})}),await s.onIdle(),{cid:e,...o}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Hu+(e.cid!=null?`${e.cid.toString(Kt)}`:"")},e)){let i=x.parse(t.toString().substring(5),Kt),o=Ce(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new P(`${qu}${go.encode(e.multihash.bytes)}`);return await this.datastore.has(n,t)}};Ft=new WeakSet,yo=async function r(e,t,n,i){if(i.depth===-1)return;let o=this.dagWalkers[e.code];if(o==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.blockstore.get(e);await Tn(this,Ft,"m",zu).call(this,e,n,i);for await(let a of o.walk(s))t.add(async()=>{await Tn(this,Ft,"m",r).call(this,a,t,n,{...i,depth:i.depth-1})})},zu=async function(e,t,n){let i=new P(`${qu}${go.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=Ce(await this.datastore.get(i,n))}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}if(t(o),o.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,kn(o),n)};var wo=new P("/version"),Vu=1;async function ju(r){if(!await r.has(wo)){await r.put(wo,fn(`${Vu}`));return}let e=await r.get(wo),t=ot(e);if(parseInt(t,10)!==Vu)throw new Error("Unknown datastore version, a datastore migration may be required")}var Gu=U(Or(),1);function Bn(r){return r=r??new Error("Not Found"),(0,Gu.default)(r,"ERR_NOT_FOUND")}var Qu="SHARDING";function Ud(r){return r[Symbol.asyncIterator]!=null}function Rd(r){if(Ud(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var bo=Rd;function zd(r){return r[Symbol.asyncIterator]!=null}function $d(r,e){return zd(r)?async function*(){yield*(await bo(r)).sort(e)}():function*(){yield*bo(r).sort(e)}()}var Cn=$d;function Wd(r){return r[Symbol.asyncIterator]!=null}function Hd(r,e){if(Wd(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=St(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){await o&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let s=e;return function*(){o===!0&&(yield n);for(let a of t)s(a)&&(yield a)}()}var qe=Hd;var Le=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:i}of e)await this.put(n,i,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await Oe(this.putMany(e,n)),e=[],await Oe(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let i=e.prefix;n=qe(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>qe(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cn(i,o),n)),e.offset!=null){let i=0,o=e.offset;n=qe(n,()=>i++>=o)}return e.limit!=null&&(n=Et(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=qe(n,o=>o.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>qe(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cn(i,o),n)),e.offset!=null){let i=e.offset,o=0;n=qe(n,()=>o++>=i)}return e.limit!=null&&(n=Et(n,e.limit)),n}};var pr=class extends Le{constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw Bn();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new P(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new P(e)}};var m1=new P(Qu);var A1=wt("datastore:core:tiered");var Ln={};V(Ln,{abortedError:()=>Zd,closeFailedError:()=>Gd,deleteFailedError:()=>Xd,getFailedError:()=>Kd,hasFailedError:()=>Jd,notFoundError:()=>_o,openFailedError:()=>jd,putFailedError:()=>Qd});var Pe=U(Or(),1);function jd(r){return r=r??new Error("Open failed"),(0,Pe.default)(r,"ERR_OPEN_FAILED")}function Gd(r){return r=r??new Error("Close failed"),(0,Pe.default)(r,"ERR_CLOSE_FAILED")}function Qd(r){return r=r??new Error("Put failed"),(0,Pe.default)(r,"ERR_PUT_FAILED")}function Kd(r){return r=r??new Error("Get failed"),(0,Pe.default)(r,"ERR_GET_FAILED")}function Xd(r){return r=r??new Error("Delete failed"),(0,Pe.default)(r,"ERR_DELETE_FAILED")}function Jd(r){return r=r??new Error("Has failed"),(0,Pe.default)(r,"ERR_HAS_FAILED")}function _o(r){return r=r??new Error("Not Found"),(0,Pe.default)(r,"ERR_NOT_FOUND")}function Zd(r){return r=r??new Error("Aborted"),(0,Pe.default)(r,"ERR_ABORTED")}var mr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:i}of e)await this.put(n,i,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async delete(e,t){await Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var yr=class extends mr{constructor(){super(),this.data=new Map}put(e,t){return this.data.set(j.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(j.encode(e.multihash.bytes));if(t==null)throw _o();return t}has(e){return this.data.has(j.encode(e.multihash.bytes))}async delete(e){this.data.delete(j.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:x.createV1(Kr,br(j.decode(e))),block:t}}};var K1={...Ln};var Yd=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},vo=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Ot,xo=wt("helia"),Pn=class{constructor(e){Ot.set(this,void 0);let t=[je,On,Nn,...e.hashers??[]],n=e.datastore??new pr,i=e.blockstore??new yr,o=e.libp2p??new Proxy({},{get(s,a){let c=()=>{};if(["start","stop"].includes(a.toString()))return c;if(a==="isProxy")return!0;throw new Error("Please configure Helia with a libp2p instance")},set(){throw new Error("Please configure Helia with a libp2p instance")}});e.libp2p!=null&&Yd(this,Ot,oc(o,i,{hashLoader:{getHasher:async s=>{let a=t.find(c=>c.code===s||c.name===s);if(a!=null)return await Promise.resolve(a);throw new Error(`Could not load hasher for code/name "${s}"`)}}}),"f"),this.pins=new An(n,i,e.dagWalkers??[]),this.libp2p=o,this.blockstore=new ln(i,this.pins,{bitswap:vo(this,Ot,"f"),holdGcLock:e.holdGcLock}),this.datastore=n}async start(){await ju(this.datastore),await vo(this,Ot,"f")?.start(),await this.libp2p.start()}async stop(){await this.libp2p.stop(),await vo(this,Ot,"f")?.stop()}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();xo("gc start"),await Oe(i.deleteMany(async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new C("helia:gc:deleted",o))}catch(s){xo.error("Error during gc",s),e.onProgress?.(new C("helia:gc:error",s))}}()))}finally{t()}xo("gc finished")}};Ot=new WeakMap;async function ep(r={}){let e=new Pn(r);return r.start!==!1&&await e.start(),e}return tl(tp);})();
|
|
3
3
|
return Helia}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "helia",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "An implementation of IPFS in JavaScript",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/ipfs/helia/tree/master/packages/helia#readme",
|
|
@@ -151,7 +151,7 @@
|
|
|
151
151
|
"interface-store": "^5.0.1",
|
|
152
152
|
"ipfs-bitswap": "^17.0.0",
|
|
153
153
|
"it-all": "^3.0.1",
|
|
154
|
-
"it-drain": "^
|
|
154
|
+
"it-drain": "^3.0.1",
|
|
155
155
|
"it-filter": "^2.0.0",
|
|
156
156
|
"it-foreach": "^2.0.2",
|
|
157
157
|
"mortice": "^3.0.1",
|