@helia/block-brokers 2.0.3-5cf216b → 2.0.3-6ddefb0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/src/trustless-gateway/broker.d.ts +28 -1
- package/dist/src/trustless-gateway/broker.d.ts.map +1 -1
- package/dist/src/trustless-gateway/broker.js +100 -4
- package/dist/src/trustless-gateway/broker.js.map +1 -1
- package/dist/src/trustless-gateway/index.d.ts +2 -1
- package/dist/src/trustless-gateway/index.d.ts.map +1 -1
- package/dist/src/trustless-gateway/index.js.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.d.ts +3 -1
- package/dist/src/trustless-gateway/trustless-gateway.d.ts.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.js +4 -1
- package/dist/src/trustless-gateway/trustless-gateway.js.map +1 -1
- package/package.json +11 -2
- package/src/trustless-gateway/broker.ts +145 -5
- package/src/trustless-gateway/index.ts +2 -1
- package/src/trustless-gateway/trustless-gateway.ts +8 -1
package/dist/index.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBlockBrokers = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaBlockBrokers=(()=>{var Fs=Object.create;var It=Object.defineProperty;var Ds=Object.getOwnPropertyDescriptor;var Is=Object.getOwnPropertyNames;var Ns=Object.getPrototypeOf,Ms=Object.prototype.hasOwnProperty;var S=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),N=(r,t)=>{for(var e in t)It(r,e,{get:t[e],enumerable:!0})},wr=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Is(t))!Ms.call(r,s)&&s!==e&&It(r,s,{get:()=>t[s],enumerable:!(n=Ds(t,s))||n.enumerable});return r};var $=(r,t,e)=>(e=r!=null?Fs(Ns(r)):{},wr(t||!r||!r.__esModule?It(e,"default",{value:r,enumerable:!0}):e,r)),Rs=r=>wr(It({},"__esModule",{value:!0}),r);var Wr=S((Ka,Hr)=>{Hr.exports=zr;var Or=128,Ei=127,Si=~Ei,Ci=Math.pow(2,31);function zr(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Ci;)t[e++]=r&255|Or,r/=128;for(;r&Si;)t[e++]=r&255|Or,r>>>=7;return t[e]=r|0,zr.bytes=e-n+1,t}});var Vr=S((Za,$r)=>{$r.exports=Ce;var Ti=128,qr=127;function Ce(r,n){var e=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw Ce.bytes=0,new RangeError("Could not decode varint");o=r[i++],e+=s<28?(o&qr)<<s:(o&qr)*Math.pow(2,s),s+=7}while(o>=Ti);return Ce.bytes=i-n,e}});var Xr=S((Ya,Gr)=>{var Ai=Math.pow(2,7),Li=Math.pow(2,14),Bi=Math.pow(2,21),Fi=Math.pow(2,28),Di=Math.pow(2,35),Ii=Math.pow(2,42),Ni=Math.pow(2,49),Mi=Math.pow(2,56),Ri=Math.pow(2,63);Gr.exports=function(r){return r<Ai?1:r<Li?2:r<Bi?3:r<Fi?4:r<Di?5:r<Ii?6:r<Ni?7:r<Mi?8:r<Ri?9:10}});var jr=S((tc,Qr)=>{Qr.exports={encode:Wr(),decode:Vr(),encodingLength:Xr()}});var Zr=S((ec,Kr)=>{"use strict";var Jr=jr();Kr.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=Jr.decode(r);t.push(e),r=r.slice(Jr.decode.bytes)}return t}});var tn=S((rc,Yr)=>{var pt=1e3,mt=pt*60,gt=mt*60,tt=gt*24,Pi=tt*7,Ui=tt*365.25;Yr.exports=function(r,t){t=t||{};var e=typeof r;if(e==="string"&&r.length>0)return Oi(r);if(e==="number"&&isFinite(r))return t.long?Hi(r):zi(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Oi(r){if(r=String(r),!(r.length>100)){var t=/^(-?(?:\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(t){var e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*Ui;case"weeks":case"week":case"w":return e*Pi;case"days":case"day":case"d":return e*tt;case"hours":case"hour":case"hrs":case"hr":case"h":return e*gt;case"minutes":case"minute":case"mins":case"min":case"m":return e*mt;case"seconds":case"second":case"secs":case"sec":case"s":return e*pt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:return}}}}function zi(r){var t=Math.abs(r);return t>=tt?Math.round(r/tt)+"d":t>=gt?Math.round(r/gt)+"h":t>=mt?Math.round(r/mt)+"m":t>=pt?Math.round(r/pt)+"s":r+"ms"}function Hi(r){var t=Math.abs(r);return t>=tt?Rt(r,t,tt,"day"):t>=gt?Rt(r,t,gt,"hour"):t>=mt?Rt(r,t,mt,"minute"):t>=pt?Rt(r,t,pt,"second"):r+" ms"}function Rt(r,t,e,n){var s=t>=e*1.5;return Math.round(r/e)+" "+n+(s?"s":"")}});var rn=S((nc,en)=>{function Wi(r){e.debug=e,e.default=e,e.coerce=c,e.disable=i,e.enable=s,e.enabled=o,e.humanize=tn(),e.destroy=l,Object.keys(r).forEach(u=>{e[u]=r[u]}),e.names=[],e.skips=[],e.formatters={};function t(u){let h=0;for(let f=0;f<u.length;f++)h=(h<<5)-h+u.charCodeAt(f),h|=0;return e.colors[Math.abs(h)%e.colors.length]}e.selectColor=t;function e(u){let h,f=null,g,d;function m(...p){if(!m.enabled)return;let w=m,x=Number(new Date),k=x-(h||x);w.diff=k,w.prev=h,w.curr=x,h=x,p[0]=e.coerce(p[0]),typeof p[0]!="string"&&p.unshift("%O");let E=0;p[0]=p[0].replace(/%([a-zA-Z%])/g,(U,I)=>{if(U==="%%")return"%";E++;let O=e.formatters[I];if(typeof O=="function"){let ct=p[E];U=O.call(w,ct),p.splice(E,1),E--}return U}),e.formatArgs.call(w,p),(w.log||e.log).apply(w,p)}return m.namespace=u,m.useColors=e.useColors(),m.color=e.selectColor(u),m.extend=n,m.destroy=e.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(g!==e.namespaces&&(g=e.namespaces,d=e.enabled(u)),d),set:p=>{f=p}}),typeof e.init=="function"&&e.init(m),m}function n(u,h){let f=e(this.namespace+(typeof h>"u"?":":h)+u);return f.log=this.log,f}function s(u){e.save(u),e.namespaces=u,e.names=[],e.skips=[];let h,f=(typeof u=="string"?u:"").split(/[\s,]+/),g=f.length;for(h=0;h<g;h++)f[h]&&(u=f[h].replace(/\*/g,".*?"),u[0]==="-"?e.skips.push(new RegExp("^"+u.slice(1)+"$")):e.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...e.names.map(a),...e.skips.map(a).map(h=>"-"+h)].join(",");return e.enable(""),u}function o(u){if(u[u.length-1]==="*")return!0;let h,f;for(h=0,f=e.skips.length;h<f;h++)if(e.skips[h].test(u))return!1;for(h=0,f=e.names.length;h<f;h++)if(e.names[h].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){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 e.enable(e.load()),e}en.exports=Wi});var nn=S((M,Pt)=>{M.formatArgs=$i;M.save=Vi;M.load=Gi;M.useColors=qi;M.storage=Xi();M.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`."))}})();M.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 qi(){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 $i(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Pt.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(e++,s==="%c"&&(n=e))}),r.splice(n,0,t)}M.log=console.debug||console.log||(()=>{});function Vi(r){try{r?M.storage.setItem("debug",r):M.storage.removeItem("debug")}catch{}}function Gi(){let r;try{r=M.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Xi(){try{return localStorage}catch{}}Pt.exports=rn()(M);var{formatters:Qi}=Pt.exports;Qi.j=function(r){try{return JSON.stringify(r)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var cn=S((wc,an)=>{an.exports=Le;var on=128,Yi=127,to=~Yi,eo=Math.pow(2,31);function Le(r,t,e){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Le.bytes=0,new RangeError("Could not encode varint");t=t||[],e=e||0;for(var n=e;r>=eo;)t[e++]=r&255|on,r/=128;for(;r&to;)t[e++]=r&255|on,r>>>=7;return t[e]=r|0,Le.bytes=e-n+1,t}});var hn=S((_c,un)=>{un.exports=Be;var ro=128,ln=127;function Be(r,n){var e=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a||s>49)throw Be.bytes=0,new RangeError("Could not decode varint");o=r[i++],e+=s<28?(o&ln)<<s:(o&ln)*Math.pow(2,s),s+=7}while(o>=ro);return Be.bytes=i-n,e}});var dn=S((xc,fn)=>{var no=Math.pow(2,7),so=Math.pow(2,14),io=Math.pow(2,21),oo=Math.pow(2,28),ao=Math.pow(2,35),co=Math.pow(2,42),lo=Math.pow(2,49),uo=Math.pow(2,56),ho=Math.pow(2,63);fn.exports=function(r){return r<no?1:r<so?2:r<io?3:r<oo?4:r<ao?5:r<co?6:r<lo?7:r<uo?8:r<ho?9:10}});var mn=S((vc,pn)=>{pn.exports={encode:cn(),decode:hn(),encodingLength:dn()}});var qn=S((Eu,Wn)=>{"use strict";function Hn(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function Zo(r,t,e){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");e||(e={}),typeof t=="object"&&(e=t,t=""),t&&(e.code=t);try{return Hn(r,e)}catch{e.message=r.message,e.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Hn(new s,e)}}Wn.exports=Zo});var Jn=S(($u,jn)=>{"use strict";jn.exports=function(){return Date.now()}});var Zn=S((Vu,Kn)=>{"use strict";var re=Jn(),ur=class{constructor(t,e,n){let s=this;this._started=re(),this._rescheduled=0,this._scheduled=e,this._args=n,this._triggered=!1,this._timerWrapper=()=>{s._rescheduled>0?(s._scheduled=s._rescheduled-(re()-s._started),s._schedule(s._scheduled)):(s._triggered=!0,t.apply(null,s._args))},this._timer=setTimeout(this._timerWrapper,e)}reschedule(t){t||(t=this._scheduled);let e=re();e+t-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(t)):this._triggered?this._schedule(t):(this._started=e,this._rescheduled=t)}_schedule(t){this._triggered=!1,this._started=re(),this._rescheduled=0,this._scheduled=t,this._timer=setTimeout(this._timerWrapper,t)}clear(){clearTimeout(this._timer)}};function ha(){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 t=0;t<r.length;t++)r[t]=arguments[t+2]}return new ur(arguments[0],arguments[1],r)}Kn.exports=ha});var es=S((Gu,ts)=>{"use strict";var{AbortController:fa}=globalThis,Yn=Zn(),hr=class r extends fa{constructor(t){super(),this._ms=t,this._timer=Yn(()=>this.abort(),t),Object.setPrototypeOf(this,r.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=Yn(()=>this.abort(),this._ms)}};ts.exports={TimeoutController:hr}});var oe=S((nh,mr)=>{"use strict";var xt=typeof Reflect=="object"?Reflect:null,as=xt&&typeof xt.apply=="function"?xt.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},se;xt&&typeof xt.ownKeys=="function"?se=xt.ownKeys:Object.getOwnPropertySymbols?se=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:se=function(t){return Object.getOwnPropertyNames(t)};function ga(r){console&&console.warn&&console.warn(r)}var ls=Number.isNaN||function(t){return t!==t};function _(){_.init.call(this)}mr.exports=_;mr.exports.once=_a;_.EventEmitter=_;_.prototype._events=void 0;_.prototype._eventsCount=0;_.prototype._maxListeners=void 0;var cs=10;function ie(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(_,"defaultMaxListeners",{enumerable:!0,get:function(){return cs},set:function(r){if(typeof r!="number"||r<0||ls(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");cs=r}});_.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};_.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||ls(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function us(r){return r._maxListeners===void 0?_.defaultMaxListeners:r._maxListeners}_.prototype.getMaxListeners=function(){return us(this)};_.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var s=t==="error",i=this._events;if(i!==void 0)s=s&&i.error===void 0;else if(!s)return!1;if(s){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=i[t];if(c===void 0)return!1;if(typeof c=="function")as(c,this,e);else for(var l=c.length,u=ms(c,l),n=0;n<l;++n)as(u[n],this,e);return!0};function hs(r,t,e,n){var s,i,o;if(ie(e),i=r._events,i===void 0?(i=r._events=Object.create(null),r._eventsCount=0):(i.newListener!==void 0&&(r.emit("newListener",t,e.listener?e.listener:e),i=r._events),o=i[t]),o===void 0)o=i[t]=e,++r._eventsCount;else if(typeof o=="function"?o=i[t]=n?[e,o]:[o,e]:n?o.unshift(e):o.push(e),s=us(r),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=t,a.count=o.length,ga(a)}return r}_.prototype.addListener=function(t,e){return hs(this,t,e,!1)};_.prototype.on=_.prototype.addListener;_.prototype.prependListener=function(t,e){return hs(this,t,e,!0)};function ya(){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 fs(r,t,e){var n={fired:!1,wrapFn:void 0,target:r,type:t,listener:e},s=ya.bind(n);return s.listener=e,n.wrapFn=s,s}_.prototype.once=function(t,e){return ie(e),this.on(t,fs(this,t,e)),this};_.prototype.prependOnceListener=function(t,e){return ie(e),this.prependListener(t,fs(this,t,e)),this};_.prototype.removeListener=function(t,e){var n,s,i,o,a;if(ie(e),s=this._events,s===void 0)return this;if(n=s[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete s[t],s.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===e||n[o].listener===e){a=n[o].listener,i=o;break}if(i<0)return this;i===0?n.shift():ba(n,i),n.length===1&&(s[t]=n[0]),s.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this};_.prototype.off=_.prototype.removeListener;_.prototype.removeAllListeners=function(t){var e,n,s;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[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var i=Object.keys(n),o;for(s=0;s<i.length;++s)o=i[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(s=e.length-1;s>=0;s--)this.removeListener(t,e[s]);return this};function ds(r,t,e){var n=r._events;if(n===void 0)return[];var s=n[t];return s===void 0?[]:typeof s=="function"?e?[s.listener||s]:[s]:e?wa(s):ms(s,s.length)}_.prototype.listeners=function(t){return ds(this,t,!0)};_.prototype.rawListeners=function(t){return ds(this,t,!1)};_.listenerCount=function(r,t){return typeof r.listenerCount=="function"?r.listenerCount(t):ps.call(r,t)};_.prototype.listenerCount=ps;function ps(r){var t=this._events;if(t!==void 0){var e=t[r];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}_.prototype.eventNames=function(){return this._eventsCount>0?se(this._events):[]};function ms(r,t){for(var e=new Array(t),n=0;n<t;++n)e[n]=r[n];return e}function ba(r,t){for(;t+1<r.length;t++)r[t]=r[t+1];r.pop()}function wa(r){for(var t=new Array(r.length),e=0;e<t.length;++e)t[e]=r[e].listener||r[e];return t}function _a(r,t){return new Promise(function(e,n){function s(o){r.removeListener(t,i),n(o)}function i(){typeof r.removeListener=="function"&&r.removeListener("error",s),e([].slice.call(arguments))}gs(r,t,i,{once:!0}),t!=="error"&&xa(r,s,{once:!0})})}function xa(r,t,e){typeof r.on=="function"&&gs(r,"error",t,e)}function gs(r,t,e,n){if(typeof r.on=="function")n.once?r.once(t,e):r.on(t,e);else if(typeof r.addEventListener=="function")r.addEventListener(t,function s(i){n.once&&r.removeEventListener(t,s),e(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var vs=S((_s,xs)=>{"use strict";var va=Math.exp;_s=xs.exports=function(t){if(typeof t!="number")throw new Error("must provide a timespan to the moving average constructor");if(t<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let e,n=0,s=0,i=0,o,a={};function c(l,u){return 1-va(-(l-u)/t)}return a.push=function(u,h){if(o){let f=c(u,o),g=h-e,d=f*g;e=f*h+(1-f)*e,n=(1-f)*(n+g*d),s=Math.sqrt(n),i=e+f*g}else e=h;o=u},a.movingAverage=function(){return e},a.variance=function(){return n},a.deviation=function(){return s},a.forecast=function(){return i},a}});var Ta={};N(Ta,{bitswap:()=>As,trustlessGateway:()=>Bs});function _r(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function Ps(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Nt=Ps;function Us(r){return r[Symbol.asyncIterator]!=null}function xr(r){return r?.then!=null}function Os(r,t){if(Us(r))return async function*(){for await(let a of r){let c=t(a);xr(c)&&await c,yield a}}();let e=Nt(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();if(typeof t(n)?.then=="function")return async function*(){yield n;for await(let a of e){let c=t(a);xr(c)&&await c,yield a}}();let o=t;return function*(){yield n;for(let a of e)o(a),yield a}()}var vr=Os;var be={};N(be,{base32:()=>Q,base32hex:()=>Qs,base32hexpad:()=>Js,base32hexpadupper:()=>Ks,base32hexupper:()=>js,base32pad:()=>Gs,base32padupper:()=>Xs,base32upper:()=>Vs,base32z:()=>Zs});var Ia=new Uint8Array(0);function kr(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function V(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Er(r){return new TextEncoder().encode(r)}function Sr(r){return new TextDecoder().decode(r)}function zs(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(e[o]!==255)throw new TypeError(i+" is ambiguous");e[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,p=0,w=0,x=d.length;w!==x&&d[w]===0;)w++,m++;for(var k=(x-w)*u+1>>>0,E=new Uint8Array(k);w!==x;){for(var D=d[w],U=0,I=k-1;(D!==0||U<p)&&I!==-1;I--,U++)D+=256*E[I]>>>0,E[I]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");p=U,w++}for(var O=k-p;O!==k&&E[O]===0;)O++;for(var ct=c.repeat(m);O<k;++O)ct+=r.charAt(E[O]);return ct}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var p=0,w=0;d[m]===c;)p++,m++;for(var x=(d.length-m)*l+1>>>0,k=new Uint8Array(x);d[m];){var E=e[d.charCodeAt(m)];if(E===255)return;for(var D=0,U=x-1;(E!==0||D<w)&&U!==-1;U--,D++)E+=a*k[U]>>>0,k[U]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=D,m++}if(d[m]!==" "){for(var I=x-w;I!==x&&k[I]===0;)I++;for(var O=new Uint8Array(p+(x-I)),ct=p;I!==x;)O[ct++]=k[I++];return O}}}function g(d){var m=f(d);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:g}}var Hs=zs,Ws=Hs,Tr=Ws;var pe=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},me=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Ar(this,t)}},ge=class{decoders;constructor(t){this.decoders=t}or(t){return Ar(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Ar(r,t){return new ge({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ye=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new pe(t,e,n),this.decoder=new me(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function lt({name:r,prefix:t,encode:e,decode:n}){return new ye(r,t,e,n)}function X({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Tr(e,r);return lt({prefix:t,name:r,encode:n,decode:i=>V(s(i))})}function qs(r,t,e,n){let s={};for(let u=0;u<t.length;++u)s[t[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let h=s[r[u]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|h,a+=e,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o}function $s(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>e;)o-=e,i+=t[s&a>>o];if(o!==0&&(i+=t[s&a<<e-o]),n)for(;i.length*e&7;)i+="=";return i}function v({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return lt({prefix:t,name:r,encode(s){return $s(s,n,e)},decode(s){return qs(s,n,e,r)}})}var Q=v({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Vs=v({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Gs=v({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xs=v({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qs=v({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),js=v({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Js=v({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ks=v({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Zs=v({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var we={};N(we,{base58btc:()=>y,base58flickr:()=>Ys});var y=X({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ys=X({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ti=Fr,Lr=128,ei=127,ri=~ei,ni=Math.pow(2,31);function Fr(r,t,e){t=t||[],e=e||0;for(var n=e;r>=ni;)t[e++]=r&255|Lr,r/=128;for(;r&ri;)t[e++]=r&255|Lr,r>>>=7;return t[e]=r|0,Fr.bytes=e-n+1,t}var si=_e,ii=128,Br=127;function _e(r,n){var e=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw _e.bytes=0,new RangeError("Could not decode varint");o=r[i++],e+=s<28?(o&Br)<<s:(o&Br)*Math.pow(2,s),s+=7}while(o>=ii);return _e.bytes=i-n,e}var oi=Math.pow(2,7),ai=Math.pow(2,14),ci=Math.pow(2,21),li=Math.pow(2,28),ui=Math.pow(2,35),hi=Math.pow(2,42),fi=Math.pow(2,49),di=Math.pow(2,56),pi=Math.pow(2,63),mi=function(r){return r<oi?1:r<ai?2:r<ci?3:r<li?4:r<ui?5:r<hi?6:r<fi?7:r<di?8:r<pi?9:10},gi={encode:ti,decode:si,encodingLength:mi},yi=gi,vt=yi;function kt(r,t=0){return[vt.decode(r,t),vt.decode.bytes]}function ut(r,t,e=0){return vt.encode(r,t,e),t}function ht(r){return vt.encodingLength(r)}function Y(r,t){let e=t.byteLength,n=ht(r),s=n+ht(e),i=new Uint8Array(s+e);return ut(r,i,0),ut(e,i,n),i.set(t,s),new ft(r,e,t,i)}function Dr(r){let t=V(r),[e,n]=kt(t),[s,i]=kt(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new ft(e,s,o,t)}function Ir(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&kr(r.bytes,e.bytes)}}var ft=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};function Nr(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return wi(e,xe(r),t??y.encoder);default:return _i(e,xe(r),t??Q.encoder)}}var Mr=new WeakMap;function xe(r){let t=Mr.get(r);if(t==null){let e=new Map;return Mr.set(r,e),e}return t}var C=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==St)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==xi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Y(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Ir(t.multihash,n.multihash)}toString(t){return Nr(this,t)}toJSON(){return{"/":Nr(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:i,bytes:o}=e;return new r(n,s,i,o??Rr(n,s,i.bytes))}else if(e[vi]===!0){let{version:n,multihash:s,code:i}=e,o=Dr(s);return r.create(n,i,o)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==St)throw new Error(`Version 0 CID must use dag-pb (code: ${St}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Rr(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,St,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=V(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=s.subarray(e.multihashSize-e.digestSize),o=new ft(e.multihashCode,e.digestSize,i,s);return[e.version===0?r.createV0(o):r.createV1(e.codec,o),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=kt(t.subarray(e));return e+=f,h},s=n(),i=St;if(s===18?(s=0,e=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=e,a=n(),c=n(),l=e+c,u=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,s]=bi(t,e),i=r.decode(s);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xe(i).set(n,t),i}};function bi(r,t){switch(r[0]){case"Q":{let e=t??y;return[y.prefix,e.decode(`${y.prefix}${r}`)]}case y.prefix:{let e=t??y;return[y.prefix,e.decode(r)]}case Q.prefix:{let e=t??Q;return[Q.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function wi(r,t,e){let{prefix:n}=e;if(n!==y.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return s}function _i(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let i=e.encode(r);return t.set(n,i),i}else return s}var St=112,xi=18;function Rr(r,t,e){let n=ht(r),s=n+ht(t),i=new Uint8Array(s+e.byteLength);return ut(r,i,0),ut(t,i,n),i.set(e,s),i}var vi=Symbol.for("@ipld/js-cid/CID");var ve=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function j(r){let{name:t,metrics:e}=r,n;return e!=null?n=new ve({name:t,metrics:e}):n=new Map,n}var dt=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var Se={};N(Se,{sha256:()=>Ct,sha512:()=>ki});function Ee({name:r,code:t,encode:e}){return new ke(r,t,e)}var ke=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Y(this.code,e):e.then(n=>Y(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Ur(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ct=Ee({name:"sha2-256",code:18,encode:Ur("SHA-256")}),ki=Ee({name:"sha2-512",code:19,encode:Ur("SHA-512")});var Nn=$(Zr(),1);var R=$(nn(),1);var Ae={};N(Ae,{base64:()=>Te,base64pad:()=>ji,base64url:()=>Ji,base64urlpad:()=>Ki});var Te=v({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ji=v({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ji=v({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ki=v({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});R.default.formatters.b=r=>r==null?"undefined":y.baseEncode(r);R.default.formatters.t=r=>r==null?"undefined":Q.baseEncode(r);R.default.formatters.m=r=>r==null?"undefined":Te.baseEncode(r);R.default.formatters.p=r=>r==null?"undefined":r.toString();R.default.formatters.c=r=>r==null?"undefined":r.toString();R.default.formatters.k=r=>r==null?"undefined":r.toString();R.default.formatters.a=r=>r==null?"undefined":r.toString();function Zi(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function sn(r){let t=Zi(`${r}:trace`);return R.default.enabled(`${r}:trace`)&&R.default.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=(0,R.default)(`${r}:trace`)),Object.assign((0,R.default)(r),{error:(0,R.default)(`${r}:error`),trace:t})}function Ut(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var et=class{_refCounter;cid;priority;wantType;constructor(t,e,n){this._refCounter=1,this.cid=t,this.priority=e??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(y)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(t){return this._refCounter===t._refCounter&&this.cid.equals(t.cid)&&this.priority===t.priority&&this.wantType===t.wantType}};var J=class{entry;cancel;sendDontHave;constructor(t,e,n,s,i){this.entry=new et(t,e,n),this.cancel=!!s,this.sendDontHave=!!i}get cid(){return this.entry.cid}set cid(t){this.entry.cid=t}get priority(){return this.entry.priority}set priority(t){this.entry.priority=t}get wantType(){return this.entry.wantType}set wantType(t){this.entry.wantType=t}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(y)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(t){return this.cancel===t.cancel&&this.sendDontHave===t.sendDontHave&&this.wantType===t.wantType&&this.entry.equals(t.entry)}};var z=(r,t)=>{let e=["bitswap"];return t!=null&&e.push(t),r!=null&&e.push(`${r.toString().slice(0,8)}`),sn(e.join(":"))};var Ot=(r,t)=>{if(r.size!==t.size)return!1;for(let[e,n]of r){let s=t.get(e);if(s===void 0||n instanceof Uint8Array&&s instanceof Uint8Array&&!Ut(n,s)||n instanceof J&&s instanceof J&&!n.equals(s))return!1}return!0};var Tt=$(mn(),1);function fo(r){let t=new Uint8Array(r.reduce((n,s)=>n+Tt.default.encodingLength(s),0)),e=0;for(let n of r)t=Tt.encode(n,t,e),e+=Tt.default.encodingLength(n);return t}var gn=fo;function G(r=0){return new Uint8Array(r)}function T(r=0){return new Uint8Array(r)}var po=Math.pow(2,7),mo=Math.pow(2,14),go=Math.pow(2,21),Fe=Math.pow(2,28),De=Math.pow(2,35),Ie=Math.pow(2,42),Ne=Math.pow(2,49),b=128,A=127;function H(r){if(r<po)return 1;if(r<mo)return 2;if(r<go)return 3;if(r<Fe)return 4;if(r<De)return 5;if(r<Ie)return 6;if(r<Ne)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Me(r,t,e=0){switch(H(r)){case 8:t[e++]=r&255|b,r/=128;case 7:t[e++]=r&255|b,r/=128;case 6:t[e++]=r&255|b,r/=128;case 5:t[e++]=r&255|b,r/=128;case 4:t[e++]=r&255|b,r>>>=7;case 3:t[e++]=r&255|b,r>>>=7;case 2:t[e++]=r&255|b,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function yo(r,t,e=0){switch(H(r)){case 8:t.set(e++,r&255|b),r/=128;case 7:t.set(e++,r&255|b),r/=128;case 6:t.set(e++,r&255|b),r/=128;case 5:t.set(e++,r&255|b),r/=128;case 4:t.set(e++,r&255|b),r>>>=7;case 3:t.set(e++,r&255|b),r>>>=7;case 2:t.set(e++,r&255|b),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Re(r,t){let e=r[t],n=0;if(n+=e&A,e<b||(e=r[t+1],n+=(e&A)<<7,e<b)||(e=r[t+2],n+=(e&A)<<14,e<b)||(e=r[t+3],n+=(e&A)<<21,e<b)||(e=r[t+4],n+=(e&A)*Fe,e<b)||(e=r[t+5],n+=(e&A)*De,e<b)||(e=r[t+6],n+=(e&A)*Ie,e<b)||(e=r[t+7],n+=(e&A)*Ne,e<b))return n;throw new RangeError("Could not decode varint")}function bo(r,t){let e=r.get(t),n=0;if(n+=e&A,e<b||(e=r.get(t+1),n+=(e&A)<<7,e<b)||(e=r.get(t+2),n+=(e&A)<<14,e<b)||(e=r.get(t+3),n+=(e&A)<<21,e<b)||(e=r.get(t+4),n+=(e&A)*Fe,e<b)||(e=r.get(t+5),n+=(e&A)*De,e<b)||(e=r.get(t+6),n+=(e&A)*Ie,e<b)||(e=r.get(t+7),n+=(e&A)*Ne,e<b))return n;throw new RangeError("Could not decode varint")}function yn(r,t,e=0){return t==null&&(t=T(H(r))),t instanceof Uint8Array?Me(r,t,e):yo(r,t,e)}function bn(r,t=0){return r instanceof Uint8Array?Re(r,t):bo(r,t)}var Pe=new Float32Array([-0]),K=new Uint8Array(Pe.buffer);function _n(r,t,e){Pe[0]=r,t[e]=K[0],t[e+1]=K[1],t[e+2]=K[2],t[e+3]=K[3]}function xn(r,t){return K[0]=r[t],K[1]=r[t+1],K[2]=r[t+2],K[3]=r[t+3],Pe[0]}var Ue=new Float64Array([-0]),L=new Uint8Array(Ue.buffer);function vn(r,t,e){Ue[0]=r,t[e]=L[0],t[e+1]=L[1],t[e+2]=L[2],t[e+3]=L[3],t[e+4]=L[4],t[e+5]=L[5],t[e+6]=L[6],t[e+7]=L[7]}function kn(r,t){return L[0]=r[t],L[1]=r[t+1],L[2]=r[t+2],L[3]=r[t+3],L[4]=r[t+4],L[5]=r[t+5],L[6]=r[t+6],L[7]=r[t+7],Ue[0]}var wo=BigInt(Number.MAX_SAFE_INTEGER),_o=BigInt(Number.MIN_SAFE_INTEGER),P=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return rt;if(t<wo&&t>_o)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>En&&(s=0n,++n>En&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return rt;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):rt}},rt=new P(0,0);rt.toBigInt=function(){return 0n};rt.zzEncode=rt.zzDecode=function(){return this};rt.length=function(){return 1};var En=4294967296n;function Sn(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Cn(r,t,e){if(e-t<1)return"";let s,i=[],o=0,a;for(;t<e;)a=r[t++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,o>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s!=null?(o>0&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function Oe(r,t,e){let n=e,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++o,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function W(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function zt(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ze=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,W(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw W(this,4);return zt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw W(this,4);return zt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw W(this,4);let t=xn(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw W(this,4);let t=kn(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw W(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Cn(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw W(this,t);this.pos+=t}else do if(this.pos>=this.len)throw W(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new P(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw W(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw W(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw W(this,8);let t=zt(this.buf,this.pos+=4),e=zt(this.buf,this.pos+=4);return new P(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Re(this.buf,this.pos);return this.pos+=H(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function He(r){return new ze(r instanceof Uint8Array?r:r.subarray())}function nt(r,t,e){let n=He(r);return t.decode(n,void 0,e)}var We={};N(We,{base10:()=>xo});var xo=X({prefix:"9",name:"base10",alphabet:"0123456789"});var qe={};N(qe,{base16:()=>vo,base16upper:()=>ko});var vo=v({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ko=v({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $e={};N($e,{base2:()=>Eo});var Eo=v({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ve={};N(Ve,{base256emoji:()=>Lo});var An=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}"),So=An.reduce((r,t,e)=>(r[e]=t,r),[]),Co=An.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function To(r){return r.reduce((t,e)=>(t+=So[e],t),"")}function Ao(r){let t=[];for(let e of r){let n=Co[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var Lo=lt({prefix:"\u{1F680}",name:"base256emoji",encode:To,decode:Ao});var Ge={};N(Ge,{base36:()=>Bo,base36upper:()=>Fo});var Bo=X({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Fo=X({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xe={};N(Xe,{base8:()=>Do});var Do=v({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qe={};N(Qe,{identity:()=>Io});var Io=lt({prefix:"\0",name:"identity",encode:r=>Sr(r),decode:r=>Er(r)});var Wc=new TextEncoder,qc=new TextDecoder;var je={};N(je,{identity:()=>Uo});var Ln=0,Ro="identity",Bn=V;function Po(r){return Y(Ln,Bn(r))}var Uo={code:Ln,name:Ro,encode:Bn,digest:Po};var Je={...Qe,...$e,...Xe,...We,...qe,...be,...Ge,...we,...Ae,...Ve},el={...Se,...je};function Dn(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Fn=Dn("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ke=Dn("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=T(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Oo={utf8:Fn,"utf-8":Fn,hex:Je.base16,latin1:Ke,ascii:Ke,binary:Ke,...Je},Ht=Oo;function In(r,t="utf8"){let e=Ht[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Ze(r){let t=r??8192,e=t>>>1,n,s=t;return function(o){if(o<1||o>e)return T(o);s+o>t&&(n=T(t),s=0);let a=n.subarray(s,s+=o);return s&7&&(s=(s|7)+1),a}}var st=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ye(){}var er=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},zo=Ze();function Ho(r){return globalThis.Buffer!=null?T(r):zo(r)}var Lt=class{len;head;tail;states;constructor(){this.len=0,this.head=new st(Ye,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new st(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new rr((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Wt,10,P.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=P.fromBigInt(t);return this._push(Wt,e.length(),e)}uint64Number(t){return this._push(Me,H(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=P.fromBigInt(t).zzEncode();return this._push(Wt,e.length(),e)}sint64Number(t){let e=P.fromNumber(t).zzEncode();return this._push(Wt,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(tr,1,t?1:0)}fixed32(t){return this._push(At,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=P.fromBigInt(t);return this._push(At,4,e.lo)._push(At,4,e.hi)}fixed64Number(t){let e=P.fromNumber(t);return this._push(At,4,e.lo)._push(At,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(_n,4,t)}double(t){return this._push(vn,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(tr,1,0):this.uint32(e)._push(qo,e,t)}string(t){let e=Sn(t);return e!==0?this.uint32(e)._push(Oe,e,t):this._push(tr,1,0)}fork(){return this.states=new er(this),this.head=this.tail=new st(Ye,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new st(Ye,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Ho(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function tr(r,t,e){t[e]=r&255}function Wo(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var rr=class extends st{next;constructor(t,e){super(Wo,t,e),this.next=void 0}};function Wt(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function At(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function qo(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Lt.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push($o,t,r),this},Lt.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Vo,t,r),this});function $o(r,t,e){t.set(r,e)}function Vo(r,t,e){r.length<40?Oe(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(In(r),e)}function nr(){return new Lt}function it(r,t){let e=nr();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var yt;(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"})(yt||(yt={}));function qt(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function $t(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,o){let a=t(i);o.int32(a)},n=function(i){let o=i.int32();return t(o)};return qt("enum",yt.VARINT,e,n)}function ot(r,t){return qt("message",yt.LENGTH_DELIMITED,r,t)}var F;(function(r){let t;(function(a){let c;(function(f){f.Block="Block",f.Have="Have"})(c=a.WantType||(a.WantType={}));let l;(function(f){f[f.Block=0]="Block",f[f.Have=1]="Have"})(l||(l={})),function(f){f.codec=()=>$t(l)}(c=a.WantType||(a.WantType={}));let u;(function(f){let g;f.codec=()=>(g==null&&(g=ot((d,m,p={})=>{p.lengthDelimited!==!1&&m.fork(),d.block!=null&&d.block.byteLength>0&&(m.uint32(10),m.bytes(d.block)),d.priority!=null&&d.priority!==0&&(m.uint32(16),m.int32(d.priority)),d.cancel!=null&&d.cancel!==!1&&(m.uint32(24),m.bool(d.cancel)),d.wantType!=null&&l[d.wantType]!==0&&(m.uint32(32),r.Wantlist.WantType.codec().encode(d.wantType,m)),d.sendDontHave!=null&&d.sendDontHave!==!1&&(m.uint32(40),m.bool(d.sendDontHave)),p.lengthDelimited!==!1&&m.ldelim()},(d,m)=>{let p={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},w=m==null?d.len:d.pos+m;for(;d.pos<w;){let x=d.uint32();switch(x>>>3){case 1:p.block=d.bytes();break;case 2:p.priority=d.int32();break;case 3:p.cancel=d.bool();break;case 4:p.wantType=r.Wantlist.WantType.codec().decode(d);break;case 5:p.sendDontHave=d.bool();break;default:d.skipType(x&7);break}}return p})),g),f.encode=d=>it(d,f.codec()),f.decode=d=>nt(d,f.codec())})(u=a.Entry||(a.Entry={}));let h;a.codec=()=>(h==null&&(h=ot((f,g,d={})=>{if(d.lengthDelimited!==!1&&g.fork(),f.entries!=null)for(let m of f.entries)g.uint32(10),r.Wantlist.Entry.codec().encode(m,g);f.full!=null&&f.full!==!1&&(g.uint32(16),g.bool(f.full)),d.lengthDelimited!==!1&&g.ldelim()},(f,g)=>{let d={entries:[],full:!1},m=g==null?f.len:f.pos+g;for(;f.pos<m;){let p=f.uint32();switch(p>>>3){case 1:d.entries.push(r.Wantlist.Entry.codec().decode(f,f.uint32()));break;case 2:d.full=f.bool();break;default:f.skipType(p&7);break}}return d})),h),a.encode=f=>it(f,a.codec()),a.decode=f=>nt(f,a.codec())})(t=r.Wantlist||(r.Wantlist={}));let e;(function(a){let c;a.codec=()=>(c==null&&(c=ot((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.prefix!=null&&l.prefix.byteLength>0&&(u.uint32(10),u.bytes(l.prefix)),l.data!=null&&l.data.byteLength>0&&(u.uint32(18),u.bytes(l.data)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={prefix:new Uint8Array(0),data:new Uint8Array(0)},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let g=l.uint32();switch(g>>>3){case 1:h.prefix=l.bytes();break;case 2:h.data=l.bytes();break;default:l.skipType(g&7);break}}return h})),c),a.encode=l=>it(l,a.codec()),a.decode=l=>nt(l,a.codec())})(e=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let s;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(s||(s={})),function(a){a.codec=()=>$t(s)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){let c;a.codec=()=>(c==null&&(c=ot((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.cid!=null&&l.cid.byteLength>0&&(u.uint32(10),u.bytes(l.cid)),l.type!=null&&s[l.type]!==0&&(u.uint32(16),r.BlockPresenceType.codec().encode(l.type,u)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={cid:new Uint8Array(0),type:n.Have},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let g=l.uint32();switch(g>>>3){case 1:h.cid=l.bytes();break;case 2:h.type=r.BlockPresenceType.codec().decode(l);break;default:l.skipType(g&7);break}}return h})),c),a.encode=l=>it(l,a.codec()),a.decode=l=>nt(l,a.codec())})(i=r.BlockPresence||(r.BlockPresence={}));let o;r.codec=()=>(o==null&&(o=ot((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let u of a.blocks)c.uint32(18),c.bytes(u);if(a.payload!=null)for(let u of a.payload)c.uint32(26),r.Block.codec().encode(u,c);if(a.blockPresences!=null)for(let u of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(u,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),l.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let l={blocks:[],payload:[],blockPresences:[],pendingBytes:0},u=c==null?a.len:a.pos+c;for(;a.pos<u;){let h=a.uint32();switch(h>>>3){case 1:l.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:l.blocks.push(a.bytes());break;case 3:l.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:l.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:l.pendingBytes=a.int32();break;default:a.skipType(h&7);break}}return l})),o),r.encode=a=>it(a,r.codec()),r.decode=a=>nt(a,r.codec())})(F||(F={}));var B=class r{static Entry=J;static WantType={Block:F.Wantlist.WantType.Block,Have:F.Wantlist.WantType.Have};static BlockPresenceType={Have:F.BlockPresenceType.Have,DontHave:F.BlockPresenceType.DontHave};static deserialize=async(t,e)=>{let n=F.decode(t),s=n.wantlist?.full===!0,i=new r(s);return n.wantlist?.entries.forEach(o=>{if(o.block==null)return;let a=C.decode(o.block);i.addEntry(a,o.priority??0,o.wantType,!!o.cancel,!!o.sendDontHave)}),n.blockPresences.forEach(o=>{if(o.cid==null)return;let a=C.decode(o.cid);o.type===r.BlockPresenceType.Have?i.addHave(a):i.addDontHave(a)}),n.blocks.length>0?(await Promise.all(n.blocks.map(async o=>{let a=await Ct.digest(o),c=C.createV0(a);i.addBlock(c,o)})),i):(n.payload.length>0&&(await Promise.all(n.payload.map(async o=>{if(o.prefix==null||o.data==null)return;let a=(0,Nn.default)(o.prefix),c=a[0],l=a[1],u=a[2],h=u===Ct.code?Ct:await e?.getHasher(u);if(h==null)throw new dt("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let f=await h.digest(o.data),g=C.create(c,l,f);i.addBlock(g,o.data)})),i.setPendingBytes(n.pendingBytes)),i)};static blockPresenceSize=t=>t.bytes.length+1;full;wantlist;blocks;blockPresences;pendingBytes;constructor(t){this.full=t,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(t,e,n,s,i){n==null&&(n=r.WantType.Block);let o=t.toString(y),a=this.wantlist.get(o);a!=null?(a.wantType===n&&(a.priority=e),s===!0&&(a.cancel=!!s),i===!0&&(a.sendDontHave=!!i),n===r.WantType.Block&&a.wantType===r.WantType.Have&&(a.wantType=n)):this.wantlist.set(o,new J(t,e,n,s,i))}addBlock(t,e){let n=t.toString(y);this.blocks.set(n,e)}addHave(t){let e=t.toString(y);this.blockPresences.has(e)||this.blockPresences.set(e,r.BlockPresenceType.Have)}addDontHave(t){let e=t.toString(y);this.blockPresences.has(e)||this.blockPresences.set(e,r.BlockPresenceType.DontHave)}cancel(t){let e=t.toString(y);this.wantlist.delete(e),this.addEntry(t,0,r.WantType.Block,!0,!1)}setPendingBytes(t){this.pendingBytes=t}serializeToBitswap100(){return F.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),cancel:!!t.cancel,wantType:F.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}serializeToBitswap110(){let t={wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),wantType:e.wantType,cancel:!!e.cancel,sendDontHave:!!e.sendDontHave})),full:!!this.full},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[e,n]of this.blocks.entries()){let s=C.parse(e),i=s.version,o=s.code,a=s.multihash.code,c=s.multihash.digest.length,l=gn([i,o,a,c]);t.payload.push({prefix:l,data:n})}for(let[e,n]of this.blockPresences)t.blockPresences.push({cid:C.parse(e).bytes,type:n});return this.pendingBytes>0&&(t.pendingBytes=this.pendingBytes),F.encode(t)}equals(t){return!(this.full!==t.full||this.pendingBytes!==t.pendingBytes||!Ot(this.wantlist,t.wantlist)||!Ot(this.blocks,t.blocks)||!Ot(this.blockPresences,t.blockPresences))}get[Symbol.toStringTag](){let t=Array.from(this.wantlist.keys()),e=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${t}, blocks: ${e}>`}};var Mn={Block:F.Wantlist.WantType.Block,Have:F.Wantlist.WantType.Have},Go=(r,t)=>Array.prototype.slice.call(t,0).sort((e,n)=>{let s=r(e),i=r(n);return s<i?-1:s>i?1:0}),Z=class{static Entry=et;set;_stats;constructor(t,e){this.set=e!=null?j({name:"ipfs_bitswap_wantlist",metrics:e.metrics}):new Map,this._stats=t}get length(){return this.set.size}add(t,e,n){let s=t.toString(y),i=this.set.get(s);i!=null?(i.inc(),i.priority=e,i.wantType===Mn.Have&&n===Mn.Block&&(i.wantType=n)):(this.set.set(s,new et(t,e,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(t){let e=t.toString(y),n=this.set.get(e);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(e),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(t){this.set.has(t)&&this.set.delete(t)}forEach(t){this.set.forEach(t)}entries(){return this.set.entries()}sortedEntries(){return new Map(Go(t=>t[1].key,Array.from(this.set.entries())))}contains(t){let e=t.toString(y);return this.set.has(e)}get(t){let e=t.toString(y);return this.set.get(e)}};var Vt=class{partner;wantlist;exchangeCount;accounting;lastExchange;constructor(t){this.partner=t,this.wantlist=new Z,this.exchangeCount=0,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=t}wants(t,e,n){this.wantlist.add(t,e,n)}cancelWant(t){this.wantlist.remove(t)}wantlistContains(t){return this.wantlist.get(t)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var Bt=class extends Map{_cmp;_keys;constructor(t,e){super(),this._cmp=e??this._defaultSort,this._keys=[];for(let[n,s]of t??[])this.set(n,s)}update(t){if(t<0||t>=this._keys.length)return;let e=this._keys[t];this._keys.splice(t,1);let n=this._find(e);this._keys.splice(n,0,e)}set(t,e){if(this.has(t)){let s=this.indexOf(t);this._keys.splice(s,1)}super.set(t,e);let n=this._find(t);return this._keys.splice(n,0,t),this}clear(){super.clear(),this._keys=[]}delete(t){if(!this.has(t))return!1;let e=this.indexOf(t);return this._keys.splice(e,1),super.delete(t)}indexOf(t){if(!this.has(t))return-1;let e=this._find(t);if(this._keys[e]===t)return e;for(let n=1;n<this._keys.length;n++){if(this._keys[e+n]===t)return e+n;if(this._keys[e-n]===t)return e-n}return-1}_find(t){let e=0,n=this._keys.length;for(;e<n;){let s=e+n>>>1,i=this._kCmp(this._keys[s],t);if(i<0)e=s+1;else if(i>0)n=s;else return s}return e}*keys(){for(let t of this._keys)yield t}*values(){for(let t of this._keys)yield this.get(t)}*entries(){for(let t of this._keys)yield[t,this.get(t)]}*[Symbol.iterator](){yield*this.entries()}forEach(t,e=this){if(t!=null)for(let n of this._keys){let s=this.get(n);if(s==null)throw new Error("Value cannot be undefined");t.apply(e,[[n,s]])}}_defaultSort(t,e){return t[0]<e[0]?-1:e[0]<t[0]?1:0}_kCmp(t,e){return this._cmp([t,this.get(t)],[e,this.get(e)])}};var Xo={hasNewInfo(){return!1},merge(){}},Gt=class{_taskMerger;_byPeer;constructor(t=Xo){this._taskMerger=t,this._byPeer=new Bt([],Xt.compare)}pushTasks(t,e){let n=this._byPeer.get(t.toString());n==null&&(n=new Xt(t,this._taskMerger)),n.pushTasks(e),this._byPeer.set(t.toString(),n)}popTasks(t){let e=this._head();if(e===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:s}=e.popTasks(t);if(n.length===0)return{tasks:n,pendingSize:s};let i=e.peerId;return e.isIdle()?this._byPeer.delete(i.toString()):this._byPeer.update(0),{peerId:i,tasks:n,pendingSize:s}}_head(){if(this._byPeer.size!==0)for(let[,t]of this._byPeer)return t}remove(t,e){this._byPeer.get(e.toString())?.remove(t)}tasksDone(t,e){let n=this._byPeer.get(t.toString());if(n==null)return;let s=this._byPeer.indexOf(t.toString());for(let i of e)n.taskDone(i);this._byPeer.update(s)}},Xt=class{peerId;_taskMerger;_activeTotalSize;_pending;_active;constructor(t,e){this.peerId=t,this._taskMerger=e,this._activeTotalSize=0,this._pending=new sr,this._active=new Set}pushTasks(t){for(let e of t)this._pushTask(e)}_pushTask(t){if(!this._taskHasMoreInfoThanActiveTasks(t))return;let e=this._pending.get(t.topic);if(e!=null){t.priority>e.priority&&this._pending.updatePriority(t.topic,t.priority),this._taskMerger.merge(t,e);return}this._pending.add(t)}_taskHasMoreInfoThanActiveTasks(t){let e=[];for(let n of this._active)n.topic===t.topic&&e.push(n);return e.length===0?!0:this._taskMerger.hasNewInfo(t,e)}popTasks(t){let e=0,n=[],s=this._pending.tasks();for(let i=0;i<s.length&&e<t;i++){let o=s[i];n.push(o),e+=o.size,this._pending.delete(o.topic),this._activeTotalSize+=o.size,this._active.add(o)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(t){this._active.has(t)&&(this._activeTotalSize-=t.size,this._active.delete(t))}remove(t){this._pending.delete(t)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(t,e){return t[1]._pending.length===0?1:e[1]._pending.length===0?-1:t[1]._activeTotalSize===e[1]._activeTotalSize?e[1]._pending.length-t[1]._pending.length:t[1]._activeTotalSize-e[1]._activeTotalSize}},sr=class{_tasks;constructor(){this._tasks=new Bt([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((t,e)=>t+e.task.size,0)}get(t){return this._tasks?.get(t)?.task}add(t){this._tasks.set(t.topic,{created:Date.now(),task:t})}delete(t){this._tasks.delete(t)}tasks(){return[...this._tasks.values()].map(t=>t.task)}updatePriority(t,e){let n=this._tasks.get(t);if(n==null)return;let s=this._tasks.indexOf(t);n.task.priority=e,this._tasks.update(s)}_compare(t,e){return t[1].task.priority===e[1].task.priority?t[1].created-e[1].created:e[1].task.priority-t[1].task.priority}};var Rn={hasNewInfo(r,t){let e=!1,n=!1;for(let s of t)s.data.haveBlock&&(e=!0),s.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!e&&r.data.haveBlock)},merge(r,t){let e=r.data,n=t.data;!n.haveBlock&&e.haveBlock&&(n.haveBlock=e.haveBlock,n.blockSize=e.blockSize),!n.isWantBlock&&e.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||e.haveBlock)&&(n.haveBlock=e.haveBlock,t.size=r.size)),n.isWantBlock&&n.haveBlock&&(t.size=n.blockSize)}};var Pn=B.WantType,Qo=16*1024,jo=1024,Qt=class{_log;blockstore;network;_stats;_opts;ledgerMap;_running;_requestQueue;constructor(t,e,n,s,i,o={}){this._log=z(t,"engine"),this.blockstore=e,this.network=n,this._stats=s,this._opts=this._processOpts(o),this.ledgerMap=j({name:"ipfs_bitswap_ledger_map",metrics:i.metrics}),this._running=!1,this._requestQueue=new Gt(Rn)}_processOpts(t){return{maxSizeReplaceHasWithBlock:jo,targetMessageSize:Qo,...t}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(t=>{this._log.error("error processing stats",t)})})}async _processTasks(){if(!this._running)return;let{peerId:t,tasks:e,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(e.length===0)return;let s=new B(!1);s.setPendingBytes(n);let i=[],o=new Map;for(let c of e){let l=C.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(i.push(l),o.set(c.topic,c.data)):s.addHave(l):s.addDontHave(l)}let a=await this._getBlocks(i);for(let[c,l]of o){let u=C.parse(c),h=a.get(c);h!=null?s.addBlock(u,h):l.sendDontHave&&s.addDontHave(u)}if(s.empty){t!=null&&this._requestQueue.tasksDone(t,e),this._scheduleProcessTasks();return}try{t!=null&&await this.network.sendMessage(t,s);for(let[c,l]of a.entries())t!=null&&this.messageSent(t,C.parse(c),l)}catch(c){this._log.error(c)}t!=null&&this._requestQueue.tasksDone(t,e),this._scheduleProcessTasks()}wantlistForPeer(t){let e=t.toString(),n=this.ledgerMap.get(e);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(t){let e=t.toString(),n=this.ledgerMap.get(e);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(t=>t.partner)}receivedBlocks(t){if(t.length!==0){for(let e of this.ledgerMap.values())for(let{cid:n,block:s}of t){let i=e.wantlistContains(n);if(i==null)continue;let o=s.length,a=this._sendAsBlock(i.wantType,o),c=o;a||(c=B.blockPresenceSize(i.cid)),this._requestQueue.pushTasks(e.partner,[{topic:i.cid.toString(y),priority:i.priority,size:c,data:{blockSize:o,isWantBlock:a,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(t,e){let n=this._findOrCreate(t);if(e.empty)return;if(e.full&&(n.wantlist=new Z),this._updateBlockAccounting(e.blocks,n),e.wantlist.size===0){this._scheduleProcessTasks();return}let s=[],i=[];e.wantlist.forEach(o=>{o.cancel?(n.cancelWant(o.cid),s.push(o.cid)):(n.wants(o.cid,o.priority,o.wantType),i.push(o))}),this._cancelWants(t,s),await this._addWants(t,i),this._scheduleProcessTasks()}_cancelWants(t,e){for(let n of e)this._requestQueue.remove(n.toString(y),t)}async _addWants(t,e){let n=await this._getBlockSizes(e.map(i=>i.cid)),s=[];for(let i of e){let o=i.cid.toString(y),a=n.get(o);if(a==null)i.sendDontHave&&s.push({topic:o,priority:i.priority,size:B.blockPresenceSize(i.cid),data:{isWantBlock:i.wantType===Pn.Block,blockSize:0,haveBlock:!1,sendDontHave:i.sendDontHave}});else{let c=this._sendAsBlock(i.wantType,a),l=a;c||(l=B.blockPresenceSize(i.cid)),s.push({topic:o,priority:i.priority,size:l,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:i.sendDontHave}})}this._requestQueue.pushTasks(t,s)}}_sendAsBlock(t,e){return t===Pn.Block||e<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(t){let e=await this._getBlocks(t);return new Map([...e].map(([n,s])=>[n,s.length]))}async _getBlocks(t){let e=new Map;return await Promise.all(t.map(async n=>{try{let s=await this.blockstore.get(n);e.set(n.toString(y),s)}catch(s){s.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,s)}})),e}_updateBlockAccounting(t,e){for(let n of t.values())this._log("got block (%s bytes)",n.length),e.receivedBytes(n.length)}messageSent(t,e,n){let s=this._findOrCreate(t);s.sentBytes(n.length),s.wantlist.remove(e)}numBytesSentTo(t){return this._findOrCreate(t).accounting.bytesSent}numBytesReceivedFrom(t){return this._findOrCreate(t).accounting.bytesRecv}peerDisconnected(t){this.ledgerMap.delete(t.toString())}_findOrCreate(t){let e=t.toString(),n=this.ledgerMap.get(e);if(n!=null)return n;let s=new Vt(t);return this.ledgerMap.set(e,s),this._stats!=null&&this._stats.push(e,"peerCount",1),s}start(){this._running=!0}stop(){this._running=!1}};function Jo(r){return r[Symbol.asyncIterator]!=null}function Ko(r){if(Jo(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Un=Ko;function ir(r,t){t==null&&(t=r.reduce((s,i)=>s+i.length,0));let e=T(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}var zn=Symbol.for("@achingbrain/uint8arraylist");function On(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function jt(r){return!!r?.[zn]}var bt=class r{bufs;length;[zn]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(jt(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(jt(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=On(this.bufs,t);return e.buf[e.index]}set(t,e){let n=On(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(jt(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return ir(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:ir(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),i=new r;return i.length=s,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=s,c=a+o.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(o);break}let h=t-a;n.push(o.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(u){if(e===c){n.push(o);break}n.push(o.subarray(0,e-a));break}n.push(o)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!jt(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let h=0;h<i;h++)o[h]=-1;for(let h=0;h<s;h++)o[n[h]]=h;let a=o,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let g=this.get(h+f);if(n[f]!==g){u=Math.max(1,f-a[g]);break}}if(u===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=T(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=G(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=G(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=G(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=T(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=G(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=G(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=G(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=G(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=G(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Ut(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,i)=>s+i.byteLength,0)),n.length=e,n}};function Jt(r){return r[Symbol.asyncIterator]!=null}var Kt=r=>{let t=H(r),e=T(t);return yn(r,e),Kt.bytes=t,e};Kt.bytes=0;function Zt(r,t){t=t??{};let e=t.lengthEncoder??Kt;function*n(s){let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Jt(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}Zt.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Kt;return new bt(e(r.byteLength),r)};var wt=$(qn(),1);var Yo=8,ta=1024*1024*4,at;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(at||(at={}));var or=r=>{let t=bn(r);return or.bytes=H(t),t};or.bytes=0;function Ft(r,t){let e=new bt,n=at.LENGTH,s=-1,i=t?.lengthDecoder??or,o=t?.maxLengthLength??Yo,a=t?.maxDataLength??ta;function*c(){for(;e.byteLength>0;){if(n===at.LENGTH)try{if(s=i(e),s<0)throw(0,wt.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>a)throw(0,wt.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=i.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=at.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>o)throw(0,wt.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===at.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=at.LENGTH}}}return Jt(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,wt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,wt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Ft.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:i,value:o}=await r.next(e);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{e=1}}();return Ft(n,{...t??{},onLength:i=>{e=i}})};function ra(r){return r[Symbol.asyncIterator]!=null}function na(r,t){if(ra(r))return async function*(){for await(let a of r)yield t(a)}();let e=Nt(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let i=t(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let a of e)yield t(a)}();let o=t;return function*(){yield i;for(let a of e)yield o(a)}()}var $n=na;function Yt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var te=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},_t=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new te(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new te(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var ar=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function ee(r={}){return sa(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function sa(r,t){t=t??{};let e=t.onEnd,n=new _t,s,i,o,a=Yt(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((p,w)=>{i=x=>{i=null,n.push(x);try{p(r(n))}catch(k){w(k)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Yt()})}},l=p=>i!=null?i(p):(n.push(p),s),u=p=>(n=new _t,i!=null?i({error:p}):(n.push({error:p}),s)),h=p=>{if(o)return s;if(t?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:p})},f=p=>o?s:(o=!0,p!=null?u(p):l({done:!0})),g=()=>(n=new _t,f(),{done:!0}),d=p=>(f(p),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:g,throw:d,push:h,end:f,get readableLength(){return n.size},onEmpty:async p=>{let w=p?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,k;w!=null&&(x=new Promise((E,D)=>{k=()=>{D(new ar)},w.addEventListener("abort",k)}));try{await Promise.race([a.promise,x])}finally{k!=null&&w!=null&&w?.removeEventListener("abort",k)}}},e==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(p){return m.throw(p),e!=null&&(e(p),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(p){return m.end(p),e!=null&&(e(p),e=void 0),s},get readableLength(){return m.readableLength},onEmpty:p=>m.onEmpty(p)},s}function ia(r){return r[Symbol.asyncIterator]!=null}function oa(...r){let t=[];for(let e of r)ia(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=ee({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)e.push(s)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var Vn=oa;function lr(r,...t){if(r==null)throw new Error("Empty pipeline");if(cr(r)){let n=r;r=()=>n.source}else if(Xn(r)||Gn(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&cr(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)cr(e[n])&&(e[n]=ca(e[n]));return aa(...e)}var aa=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Gn=r=>r?.[Symbol.asyncIterator]!=null,Xn=r=>r?.[Symbol.iterator]!=null,cr=r=>r==null?!1:r.sink!=null&&r.source!=null,ca=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=ee({objectMode:!0});e.then(()=>{n.end()},o=>{n.end(o)});let s,i=r.source;if(Gn(i))s=async function*(){yield*i,n.end()};else if(Xn(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Vn(n,s())}return r.source};function la(r){return r[Symbol.asyncIterator]!=null}function ua(r,t){return la(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var Qn=ua;var q=class extends Event{constructor(t,e){super(t),this.detail=e}};var os=$(es(),1);var rs=Math.pow(2,31)-1,ns=1e3,ss=1;var fr="/ipfs/bitswap/1.0.0",dr="/ipfs/bitswap/1.1.0",pr="/ipfs/bitswap/1.2.0",da=1024,pa=1024,ma=3e4,ne=class{_log;_libp2p;_bitswap;_protocols;_stats;_running;_hashLoader;_maxInboundStreams;_maxOutboundStreams;_incomingStreamTimeout;_registrarIds;constructor(t,e,n,s={}){this._log=z(t.peerId,"network"),this._libp2p=t,this._bitswap=e,this._protocols=[fr],s.b100Only!==!0&&(this._protocols.unshift(dr),this._protocols.unshift(pr)),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=s.hashLoader??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=s.maxInboundStreams??da,this._maxOutboundStreams=s.maxOutboundStreams??pa,this._incomingStreamTimeout=s.incomingStreamTimeout??ma}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let t={onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect};this._registrarIds=[];for(let e of this._protocols)this._registrarIds.push(await this._libp2p.register(e,t));this._libp2p.getConnections().forEach(e=>{this._onPeerConnect(e.remotePeer)})}async stop(){if(this._running=!1,await this._libp2p.unhandle(this._protocols),this._registrarIds!=null){for(let t of this._registrarIds)this._libp2p.unregister(t);this._registrarIds=[]}}_onConnection(t){if(!this._running)return;let{stream:e,connection:n}=t,s=new os.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",e.protocol,n.remotePeer);let i=()=>{e.abort(new dt("Incoming Bitswap stream timed out","ERR_TIMEOUT"))},o=AbortSignal.timeout(this._incomingStreamTimeout);o.addEventListener("abort",i),await lr(e,a=>Ft(a),async a=>{for await(let c of a){try{let l=await B.deserialize(c.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,l)}catch(l){this._bitswap._receiveError(l);break}o.removeEventListener("abort",i),o=AbortSignal.timeout(this._incomingStreamTimeout),o.addEventListener("abort",i)}}),await e.close({signal:o})}).catch(i=>{this._log(i),e.abort(i)}).finally(()=>{s.clear()})}_onPeerConnect(t){this._bitswap._onPeerConnected(t)}_onPeerDisconnect(t){this._bitswap._onPeerDisconnected(t)}findProviders(t,e={}){return e.onProgress?.(new q("bitswap:network:find-providers",t)),this._libp2p.contentRouting.findProviders(t,e)}async findAndConnect(t,e){await Un(Qn($n(this.findProviders(t,e),async n=>this.connectTo(n.id,e).catch(s=>{this._log.error(s)})),3)).catch(n=>{this._log.error(n)})}async provide(t,e={}){e.onProgress?.(new q("bitswap:network:provide",t)),await this._libp2p.contentRouting.provide(t,e)}async sendMessage(t,e,n={}){if(!this._running)throw new Error("network isn't running");let s=t.toString();this._log("sendMessage to %s",s,e),n.onProgress?.(new q("bitswap:network:send-wantlist",t)),await this._writeMessage(t,e,n),this._updateSentStats(t,e.blocks)}async connectTo(t,e={}){if(!this._running)throw new Error("network isn't running");return e.onProgress?.(new q("bitswap:network:dial",t)),this._libp2p.dial(t,e)}_updateSentStats(t,e){let n=t.toString();if(this._stats!=null){for(let s of e.values())this._stats.push(n,"dataSent",s.length);this._stats.push(n,"blocksSent",e.size)}}async _writeMessage(t,e,n={}){let s=await this._libp2p.dialProtocol(t,[pr,dr,fr]);try{let i;switch(s.protocol){case fr:i=e.serializeToBitswap100();break;case dr:case pr:i=e.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${s.protocol}`)}await lr([i],o=>Zt(o),s),await s.close()}catch(i){n.onProgress?.(new q("bitswap:network:send-wantlist:error",{peer:t,error:i})),this._log(i),s.abort(i)}}};var ws=$(oe(),1);function gr(r,t="utf8"){let e=Ht[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var ys=r=>`unwant:${gr(r.multihash.bytes,"base64")}`,bs=r=>`block:${gr(r.multihash.bytes,"base64")}`,ae=class extends ws.EventEmitter{_log;constructor(t){super(),this.setMaxListeners(ns),this._log=z(t,"notif")}hasBlock(t,e){let n=bs(t);this._log(n),this.emit(n,e)}async wantBlock(t,e={}){if(t==null)throw new Error("Not a valid cid");let n=bs(t),s=ys(t);return this._log(`wantBlock:${t}`),new Promise((i,o)=>{let a=()=>{this.removeListener(n,c),e.onProgress?.(new q("bitswap:want-block:unwant",t)),o(new Error(`Block for ${t} unwanted`))},c=l=>{this.removeListener(s,a),e.onProgress?.(new q("bitswap:want-block:block",t)),i(l)};this.once(s,a),this.once(n,c),e.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(s,a),o(new Error(`Want for ${t} aborted`))})})}unwantBlock(t){let e=ys(t);this._log(e),this.emit(e)}};var Ss=$(oe(),1);var ks=$(oe(),1),yr=$(vs(),1),Dt=class extends ks.EventEmitter{_options;_queue;_stats;_frequencyLastTime;_frequencyAccumulators;_movingAverages;_enabled;_timeout;constructor(t,e){super(),this._options=e,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),t.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(s=>{(this._movingAverages[n][s]=(0,yr.default)(s)).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(t,e){this._enabled&&(this._queue.push([t,e,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout!=null&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let t=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-t),0)}_update(){if(this._timeout=void 0,this._queue.length>0){let t;for(;this._queue.length>0;){let e=t=this._queue.shift();e!=null&&this._applyOp(e)}t!=null&&this._updateFrequency(t[2]),this.emit("update",this._stats)}}_updateFrequency(t){let e=t-this._frequencyLastTime;e>0&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,e,t)}),this._frequencyLastTime=t}_updateFrequencyFor(t,e,n){let s=this._frequencyAccumulators[t]??0;this._frequencyAccumulators[t]=0;let i=s/e*1e3,o=this._movingAverages[t];o==null&&(o=this._movingAverages[t]={}),this._options.movingAverageIntervals.forEach(a=>{let c=o[a];c==null&&(c=o[a]=(0,yr.default)(a)),c.push(n,i)})}_applyOp(t){let e=t[0],n=t[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,e)||(this._stats[e]=BigInt(0)),this._stats[e]=BigInt(this._stats[e])+BigInt(n),this._frequencyAccumulators[e]==null&&(this._frequencyAccumulators[e]=0),this._frequencyAccumulators[e]+=n}};var Es={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},ce=class extends Ss.EventEmitter{_initialCounters;_options;_enabled;_global;_peers;constructor(t,e=[],n=Es){super();let s=Object.assign({},Es,n);if(typeof s.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof s.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=e,this._options=s,this._enabled=this._options.enabled,this._global=new Dt(e,s),this._global.on("update",i=>this.emit("update",i)),this._peers=j({name:"ipfs_bitswap_stats_peers",metrics:t.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 t of this._peers)t[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(t){let e=t.toString();return this._peers.get(e)}push(t,e,n){if(this._enabled&&(this._global.push(e,n),t!=null)){let s=this._peers.get(t);s==null&&(s=new Dt(this._initialCounters,this._options),this._peers.set(t,s)),s.push(e,n)}}disconnected(t){let e=t.toString(),n=this._peers.get(e);n!=null&&(n.stop(),this._peers.delete(e))}};var Cs=ka;function ka(r,t,e){var n=null,s=null,i=function(){n&&(clearTimeout(n),s=null,n=null)},o=function(){var c=s;i(),c&&c()},a=function(){if(!t)return r.apply(this,arguments);var c=this,l=arguments,u=e&&!n;if(i(),s=function(){r.apply(c,l)},n=setTimeout(function(){if(n=null,!u){var h=s;return s=null,h()}},t),u)return s()};return a.cancel=i,a.flush=o,a}var le=class{peerId;refcnt;network;_entries;_log;constructor(t,e,n){this.peerId=e,this.network=n,this.refcnt=1,this._entries=[],this._log=z(t,"msgqueue"),this.sendEntries=Cs(this.sendEntries.bind(this),ss)}addMessage(t,e={}){t.empty||this.send(t,e)}addEntries(t,e={}){this._entries=this._entries.concat(t),this.sendEntries(e)}sendEntries(t={}){if(this._entries.length===0)return;let e=new B(!1);this._entries.forEach(n=>{n.cancel===!0?e.cancel(n.cid):e.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(e,t)}async send(t,e={}){try{await this.network.connectTo(this.peerId,e)}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,t,e).catch(n=>{this._log.error("send error",n)})}};var ue=class{peers;wantlist;network;_peerId;_log;constructor(t,e,n,s){this.peers=j({name:"ipfs_bitswap_want_manager_peers",metrics:s.metrics}),this.wantlist=new Z(n,s),this.network=e,this._peerId=t,this._log=z(t,"want")}_addEntries(t,e,n,s={}){let i=t.map((o,a)=>new B.Entry(o,rs-a,B.WantType.Block,e));i.forEach(o=>{o.cancel?n===!0?this.wantlist.removeForce(o.cid.toString(y)):this.wantlist.remove(o.cid):(this._log("adding to wantlist"),this.wantlist.add(o.cid,o.priority))});for(let o of this.peers.values())o.addEntries(i,s)}_startPeerHandler(t){let e=this.peers.get(t.toString());if(e!=null){e.refcnt++;return}e=new le(this._peerId,t,this.network);let n=new B(!0);for(let s of this.wantlist.entries())n.addEntry(s[1].cid,s[1].priority);return e.addMessage(n),this.peers.set(t.toString(),e),e}_stopPeerHandler(t){let e=this.peers.get(t.toString());e!=null&&(e.refcnt--,!(e.refcnt>0)&&this.peers.delete(t.toString()))}wantBlocks(t,e={}){this._addEntries(t,!1,!1,e),e.signal?.addEventListener("abort",()=>{this.cancelWants(t)})}unwantBlocks(t){this._log("unwant blocks: %s",t.length),this._addEntries(t,!0,!0)}cancelWants(t){this._log("cancel wants: %s",t.length),this._addEntries(t,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(t){this._startPeerHandler(t)}disconnected(t){this._stopPeerHandler(t)}start(){}stop(){this.peers.forEach(t=>{this.disconnected(t.peerId)})}};var Ea={async getHasher(){throw new Error("Not implemented")}},Sa={maxInboundStreams:1024,maxOutboundStreams:1024,incomingStreamTimeout:3e4,hashLoader:Ea,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},Ca=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],he=class{_libp2p;_log;stats;network;blockstore;engine;wm;notifications;started;constructor(t,e,n={}){this._libp2p=t,this._log=z(this.peerId),n=Object.assign({},Sa,n),this.stats=new ce(t,Ca,{enabled:n.statsEnabled,computeThrottleTimeout:n.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:n.statsComputeThrottleMaxQueueSize}),this.network=new ne(t,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=e,this.engine=new Qt(this.peerId,e,this.network,this.stats,t),this.wm=new ue(this.peerId,this.network,this.stats,t),this.notifications=new ae(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(t,e){try{await this.engine.messageReceived(t,e)}catch{this._log("failed to receive message",e)}if(e.blocks.size===0)return;let n=[];for(let[s,i]of e.blocks.entries()){let o=C.parse(s);n.push({wasWanted:this.wm.wantlist.contains(o),cid:o,data:i})}this.wm.cancelWants(n.filter(({wasWanted:s})=>s).map(({cid:s})=>s)),await Promise.all(n.map(async({cid:s,wasWanted:i,data:o})=>{await this._handleReceivedBlock(t,s,o,i)}))}async _handleReceivedBlock(t,e,n,s){this._log("received block");let i=await this.blockstore.has(e);this._updateReceiveCounters(t.toString(),e,n,i),s&&await this.put(e,n)}_updateReceiveCounters(t,e,n,s){this.stats.push(t,"blocksReceived",1),this.stats.push(t,"dataReceived",n.length),s&&(this.stats.push(t,"dupBlksReceived",1),this.stats.push(t,"dupDataReceived",n.length))}_receiveError(t){this._log.error("ReceiveError",t)}_onPeerConnected(t){this.wm.connected(t)}_onPeerDisconnected(t){this.wm.disconnected(t),this.engine.peerDisconnected(t),this.stats.disconnected(t)}enableStats(){this.stats.enable()}disableStats(){this.stats.disable()}wantlistForPeer(t,e){return this.engine.wantlistForPeer(t)}ledgerForPeer(t){return this.engine.ledgerForPeer(t)}async want(t,e={}){let n=async(c,l)=>(this.wm.wantBlocks([c],l),this.notifications.wantBlock(c,l)),s=!1,i=async(c,l)=>{try{return await this.blockstore.get(c,l)}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u;return s||(s=!0,this.network.findAndConnect(c,l).catch(h=>{this._log.error(h)})),await n(c,l)}},o=new AbortController,a=_r([o.signal,e.signal]);try{return await Promise.race([this.notifications.wantBlock(t,{...e,signal:a}),i(t,{...e,signal:a})])}finally{o.abort(),a.clear()}}unwant(t){let e=Array.isArray(t)?t:[t];this.wm.unwantBlocks(e),e.forEach(n=>{this.notifications.unwantBlock(n)})}cancelWants(t){this.wm.cancelWants(Array.isArray(t)?t:[t])}async put(t,e,n){await this.blockstore.put(t,e),this.notify(t,e)}async*putMany(t,e){yield*this.blockstore.putMany(vr(t,({cid:n,block:s})=>{this.notify(n,s)}),e)}notify(t,e,n={}){this.notifications.hasBlock(t,e),this.engine.receivedBlocks([{cid:t,block:e}]),this.network.provide(t,n).catch(s=>{this._log.error("Failed to provide: %s",s.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 Ts=(r,t,e={})=>new he(r,t,e);var br=class{bitswap;started;constructor(t,e={}){let{libp2p:n,blockstore:s,hashers:i}=t;this.bitswap=Ts(n,s,{hashLoader:{getHasher:async o=>{let a;if(typeof o=="string"?a=Object.values(i).find(c=>c.name===o):a=i[o],a!=null)return a;throw new Error(`Could not load hasher for code/name "${o}"`)}},...e}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e,n){this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}};function As(r={}){return t=>new br(t,r)}var fe=class{url;#t=0;#e=0;#r=0;#n=0;constructor(t){this.url=t instanceof URL?t:new URL(t)}async getRawBlock(t,e){let n=this.url;if(n.pathname=`/ipfs/${t.toString()}`,n.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);try{this.#t++;let s=await fetch(n.toString(),{signal:e,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"});if(!s.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await s.arrayBuffer())}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`unable to fetch raw block for CID ${t}`))}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#n/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}};var de=class{gateways;log;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.gateways=(e.gateways??Ls).map(n=>new fe(n))}async retrieve(t,e={}){let n=this.gateways.sort((i,o)=>o.reliability()-i.reliability()),s=[];for(let i of n){this.log("getting block for %c from %s",t,i.url);try{let o=await i.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,i.url);try{await e.validateFn?.(o)}catch(a){throw this.log.error("failed to validate block for %c from %s",t,i.url,a),i.incrementInvalidBlocks(),new Error(`unable to validate block for CID ${t} from gateway ${i.url}`)}return o}catch(o){if(this.log.error("failed to get block for %c from %s",t,i.url,o),o instanceof Error?s.push(o):s.push(new Error(`unable to fetch raw block for CID ${t} from gateway ${i.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,i.url);break}}}throw new AggregateError(s,`unable to fetch raw block for CID ${t} from any gateway`)}};var Ls=["https://trustless-gateway.link","https://cloudflare-ipfs.com","https://4everland.io"];function Bs(r={}){return t=>new de(t,r)}return Rs(Ta);})();
|
|
2
|
+
"use strict";var HeliaBlockBrokers=(()=>{var po=Object.create;var ae=Object.defineProperty;var mo=Object.getOwnPropertyDescriptor;var go=Object.getOwnPropertyNames;var wo=Object.getPrototypeOf,bo=Object.prototype.hasOwnProperty;var I=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),q=(r,t)=>{for(var e in t)ae(r,e,{get:t[e],enumerable:!0})},Tn=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of go(t))!bo.call(r,s)&&s!==e&&ae(r,s,{get:()=>t[s],enumerable:!(n=mo(t,s))||n.enumerable});return r};var et=(r,t,e)=>(e=r!=null?po(wo(r)):{},Tn(t||!r||!r.__esModule?ae(e,"default",{value:r,enumerable:!0}):e,r)),yo=r=>Tn(ae({},"__esModule",{value:!0}),r);var Xn=I((xl,Qn)=>{Qn.exports=jn;var Gn=128,ca=127,ua=~ca,la=Math.pow(2,31);function jn(r,t,e){t=t||[],e=e||0;for(var n=e;r>=la;)t[e++]=r&255|Gn,r/=128;for(;r&ua;)t[e++]=r&255|Gn,r>>>=7;return t[e]=r|0,jn.bytes=e-n+1,t}});var Zn=I((vl,Kn)=>{Kn.exports=wr;var ha=128,Jn=127;function wr(r,n){var e=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw wr.bytes=0,new RangeError("Could not decode varint");o=r[i++],e+=s<28?(o&Jn)<<s:(o&Jn)*Math.pow(2,s),s+=7}while(o>=ha);return wr.bytes=i-n,e}});var ts=I((_l,Yn)=>{var fa=Math.pow(2,7),da=Math.pow(2,14),pa=Math.pow(2,21),ma=Math.pow(2,28),ga=Math.pow(2,35),wa=Math.pow(2,42),ba=Math.pow(2,49),ya=Math.pow(2,56),xa=Math.pow(2,63);Yn.exports=function(r){return r<fa?1:r<da?2:r<pa?3:r<ma?4:r<ga?5:r<wa?6:r<ba?7:r<ya?8:r<xa?9:10}});var rs=I((El,es)=>{es.exports={encode:Xn(),decode:Zn(),encodingLength:ts()}});var is=I((kl,ss)=>{"use strict";var ns=rs();ss.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=ns.decode(r);t.push(e),r=r.slice(ns.decode.bytes)}return t}});var as=I((Sl,os)=>{var Lt=1e3,Ft=Lt*60,Pt=Ft*60,gt=Pt*24,va=gt*7,_a=gt*365.25;os.exports=function(r,t){t=t||{};var e=typeof r;if(e==="string"&&r.length>0)return Ea(r);if(e==="number"&&isFinite(r))return t.long?Sa(r):ka(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Ea(r){if(r=String(r),!(r.length>100)){var t=/^(-?(?:\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(t){var e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*_a;case"weeks":case"week":case"w":return e*va;case"days":case"day":case"d":return e*gt;case"hours":case"hour":case"hrs":case"hr":case"h":return e*Pt;case"minutes":case"minute":case"mins":case"min":case"m":return e*Ft;case"seconds":case"second":case"secs":case"sec":case"s":return e*Lt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:return}}}}function ka(r){var t=Math.abs(r);return t>=gt?Math.round(r/gt)+"d":t>=Pt?Math.round(r/Pt)+"h":t>=Ft?Math.round(r/Ft)+"m":t>=Lt?Math.round(r/Lt)+"s":r+"ms"}function Sa(r){var t=Math.abs(r);return t>=gt?de(r,t,gt,"day"):t>=Pt?de(r,t,Pt,"hour"):t>=Ft?de(r,t,Ft,"minute"):t>=Lt?de(r,t,Lt,"second"):r+" ms"}function de(r,t,e,n){var s=t>=e*1.5;return Math.round(r/e)+" "+n+(s?"s":"")}});var us=I((Al,cs)=>{function Aa(r){e.debug=e,e.default=e,e.coerce=u,e.disable=i,e.enable=s,e.enabled=o,e.humanize=as(),e.destroy=c,Object.keys(r).forEach(l=>{e[l]=r[l]}),e.names=[],e.skips=[],e.formatters={};function t(l){let h=0;for(let f=0;f<l.length;f++)h=(h<<5)-h+l.charCodeAt(f),h|=0;return e.colors[Math.abs(h)%e.colors.length]}e.selectColor=t;function e(l){let h,f=null,p,d;function g(...m){if(!g.enabled)return;let v=g,k=Number(new Date),C=k-(h||k);v.diff=C,v.prev=h,v.curr=k,h=k,m[0]=e.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let L=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(Q,$)=>{if(Q==="%%")return"%";L++;let X=e.formatters[$];if(typeof X=="function"){let kt=m[L];Q=X.call(v,kt),m.splice(L,1),L--}return Q}),e.formatArgs.call(v,m),(v.log||e.log).apply(v,m)}return g.namespace=l,g.useColors=e.useColors(),g.color=e.selectColor(l),g.extend=n,g.destroy=e.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(p!==e.namespaces&&(p=e.namespaces,d=e.enabled(l)),d),set:m=>{f=m}}),typeof e.init=="function"&&e.init(g),g}function n(l,h){let f=e(this.namespace+(typeof h>"u"?":":h)+l);return f.log=this.log,f}function s(l){e.save(l),e.namespaces=l,e.names=[],e.skips=[];let h,f=(typeof l=="string"?l:"").split(/[\s,]+/),p=f.length;for(h=0;h<p;h++)f[h]&&(l=f[h].replace(/\*/g,".*?"),l[0]==="-"?e.skips.push(new RegExp("^"+l.slice(1)+"$")):e.names.push(new RegExp("^"+l+"$")))}function i(){let l=[...e.names.map(a),...e.skips.map(a).map(h=>"-"+h)].join(",");return e.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let h,f;for(h=0,f=e.skips.length;h<f;h++)if(e.skips[h].test(l))return!1;for(h=0,f=e.names.length;h<f;h++)if(e.names[h].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function u(l){return l instanceof Error?l.stack||l.message:l}function c(){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 e.enable(e.load()),e}cs.exports=Aa});var ls=I((V,pe)=>{V.formatArgs=Ca;V.save=Ia;V.load=La;V.useColors=Ta;V.storage=Fa();V.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`."))}})();V.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 Ta(){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 Ca(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+pe.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(e++,s==="%c"&&(n=e))}),r.splice(n,0,t)}V.log=console.debug||console.log||(()=>{});function Ia(r){try{r?V.storage.setItem("debug",r):V.storage.removeItem("debug")}catch{}}function La(){let r;try{r=V.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Fa(){try{return localStorage}catch{}}pe.exports=us()(V);var{formatters:Pa}=pe.exports;Pa.j=function(r){try{return JSON.stringify(r)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var ps=I((ql,ds)=>{ds.exports=vr;var fs=128,Ma=127,Ra=~Ma,Ua=Math.pow(2,31);function vr(r,t,e){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw vr.bytes=0,new RangeError("Could not encode varint");t=t||[],e=e||0;for(var n=e;r>=Ua;)t[e++]=r&255|fs,r/=128;for(;r&Ra;)t[e++]=r&255|fs,r>>>=7;return t[e]=r|0,vr.bytes=e-n+1,t}});var ws=I((Vl,gs)=>{gs.exports=_r;var Oa=128,ms=127;function _r(r,n){var e=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a||s>49)throw _r.bytes=0,new RangeError("Could not decode varint");o=r[i++],e+=s<28?(o&ms)<<s:(o&ms)*Math.pow(2,s),s+=7}while(o>=Oa);return _r.bytes=i-n,e}});var ys=I((Wl,bs)=>{var za=Math.pow(2,7),$a=Math.pow(2,14),qa=Math.pow(2,21),Va=Math.pow(2,28),Wa=Math.pow(2,35),Ha=Math.pow(2,42),Ga=Math.pow(2,49),ja=Math.pow(2,56),Qa=Math.pow(2,63);bs.exports=function(r){return r<za?1:r<$a?2:r<qa?3:r<Va?4:r<Wa?5:r<Ha?6:r<Ga?7:r<ja?8:r<Qa?9:10}});var vs=I((Hl,xs)=>{xs.exports={encode:ps(),decode:ws(),encodingLength:ys()}});var Hs=I((Qf,Ws)=>{"use strict";function Vs(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function Bc(r,t,e){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");e||(e={}),typeof t=="object"&&(e=t,t=""),t&&(e.code=t);try{return Vs(r,e)}catch{e.message=r.message,e.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Vs(new s,e)}}Ws.exports=Bc});var Zs=I((pd,Ks)=>{"use strict";Ks.exports=function(){return Date.now()}});var ti=I((md,Ys)=>{"use strict";var Fe=Zs(),tn=class{constructor(t,e,n){let s=this;this._started=Fe(),this._rescheduled=0,this._scheduled=e,this._args=n,this._triggered=!1,this._timerWrapper=()=>{s._rescheduled>0?(s._scheduled=s._rescheduled-(Fe()-s._started),s._schedule(s._scheduled)):(s._triggered=!0,t.apply(null,s._args))},this._timer=setTimeout(this._timerWrapper,e)}reschedule(t){t||(t=this._scheduled);let e=Fe();e+t-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(t)):this._triggered?this._schedule(t):(this._started=e,this._rescheduled=t)}_schedule(t){this._triggered=!1,this._started=Fe(),this._rescheduled=0,this._scheduled=t,this._timer=setTimeout(this._timerWrapper,t)}clear(){clearTimeout(this._timer)}};function jc(){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 t=0;t<r.length;t++)r[t]=arguments[t+2]}return new tn(arguments[0],arguments[1],r)}Ys.exports=jc});var ni=I((gd,ri)=>{"use strict";var{AbortController:Qc}=globalThis,ei=ti(),en=class r extends Qc{constructor(t){super(),this._ms=t,this._timer=ei(()=>this.abort(),t),Object.setPrototypeOf(this,r.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=ei(()=>this.abort(),this._ms)}};ri.exports={TimeoutController:en}});var Ne=I((Td,on)=>{"use strict";var Ot=typeof Reflect=="object"?Reflect:null,ui=Ot&&typeof Ot.apply=="function"?Ot.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},De;Ot&&typeof Ot.ownKeys=="function"?De=Ot.ownKeys:Object.getOwnPropertySymbols?De=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:De=function(t){return Object.getOwnPropertyNames(t)};function Zc(r){console&&console.warn&&console.warn(r)}var hi=Number.isNaN||function(t){return t!==t};function _(){_.init.call(this)}on.exports=_;on.exports.once=ru;_.EventEmitter=_;_.prototype._events=void 0;_.prototype._eventsCount=0;_.prototype._maxListeners=void 0;var li=10;function Be(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(_,"defaultMaxListeners",{enumerable:!0,get:function(){return li},set:function(r){if(typeof r!="number"||r<0||hi(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");li=r}});_.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};_.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||hi(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function fi(r){return r._maxListeners===void 0?_.defaultMaxListeners:r._maxListeners}_.prototype.getMaxListeners=function(){return fi(this)};_.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var s=t==="error",i=this._events;if(i!==void 0)s=s&&i.error===void 0;else if(!s)return!1;if(s){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=i[t];if(u===void 0)return!1;if(typeof u=="function")ui(u,this,e);else for(var c=u.length,l=wi(u,c),n=0;n<c;++n)ui(l[n],this,e);return!0};function di(r,t,e,n){var s,i,o;if(Be(e),i=r._events,i===void 0?(i=r._events=Object.create(null),r._eventsCount=0):(i.newListener!==void 0&&(r.emit("newListener",t,e.listener?e.listener:e),i=r._events),o=i[t]),o===void 0)o=i[t]=e,++r._eventsCount;else if(typeof o=="function"?o=i[t]=n?[e,o]:[o,e]:n?o.unshift(e):o.push(e),s=fi(r),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=t,a.count=o.length,Zc(a)}return r}_.prototype.addListener=function(t,e){return di(this,t,e,!1)};_.prototype.on=_.prototype.addListener;_.prototype.prependListener=function(t,e){return di(this,t,e,!0)};function Yc(){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 pi(r,t,e){var n={fired:!1,wrapFn:void 0,target:r,type:t,listener:e},s=Yc.bind(n);return s.listener=e,n.wrapFn=s,s}_.prototype.once=function(t,e){return Be(e),this.on(t,pi(this,t,e)),this};_.prototype.prependOnceListener=function(t,e){return Be(e),this.prependListener(t,pi(this,t,e)),this};_.prototype.removeListener=function(t,e){var n,s,i,o,a;if(Be(e),s=this._events,s===void 0)return this;if(n=s[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete s[t],s.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===e||n[o].listener===e){a=n[o].listener,i=o;break}if(i<0)return this;i===0?n.shift():tu(n,i),n.length===1&&(s[t]=n[0]),s.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this};_.prototype.off=_.prototype.removeListener;_.prototype.removeAllListeners=function(t){var e,n,s;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[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var i=Object.keys(n),o;for(s=0;s<i.length;++s)o=i[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(s=e.length-1;s>=0;s--)this.removeListener(t,e[s]);return this};function mi(r,t,e){var n=r._events;if(n===void 0)return[];var s=n[t];return s===void 0?[]:typeof s=="function"?e?[s.listener||s]:[s]:e?eu(s):wi(s,s.length)}_.prototype.listeners=function(t){return mi(this,t,!0)};_.prototype.rawListeners=function(t){return mi(this,t,!1)};_.listenerCount=function(r,t){return typeof r.listenerCount=="function"?r.listenerCount(t):gi.call(r,t)};_.prototype.listenerCount=gi;function gi(r){var t=this._events;if(t!==void 0){var e=t[r];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}_.prototype.eventNames=function(){return this._eventsCount>0?De(this._events):[]};function wi(r,t){for(var e=new Array(t),n=0;n<t;++n)e[n]=r[n];return e}function tu(r,t){for(;t+1<r.length;t++)r[t]=r[t+1];r.pop()}function eu(r){for(var t=new Array(r.length),e=0;e<t.length;++e)t[e]=r[e].listener||r[e];return t}function ru(r,t){return new Promise(function(e,n){function s(o){r.removeListener(t,i),n(o)}function i(){typeof r.removeListener=="function"&&r.removeListener("error",s),e([].slice.call(arguments))}bi(r,t,i,{once:!0}),t!=="error"&&nu(r,s,{once:!0})})}function nu(r,t,e){typeof r.on=="function"&&bi(r,"error",t,e)}function bi(r,t,e,n){if(typeof r.on=="function")n.once?r.once(t,e):r.on(t,e);else if(typeof r.addEventListener=="function")r.addEventListener(t,function s(i){n.once&&r.removeEventListener(t,s),e(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var ki=I((_i,Ei)=>{"use strict";var su=Math.exp;_i=Ei.exports=function(t){if(typeof t!="number")throw new Error("must provide a timespan to the moving average constructor");if(t<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let e,n=0,s=0,i=0,o,a={};function u(c,l){return 1-su(-(c-l)/t)}return a.push=function(l,h){if(o){let f=u(l,o),p=h-e,d=f*p;e=f*h+(1-f)*e,n=(1-f)*(n+p*d),s=Math.sqrt(n),i=e+f*p}else e=h;o=l},a.movingAverage=function(){return e},a.variance=function(){return n},a.deviation=function(){return s},a.forecast=function(){return i},a}});var Di=I(re=>{(function(){var r,t,e,n,s,i,o,a;a=function(u){var c,l,h,f;return c=(u&255<<24)>>>24,l=(u&255<<16)>>>16,h=(u&65280)>>>8,f=u&255,[c,l,h,f].join(".")},o=function(u){var c,l,h,f,p,d;for(c=[],h=f=0;f<=3&&u.length!==0;h=++f){if(h>0){if(u[0]!==".")throw new Error("Invalid IP");u=u.substring(1)}d=t(u),p=d[0],l=d[1],u=u.substring(l),c.push(p)}if(u.length!==0)throw new Error("Invalid IP");switch(c.length){case 1:if(c[0]>4294967295)throw new Error("Invalid IP");return c[0]>>>0;case 2:if(c[0]>255||c[1]>16777215)throw new Error("Invalid IP");return(c[0]<<24|c[1])>>>0;case 3:if(c[0]>255||c[1]>255||c[2]>65535)throw new Error("Invalid IP");return(c[0]<<24|c[1]<<16|c[2])>>>0;case 4:if(c[0]>255||c[1]>255||c[2]>255||c[3]>255)throw new Error("Invalid IP");return(c[0]<<24|c[1]<<16|c[2]<<8|c[3])>>>0;default:throw new Error("Invalid IP")}},e=function(u){return u.charCodeAt(0)},n=e("0"),i=e("a"),s=e("A"),t=function(u){var c,l,h,f,p;for(f=0,c=10,l="9",h=0,u.length>1&&u[h]==="0"&&(u[h+1]==="x"||u[h+1]==="X"?(h+=2,c=16):"0"<=u[h+1]&&u[h+1]<="9"&&(h++,c=8,l="7")),p=h;h<u.length;){if("0"<=u[h]&&u[h]<=l)f=f*c+(e(u[h])-n)>>>0;else if(c===16)if("a"<=u[h]&&u[h]<="f")f=f*c+(10+e(u[h])-i)>>>0;else if("A"<=u[h]&&u[h]<="F")f=f*c+(10+e(u[h])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");h++}if(h===p)throw new Error("empty octet");return[f,h]},r=function(){function u(c,l){var h,f,p,d;if(typeof c!="string")throw new Error("Missing `net' parameter");if(l||(d=c.split("/",2),c=d[0],l=d[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=o(l)}catch(g){throw h=g,new Error("Invalid mask: "+l)}for(f=p=32;p>=0;f=--p)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(c)&this.maskLong)>>>0}catch(g){throw h=g,new Error("Invalid net address: "+c)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return u.prototype.contains=function(c){return typeof c=="string"&&(c.indexOf("/")>0||c.split(".").length!==4)&&(c=new u(c)),c instanceof u?this.contains(c.base)&&this.contains(c.broadcast||c.last):(o(c)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},u.prototype.next=function(c){return c==null&&(c=1),new u(a(this.netLong+this.size*c),this.mask)},u.prototype.forEach=function(c){var l,h,f;for(f=o(this.first),h=o(this.last),l=0;f<=h;)c(a(f),f,l),l++,f++},u.prototype.toString=function(){return this.base+"/"+this.bitmask},u}(),re.ip2long=o,re.long2ip=a,re.Netmask=r}).call(re)});var ju={};q(ju,{bitswap:()=>Li,trustlessGateway:()=>fo});function Cn(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function xo(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var ce=xo;function vo(r){return r[Symbol.asyncIterator]!=null}function In(r){return r?.then!=null}function _o(r,t){if(vo(r))return async function*(){for await(let a of r){let u=t(a);In(u)&&await u,yield a}}();let e=ce(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();if(typeof t(n)?.then=="function")return async function*(){yield n;for await(let a of e){let u=t(a);In(u)&&await u,yield a}}();let o=t;return function*(){yield n;for(let a of e)o(a),yield a}()}var Ln=_o;var cr={};q(cr,{base32:()=>Z,base32hex:()=>Fo,base32hexpad:()=>Do,base32hexpadupper:()=>Bo,base32hexupper:()=>Po,base32pad:()=>Io,base32padupper:()=>Lo,base32upper:()=>Co,base32z:()=>No});var Yu=new Uint8Array(0);function Fn(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function st(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Pn(r){return new TextEncoder().encode(r)}function Dn(r){return new TextDecoder().decode(r)}function Eo(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(e[o]!==255)throw new TypeError(i+" is ambiguous");e[o]=s}var a=r.length,u=r.charAt(0),c=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,m=0,v=0,k=d.length;v!==k&&d[v]===0;)v++,g++;for(var C=(k-v)*l+1>>>0,L=new Uint8Array(C);v!==k;){for(var z=d[v],Q=0,$=C-1;(z!==0||Q<m)&&$!==-1;$--,Q++)z+=256*L[$]>>>0,L[$]=z%a>>>0,z=z/a>>>0;if(z!==0)throw new Error("Non-zero carry");m=Q,v++}for(var X=C-m;X!==C&&L[X]===0;)X++;for(var kt=u.repeat(g);X<C;++X)kt+=r.charAt(L[X]);return kt}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var m=0,v=0;d[g]===u;)m++,g++;for(var k=(d.length-g)*c+1>>>0,C=new Uint8Array(k);d[g];){var L=e[d.charCodeAt(g)];if(L===255)return;for(var z=0,Q=k-1;(L!==0||z<v)&&Q!==-1;Q--,z++)L+=a*C[Q]>>>0,C[Q]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");v=z,g++}if(d[g]!==" "){for(var $=k-v;$!==k&&C[$]===0;)$++;for(var X=new Uint8Array(m+(k-$)),kt=m;$!==k;)X[kt++]=C[$++];return X}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var ko=Eo,So=ko,Nn=So;var sr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},ir=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Mn(this,t)}},or=class{decoders;constructor(t){this.decoders=t}or(t){return Mn(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Mn(r,t){return new or({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ar=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new sr(t,e,n),this.decoder=new ir(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function St({name:r,prefix:t,encode:e,decode:n}){return new ar(r,t,e,n)}function at({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Nn(e,r);return St({prefix:t,name:r,encode:n,decode:i=>st(s(i))})}function Ao(r,t,e,n){let s={};for(let l=0;l<t.length;++l)s[t[l]]=l;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*e/8|0),a=0,u=0,c=0;for(let l=0;l<i;++l){let h=s[r[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);u=u<<e|h,a+=e,a>=8&&(a-=8,o[c++]=255&u>>a)}if(a>=e||255&u<<8-a)throw new SyntaxError("Unexpected end of data");return o}function To(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,i="",o=0,a=0;for(let u=0;u<r.length;++u)for(a=a<<8|r[u],o+=8;o>e;)o-=e,i+=t[s&a>>o];if(o!==0&&(i+=t[s&a<<e-o]),n)for(;i.length*e&7;)i+="=";return i}function S({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return St({prefix:t,name:r,encode(s){return To(s,n,e)},decode(s){return Ao(s,n,e,r)}})}var Z=S({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Co=S({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Io=S({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Lo=S({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Fo=S({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Po=S({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Do=S({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Bo=S({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),No=S({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ur={};q(ur,{base58btc:()=>w,base58flickr:()=>Mo});var w=at({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mo=at({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ro=On,Rn=128,Uo=127,Oo=~Uo,zo=Math.pow(2,31);function On(r,t,e){t=t||[],e=e||0;for(var n=e;r>=zo;)t[e++]=r&255|Rn,r/=128;for(;r&Oo;)t[e++]=r&255|Rn,r>>>=7;return t[e]=r|0,On.bytes=e-n+1,t}var $o=lr,qo=128,Un=127;function lr(r,n){var e=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw lr.bytes=0,new RangeError("Could not decode varint");o=r[i++],e+=s<28?(o&Un)<<s:(o&Un)*Math.pow(2,s),s+=7}while(o>=qo);return lr.bytes=i-n,e}var Vo=Math.pow(2,7),Wo=Math.pow(2,14),Ho=Math.pow(2,21),Go=Math.pow(2,28),jo=Math.pow(2,35),Qo=Math.pow(2,42),Xo=Math.pow(2,49),Jo=Math.pow(2,56),Ko=Math.pow(2,63),Zo=function(r){return r<Vo?1:r<Wo?2:r<Ho?3:r<Go?4:r<jo?5:r<Qo?6:r<Xo?7:r<Jo?8:r<Ko?9:10},Yo={encode:Ro,decode:$o,encodingLength:Zo},ta=Yo,Wt=ta;function Ht(r,t=0){return[Wt.decode(r,t),Wt.decode.bytes]}function At(r,t,e=0){return Wt.encode(r,t,e),t}function Tt(r){return Wt.encodingLength(r)}function mt(r,t){let e=t.byteLength,n=Tt(r),s=n+Tt(e),i=new Uint8Array(s+e);return At(r,i,0),At(e,i,n),i.set(t,s),new Ct(r,e,t,i)}function le(r){let t=st(r),[e,n]=Ht(t),[s,i]=Ht(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Ct(e,s,o,t)}function zn(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Fn(r.bytes,e.bytes)}}var Ct=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};function $n(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return ra(e,hr(r),t??w.encoder);default:return na(e,hr(r),t??Z.encoder)}}var qn=new WeakMap;function hr(r){let t=qn.get(r);if(t==null){let e=new Map;return qn.set(r,e),e}return t}var A=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Gt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==sa)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=mt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&zn(t.multihash,n.multihash)}toString(t){return $n(this,t)}toJSON(){return{"/":$n(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:i,bytes:o}=e;return new r(n,s,i,o??Vn(n,s,i.bytes))}else if(e[ia]===!0){let{version:n,multihash:s,code:i}=e,o=le(s);return r.create(n,i,o)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Gt)throw new Error(`Version 0 CID must use dag-pb (code: ${Gt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Vn(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Gt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=st(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=s.subarray(e.multihashSize-e.digestSize),o=new Ct(e.multihashCode,e.digestSize,i,s);return[e.version===0?r.createV0(o):r.createV1(e.codec,o),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=Ht(t.subarray(e));return e+=f,h},s=n(),i=Gt;if(s===18?(s=0,e=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=e,a=n(),u=n(),c=e+u,l=c-o;return{version:s,codec:i,multihashCode:a,digestSize:u,multihashSize:l,size:c}}static parse(t,e){let[n,s]=ea(t,e),i=r.decode(s);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return hr(i).set(n,t),i}};function ea(r,t){switch(r[0]){case"Q":{let e=t??w;return[w.prefix,e.decode(`${w.prefix}${r}`)]}case w.prefix:{let e=t??w;return[w.prefix,e.decode(r)]}case Z.prefix:{let e=t??Z;return[Z.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function ra(r,t,e){let{prefix:n}=e;if(n!==w.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return s}function na(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let i=e.encode(r);return t.set(n,i),i}else return s}var Gt=112,sa=18;function Vn(r,t,e){let n=Tt(r),s=n+Tt(t),i=new Uint8Array(s+e.byteLength);return At(r,i,0),At(t,i,n),i.set(e,s),i}var ia=Symbol.for("@ipld/js-cid/CID");var fr=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ct(r){let{name:t,metrics:e}=r,n;return e!=null?n=new fr({name:t,metrics:e}):n=new Map,n}var ut=class r extends Error{code;type;constructor(t="The operation was aborted"){super(t),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},rt=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var he=(r,...t)=>{try{[...t]}catch{}};var fe=class extends EventTarget{#t=new Map;constructor(){super(),he(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:i})=>i!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new oa(t,e))}},dr=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},oa=globalThis.CustomEvent??dr;var gr={};q(gr,{sha256:()=>jt,sha512:()=>aa});function mr({name:r,code:t,encode:e}){return new pr(r,t,e)}var pr=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?mt(this.code,e):e.then(n=>mt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Hn(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var jt=mr({name:"sha2-256",code:18,encode:Hn("SHA-256")}),aa=mr({name:"sha2-512",code:19,encode:Hn("SHA-512")});var Ms=et(is(),1);var W=et(ls(),1);var xr={};q(xr,{base64:()=>br,base64pad:()=>Da,base64url:()=>yr,base64urlpad:()=>Ba});var br=S({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Da=S({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),yr=S({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ba=S({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});W.default.formatters.b=r=>r==null?"undefined":w.baseEncode(r);W.default.formatters.t=r=>r==null?"undefined":Z.baseEncode(r);W.default.formatters.m=r=>r==null?"undefined":br.baseEncode(r);W.default.formatters.p=r=>r==null?"undefined":r.toString();W.default.formatters.c=r=>r==null?"undefined":r.toString();W.default.formatters.k=r=>r==null?"undefined":r.toString();W.default.formatters.a=r=>r==null?"undefined":r.toString();function Na(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function hs(r){let t=Na(`${r}:trace`);return W.default.enabled(`${r}:trace`)&&W.default.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=(0,W.default)(`${r}:trace`)),Object.assign((0,W.default)(r),{error:(0,W.default)(`${r}:error`),trace:t})}function Dt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var wt=class{_refCounter;cid;priority;wantType;constructor(t,e,n){this._refCounter=1,this.cid=t,this.priority=e??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(w)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(t){return this._refCounter===t._refCounter&&this.cid.equals(t.cid)&&this.priority===t.priority&&this.wantType===t.wantType}};var lt=class{entry;cancel;sendDontHave;constructor(t,e,n,s,i){this.entry=new wt(t,e,n),this.cancel=!!s,this.sendDontHave=!!i}get cid(){return this.entry.cid}set cid(t){this.entry.cid=t}get priority(){return this.entry.priority}set priority(t){this.entry.priority=t}get wantType(){return this.entry.wantType}set wantType(t){this.entry.wantType=t}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(w)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(t){return this.cancel===t.cancel&&this.sendDontHave===t.sendDontHave&&this.wantType===t.wantType&&this.entry.equals(t.entry)}};var J=(r,t)=>{let e=["bitswap"];return t!=null&&e.push(t),r!=null&&e.push(`${r.toString().slice(0,8)}`),hs(e.join(":"))};var me=(r,t)=>{if(r.size!==t.size)return!1;for(let[e,n]of r){let s=t.get(e);if(s===void 0||n instanceof Uint8Array&&s instanceof Uint8Array&&!Dt(n,s)||n instanceof lt&&s instanceof lt&&!n.equals(s))return!1}return!0};var Qt=et(vs(),1);function Xa(r){let t=new Uint8Array(r.reduce((n,s)=>n+Qt.default.encodingLength(s),0)),e=0;for(let n of r)t=Qt.encode(n,t,e),e+=Qt.default.encodingLength(n);return t}var _s=Xa;function it(r=0){return new Uint8Array(r)}function B(r=0){return new Uint8Array(r)}var Ja=Math.pow(2,7),Ka=Math.pow(2,14),Za=Math.pow(2,21),Er=Math.pow(2,28),kr=Math.pow(2,35),Sr=Math.pow(2,42),Ar=Math.pow(2,49),x=128,N=127;function F(r){if(r<Ja)return 1;if(r<Ka)return 2;if(r<Za)return 3;if(r<Er)return 4;if(r<kr)return 5;if(r<Sr)return 6;if(r<Ar)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Tr(r,t,e=0){switch(F(r)){case 8:t[e++]=r&255|x,r/=128;case 7:t[e++]=r&255|x,r/=128;case 6:t[e++]=r&255|x,r/=128;case 5:t[e++]=r&255|x,r/=128;case 4:t[e++]=r&255|x,r>>>=7;case 3:t[e++]=r&255|x,r>>>=7;case 2:t[e++]=r&255|x,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Ya(r,t,e=0){switch(F(r)){case 8:t.set(e++,r&255|x),r/=128;case 7:t.set(e++,r&255|x),r/=128;case 6:t.set(e++,r&255|x),r/=128;case 5:t.set(e++,r&255|x),r/=128;case 4:t.set(e++,r&255|x),r>>>=7;case 3:t.set(e++,r&255|x),r>>>=7;case 2:t.set(e++,r&255|x),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Cr(r,t){let e=r[t],n=0;if(n+=e&N,e<x||(e=r[t+1],n+=(e&N)<<7,e<x)||(e=r[t+2],n+=(e&N)<<14,e<x)||(e=r[t+3],n+=(e&N)<<21,e<x)||(e=r[t+4],n+=(e&N)*Er,e<x)||(e=r[t+5],n+=(e&N)*kr,e<x)||(e=r[t+6],n+=(e&N)*Sr,e<x)||(e=r[t+7],n+=(e&N)*Ar,e<x))return n;throw new RangeError("Could not decode varint")}function tc(r,t){let e=r.get(t),n=0;if(n+=e&N,e<x||(e=r.get(t+1),n+=(e&N)<<7,e<x)||(e=r.get(t+2),n+=(e&N)<<14,e<x)||(e=r.get(t+3),n+=(e&N)<<21,e<x)||(e=r.get(t+4),n+=(e&N)*Er,e<x)||(e=r.get(t+5),n+=(e&N)*kr,e<x)||(e=r.get(t+6),n+=(e&N)*Sr,e<x)||(e=r.get(t+7),n+=(e&N)*Ar,e<x))return n;throw new RangeError("Could not decode varint")}function ht(r,t,e=0){return t==null&&(t=B(F(r))),t instanceof Uint8Array?Tr(r,t,e):Ya(r,t,e)}function ot(r,t=0){return r instanceof Uint8Array?Cr(r,t):tc(r,t)}var Ir=new Float32Array([-0]),ft=new Uint8Array(Ir.buffer);function Es(r,t,e){Ir[0]=r,t[e]=ft[0],t[e+1]=ft[1],t[e+2]=ft[2],t[e+3]=ft[3]}function ks(r,t){return ft[0]=r[t],ft[1]=r[t+1],ft[2]=r[t+2],ft[3]=r[t+3],Ir[0]}var Lr=new Float64Array([-0]),M=new Uint8Array(Lr.buffer);function Ss(r,t,e){Lr[0]=r,t[e]=M[0],t[e+1]=M[1],t[e+2]=M[2],t[e+3]=M[3],t[e+4]=M[4],t[e+5]=M[5],t[e+6]=M[6],t[e+7]=M[7]}function As(r,t){return M[0]=r[t],M[1]=r[t+1],M[2]=r[t+2],M[3]=r[t+3],M[4]=r[t+4],M[5]=r[t+5],M[6]=r[t+6],M[7]=r[t+7],Lr[0]}var ec=BigInt(Number.MAX_SAFE_INTEGER),rc=BigInt(Number.MIN_SAFE_INTEGER),H=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return bt;if(t<ec&&t>rc)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>Ts&&(s=0n,++n>Ts&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return bt;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):bt}},bt=new H(0,0);bt.toBigInt=function(){return 0n};bt.zzEncode=bt.zzDecode=function(){return this};bt.length=function(){return 1};var Ts=4294967296n;function Cs(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Is(r,t,e){if(e-t<1)return"";let s,i=[],o=0,a;for(;t<e;)a=r[t++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,o>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s!=null?(o>0&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function Fr(r,t,e){let n=e,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++o,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function Y(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function we(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Pr=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Y(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Y(this,4);return we(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Y(this,4);return we(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Y(this,4);let t=ks(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Y(this,4);let t=As(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Y(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Is(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Y(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Y(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new H(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Y(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Y(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Y(this,8);let t=we(this.buf,this.pos+=4),e=we(this.buf,this.pos+=4);return new H(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Cr(this.buf,this.pos);return this.pos+=F(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Dr(r){return new Pr(r instanceof Uint8Array?r:r.subarray())}function yt(r,t,e){let n=Dr(r);return t.decode(n,void 0,e)}var Br={};q(Br,{base10:()=>nc});var nc=at({prefix:"9",name:"base10",alphabet:"0123456789"});var Nr={};q(Nr,{base16:()=>sc,base16upper:()=>ic});var sc=S({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ic=S({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Mr={};q(Mr,{base2:()=>oc});var oc=S({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Rr={};q(Rr,{base256emoji:()=>hc});var Fs=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}"),ac=Fs.reduce((r,t,e)=>(r[e]=t,r),[]),cc=Fs.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function uc(r){return r.reduce((t,e)=>(t+=ac[e],t),"")}function lc(r){let t=[];for(let e of r){let n=cc[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var hc=St({prefix:"\u{1F680}",name:"base256emoji",encode:uc,decode:lc});var Ur={};q(Ur,{base36:()=>fc,base36upper:()=>dc});var fc=at({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),dc=at({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Or={};q(Or,{base8:()=>pc});var pc=S({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var zr={};q(zr,{identity:()=>mc});var mc=St({prefix:"\0",name:"identity",encode:r=>Dn(r),decode:r=>Pn(r)});var hh=new TextEncoder,fh=new TextDecoder;var $r={};q($r,{identity:()=>xc});var Ps=0,bc="identity",Ds=st;function yc(r){return mt(Ps,Ds(r))}var xc={code:Ps,name:bc,encode:Ds,digest:yc};var Xt={...zr,...Mr,...Or,...Br,...Nr,...cr,...Ur,...ur,...xr,...Rr},kh={...gr,...$r};function Ns(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Bs=Ns("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),qr=Ns("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=B(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),vc={utf8:Bs,"utf-8":Bs,hex:Xt.base16,latin1:qr,ascii:qr,binary:qr,...Xt},be=vc;function Jt(r,t="utf8"){let e=be[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Vr(r){let t=r??8192,e=t>>>1,n,s=t;return function(o){if(o<1||o>e)return B(o);s+o>t&&(n=B(t),s=0);let a=n.subarray(s,s+=o);return s&7&&(s=(s|7)+1),a}}var xt=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Wr(){}var Gr=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},_c=Vr();function Ec(r){return globalThis.Buffer!=null?B(r):_c(r)}var Zt=class{len;head;tail;states;constructor(){this.len=0,this.head=new xt(Wr,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new xt(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new jr((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ye,10,H.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=H.fromBigInt(t);return this._push(ye,e.length(),e)}uint64Number(t){return this._push(Tr,F(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=H.fromBigInt(t).zzEncode();return this._push(ye,e.length(),e)}sint64Number(t){let e=H.fromNumber(t).zzEncode();return this._push(ye,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Hr,1,t?1:0)}fixed32(t){return this._push(Kt,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=H.fromBigInt(t);return this._push(Kt,4,e.lo)._push(Kt,4,e.hi)}fixed64Number(t){let e=H.fromNumber(t);return this._push(Kt,4,e.lo)._push(Kt,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Es,4,t)}double(t){return this._push(Ss,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Hr,1,0):this.uint32(e)._push(Sc,e,t)}string(t){let e=Cs(t);return e!==0?this.uint32(e)._push(Fr,e,t):this._push(Hr,1,0)}fork(){return this.states=new Gr(this),this.head=this.tail=new xt(Wr,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new xt(Wr,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Ec(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Hr(r,t,e){t[e]=r&255}function kc(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var jr=class extends xt{next;constructor(t,e){super(kc,t,e),this.next=void 0}};function ye(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Kt(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Sc(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Zt.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Ac,t,r),this},Zt.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Tc,t,r),this});function Ac(r,t,e){t.set(r,e)}function Tc(r,t,e){r.length<40?Fr(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Jt(r),e)}function Qr(){return new Zt}function vt(r,t){let e=Qr();return t.encode(r,e,{lengthDelimited:!1}),e.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 xe(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function ve(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,o){let a=t(i);o.int32(a)},n=function(i){let o=i.int32();return t(o)};return xe("enum",Bt.VARINT,e,n)}function _t(r,t){return xe("message",Bt.LENGTH_DELIMITED,r,t)}var O;(function(r){let t;(function(a){let u;(function(f){f.Block="Block",f.Have="Have"})(u=a.WantType||(a.WantType={}));let c;(function(f){f[f.Block=0]="Block",f[f.Have=1]="Have"})(c||(c={})),function(f){f.codec=()=>ve(c)}(u=a.WantType||(a.WantType={}));let l;(function(f){let p;f.codec=()=>(p==null&&(p=_t((d,g,m={})=>{m.lengthDelimited!==!1&&g.fork(),d.block!=null&&d.block.byteLength>0&&(g.uint32(10),g.bytes(d.block)),d.priority!=null&&d.priority!==0&&(g.uint32(16),g.int32(d.priority)),d.cancel!=null&&d.cancel!==!1&&(g.uint32(24),g.bool(d.cancel)),d.wantType!=null&&c[d.wantType]!==0&&(g.uint32(32),r.Wantlist.WantType.codec().encode(d.wantType,g)),d.sendDontHave!=null&&d.sendDontHave!==!1&&(g.uint32(40),g.bool(d.sendDontHave)),m.lengthDelimited!==!1&&g.ldelim()},(d,g)=>{let m={block:new Uint8Array(0),priority:0,cancel:!1,wantType:u.Block,sendDontHave:!1},v=g==null?d.len:d.pos+g;for(;d.pos<v;){let k=d.uint32();switch(k>>>3){case 1:m.block=d.bytes();break;case 2:m.priority=d.int32();break;case 3:m.cancel=d.bool();break;case 4:m.wantType=r.Wantlist.WantType.codec().decode(d);break;case 5:m.sendDontHave=d.bool();break;default:d.skipType(k&7);break}}return m})),p),f.encode=d=>vt(d,f.codec()),f.decode=d=>yt(d,f.codec())})(l=a.Entry||(a.Entry={}));let h;a.codec=()=>(h==null&&(h=_t((f,p,d={})=>{if(d.lengthDelimited!==!1&&p.fork(),f.entries!=null)for(let g of f.entries)p.uint32(10),r.Wantlist.Entry.codec().encode(g,p);f.full!=null&&f.full!==!1&&(p.uint32(16),p.bool(f.full)),d.lengthDelimited!==!1&&p.ldelim()},(f,p)=>{let d={entries:[],full:!1},g=p==null?f.len:f.pos+p;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:d.entries.push(r.Wantlist.Entry.codec().decode(f,f.uint32()));break;case 2:d.full=f.bool();break;default:f.skipType(m&7);break}}return d})),h),a.encode=f=>vt(f,a.codec()),a.decode=f=>yt(f,a.codec())})(t=r.Wantlist||(r.Wantlist={}));let e;(function(a){let u;a.codec=()=>(u==null&&(u=_t((c,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),c.prefix!=null&&c.prefix.byteLength>0&&(l.uint32(10),l.bytes(c.prefix)),c.data!=null&&c.data.byteLength>0&&(l.uint32(18),l.bytes(c.data)),h.lengthDelimited!==!1&&l.ldelim()},(c,l)=>{let h={prefix:new Uint8Array(0),data:new Uint8Array(0)},f=l==null?c.len:c.pos+l;for(;c.pos<f;){let p=c.uint32();switch(p>>>3){case 1:h.prefix=c.bytes();break;case 2:h.data=c.bytes();break;default:c.skipType(p&7);break}}return h})),u),a.encode=c=>vt(c,a.codec()),a.decode=c=>yt(c,a.codec())})(e=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let s;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(s||(s={})),function(a){a.codec=()=>ve(s)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){let u;a.codec=()=>(u==null&&(u=_t((c,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),c.cid!=null&&c.cid.byteLength>0&&(l.uint32(10),l.bytes(c.cid)),c.type!=null&&s[c.type]!==0&&(l.uint32(16),r.BlockPresenceType.codec().encode(c.type,l)),h.lengthDelimited!==!1&&l.ldelim()},(c,l)=>{let h={cid:new Uint8Array(0),type:n.Have},f=l==null?c.len:c.pos+l;for(;c.pos<f;){let p=c.uint32();switch(p>>>3){case 1:h.cid=c.bytes();break;case 2:h.type=r.BlockPresenceType.codec().decode(c);break;default:c.skipType(p&7);break}}return h})),u),a.encode=c=>vt(c,a.codec()),a.decode=c=>yt(c,a.codec())})(i=r.BlockPresence||(r.BlockPresence={}));let o;r.codec=()=>(o==null&&(o=_t((a,u,c={})=>{if(c.lengthDelimited!==!1&&u.fork(),a.wantlist!=null&&(u.uint32(10),r.Wantlist.codec().encode(a.wantlist,u)),a.blocks!=null)for(let l of a.blocks)u.uint32(18),u.bytes(l);if(a.payload!=null)for(let l of a.payload)u.uint32(26),r.Block.codec().encode(l,u);if(a.blockPresences!=null)for(let l of a.blockPresences)u.uint32(34),r.BlockPresence.codec().encode(l,u);a.pendingBytes!=null&&a.pendingBytes!==0&&(u.uint32(40),u.int32(a.pendingBytes)),c.lengthDelimited!==!1&&u.ldelim()},(a,u)=>{let c={blocks:[],payload:[],blockPresences:[],pendingBytes:0},l=u==null?a.len:a.pos+u;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:c.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:c.blocks.push(a.bytes());break;case 3:c.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:c.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:c.pendingBytes=a.int32();break;default:a.skipType(h&7);break}}return c})),o),r.encode=a=>vt(a,r.codec()),r.decode=a=>yt(a,r.codec())})(O||(O={}));var R=class r{static Entry=lt;static WantType={Block:O.Wantlist.WantType.Block,Have:O.Wantlist.WantType.Have};static BlockPresenceType={Have:O.BlockPresenceType.Have,DontHave:O.BlockPresenceType.DontHave};static deserialize=async(t,e)=>{let n=O.decode(t),s=n.wantlist?.full===!0,i=new r(s);return n.wantlist?.entries.forEach(o=>{if(o.block==null)return;let a=A.decode(o.block);i.addEntry(a,o.priority??0,o.wantType,!!o.cancel,!!o.sendDontHave)}),n.blockPresences.forEach(o=>{if(o.cid==null)return;let a=A.decode(o.cid);o.type===r.BlockPresenceType.Have?i.addHave(a):i.addDontHave(a)}),n.blocks.length>0?(await Promise.all(n.blocks.map(async o=>{let a=await jt.digest(o),u=A.createV0(a);i.addBlock(u,o)})),i):(n.payload.length>0&&(await Promise.all(n.payload.map(async o=>{if(o.prefix==null||o.data==null)return;let a=(0,Ms.default)(o.prefix),u=a[0],c=a[1],l=a[2],h=l===jt.code?jt:await e?.getHasher(l);if(h==null)throw new rt("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let f=await h.digest(o.data),p=A.create(u,c,f);i.addBlock(p,o.data)})),i.setPendingBytes(n.pendingBytes)),i)};static blockPresenceSize=t=>t.bytes.length+1;full;wantlist;blocks;blockPresences;pendingBytes;constructor(t){this.full=t,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(t,e,n,s,i){n==null&&(n=r.WantType.Block);let o=t.toString(w),a=this.wantlist.get(o);a!=null?(a.wantType===n&&(a.priority=e),s===!0&&(a.cancel=!!s),i===!0&&(a.sendDontHave=!!i),n===r.WantType.Block&&a.wantType===r.WantType.Have&&(a.wantType=n)):this.wantlist.set(o,new lt(t,e,n,s,i))}addBlock(t,e){let n=t.toString(w);this.blocks.set(n,e)}addHave(t){let e=t.toString(w);this.blockPresences.has(e)||this.blockPresences.set(e,r.BlockPresenceType.Have)}addDontHave(t){let e=t.toString(w);this.blockPresences.has(e)||this.blockPresences.set(e,r.BlockPresenceType.DontHave)}cancel(t){let e=t.toString(w);this.wantlist.delete(e),this.addEntry(t,0,r.WantType.Block,!0,!1)}setPendingBytes(t){this.pendingBytes=t}serializeToBitswap100(){return O.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),cancel:!!t.cancel,wantType:O.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}serializeToBitswap110(){let t={wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),wantType:e.wantType,cancel:!!e.cancel,sendDontHave:!!e.sendDontHave})),full:!!this.full},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[e,n]of this.blocks.entries()){let s=A.parse(e),i=s.version,o=s.code,a=s.multihash.code,u=s.multihash.digest.length,c=_s([i,o,a,u]);t.payload.push({prefix:c,data:n})}for(let[e,n]of this.blockPresences)t.blockPresences.push({cid:A.parse(e).bytes,type:n});return this.pendingBytes>0&&(t.pendingBytes=this.pendingBytes),O.encode(t)}equals(t){return!(this.full!==t.full||this.pendingBytes!==t.pendingBytes||!me(this.wantlist,t.wantlist)||!me(this.blocks,t.blocks)||!me(this.blockPresences,t.blockPresences))}get[Symbol.toStringTag](){let t=Array.from(this.wantlist.keys()),e=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${t}, blocks: ${e}>`}};var Rs={Block:O.Wantlist.WantType.Block,Have:O.Wantlist.WantType.Have},Cc=(r,t)=>Array.prototype.slice.call(t,0).sort((e,n)=>{let s=r(e),i=r(n);return s<i?-1:s>i?1:0}),dt=class{static Entry=wt;set;_stats;constructor(t,e){this.set=e!=null?ct({name:"ipfs_bitswap_wantlist",metrics:e.metrics}):new Map,this._stats=t}get length(){return this.set.size}add(t,e,n){let s=t.toString(w),i=this.set.get(s);i!=null?(i.inc(),i.priority=e,i.wantType===Rs.Have&&n===Rs.Block&&(i.wantType=n)):(this.set.set(s,new wt(t,e,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(t){let e=t.toString(w),n=this.set.get(e);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(e),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(t){this.set.has(t)&&this.set.delete(t)}forEach(t){this.set.forEach(t)}entries(){return this.set.entries()}sortedEntries(){return new Map(Cc(t=>t[1].key,Array.from(this.set.entries())))}contains(t){let e=t.toString(w);return this.set.has(e)}get(t){let e=t.toString(w);return this.set.get(e)}};var _e=class{partner;wantlist;exchangeCount;accounting;lastExchange;constructor(t){this.partner=t,this.wantlist=new dt,this.exchangeCount=0,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=t}wants(t,e,n){this.wantlist.add(t,e,n)}cancelWant(t){this.wantlist.remove(t)}wantlistContains(t){return this.wantlist.get(t)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var Yt=class extends Map{_cmp;_keys;constructor(t,e){super(),this._cmp=e??this._defaultSort,this._keys=[];for(let[n,s]of t??[])this.set(n,s)}update(t){if(t<0||t>=this._keys.length)return;let e=this._keys[t];this._keys.splice(t,1);let n=this._find(e);this._keys.splice(n,0,e)}set(t,e){if(this.has(t)){let s=this.indexOf(t);this._keys.splice(s,1)}super.set(t,e);let n=this._find(t);return this._keys.splice(n,0,t),this}clear(){super.clear(),this._keys=[]}delete(t){if(!this.has(t))return!1;let e=this.indexOf(t);return this._keys.splice(e,1),super.delete(t)}indexOf(t){if(!this.has(t))return-1;let e=this._find(t);if(this._keys[e]===t)return e;for(let n=1;n<this._keys.length;n++){if(this._keys[e+n]===t)return e+n;if(this._keys[e-n]===t)return e-n}return-1}_find(t){let e=0,n=this._keys.length;for(;e<n;){let s=e+n>>>1,i=this._kCmp(this._keys[s],t);if(i<0)e=s+1;else if(i>0)n=s;else return s}return e}*keys(){for(let t of this._keys)yield t}*values(){for(let t of this._keys)yield this.get(t)}*entries(){for(let t of this._keys)yield[t,this.get(t)]}*[Symbol.iterator](){yield*this.entries()}forEach(t,e=this){if(t!=null)for(let n of this._keys){let s=this.get(n);if(s==null)throw new Error("Value cannot be undefined");t.apply(e,[[n,s]])}}_defaultSort(t,e){return t[0]<e[0]?-1:e[0]<t[0]?1:0}_kCmp(t,e){return this._cmp([t,this.get(t)],[e,this.get(e)])}};var Ic={hasNewInfo(){return!1},merge(){}},Ee=class{_taskMerger;_byPeer;constructor(t=Ic){this._taskMerger=t,this._byPeer=new Yt([],ke.compare)}pushTasks(t,e){let n=this._byPeer.get(t.toString());n==null&&(n=new ke(t,this._taskMerger)),n.pushTasks(e),this._byPeer.set(t.toString(),n)}popTasks(t){let e=this._head();if(e===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:s}=e.popTasks(t);if(n.length===0)return{tasks:n,pendingSize:s};let i=e.peerId;return e.isIdle()?this._byPeer.delete(i.toString()):this._byPeer.update(0),{peerId:i,tasks:n,pendingSize:s}}_head(){if(this._byPeer.size!==0)for(let[,t]of this._byPeer)return t}remove(t,e){this._byPeer.get(e.toString())?.remove(t)}tasksDone(t,e){let n=this._byPeer.get(t.toString());if(n==null)return;let s=this._byPeer.indexOf(t.toString());for(let i of e)n.taskDone(i);this._byPeer.update(s)}},ke=class{peerId;_taskMerger;_activeTotalSize;_pending;_active;constructor(t,e){this.peerId=t,this._taskMerger=e,this._activeTotalSize=0,this._pending=new Xr,this._active=new Set}pushTasks(t){for(let e of t)this._pushTask(e)}_pushTask(t){if(!this._taskHasMoreInfoThanActiveTasks(t))return;let e=this._pending.get(t.topic);if(e!=null){t.priority>e.priority&&this._pending.updatePriority(t.topic,t.priority),this._taskMerger.merge(t,e);return}this._pending.add(t)}_taskHasMoreInfoThanActiveTasks(t){let e=[];for(let n of this._active)n.topic===t.topic&&e.push(n);return e.length===0?!0:this._taskMerger.hasNewInfo(t,e)}popTasks(t){let e=0,n=[],s=this._pending.tasks();for(let i=0;i<s.length&&e<t;i++){let o=s[i];n.push(o),e+=o.size,this._pending.delete(o.topic),this._activeTotalSize+=o.size,this._active.add(o)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(t){this._active.has(t)&&(this._activeTotalSize-=t.size,this._active.delete(t))}remove(t){this._pending.delete(t)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(t,e){return t[1]._pending.length===0?1:e[1]._pending.length===0?-1:t[1]._activeTotalSize===e[1]._activeTotalSize?e[1]._pending.length-t[1]._pending.length:t[1]._activeTotalSize-e[1]._activeTotalSize}},Xr=class{_tasks;constructor(){this._tasks=new Yt([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((t,e)=>t+e.task.size,0)}get(t){return this._tasks?.get(t)?.task}add(t){this._tasks.set(t.topic,{created:Date.now(),task:t})}delete(t){this._tasks.delete(t)}tasks(){return[...this._tasks.values()].map(t=>t.task)}updatePriority(t,e){let n=this._tasks.get(t);if(n==null)return;let s=this._tasks.indexOf(t);n.task.priority=e,this._tasks.update(s)}_compare(t,e){return t[1].task.priority===e[1].task.priority?t[1].created-e[1].created:e[1].task.priority-t[1].task.priority}};var Us={hasNewInfo(r,t){let e=!1,n=!1;for(let s of t)s.data.haveBlock&&(e=!0),s.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!e&&r.data.haveBlock)},merge(r,t){let e=r.data,n=t.data;!n.haveBlock&&e.haveBlock&&(n.haveBlock=e.haveBlock,n.blockSize=e.blockSize),!n.isWantBlock&&e.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||e.haveBlock)&&(n.haveBlock=e.haveBlock,t.size=r.size)),n.isWantBlock&&n.haveBlock&&(t.size=n.blockSize)}};var Os=R.WantType,Lc=16*1024,Fc=1024,Se=class{_log;blockstore;network;_stats;_opts;ledgerMap;_running;_requestQueue;constructor(t,e,n,s,i,o={}){this._log=J(t,"engine"),this.blockstore=e,this.network=n,this._stats=s,this._opts=this._processOpts(o),this.ledgerMap=ct({name:"ipfs_bitswap_ledger_map",metrics:i.metrics}),this._running=!1,this._requestQueue=new Ee(Us)}_processOpts(t){return{maxSizeReplaceHasWithBlock:Fc,targetMessageSize:Lc,...t}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(t=>{this._log.error("error processing stats",t)})})}async _processTasks(){if(!this._running)return;let{peerId:t,tasks:e,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(e.length===0)return;let s=new R(!1);s.setPendingBytes(n);let i=[],o=new Map;for(let u of e){let c=A.parse(u.topic);u.data.haveBlock?u.data.isWantBlock?(i.push(c),o.set(u.topic,u.data)):s.addHave(c):s.addDontHave(c)}let a=await this._getBlocks(i);for(let[u,c]of o){let l=A.parse(u),h=a.get(u);h!=null?s.addBlock(l,h):c.sendDontHave&&s.addDontHave(l)}if(s.empty){t!=null&&this._requestQueue.tasksDone(t,e),this._scheduleProcessTasks();return}try{t!=null&&await this.network.sendMessage(t,s);for(let[u,c]of a.entries())t!=null&&this.messageSent(t,A.parse(u),c)}catch(u){this._log.error(u)}t!=null&&this._requestQueue.tasksDone(t,e),this._scheduleProcessTasks()}wantlistForPeer(t){let e=t.toString(),n=this.ledgerMap.get(e);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(t){let e=t.toString(),n=this.ledgerMap.get(e);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(t=>t.partner)}receivedBlocks(t){if(t.length!==0){for(let e of this.ledgerMap.values())for(let{cid:n,block:s}of t){let i=e.wantlistContains(n);if(i==null)continue;let o=s.length,a=this._sendAsBlock(i.wantType,o),u=o;a||(u=R.blockPresenceSize(i.cid)),this._requestQueue.pushTasks(e.partner,[{topic:i.cid.toString(w),priority:i.priority,size:u,data:{blockSize:o,isWantBlock:a,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(t,e){let n=this._findOrCreate(t);if(e.empty)return;if(e.full&&(n.wantlist=new dt),this._updateBlockAccounting(e.blocks,n),e.wantlist.size===0){this._scheduleProcessTasks();return}let s=[],i=[];e.wantlist.forEach(o=>{o.cancel?(n.cancelWant(o.cid),s.push(o.cid)):(n.wants(o.cid,o.priority,o.wantType),i.push(o))}),this._cancelWants(t,s),await this._addWants(t,i),this._scheduleProcessTasks()}_cancelWants(t,e){for(let n of e)this._requestQueue.remove(n.toString(w),t)}async _addWants(t,e){let n=await this._getBlockSizes(e.map(i=>i.cid)),s=[];for(let i of e){let o=i.cid.toString(w),a=n.get(o);if(a==null)i.sendDontHave&&s.push({topic:o,priority:i.priority,size:R.blockPresenceSize(i.cid),data:{isWantBlock:i.wantType===Os.Block,blockSize:0,haveBlock:!1,sendDontHave:i.sendDontHave}});else{let u=this._sendAsBlock(i.wantType,a),c=a;u||(c=R.blockPresenceSize(i.cid)),s.push({topic:o,priority:i.priority,size:c,data:{isWantBlock:u,blockSize:a,haveBlock:!0,sendDontHave:i.sendDontHave}})}this._requestQueue.pushTasks(t,s)}}_sendAsBlock(t,e){return t===Os.Block||e<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(t){let e=await this._getBlocks(t);return new Map([...e].map(([n,s])=>[n,s.length]))}async _getBlocks(t){let e=new Map;return await Promise.all(t.map(async n=>{try{let s=await this.blockstore.get(n);e.set(n.toString(w),s)}catch(s){s.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,s)}})),e}_updateBlockAccounting(t,e){for(let n of t.values())this._log("got block (%s bytes)",n.length),e.receivedBytes(n.length)}messageSent(t,e,n){let s=this._findOrCreate(t);s.sentBytes(n.length),s.wantlist.remove(e)}numBytesSentTo(t){return this._findOrCreate(t).accounting.bytesSent}numBytesReceivedFrom(t){return this._findOrCreate(t).accounting.bytesRecv}peerDisconnected(t){this.ledgerMap.delete(t.toString())}_findOrCreate(t){let e=t.toString(),n=this.ledgerMap.get(e);if(n!=null)return n;let s=new _e(t);return this.ledgerMap.set(e,s),this._stats!=null&&this._stats.push(e,"peerCount",1),s}start(){this._running=!0}stop(){this._running=!1}};function Pc(r){return r[Symbol.asyncIterator]!=null}function Dc(r){if(Pc(r))return(async()=>{for await(let t of r);})();for(let t of r);}var zs=Dc;function K(r,t){t==null&&(t=r.reduce((s,i)=>s+i.length,0));let e=B(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}var qs=Symbol.for("@achingbrain/uint8arraylist");function $s(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function Ae(r){return!!r?.[qs]}var Nt=class r{bufs;length;[qs]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Ae(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Ae(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=$s(this.bufs,t);return e.buf[e.index]}set(t,e){let n=$s(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Ae(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return K(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:K(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),i=new r;return i.length=s,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=s,u=a+o.byteLength;if(s=u,t>=u)continue;let c=t>=a&&t<u,l=e>a&&e<=u;if(c&&l){if(t===a&&e===u){n.push(o);break}let h=t-a;n.push(o.subarray(h,h+(e-t)));break}if(c){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(l){if(e===u){n.push(o);break}n.push(o.subarray(0,e-a));break}n.push(o)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Ae(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let h=0;h<i;h++)o[h]=-1;for(let h=0;h<s;h++)o[n[h]]=h;let a=o,u=this.byteLength-n.byteLength,c=n.byteLength-1,l;for(let h=e;h<=u;h+=l){l=0;for(let f=c;f>=0;f--){let p=this.get(h+f);if(n[f]!==p){l=Math.max(1,f-a[p]);break}}if(l===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=B(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=it(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=it(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=it(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=B(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=it(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=it(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=it(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=it(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=it(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Dt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,i)=>s+i.byteLength,0)),n.length=e,n}};function Te(r){return r[Symbol.asyncIterator]!=null}var Ce=r=>{let t=F(r),e=B(t);return ht(r,e),Ce.bytes=t,e};Ce.bytes=0;function Ie(r,t){t=t??{};let e=t.lengthEncoder??Ce;function*n(s){let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Te(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}Ie.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Ce;return new Nt(e(r.byteLength),r)};var Mt=et(Hs(),1);var Nc=8,Mc=1024*1024*4,Et;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Et||(Et={}));var Jr=r=>{let t=ot(r);return Jr.bytes=F(t),t};Jr.bytes=0;function te(r,t){let e=new Nt,n=Et.LENGTH,s=-1,i=t?.lengthDecoder??Jr,o=t?.maxLengthLength??Nc,a=t?.maxDataLength??Mc;function*u(){for(;e.byteLength>0;){if(n===Et.LENGTH)try{if(s=i(e),s<0)throw(0,Mt.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>a)throw(0,Mt.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let c=i.bytes;e.consume(c),t?.onLength!=null&&t.onLength(s),n=Et.DATA}catch(c){if(c instanceof RangeError){if(e.byteLength>o)throw(0,Mt.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw c}if(n===Et.DATA){if(e.byteLength<s)break;let c=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(c),yield c,n=Et.LENGTH}}}return Te(r)?async function*(){for await(let c of r)e.append(c),yield*u();if(e.byteLength>0)throw(0,Mt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let c of r)e.append(c),yield*u();if(e.byteLength>0)throw(0,Mt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}te.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:i,value:o}=await r.next(e);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{e=1}}();return te(n,{...t??{},onLength:i=>{e=i}})};function Uc(r){return r[Symbol.asyncIterator]!=null}function Oc(r,t){if(Uc(r))return async function*(){for await(let a of r)yield t(a)}();let e=ce(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let i=t(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let a of e)yield t(a)}();let o=t;return function*(){yield i;for(let a of e)yield o(a)}()}var Gs=Oc;function pt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Le=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Rt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Le(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Le(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Kr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ut(r={}){return zc(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function zc(r,t){t=t??{};let e=t.onEnd,n=new Rt,s,i,o,a=pt(),u=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((m,v)=>{i=k=>{i=null,n.push(k);try{m(r(n))}catch(C){v(C)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pt()})}},c=m=>i!=null?i(m):(n.push(m),s),l=m=>(n=new Rt,i!=null?i({error:m}):(n.push({error:m}),s)),h=m=>{if(o)return s;if(t?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:m})},f=m=>o?s:(o=!0,m!=null?l(m):c({done:!0})),p=()=>(n=new Rt,f(),{done:!0}),d=m=>(f(m),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:u,return:p,throw:d,push:h,end:f,get readableLength(){return n.size},onEmpty:async m=>{let v=m?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let k,C;v!=null&&(k=new Promise((L,z)=>{C=()=>{z(new Kr)},v.addEventListener("abort",C)}));try{await Promise.race([a.promise,k])}finally{C!=null&&v!=null&&v?.removeEventListener("abort",C)}}},e==null)return s;let g=s;return s={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(m){return g.throw(m),e!=null&&(e(m),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(m){return g.end(m),e!=null&&(e(m),e=void 0),s},get readableLength(){return g.readableLength},onEmpty:m=>g.onEmpty(m)},s}function $c(r){return r[Symbol.asyncIterator]!=null}function qc(...r){let t=[];for(let e of r)$c(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Ut({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)e.push(s)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var js=qc;function Yr(r,...t){if(r==null)throw new Error("Empty pipeline");if(Zr(r)){let n=r;r=()=>n.source}else if(Xs(r)||Qs(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Zr(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Zr(e[n])&&(e[n]=Wc(e[n]));return Vc(...e)}var Vc=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Qs=r=>r?.[Symbol.asyncIterator]!=null,Xs=r=>r?.[Symbol.iterator]!=null,Zr=r=>r==null?!1:r.sink!=null&&r.source!=null,Wc=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ut({objectMode:!0});e.then(()=>{n.end()},o=>{n.end(o)});let s,i=r.source;if(Qs(i))s=async function*(){yield*i,n.end()};else if(Xs(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return js(n,s())}return r.source};function Hc(r){return r[Symbol.asyncIterator]!=null}function Gc(r,t){return Hc(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var Js=Gc;var tt=class extends Event{constructor(t,e){super(t),this.detail=e}};var ci=et(ni(),1);var si=Math.pow(2,31)-1,ii=1e3,oi=1;var rn="/ipfs/bitswap/1.0.0",nn="/ipfs/bitswap/1.1.0",sn="/ipfs/bitswap/1.2.0",Xc=1024,Jc=1024,Kc=3e4,Pe=class{_log;_libp2p;_bitswap;_protocols;_stats;_running;_hashLoader;_maxInboundStreams;_maxOutboundStreams;_incomingStreamTimeout;_registrarIds;constructor(t,e,n,s={}){this._log=J(t.peerId,"network"),this._libp2p=t,this._bitswap=e,this._protocols=[rn],s.b100Only!==!0&&(this._protocols.unshift(nn),this._protocols.unshift(sn)),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=s.hashLoader??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=s.maxInboundStreams??Xc,this._maxOutboundStreams=s.maxOutboundStreams??Jc,this._incomingStreamTimeout=s.incomingStreamTimeout??Kc}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let t={onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect};this._registrarIds=[];for(let e of this._protocols)this._registrarIds.push(await this._libp2p.register(e,t));this._libp2p.getConnections().forEach(e=>{this._onPeerConnect(e.remotePeer)})}async stop(){if(this._running=!1,await this._libp2p.unhandle(this._protocols),this._registrarIds!=null){for(let t of this._registrarIds)this._libp2p.unregister(t);this._registrarIds=[]}}_onConnection(t){if(!this._running)return;let{stream:e,connection:n}=t,s=new ci.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",e.protocol,n.remotePeer);let i=()=>{e.abort(new rt("Incoming Bitswap stream timed out","ERR_TIMEOUT"))},o=AbortSignal.timeout(this._incomingStreamTimeout);o.addEventListener("abort",i),await Yr(e,a=>te(a),async a=>{for await(let u of a){try{let c=await R.deserialize(u.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,c)}catch(c){this._bitswap._receiveError(c);break}o.removeEventListener("abort",i),o=AbortSignal.timeout(this._incomingStreamTimeout),o.addEventListener("abort",i)}}),await e.close({signal:o})}).catch(i=>{this._log(i),e.abort(i)}).finally(()=>{s.clear()})}_onPeerConnect(t){this._bitswap._onPeerConnected(t)}_onPeerDisconnect(t){this._bitswap._onPeerDisconnected(t)}findProviders(t,e={}){return e.onProgress?.(new tt("bitswap:network:find-providers",t)),this._libp2p.contentRouting.findProviders(t,e)}async findAndConnect(t,e){await zs(Js(Gs(this.findProviders(t,e),async n=>this.connectTo(n.id,e).catch(s=>{this._log.error(s)})),3)).catch(n=>{this._log.error(n)})}async provide(t,e={}){e.onProgress?.(new tt("bitswap:network:provide",t)),await this._libp2p.contentRouting.provide(t,e)}async sendMessage(t,e,n={}){if(!this._running)throw new Error("network isn't running");let s=t.toString();this._log("sendMessage to %s",s,e),n.onProgress?.(new tt("bitswap:network:send-wantlist",t)),await this._writeMessage(t,e,n),this._updateSentStats(t,e.blocks)}async connectTo(t,e={}){if(!this._running)throw new Error("network isn't running");return e.onProgress?.(new tt("bitswap:network:dial",t)),this._libp2p.dial(t,e)}_updateSentStats(t,e){let n=t.toString();if(this._stats!=null){for(let s of e.values())this._stats.push(n,"dataSent",s.length);this._stats.push(n,"blocksSent",e.size)}}async _writeMessage(t,e,n={}){let s=await this._libp2p.dialProtocol(t,[sn,nn,rn]);try{let i;switch(s.protocol){case rn:i=e.serializeToBitswap100();break;case nn:case sn:i=e.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${s.protocol}`)}await Yr([i],o=>Ie(o),s),await s.close()}catch(i){n.onProgress?.(new tt("bitswap:network:send-wantlist:error",{peer:t,error:i})),this._log(i),s.abort(i)}}};var vi=et(Ne(),1);function P(r,t="utf8"){let e=be[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var yi=r=>`unwant:${P(r.multihash.bytes,"base64")}`,xi=r=>`block:${P(r.multihash.bytes,"base64")}`,Me=class extends vi.EventEmitter{_log;constructor(t){super(),this.setMaxListeners(ii),this._log=J(t,"notif")}hasBlock(t,e){let n=xi(t);this._log(n),this.emit(n,e)}async wantBlock(t,e={}){if(t==null)throw new Error("Not a valid cid");let n=xi(t),s=yi(t);return this._log(`wantBlock:${t}`),new Promise((i,o)=>{let a=()=>{this.removeListener(n,u),e.onProgress?.(new tt("bitswap:want-block:unwant",t)),o(new Error(`Block for ${t} unwanted`))},u=c=>{this.removeListener(s,a),e.onProgress?.(new tt("bitswap:want-block:block",t)),i(c)};this.once(s,a),this.once(n,u),e.signal?.addEventListener("abort",()=>{this.removeListener(n,u),this.removeListener(s,a),o(new Error(`Want for ${t} aborted`))})})}unwantBlock(t){let e=yi(t);this._log(e),this.emit(e)}};var Ti=et(Ne(),1);var Si=et(Ne(),1),an=et(ki(),1),ee=class extends Si.EventEmitter{_options;_queue;_stats;_frequencyLastTime;_frequencyAccumulators;_movingAverages;_enabled;_timeout;constructor(t,e){super(),this._options=e,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),t.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(s=>{(this._movingAverages[n][s]=(0,an.default)(s)).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(t,e){this._enabled&&(this._queue.push([t,e,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout!=null&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let t=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-t),0)}_update(){if(this._timeout=void 0,this._queue.length>0){let t;for(;this._queue.length>0;){let e=t=this._queue.shift();e!=null&&this._applyOp(e)}t!=null&&this._updateFrequency(t[2]),this.emit("update",this._stats)}}_updateFrequency(t){let e=t-this._frequencyLastTime;e>0&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,e,t)}),this._frequencyLastTime=t}_updateFrequencyFor(t,e,n){let s=this._frequencyAccumulators[t]??0;this._frequencyAccumulators[t]=0;let i=s/e*1e3,o=this._movingAverages[t];o==null&&(o=this._movingAverages[t]={}),this._options.movingAverageIntervals.forEach(a=>{let u=o[a];u==null&&(u=o[a]=(0,an.default)(a)),u.push(n,i)})}_applyOp(t){let e=t[0],n=t[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,e)||(this._stats[e]=BigInt(0)),this._stats[e]=BigInt(this._stats[e])+BigInt(n),this._frequencyAccumulators[e]==null&&(this._frequencyAccumulators[e]=0),this._frequencyAccumulators[e]+=n}};var Ai={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},Re=class extends Ti.EventEmitter{_initialCounters;_options;_enabled;_global;_peers;constructor(t,e=[],n=Ai){super();let s=Object.assign({},Ai,n);if(typeof s.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof s.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=e,this._options=s,this._enabled=this._options.enabled,this._global=new ee(e,s),this._global.on("update",i=>this.emit("update",i)),this._peers=ct({name:"ipfs_bitswap_stats_peers",metrics:t.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 t of this._peers)t[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(t){let e=t.toString();return this._peers.get(e)}push(t,e,n){if(this._enabled&&(this._global.push(e,n),t!=null)){let s=this._peers.get(t);s==null&&(s=new ee(this._initialCounters,this._options),this._peers.set(t,s)),s.push(e,n)}}disconnected(t){let e=t.toString(),n=this._peers.get(e);n!=null&&(n.stop(),this._peers.delete(e))}};var Ci=iu;function iu(r,t,e){var n=null,s=null,i=function(){n&&(clearTimeout(n),s=null,n=null)},o=function(){var u=s;i(),u&&u()},a=function(){if(!t)return r.apply(this,arguments);var u=this,c=arguments,l=e&&!n;if(i(),s=function(){r.apply(u,c)},n=setTimeout(function(){if(n=null,!l){var h=s;return s=null,h()}},t),l)return s()};return a.cancel=i,a.flush=o,a}var Ue=class{peerId;refcnt;network;_entries;_log;constructor(t,e,n){this.peerId=e,this.network=n,this.refcnt=1,this._entries=[],this._log=J(t,"msgqueue"),this.sendEntries=Ci(this.sendEntries.bind(this),oi)}addMessage(t,e={}){t.empty||this.send(t,e)}addEntries(t,e={}){this._entries=this._entries.concat(t),this.sendEntries(e)}sendEntries(t={}){if(this._entries.length===0)return;let e=new R(!1);this._entries.forEach(n=>{n.cancel===!0?e.cancel(n.cid):e.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(e,t)}async send(t,e={}){try{await this.network.connectTo(this.peerId,e)}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,t,e).catch(n=>{this._log.error("send error",n)})}};var Oe=class{peers;wantlist;network;_peerId;_log;constructor(t,e,n,s){this.peers=ct({name:"ipfs_bitswap_want_manager_peers",metrics:s.metrics}),this.wantlist=new dt(n,s),this.network=e,this._peerId=t,this._log=J(t,"want")}_addEntries(t,e,n,s={}){let i=t.map((o,a)=>new R.Entry(o,si-a,R.WantType.Block,e));i.forEach(o=>{o.cancel?n===!0?this.wantlist.removeForce(o.cid.toString(w)):this.wantlist.remove(o.cid):(this._log("adding to wantlist"),this.wantlist.add(o.cid,o.priority))});for(let o of this.peers.values())o.addEntries(i,s)}_startPeerHandler(t){let e=this.peers.get(t.toString());if(e!=null){e.refcnt++;return}e=new Ue(this._peerId,t,this.network);let n=new R(!0);for(let s of this.wantlist.entries())n.addEntry(s[1].cid,s[1].priority);return e.addMessage(n),this.peers.set(t.toString(),e),e}_stopPeerHandler(t){let e=this.peers.get(t.toString());e!=null&&(e.refcnt--,!(e.refcnt>0)&&this.peers.delete(t.toString()))}wantBlocks(t,e={}){this._addEntries(t,!1,!1,e),e.signal?.addEventListener("abort",()=>{this.cancelWants(t)})}unwantBlocks(t){this._log("unwant blocks: %s",t.length),this._addEntries(t,!0,!0)}cancelWants(t){this._log("cancel wants: %s",t.length),this._addEntries(t,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(t){this._startPeerHandler(t)}disconnected(t){this._stopPeerHandler(t)}start(){}stop(){this.peers.forEach(t=>{this.disconnected(t.peerId)})}};var ou={async getHasher(){throw new Error("Not implemented")}},au={maxInboundStreams:1024,maxOutboundStreams:1024,incomingStreamTimeout:3e4,hashLoader:ou,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},cu=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],ze=class{_libp2p;_log;stats;network;blockstore;engine;wm;notifications;started;constructor(t,e,n={}){this._libp2p=t,this._log=J(this.peerId),n=Object.assign({},au,n),this.stats=new Re(t,cu,{enabled:n.statsEnabled,computeThrottleTimeout:n.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:n.statsComputeThrottleMaxQueueSize}),this.network=new Pe(t,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=e,this.engine=new Se(this.peerId,e,this.network,this.stats,t),this.wm=new Oe(this.peerId,this.network,this.stats,t),this.notifications=new Me(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(t,e){try{await this.engine.messageReceived(t,e)}catch{this._log("failed to receive message",e)}if(e.blocks.size===0)return;let n=[];for(let[s,i]of e.blocks.entries()){let o=A.parse(s);n.push({wasWanted:this.wm.wantlist.contains(o),cid:o,data:i})}this.wm.cancelWants(n.filter(({wasWanted:s})=>s).map(({cid:s})=>s)),await Promise.all(n.map(async({cid:s,wasWanted:i,data:o})=>{await this._handleReceivedBlock(t,s,o,i)}))}async _handleReceivedBlock(t,e,n,s){this._log("received block");let i=await this.blockstore.has(e);this._updateReceiveCounters(t.toString(),e,n,i),s&&await this.put(e,n)}_updateReceiveCounters(t,e,n,s){this.stats.push(t,"blocksReceived",1),this.stats.push(t,"dataReceived",n.length),s&&(this.stats.push(t,"dupBlksReceived",1),this.stats.push(t,"dupDataReceived",n.length))}_receiveError(t){this._log.error("ReceiveError",t)}_onPeerConnected(t){this.wm.connected(t)}_onPeerDisconnected(t){this.wm.disconnected(t),this.engine.peerDisconnected(t),this.stats.disconnected(t)}enableStats(){this.stats.enable()}disableStats(){this.stats.disable()}wantlistForPeer(t,e){return this.engine.wantlistForPeer(t)}ledgerForPeer(t){return this.engine.ledgerForPeer(t)}async want(t,e={}){let n=async(u,c)=>(this.wm.wantBlocks([u],c),this.notifications.wantBlock(u,c)),s=!1,i=async(u,c)=>{try{return await this.blockstore.get(u,c)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l;return s||(s=!0,this.network.findAndConnect(u,c).catch(h=>{this._log.error(h)})),await n(u,c)}},o=new AbortController,a=Cn([o.signal,e.signal]);try{return await Promise.race([this.notifications.wantBlock(t,{...e,signal:a}),i(t,{...e,signal:a})])}finally{o.abort(),a.clear()}}unwant(t){let e=Array.isArray(t)?t:[t];this.wm.unwantBlocks(e),e.forEach(n=>{this.notifications.unwantBlock(n)})}cancelWants(t){this.wm.cancelWants(Array.isArray(t)?t:[t])}async put(t,e,n){await this.blockstore.put(t,e),this.notify(t,e)}async*putMany(t,e){yield*this.blockstore.putMany(Ln(t,({cid:n,block:s})=>{this.notify(n,s)}),e)}notify(t,e,n={}){this.notifications.hasBlock(t,e),this.engine.receivedBlocks([{cid:t,block:e}]),this.network.provide(t,n).catch(s=>{this._log.error("Failed to provide: %s",s.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 Ii=(r,t,e={})=>new ze(r,t,e);var cn=class{bitswap;started;constructor(t,e={}){let{libp2p:n,blockstore:s,hashers:i}=t;this.bitswap=Ii(n,s,{hashLoader:{getHasher:async o=>{let a;if(typeof o=="string"?a=Object.values(i).find(u=>u.name===o):a=i[o],a!=null)return a;throw new Error(`Could not load hasher for code/name "${o}"`)}},...e}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e,n){this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}};function Li(r={}){return t=>new cn(t,r)}var un=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function $e(r,t,e,n){let s=new un(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{let a=c=>{try{if(n?.filter?.(c)===!1)return}catch(l){r.removeEventListener(t,a),e?.removeEventListener("abort",u),o(l);return}r.removeEventListener(t,a),e?.removeEventListener("abort",u),i(c)},u=()=>{r.removeEventListener(t,a),e?.removeEventListener("abort",u),o(s)};r.addEventListener(t,a),e?.addEventListener("abort",u)})}var qe=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Fi(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new qe(e?.errorMessage,e?.errorCode));let n,s=new qe(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Ve=class{deferred;signal;where;constructor(t,e){this.signal=e,this.deferred=pt(),this.where=t,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new ut)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function uu(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var We=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(t,e,n=0){this.id=uu(),this.status="queued",this.fn=t,this.priority=n,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,he(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&this.controller.abort(new ut)}async join(t={}){let e=new Ve(new Error("where").stack,t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Fi(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.signal?.removeEventListener("abort",this.onAbort)})}};function lu(r,t,e){let n=0,s=r.length;for(;s>0;){let i=Math.trunc(s/2),o=n+i;e(r[o],t)<=0?(n=++o,s-=i+1):s=i}return n}var He=class extends fe{concurrency;queue;pending;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){if(this.queue[this.size-1]?.priority>=t.priority){this.queue.push(t);return}let e=lu(this.queue,t,(n,s)=>s.priority-n.priority);this.queue.splice(e,0,t)}async add(t,e){e?.signal?.throwIfAborted();let n=new We(t,e,e?.priority),s=n.join(e).then(i=>(this.safeDispatchEvent("completed",{detail:i}),i)).catch(i=>{throw this.safeDispatchEvent("error",{detail:i}),i});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new ut)}),this.clear()}async onEmpty(t){this.size!==0&&await $e(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await $e(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await $e(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Ut({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),e.end(u)},s=u=>{u.detail!=null&&e.push(u.detail)},i=u=>{n(u.detail)},o=()=>{n()},a=()=>{n(new rt("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",o),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",o),t?.signal?.removeEventListener("abort",a),n()}}};var Ge=class extends He{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var je=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let i=0,o=0,a=this.peekChar();if(a===void 0)return;let u=a==="0",c=2**(8*s)-1;for(;;){let l=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(l===void 0)break;if(i*=t,i+=l,i>c||(o+=1,e!==void 0&&o>e))return}if(o!==0)return!n&&u&&o>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return e[s]=o[0],e[s+1]=o[1],e[s+2]=o[2],e[s+3]=o[3],[s+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[s,!1];e[s]=i>>8,e[s+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),o=16-(n+2),[a]=t(i.subarray(0,o));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Pi=45,hu=15,zt=new je;function ln(r){if(!(r.length>hu))return zt.new(r).parseWith(()=>zt.readIPv4Addr())}function hn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Pi))return zt.new(r).parseWith(()=>zt.readIPv6Addr())}function Qe(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Pi))return zt.new(r).parseWith(()=>zt.readIPAddr())}function $t(r){return!!ln(r)}function qt(r){return!!hn(r)}function Xe(r){return!!Qe(r)}var Bi=et(Di(),1),fu=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],du=fu.map(r=>new Bi.Netmask(r));function pu(r){for(let t of du)if(t.contains(r))return!0;return!1}function mu(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Ni(r){return $t(r)?pu(r):qt(r)?mu(r):void 0}var Gp=parseInt("0xFFFF",16),jp=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Ui=$t,xu=qt,fn=function(r){let t=0;if(r=r.toString().trim(),Ui(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(xu(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Ui(e[n]),o;i&&(o=fn(e[n]),e[n]=P(o.slice(0,2),"base16")),o!=null&&++n<8&&e.splice(n,0,P(o.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);s[t++]=i>>8&255,s[t++]=i&255}return s}throw new Error("invalid ip address")},Oi=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let s=[];for(let i=0;i<e;i++)s.push(r[t+i]);return s.join(".")}if(e===16){let s=[];for(let i=0;i<e;i+=2)s.push(n.getUint16(t+i).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Vt={},dn={},_u=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];_u.forEach(r=>{let t=Eu(...r);dn[t.code]=t,Vt[t.name]=t});function Eu(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function b(r){if(typeof r=="number"){if(dn[r]!=null)return dn[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Vt[r]!=null)return Vt[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Cm=b("ip4"),Im=b("ip6"),Lm=b("ipcidr");function mn(r,t){switch(b(r).code){case 4:case 41:return Su(t);case 42:return qi(t);case 6:case 273:case 33:case 132:return Wi(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return qi(t);case 421:return Iu(t);case 444:return Vi(t);case 445:return Vi(t);case 466:return Cu(t);default:return P(t,"base16")}}function gn(r,t){switch(b(r).code){case 4:return zi(t);case 41:return zi(t);case 42:return $i(t);case 6:case 273:case 33:case 132:return wn(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return $i(t);case 421:return Au(t);case 444:return Lu(t);case 445:return Fu(t);case 466:return Tu(t);default:return Jt(t,"base16")}}var pn=Object.values(Xt).map(r=>r.decoder),ku=function(){let r=pn[0].or(pn[1]);return pn.slice(2).forEach(t=>r=r.or(t)),r}();function zi(r){if(!Xe(r))throw new Error("invalid ip address");return fn(r)}function Su(r){let t=Oi(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Xe(t))throw new Error("invalid ip address");return t}function wn(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Wi(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function $i(r){let t=Jt(r),e=Uint8Array.from(ht(t.length));return K([e,t],e.length+t.length)}function qi(r){let t=ot(r);if(r=r.slice(F(t)),r.length!==t)throw new Error("inconsistent lengths");return P(r)}function Au(r){let t;r[0]==="Q"||r[0]==="1"?t=le(w.decode(`z${r}`)).bytes:t=A.parse(r).multihash.bytes;let e=Uint8Array.from(ht(t.length));return K([e,t],e.length+t.length)}function Tu(r){let t=ku.decode(r),e=Uint8Array.from(ht(t.length));return K([e,t],e.length+t.length)}function Cu(r){let t=ot(r),e=r.slice(F(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+P(e,"base64url")}function Iu(r){let t=ot(r),e=r.slice(F(t));if(e.length!==t)throw new Error("inconsistent lengths");return P(e,"base58btc")}function Lu(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Z.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=wn(n);return K([e,s],e.length+s.length)}function Fu(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Z.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=wn(n);return K([e,s],e.length+s.length)}function Vi(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=P(t,"base32"),s=Wi(e);return`${n}:${s}`}function Hi(r){r=bn(r);let t=[],e=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<s.length;i++){let o=s[i],a=b(o);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=s.length)throw ji("invalid address: "+r);if(a.path===!0){n=bn(s.slice(i).join("/")),t.push([a.code,gn(a.code,n)]),e.push([a.code,n]);break}let u=gn(a.code,s[i]);t.push([a.code,u]),e.push([a.code,mn(a.code,u)])}return{string:Gi(e),bytes:xn(t),tuples:t,stringTuples:e,path:n}}function yn(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let i=ot(r,s),o=F(i),a=b(i),u=Pu(a,r.slice(s+o));if(u===0){t.push([i]),e.push([i]),s+=o;continue}let c=r.slice(s+o,s+o+u);if(s+=u+o,s>r.length)throw ji("Invalid address Uint8Array: "+P(r,"base16"));t.push([i,c]);let l=mn(i,c);if(e.push([i,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:Gi(e),tuples:t,stringTuples:e,path:n}}function Gi(r){let t=[];return r.map(e=>{let n=b(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),bn(t.join("/"))}function xn(r){return K(r.map(t=>{let e=b(t[0]),n=Uint8Array.from(ht(e.code));return t.length>1&&t[1]!=null&&(n=K([n,t[1]])),n}))}function Pu(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ot(t instanceof Uint8Array?t:Uint8Array.from(t));return e+F(e)}}function bn(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function ji(r){return new Error("Error parsing address: "+r)}var Du=Symbol.for("nodejs.util.inspect.custom"),vn=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Bu=[b("dns").code,b("dns4").code,b("dns6").code,b("dnsaddr").code],Je=class r{bytes;#t;#e;#r;#n;[vn]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=yn(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Hi(t)}else if(Xi(t))e=yn(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,s,i="",o=b("tcp"),a=b("udp"),u=b("ip4"),c=b("ip6"),l=b("dns6"),h=b("ip6zone");for(let[p,d]of this.stringTuples())p===h.code&&(i=`%${d??""}`),Bu.includes(p)&&(e=o.name,s=443,n=`${d??""}${i}`,t=p===l.code?6:4),(p===o.code||p===a.code)&&(e=b(p).name,s=parseInt(d??"")),(p===u.code||p===c.code)&&(e=b(p).name,n=`${d??""}${i}`,t=p===c.code?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}protos(){return this.#e.map(([t])=>Object.assign({},b(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>b(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,s))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(xn(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Vt.p2p.code&&t.push([n,s]),n===Vt["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?P(w.decode(`z${n}`),"base58btc"):P(A.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Dt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Qi.get(e.name);if(n==null)throw new rt(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(i=>ne(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Du](){return`Multiaddr(${this.#t})`}};var Qi=new Map;function Xi(r){return!!r?.[vn]}function ne(r){return new Je(r)}var Nu=r=>r.toString().split("/").slice(1),se=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),y=r=>({match:t=>se(e=>e===r).match(t),pattern:r}),Ye=()=>({match:r=>se(t=>typeof t=="string").match(r),pattern:"{string}"}),tr=()=>({match:r=>se(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),D=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{w.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ke=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{yr.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),U=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),G=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),E=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function T(...r){function t(s){let i=Nu(s);for(let o of r){let a=o.match(i);if(a===!1)return!1;i=a}return i}function e(s){return t(s)!==!1}function n(s){let i=t(s);return i===!1?!1:i.length===0}return{matches:e,exactMatch:n}}var En=E(y("dns4"),Ye()),kn=E(y("dns6"),Ye()),Sn=E(y("dnsaddr"),Ye()),Ji=E(y("dns"),Ye()),ig=T(En),og=T(kn),ag=T(Sn),Ki=T(G(Ji,Sn,En,kn)),Zi=E(y("ip4"),se($t)),Yi=E(y("ip6"),se(qt)),to=G(Zi,Yi),nt=G(to,Ji,En,kn,Sn),cg=T(nt),ug=T(Zi),lg=T(Yi),hg=T(to),er=E(nt,y("tcp"),tr()),ie=E(nt,y("udp"),tr()),Mu=G(er,ie),fg=T(er),dg=T(ie),An=E(ie,y("quic")),rr=E(ie,y("quic-v1")),Ru=G(An,rr),pg=T(An),mg=T(rr),_n=G(nt,er,ie,An,rr),eo=G(E(_n,y("ws"),U(D()))),gg=T(eo),ro=G(E(_n,y("wss"),U(D())),E(_n,y("tls"),y("ws"),U(D()))),wg=T(ro),no=E(Mu,y("webrtc-direct"),Ke(),U(Ke()),U(D())),bg=T(no),so=E(rr,y("webtransport"),Ke(),Ke(),U(D())),yg=T(so),Ze=G(eo,ro,E(er,U(D())),E(Ru,U(D())),E(nt,U(D())),no,so,D()),xg=T(Ze),Uu=E(Ze,y("p2p-circuit"),D()),vg=T(Uu),Ou=G(E(Ze,y("p2p-circuit"),y("webrtc"),D()),E(Ze,y("webrtc"),U(D())),y("webrtc")),_g=T(Ou),zu=G(E(nt,y("tcp"),tr(),y("http"),U(D())),E(nt,y("http"),U(D()))),io=T(zu),$u=G(E(nt,y("tcp"),G(E(y("443"),y("http")),E(tr(),y("https"))),U(D())),E(nt,y("tls"),y("http"),U(D())),E(nt,y("https"),U(D()))),oo=T($u);var qu=[b("tcp").code,b("dns").code,b("dnsaddr").code,b("dns4").code,b("dns6").code];function ao(r){let t;try{t=b("sni").code}catch{return null}for(let[e,n]of r)if(e===t&&n!==void 0)return n;return null}function co(r){return r.some(([t,e])=>t===b("tls").code)}function j(r,t,e){let n=uo[b(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${b(r).name}`);let s=n(t,e);return r===b("ip6").code?`[${s}]`:s}var uo={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${j(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${j(e[0],e[1]??"",t)}:${r}`},dnsaddr:(r,t)=>r,dns4:(r,t)=>r,dns6:(r,t)=>r,dns:(r,t)=>r,ipfs:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${j(e[0],e[1]??"",t)}/ipfs/${r}`},p2p:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${j(e[0],e[1]??"",t)}/p2p/${r}`},http:(r,t)=>{let e=co(t),n=ao(t);if(e&&n!==null)return`https://${n}`;let s=e?"https://":"http://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=j(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},tls:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return j(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return j(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=j(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=co(t),n=ao(t);if(e&&n!==null)return`wss://${n}`;let s=e?"wss://":"ws://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=j(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},wss:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=j(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${j(e[0],e[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${j(e[0],e[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${j(e[0],e[1]??"",t)}/p2p-webrtc-direct`}};function lo(r,t){let n=ne(r).stringTuples(),s=n.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=b(s[0]),o=uo[i.name];if(o==null)throw new Error(`No interpreter found for ${i.name}`);let a=o(s[1]??"",n);return t?.assumeHttp!==!1&&qu.includes(s[0])&&(a=a.replace(/^.*:\/\//,""),s[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var oe=class{url;#t=0;#e=0;#r=0;#n=0;log;constructor(t,e){this.url=t instanceof URL?t:new URL(t),this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}async getRawBlock(t,e){let n=this.url;if(n.pathname=`/ipfs/${t.toString()}`,n.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);try{this.#t++;let s=await fetch(n.toString(),{signal:e,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"});if(this.log("GET %s %d",n,s.status),!s.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await s.arrayBuffer())}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`unable to fetch raw block for CID ${t}`))}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#n/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}};var nr=class r{components;gateways;routing;log;constructor(t,e={}){this.components=t,this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.routing=t.routing,this.gateways=(e.gateways??ho).map(n=>new oe(n,t.logger))}addGateway(t){this.gateways.push(new oe(t,this.components.logger))}async retrieve(t,e={}){let n=this.gateways.sort((i,o)=>o.reliability()-i.reliability()),s=[];for(let i of n){this.log("getting block for %c from %s",t,i.url);try{let o=await i.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,i.url);try{await e.validateFn?.(o)}catch(a){throw this.log.error("failed to validate block for %c from %s",t,i.url,a),i.incrementInvalidBlocks(),new Error(`Block for CID ${t} from gateway ${i.url} failed validation`)}return o}catch(o){if(this.log.error("failed to get block for %c from %s",t,i.url,o),o instanceof Error?s.push(o):s.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${i.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,i.url);break}}}throw s.length>0?new AggregateError(s,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}async createSession(t,e={}){let n=[],s=e.minProviders??1,i=e.minProviders??5,o=pt(),a=new r(this.components,{gateways:n});this.log("finding transport-ipfs-gateway-http providers for cid %c",t);let u=new Ge({concurrency:e.providerQueryConcurrency??5});return Promise.resolve().then(async()=>{for await(let c of this.routing.findProviders(t,e)){let l=c.multiaddrs.filter(h=>oo.matches(h)||e.allowInsecure===!0&&io.matches(h)?e.allowLocal===!0||Ki.matches(h)?!0:Ni(h.toOptions().host)===!1:!1);l.length!==0&&(this.log("found transport-ipfs-gateway-http provider %p for cid %c",c.id,t),u.add(async()=>{for(let h of l){let f;try{f=lo(h);let p=`${f}/ipfs/${t.toString()}?format=raw`,d=await fetch(p,{method:"HEAD",headers:{Accept:"application/vnd.ipld.raw","Cache-Control":e.cacheControl??"only-if-cached"},signal:AbortSignal.timeout(e.providerQueryTimeout??5e3)});this.log("HEAD %s %d",p,d.status),n.push(f),a.addGateway(f),this.log("found %d transport-ipfs-gateway-http providers for cid %c",n.length,t),n.length===s&&o.resolve(a),n.length===i&&u.clear()}catch(p){this.log.error("could not fetch %c from %a",t,f??h,p)}}}))}}).catch(c=>{this.log.error("error creating session for %c",t,c)}),o.promise}};var ho=["https://trustless-gateway.link","https://cloudflare-ipfs.com","https://4everland.io"];function fo(r={}){return t=>new nr(t,r)}return yo(ju);})();
|
|
3
3
|
return HeliaBlockBrokers}));
|
|
@@ -1,14 +1,41 @@
|
|
|
1
1
|
import type { TrustlessGatewayBlockBrokerInit, TrustlessGatewayComponents, TrustlessGatewayGetBlockProgressEvents } from './index.js';
|
|
2
|
-
import type { BlockRetrievalOptions, BlockBroker } from '@helia/interface
|
|
2
|
+
import type { BlockRetrievalOptions, BlockBroker, CreateSessionOptions } from '@helia/interface';
|
|
3
3
|
import type { CID } from 'multiformats/cid';
|
|
4
|
+
export interface CreateTrustlessGatewaySessionOptions extends CreateSessionOptions<TrustlessGatewayGetBlockProgressEvents> {
|
|
5
|
+
/**
|
|
6
|
+
* Specify the cache control header to send to the remote. 'only-if-cached'
|
|
7
|
+
* will prevent the gateway from fetching the content if they don't have it.
|
|
8
|
+
*
|
|
9
|
+
* @default only-if-cached
|
|
10
|
+
*/
|
|
11
|
+
cacheControl?: string;
|
|
12
|
+
/**
|
|
13
|
+
* By default we will only connect to peers with HTTPS addresses, pass true
|
|
14
|
+
* to also connect to HTTP addresses.
|
|
15
|
+
*
|
|
16
|
+
* @default false
|
|
17
|
+
*/
|
|
18
|
+
allowInsecure?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* By default we will only connect to peers with public or DNS addresses, pass
|
|
21
|
+
* true to also connect to private addresses.
|
|
22
|
+
*
|
|
23
|
+
* @default false
|
|
24
|
+
*/
|
|
25
|
+
allowLocal?: boolean;
|
|
26
|
+
}
|
|
4
27
|
/**
|
|
5
28
|
* A class that accepts a list of trustless gateways that are queried
|
|
6
29
|
* for blocks.
|
|
7
30
|
*/
|
|
8
31
|
export declare class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGatewayGetBlockProgressEvents> {
|
|
32
|
+
private readonly components;
|
|
9
33
|
private readonly gateways;
|
|
34
|
+
private readonly routing;
|
|
10
35
|
private readonly log;
|
|
11
36
|
constructor(components: TrustlessGatewayComponents, init?: TrustlessGatewayBlockBrokerInit);
|
|
37
|
+
addGateway(gatewayOrUrl: string): void;
|
|
12
38
|
retrieve(cid: CID, options?: BlockRetrievalOptions<TrustlessGatewayGetBlockProgressEvents>): Promise<Uint8Array>;
|
|
39
|
+
createSession(root: CID, options?: CreateTrustlessGatewaySessionOptions): Promise<BlockBroker<TrustlessGatewayGetBlockProgressEvents>>;
|
|
13
40
|
}
|
|
14
41
|
//# sourceMappingURL=broker.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broker.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"broker.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,+BAA+B,EAAE,0BAA0B,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAA;AACrI,OAAO,KAAK,EAAW,qBAAqB,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAA;AAEzG,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,MAAM,WAAW,oCAAqC,SAAQ,oBAAoB,CAAC,sCAAsC,CAAC;IACxH;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IAErB;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;AAED;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,WAAW,CAAC,sCAAsC,CAAC;IACrG,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA4B;IACvD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAoB;IAC7C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;gBAEf,UAAU,EAAE,0BAA0B,EAAE,IAAI,GAAE,+BAAoC;IAU/F,UAAU,CAAE,YAAY,EAAE,MAAM,GAAG,IAAI;IAIjC,QAAQ,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,qBAAqB,CAAC,sCAAsC,CAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IA2CrH,aAAa,CAAE,IAAI,EAAE,GAAG,EAAE,OAAO,GAAE,oCAAyC,GAAG,OAAO,CAAC,WAAW,CAAC,sCAAsC,CAAC,CAAC;CA+FlJ"}
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
import { DEFAULT_SESSION_MIN_PROVIDERS, DEFAULT_SESSION_MAX_PROVIDERS, DEFAULT_SESSION_PROVIDER_QUERY_CONCURRENCY, DEFAULT_SESSION_PROVIDER_QUERY_TIMEOUT } from '@helia/interface';
|
|
2
|
+
import { PeerQueue } from '@libp2p/utils/peer-queue';
|
|
3
|
+
import { isPrivateIp } from '@libp2p/utils/private-ip';
|
|
4
|
+
import { DNS, HTTP, HTTPS } from '@multiformats/multiaddr-matcher';
|
|
5
|
+
import { multiaddrToUri } from '@multiformats/multiaddr-to-uri';
|
|
6
|
+
import pDefer from 'p-defer';
|
|
1
7
|
import { TrustlessGateway } from './trustless-gateway.js';
|
|
2
8
|
import { DEFAULT_TRUSTLESS_GATEWAYS } from './index.js';
|
|
3
9
|
/**
|
|
@@ -5,15 +11,22 @@ import { DEFAULT_TRUSTLESS_GATEWAYS } from './index.js';
|
|
|
5
11
|
* for blocks.
|
|
6
12
|
*/
|
|
7
13
|
export class TrustlessGatewayBlockBroker {
|
|
14
|
+
components;
|
|
8
15
|
gateways;
|
|
16
|
+
routing;
|
|
9
17
|
log;
|
|
10
18
|
constructor(components, init = {}) {
|
|
19
|
+
this.components = components;
|
|
11
20
|
this.log = components.logger.forComponent('helia:trustless-gateway-block-broker');
|
|
21
|
+
this.routing = components.routing;
|
|
12
22
|
this.gateways = (init.gateways ?? DEFAULT_TRUSTLESS_GATEWAYS)
|
|
13
23
|
.map((gatewayOrUrl) => {
|
|
14
|
-
return new TrustlessGateway(gatewayOrUrl);
|
|
24
|
+
return new TrustlessGateway(gatewayOrUrl, components.logger);
|
|
15
25
|
});
|
|
16
26
|
}
|
|
27
|
+
addGateway(gatewayOrUrl) {
|
|
28
|
+
this.gateways.push(new TrustlessGateway(gatewayOrUrl, this.components.logger));
|
|
29
|
+
}
|
|
17
30
|
async retrieve(cid, options = {}) {
|
|
18
31
|
// Loop through the gateways until we get a block or run out of gateways
|
|
19
32
|
// TODO: switch to toSorted when support is better
|
|
@@ -30,7 +43,7 @@ export class TrustlessGatewayBlockBroker {
|
|
|
30
43
|
catch (err) {
|
|
31
44
|
this.log.error('failed to validate block for %c from %s', cid, gateway.url, err);
|
|
32
45
|
gateway.incrementInvalidBlocks();
|
|
33
|
-
throw new Error(`
|
|
46
|
+
throw new Error(`Block for CID ${cid} from gateway ${gateway.url} failed validation`);
|
|
34
47
|
}
|
|
35
48
|
return block;
|
|
36
49
|
}
|
|
@@ -40,7 +53,7 @@ export class TrustlessGatewayBlockBroker {
|
|
|
40
53
|
aggregateErrors.push(err);
|
|
41
54
|
}
|
|
42
55
|
else {
|
|
43
|
-
aggregateErrors.push(new Error(`
|
|
56
|
+
aggregateErrors.push(new Error(`Unable to fetch raw block for CID ${cid} from gateway ${gateway.url}`));
|
|
44
57
|
}
|
|
45
58
|
// if signal was aborted, exit the loop
|
|
46
59
|
if (options.signal?.aborted === true) {
|
|
@@ -49,7 +62,90 @@ export class TrustlessGatewayBlockBroker {
|
|
|
49
62
|
}
|
|
50
63
|
}
|
|
51
64
|
}
|
|
52
|
-
|
|
65
|
+
if (aggregateErrors.length > 0) {
|
|
66
|
+
throw new AggregateError(aggregateErrors, `Unable to fetch raw block for CID ${cid} from any gateway`);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
throw new Error(`Unable to fetch raw block for CID ${cid} from any gateway`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async createSession(root, options = {}) {
|
|
73
|
+
const gateways = [];
|
|
74
|
+
const minProviders = options.minProviders ?? DEFAULT_SESSION_MIN_PROVIDERS;
|
|
75
|
+
const maxProviders = options.minProviders ?? DEFAULT_SESSION_MAX_PROVIDERS;
|
|
76
|
+
const deferred = pDefer();
|
|
77
|
+
const broker = new TrustlessGatewayBlockBroker(this.components, {
|
|
78
|
+
gateways
|
|
79
|
+
});
|
|
80
|
+
this.log('finding transport-ipfs-gateway-http providers for cid %c', root);
|
|
81
|
+
const queue = new PeerQueue({
|
|
82
|
+
concurrency: options.providerQueryConcurrency ?? DEFAULT_SESSION_PROVIDER_QUERY_CONCURRENCY
|
|
83
|
+
});
|
|
84
|
+
Promise.resolve().then(async () => {
|
|
85
|
+
for await (const provider of this.routing.findProviders(root, options)) {
|
|
86
|
+
const httpAddresses = provider.multiaddrs.filter(ma => {
|
|
87
|
+
if (HTTPS.matches(ma) || (options.allowInsecure === true && HTTP.matches(ma))) {
|
|
88
|
+
if (options.allowLocal === true) {
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
if (DNS.matches(ma)) {
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
return isPrivateIp(ma.toOptions().host) === false;
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
});
|
|
98
|
+
if (httpAddresses.length === 0) {
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
this.log('found transport-ipfs-gateway-http provider %p for cid %c', provider.id, root);
|
|
102
|
+
void queue.add(async () => {
|
|
103
|
+
for (const ma of httpAddresses) {
|
|
104
|
+
let uri;
|
|
105
|
+
try {
|
|
106
|
+
// /ip4/x.x.x.x/tcp/31337/http
|
|
107
|
+
// /ip4/x.x.x.x/tcp/31337/https
|
|
108
|
+
// etc
|
|
109
|
+
uri = multiaddrToUri(ma);
|
|
110
|
+
const resource = `${uri}/ipfs/${root.toString()}?format=raw`;
|
|
111
|
+
// make sure the peer is available - HEAD support doesn't seem to
|
|
112
|
+
// be very widely implemented so as long as the remote responds
|
|
113
|
+
// we are happy they are valid
|
|
114
|
+
// https://specs.ipfs.tech/http-gateways/trustless-gateway/#head-ipfs-cid-path-params
|
|
115
|
+
// in the future we should be able to request `${uri}/.well-known/libp2p-http
|
|
116
|
+
// and discover an IPFS gateway from $.protocols['/ipfs/gateway'].path
|
|
117
|
+
// in the response
|
|
118
|
+
// https://github.com/libp2p/specs/pull/508/files
|
|
119
|
+
const response = await fetch(resource, {
|
|
120
|
+
method: 'HEAD',
|
|
121
|
+
headers: {
|
|
122
|
+
Accept: 'application/vnd.ipld.raw',
|
|
123
|
+
'Cache-Control': options.cacheControl ?? 'only-if-cached'
|
|
124
|
+
},
|
|
125
|
+
signal: AbortSignal.timeout(options.providerQueryTimeout ?? DEFAULT_SESSION_PROVIDER_QUERY_TIMEOUT)
|
|
126
|
+
});
|
|
127
|
+
this.log('HEAD %s %d', resource, response.status);
|
|
128
|
+
gateways.push(uri);
|
|
129
|
+
broker.addGateway(uri);
|
|
130
|
+
this.log('found %d transport-ipfs-gateway-http providers for cid %c', gateways.length, root);
|
|
131
|
+
if (gateways.length === minProviders) {
|
|
132
|
+
deferred.resolve(broker);
|
|
133
|
+
}
|
|
134
|
+
if (gateways.length === maxProviders) {
|
|
135
|
+
queue.clear();
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
this.log.error('could not fetch %c from %a', root, uri ?? ma, err);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
})
|
|
145
|
+
.catch(err => {
|
|
146
|
+
this.log.error('error creating session for %c', root, err);
|
|
147
|
+
});
|
|
148
|
+
return deferred.promise;
|
|
53
149
|
}
|
|
54
150
|
}
|
|
55
151
|
//# sourceMappingURL=broker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broker.js","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AACzD,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAA;
|
|
1
|
+
{"version":3,"file":"broker.js","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,6BAA6B,EAAE,0CAA0C,EAAE,sCAAsC,EAAE,MAAM,kBAAkB,CAAA;AACnL,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AACtD,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAA;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AAC/D,OAAO,MAAM,MAAM,SAAS,CAAA;AAC5B,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AACzD,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAA;AAgCvD;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IACrB,UAAU,CAA4B;IACtC,QAAQ,CAAoB;IAC5B,OAAO,CAAS;IAChB,GAAG,CAAQ;IAE5B,YAAa,UAAsC,EAAE,OAAwC,EAAE;QAC7F,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,YAAY,CAAC,sCAAsC,CAAC,CAAA;QACjF,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,CAAA;QACjC,IAAI,CAAC,QAAQ,GAAG,CAAC,IAAI,CAAC,QAAQ,IAAI,0BAA0B,CAAC;aAC1D,GAAG,CAAC,CAAC,YAAY,EAAE,EAAE;YACpB,OAAO,IAAI,gBAAgB,CAAC,YAAY,EAAE,UAAU,CAAC,MAAM,CAAC,CAAA;QAC9D,CAAC,CAAC,CAAA;IACN,CAAC;IAED,UAAU,CAAE,YAAoB;QAC9B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,gBAAgB,CAAC,YAAY,EAAE,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAA;IAChF,CAAC;IAED,KAAK,CAAC,QAAQ,CAAE,GAAQ,EAAE,UAAyE,EAAE;QACnG,wEAAwE;QACxE,kDAAkD;QAClD,MAAM,cAAc,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC,CAAA;QACtF,MAAM,eAAe,GAAY,EAAE,CAAA;QAEnC,KAAK,MAAM,OAAO,IAAI,cAAc,EAAE,CAAC;YACrC,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;YAC1D,IAAI,CAAC;gBACH,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;gBAC5D,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,0BAA0B,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;gBAC5D,IAAI,CAAC;oBACH,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,CAAA;gBACnC,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,yCAAyC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;oBAChF,OAAO,CAAC,sBAAsB,EAAE,CAAA;oBAEhC,MAAM,IAAI,KAAK,CAAC,iBAAiB,GAAG,iBAAiB,OAAO,CAAC,GAAG,oBAAoB,CAAC,CAAA;gBACvF,CAAC;gBAED,OAAO,KAAK,CAAA;YACd,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACtB,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,oCAAoC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;gBAC3E,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;oBACzB,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBAC3B,CAAC;qBAAM,CAAC;oBACN,eAAe,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,qCAAqC,GAAG,iBAAiB,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;gBACzG,CAAC;gBACD,uCAAuC;gBACvC,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE,CAAC;oBACrC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,qEAAqE,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;oBACvG,MAAK;gBACP,CAAC;YACH,CAAC;QACH,CAAC;QAED,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC/B,MAAM,IAAI,cAAc,CAAC,eAAe,EAAE,qCAAqC,GAAG,mBAAmB,CAAC,CAAA;QACxG,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,mBAAmB,CAAC,CAAA;QAC9E,CAAC;IACH,CAAC;IAED,KAAK,CAAC,aAAa,CAAE,IAAS,EAAE,UAAgD,EAAE;QAChF,MAAM,QAAQ,GAAa,EAAE,CAAA;QAC7B,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,6BAA6B,CAAA;QAC1E,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,6BAA6B,CAAA;QAC1E,MAAM,QAAQ,GAAG,MAAM,EAAuD,CAAA;QAC9E,MAAM,MAAM,GAAG,IAAI,2BAA2B,CAAC,IAAI,CAAC,UAAU,EAAE;YAC9D,QAAQ;SACT,CAAC,CAAA;QAEF,IAAI,CAAC,GAAG,CAAC,0DAA0D,EAAE,IAAI,CAAC,CAAA;QAE1E,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC;YAC1B,WAAW,EAAE,OAAO,CAAC,wBAAwB,IAAI,0CAA0C;SAC5F,CAAC,CAAA;QAEF,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;YAChC,IAAI,KAAK,EAAE,MAAM,QAAQ,IAAI,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,CAAC;gBACvE,MAAM,aAAa,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE;oBACpD,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,KAAK,IAAI,IAAI,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;wBAC9E,IAAI,OAAO,CAAC,UAAU,KAAK,IAAI,EAAE,CAAC;4BAChC,OAAO,IAAI,CAAA;wBACb,CAAC;wBAED,IAAI,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;4BACpB,OAAO,IAAI,CAAA;wBACb,CAAC;wBAED,OAAO,WAAW,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,CAAA;oBACnD,CAAC;oBAED,OAAO,KAAK,CAAA;gBACd,CAAC,CAAC,CAAA;gBAEF,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBAC/B,SAAQ;gBACV,CAAC;gBAED,IAAI,CAAC,GAAG,CAAC,0DAA0D,EAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;gBAEvF,KAAK,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;oBACxB,KAAK,MAAM,EAAE,IAAI,aAAa,EAAE,CAAC;wBAC/B,IAAI,GAAuB,CAAA;wBAE3B,IAAI,CAAC;4BACH,8BAA8B;4BAC9B,+BAA+B;4BAC/B,MAAM;4BACN,GAAG,GAAG,cAAc,CAAC,EAAE,CAAC,CAAA;4BAExB,MAAM,QAAQ,GAAG,GAAG,GAAG,SAAS,IAAI,CAAC,QAAQ,EAAE,aAAa,CAAA;4BAE5D,iEAAiE;4BACjE,+DAA+D;4BAC/D,8BAA8B;4BAC9B,qFAAqF;4BAErF,6EAA6E;4BAC7E,sEAAsE;4BACtE,kBAAkB;4BAClB,iDAAiD;4BACjD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,QAAQ,EAAE;gCACrC,MAAM,EAAE,MAAM;gCACd,OAAO,EAAE;oCACP,MAAM,EAAE,0BAA0B;oCAClC,eAAe,EAAE,OAAO,CAAC,YAAY,IAAI,gBAAgB;iCAC1D;gCACD,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,oBAAoB,IAAI,sCAAsC,CAAC;6BACpG,CAAC,CAAA;4BAEF,IAAI,CAAC,GAAG,CAAC,YAAY,EAAE,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAA;4BACjD,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;4BAClB,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;4BAEtB,IAAI,CAAC,GAAG,CAAC,2DAA2D,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;4BAE5F,IAAI,QAAQ,CAAC,MAAM,KAAK,YAAY,EAAE,CAAC;gCACrC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;4BAC1B,CAAC;4BAED,IAAI,QAAQ,CAAC,MAAM,KAAK,YAAY,EAAE,CAAC;gCACrC,KAAK,CAAC,KAAK,EAAE,CAAA;4BACf,CAAC;wBACH,CAAC;wBAAC,OAAO,GAAQ,EAAE,CAAC;4BAClB,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,4BAA4B,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,EAAE,GAAG,CAAC,CAAA;wBACpE,CAAC;oBACH,CAAC;gBACH,CAAC,CAAC,CAAA;YACJ,CAAC;QACH,CAAC,CAAC;aACC,KAAK,CAAC,GAAG,CAAC,EAAE;YACX,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,+BAA+B,EAAE,IAAI,EAAE,GAAG,CAAC,CAAA;QAC5D,CAAC,CAAC,CAAA;QAEJ,OAAO,QAAQ,CAAC,OAAO,CAAA;IACzB,CAAC;CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BlockBroker } from '@helia/interface
|
|
1
|
+
import type { Routing, BlockBroker } from '@helia/interface';
|
|
2
2
|
import type { ComponentLogger } from '@libp2p/interface';
|
|
3
3
|
import type { ProgressEvent } from 'progress-events';
|
|
4
4
|
export declare const DEFAULT_TRUSTLESS_GATEWAYS: string[];
|
|
@@ -7,6 +7,7 @@ export interface TrustlessGatewayBlockBrokerInit {
|
|
|
7
7
|
gateways?: Array<string | URL>;
|
|
8
8
|
}
|
|
9
9
|
export interface TrustlessGatewayComponents {
|
|
10
|
+
routing: Routing;
|
|
10
11
|
logger: ComponentLogger;
|
|
11
12
|
}
|
|
12
13
|
export declare function trustlessGateway(init?: TrustlessGatewayBlockBrokerInit): (components: TrustlessGatewayComponents) => BlockBroker<TrustlessGatewayGetBlockProgressEvents>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAEpD,eAAO,MAAM,0BAA0B,UAStC,CAAA;AAED,MAAM,MAAM,sCAAsC,GAChD,aAAa,CAAC,mCAAmC,EAAE,GAAG,CAAC,CAAA;AAEzD,MAAM,WAAW,+BAA+B;IAC9C,QAAQ,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;CAC/B;AAED,MAAM,WAAW,0BAA0B;IACzC,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,eAAe,CAAA;CACxB;AAED,wBAAgB,gBAAgB,CAAE,IAAI,GAAE,+BAAoC,GAAG,CAAC,UAAU,EAAE,0BAA0B,KAAK,WAAW,CAAC,sCAAsC,CAAC,CAE7K"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAKzD,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,wGAAwG;IACxG,gCAAgC;IAEhC,wGAAwG;IACxG,6BAA6B;IAE7B,wGAAwG;IACxG,sBAAsB;CACvB,CAAA;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAKzD,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,wGAAwG;IACxG,gCAAgC;IAEhC,wGAAwG;IACxG,6BAA6B;IAE7B,wGAAwG;IACxG,sBAAsB;CACvB,CAAA;AAcD,MAAM,UAAU,gBAAgB,CAAE,OAAwC,EAAE;IAC1E,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,IAAI,2BAA2B,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;AAC1E,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ComponentLogger } from '@libp2p/interface';
|
|
1
2
|
import type { CID } from 'multiformats/cid';
|
|
2
3
|
/**
|
|
3
4
|
* A `TrustlessGateway` keeps track of the number of attempts, errors, and
|
|
@@ -8,7 +9,8 @@ import type { CID } from 'multiformats/cid';
|
|
|
8
9
|
export declare class TrustlessGateway {
|
|
9
10
|
#private;
|
|
10
11
|
readonly url: URL;
|
|
11
|
-
|
|
12
|
+
private readonly log;
|
|
13
|
+
constructor(url: URL | string, logger: ComponentLogger);
|
|
12
14
|
/**
|
|
13
15
|
* Fetch a raw block from `this.url` following the specification defined at
|
|
14
16
|
* https://specs.ipfs.tech/http-gateways/trustless-gateway/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trustless-gateway.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C;;;;;GAKG;AACH,qBAAa,gBAAgB;;IAC3B,SAAgB,GAAG,EAAE,GAAG,CAAA;
|
|
1
|
+
{"version":3,"file":"trustless-gateway.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAU,MAAM,mBAAmB,CAAA;AAChE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C;;;;;GAKG;AACH,qBAAa,gBAAgB;;IAC3B,SAAgB,GAAG,EAAE,GAAG,CAAA;IA6BxB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;gBAEf,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,MAAM,EAAE,eAAe;IAKvD;;;OAGG;IACG,WAAW,CAAE,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;IA2CvE;;;;;;;OAOG;IACH,WAAW,IAAK,MAAM;IAyBtB;;OAEG;IACH,sBAAsB,IAAK,IAAI;CAGhC"}
|
|
@@ -30,8 +30,10 @@ export class TrustlessGateway {
|
|
|
30
30
|
* The number of times this gateway has successfully fetched a block.
|
|
31
31
|
*/
|
|
32
32
|
#successes = 0;
|
|
33
|
-
|
|
33
|
+
log;
|
|
34
|
+
constructor(url, logger) {
|
|
34
35
|
this.url = url instanceof URL ? url : new URL(url);
|
|
36
|
+
this.log = logger.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`);
|
|
35
37
|
}
|
|
36
38
|
/**
|
|
37
39
|
* Fetch a raw block from `this.url` following the specification defined at
|
|
@@ -57,6 +59,7 @@ export class TrustlessGateway {
|
|
|
57
59
|
},
|
|
58
60
|
cache: 'force-cache'
|
|
59
61
|
});
|
|
62
|
+
this.log('GET %s %d', gwUrl, res.status);
|
|
60
63
|
if (!res.ok) {
|
|
61
64
|
this.#errors++;
|
|
62
65
|
throw new Error(`unable to fetch raw block for CID ${cid} from gateway ${this.url}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trustless-gateway.js","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"trustless-gateway.js","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AACH,MAAM,OAAO,gBAAgB;IACX,GAAG,CAAK;IACxB;;;;;OAKG;IACH,SAAS,GAAG,CAAC,CAAA;IAEb;;;;;OAKG;IACH,OAAO,GAAG,CAAC,CAAA;IAEX;;;;OAIG;IACH,cAAc,GAAG,CAAC,CAAA;IAElB;;OAEG;IACH,UAAU,GAAG,CAAC,CAAA;IAEG,GAAG,CAAQ;IAE5B,YAAa,GAAiB,EAAE,MAAuB;QACrD,IAAI,CAAC,GAAG,GAAG,GAAG,YAAY,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAA;QAClD,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,YAAY,CAAC,wCAAwC,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAA;IAC7F,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,WAAW,CAAE,GAAQ,EAAE,MAAoB;QAC/C,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAA;QACtB,KAAK,CAAC,QAAQ,GAAG,SAAS,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAA;QAE1C,6EAA6E;QAC7E,0BAA0B;QAC1B,KAAK,CAAC,MAAM,GAAG,aAAa,CAAA;QAE5B,IAAI,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE,CAAC;YAC7B,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,iBAAiB,IAAI,CAAC,GAAG,6BAA6B,CAAC,CAAA;QACjH,CAAC;QAED,IAAI,CAAC;YACH,IAAI,CAAC,SAAS,EAAE,CAAA;YAChB,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE;gBACxC,MAAM;gBACN,OAAO,EAAE;oBACT,iEAAiE;oBACjE,gBAAgB;oBACd,MAAM,EAAE,0BAA0B;iBACnC;gBACD,KAAK,EAAE,aAAa;aACrB,CAAC,CAAA;YAEF,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;YAExC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;gBACZ,IAAI,CAAC,OAAO,EAAE,CAAA;gBACd,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,iBAAiB,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;YACtF,CAAC;YACD,IAAI,CAAC,UAAU,EAAE,CAAA;YACjB,OAAO,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,WAAW,EAAE,CAAC,CAAA;QAChD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,qEAAqE;YACrE,yCAAyC;YACzC,IAAI,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE,CAAC;gBAC7B,MAAM,IAAI,KAAK,CAAC,8BAA8B,GAAG,iBAAiB,IAAI,CAAC,GAAG,cAAc,CAAC,CAAA;YAC3F,CAAC;YACD,IAAI,CAAC,OAAO,EAAE,CAAA;YACd,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,EAAE,CAAC,CAAA;QAC7D,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACH,WAAW;QACT;;;WAGG;QACH,IAAI,IAAI,CAAC,SAAS,KAAK,CAAC,EAAE,CAAC;YACzB,OAAO,CAAC,CAAA;QACV,CAAC;QAED,IAAI,IAAI,CAAC,cAAc,GAAG,CAAC,EAAE,CAAC;YAC5B,wCAAwC;YACxC,OAAO,CAAC,QAAQ,CAAA;QAClB,CAAC;QAED;;;;;;;WAOG;QACH,OAAO,IAAI,CAAC,UAAU,GAAG,CAAC,IAAI,CAAC,SAAS,GAAG,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAA;IAChE,CAAC;IAED;;OAEG;IACH,sBAAsB;QACpB,IAAI,CAAC,cAAc,EAAE,CAAA;IACvB,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@helia/block-brokers",
|
|
3
|
-
"version": "2.0.3-
|
|
3
|
+
"version": "2.0.3-6ddefb0",
|
|
4
4
|
"description": "Block brokers for Helia",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/ipfs/helia/tree/main/packages/block-brokers#readme",
|
|
@@ -53,17 +53,26 @@
|
|
|
53
53
|
"test:electron-main": "aegir test -t electron-main"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@helia/interface": "4.1.0-
|
|
56
|
+
"@helia/interface": "4.1.0-6ddefb0",
|
|
57
57
|
"@libp2p/interface": "^1.1.4",
|
|
58
|
+
"@libp2p/utils": "^5.2.6",
|
|
59
|
+
"@multiformats/multiaddr-matcher": "^1.2.0",
|
|
60
|
+
"@multiformats/multiaddr-to-uri": "^10.0.1",
|
|
58
61
|
"interface-blockstore": "^5.2.10",
|
|
59
62
|
"ipfs-bitswap": "^20.0.2",
|
|
60
63
|
"multiformats": "^13.1.0",
|
|
64
|
+
"p-defer": "^4.0.0",
|
|
61
65
|
"progress-events": "^1.0.0"
|
|
62
66
|
},
|
|
63
67
|
"devDependencies": {
|
|
64
68
|
"@libp2p/logger": "^4.0.7",
|
|
69
|
+
"@libp2p/peer-id-factory": "^4.0.7",
|
|
70
|
+
"@multiformats/multiaddr": "^12.1.14",
|
|
71
|
+
"@multiformats/uri-to-multiaddr": "^8.0.0",
|
|
65
72
|
"@types/sinon": "^17.0.3",
|
|
66
73
|
"aegir": "^42.2.5",
|
|
74
|
+
"cors": "^2.8.5",
|
|
75
|
+
"polka": "^0.5.2",
|
|
67
76
|
"sinon": "^17.0.1",
|
|
68
77
|
"sinon-ts": "^2.0.0"
|
|
69
78
|
}
|
|
@@ -1,26 +1,66 @@
|
|
|
1
|
+
import { DEFAULT_SESSION_MIN_PROVIDERS, DEFAULT_SESSION_MAX_PROVIDERS, DEFAULT_SESSION_PROVIDER_QUERY_CONCURRENCY, DEFAULT_SESSION_PROVIDER_QUERY_TIMEOUT } from '@helia/interface'
|
|
2
|
+
import { PeerQueue } from '@libp2p/utils/peer-queue'
|
|
3
|
+
import { isPrivateIp } from '@libp2p/utils/private-ip'
|
|
4
|
+
import { DNS, HTTP, HTTPS } from '@multiformats/multiaddr-matcher'
|
|
5
|
+
import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'
|
|
6
|
+
import pDefer from 'p-defer'
|
|
1
7
|
import { TrustlessGateway } from './trustless-gateway.js'
|
|
2
8
|
import { DEFAULT_TRUSTLESS_GATEWAYS } from './index.js'
|
|
3
9
|
import type { TrustlessGatewayBlockBrokerInit, TrustlessGatewayComponents, TrustlessGatewayGetBlockProgressEvents } from './index.js'
|
|
4
|
-
import type { BlockRetrievalOptions, BlockBroker } from '@helia/interface
|
|
10
|
+
import type { Routing, BlockRetrievalOptions, BlockBroker, CreateSessionOptions } from '@helia/interface'
|
|
5
11
|
import type { Logger } from '@libp2p/interface'
|
|
6
12
|
import type { CID } from 'multiformats/cid'
|
|
7
13
|
|
|
14
|
+
export interface CreateTrustlessGatewaySessionOptions extends CreateSessionOptions<TrustlessGatewayGetBlockProgressEvents> {
|
|
15
|
+
/**
|
|
16
|
+
* Specify the cache control header to send to the remote. 'only-if-cached'
|
|
17
|
+
* will prevent the gateway from fetching the content if they don't have it.
|
|
18
|
+
*
|
|
19
|
+
* @default only-if-cached
|
|
20
|
+
*/
|
|
21
|
+
cacheControl?: string
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* By default we will only connect to peers with HTTPS addresses, pass true
|
|
25
|
+
* to also connect to HTTP addresses.
|
|
26
|
+
*
|
|
27
|
+
* @default false
|
|
28
|
+
*/
|
|
29
|
+
allowInsecure?: boolean
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* By default we will only connect to peers with public or DNS addresses, pass
|
|
33
|
+
* true to also connect to private addresses.
|
|
34
|
+
*
|
|
35
|
+
* @default false
|
|
36
|
+
*/
|
|
37
|
+
allowLocal?: boolean
|
|
38
|
+
}
|
|
39
|
+
|
|
8
40
|
/**
|
|
9
41
|
* A class that accepts a list of trustless gateways that are queried
|
|
10
42
|
* for blocks.
|
|
11
43
|
*/
|
|
12
44
|
export class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGatewayGetBlockProgressEvents> {
|
|
45
|
+
private readonly components: TrustlessGatewayComponents
|
|
13
46
|
private readonly gateways: TrustlessGateway[]
|
|
47
|
+
private readonly routing: Routing
|
|
14
48
|
private readonly log: Logger
|
|
15
49
|
|
|
16
50
|
constructor (components: TrustlessGatewayComponents, init: TrustlessGatewayBlockBrokerInit = {}) {
|
|
51
|
+
this.components = components
|
|
17
52
|
this.log = components.logger.forComponent('helia:trustless-gateway-block-broker')
|
|
53
|
+
this.routing = components.routing
|
|
18
54
|
this.gateways = (init.gateways ?? DEFAULT_TRUSTLESS_GATEWAYS)
|
|
19
55
|
.map((gatewayOrUrl) => {
|
|
20
|
-
return new TrustlessGateway(gatewayOrUrl)
|
|
56
|
+
return new TrustlessGateway(gatewayOrUrl, components.logger)
|
|
21
57
|
})
|
|
22
58
|
}
|
|
23
59
|
|
|
60
|
+
addGateway (gatewayOrUrl: string): void {
|
|
61
|
+
this.gateways.push(new TrustlessGateway(gatewayOrUrl, this.components.logger))
|
|
62
|
+
}
|
|
63
|
+
|
|
24
64
|
async retrieve (cid: CID, options: BlockRetrievalOptions<TrustlessGatewayGetBlockProgressEvents> = {}): Promise<Uint8Array> {
|
|
25
65
|
// Loop through the gateways until we get a block or run out of gateways
|
|
26
66
|
// TODO: switch to toSorted when support is better
|
|
@@ -38,7 +78,7 @@ export class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGateway
|
|
|
38
78
|
this.log.error('failed to validate block for %c from %s', cid, gateway.url, err)
|
|
39
79
|
gateway.incrementInvalidBlocks()
|
|
40
80
|
|
|
41
|
-
throw new Error(`
|
|
81
|
+
throw new Error(`Block for CID ${cid} from gateway ${gateway.url} failed validation`)
|
|
42
82
|
}
|
|
43
83
|
|
|
44
84
|
return block
|
|
@@ -47,7 +87,7 @@ export class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGateway
|
|
|
47
87
|
if (err instanceof Error) {
|
|
48
88
|
aggregateErrors.push(err)
|
|
49
89
|
} else {
|
|
50
|
-
aggregateErrors.push(new Error(`
|
|
90
|
+
aggregateErrors.push(new Error(`Unable to fetch raw block for CID ${cid} from gateway ${gateway.url}`))
|
|
51
91
|
}
|
|
52
92
|
// if signal was aborted, exit the loop
|
|
53
93
|
if (options.signal?.aborted === true) {
|
|
@@ -57,6 +97,106 @@ export class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGateway
|
|
|
57
97
|
}
|
|
58
98
|
}
|
|
59
99
|
|
|
60
|
-
|
|
100
|
+
if (aggregateErrors.length > 0) {
|
|
101
|
+
throw new AggregateError(aggregateErrors, `Unable to fetch raw block for CID ${cid} from any gateway`)
|
|
102
|
+
} else {
|
|
103
|
+
throw new Error(`Unable to fetch raw block for CID ${cid} from any gateway`)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async createSession (root: CID, options: CreateTrustlessGatewaySessionOptions = {}): Promise<BlockBroker<TrustlessGatewayGetBlockProgressEvents>> {
|
|
108
|
+
const gateways: string[] = []
|
|
109
|
+
const minProviders = options.minProviders ?? DEFAULT_SESSION_MIN_PROVIDERS
|
|
110
|
+
const maxProviders = options.minProviders ?? DEFAULT_SESSION_MAX_PROVIDERS
|
|
111
|
+
const deferred = pDefer<BlockBroker<TrustlessGatewayGetBlockProgressEvents>>()
|
|
112
|
+
const broker = new TrustlessGatewayBlockBroker(this.components, {
|
|
113
|
+
gateways
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
this.log('finding transport-ipfs-gateway-http providers for cid %c', root)
|
|
117
|
+
|
|
118
|
+
const queue = new PeerQueue({
|
|
119
|
+
concurrency: options.providerQueryConcurrency ?? DEFAULT_SESSION_PROVIDER_QUERY_CONCURRENCY
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
Promise.resolve().then(async () => {
|
|
123
|
+
for await (const provider of this.routing.findProviders(root, options)) {
|
|
124
|
+
const httpAddresses = provider.multiaddrs.filter(ma => {
|
|
125
|
+
if (HTTPS.matches(ma) || (options.allowInsecure === true && HTTP.matches(ma))) {
|
|
126
|
+
if (options.allowLocal === true) {
|
|
127
|
+
return true
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (DNS.matches(ma)) {
|
|
131
|
+
return true
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return isPrivateIp(ma.toOptions().host) === false
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return false
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
if (httpAddresses.length === 0) {
|
|
141
|
+
continue
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
this.log('found transport-ipfs-gateway-http provider %p for cid %c', provider.id, root)
|
|
145
|
+
|
|
146
|
+
void queue.add(async () => {
|
|
147
|
+
for (const ma of httpAddresses) {
|
|
148
|
+
let uri: string | undefined
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
// /ip4/x.x.x.x/tcp/31337/http
|
|
152
|
+
// /ip4/x.x.x.x/tcp/31337/https
|
|
153
|
+
// etc
|
|
154
|
+
uri = multiaddrToUri(ma)
|
|
155
|
+
|
|
156
|
+
const resource = `${uri}/ipfs/${root.toString()}?format=raw`
|
|
157
|
+
|
|
158
|
+
// make sure the peer is available - HEAD support doesn't seem to
|
|
159
|
+
// be very widely implemented so as long as the remote responds
|
|
160
|
+
// we are happy they are valid
|
|
161
|
+
// https://specs.ipfs.tech/http-gateways/trustless-gateway/#head-ipfs-cid-path-params
|
|
162
|
+
|
|
163
|
+
// in the future we should be able to request `${uri}/.well-known/libp2p-http
|
|
164
|
+
// and discover an IPFS gateway from $.protocols['/ipfs/gateway'].path
|
|
165
|
+
// in the response
|
|
166
|
+
// https://github.com/libp2p/specs/pull/508/files
|
|
167
|
+
const response = await fetch(resource, {
|
|
168
|
+
method: 'HEAD',
|
|
169
|
+
headers: {
|
|
170
|
+
Accept: 'application/vnd.ipld.raw',
|
|
171
|
+
'Cache-Control': options.cacheControl ?? 'only-if-cached'
|
|
172
|
+
},
|
|
173
|
+
signal: AbortSignal.timeout(options.providerQueryTimeout ?? DEFAULT_SESSION_PROVIDER_QUERY_TIMEOUT)
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
this.log('HEAD %s %d', resource, response.status)
|
|
177
|
+
gateways.push(uri)
|
|
178
|
+
broker.addGateway(uri)
|
|
179
|
+
|
|
180
|
+
this.log('found %d transport-ipfs-gateway-http providers for cid %c', gateways.length, root)
|
|
181
|
+
|
|
182
|
+
if (gateways.length === minProviders) {
|
|
183
|
+
deferred.resolve(broker)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (gateways.length === maxProviders) {
|
|
187
|
+
queue.clear()
|
|
188
|
+
}
|
|
189
|
+
} catch (err: any) {
|
|
190
|
+
this.log.error('could not fetch %c from %a', root, uri ?? ma, err)
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
})
|
|
196
|
+
.catch(err => {
|
|
197
|
+
this.log.error('error creating session for %c', root, err)
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
return deferred.promise
|
|
61
201
|
}
|
|
62
202
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TrustlessGatewayBlockBroker } from './broker.js'
|
|
2
|
-
import type { BlockBroker } from '@helia/interface
|
|
2
|
+
import type { Routing, BlockBroker } from '@helia/interface'
|
|
3
3
|
import type { ComponentLogger } from '@libp2p/interface'
|
|
4
4
|
import type { ProgressEvent } from 'progress-events'
|
|
5
5
|
|
|
@@ -22,6 +22,7 @@ export interface TrustlessGatewayBlockBrokerInit {
|
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
export interface TrustlessGatewayComponents {
|
|
25
|
+
routing: Routing
|
|
25
26
|
logger: ComponentLogger
|
|
26
27
|
}
|
|
27
28
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ComponentLogger, Logger } from '@libp2p/interface'
|
|
1
2
|
import type { CID } from 'multiformats/cid'
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -36,8 +37,11 @@ export class TrustlessGateway {
|
|
|
36
37
|
*/
|
|
37
38
|
#successes = 0
|
|
38
39
|
|
|
39
|
-
|
|
40
|
+
private readonly log: Logger
|
|
41
|
+
|
|
42
|
+
constructor (url: URL | string, logger: ComponentLogger) {
|
|
40
43
|
this.url = url instanceof URL ? url : new URL(url)
|
|
44
|
+
this.log = logger.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)
|
|
41
45
|
}
|
|
42
46
|
|
|
43
47
|
/**
|
|
@@ -67,6 +71,9 @@ export class TrustlessGateway {
|
|
|
67
71
|
},
|
|
68
72
|
cache: 'force-cache'
|
|
69
73
|
})
|
|
74
|
+
|
|
75
|
+
this.log('GET %s %d', gwUrl, res.status)
|
|
76
|
+
|
|
70
77
|
if (!res.ok) {
|
|
71
78
|
this.#errors++
|
|
72
79
|
throw new Error(`unable to fetch raw block for CID ${cid} from gateway ${this.url}`)
|