@helia/block-brokers 2.1.0 → 2.1.1-52dbcf2
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/trustless-gateway.d.ts +8 -0
- package/dist/src/trustless-gateway/trustless-gateway.d.ts.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.js +53 -16
- package/dist/src/trustless-gateway/trustless-gateway.js.map +1 -1
- package/package.json +5 -4
- package/src/trustless-gateway/trustless-gateway.ts +63 -18
- package/dist/typedoc-urls.json +0 -4
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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 Fo=Object.create;var ve=Object.defineProperty;var Po=Object.getOwnPropertyDescriptor;var Ro=Object.getOwnPropertyNames;var No=Object.getPrototypeOf,Uo=Object.prototype.hasOwnProperty;var ht=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),j=(r,t)=>{for(var e in t)ve(r,e,{get:t[e],enumerable:!0})},Bn=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ro(t))!Uo.call(r,s)&&s!==e&&ve(r,s,{get:()=>t[s],enumerable:!(n=Po(t,s))||n.enumerable});return r};var Xt=(r,t,e)=>(e=r!=null?Fo(No(r)):{},Bn(t||!r||!r.__esModule?ve(e,"default",{value:r,enumerable:!0}):e,r)),Mo=r=>Bn(ve({},"__esModule",{value:!0}),r);var Vn=ht((fl,$n)=>{var Rt=1e3,Nt=Rt*60,Ut=Nt*60,yt=Ut*24,zo=yt*7,Ho=yt*365.25;$n.exports=function(r,t){t=t||{};var e=typeof r;if(e==="string"&&r.length>0)return qo(r);if(e==="number"&&isFinite(r))return t.long?Go(r):Wo(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function qo(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*Ho;case"weeks":case"week":case"w":return e*zo;case"days":case"day":case"d":return e*yt;case"hours":case"hour":case"hrs":case"hr":case"h":return e*Ut;case"minutes":case"minute":case"mins":case"min":case"m":return e*Nt;case"seconds":case"second":case"secs":case"sec":case"s":return e*Rt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:return}}}}function Wo(r){var t=Math.abs(r);return t>=yt?Math.round(r/yt)+"d":t>=Ut?Math.round(r/Ut)+"h":t>=Nt?Math.round(r/Nt)+"m":t>=Rt?Math.round(r/Rt)+"s":r+"ms"}function Go(r){var t=Math.abs(r);return t>=yt?Te(r,t,yt,"day"):t>=Ut?Te(r,t,Ut,"hour"):t>=Nt?Te(r,t,Nt,"minute"):t>=Rt?Te(r,t,Rt,"second"):r+" ms"}function Te(r,t,e,n){var s=t>=e*1.5;return Math.round(r/e)+" "+n+(s?"s":"")}});var Hn=ht((hl,zn)=>{function jo(r){e.debug=e,e.default=e,e.coerce=l,e.disable=o,e.enable=s,e.enabled=i,e.humanize=Vn(),e.destroy=u,Object.keys(r).forEach(h=>{e[h]=r[h]}),e.names=[],e.skips=[],e.formatters={};function t(h){let f=0;for(let w=0;w<h.length;w++)f=(f<<5)-f+h.charCodeAt(w),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(h){let f,w=null,a,d;function p(...v){if(!p.enabled)return;let m=p,g=Number(new Date),b=g-(f||g);m.diff=b,m.prev=f,m.curr=g,f=g,v[0]=e.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let y=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(A,x)=>{if(A==="%%")return"%";y++;let L=e.formatters[x];if(typeof L=="function"){let nt=v[y];A=L.call(m,nt),v.splice(y,1),y--}return A}),e.formatArgs.call(m,v),(m.log||e.log).apply(m,v)}return p.namespace=h,p.useColors=e.useColors(),p.color=e.selectColor(h),p.extend=n,p.destroy=e.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>w!==null?w:(a!==e.namespaces&&(a=e.namespaces,d=e.enabled(h)),d),set:v=>{w=v}}),typeof e.init=="function"&&e.init(p),p}function n(h,f){let w=e(this.namespace+(typeof f>"u"?":":f)+h);return w.log=this.log,w}function s(h){e.save(h),e.namespaces=h,e.names=[],e.skips=[];let f,w=(typeof h=="string"?h:"").split(/[\s,]+/),a=w.length;for(f=0;f<a;f++)w[f]&&(h=w[f].replace(/\*/g,".*?"),h[0]==="-"?e.skips.push(new RegExp("^"+h.slice(1)+"$")):e.names.push(new RegExp("^"+h+"$")))}function o(){let h=[...e.names.map(c),...e.skips.map(c).map(f=>"-"+f)].join(",");return e.enable(""),h}function i(h){if(h[h.length-1]==="*")return!0;let f,w;for(f=0,w=e.skips.length;f<w;f++)if(e.skips[f].test(h))return!1;for(f=0,w=e.names.length;f<w;f++)if(e.names[f].test(h))return!0;return!1}function c(h){return h.toString().substring(2,h.toString().length-2).replace(/\.\*\?$/,"*")}function l(h){return h instanceof Error?h.stack||h.message:h}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.enable(e.load()),e}zn.exports=jo});var qn=ht((X,De)=>{X.formatArgs=Qo;X.save=Jo;X.load=Ko;X.useColors=Xo;X.storage=Yo();X.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`."))}})();X.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 Xo(){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 Qo(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+De.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)}X.log=console.debug||console.log||(()=>{});function Jo(r){try{r?X.storage.setItem("debug",r):X.storage.removeItem("debug")}catch{}}function Ko(){let r;try{r=X.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Yo(){try{return localStorage}catch{}}De.exports=Hn()(X);var{formatters:Zo}=De.exports;Zo.j=function(r){try{return JSON.stringify(r)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Jn=ht((_l,Qn)=>{"use strict";function Xn(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function ai(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 Xn(r,e)}catch{e.message=r.message,e.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Xn(new s,e)}}Qn.exports=ai});var Os=ht((Mh,Bs)=>{Bs.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Vs=ht((de,tr)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(a){if(!Array.isArray(a)&&!ArrayBuffer.isView(a))return!1;for(var d=0;d<a.length;d++)if(!Number.isInteger(a[d])||a[d]<0||a[d]>255)return!1;return!0}function s(a,d){return(a&65535)*d+(((a>>>16)*d&65535)<<16)}function o(a,d){return a<<d|a>>>32-d}function i(a){return a^=a>>>16,a=s(a,2246822507),a^=a>>>13,a=s(a,3266489909),a^=a>>>16,a}function c(a,d){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535];var p=[0,0,0,0];return p[3]+=a[3]+d[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=a[2]+d[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=a[1]+d[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=a[0]+d[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function l(a,d){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535];var p=[0,0,0,0];return p[3]+=a[3]*d[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=a[2]*d[3],p[1]+=p[2]>>>16,p[2]&=65535,p[2]+=a[3]*d[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=a[1]*d[3],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=a[2]*d[2],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=a[3]*d[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=a[0]*d[3]+a[1]*d[2]+a[2]*d[1]+a[3]*d[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function u(a,d){return d%=64,d===32?[a[1],a[0]]:d<32?[a[0]<<d|a[1]>>>32-d,a[1]<<d|a[0]>>>32-d]:(d-=32,[a[1]<<d|a[0]>>>32-d,a[0]<<d|a[1]>>>32-d])}function h(a,d){return d%=64,d===0?a:d<32?[a[0]<<d|a[1]>>>32-d,a[1]<<d]:[a[1]<<d-32,0]}function f(a,d){return[a[0]^d[0],a[1]^d[1]]}function w(a){return a=f(a,[0,a[0]>>>1]),a=l(a,[4283543511,3981806797]),a=f(a,[0,a[0]>>>1]),a=l(a,[3301882366,444984403]),a=f(a,[0,a[0]>>>1]),a}e.x86.hash32=function(a,d){if(e.inputValidation&&!n(a))return t;d=d||0;for(var p=a.length%4,v=a.length-p,m=d,g=0,b=3432918353,y=461845907,E=0;E<v;E=E+4)g=a[E]|a[E+1]<<8|a[E+2]<<16|a[E+3]<<24,g=s(g,b),g=o(g,15),g=s(g,y),m^=g,m=o(m,13),m=s(m,5)+3864292196;switch(g=0,p){case 3:g^=a[E+2]<<16;case 2:g^=a[E+1]<<8;case 1:g^=a[E],g=s(g,b),g=o(g,15),g=s(g,y),m^=g}return m^=a.length,m=i(m),m>>>0},e.x86.hash128=function(a,d){if(e.inputValidation&&!n(a))return t;d=d||0;for(var p=a.length%16,v=a.length-p,m=d,g=d,b=d,y=d,E=0,A=0,x=0,L=0,nt=597399067,be=2869860233,ye=951274213,xe=2716044179,k=0;k<v;k=k+16)E=a[k]|a[k+1]<<8|a[k+2]<<16|a[k+3]<<24,A=a[k+4]|a[k+5]<<8|a[k+6]<<16|a[k+7]<<24,x=a[k+8]|a[k+9]<<8|a[k+10]<<16|a[k+11]<<24,L=a[k+12]|a[k+13]<<8|a[k+14]<<16|a[k+15]<<24,E=s(E,nt),E=o(E,15),E=s(E,be),m^=E,m=o(m,19),m+=g,m=s(m,5)+1444728091,A=s(A,be),A=o(A,16),A=s(A,ye),g^=A,g=o(g,17),g+=b,g=s(g,5)+197830471,x=s(x,ye),x=o(x,17),x=s(x,xe),b^=x,b=o(b,15),b+=y,b=s(b,5)+2530024501,L=s(L,xe),L=o(L,18),L=s(L,nt),y^=L,y=o(y,13),y+=m,y=s(y,5)+850148119;switch(E=0,A=0,x=0,L=0,p){case 15:L^=a[k+14]<<16;case 14:L^=a[k+13]<<8;case 13:L^=a[k+12],L=s(L,xe),L=o(L,18),L=s(L,nt),y^=L;case 12:x^=a[k+11]<<24;case 11:x^=a[k+10]<<16;case 10:x^=a[k+9]<<8;case 9:x^=a[k+8],x=s(x,ye),x=o(x,17),x=s(x,xe),b^=x;case 8:A^=a[k+7]<<24;case 7:A^=a[k+6]<<16;case 6:A^=a[k+5]<<8;case 5:A^=a[k+4],A=s(A,be),A=o(A,16),A=s(A,ye),g^=A;case 4:E^=a[k+3]<<24;case 3:E^=a[k+2]<<16;case 2:E^=a[k+1]<<8;case 1:E^=a[k],E=s(E,nt),E=o(E,15),E=s(E,be),m^=E}return m^=a.length,g^=a.length,b^=a.length,y^=a.length,m+=g,m+=b,m+=y,g+=m,b+=m,y+=m,m=i(m),g=i(g),b=i(b),y=i(y),m+=g,m+=b,m+=y,g+=m,b+=m,y+=m,("00000000"+(m>>>0).toString(16)).slice(-8)+("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(y>>>0).toString(16)).slice(-8)},e.x64.hash128=function(a,d){if(e.inputValidation&&!n(a))return t;d=d||0;for(var p=a.length%16,v=a.length-p,m=[0,d],g=[0,d],b=[0,0],y=[0,0],E=[2277735313,289559509],A=[1291169091,658871167],x=0;x<v;x=x+16)b=[a[x+4]|a[x+5]<<8|a[x+6]<<16|a[x+7]<<24,a[x]|a[x+1]<<8|a[x+2]<<16|a[x+3]<<24],y=[a[x+12]|a[x+13]<<8|a[x+14]<<16|a[x+15]<<24,a[x+8]|a[x+9]<<8|a[x+10]<<16|a[x+11]<<24],b=l(b,E),b=u(b,31),b=l(b,A),m=f(m,b),m=u(m,27),m=c(m,g),m=c(l(m,[0,5]),[0,1390208809]),y=l(y,A),y=u(y,33),y=l(y,E),g=f(g,y),g=u(g,31),g=c(g,m),g=c(l(g,[0,5]),[0,944331445]);switch(b=[0,0],y=[0,0],p){case 15:y=f(y,h([0,a[x+14]],48));case 14:y=f(y,h([0,a[x+13]],40));case 13:y=f(y,h([0,a[x+12]],32));case 12:y=f(y,h([0,a[x+11]],24));case 11:y=f(y,h([0,a[x+10]],16));case 10:y=f(y,h([0,a[x+9]],8));case 9:y=f(y,[0,a[x+8]]),y=l(y,A),y=u(y,33),y=l(y,E),g=f(g,y);case 8:b=f(b,h([0,a[x+7]],56));case 7:b=f(b,h([0,a[x+6]],48));case 6:b=f(b,h([0,a[x+5]],40));case 5:b=f(b,h([0,a[x+4]],32));case 4:b=f(b,h([0,a[x+3]],24));case 3:b=f(b,h([0,a[x+2]],16));case 2:b=f(b,h([0,a[x+1]],8));case 1:b=f(b,[0,a[x]]),b=l(b,E),b=u(b,31),b=l(b,A),m=f(m,b)}return m=f(m,[0,a.length]),g=f(g,[0,a.length]),m=c(m,g),g=c(g,m),m=w(m),g=w(g),m=c(m,g),g=c(g,m),("00000000"+(m[0]>>>0).toString(16)).slice(-8)+("00000000"+(m[1]>>>0).toString(16)).slice(-8)+("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)},typeof de<"u"?(typeof tr<"u"&&tr.exports&&(de=tr.exports=e),de.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(de)});var Hs=ht((ud,zs)=>{zs.exports=Vs()});var Js=ht(pe=>{(function(){var r,t,e,n,s,o,i,c;c=function(l){var u,h,f,w;return u=(l&255<<24)>>>24,h=(l&255<<16)>>>16,f=(l&65280)>>>8,w=l&255,[u,h,f,w].join(".")},i=function(l){var u,h,f,w,a,d;for(u=[],f=w=0;w<=3&&l.length!==0;f=++w){if(f>0){if(l[0]!==".")throw new Error("Invalid IP");l=l.substring(1)}d=t(l),a=d[0],h=d[1],l=l.substring(h),u.push(a)}if(l.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(l){return l.charCodeAt(0)},n=e("0"),o=e("a"),s=e("A"),t=function(l){var u,h,f,w,a;for(w=0,u=10,h="9",f=0,l.length>1&&l[f]==="0"&&(l[f+1]==="x"||l[f+1]==="X"?(f+=2,u=16):"0"<=l[f+1]&&l[f+1]<="9"&&(f++,u=8,h="7")),a=f;f<l.length;){if("0"<=l[f]&&l[f]<=h)w=w*u+(e(l[f])-n)>>>0;else if(u===16)if("a"<=l[f]&&l[f]<="f")w=w*u+(10+e(l[f])-o)>>>0;else if("A"<=l[f]&&l[f]<="F")w=w*u+(10+e(l[f])-s)>>>0;else break;else break;if(w>4294967295)throw new Error("too large");f++}if(f===a)throw new Error("empty octet");return[w,f]},r=function(){function l(u,h){var f,w,a,d;if(typeof u!="string")throw new Error("Missing `net' parameter");if(h||(d=u.split("/",2),u=d[0],h=d[1]),h||(h=32),typeof h=="string"&&h.indexOf(".")>-1){try{this.maskLong=i(h)}catch(p){throw f=p,new Error("Invalid mask: "+h)}for(w=a=32;a>=0;w=--a)if(this.maskLong===4294967295<<32-w>>>0){this.bitmask=w;break}}else if(h||h===0)this.bitmask=parseInt(h,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(p){throw f=p,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+h);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return l.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new l(u)),u instanceof l?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},l.prototype.next=function(u){return u==null&&(u=1),new l(c(this.netLong+this.size*u),this.mask)},l.prototype.forEach=function(u){var h,f,w;for(w=i(this.first),f=i(this.last),h=0;w<=f;)u(c(w),w,h),h++,w++},l.prototype.toString=function(){return this.base+"/"+this.bitmask},l}(),pe.ip2long=i,pe.long2ip=c,pe.Netmask=r}).call(pe)});var Uc={};j(Uc,{bitswap:()=>Xs,trustlessGateway:()=>_o});var On=Symbol.for("@libp2p/peer-id");var dt=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"},H=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var G=(r,...t)=>{try{[...t]}catch{}};var it=class extends EventTarget{#t=new Map;constructor(){super(),G(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:o})=>o!==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 Bo(t,e))}},gr=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},Bo=globalThis.CustomEvent??gr;function Ee(r){let t=new globalThis.AbortController;function e(){t.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function B(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Se=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 Se(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 Se(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 wr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ft(r={}){return Oo(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 Oo(r,t){t=t??{};let e=t.onEnd,n=new _t,s,o,i,c=B(),l=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((v,m)=>{o=g=>{o=null,n.push(g);try{v(r(n))}catch(b){m(b)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=B()})}},u=v=>o!=null?o(v):(n.push(v),s),h=v=>(n=new _t,o!=null?o({error:v}):(n.push({error:v}),s)),f=v=>{if(i)return s;if(t?.objectMode!==!0&&v?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:v})},w=v=>i?s:(i=!0,v!=null?h(v):u({done:!0})),a=()=>(n=new _t,w(),{done:!0}),d=v=>(w(v),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:l,return:a,throw:d,push:f,end:w,get readableLength(){return n.size},onEmpty:async v=>{let m=v?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let g,b;m!=null&&(g=new Promise((y,E)=>{b=()=>{E(new wr)},m.addEventListener("abort",b)}));try{await Promise.race([c.promise,g])}finally{b!=null&&m!=null&&m?.removeEventListener("abort",b)}}},e==null)return s;let p=s;return s={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(v){return p.throw(v),e!=null&&(e(v),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(v){return p.end(v),e!=null&&(e(v),e=void 0),s},get readableLength(){return p.readableLength},onEmpty:v=>p.onEmpty(v)},s}var br=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 st(r,t,e,n){let s=new br(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{let c=u=>{try{if(n?.filter?.(u)===!1)return}catch(h){r.removeEventListener(t,c),e?.removeEventListener("abort",l),i(h);return}r.removeEventListener(t,c),e?.removeEventListener("abort",l),o(u)},l=()=>{r.removeEventListener(t,c),e?.removeEventListener("abort",l),i(s)};r.addEventListener(t,c),e?.addEventListener("abort",l)})}var Ae=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 ke(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Ae(e?.errorMessage,e?.errorCode));let n,s=new Ae(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Le=class{deferred;signal;where;constructor(t,e){this.signal=e,this.deferred=B(),this.where=t,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new dt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function $o(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ce=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(t,e,n=0){this.id=$o(),this.status="queued",this.fn=t,this.priority=n,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,G(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 dt)}async join(t={}){let e=new Le(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 ke(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 Vo(r,t,e){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;e(r[i],t)<=0?(n=++i,s-=o+1):s=o}return n}var Pt=class extends it{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=Vo(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 Ce(t,e,e?.priority),s=n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});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 dt)}),this.clear()}async onEmpty(t){this.size!==0&&await st(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await st(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await st(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=Ft({objectMode:!0}),n=l=>{l!=null?this.abort():this.clear(),e.end(l)},s=l=>{l.detail!=null&&e.push(l.detail)},o=l=>{n(l.detail)},i=()=>{n()},c=()=>{n(new H("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",c);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",c),n()}}};var Ie=class extends Pt{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Fs=Xt(qn(),1);function ti(r){return r[Symbol.asyncIterator]!=null}function ei(r){if(ti(r))return(async()=>{for await(let t of r);})();for(let t of r);}var yr=ei;function O(r=0){return new Uint8Array(r)}function $(r=0){return new Uint8Array(r)}var ri=Math.pow(2,7),ni=Math.pow(2,14),si=Math.pow(2,21),xr=Math.pow(2,28),vr=Math.pow(2,35),Er=Math.pow(2,42),Sr=Math.pow(2,49),I=128,V=127;function _(r){if(r<ri)return 1;if(r<ni)return 2;if(r<si)return 3;if(r<xr)return 4;if(r<vr)return 5;if(r<Er)return 6;if(r<Sr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ar(r,t,e=0){switch(_(r)){case 8:t[e++]=r&255|I,r/=128;case 7:t[e++]=r&255|I,r/=128;case 6:t[e++]=r&255|I,r/=128;case 5:t[e++]=r&255|I,r/=128;case 4:t[e++]=r&255|I,r>>>=7;case 3:t[e++]=r&255|I,r>>>=7;case 2:t[e++]=r&255|I,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function oi(r,t,e=0){switch(_(r)){case 8:t.set(e++,r&255|I),r/=128;case 7:t.set(e++,r&255|I),r/=128;case 6:t.set(e++,r&255|I),r/=128;case 5:t.set(e++,r&255|I),r/=128;case 4:t.set(e++,r&255|I),r>>>=7;case 3:t.set(e++,r&255|I),r>>>=7;case 2:t.set(e++,r&255|I),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function kr(r,t){let e=r[t],n=0;if(n+=e&V,e<I||(e=r[t+1],n+=(e&V)<<7,e<I)||(e=r[t+2],n+=(e&V)<<14,e<I)||(e=r[t+3],n+=(e&V)<<21,e<I)||(e=r[t+4],n+=(e&V)*xr,e<I)||(e=r[t+5],n+=(e&V)*vr,e<I)||(e=r[t+6],n+=(e&V)*Er,e<I)||(e=r[t+7],n+=(e&V)*Sr,e<I))return n;throw new RangeError("Could not decode varint")}function ii(r,t){let e=r.get(t),n=0;if(n+=e&V,e<I||(e=r.get(t+1),n+=(e&V)<<7,e<I)||(e=r.get(t+2),n+=(e&V)<<14,e<I)||(e=r.get(t+3),n+=(e&V)<<21,e<I)||(e=r.get(t+4),n+=(e&V)*xr,e<I)||(e=r.get(t+5),n+=(e&V)*vr,e<I)||(e=r.get(t+6),n+=(e&V)*Er,e<I)||(e=r.get(t+7),n+=(e&V)*Sr,e<I))return n;throw new RangeError("Could not decode varint")}function Z(r,t,e=0){return t==null&&(t=$(_(r))),t instanceof Uint8Array?Ar(r,t,e):oi(r,t,e)}function Q(r,t=0){return r instanceof Uint8Array?kr(r,t):ii(r,t)}function tt(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=$(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function et(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 Gn=Symbol.for("@achingbrain/uint8arraylist");function Wn(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 _e(r){return!!r?.[Gn]}var q=class r{bufs;length;[Gn]=!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(_e(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(_e(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=Wn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Wn(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(_e(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 tt(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:tt(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_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 o=0;o<this.bufs.length;o++){let i=this.bufs[o],c=s,l=c+i.byteLength;if(s=l,t>=l)continue;let u=t>=c&&t<l,h=e>c&&e<=l;if(u&&h){if(t===c&&e===l){n.push(i);break}let f=t-c;n.push(i.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-c));continue}if(h){if(e===l){n.push(i);break}n.push(i.subarray(0,e-c));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!_e(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 o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let c=i,l=this.byteLength-n.byteLength,u=n.byteLength-1,h;for(let f=e;f<=l;f+=h){h=0;for(let w=u;w>=0;w--){let a=this.get(f+w);if(n[w]!==a){h=Math.max(1,w-c[a]);break}}if(h===0)return f}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=$(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=O(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=O(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=O(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=$(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=O(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=O(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=O(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=O(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=O(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(!et(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,o)=>s+o.byteLength,0)),n.length=e,n}};function Fe(r){return r[Symbol.asyncIterator]!=null}var Pe=r=>{let t=_(r),e=$(t);return Z(r,e),Pe.bytes=t,e};Pe.bytes=0;function jn(r,t){t=t??{};let e=t.lengthEncoder??Pe;function*n(s){let o=e(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return Fe(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}jn.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Pe;return new q(e(r.byteLength),r)};var Mt=Xt(Jn(),1);var ci=8,li=1024*1024*4,xt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(xt||(xt={}));var Lr=r=>{let t=Q(r);return Lr.bytes=_(t),t};Lr.bytes=0;function Jt(r,t){let e=new q,n=xt.LENGTH,s=-1,o=t?.lengthDecoder??Lr,i=t?.maxLengthLength??ci,c=t?.maxDataLength??li;function*l(){for(;e.byteLength>0;){if(n===xt.LENGTH)try{if(s=o(e),s<0)throw(0,Mt.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,Mt.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;e.consume(u),t?.onLength!=null&&t.onLength(s),n=xt.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw(0,Mt.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===xt.DATA){if(e.byteLength<s)break;let u=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(u),yield u,n=xt.LENGTH}}}return Fe(r)?async function*(){for await(let u of r)e.append(u),yield*l();if(e.byteLength>0)throw(0,Mt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)e.append(u),yield*l();if(e.byteLength>0)throw(0,Mt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Jt.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}}();return Jt(n,{...t??{},onLength:o=>{e=o}})};var Cr=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=B(),this.haveNext=B()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=B(),t}async throw(t){return this.ended=!0,t!=null&&this.haveNext.reject(t),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");if(this.nextResult!=null&&(await this.readNext.promise,this.nextResult!=null))throw new Error("NeedNext promise resolved but nextResult was not consumed");t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=B(),await ke(this.readNext.promise,e?.signal,e)}};function Kn(){return new Cr}var Re=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ir=class extends Re{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function Yn(r,t){let e=Kn();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let c of i)await e.push(c);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let s=new q;return{read:async(i,c)=>{c?.signal?.throwIfAborted();let l,u=new Promise((h,f)=>{l=()=>{f(new Ir("Read aborted"))},c?.signal?.addEventListener("abort",l)});try{if(i==null){let{done:f,value:w}=await Promise.race([n.next(),u]);return f===!0?new q:w}for(;s.byteLength<i;){let{value:f,done:w}=await Promise.race([n.next(),u]);if(w===!0)throw new Re("unexpected end of input","ERR_UNEXPECTED_EOF");s.append(f)}let h=s.sublist(0,i);return s.consume(i),h}finally{l!=null&&c?.signal?.removeEventListener("abort",l)}},write:async(i,c)=>{c?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,c):await e.push(i.subarray(),c)},unwrap:()=>{if(s.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield s:yield*s,yield*i}()}return r}}}var Ne=class extends Error{code;constructor(t,e){super(t),this.code=e}};function Zn(r,t={}){let e=Yn(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=_(t.maxDataLength));let n=t?.lengthDecoder??Q,s=t?.lengthEncoder??Z;return{read:async i=>{let c=-1,l=new q;for(;;){l.append(await e.read(1,i));try{c=n(l)}catch(u){if(u instanceof RangeError)continue;throw u}if(t?.maxLengthLength!=null&&l.byteLength>t.maxLengthLength)throw new Ne("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(c>-1)break}if(t?.maxDataLength!=null&&c>t.maxDataLength)throw new Ne("message length too long","ERR_MSG_DATA_TOO_LONG");return e.read(c,i)},write:async(i,c)=>{await e.write(new q(s(i.byteLength),i),c)},writeV:async(i,c)=>{let l=new q(...i.flatMap(u=>[s(u.byteLength),u]));await e.write(l,c)},unwrap:()=>e.unwrap()}}function fi(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 Ue=fi;function hi(r){return r[Symbol.asyncIterator]!=null}function di(r,t){if(hi(r))return async function*(){for await(let c of r)yield t(c)}();let e=Ue(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let o=t(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let c of e)yield t(c)}();let i=t;return function*(){yield o;for(let c of e)yield i(c)}()}var Kt=di;function pi(r){return r[Symbol.asyncIterator]!=null}function mi(...r){let t=[];for(let e of r)pi(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Ft({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 ts=mi;function Yt(r,...t){if(r==null)throw new Error("Empty pipeline");if(Tr(r)){let n=r;r=()=>n.source}else if(rs(r)||es(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Tr(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++)Tr(e[n])&&(e[n]=wi(e[n]));return gi(...e)}var gi=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},es=r=>r?.[Symbol.asyncIterator]!=null,rs=r=>r?.[Symbol.iterator]!=null,Tr=r=>r==null?!1:r.sink!=null&&r.source!=null,wi=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ft({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(es(o))s=async function*(){yield*o,n.end()};else if(rs(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return ts(n,s())}return r.source};function bi(r){return r[Symbol.asyncIterator]!=null}function yi(r,t){return bi(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 ns=yi;var Nr={};j(Nr,{base64:()=>at,base64pad:()=>ki,base64url:()=>Rr,base64urlpad:()=>Li});var ru=new Uint8Array(0);function ss(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 ut(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 os(r){return new TextEncoder().encode(r)}function is(r){return new TextDecoder().decode(r)}function xi(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 o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var c=r.length,l=r.charAt(0),u=Math.log(c)/Math.log(256),h=Math.log(256)/Math.log(c);function f(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 p=0,v=0,m=0,g=d.length;m!==g&&d[m]===0;)m++,p++;for(var b=(g-m)*h+1>>>0,y=new Uint8Array(b);m!==g;){for(var E=d[m],A=0,x=b-1;(E!==0||A<v)&&x!==-1;x--,A++)E+=256*y[x]>>>0,y[x]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");v=A,m++}for(var L=b-v;L!==b&&y[L]===0;)L++;for(var nt=l.repeat(p);L<b;++L)nt+=r.charAt(y[L]);return nt}function w(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var p=0;if(d[p]!==" "){for(var v=0,m=0;d[p]===l;)v++,p++;for(var g=(d.length-p)*u+1>>>0,b=new Uint8Array(g);d[p];){var y=e[d.charCodeAt(p)];if(y===255)return;for(var E=0,A=g-1;(y!==0||E<m)&&A!==-1;A--,E++)y+=c*b[A]>>>0,b[A]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");m=E,p++}if(d[p]!==" "){for(var x=g-m;x!==g&&b[x]===0;)x++;for(var L=new Uint8Array(v+(g-x)),nt=v;x!==g;)L[nt++]=b[x++];return L}}}function a(d){var p=w(d);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:w,decode:a}}var vi=xi,Ei=vi,cs=Ei;var Dr=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")}},_r=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 ls(this,t)}},Fr=class{decoders;constructor(t){this.decoders=t}or(t){return ls(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 ls(r,t){return new Fr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Pr=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 Dr(t,e,n),this.decoder=new _r(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Bt({name:r,prefix:t,encode:e,decode:n}){return new Pr(r,t,e,n)}function pt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=cs(e,r);return Bt({prefix:t,name:r,encode:n,decode:o=>ut(s(o))})}function Si(r,t,e,n){let s={};for(let h=0;h<t.length;++h)s[t[h]]=h;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),c=0,l=0,u=0;for(let h=0;h<o;++h){let f=s[r[h]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);l=l<<e|f,c+=e,c>=8&&(c-=8,i[u++]=255&l>>c)}if(c>=e||255&l<<8-c)throw new SyntaxError("Unexpected end of data");return i}function Ai(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,c=0;for(let l=0;l<r.length;++l)for(c=c<<8|r[l],i+=8;i>e;)i-=e,o+=t[s&c>>i];if(i!==0&&(o+=t[s&c<<e-i]),n)for(;o.length*e&7;)o+="=";return o}function F({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Bt({prefix:t,name:r,encode(s){return Ai(s,n,e)},decode(s){return Si(s,n,e,r)}})}var at=F({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ki=F({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Rr=F({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Li=F({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ur={};j(Ur,{base32:()=>ft,base32hex:()=>Di,base32hexpad:()=>Fi,base32hexpadupper:()=>Pi,base32hexupper:()=>_i,base32pad:()=>Ii,base32padupper:()=>Ti,base32upper:()=>Ci,base32z:()=>Ri});var ft=F({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ci=F({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ii=F({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ti=F({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Di=F({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_i=F({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Fi=F({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pi=F({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ri=F({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Mr={};j(Mr,{base58btc:()=>N,base58flickr:()=>Ni});var N=pt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ni=pt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ui=hs,us=128,Mi=127,Bi=~Mi,Oi=Math.pow(2,31);function hs(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Oi;)t[e++]=r&255|us,r/=128;for(;r&Bi;)t[e++]=r&255|us,r>>>=7;return t[e]=r|0,hs.bytes=e-n+1,t}var $i=Br,Vi=128,fs=127;function Br(r,n){var e=0,n=n||0,s=0,o=n,i,c=r.length;do{if(o>=c)throw Br.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&fs)<<s:(i&fs)*Math.pow(2,s),s+=7}while(i>=Vi);return Br.bytes=o-n,e}var zi=Math.pow(2,7),Hi=Math.pow(2,14),qi=Math.pow(2,21),Wi=Math.pow(2,28),Gi=Math.pow(2,35),ji=Math.pow(2,42),Xi=Math.pow(2,49),Qi=Math.pow(2,56),Ji=Math.pow(2,63),Ki=function(r){return r<zi?1:r<Hi?2:r<qi?3:r<Wi?4:r<Gi?5:r<ji?6:r<Xi?7:r<Qi?8:r<Ji?9:10},Yi={encode:Ui,decode:$i,encodingLength:Ki},Zi=Yi,Zt=Zi;function te(r,t=0){return[Zt.decode(r,t),Zt.decode.bytes]}function Ot(r,t,e=0){return Zt.encode(r,t,e),t}function $t(r){return Zt.encodingLength(r)}function mt(r,t){let e=t.byteLength,n=$t(r),s=n+$t(e),o=new Uint8Array(s+e);return Ot(r,o,0),Ot(e,o,n),o.set(t,s),new Vt(r,e,t,o)}function vt(r){let t=ut(r),[e,n]=te(t),[s,o]=te(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Vt(e,s,i,t)}function ds(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ss(r.bytes,e.bytes)}}var Vt=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};function ps(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return ea(e,Or(r),t??N.encoder);default:return ra(e,Or(r),t??ft.encoder)}}var ms=new WeakMap;function Or(r){let t=ms.get(r);if(t==null){let e=new Map;return ms.set(r,e),e}return t}var U=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!==ee)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==na)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&&ds(t.multihash,n.multihash)}toString(t){return ps(this,t)}toJSON(){return{"/":ps(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:o,bytes:i}=e;return new r(n,s,o,i??gs(n,s,o.bytes))}else if(e[sa]===!0){let{version:n,multihash:s,code:o}=e,i=vt(s);return r.create(n,o,i)}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!==ee)throw new Error(`Version 0 CID must use dag-pb (code: ${ee}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=gs(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,ee,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=ut(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Vt(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,w]=te(t.subarray(e));return e+=w,f},s=n(),o=ee;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,c=n(),l=n(),u=e+l,h=u-i;return{version:s,codec:o,multihashCode:c,digestSize:l,multihashSize:h,size:u}}static parse(t,e){let[n,s]=ta(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Or(o).set(n,t),o}};function ta(r,t){switch(r[0]){case"Q":{let e=t??N;return[N.prefix,e.decode(`${N.prefix}${r}`)]}case N.prefix:{let e=t??N;return[N.prefix,e.decode(r)]}case ft.prefix:{let e=t??ft;return[ft.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 ea(r,t,e){let{prefix:n}=e;if(n!==N.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function ra(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var ee=112,na=18;function gs(r,t,e){let n=$t(r),s=n+$t(t),o=new Uint8Array(s+e.byteLength);return Ot(r,o,0),Ot(t,o,n),o.set(e,s),o}var sa=Symbol.for("@ipld/js-cid/CID");var ct=class extends Event{constructor(t,e){super(t),this.detail=e}};var $r={};j($r,{base10:()=>oa});var oa=pt({prefix:"9",name:"base10",alphabet:"0123456789"});var Vr={};j(Vr,{base16:()=>ia,base16upper:()=>aa});var ia=F({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),aa=F({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var zr={};j(zr,{base2:()=>ca});var ca=F({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Hr={};j(Hr,{base256emoji:()=>da});var ws=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}"),la=ws.reduce((r,t,e)=>(r[e]=t,r),[]),ua=ws.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function fa(r){return r.reduce((t,e)=>(t+=la[e],t),"")}function ha(r){let t=[];for(let e of r){let n=ua[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var da=Bt({prefix:"\u{1F680}",name:"base256emoji",encode:fa,decode:ha});var qr={};j(qr,{base36:()=>pa,base36upper:()=>ma});var pa=pt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ma=pt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Wr={};j(Wr,{base8:()=>ga});var ga=F({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Gr={};j(Gr,{identity:()=>wa});var wa=Bt({prefix:"\0",name:"identity",encode:r=>is(r),decode:r=>os(r)});var Cu=new TextEncoder,Iu=new TextDecoder;var jr={};j(jr,{identity:()=>Be});var bs=0,xa="identity",ys=ut;function va(r){return mt(bs,ys(r))}var Be={code:bs,name:xa,encode:ys,digest:va};var Jr={};j(Jr,{sha256:()=>St,sha512:()=>Ea});function Qr({name:r,code:t,encode:e}){return new Xr(r,t,e)}var Xr=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 vs(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var St=Qr({name:"sha2-256",code:18,encode:vs("SHA-256")}),Ea=Qr({name:"sha2-512",code:19,encode:vs("SHA-512")});var gt={...Gr,...zr,...Wr,...$r,...Vr,...Ur,...qr,...Mr,...Nr,...Hr},Vu={...Jr,...jr};function Ss(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Es=Ss("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Kr=Ss("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=$(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Sa={utf8:Es,"utf-8":Es,hex:gt.base16,latin1:Kr,ascii:Kr,binary:Kr,...gt},Oe=Sa;function D(r,t="utf8"){let e=Oe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var re="/ipfs/bitswap/1.2.0";var Yr=new Float32Array([-0]),wt=new Uint8Array(Yr.buffer);function As(r,t,e){Yr[0]=r,t[e]=wt[0],t[e+1]=wt[1],t[e+2]=wt[2],t[e+3]=wt[3]}function ks(r,t){return wt[0]=r[t],wt[1]=r[t+1],wt[2]=r[t+2],wt[3]=r[t+3],Yr[0]}var Zr=new Float64Array([-0]),z=new Uint8Array(Zr.buffer);function Ls(r,t,e){Zr[0]=r,t[e]=z[0],t[e+1]=z[1],t[e+2]=z[2],t[e+3]=z[3],t[e+4]=z[4],t[e+5]=z[5],t[e+6]=z[6],t[e+7]=z[7]}function Cs(r,t){return z[0]=r[t],z[1]=r[t+1],z[2]=r[t+2],z[3]=r[t+3],z[4]=r[t+4],z[5]=r[t+5],z[6]=r[t+6],z[7]=r[t+7],Zr[0]}var Aa=BigInt(Number.MAX_SAFE_INTEGER),ka=BigInt(Number.MIN_SAFE_INTEGER),J=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 At;if(t<Aa&&t>ka)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>Is&&(s=0n,++n>Is&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return At;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):At}},At=new J(0,0);At.toBigInt=function(){return 0n};At.zzEncode=At.zzDecode=function(){return this};At.length=function(){return 1};var Is=4294967296n;function Ts(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 Ds(r,t,e){if(e-t<1)return"";let s,o=[],i=0,c;for(;t<e;)c=r[t++],c<128?o[i++]=c:c>191&&c<224?o[i++]=(c&31)<<6|r[t++]&63:c>239&&c<365?(c=((c&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(c>>10),o[i++]=56320+(c&1023)):o[i++]=(c&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function tn(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,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 ot(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function $e(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var en=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,ot(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 ot(this,4);return $e(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return $e(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);let t=ks(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ot(this,4);let t=Cs(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 ot(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ds(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ot(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ot(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 J(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 ot(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 ot(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 ot(this,8);let t=$e(this.buf,this.pos+=4),e=$e(this.buf,this.pos+=4);return new J(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=kr(this.buf,this.pos);return this.pos+=_(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 rn(r){return new en(r instanceof Uint8Array?r:r.subarray())}function kt(r,t,e){let n=rn(r);return t.decode(n,void 0,e)}function bt(r,t="utf8"){let e=Oe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function nn(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return $(i);s+i>t&&(n=$(t),s=0);let c=n.subarray(s,s+=i);return s&7&&(s=(s|7)+1),c}}var Lt=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function sn(){}var an=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},La=nn();function Ca(r){return globalThis.Buffer!=null?$(r):La(r)}var se=class{len;head;tail;states;constructor(){this.len=0,this.head=new Lt(sn,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Lt(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new cn((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(Ve,10,J.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=J.fromBigInt(t);return this._push(Ve,e.length(),e)}uint64Number(t){return this._push(Ar,_(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=J.fromBigInt(t).zzEncode();return this._push(Ve,e.length(),e)}sint64Number(t){let e=J.fromNumber(t).zzEncode();return this._push(Ve,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(on,1,t?1:0)}fixed32(t){return this._push(ne,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=J.fromBigInt(t);return this._push(ne,4,e.lo)._push(ne,4,e.hi)}fixed64Number(t){let e=J.fromNumber(t);return this._push(ne,4,e.lo)._push(ne,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(As,4,t)}double(t){return this._push(Ls,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(on,1,0):this.uint32(e)._push(Ta,e,t)}string(t){let e=Ts(t);return e!==0?this.uint32(e)._push(tn,e,t):this._push(on,1,0)}fork(){return this.states=new an(this),this.head=this.tail=new Lt(sn,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 Lt(sn,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=Ca(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function on(r,t,e){t[e]=r&255}function Ia(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var cn=class extends Lt{next;constructor(t,e){super(Ia,t,e),this.next=void 0}};function Ve(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 ne(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 Ta(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(se.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Da,t,r),this},se.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(_a,t,r),this});function Da(r,t,e){t.set(r,e)}function _a(r,t,e){r.length<40?tn(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(bt(r),e)}function ln(){return new se}function Ct(r,t){let e=ln();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var zt;(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"})(zt||(zt={}));function ze(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function He(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let c=t(o);i.int32(c)},n=function(o){let i=o.int32();return t(i)};return ze("enum",zt.VARINT,e,n)}function It(r,t){return ze("message",zt.LENGTH_DELIMITED,r,t)}var P;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(P||(P={}));var un;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(un||(un={}));(function(r){r.codec=()=>He(un)})(P||(P={}));var qe;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.priority!=null&&e.priority!==0&&(n.uint32(16),n.int32(e.priority)),e.cancel!=null&&(n.uint32(24),n.bool(e.cancel)),e.wantType!=null&&(n.uint32(32),P.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={cid:O(0),priority:0},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let i=e.uint32();switch(i>>>3){case 1:{s.cid=e.bytes();break}case 2:{s.priority=e.int32();break}case 3:{s.cancel=e.bool();break}case 4:{s.wantType=P.codec().decode(e);break}case 5:{s.sendDontHave=e.bool();break}default:{e.skipType(i&7);break}}}return s})),t),r.encode=e=>Ct(e,r.codec()),r.decode=e=>kt(e,r.codec())})(qe||(qe={}));var We;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let o of e.entries)n.uint32(10),qe.codec().encode(o,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={entries:[]},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let i=e.uint32();switch(i>>>3){case 1:{s.entries.push(qe.codec().decode(e,e.uint32()));break}case 2:{s.full=e.bool();break}default:{e.skipType(i&7);break}}}return s})),t),r.encode=e=>Ct(e,r.codec()),r.decode=e=>kt(e,r.codec())})(We||(We={}));var Ge;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.prefix!=null&&e.prefix.byteLength>0&&(n.uint32(10),n.bytes(e.prefix)),e.data!=null&&e.data.byteLength>0&&(n.uint32(18),n.bytes(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={prefix:O(0),data:O(0)},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let i=e.uint32();switch(i>>>3){case 1:{s.prefix=e.bytes();break}case 2:{s.data=e.bytes();break}default:{e.skipType(i&7);break}}}return s})),t),r.encode=e=>Ct(e,r.codec()),r.decode=e=>kt(e,r.codec())})(Ge||(Ge={}));var rt;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(rt||(rt={}));var je;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(je||(je={}));(function(r){r.codec=()=>He(je)})(rt||(rt={}));var Xe;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.type!=null&&je[e.type]!==0&&(n.uint32(16),rt.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={cid:O(0),type:rt.HaveBlock},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let i=e.uint32();switch(i>>>3){case 1:{s.cid=e.bytes();break}case 2:{s.type=rt.codec().decode(e);break}default:{e.skipType(i&7);break}}}return s})),t),r.encode=e=>Ct(e,r.codec()),r.decode=e=>kt(e,r.codec())})(Xe||(Xe={}));var oe;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),We.codec().encode(e.wantlist,n)),e.blocks!=null)for(let o of e.blocks)n.uint32(26),Ge.codec().encode(o,n);if(e.blockPresences!=null)for(let o of e.blockPresences)n.uint32(34),Xe.codec().encode(o,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={blocks:[],blockPresences:[],pendingBytes:0},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let i=e.uint32();switch(i>>>3){case 1:{s.wantlist=We.codec().decode(e,e.uint32());break}case 3:{s.blocks.push(Ge.codec().decode(e,e.uint32()));break}case 4:{s.blockPresences.push(Xe.codec().decode(e,e.uint32()));break}case 5:{s.pendingBytes=e.int32();break}default:{e.skipType(i&7);break}}}return s})),t),r.encode=e=>Ct(e,r.codec()),r.decode=e=>kt(e,r.codec())})(oe||(oe={}));Fs.default.formatters.B=r=>r==null?"undefined":JSON.stringify({blocks:r.blocks?.map(t=>({data:`${D(t.data,"base64").substring(0,10)}...`,prefix:D(t.prefix,"base64")})),blockPresences:r.blockPresences?.map(t=>({...t,cid:U.decode(t.cid).toString()})),wantlist:r.wantlist==null?void 0:{full:r.wantlist.full,entries:r.wantlist.entries.map(t=>({...t,cid:U.decode(t.cid).toString()}))}},null,2);var Qe=class extends it{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;messageSendTimeout;runOnTransientConnections;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[re],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??5e3,this.messageSendTimeout=e.messageSendTimeout??5e3,this.runOnTransientConnections=e.runOnTransientConnections??!1,this.metrics={blocksSent:t.libp2p.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.libp2p.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Ie({concurrency:e.messageSendConcurrency??50,metrics:t.libp2p.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail: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=[]}}_onStream(t){if(!this.running)return;let{stream:e,connection:n}=t;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,n.remotePeer);let s=()=>{e.abort(new H("Incoming Bitswap stream timed out","ERR_TIMEOUT"))},o=AbortSignal.timeout(this.messageReceiveTimeout);G(1/0,o),o.addEventListener("abort",s),await Yt(e,i=>Jt(i),async i=>{for await(let c of i)try{let l=oe.decode(c);this.log("incoming new bitswap %s message from %p %B",e.protocol,n.remotePeer,l),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:l}}),o.removeEventListener("abort",s),o=AbortSignal.timeout(this.messageReceiveTimeout),G(1/0,o),o.addEventListener("abort",s)}catch(l){this.log.error("error reading incoming bitswap message from %p",n.remotePeer,l),e.abort(l);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new ct("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnTransientConnection:this.runOnTransientConnections})&&(yield n)}async findAndConnect(t,e){await yr(Kt(ns(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s={wantlist:{full:e.wantlist?.full??!1,entries:e.wantlist?.entries??[]},blocks:e.blocks??[],blockPresences:e.blockPresences??[],pendingBytes:e.pendingBytes??0},o=AbortSignal.timeout(this.messageSendTimeout),i=Ee([o,n?.signal]);G(1/0,o,i);try{let c=this.sendQueue.queue.find(l=>t.equals(l.options.peerId)&&l.status==="queued");if(c!=null){c.options.message=Oa(c.options.message,s),await c.join({signal:i});return}await this.sendQueue.add(async l=>{let u=l?.message;if(u==null)throw new H("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p %B",t,u),l?.onProgress?.(new ct("bitswap:network:send-wantlist",t));let h=await this.libp2p.dialProtocol(t,re,l);try{let f=Zn(h);await f.write(oe.encode(u),l),await f.unwrap().close(l)}catch(f){l?.onProgress?.(new ct("bitswap:network:send-wantlist:error",{peer:t,error:f})),this.log.error("error sending message to %p",t,f),h.abort(f)}this._updateSentStats(u.blocks)},{peerId:t,signal:i,message:s})}finally{i.clear()}}async connectTo(t,e){if(!this.running)throw new H("Network isn't running","ERR_NOT_STARTED");e?.onProgress?.(new ct("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),st(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(re))return!0;throw new H(`${t} did not support ${re}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);return n}_updateSentStats(t=[]){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.length)}};function Oa(r,t){let e=new Map((r.wantlist?.entries??[]).map(i=>[at.encode(i.cid),i]));for(let i of t.wantlist?.entries??[]){let c=at.encode(i.cid),l=e.get(c);l!=null&&(l.priority>i.priority&&(i.priority=l.priority),i.cancel=i.cancel??l.cancel,i.wantType=i.wantType??l.wantType,i.sendDontHave=i.sendDontHave??l.sendDontHave),e.set(c,i)}let n=new Map(r.blockPresences.map(i=>[at.encode(i.cid),i]));for(let i of t.blockPresences){let c=at.encode(i.cid);n.set(c,i)}let s=new Map(r.blocks.map(i=>[at.encode(i.data),i]));for(let i of t.blocks){let c=at.encode(i.data);s.set(c,i)}return{wantlist:{full:r.wantlist?.full??t.wantlist?.full??!1,entries:[...e.values()]},blockPresences:[...n.values()],blocks:[...s.values()],pendingBytes:r.pendingBytes+t.pendingBytes}}var $a=Symbol.for("nodejs.util.inspect.custom"),Ps=Object.values(gt).map(r=>r.decoder).reduce((r,t)=>r.or(t),gt.identity.decoder),Rs=114,Ns=36,Us=37,ie=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[On]=!0;toString(){return this.string==null&&(this.string=N.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return U.createV1(Rs,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return et(this.multihash.bytes,t);if(typeof t=="string")return ue(t).equals(this);if(t?.multihash?.bytes!=null)return et(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[$a](){return`PeerId(${this.toString()})`}},ae=class extends ie{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},ce=class extends ie{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},le=class extends ie{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}};function ue(r,t){if(t=t??Ps,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=vt(N.decode(`z${r}`));return r.startsWith("12D")?new ce({multihash:e}):r.startsWith("16U")?new le({multihash:e}):new ae({multihash:e})}return Va(Ps.decode(r))}function Va(r){try{let t=vt(r);if(t.code===Be.code){if(t.digest.length===Ns)return new ce({multihash:t});if(t.digest.length===Us)return new le({multihash:t})}if(t.code===St.code)return new ae({multihash:t})}catch{return za(U.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function za(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Rs)throw new Error("Supplied PeerID CID is invalid");let t=r.multihash;if(t.code===St.code)return new ae({multihash:r.multihash});if(t.code===Be.code){if(t.digest.length===Ns)return new ce({multihash:r.multihash});if(t.digest.length===Us)return new le({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function fn(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var fe=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return fn(this.map.entries(),t=>[ue(t[0]),t[1]])}forEach(t){this.map.forEach((e,n)=>{t(e,ue(n),this)})}get(t){return this.map.get(t.toString())}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),e)}keys(){return fn(this.map.keys(),t=>ue(t))}values(){return this.map.values()}get size(){return this.map.size}};var hn=class extends fe{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 he(r){let{name:t,metrics:e}=r,n;return e!=null?n=new hn({name:t,metrics:e}):n=new fe,n}function Ha(r){let t=new Uint8Array(r.reduce((n,s)=>n+_(s),0)),e=0;for(let n of r)t=Z(n,t,e),e+=_(n);return t}var Ms=Ha;function dn(r){return Ms([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Je=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(t){let e={blockPresences:[],blocks:[]},n=new Set;for(let[s,o]of this.wants.entries()){if(!await this.blockstore.has(o.cid,t)){if(!o.sendDontHave||o.sentDontHave===!0)continue;o.sentDontHave=!0,e.blockPresences.push({cid:o.cid.bytes,type:rt.DontHaveBlock});continue}let c=await this.blockstore.get(o.cid,t);o.wantType===P.WantHave?c.byteLength<this.maxSizeReplaceHasWithBlock?(n.add(s),e.blocks.push({data:c,prefix:dn(o.cid)})):e.blockPresences.push({cid:o.cid.bytes,type:rt.HaveBlock}):(n.add(s),e.blocks.push({data:c,prefix:dn(o.cid)}))}if(e.blocks.length>0||e.blockPresences.length>0){await this.network.sendMessage(this.peerId,e,t),this.sentBytes(e.blocks.reduce((s,o)=>s+o.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var Ke=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.ledgerMap=he({name:"helia_bitswap_ledger_map",metrics:t.libp2p.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return[...e.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);if(n==null&&(n=new Je({peerId:t,blockstore:this.blockstore,network:this.network},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let o=U.decode(s.cid),i=D(o.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,o),n.wants.delete(i)):(s.wantType===P.WantHave?this.log("peer %p wanted block presence for %c",t,o):this.log("peer %p wanted block for %c",t,o),n.wants.set(i,{cid:o,priority:s.priority,wantType:s.wantType??P.WantBlock,sendDontHave:s.sendDontHave??!1}))}}await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=D(t.multihash.bytes,"base64"),s=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&s.push(o);await Promise.all(s.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var Ga=Xt(Os(),1);var Ht;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ht||(Ht={}));function ja(r){return r[Symbol.asyncIterator]!=null}function Xa(r,t){if(ja(r))return async function*(){for await(let c of r)await t(c)&&(yield c)}();let e=Ue(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let o=t(n);if(typeof o.then=="function")return async function*(){await o&&(yield n);for await(let c of e)await t(c)&&(yield c)}();let i=t;return function*(){o===!0&&(yield n);for(let c of e)i(c)&&(yield c)}()}var pn=Xa;var Ye=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var rd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var nd={}.toString;function $s(r=32){if(Ye&&typeof Ye.getRandomValues=="function")return Ye.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Ze(r){if(isNaN(r)||r<=0)throw new H("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return $s(r)}var mn=Xt(Hs(),1);var Qa=Math.LN2*Math.LN2,er=class r{static create(t,e=.005){let n=Ja(t,e);return new r(n)}seeds;bits;buffer;constructor(t={}){t.seeds!=null?this.seeds=t.seeds:this.seeds=Ka(t.hashes??8),this.bits=t.bits??1024,this.buffer=O(Math.ceil(this.bits/8))}add(t){typeof t=="string"&&(t=bt(t));for(let e=0;e<this.seeds.length;e++){let s=mn.default.x86.hash32(t,this.seeds[e])%this.bits;this.setbit(s)}}has(t){typeof t=="string"&&(t=bt(t));for(let e=0;e<this.seeds.length;e++){let s=mn.default.x86.hash32(t,this.seeds[e])%this.bits;if(!this.getbit(s))return!1}return!0}clear(){this.buffer.fill(0)}setbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;let s=this.buffer[e];s|=1<<n,this.buffer[e]=s}getbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;return(this.buffer[e]&1<<n)!==0}};function Ja(r,t=.005){let e=Math.round(-1*r*Math.log(t)/Qa),n=Math.round(e/r*Math.LN2);return{bits:e,hashes:n}}function Ka(r){let t,e,n=[];for(let s=0;s<r;s++)for(t=new q(Ze(4)),n[s]=t.getUint32(0,!0),e=0;e<s;e++)if(n[s]===n[e]){s--;break}return n}var Tt=class extends it{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(t,e){super(),G(1/0,this),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=er.create(this.maxProviders)}async retrieve(t,e={}){let n=at.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let o=B();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.intialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.intialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.intialPeerSearchComplete,u&&this.log("found initial session peers for %c",t)}let i=!1,c=new Pt({concurrency:this.maxProviders});c.addEventListener("error",()=>{}),c.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),c.addEventListener("success",u=>{i=!0,o.resolve(u.detail.result)}),c.addEventListener("idle",()=>{i||e.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c",t,u),o.reject(u)})});let l=u=>{c.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,h)})};this.addEventListener("provider",l),Promise.all([...this.providers].map(async u=>c.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,u)});try{return await o.promise}finally{this.removeEventListener("provider",l),c.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.providers.some(e=>this.equals(e,t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let s=B(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t);for await(let i of this.findNewProviders(t,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<e)throw new H(`Found ${o} of ${e} ${this.name} providers for ${t}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",t,i.errors??i),s.reject(i)}),s.promise}};var gn=class extends Tt{wantList;network;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield n.id}toEvictionKey(t){return t.toBytes()}equals(t,e){return t.equals(e)}};function qs(r,t){return new gn(r,t)}var rr=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.libp2p.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.libp2p.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.libp2p.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.libp2p.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};var wn=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 Ws(r){let{name:t,metrics:e}=r,n;return e!=null?n=new wn({name:t,metrics:e}):n=new Map,n}function Ya(r){return r[Symbol.asyncIterator]!=null}function Za(r){if(Ya(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var bn=Za;function tc(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=Q(r);t.push(e),r=r.slice(_(e))}return t}var Gs=tc;var nr=class extends it{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),G(1/0,this),this.peers=he({name:"helia_bitswap_peers",metrics:t.libp2p.metrics}),this.wants=Ws({name:"helia_bitswap_wantlist",metrics:t.libp2p.metrics}),this.network=t.network,this.sendMessagesDelay=e.sendMessagesDelay??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=e.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=D(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??P.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===P.WantHave&&e.wantType===P.WantBlock&&(s.wantType=P.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===P.WantBlock?(await st(this,"block",e?.signal,{filter:c=>et(t.multihash.digest,c.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await st(this,"presence",e?.signal,{filter:i=>et(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers",t)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=B(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s={wantlist:{full:!1,entries:Yt(this.wants.entries(),o=>pn(o,([i,c])=>{let l=e.has(i);return c.cancel?l:!l}),o=>Kt(o,([i,c])=>(n.add(i),{cid:c.cid.bytes,priority:c.priority,wantType:c.wantType,cancel:c.cancel,sendDontHave:c.sendDontHave})),o=>bn(o))}};if(s.wantlist?.entries.length!==0)try{await this.network.sendMessage(t,s);for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer",o)}})).catch(t=>{this.log.error("error sending messages",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=D(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){return await this.network.sendMessage(e,{wantlist:{full:!1,entries:[{cid:t.bytes,sendDontHave:!0,wantType:P.WantHave,priority:1}]}}),(await st(this,"presence",n.signal,{filter:o=>e.equals(o.detail.sender)&&et(t.multihash.digest,o.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:P.WantBlock})}async wantSessionBlock(t,e,n={}){return await this.network.sendMessage(e,{wantlist:{full:!1,entries:[{cid:t.bytes,sendDontHave:!0,wantType:P.WantBlock,priority:1}]}}),(await st(this,"presence",n.signal,{filter:o=>e.equals(o.detail.sender)&&et(t.multihash.digest,o.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=D(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p",t);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=Gs(s.prefix),i=o[0],c=o[1],l=o[2],u=l===St.code?St:await this.hashLoader?.getHasher(l);if(u==null){this.log.error("unknown hash algorithm",l);continue}let h=await u.digest(s.data),f=U.create(i===0?0:1,c,h);this.log("received block from %p for %c",t,f),this.safeDispatchEvent("block",{detail:{sender:t,cid:f,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:f,has:!0,block:s.data}});let w=D(f.multihash.bytes,"base64"),a=this.wants.get(w);if(a==null)return;a.cancel=!0,n=!0}for(let{cid:s,type:o}of e.blockPresences){let i=U.decode(s);this.log("received %s from %p for %c",o,t,i),this.safeDispatchEvent("presence",{detail:{sender:t,cid:i,has:o===rt.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n={wantlist:{full:!0,entries:Yt(this.wants.entries(),s=>pn(s,([o,i])=>!i.cancel),s=>Kt(s,([o,i])=>(e.add(o),{cid:i.cid.bytes,priority:1,wantType:P.WantBlock,cancel:!1,sendDontHave:!1})),s=>bn(s))}};if(n.wantlist?.entries.length===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var sr=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.stats=new rr(t),this.network=new Qe(t,e),this.peerWantLists=new Ke({...t,network:this.network},e),this.wantList=new nr({...t,network:this.network},e)}createSession(t={}){return qs({wantList:this.wantList,network:this.network,logger:this.logger},t)}async want(t,e={}){let n=new AbortController,s=Ee([n.signal,e.signal]);G(1/0,n.signal,s),this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,o)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await Promise.all([this.peerWantLists.receivedBlock(t,n),this.wantList.receivedBlock(t,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var js=(r,t={})=>new sr(r,t);var yn=class{bitswap;started;constructor(t,e={}){let{hashers:n}=t;this.bitswap=js(t,{hashLoader:{getHasher:async s=>{let o;if(typeof s=="string"?o=Object.values(n).find(i=>i.name===s):o=n[s],o!=null)return o;throw new Error(`Could not load hasher for code/name "${s}"`)}},...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){await this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}createSession(t){let e=this.bitswap.createSession(t);return{announce:async(n,s,o)=>{await this.bitswap.notify(n,s,o)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function Xs(r={}){return t=>new yn(t,r)}var or=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 o=0,i=0,c=this.peekChar();if(c===void 0)return;let l=c==="0",u=2**(8*s)-1;for(;;){let h=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let w=Number.parseInt(f,t);if(!Number.isNaN(w))return w});if(h===void 0)break;if(o*=t,o+=h,o>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&l&&i>1?void 0:o})}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 i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&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 o=new Uint8Array(14),i=16-(n+2),[c]=t(o.subarray(0,i));return e.set(o.subarray(0,c),16-c),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Qs=45,ec=15,qt=new or;function xn(r){if(!(r.length>ec))return qt.new(r).parseWith(()=>qt.readIPv4Addr())}function vn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Qs))return qt.new(r).parseWith(()=>qt.readIPv6Addr())}function ir(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Qs))return qt.new(r).parseWith(()=>qt.readIPAddr())}function Wt(r){return!!xn(r)}function Gt(r){return!!vn(r)}function ar(r){return!!ir(r)}var Ks=Xt(Js(),1),rc=["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"],nc=rc.map(r=>new Ks.Netmask(r));function sc(r){for(let t of nc)if(t.contains(r))return!0;return!1}function oc(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 Ys(r){return Wt(r)?sc(r):Gt(r)?oc(r):void 0}var Lp=parseInt("0xFFFF",16),Cp=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var eo=Wt,uc=Gt,En=function(r){let t=0;if(r=r.toString().trim(),eo(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(uc(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=eo(e[n]),i;o&&(i=En(e[n]),e[n]=D(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,D(i.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 o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let o=parseInt(e[n],16);s[t++]=o>>8&255,s[t++]=o&255}return s}throw new Error("invalid ip address")},ro=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 o=0;o<e;o++)s.push(r[t+o]);return s.join(".")}if(e===16){let s=[];for(let o=0;o<e;o+=2)s.push(n.getUint16(t+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var jt={},Sn={},hc=[[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"]];hc.forEach(r=>{let t=dc(...r);Sn[t.code]=t,jt[t.name]=t});function dc(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function S(r){if(typeof r=="number"){if(Sn[r]!=null)return Sn[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(jt[r]!=null)return jt[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var cm=S("ip4"),lm=S("ip6"),um=S("ipcidr");function kn(r,t){switch(S(r).code){case 4:case 41:return mc(t);case 42:return oo(t);case 6:case 273:case 33:case 132:return ao(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return oo(t);case 421:return yc(t);case 444:return io(t);case 445:return io(t);case 466:return bc(t);default:return D(t,"base16")}}function Ln(r,t){switch(S(r).code){case 4:return no(t);case 41:return no(t);case 42:return so(t);case 6:case 273:case 33:case 132:return Cn(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return so(t);case 421:return gc(t);case 444:return xc(t);case 445:return vc(t);case 466:return wc(t);default:return bt(t,"base16")}}var An=Object.values(gt).map(r=>r.decoder),pc=function(){let r=An[0].or(An[1]);return An.slice(2).forEach(t=>r=r.or(t)),r}();function no(r){if(!ar(r))throw new Error("invalid ip address");return En(r)}function mc(r){let t=ro(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ar(t))throw new Error("invalid ip address");return t}function Cn(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function ao(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function so(r){let t=bt(r),e=Uint8Array.from(Z(t.length));return tt([e,t],e.length+t.length)}function oo(r){let t=Q(r);if(r=r.slice(_(t)),r.length!==t)throw new Error("inconsistent lengths");return D(r)}function gc(r){let t;r[0]==="Q"||r[0]==="1"?t=vt(N.decode(`z${r}`)).bytes:t=U.parse(r).multihash.bytes;let e=Uint8Array.from(Z(t.length));return tt([e,t],e.length+t.length)}function wc(r){let t=pc.decode(r),e=Uint8Array.from(Z(t.length));return tt([e,t],e.length+t.length)}function bc(r){let t=Q(r),e=r.slice(_(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+D(e,"base64url")}function yc(r){let t=Q(r),e=r.slice(_(t));if(e.length!==t)throw new Error("inconsistent lengths");return D(e,"base58btc")}function xc(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=ft.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=Cn(n);return tt([e,s],e.length+s.length)}function vc(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=ft.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=Cn(n);return tt([e,s],e.length+s.length)}function io(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=D(t,"base32"),s=ao(e);return`${n}:${s}`}function co(r){r=In(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 o=0;o<s.length;o++){let i=s[o],c=S(i);if(c.size===0){t.push([c.code]),e.push([c.code]);continue}if(o++,o>=s.length)throw uo("invalid address: "+r);if(c.path===!0){n=In(s.slice(o).join("/")),t.push([c.code,Ln(c.code,n)]),e.push([c.code,n]);break}let l=Ln(c.code,s[o]);t.push([c.code,l]),e.push([c.code,kn(c.code,l)])}return{string:lo(e),bytes:Dn(t),tuples:t,stringTuples:e,path:n}}function Tn(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let o=Q(r,s),i=_(o),c=S(o),l=Ec(c,r.slice(s+i));if(l===0){t.push([o]),e.push([o]),s+=i;continue}let u=r.slice(s+i,s+i+l);if(s+=l+i,s>r.length)throw uo("Invalid address Uint8Array: "+D(r,"base16"));t.push([o,u]);let h=kn(o,u);if(e.push([o,h]),c.path===!0){n=h;break}}return{bytes:Uint8Array.from(r),string:lo(e),tuples:t,stringTuples:e,path:n}}function lo(r){let t=[];return r.map(e=>{let n=S(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),In(t.join("/"))}function Dn(r){return tt(r.map(t=>{let e=S(t[0]),n=Uint8Array.from(Z(e.code));return t.length>1&&t[1]!=null&&(n=tt([n,t[1]])),n}))}function Ec(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Q(t instanceof Uint8Array?t:Uint8Array.from(t));return e+_(e)}}function In(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function uo(r){return new Error("Error parsing address: "+r)}var Sc=Symbol.for("nodejs.util.inspect.custom"),_n=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Ac=[S("dns").code,S("dns4").code,S("dns6").code,S("dnsaddr").code],cr=class r{bytes;#t;#e;#r;#n;[_n]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Tn(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=co(t)}else if(ho(t))e=Tn(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,o="",i=S("tcp"),c=S("udp"),l=S("ip4"),u=S("ip6"),h=S("dns6"),f=S("ip6zone");for(let[a,d]of this.stringTuples())a===f.code&&(o=`%${d??""}`),Ac.includes(a)&&(e=i.name,s=443,n=`${d??""}${o}`,t=a===h.code?6:4),(a===i.code||a===c.code)&&(e=S(a).name,s=parseInt(d??"")),(a===l.code||a===u.code)&&(e=S(a).name,n=`${d??""}${o}`,t=a===u.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({},S(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>S(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(Dn(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===jt.p2p.code&&t.push([n,s]),n===jt["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?D(N.decode(`z${n}`),"base58btc"):D(U.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return et(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(o=>o.resolvable);if(e==null)return[this];let n=fo.get(e.name);if(n==null)throw new H(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(o=>me(o))}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)}[Sc](){return`Multiaddr(${this.#t})`}};var fo=new Map;function ho(r){return!!r?.[_n]}function me(r){return new cr(r)}var kc=r=>r.toString().split("/").slice(1),ge=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),C=r=>({match:t=>ge(e=>e===r).match(t),pattern:r}),fr=()=>({match:r=>ge(t=>typeof t=="string").match(r),pattern:"{string}"}),hr=()=>({match:r=>ge(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),M=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{N.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),lr=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Rr.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),W=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),K=(...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(", ")})`}),T=(...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 R(...r){function t(s){let o=kc(s);for(let i of r){let c=i.match(o);if(c===!1)return!1;o=c}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matches:e,exactMatch:n}}var Pn=T(C("dns4"),fr()),Rn=T(C("dns6"),fr()),Nn=T(C("dnsaddr"),fr()),po=T(C("dns"),fr()),Om=R(Pn),$m=R(Rn),Vm=R(Nn),mo=R(K(po,Nn,Pn,Rn)),go=T(C("ip4"),ge(Wt)),wo=T(C("ip6"),ge(Gt)),bo=K(go,wo),lt=K(bo,po,Pn,Rn,Nn),zm=R(lt),Hm=R(go),qm=R(wo),Wm=R(bo),dr=T(lt,C("tcp"),hr()),we=T(lt,C("udp"),hr()),Lc=K(dr,we),Gm=R(dr),jm=R(we),Un=T(we,C("quic")),pr=T(we,C("quic-v1")),Cc=K(Un,pr),Xm=R(Un),Qm=R(pr),Fn=K(lt,dr,we,Un,pr),yo=K(T(Fn,C("ws"),W(M()))),Jm=R(yo),xo=K(T(Fn,C("wss"),W(M())),T(Fn,C("tls"),C("ws"),W(M()))),Km=R(xo),vo=T(Lc,C("webrtc-direct"),lr(),W(lr()),W(M())),Ym=R(vo),Eo=T(pr,C("webtransport"),lr(),lr(),W(M())),Zm=R(Eo),ur=K(yo,xo,T(dr,W(M())),T(Cc,W(M())),T(lt,W(M())),vo,Eo,M()),tg=R(ur),Ic=T(ur,C("p2p-circuit"),M()),eg=R(Ic),Tc=K(T(ur,C("p2p-circuit"),C("webrtc"),M()),T(ur,C("webrtc"),W(M())),C("webrtc")),rg=R(Tc),Dc=K(T(lt,C("tcp"),hr(),C("http"),W(M())),T(lt,C("http"),W(M()))),So=R(Dc),_c=K(T(lt,C("tcp"),K(T(C("443"),C("http")),T(hr(),C("https"))),W(M())),T(lt,C("tls"),C("http"),W(M())),T(lt,C("https"),W(M()))),Ao=R(_c);var Fc=[S("tcp").code,S("dns").code,S("dnsaddr").code,S("dns4").code,S("dns6").code];function ko(r){let t;try{t=S("sni").code}catch{return null}for(let[e,n]of r)if(e===t&&n!==void 0)return n;return null}function Lo(r){return r.some(([t,e])=>t===S("tls").code)}function Y(r,t,e){let n=Co[S(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${S(r).name}`);let s=n(t,e);return r===S("ip6").code?`[${s}]`:s}var Co={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://${Y(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://${Y(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`${Y(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`${Y(e[0],e[1]??"",t)}/p2p/${r}`},http:(r,t)=>{let e=Lo(t),n=ko(t);if(e&&n!==null)return`https://${n}`;let s=e?"https://":"http://",o=t.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=Y(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},tls:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return Y(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return Y(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=Y(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Lo(t),n=ko(t);if(e&&n!==null)return`wss://${n}`;let s=e?"wss://":"ws://",o=t.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=Y(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},wss:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=Y(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`${Y(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`${Y(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`${Y(e[0],e[1]??"",t)}/p2p-webrtc-direct`}};function Io(r,t){let n=me(r).stringTuples(),s=n.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=S(s[0]),i=Co[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let c=i(s[1]??"",n);return t?.assumeHttp!==!1&&Fc.includes(s[0])&&(c=c.replace(/^.*:\/\//,""),s[1]==="443"?c=`https://${c}`:c=`http://${c}`),(c.startsWith("http://")||c.startsWith("https://"))&&(c=new URL(c).toString(),c.endsWith("/")&&(c=c.substring(0,c.length-1))),c}var Dt=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=new URL(this.url.toString());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 Pc=!1,Rc=!1,Mn=class extends Tt{routing;allowInsecure;allowLocal;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Pc,this.allowLocal=e.allowLocal??Rc}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let s=await e.getRawBlock(t,n.signal);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(s),s}async*findNewProviders(t,e={}){for await(let n of this.routing.findProviders(t,e)){let s=Nc(n.multiaddrs,this.allowInsecure,this.allowLocal);if(s.length===0)continue;let o=Io(s[0]);this.log("found http-gateway provider %p %s for cid %c",n.id,o,t),yield new Dt(o,this.logger)}}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}};function Nc(r,t,e){return r.filter(n=>Ao.matches(n)||t&&So.matches(n)?e||mo.matches(n)?!0:Ys(n.toOptions().host)===!1:!1)}function To(r,t){return new Mn(r,t)}var mr=class{components;gateways;routing;log;logger;constructor(t,e={}){this.components=t,this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.gateways=(e.gateways??Do).map(n=>new Dt(n,t.logger))}addGateway(t){this.gateways.push(new Dt(t,this.components.logger))}async retrieve(t,e={}){let n=this.gateways.sort((o,i)=>i.reliability()-o.reliability()),s=[];for(let o of n){this.log("getting block for %c from %s",t,o.url);try{let i=await o.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(i)}catch(c){throw this.log.error("failed to validate block for %c from %s",t,o.url,c),o.incrementInvalidBlocks(),new Error(`Block for CID ${t} from gateway ${o.url} failed validation`)}return i}catch(i){if(this.log.error("failed to get block for %c from %s",t,o.url,i),i instanceof Error?s.push(i):s.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.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`)}createSession(t={}){return To({logger:this.logger,routing:this.routing},t)}};var Do=["https://trustless-gateway.link","https://cloudflare-ipfs.com","https://4everland.io"];function _o(r={}){return t=>new mr(t,r)}return Mo(Uc);})();
|
|
2
|
+
"use strict";var HeliaBlockBrokers=(()=>{var wo=Object.create;var be=Object.defineProperty;var bo=Object.getOwnPropertyDescriptor;var yo=Object.getOwnPropertyNames;var xo=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty;var Qt=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),q=(r,t)=>{for(var e in t)be(r,e,{get:t[e],enumerable:!0})},_n=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yo(t))!Eo.call(r,s)&&s!==e&&be(r,s,{get:()=>t[s],enumerable:!(n=bo(t,s))||n.enumerable});return r};var ye=(r,t,e)=>(e=r!=null?wo(xo(r)):{},_n(t||!r||!r.__esModule?be(e,"default",{value:r,enumerable:!0}):e,r)),vo=r=>_n(be({},"__esModule",{value:!0}),r);var Fn=Qt((al,Nn)=>{"use strict";function Un(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function Co(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 Un(r,e)}catch{e.message=r.message,e.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Un(new s,e)}}Nn.exports=Co});var ks=Qt((of,Ss)=>{Ss.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Ls=Qt((ue,We)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(a){if(!Array.isArray(a)&&!ArrayBuffer.isView(a))return!1;for(var h=0;h<a.length;h++)if(!Number.isInteger(a[h])||a[h]<0||a[h]>255)return!1;return!0}function s(a,h){return(a&65535)*h+(((a>>>16)*h&65535)<<16)}function o(a,h){return a<<h|a>>>32-h}function i(a){return a^=a>>>16,a=s(a,2246822507),a^=a>>>13,a=s(a,3266489909),a^=a>>>16,a}function c(a,h){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var p=[0,0,0,0];return p[3]+=a[3]+h[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=a[2]+h[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=a[1]+h[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=a[0]+h[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function u(a,h){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var p=[0,0,0,0];return p[3]+=a[3]*h[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=a[2]*h[3],p[1]+=p[2]>>>16,p[2]&=65535,p[2]+=a[3]*h[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=a[1]*h[3],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=a[2]*h[2],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=a[3]*h[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=a[0]*h[3]+a[1]*h[2]+a[2]*h[1]+a[3]*h[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function l(a,h){return h%=64,h===32?[a[1],a[0]]:h<32?[a[0]<<h|a[1]>>>32-h,a[1]<<h|a[0]>>>32-h]:(h-=32,[a[1]<<h|a[0]>>>32-h,a[0]<<h|a[1]>>>32-h])}function d(a,h){return h%=64,h===0?a:h<32?[a[0]<<h|a[1]>>>32-h,a[1]<<h]:[a[1]<<h-32,0]}function f(a,h){return[a[0]^h[0],a[1]^h[1]]}function x(a){return a=f(a,[0,a[0]>>>1]),a=u(a,[4283543511,3981806797]),a=f(a,[0,a[0]>>>1]),a=u(a,[3301882366,444984403]),a=f(a,[0,a[0]>>>1]),a}e.x86.hash32=function(a,h){if(e.inputValidation&&!n(a))return t;h=h||0;for(var p=a.length%4,v=a.length-p,m=h,g=0,w=3432918353,y=461845907,E=0;E<v;E=E+4)g=a[E]|a[E+1]<<8|a[E+2]<<16|a[E+3]<<24,g=s(g,w),g=o(g,15),g=s(g,y),m^=g,m=o(m,13),m=s(m,5)+3864292196;switch(g=0,p){case 3:g^=a[E+2]<<16;case 2:g^=a[E+1]<<8;case 1:g^=a[E],g=s(g,w),g=o(g,15),g=s(g,y),m^=g}return m^=a.length,m=i(m),m>>>0},e.x86.hash128=function(a,h){if(e.inputValidation&&!n(a))return t;h=h||0;for(var p=a.length%16,v=a.length-p,m=h,g=h,w=h,y=h,E=0,k=0,b=0,T=0,at=597399067,me=2869860233,ge=951274213,we=2716044179,A=0;A<v;A=A+16)E=a[A]|a[A+1]<<8|a[A+2]<<16|a[A+3]<<24,k=a[A+4]|a[A+5]<<8|a[A+6]<<16|a[A+7]<<24,b=a[A+8]|a[A+9]<<8|a[A+10]<<16|a[A+11]<<24,T=a[A+12]|a[A+13]<<8|a[A+14]<<16|a[A+15]<<24,E=s(E,at),E=o(E,15),E=s(E,me),m^=E,m=o(m,19),m+=g,m=s(m,5)+1444728091,k=s(k,me),k=o(k,16),k=s(k,ge),g^=k,g=o(g,17),g+=w,g=s(g,5)+197830471,b=s(b,ge),b=o(b,17),b=s(b,we),w^=b,w=o(w,15),w+=y,w=s(w,5)+2530024501,T=s(T,we),T=o(T,18),T=s(T,at),y^=T,y=o(y,13),y+=m,y=s(y,5)+850148119;switch(E=0,k=0,b=0,T=0,p){case 15:T^=a[A+14]<<16;case 14:T^=a[A+13]<<8;case 13:T^=a[A+12],T=s(T,we),T=o(T,18),T=s(T,at),y^=T;case 12:b^=a[A+11]<<24;case 11:b^=a[A+10]<<16;case 10:b^=a[A+9]<<8;case 9:b^=a[A+8],b=s(b,ge),b=o(b,17),b=s(b,we),w^=b;case 8:k^=a[A+7]<<24;case 7:k^=a[A+6]<<16;case 6:k^=a[A+5]<<8;case 5:k^=a[A+4],k=s(k,me),k=o(k,16),k=s(k,ge),g^=k;case 4:E^=a[A+3]<<24;case 3:E^=a[A+2]<<16;case 2:E^=a[A+1]<<8;case 1:E^=a[A],E=s(E,at),E=o(E,15),E=s(E,me),m^=E}return m^=a.length,g^=a.length,w^=a.length,y^=a.length,m+=g,m+=w,m+=y,g+=m,w+=m,y+=m,m=i(m),g=i(g),w=i(w),y=i(y),m+=g,m+=w,m+=y,g+=m,w+=m,y+=m,("00000000"+(m>>>0).toString(16)).slice(-8)+("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(y>>>0).toString(16)).slice(-8)},e.x64.hash128=function(a,h){if(e.inputValidation&&!n(a))return t;h=h||0;for(var p=a.length%16,v=a.length-p,m=[0,h],g=[0,h],w=[0,0],y=[0,0],E=[2277735313,289559509],k=[1291169091,658871167],b=0;b<v;b=b+16)w=[a[b+4]|a[b+5]<<8|a[b+6]<<16|a[b+7]<<24,a[b]|a[b+1]<<8|a[b+2]<<16|a[b+3]<<24],y=[a[b+12]|a[b+13]<<8|a[b+14]<<16|a[b+15]<<24,a[b+8]|a[b+9]<<8|a[b+10]<<16|a[b+11]<<24],w=u(w,E),w=l(w,31),w=u(w,k),m=f(m,w),m=l(m,27),m=c(m,g),m=c(u(m,[0,5]),[0,1390208809]),y=u(y,k),y=l(y,33),y=u(y,E),g=f(g,y),g=l(g,31),g=c(g,m),g=c(u(g,[0,5]),[0,944331445]);switch(w=[0,0],y=[0,0],p){case 15:y=f(y,d([0,a[b+14]],48));case 14:y=f(y,d([0,a[b+13]],40));case 13:y=f(y,d([0,a[b+12]],32));case 12:y=f(y,d([0,a[b+11]],24));case 11:y=f(y,d([0,a[b+10]],16));case 10:y=f(y,d([0,a[b+9]],8));case 9:y=f(y,[0,a[b+8]]),y=u(y,k),y=l(y,33),y=u(y,E),g=f(g,y);case 8:w=f(w,d([0,a[b+7]],56));case 7:w=f(w,d([0,a[b+6]],48));case 6:w=f(w,d([0,a[b+5]],40));case 5:w=f(w,d([0,a[b+4]],32));case 4:w=f(w,d([0,a[b+3]],24));case 3:w=f(w,d([0,a[b+2]],16));case 2:w=f(w,d([0,a[b+1]],8));case 1:w=f(w,[0,a[b]]),w=u(w,E),w=l(w,31),w=u(w,k),m=f(m,w)}return m=f(m,[0,a.length]),g=f(g,[0,a.length]),m=c(m,g),g=c(g,m),m=x(m),g=x(g),m=c(m,g),g=c(g,m),("00000000"+(m[0]>>>0).toString(16)).slice(-8)+("00000000"+(m[1]>>>0).toString(16)).slice(-8)+("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)},typeof ue<"u"?(typeof We<"u"&&We.exports&&(ue=We.exports=e),ue.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(ue)});var Ts=Qt((Mf,Is)=>{Is.exports=Ls()});var Us=Qt(he=>{(function(){var r,t,e,n,s,o,i,c;c=function(u){var l,d,f,x;return l=(u&255<<24)>>>24,d=(u&255<<16)>>>16,f=(u&65280)>>>8,x=u&255,[l,d,f,x].join(".")},i=function(u){var l,d,f,x,a,h;for(l=[],f=x=0;x<=3&&u.length!==0;f=++x){if(f>0){if(u[0]!==".")throw new Error("Invalid IP");u=u.substring(1)}h=t(u),a=h[0],d=h[1],u=u.substring(d),l.push(a)}if(u.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(u){return u.charCodeAt(0)},n=e("0"),o=e("a"),s=e("A"),t=function(u){var l,d,f,x,a;for(x=0,l=10,d="9",f=0,u.length>1&&u[f]==="0"&&(u[f+1]==="x"||u[f+1]==="X"?(f+=2,l=16):"0"<=u[f+1]&&u[f+1]<="9"&&(f++,l=8,d="7")),a=f;f<u.length;){if("0"<=u[f]&&u[f]<=d)x=x*l+(e(u[f])-n)>>>0;else if(l===16)if("a"<=u[f]&&u[f]<="f")x=x*l+(10+e(u[f])-o)>>>0;else if("A"<=u[f]&&u[f]<="F")x=x*l+(10+e(u[f])-s)>>>0;else break;else break;if(x>4294967295)throw new Error("too large");f++}if(f===a)throw new Error("empty octet");return[x,f]},r=function(){function u(l,d){var f,x,a,h;if(typeof l!="string")throw new Error("Missing `net' parameter");if(d||(h=l.split("/",2),l=h[0],d=h[1]),d||(d=32),typeof d=="string"&&d.indexOf(".")>-1){try{this.maskLong=i(d)}catch(p){throw f=p,new Error("Invalid mask: "+d)}for(x=a=32;a>=0;x=--a)if(this.maskLong===4294967295<<32-x>>>0){this.bitmask=x;break}}else if(d||d===0)this.bitmask=parseInt(d,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(p){throw f=p,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+d);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return u.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new u(l)),l instanceof u?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},u.prototype.next=function(l){return l==null&&(l=1),new u(c(this.netLong+this.size*l),this.mask)},u.prototype.forEach=function(l){var d,f,x;for(x=i(this.first),f=i(this.last),d=0;x<=f;)l(c(x),x,d),d++,x++},u.prototype.toString=function(){return this.base+"/"+this.bitmask},u}(),he.ip2long=i,he.long2ip=c,he.Netmask=r}).call(he)});var pc={};q(pc,{bitswap:()=>Ms,trustlessGateway:()=>go});var Dn=Symbol.for("@libp2p/peer-id");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"},N=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var W=(r,...t)=>{try{[...t]}catch{}};var nt=class extends EventTarget{#t=new Map;constructor(){super(),W(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:o})=>o!==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 So(t,e))}},ar=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},So=globalThis.CustomEvent??ar;function Pn(r){let t=new globalThis.AbortController;function e(){t.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function Y(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var xe=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 xe(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 xe(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 cr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Dt(r={}){return ko(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 ko(r,t){t=t??{};let e=t.onEnd,n=new _t,s,o,i,c=Y(),u=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((v,m)=>{o=g=>{o=null,n.push(g);try{v(r(n))}catch(w){m(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=Y()})}},l=v=>o!=null?o(v):(n.push(v),s),d=v=>(n=new _t,o!=null?o({error:v}):(n.push({error:v}),s)),f=v=>{if(i)return s;if(t?.objectMode!==!0&&v?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:v})},x=v=>i?s:(i=!0,v!=null?d(v):l({done:!0})),a=()=>(n=new _t,x(),{done:!0}),h=v=>(x(v),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:u,return:a,throw:h,push:f,end:x,get readableLength(){return n.size},onEmpty:async v=>{let m=v?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let g,w;m!=null&&(g=new Promise((y,E)=>{w=()=>{E(new cr)},m.addEventListener("abort",w)}));try{await Promise.race([c.promise,g])}finally{w!=null&&m!=null&&m?.removeEventListener("abort",w)}}},e==null)return s;let p=s;return s={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(v){return p.throw(v),e!=null&&(e(v),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(v){return p.end(v),e!=null&&(e(v),e=void 0),s},get readableLength(){return p.readableLength},onEmpty:v=>p.onEmpty(v)},s}var lr=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 tt(r,t,e,n){let s=new lr(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){r.removeEventListener(t,c),e?.removeEventListener("abort",u),i(d);return}r.removeEventListener(t,c),e?.removeEventListener("abort",u),o(l)},u=()=>{r.removeEventListener(t,c),e?.removeEventListener("abort",u),i(s)};r.addEventListener(t,c),e?.addEventListener("abort",u)})}var Ee=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 Rn(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Ee(e?.errorMessage,e?.errorCode));let n,s=new Ee(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(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=Y(),this.where=t,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ut)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ao(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Se=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(t,e,n=0){this.id=Ao(),this.status="queued",this.fn=t,this.priority=n,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,W(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),this.cleanup())}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 Rn(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.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};function Lo(r,t,e){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;e(r[i],t)<=0?(n=++i,s-=o+1):s=o}return n}var Pt=class extends nt{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=Lo(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 Se(t,e,e?.priority),s=n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});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 tt(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await tt(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await tt(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=Dt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),e.end(u)},s=u=>{u.detail!=null&&e.push(u.detail)},o=u=>{n(u.detail)},i=()=>{n()},c=()=>{n(new N("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",c);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",c),n()}}};var ke=class extends Pt{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Io(r){return r[Symbol.asyncIterator]!=null}function To(r){if(Io(r))return(async()=>{for await(let t of r);})();for(let t of r);}var ur=To;function B(r=0){return new Uint8Array(r)}function O(r=0){return new Uint8Array(r)}var _o=Math.pow(2,7),Do=Math.pow(2,14),Po=Math.pow(2,21),hr=Math.pow(2,28),fr=Math.pow(2,35),dr=Math.pow(2,42),pr=Math.pow(2,49),I=128,$=127;function D(r){if(r<_o)return 1;if(r<Do)return 2;if(r<Po)return 3;if(r<hr)return 4;if(r<fr)return 5;if(r<dr)return 6;if(r<pr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function mr(r,t,e=0){switch(D(r)){case 8:t[e++]=r&255|I,r/=128;case 7:t[e++]=r&255|I,r/=128;case 6:t[e++]=r&255|I,r/=128;case 5:t[e++]=r&255|I,r/=128;case 4:t[e++]=r&255|I,r>>>=7;case 3:t[e++]=r&255|I,r>>>=7;case 2:t[e++]=r&255|I,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Ro(r,t,e=0){switch(D(r)){case 8:t.set(e++,r&255|I),r/=128;case 7:t.set(e++,r&255|I),r/=128;case 6:t.set(e++,r&255|I),r/=128;case 5:t.set(e++,r&255|I),r/=128;case 4:t.set(e++,r&255|I),r>>>=7;case 3:t.set(e++,r&255|I),r>>>=7;case 2:t.set(e++,r&255|I),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function gr(r,t){let e=r[t],n=0;if(n+=e&$,e<I||(e=r[t+1],n+=(e&$)<<7,e<I)||(e=r[t+2],n+=(e&$)<<14,e<I)||(e=r[t+3],n+=(e&$)<<21,e<I)||(e=r[t+4],n+=(e&$)*hr,e<I)||(e=r[t+5],n+=(e&$)*fr,e<I)||(e=r[t+6],n+=(e&$)*dr,e<I)||(e=r[t+7],n+=(e&$)*pr,e<I))return n;throw new RangeError("Could not decode varint")}function Mo(r,t){let e=r.get(t),n=0;if(n+=e&$,e<I||(e=r.get(t+1),n+=(e&$)<<7,e<I)||(e=r.get(t+2),n+=(e&$)<<14,e<I)||(e=r.get(t+3),n+=(e&$)<<21,e<I)||(e=r.get(t+4),n+=(e&$)*hr,e<I)||(e=r.get(t+5),n+=(e&$)*fr,e<I)||(e=r.get(t+6),n+=(e&$)*dr,e<I)||(e=r.get(t+7),n+=(e&$)*pr,e<I))return n;throw new RangeError("Could not decode varint")}function st(r,t,e=0){return t==null&&(t=O(D(r))),t instanceof Uint8Array?mr(r,t,e):Ro(r,t,e)}function et(r,t=0){return r instanceof Uint8Array?gr(r,t):Mo(r,t)}function j(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=O(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function K(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 Cn=Symbol.for("@achingbrain/uint8arraylist");function Mn(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 Le(r){return!!r?.[Cn]}var ht=class r{bufs;length;[Cn]=!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(Le(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(Le(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=Mn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Mn(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(Le(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 j(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:j(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_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 o=0;o<this.bufs.length;o++){let i=this.bufs[o],c=s,u=c+i.byteLength;if(s=u,t>=u)continue;let l=t>=c&&t<u,d=e>c&&e<=u;if(l&&d){if(t===c&&e===u){n.push(i);break}let f=t-c;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-c));continue}if(d){if(e===u){n.push(i);break}n.push(i.subarray(0,e-c));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Le(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 o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let c=i,u=this.byteLength-n.byteLength,l=n.byteLength-1,d;for(let f=e;f<=u;f+=d){d=0;for(let x=l;x>=0;x--){let a=this.get(f+x);if(n[x]!==a){d=Math.max(1,x-c[a]);break}}if(d===0)return f}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=O(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=B(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=B(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=B(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=O(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=B(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=B(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=B(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=B(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=B(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(!K(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,o)=>s+o.byteLength,0)),n.length=e,n}};function Ie(r){return r[Symbol.asyncIterator]!=null}var Te=r=>{let t=D(r),e=O(t);return st(r,e),Te.bytes=t,e};Te.bytes=0;function _e(r,t){t=t??{};let e=t.lengthEncoder??Te;function*n(s){let o=e(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return Ie(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}_e.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Te;return new ht(e(r.byteLength),r)};var Rt=ye(Fn(),1);var Uo=8,No=1024*1024*4,wt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(wt||(wt={}));var wr=r=>{let t=et(r);return wr.bytes=D(t),t};wr.bytes=0;function jt(r,t){let e=new ht,n=wt.LENGTH,s=-1,o=t?.lengthDecoder??wr,i=t?.maxLengthLength??Uo,c=t?.maxDataLength??No;function*u(){for(;e.byteLength>0;){if(n===wt.LENGTH)try{if(s=o(e),s<0)throw(0,Rt.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,Rt.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=wt.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw(0,Rt.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===wt.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=wt.LENGTH}}}return Ie(r)?async function*(){for await(let l of r)e.append(l),yield*u();if(e.byteLength>0)throw(0,Rt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)e.append(l),yield*u();if(e.byteLength>0)throw(0,Rt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}jt.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}}();return jt(n,{...t??{},onLength:o=>{e=o}})};function Bo(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 De=Bo;function Oo(r){return r[Symbol.asyncIterator]!=null}function $o(r,t){if(Oo(r))return async function*(){for await(let c of r)yield t(c)}();let e=De(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let o=t(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let c of e)yield t(c)}();let i=t;return function*(){yield o;for(let c of e)yield i(c)}()}var Kt=$o;function zo(r){return r[Symbol.asyncIterator]!=null}function Vo(...r){let t=[];for(let e of r)zo(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Dt({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 Bn=Vo;function Mt(r,...t){if(r==null)throw new Error("Empty pipeline");if(br(r)){let n=r;r=()=>n.source}else if($n(r)||On(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&br(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++)br(e[n])&&(e[n]=qo(e[n]));return Ho(...e)}var Ho=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},On=r=>r?.[Symbol.asyncIterator]!=null,$n=r=>r?.[Symbol.iterator]!=null,br=r=>r==null?!1:r.sink!=null&&r.source!=null,qo=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Dt({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(On(o))s=async function*(){yield*o,n.end()};else if($n(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Bn(n,s())}return r.source};function Wo(r){return r[Symbol.asyncIterator]!=null}function Go(r,t){return Wo(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 zn=Go;var ot=class extends Event{constructor(t,e){super(t),this.detail=e}};var Jt="/ipfs/bitswap/1.2.0";var yr=new Float32Array([-0]),ft=new Uint8Array(yr.buffer);function Vn(r,t,e){yr[0]=r,t[e]=ft[0],t[e+1]=ft[1],t[e+2]=ft[2],t[e+3]=ft[3]}function Hn(r,t){return ft[0]=r[t],ft[1]=r[t+1],ft[2]=r[t+2],ft[3]=r[t+3],yr[0]}var xr=new Float64Array([-0]),z=new Uint8Array(xr.buffer);function qn(r,t,e){xr[0]=r,t[e]=z[0],t[e+1]=z[1],t[e+2]=z[2],t[e+3]=z[3],t[e+4]=z[4],t[e+5]=z[5],t[e+6]=z[6],t[e+7]=z[7]}function Wn(r,t){return z[0]=r[t],z[1]=r[t+1],z[2]=r[t+2],z[3]=r[t+3],z[4]=r[t+4],z[5]=r[t+5],z[6]=r[t+6],z[7]=r[t+7],xr[0]}var Xo=BigInt(Number.MAX_SAFE_INTEGER),Qo=BigInt(Number.MIN_SAFE_INTEGER),G=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<Xo&&t>Qo)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>Gn&&(s=0n,++n>Gn&&(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 G(0,0);bt.toBigInt=function(){return 0n};bt.zzEncode=bt.zzDecode=function(){return this};bt.length=function(){return 1};var Gn=4294967296n;function Xn(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 Qn(r,t,e){if(e-t<1)return"";let s,o=[],i=0,c;for(;t<e;)c=r[t++],c<128?o[i++]=c:c>191&&c<224?o[i++]=(c&31)<<6|r[t++]&63:c>239&&c<365?(c=((c&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(c>>10),o[i++]=56320+(c&1023)):o[i++]=(c&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Er(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,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 rt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Pe(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var vr=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,rt(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 rt(this,4);return Pe(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw rt(this,4);return Pe(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw rt(this,4);let t=Hn(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw rt(this,4);let t=Wn(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 rt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Qn(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw rt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw rt(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 G(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 rt(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 rt(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 rt(this,8);let t=Pe(this.buf,this.pos+=4),e=Pe(this.buf,this.pos+=4);return new G(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=gr(this.buf,this.pos);return this.pos+=D(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 Sr(r){return new vr(r instanceof Uint8Array?r:r.subarray())}function yt(r,t,e){let n=Sr(r);return t.decode(n,void 0,e)}var Tr={};q(Tr,{base10:()=>ti});var Rl=new Uint8Array(0);function Kn(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 ct(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 Jn(r){return new TextEncoder().encode(r)}function Zn(r){return new TextDecoder().decode(r)}function jo(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 o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var c=r.length,u=r.charAt(0),l=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var p=0,v=0,m=0,g=h.length;m!==g&&h[m]===0;)m++,p++;for(var w=(g-m)*d+1>>>0,y=new Uint8Array(w);m!==g;){for(var E=h[m],k=0,b=w-1;(E!==0||k<v)&&b!==-1;b--,k++)E+=256*y[b]>>>0,y[b]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");v=k,m++}for(var T=w-v;T!==w&&y[T]===0;)T++;for(var at=u.repeat(p);T<w;++T)at+=r.charAt(y[T]);return at}function x(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var p=0;if(h[p]!==" "){for(var v=0,m=0;h[p]===u;)v++,p++;for(var g=(h.length-p)*l+1>>>0,w=new Uint8Array(g);h[p];){var y=e[h.charCodeAt(p)];if(y===255)return;for(var E=0,k=g-1;(y!==0||E<m)&&k!==-1;k--,E++)y+=c*w[k]>>>0,w[k]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");m=E,p++}if(h[p]!==" "){for(var b=g-m;b!==g&&w[b]===0;)b++;for(var T=new Uint8Array(v+(g-b)),at=v;b!==g;)T[at++]=w[b++];return T}}}function a(h){var p=x(h);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:x,decode:a}}var Ko=jo,Jo=Ko,ts=Jo;var kr=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")}},Ar=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 es(this,t)}},Lr=class{decoders;constructor(t){this.decoders=t}or(t){return es(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 es(r,t){return new Lr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Ir=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 kr(t,e,n),this.decoder=new Ar(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ct({name:r,prefix:t,encode:e,decode:n}){return new Ir(r,t,e,n)}function dt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=ts(e,r);return Ct({prefix:t,name:r,encode:n,decode:o=>ct(s(o))})}function Zo(r,t,e,n){let s={};for(let d=0;d<t.length;++d)s[t[d]]=d;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),c=0,u=0,l=0;for(let d=0;d<o;++d){let f=s[r[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);u=u<<e|f,c+=e,c>=8&&(c-=8,i[l++]=255&u>>c)}if(c>=e||255&u<<8-c)throw new SyntaxError("Unexpected end of data");return i}function Yo(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,c=0;for(let u=0;u<r.length;++u)for(c=c<<8|r[u],i+=8;i>e;)i-=e,o+=t[s&c>>i];if(i!==0&&(o+=t[s&c<<e-i]),n)for(;o.length*e&7;)o+="=";return o}function R({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Ct({prefix:t,name:r,encode(s){return Yo(s,n,e)},decode(s){return Zo(s,n,e,r)}})}var ti=dt({prefix:"9",name:"base10",alphabet:"0123456789"});var _r={};q(_r,{base16:()=>ei,base16upper:()=>ri});var ei=R({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ri=R({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Dr={};q(Dr,{base2:()=>ni});var ni=R({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Pr={};q(Pr,{base256emoji:()=>ci});var rs=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}"),si=rs.reduce((r,t,e)=>(r[e]=t,r),[]),oi=rs.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function ii(r){return r.reduce((t,e)=>(t+=si[e],t),"")}function ai(r){let t=[];for(let e of r){let n=oi[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var ci=Ct({prefix:"\u{1F680}",name:"base256emoji",encode:ii,decode:ai});var Rr={};q(Rr,{base32:()=>lt,base32hex:()=>fi,base32hexpad:()=>pi,base32hexpadupper:()=>mi,base32hexupper:()=>di,base32pad:()=>ui,base32padupper:()=>hi,base32upper:()=>li,base32z:()=>gi});var lt=R({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),li=R({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ui=R({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hi=R({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fi=R({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),di=R({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pi=R({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mi=R({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gi=R({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Mr={};q(Mr,{base36:()=>wi,base36upper:()=>bi});var wi=dt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bi=dt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Cr={};q(Cr,{base58btc:()=>U,base58flickr:()=>yi});var U=dt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),yi=dt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Nr={};q(Nr,{base64:()=>J,base64pad:()=>xi,base64url:()=>Ur,base64urlpad:()=>Ei});var J=R({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),xi=R({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ur=R({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ei=R({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Fr={};q(Fr,{base8:()=>vi});var vi=R({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Br={};q(Br,{identity:()=>Si});var Si=Ct({prefix:"\0",name:"identity",encode:r=>Zn(r),decode:r=>Jn(r)});var Ql=new TextEncoder,jl=new TextDecoder;var $r={};q($r,{identity:()=>Me});var Li=os,ns=128,Ii=127,Ti=~Ii,_i=Math.pow(2,31);function os(r,t,e){t=t||[],e=e||0;for(var n=e;r>=_i;)t[e++]=r&255|ns,r/=128;for(;r&Ti;)t[e++]=r&255|ns,r>>>=7;return t[e]=r|0,os.bytes=e-n+1,t}var Di=Or,Pi=128,ss=127;function Or(r,n){var e=0,n=n||0,s=0,o=n,i,c=r.length;do{if(o>=c)throw Or.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&ss)<<s:(i&ss)*Math.pow(2,s),s+=7}while(i>=Pi);return Or.bytes=o-n,e}var Ri=Math.pow(2,7),Mi=Math.pow(2,14),Ci=Math.pow(2,21),Ui=Math.pow(2,28),Ni=Math.pow(2,35),Fi=Math.pow(2,42),Bi=Math.pow(2,49),Oi=Math.pow(2,56),$i=Math.pow(2,63),zi=function(r){return r<Ri?1:r<Mi?2:r<Ci?3:r<Ui?4:r<Ni?5:r<Fi?6:r<Bi?7:r<Oi?8:r<$i?9:10},Vi={encode:Li,decode:Di,encodingLength:zi},Hi=Vi,Zt=Hi;function Yt(r,t=0){return[Zt.decode(r,t),Zt.decode.bytes]}function Ut(r,t,e=0){return Zt.encode(r,t,e),t}function Nt(r){return Zt.encodingLength(r)}function pt(r,t){let e=t.byteLength,n=Nt(r),s=n+Nt(e),o=new Uint8Array(s+e);return Ut(r,o,0),Ut(e,o,n),o.set(t,s),new Ft(r,e,t,o)}function xt(r){let t=ct(r),[e,n]=Yt(t),[s,o]=Yt(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ft(e,s,i,t)}function is(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Kn(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}};var as=0,qi="identity",cs=ct;function Wi(r){return pt(as,cs(r))}var Me={code:as,name:qi,encode:cs,digest:Wi};var Hr={};q(Hr,{sha256:()=>vt,sha512:()=>Gi});function Vr({name:r,code:t,encode:e}){return new zr(r,t,e)}var zr=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?pt(this.code,e):e.then(n=>pt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function us(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var vt=Vr({name:"sha2-256",code:18,encode:us("SHA-256")}),Gi=Vr({name:"sha2-512",code:19,encode:us("SHA-512")});function hs(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Qi(e,qr(r),t??U.encoder);default:return ji(e,qr(r),t??lt.encoder)}}var fs=new WeakMap;function qr(r){let t=fs.get(r);if(t==null){let e=new Map;return fs.set(r,e),e}return t}var V=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!==te)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Ki)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=pt(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&&is(t.multihash,n.multihash)}toString(t){return hs(this,t)}toJSON(){return{"/":hs(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:o,bytes:i}=e;return new r(n,s,o,i??ds(n,s,o.bytes))}else if(e[Ji]===!0){let{version:n,multihash:s,code:o}=e,i=xt(s);return r.create(n,o,i)}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!==te)throw new Error(`Version 0 CID must use dag-pb (code: ${te}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=ds(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,te,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=ct(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Ft(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,x]=Yt(t.subarray(e));return e+=x,f},s=n(),o=te;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,c=n(),u=n(),l=e+u,d=l-i;return{version:s,codec:o,multihashCode:c,digestSize:u,multihashSize:d,size:l}}static parse(t,e){let[n,s]=Xi(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return qr(o).set(n,t),o}};function Xi(r,t){switch(r[0]){case"Q":{let e=t??U;return[U.prefix,e.decode(`${U.prefix}${r}`)]}case U.prefix:{let e=t??U;return[U.prefix,e.decode(r)]}case lt.prefix:{let e=t??lt;return[lt.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 Qi(r,t,e){let{prefix:n}=e;if(n!==U.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function ji(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var te=112,Ki=18;function ds(r,t,e){let n=Nt(r),s=n+Nt(t),o=new Uint8Array(s+e.byteLength);return Ut(r,o,0),Ut(t,o,n),o.set(e,s),o}var Ji=Symbol.for("@ipld/js-cid/CID");var mt={...Br,...Dr,...Fr,...Tr,..._r,...Rr,...Mr,...Cr,...Nr,...Pr},gu={...Hr,...$r};function ms(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ps=ms("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Wr=ms("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=O(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Zi={utf8:ps,"utf-8":ps,hex:mt.base16,latin1:Wr,ascii:Wr,binary:Wr,...mt},Ce=Zi;function gt(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Gr(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return O(i);s+i>t&&(n=O(t),s=0);let c=n.subarray(s,s+=i);return s&7&&(s=(s|7)+1),c}}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 Xr(){}var jr=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Yi=Gr();function ta(r){return globalThis.Buffer!=null?O(r):Yi(r)}var re=class{len;head;tail;states;constructor(){this.len=0,this.head=new St(Xr,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 Kr((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(Ue,10,G.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=G.fromBigInt(t);return this._push(Ue,e.length(),e)}uint64Number(t){return this._push(mr,D(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=G.fromBigInt(t).zzEncode();return this._push(Ue,e.length(),e)}sint64Number(t){let e=G.fromNumber(t).zzEncode();return this._push(Ue,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Qr,1,t?1:0)}fixed32(t){return this._push(ee,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=G.fromBigInt(t);return this._push(ee,4,e.lo)._push(ee,4,e.hi)}fixed64Number(t){let e=G.fromNumber(t);return this._push(ee,4,e.lo)._push(ee,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(Vn,4,t)}double(t){return this._push(qn,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Qr,1,0):this.uint32(e)._push(ra,e,t)}string(t){let e=Xn(t);return e!==0?this.uint32(e)._push(Er,e,t):this._push(Qr,1,0)}fork(){return this.states=new jr(this),this.head=this.tail=new St(Xr,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(Xr,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=ta(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Qr(r,t,e){t[e]=r&255}function ea(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Kr=class extends St{next;constructor(t,e){super(ea,t,e),this.next=void 0}};function Ue(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 ee(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 ra(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(re.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(na,t,r),this},re.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(sa,t,r),this});function na(r,t,e){t.set(r,e)}function sa(r,t,e){r.length<40?Er(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(gt(r),e)}function Jr(){return new re}function kt(r,t){let e=Jr();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 Ne(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Fe(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let c=t(o);i.int32(c)},n=function(o){let i=o.int32();return t(i)};return Ne("enum",Bt.VARINT,e,n)}function At(r,t){return Ne("message",Bt.LENGTH_DELIMITED,r,t)}var Ot=class extends Error{code;constructor(t,e,n){super(t,n),this.code=e}};var M;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(M||(M={}));var Zr;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Zr||(Zr={}));(function(r){r.codec=()=>Fe(Zr)})(M||(M={}));var $t;(function(r){let t;r.codec=()=>(t==null&&(t=At((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.priority!=null&&e.priority!==0&&(n.uint32(16),n.int32(e.priority)),e.cancel!=null&&(n.uint32(24),n.bool(e.cancel)),e.wantType!=null&&(n.uint32(32),M.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:B(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.priority=e.int32();break}case 3:{o.cancel=e.bool();break}case 4:{o.wantType=M.codec().decode(e);break}case 5:{o.sendDontHave=e.bool();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})($t||($t={}));var Be;(function(r){let t;r.codec=()=>(t==null&&(t=At((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let o of e.entries)n.uint32(10),$t.codec().encode(o,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={entries:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new Ot('decode error - map field "entries" had too many elements',"ERR_MAX_LENGTH");o.entries.push($t.codec().decode(e,e.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=e.bool();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})(Be||(Be={}));var zt;(function(r){let t;r.codec=()=>(t==null&&(t=At((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.prefix!=null&&e.prefix.byteLength>0&&(n.uint32(10),n.bytes(e.prefix)),e.data!=null&&e.data.byteLength>0&&(n.uint32(18),n.bytes(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={prefix:B(0),data:B(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.prefix=e.bytes();break}case 2:{o.data=e.bytes();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})(zt||(zt={}));var Z;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(Z||(Z={}));var Oe;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(Oe||(Oe={}));(function(r){r.codec=()=>Fe(Oe)})(Z||(Z={}));var Vt;(function(r){let t;r.codec=()=>(t==null&&(t=At((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.type!=null&&Oe[e.type]!==0&&(n.uint32(16),Z.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:B(0),type:Z.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.type=Z.codec().decode(e);break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})(Vt||(Vt={}));var Lt;(function(r){let t;r.codec=()=>(t==null&&(t=At((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),Be.codec().encode(e.wantlist,n)),e.blocks!=null)for(let o of e.blocks)n.uint32(26),zt.codec().encode(o,n);if(e.blockPresences!=null)for(let o of e.blockPresences)n.uint32(34),Vt.codec().encode(o,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.wantlist=Be.codec().decode(e,e.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&o.blocks.length===s.limits.blocks)throw new Ot('decode error - map field "blocks" had too many elements',"ERR_MAX_LENGTH");o.blocks.push(zt.codec().decode(e,e.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&o.blockPresences.length===s.limits.blockPresences)throw new Ot('decode error - map field "blockPresences" had too many elements',"ERR_MAX_LENGTH");o.blockPresences.push(Vt.codec().decode(e,e.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=e.int32();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})(Lt||(Lt={}));function gs(r,t){let e=new Map((r.wantlist?.entries??[]).map(i=>[J.encode(i.cid),i]));for(let i of t.wantlist?.entries??[]){let c=J.encode(i.cid),u=e.get(c);u!=null&&(u.priority>i.priority&&(i.priority=u.priority),i.cancel=i.cancel??u.cancel,i.wantType=i.wantType??u.wantType,i.sendDontHave=i.sendDontHave??u.sendDontHave),e.set(c,i)}let n=new Map(r.blockPresences.map(i=>[J.encode(i.cid),i]));for(let i of t.blockPresences){let c=J.encode(i.cid);n.set(c,i)}let s=new Map(r.blocks.map(i=>[J.encode(i.data),i]));for(let i of t.blocks){let c=J.encode(i.data);s.set(c,i)}return{wantlist:{full:r.wantlist?.full??t.wantlist?.full??!1,entries:[...e.values()]},blockPresences:[...n.values()],blocks:[...s.values()],pendingBytes:r.pendingBytes+t.pendingBytes}}var oa=4193648,ia=oa+16;async function*ws(r,t){let e=r.wantlist?.entries??[],n=r.blockPresences,s=r.blocks,o=0,i=0,c=0,u=!1;for(;;){let l={wantlist:{full:r.wantlist?.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=Lt.encode(l).byteLength,{added:f,hasMore:x,newSize:a}=Yr(s,l.blocks,c,t,d,aa);c+=f,d=a;let h=x;({added:f,hasMore:x,newSize:a}=Yr(n,l.blockPresences,i,t,d,ca)),i+=f,d=a;let p=x;if({added:f,hasMore:x,newSize:a}=Yr(e,l.wantlist.entries,o,t,d,la),o+=f,d=a,u=!h&&!p&&!x,u||(l.wantlist.full=!1),yield Lt.encode(l),u)break}}function Yr(r,t,e,n,s,o){let i=0,c=!1;for(let u=e;u<r.length;u++){let l=r[u],d=o(l);if(d>ia)throw new N("Cannot send block as after encoding it is over the max message size","ERR_BLOCK_TOO_LARGE");let f=s+d;if(f>n){c=!0;break}t.push(l),i++,s=f}return{hasMore:c,added:i,newSize:s}}function aa(r){return tn(3,zt.encode(r))}function ca(r){return tn(4,Vt.encode(r))}function la(r){return tn(1,$t.encode(r))}function tn(r,t){let e=D(r),n=D(t.byteLength);return e+n+t.byteLength}var $e=class extends nt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnTransientConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[Jt],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??5e3,this.runOnTransientConnections=e.runOnTransientConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.libp2p.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.libp2p.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new ke({concurrency:e.messageSendConcurrency??50,metrics:t.libp2p.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail: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=[]}}_onStream(t){if(!this.running)return;let{stream:e,connection:n}=t;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,n.remotePeer);let s=()=>{e.status==="open"?e.abort(new N("Incoming Bitswap stream timed out","ERR_TIMEOUT")):this.log("stream aborted with status",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);W(1/0,o),o.addEventListener("abort",s),await e.closeWrite(),await Mt(e,i=>jt(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let c of i)try{let u=Lt.decode(c);this.log("incoming new bitswap %s message from %p on stream",e.protocol,n.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:u}}),o.removeEventListener("abort",s),o=AbortSignal.timeout(this.messageReceiveTimeout),W(1/0,o),o.addEventListener("abort",s)}catch(u){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,e.id,u),e.abort(u);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new ot("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnTransientConnection:this.runOnTransientConnections})&&(yield n)}async findAndConnect(t,e){await ur(Kt(zn(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s={wantlist:{full:e.wantlist?.full??!1,entries:e.wantlist?.entries??[]},blocks:e.blocks??[],blockPresences:e.blockPresences??[],pendingBytes:e.pendingBytes??0},o=this.sendQueue.queue.find(i=>t.equals(i.options.peerId)&&i.status==="queued");if(o!=null){o.options.message=gs(o.options.message,s),await o.join({signal:n?.signal});return}await this.sendQueue.add(async i=>{let c=i?.message;if(c==null)throw new N("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p",t),i?.onProgress?.(new ot("bitswap:network:send-wantlist",t));let u=await this.libp2p.dialProtocol(t,Jt,i);await u.closeRead();try{await Mt(ws(c,this.maxOutgoingMessageSize),l=>_e(l),u),await u.close(i)}catch(l){i?.onProgress?.(new ot("bitswap:network:send-wantlist:error",{peer:t,error:l})),this.log.error("error sending message to %p",t,l),u.abort(l)}this._updateSentStats(c.blocks)},{peerId:t,signal:n?.signal,message:s})}async connectTo(t,e){if(!this.running)throw new N("Network isn't running","ERR_NOT_STARTED");e?.onProgress?.(new ot("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),tt(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(Jt))return!0;throw new N(`${t} did not support ${Jt}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);return n}_updateSentStats(t=[]){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.length)}};var ba=Symbol.for("nodejs.util.inspect.custom"),bs=Object.values(mt).map(r=>r.decoder).reduce((r,t)=>r.or(t),mt.identity.decoder),ys=114,xs=36,Es=37,ne=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Dn]=!0;toString(){return this.string==null&&(this.string=U.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return V.createV1(ys,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return K(this.multihash.bytes,t);if(typeof t=="string")return ae(t).equals(this);if(t?.multihash?.bytes!=null)return K(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[ba](){return`PeerId(${this.toString()})`}},se=class extends ne{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},oe=class extends ne{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},ie=class extends ne{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}};function ae(r,t){if(t=t??bs,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=xt(U.decode(`z${r}`));return r.startsWith("12D")?new oe({multihash:e}):r.startsWith("16U")?new ie({multihash:e}):new se({multihash:e})}return ya(bs.decode(r))}function ya(r){try{let t=xt(r);if(t.code===Me.code){if(t.digest.length===xs)return new oe({multihash:t});if(t.digest.length===Es)return new ie({multihash:t})}if(t.code===vt.code)return new se({multihash:t})}catch{return xa(V.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function xa(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==ys)throw new Error("Supplied PeerID CID is invalid");let t=r.multihash;if(t.code===vt.code)return new se({multihash:r.multihash});if(t.code===Me.code){if(t.digest.length===xs)return new oe({multihash:r.multihash});if(t.digest.length===Es)return new ie({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function en(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var ce=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return en(this.map.entries(),t=>[ae(t[0]),t[1]])}forEach(t){this.map.forEach((e,n)=>{t(e,ae(n),this)})}get(t){return this.map.get(t.toString())}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),e)}keys(){return en(this.map.keys(),t=>ae(t))}values(){return this.map.values()}get size(){return this.map.size}};var rn=class extends ce{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 le(r){let{name:t,metrics:e}=r,n;return e!=null?n=new rn({name:t,metrics:e}):n=new ce,n}function P(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function Ea(r){let t=new Uint8Array(r.reduce((n,s)=>n+D(s),0)),e=0;for(let n of r)t=st(n,t,e),e+=D(n);return t}var vs=Ea;function nn(r){return vs([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var ze=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(t){let e={blockPresences:[],blocks:[]},n=new Set;for(let[s,o]of this.wants.entries()){if(!await this.blockstore.has(o.cid,t)){if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDontHave===!0)continue;o.sentDontHave=!0,e.blockPresences.push({cid:o.cid.bytes,type:Z.DontHaveBlock});continue}let c=await this.blockstore.get(o.cid,t);o.wantType===M.WantHave?c.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),e.blocks.push({data:c,prefix:nn(o.cid)})):(this.log("sending have for %c",o.cid),e.blockPresences.push({cid:o.cid.bytes,type:Z.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),e.blocks.push({data:c,prefix:nn(o.cid)}))}if(e.blocks.length>0||e.blockPresences.length>0){this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes(e.blocks.reduce((s,o)=>s+o.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var Ve=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=le({name:"helia_bitswap_ledger_map",metrics:t.libp2p.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return[...e.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);if(n==null&&(n=new ze({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let o=V.decode(s.cid),i=P(o.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,o),n.wants.delete(i)):(s.wantType===M.WantHave?this.log("peer %p wanted block presence for %c",t,o):this.log("peer %p wanted block for %c",t,o),n.wants.set(i,{cid:o,priority:s.priority,wantType:s.wantType??M.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=P(t.multihash.bytes,"base64"),s=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&s.push(o);await Promise.all(s.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var ka=ye(ks(),1);var Ht;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ht||(Ht={}));function Aa(r){return r[Symbol.asyncIterator]!=null}function La(r,t){if(Aa(r))return async function*(){for await(let c of r)await t(c)&&(yield c)}();let e=De(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let o=t(n);if(typeof o.then=="function")return async function*(){await o&&(yield n);for await(let c of e)await t(c)&&(yield c)}();let i=t;return function*(){o===!0&&(yield n);for(let c of e)i(c)&&(yield c)}()}var sn=La;var He=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Af=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Lf={}.toString;function As(r=32){if(He&&typeof He.getRandomValues=="function")return He.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function qe(r){if(isNaN(r)||r<=0)throw new N("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return As(r)}var on=ye(Ts(),1);var Ia=Math.LN2*Math.LN2,Ge=class r{static create(t,e=.005){let n=Ta(t,e);return new r(n)}seeds;bits;buffer;constructor(t={}){t.seeds!=null?this.seeds=t.seeds:this.seeds=_a(t.hashes??8),this.bits=t.bits??1024,this.buffer=B(Math.ceil(this.bits/8))}add(t){typeof t=="string"&&(t=gt(t));for(let e=0;e<this.seeds.length;e++){let s=on.default.x86.hash32(t,this.seeds[e])%this.bits;this.setbit(s)}}has(t){typeof t=="string"&&(t=gt(t));for(let e=0;e<this.seeds.length;e++){let s=on.default.x86.hash32(t,this.seeds[e])%this.bits;if(!this.getbit(s))return!1}return!0}clear(){this.buffer.fill(0)}setbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;let s=this.buffer[e];s|=1<<n,this.buffer[e]=s}getbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;return(this.buffer[e]&1<<n)!==0}};function Ta(r,t=.005){let e=Math.round(-1*r*Math.log(t)/Ia),n=Math.round(e/r*Math.LN2);return{bits:e,hashes:n}}function _a(r){let t,e,n=[];for(let s=0;s<r;s++)for(t=new ht(qe(4)),n[s]=t.getUint32(0,!0),e=0;e<s;e++)if(n[s]===n[e]){s--;break}return n}var It=class extends nt{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(t,e){super(),W(1/0,this),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=Ge.create(this.maxProviders)}async retrieve(t,e={}){let n=J.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let o=Y();if(this.requests.set(n,o.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.intialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",t)}let i=!1,c=new Pt({concurrency:this.maxProviders});c.addEventListener("error",()=>{}),c.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),c.addEventListener("success",l=>{i=!0,o.resolve(l.detail.result)}),c.addEventListener("idle",()=>{i||e.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(l=>{this.log.error("could not find new providers for %c",t,l),o.reject(l)})});let u=l=>{c.add(async()=>this.queryProvider(t,l.detail,e),{provider:l.detail}).catch(d=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,d)})};this.addEventListener("provider",u),Promise.all([...this.providers].map(async l=>c.add(async()=>this.queryProvider(t,l,e),{provider:l}))).catch(l=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,l)});try{return await o.promise}finally{this.removeEventListener("provider",u),c.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.providers.some(e=>this.equals(e,t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let s=Y(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t);for await(let i of this.findNewProviders(t,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<e)throw new N(`Found ${o} of ${e} ${this.name} providers for ${t}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",t,i.errors??i),s.reject(i)}),s.promise}};var an=class extends It{wantList;network;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield n.id}toEvictionKey(t){return t.toBytes()}equals(t,e){return t.equals(e)}};function _s(r,t){return new an(r,t)}var Xe=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.libp2p.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.libp2p.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.libp2p.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.libp2p.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};var cn=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 Ds(r){let{name:t,metrics:e}=r,n;return e!=null?n=new cn({name:t,metrics:e}):n=new Map,n}function Da(r){return r[Symbol.asyncIterator]!=null}function Pa(r){if(Da(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var ln=Pa;function Ra(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=et(r);t.push(e),r=r.slice(D(e))}return t}var Ps=Ra;var Qe=class extends nt{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),W(1/0,this),this.peers=le({name:"helia_bitswap_peers",metrics:t.libp2p.metrics}),this.wants=Ds({name:"helia_bitswap_wantlist",metrics:t.libp2p.metrics}),this.network=t.network,this.sendMessagesDelay=e.sendMessagesDelay??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=e.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=P(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??M.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===M.WantHave&&e.wantType===M.WantBlock&&(s.wantType=M.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===M.WantBlock?(await tt(this,"block",e?.signal,{filter:c=>K(t.multihash.digest,c.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await tt(this,"presence",e?.signal,{filter:i=>K(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers",t)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=Y(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s={wantlist:{full:!1,entries:Mt(this.wants.entries(),o=>sn(o,([i,c])=>{let u=e.has(i);return c.cancel?u:!u}),o=>Kt(o,([i,c])=>(n.add(i),{cid:c.cid.bytes,priority:c.priority,wantType:c.wantType,cancel:c.cancel,sendDontHave:c.sendDontHave})),o=>ln(o))}};if(s.wantlist?.entries.length!==0)try{await this.network.sendMessage(t,s);for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer",o)}})).catch(t=>{this.log.error("error sending messages",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=P(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){return await this.network.sendMessage(e,{wantlist:{full:!1,entries:[{cid:t.bytes,sendDontHave:!0,wantType:M.WantHave,priority:1}]}}),(await tt(this,"presence",n.signal,{filter:o=>e.equals(o.detail.sender)&&K(t.multihash.digest,o.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:M.WantBlock})}async wantSessionBlock(t,e,n={}){return await this.network.sendMessage(e,{wantlist:{full:!1,entries:[{cid:t.bytes,sendDontHave:!0,wantType:M.WantBlock,priority:1}]}}),(await tt(this,"presence",n.signal,{filter:o=>e.equals(o.detail.sender)&&K(t.multihash.digest,o.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=P(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message %d from %p with %d blocks",t,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=Ps(s.prefix),i=o[0],c=o[1],u=o[2],l=u===vt.code?vt:await this.hashLoader?.getHasher(u);if(l==null){this.log.error("unknown hash algorithm",u);continue}let d=l.digest(s.data);d.then!=null&&(d=await d);let f=V.create(i===0?0:1,c,d);this.log("received block from %p for %c",t,f),this.safeDispatchEvent("block",{detail:{sender:t,cid:f,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:f,has:!0,block:s.data}});let x=P(f.multihash.bytes,"base64"),a=this.wants.get(x);a!=null&&(a.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=V.decode(s);this.log("received %s from %p for %c",o,t,i),this.safeDispatchEvent("presence",{detail:{sender:t,cid:i,has:o===Z.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n={wantlist:{full:!0,entries:Mt(this.wants.entries(),s=>sn(s,([o,i])=>!i.cancel),s=>Kt(s,([o,i])=>(e.add(o),{cid:i.cid.bytes,priority:1,wantType:M.WantBlock,cancel:!1,sendDontHave:!1})),s=>ln(s))}};if(n.wantlist?.entries.length===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var je=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.stats=new Xe(t),this.network=new $e(t,e),this.peerWantLists=new Ve({...t,network:this.network},e),this.wantList=new Qe({...t,network:this.network},e)}createSession(t={}){return _s({wantList:this.wantList,network:this.network,logger:this.logger},t)}async want(t,e={}){let n=new AbortController,s=Pn([n.signal,e.signal]);W(1/0,n.signal,s),this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,o)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await Promise.all([this.peerWantLists.receivedBlock(t,n),this.wantList.receivedBlock(t,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Rs=(r,t={})=>new je(r,t);var un=class{bitswap;started;constructor(t,e={}){let{hashers:n}=t;this.bitswap=Rs(t,{hashLoader:{getHasher:async s=>{let o;if(typeof s=="string"?o=Object.values(n).find(i=>i.name===s):o=n[s],o!=null)return o;throw new Error(`Could not load hasher for code/name "${s}"`)}},...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){await this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}createSession(t){let e=this.bitswap.createSession(t);return{announce:async(n,s,o)=>{await this.bitswap.notify(n,s,o)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function Ms(r={}){return t=>new un(t,r)}var Ke=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 o=0,i=0,c=this.peekChar();if(c===void 0)return;let u=c==="0",l=2**(8*s)-1;for(;;){let d=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let x=Number.parseInt(f,t);if(!Number.isNaN(x))return x});if(d===void 0)break;if(o*=t,o+=d,o>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&u&&i>1?void 0:o})}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 i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&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 o=new Uint8Array(14),i=16-(n+2),[c]=t(o.subarray(0,i));return e.set(o.subarray(0,c),16-c),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Cs=45,Ma=15,qt=new Ke;function hn(r){if(!(r.length>Ma))return qt.new(r).parseWith(()=>qt.readIPv4Addr())}function fn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Cs))return qt.new(r).parseWith(()=>qt.readIPv6Addr())}function Je(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Cs))return qt.new(r).parseWith(()=>qt.readIPAddr())}function Wt(r){return!!hn(r)}function Gt(r){return!!fn(r)}function Ze(r){return!!Je(r)}var Ns=ye(Us(),1),Ca=["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"],Ua=Ca.map(r=>new Ns.Netmask(r));function Na(r){for(let t of Ua)if(t.contains(r))return!0;return!1}function Fa(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 Fs(r){return Wt(r)?Na(r):Gt(r)?Fa(r):void 0}var jd=parseInt("0xFFFF",16),Kd=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var $s=Wt,Va=Gt,dn=function(r){let t=0;if(r=r.toString().trim(),$s(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Va(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=$s(e[n]),i;o&&(i=dn(e[n]),e[n]=P(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,P(i.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 o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let o=parseInt(e[n],16);s[t++]=o>>8&255,s[t++]=o&255}return s}throw new Error("invalid ip address")},zs=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 o=0;o<e;o++)s.push(r[t+o]);return s.join(".")}if(e===16){let s=[];for(let o=0;o<e;o+=2)s.push(n.getUint16(t+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Xt={},pn={},qa=[[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"]];qa.forEach(r=>{let t=Wa(...r);pn[t.code]=t,Xt[t.name]=t});function Wa(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function S(r){if(typeof r=="number"){if(pn[r]!=null)return pn[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Xt[r]!=null)return Xt[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Pp=S("ip4"),Rp=S("ip6"),Mp=S("ipcidr");function gn(r,t){switch(S(r).code){case 4:case 41:return Xa(t);case 42:return qs(t);case 6:case 273:case 33:case 132:return Gs(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return qs(t);case 421:return Ja(t);case 444:return Ws(t);case 445:return Ws(t);case 466:return Ka(t);default:return P(t,"base16")}}function wn(r,t){switch(S(r).code){case 4:return Vs(t);case 41:return Vs(t);case 42:return Hs(t);case 6:case 273:case 33:case 132:return bn(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Hs(t);case 421:return Qa(t);case 444:return Za(t);case 445:return Ya(t);case 466:return ja(t);default:return gt(t,"base16")}}var mn=Object.values(mt).map(r=>r.decoder),Ga=function(){let r=mn[0].or(mn[1]);return mn.slice(2).forEach(t=>r=r.or(t)),r}();function Vs(r){if(!Ze(r))throw new Error("invalid ip address");return dn(r)}function Xa(r){let t=zs(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Ze(t))throw new Error("invalid ip address");return t}function bn(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Gs(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Hs(r){let t=gt(r),e=Uint8Array.from(st(t.length));return j([e,t],e.length+t.length)}function qs(r){let t=et(r);if(r=r.slice(D(t)),r.length!==t)throw new Error("inconsistent lengths");return P(r)}function Qa(r){let t;r[0]==="Q"||r[0]==="1"?t=xt(U.decode(`z${r}`)).bytes:t=V.parse(r).multihash.bytes;let e=Uint8Array.from(st(t.length));return j([e,t],e.length+t.length)}function ja(r){let t=Ga.decode(r),e=Uint8Array.from(st(t.length));return j([e,t],e.length+t.length)}function Ka(r){let t=et(r),e=r.slice(D(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+P(e,"base64url")}function Ja(r){let t=et(r),e=r.slice(D(t));if(e.length!==t)throw new Error("inconsistent lengths");return P(e,"base58btc")}function Za(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=lt.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=bn(n);return j([e,s],e.length+s.length)}function Ya(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=lt.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=bn(n);return j([e,s],e.length+s.length)}function Ws(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=P(t,"base32"),s=Gs(e);return`${n}:${s}`}function Xs(r){r=yn(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 o=0;o<s.length;o++){let i=s[o],c=S(i);if(c.size===0){t.push([c.code]),e.push([c.code]);continue}if(o++,o>=s.length)throw js("invalid address: "+r);if(c.path===!0){n=yn(s.slice(o).join("/")),t.push([c.code,wn(c.code,n)]),e.push([c.code,n]);break}let u=wn(c.code,s[o]);t.push([c.code,u]),e.push([c.code,gn(c.code,u)])}return{string:Qs(e),bytes:En(t),tuples:t,stringTuples:e,path:n}}function xn(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let o=et(r,s),i=D(o),c=S(o),u=tc(c,r.slice(s+i));if(u===0){t.push([o]),e.push([o]),s+=i;continue}let l=r.slice(s+i,s+i+u);if(s+=u+i,s>r.length)throw js("Invalid address Uint8Array: "+P(r,"base16"));t.push([o,l]);let d=gn(o,l);if(e.push([o,d]),c.path===!0){n=d;break}}return{bytes:Uint8Array.from(r),string:Qs(e),tuples:t,stringTuples:e,path:n}}function Qs(r){let t=[];return r.map(e=>{let n=S(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),yn(t.join("/"))}function En(r){return j(r.map(t=>{let e=S(t[0]),n=Uint8Array.from(st(e.code));return t.length>1&&t[1]!=null&&(n=j([n,t[1]])),n}))}function tc(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=et(t instanceof Uint8Array?t:Uint8Array.from(t));return e+D(e)}}function yn(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function js(r){return new Error("Error parsing address: "+r)}var ec=Symbol.for("nodejs.util.inspect.custom"),vn=Symbol.for("@multiformats/js-multiaddr/multiaddr"),rc=[S("dns").code,S("dns4").code,S("dns6").code,S("dnsaddr").code],Ye=class r{bytes;#t;#e;#r;#n;[vn]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=xn(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Xs(t)}else if(Js(t))e=xn(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,o="",i=S("tcp"),c=S("udp"),u=S("ip4"),l=S("ip6"),d=S("dns6"),f=S("ip6zone");for(let[a,h]of this.stringTuples())a===f.code&&(o=`%${h??""}`),rc.includes(a)&&(e=i.name,s=443,n=`${h??""}${o}`,t=a===d.code?6:4),(a===i.code||a===c.code)&&(e=S(a).name,s=parseInt(h??"")),(a===u.code||a===l.code)&&(e=S(a).name,n=`${h??""}${o}`,t=a===l.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({},S(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>S(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(En(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Xt.p2p.code&&t.push([n,s]),n===Xt["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?P(U.decode(`z${n}`),"base58btc"):P(V.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return K(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(o=>o.resolvable);if(e==null)return[this];let n=Ks.get(e.name);if(n==null)throw new N(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(o=>fe(o))}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)}[ec](){return`Multiaddr(${this.#t})`}};var Ks=new Map;function Js(r){return!!r?.[vn]}function fe(r){return new Ye(r)}var nc=r=>r.toString().split("/").slice(1),de=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),L=r=>({match:t=>de(e=>e===r).match(t),pattern:r}),rr=()=>({match:r=>de(t=>typeof t=="string").match(r),pattern:"{string}"}),nr=()=>({match:r=>de(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),F=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{U.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),tr=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ur.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),H=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),X=(...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(", ")})`}),_=(...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 C(...r){function t(s){let o=nc(s);for(let i of r){let c=i.match(o);if(c===!1)return!1;o=c}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matches:e,exactMatch:n}}var kn=_(L("dns4"),rr()),An=_(L("dns6"),rr()),Ln=_(L("dnsaddr"),rr()),Zs=_(L("dns"),rr()),cm=C(kn),lm=C(An),um=C(Ln),Ys=C(X(Zs,Ln,kn,An)),to=_(L("ip4"),de(Wt)),eo=_(L("ip6"),de(Gt)),ro=X(to,eo),it=X(ro,Zs,kn,An,Ln),hm=C(it),fm=C(to),dm=C(eo),pm=C(ro),sr=_(it,L("tcp"),nr()),pe=_(it,L("udp"),nr()),sc=X(sr,pe),mm=C(sr),gm=C(pe),In=_(pe,L("quic")),or=_(pe,L("quic-v1")),oc=X(In,or),wm=C(In),bm=C(or),Sn=X(it,sr,pe,In,or),no=X(_(Sn,L("ws"),H(F()))),ym=C(no),so=X(_(Sn,L("wss"),H(F())),_(Sn,L("tls"),L("ws"),H(F()))),xm=C(so),oo=_(sc,L("webrtc-direct"),tr(),H(tr()),H(F())),Em=C(oo),io=_(or,L("webtransport"),tr(),tr(),H(F())),vm=C(io),er=X(no,so,_(sr,H(F())),_(oc,H(F())),_(it,H(F())),oo,io,F()),Sm=C(er),ic=_(er,L("p2p-circuit"),F()),km=C(ic),ac=X(_(er,L("p2p-circuit"),L("webrtc"),F()),_(er,L("webrtc"),H(F())),L("webrtc")),Am=C(ac),cc=X(_(it,L("tcp"),nr(),L("http"),H(F())),_(it,L("http"),H(F()))),ao=C(cc),lc=X(_(it,L("tcp"),X(_(L("443"),L("http")),_(nr(),L("https"))),H(F())),_(it,L("tls"),L("http"),H(F())),_(it,L("https"),H(F()))),co=C(lc);var uc=[S("tcp").code,S("dns").code,S("dnsaddr").code,S("dns4").code,S("dns6").code];function lo(r){let t;try{t=S("sni").code}catch{return null}for(let[e,n]of r)if(e===t&&n!==void 0)return n;return null}function uo(r){return r.some(([t,e])=>t===S("tls").code)}function Q(r,t,e){let n=ho[S(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${S(r).name}`);let s=n(t,e);return r===S("ip6").code?`[${s}]`:s}var ho={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://${Q(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://${Q(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`${Q(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`${Q(e[0],e[1]??"",t)}/p2p/${r}`},http:(r,t)=>{let e=uo(t),n=lo(t);if(e&&n!==null)return`https://${n}`;let s=e?"https://":"http://",o=t.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=Q(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},tls:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return Q(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return Q(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=Q(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=uo(t),n=lo(t);if(e&&n!==null)return`wss://${n}`;let s=e?"wss://":"ws://",o=t.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=Q(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},wss:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=Q(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`${Q(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`${Q(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`${Q(e[0],e[1]??"",t)}/p2p-webrtc-direct`}};function fo(r,t){let n=fe(r).stringTuples(),s=n.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=S(s[0]),i=ho[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let c=i(s[1]??"",n);return t?.assumeHttp!==!1&&uc.includes(s[0])&&(c=c.replace(/^.*:\/\//,""),s[1]==="443"?c=`https://${c}`:c=`http://${c}`),(c.startsWith("http://")||c.startsWith("https://"))&&(c=new URL(c).toString(),c.endsWith("/")&&(c=c.substring(0,c.length-1))),c}var Tt=class{url;#t=0;#e=0;#r=0;#n=0;#s=new Map;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}`)}#o(t){let e=t.multihash.bytes;return J.encode(e)}async getRawBlock(t,e){let n=new URL(this.url.toString());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`);let s=this.#o(t);try{let o=this.#s.get(s);return o==null&&(this.#t++,o=fetch(n.toString(),{signal:e,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async i=>{if(this.log("GET %s %d",n,i.status),!i.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await i.arrayBuffer())}),this.#s.set(s,o)),await o}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}`))}finally{this.#s.delete(s)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#n/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#n,pendingResponses:this.#s.size}}};var hc=!1,fc=!1,Tn=class extends It{routing;allowInsecure;allowLocal;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??hc,this.allowLocal=e.allowLocal??fc}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let s=await e.getRawBlock(t,n.signal);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(s),s}async*findNewProviders(t,e={}){for await(let n of this.routing.findProviders(t,e)){let s=dc(n.multiaddrs,this.allowInsecure,this.allowLocal);if(s.length===0)continue;let o=fo(s[0]);this.log("found http-gateway provider %p %s for cid %c",n.id,o,t),yield new Tt(o,this.logger)}}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}};function dc(r,t,e){return r.filter(n=>co.matches(n)||t&&ao.matches(n)?e||Ys.matches(n)?!0:Fs(n.toOptions().host)===!1:!1)}function po(r,t){return new Tn(r,t)}var ir=class{components;gateways;routing;log;logger;constructor(t,e={}){this.components=t,this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.gateways=(e.gateways??mo).map(n=>new Tt(n,t.logger))}addGateway(t){this.gateways.push(new Tt(t,this.components.logger))}async retrieve(t,e={}){let n=this.gateways.sort((o,i)=>i.reliability()-o.reliability()),s=[];for(let o of n){this.log("getting block for %c from %s",t,o.url);try{let i=await o.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(i)}catch(c){throw this.log.error("failed to validate block for %c from %s",t,o.url,c),o.incrementInvalidBlocks(),new Error(`Block for CID ${t} from gateway ${o.url} failed validation`)}return i}catch(i){if(this.log.error("failed to get block for %c from %s",t,o.url,i),i instanceof Error?s.push(i):s.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.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`)}createSession(t={}){return po({logger:this.logger,routing:this.routing},t)}};var mo=["https://trustless-gateway.link","https://cloudflare-ipfs.com","https://4everland.io"];function go(r={}){return t=>new ir(t,r)}return vo(pc);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/esm/utils.js:
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import type { ComponentLogger } from '@libp2p/interface';
|
|
2
2
|
import type { CID } from 'multiformats/cid';
|
|
3
|
+
export interface TrustlessGatewayStats {
|
|
4
|
+
attempts: number;
|
|
5
|
+
errors: number;
|
|
6
|
+
invalidBlocks: number;
|
|
7
|
+
successes: number;
|
|
8
|
+
pendingResponses?: number;
|
|
9
|
+
}
|
|
3
10
|
/**
|
|
4
11
|
* A `TrustlessGateway` keeps track of the number of attempts, errors, and
|
|
5
12
|
* successes for a given gateway url so that we can prioritize gateways that
|
|
@@ -29,5 +36,6 @@ export declare class TrustlessGateway {
|
|
|
29
36
|
* Increment the number of invalid blocks returned by this gateway.
|
|
30
37
|
*/
|
|
31
38
|
incrementInvalidBlocks(): void;
|
|
39
|
+
getStats(): TrustlessGatewayStats;
|
|
32
40
|
}
|
|
33
41
|
//# sourceMappingURL=trustless-gateway.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trustless-gateway.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"trustless-gateway.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAU,MAAM,mBAAmB,CAAA;AAChE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,aAAa,EAAE,MAAM,CAAA;IACrB,SAAS,EAAE,MAAM,CAAA;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED;;;;;GAKG;AACH,qBAAa,gBAAgB;;IAC3B,SAAgB,GAAG,EAAE,GAAG,CAAA;IAoCxB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;gBAEf,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,MAAM,EAAE,eAAe;IAmBvD;;;OAGG;IACG,WAAW,CAAE,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;IAgDvE;;;;;;;OAOG;IACH,WAAW,IAAK,MAAM;IAyBtB;;OAEG;IACH,sBAAsB,IAAK,IAAI;IAI/B,QAAQ,IAAK,qBAAqB;CASnC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { base64 } from 'multiformats/bases/base64';
|
|
1
2
|
/**
|
|
2
3
|
* A `TrustlessGateway` keeps track of the number of attempts, errors, and
|
|
3
4
|
* successes for a given gateway url so that we can prioritize gateways that
|
|
@@ -30,11 +31,30 @@ export class TrustlessGateway {
|
|
|
30
31
|
* The number of times this gateway has successfully fetched a block.
|
|
31
32
|
*/
|
|
32
33
|
#successes = 0;
|
|
34
|
+
/**
|
|
35
|
+
* A map of pending responses for this gateway. This is used to ensure that
|
|
36
|
+
* only one request per CID is made to a given gateway at a time, and that we
|
|
37
|
+
* don't make multiple in-flight requests for the same CID to the same gateway.
|
|
38
|
+
*/
|
|
39
|
+
#pendingResponses = new Map();
|
|
33
40
|
log;
|
|
34
41
|
constructor(url, logger) {
|
|
35
42
|
this.url = url instanceof URL ? url : new URL(url);
|
|
36
43
|
this.log = logger.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`);
|
|
37
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* This function returns a unique string for the multihash.bytes of the CID.
|
|
47
|
+
*
|
|
48
|
+
* Some useful resources for why this is needed can be found using the links below:
|
|
49
|
+
*
|
|
50
|
+
* - https://github.com/ipfs/helia/pull/503#discussion_r1572451331
|
|
51
|
+
* - https://github.com/ipfs/kubo/issues/6815
|
|
52
|
+
* - https://www.notion.so/pl-strflt/Handling-ambiguity-around-CIDs-9d5e14f6516f438980b01ef188efe15d#d9d45cd1ed8b4d349b96285de4aed5ab
|
|
53
|
+
*/
|
|
54
|
+
#uniqueBlockId(cid) {
|
|
55
|
+
const multihashBytes = cid.multihash.bytes;
|
|
56
|
+
return base64.encode(multihashBytes);
|
|
57
|
+
}
|
|
38
58
|
/**
|
|
39
59
|
* Fetch a raw block from `this.url` following the specification defined at
|
|
40
60
|
* https://specs.ipfs.tech/http-gateways/trustless-gateway/
|
|
@@ -48,24 +68,29 @@ export class TrustlessGateway {
|
|
|
48
68
|
if (signal?.aborted === true) {
|
|
49
69
|
throw new Error(`Signal to fetch raw block for CID ${cid} from gateway ${this.url} was aborted prior to fetch`);
|
|
50
70
|
}
|
|
71
|
+
const blockId = this.#uniqueBlockId(cid);
|
|
51
72
|
try {
|
|
52
|
-
this.#
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
73
|
+
let pendingResponse = this.#pendingResponses.get(blockId);
|
|
74
|
+
if (pendingResponse == null) {
|
|
75
|
+
this.#attempts++;
|
|
76
|
+
pendingResponse = fetch(gwUrl.toString(), {
|
|
77
|
+
signal,
|
|
78
|
+
headers: {
|
|
79
|
+
Accept: 'application/vnd.ipld.raw'
|
|
80
|
+
},
|
|
81
|
+
cache: 'force-cache'
|
|
82
|
+
}).then(async (res) => {
|
|
83
|
+
this.log('GET %s %d', gwUrl, res.status);
|
|
84
|
+
if (!res.ok) {
|
|
85
|
+
this.#errors++;
|
|
86
|
+
throw new Error(`unable to fetch raw block for CID ${cid} from gateway ${this.url}`);
|
|
87
|
+
}
|
|
88
|
+
this.#successes++;
|
|
89
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
90
|
+
});
|
|
91
|
+
this.#pendingResponses.set(blockId, pendingResponse);
|
|
66
92
|
}
|
|
67
|
-
|
|
68
|
-
return new Uint8Array(await res.arrayBuffer());
|
|
93
|
+
return await pendingResponse;
|
|
69
94
|
}
|
|
70
95
|
catch (cause) {
|
|
71
96
|
// @ts-expect-error - TS thinks signal?.aborted can only be false now
|
|
@@ -76,6 +101,9 @@ export class TrustlessGateway {
|
|
|
76
101
|
this.#errors++;
|
|
77
102
|
throw new Error(`unable to fetch raw block for CID ${cid}`);
|
|
78
103
|
}
|
|
104
|
+
finally {
|
|
105
|
+
this.#pendingResponses.delete(blockId);
|
|
106
|
+
}
|
|
79
107
|
}
|
|
80
108
|
/**
|
|
81
109
|
* Encapsulate the logic for determining whether a gateway is considered
|
|
@@ -113,5 +141,14 @@ export class TrustlessGateway {
|
|
|
113
141
|
incrementInvalidBlocks() {
|
|
114
142
|
this.#invalidBlocks++;
|
|
115
143
|
}
|
|
144
|
+
getStats() {
|
|
145
|
+
return {
|
|
146
|
+
attempts: this.#attempts,
|
|
147
|
+
errors: this.#errors,
|
|
148
|
+
invalidBlocks: this.#invalidBlocks,
|
|
149
|
+
successes: this.#successes,
|
|
150
|
+
pendingResponses: this.#pendingResponses.size
|
|
151
|
+
};
|
|
152
|
+
}
|
|
116
153
|
}
|
|
117
154
|
//# sourceMappingURL=trustless-gateway.js.map
|
|
@@ -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":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAA;AAYlD;;;;;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;IAEd;;;;OAIG;IACH,iBAAiB,GAAG,IAAI,GAAG,EAA+B,CAAA;IAEzC,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;;;;;;;;OAQG;IACH,cAAc,CAAE,GAAQ;QACtB,MAAM,cAAc,GAAG,GAAG,CAAC,SAAS,CAAC,KAAK,CAAA;QAC1C,OAAO,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAA;IACtC,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,WAAW,CAAE,GAAQ,EAAE,MAAoB;QAC/C,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAA;QAC1C,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,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,CAAA;QACxC,IAAI,CAAC;YACH,IAAI,eAAe,GAAoC,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;YAC1F,IAAI,eAAe,IAAI,IAAI,EAAE,CAAC;gBAC5B,IAAI,CAAC,SAAS,EAAE,CAAA;gBAChB,eAAe,GAAG,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE;oBACxC,MAAM;oBACN,OAAO,EAAE;wBACP,MAAM,EAAE,0BAA0B;qBACnC;oBACD,KAAK,EAAE,aAAa;iBACrB,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;oBACpB,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;oBACxC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;wBACZ,IAAI,CAAC,OAAO,EAAE,CAAA;wBACd,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,iBAAiB,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;oBACtF,CAAC;oBACD,IAAI,CAAC,UAAU,EAAE,CAAA;oBACjB,OAAO,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,WAAW,EAAE,CAAC,CAAA;gBAChD,CAAC,CAAC,CAAA;gBACF,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,OAAO,EAAE,eAAe,CAAC,CAAA;YACtD,CAAC;YACD,OAAO,MAAM,eAAe,CAAA;QAC9B,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;gBAAS,CAAC;YACT,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;QACxC,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;IAED,QAAQ;QACN,OAAO;YACL,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,MAAM,EAAE,IAAI,CAAC,OAAO;YACpB,aAAa,EAAE,IAAI,CAAC,cAAc;YAClC,SAAS,EAAE,IAAI,CAAC,UAAU;YAC1B,gBAAgB,EAAE,IAAI,CAAC,iBAAiB,CAAC,IAAI;SAC9C,CAAA;IACH,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@helia/block-brokers",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.1-52dbcf2",
|
|
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,9 +53,9 @@
|
|
|
53
53
|
"test:electron-main": "aegir test -t electron-main"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@helia/bitswap": "
|
|
57
|
-
"@helia/interface": "
|
|
58
|
-
"@helia/utils": "
|
|
56
|
+
"@helia/bitswap": "1.0.1-52dbcf2",
|
|
57
|
+
"@helia/interface": "4.2.0-52dbcf2",
|
|
58
|
+
"@helia/utils": "0.2.0-52dbcf2",
|
|
59
59
|
"@libp2p/interface": "^1.1.4",
|
|
60
60
|
"@libp2p/utils": "^5.2.6",
|
|
61
61
|
"@multiformats/multiaddr": "^12.2.1",
|
|
@@ -70,6 +70,7 @@
|
|
|
70
70
|
"@libp2p/logger": "^4.0.7",
|
|
71
71
|
"@libp2p/peer-id-factory": "^4.0.7",
|
|
72
72
|
"@multiformats/uri-to-multiaddr": "^8.0.0",
|
|
73
|
+
"@types/polka": "^0.5.7",
|
|
73
74
|
"@types/sinon": "^17.0.3",
|
|
74
75
|
"aegir": "^42.2.5",
|
|
75
76
|
"cors": "^2.8.5",
|
|
@@ -1,6 +1,15 @@
|
|
|
1
|
+
import { base64 } from 'multiformats/bases/base64'
|
|
1
2
|
import type { ComponentLogger, Logger } from '@libp2p/interface'
|
|
2
3
|
import type { CID } from 'multiformats/cid'
|
|
3
4
|
|
|
5
|
+
export interface TrustlessGatewayStats {
|
|
6
|
+
attempts: number
|
|
7
|
+
errors: number
|
|
8
|
+
invalidBlocks: number
|
|
9
|
+
successes: number
|
|
10
|
+
pendingResponses?: number
|
|
11
|
+
}
|
|
12
|
+
|
|
4
13
|
/**
|
|
5
14
|
* A `TrustlessGateway` keeps track of the number of attempts, errors, and
|
|
6
15
|
* successes for a given gateway url so that we can prioritize gateways that
|
|
@@ -37,6 +46,13 @@ export class TrustlessGateway {
|
|
|
37
46
|
*/
|
|
38
47
|
#successes = 0
|
|
39
48
|
|
|
49
|
+
/**
|
|
50
|
+
* A map of pending responses for this gateway. This is used to ensure that
|
|
51
|
+
* only one request per CID is made to a given gateway at a time, and that we
|
|
52
|
+
* don't make multiple in-flight requests for the same CID to the same gateway.
|
|
53
|
+
*/
|
|
54
|
+
#pendingResponses = new Map<string, Promise<Uint8Array>>()
|
|
55
|
+
|
|
40
56
|
private readonly log: Logger
|
|
41
57
|
|
|
42
58
|
constructor (url: URL | string, logger: ComponentLogger) {
|
|
@@ -44,6 +60,20 @@ export class TrustlessGateway {
|
|
|
44
60
|
this.log = logger.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)
|
|
45
61
|
}
|
|
46
62
|
|
|
63
|
+
/**
|
|
64
|
+
* This function returns a unique string for the multihash.bytes of the CID.
|
|
65
|
+
*
|
|
66
|
+
* Some useful resources for why this is needed can be found using the links below:
|
|
67
|
+
*
|
|
68
|
+
* - https://github.com/ipfs/helia/pull/503#discussion_r1572451331
|
|
69
|
+
* - https://github.com/ipfs/kubo/issues/6815
|
|
70
|
+
* - https://www.notion.so/pl-strflt/Handling-ambiguity-around-CIDs-9d5e14f6516f438980b01ef188efe15d#d9d45cd1ed8b4d349b96285de4aed5ab
|
|
71
|
+
*/
|
|
72
|
+
#uniqueBlockId (cid: CID): string {
|
|
73
|
+
const multihashBytes = cid.multihash.bytes
|
|
74
|
+
return base64.encode(multihashBytes)
|
|
75
|
+
}
|
|
76
|
+
|
|
47
77
|
/**
|
|
48
78
|
* Fetch a raw block from `this.url` following the specification defined at
|
|
49
79
|
* https://specs.ipfs.tech/http-gateways/trustless-gateway/
|
|
@@ -60,26 +90,29 @@ export class TrustlessGateway {
|
|
|
60
90
|
throw new Error(`Signal to fetch raw block for CID ${cid} from gateway ${this.url} was aborted prior to fetch`)
|
|
61
91
|
}
|
|
62
92
|
|
|
93
|
+
const blockId = this.#uniqueBlockId(cid)
|
|
63
94
|
try {
|
|
64
|
-
this.#
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
95
|
+
let pendingResponse: Promise<Uint8Array> | undefined = this.#pendingResponses.get(blockId)
|
|
96
|
+
if (pendingResponse == null) {
|
|
97
|
+
this.#attempts++
|
|
98
|
+
pendingResponse = fetch(gwUrl.toString(), {
|
|
99
|
+
signal,
|
|
100
|
+
headers: {
|
|
101
|
+
Accept: 'application/vnd.ipld.raw'
|
|
102
|
+
},
|
|
103
|
+
cache: 'force-cache'
|
|
104
|
+
}).then(async (res) => {
|
|
105
|
+
this.log('GET %s %d', gwUrl, res.status)
|
|
106
|
+
if (!res.ok) {
|
|
107
|
+
this.#errors++
|
|
108
|
+
throw new Error(`unable to fetch raw block for CID ${cid} from gateway ${this.url}`)
|
|
109
|
+
}
|
|
110
|
+
this.#successes++
|
|
111
|
+
return new Uint8Array(await res.arrayBuffer())
|
|
112
|
+
})
|
|
113
|
+
this.#pendingResponses.set(blockId, pendingResponse)
|
|
80
114
|
}
|
|
81
|
-
|
|
82
|
-
return new Uint8Array(await res.arrayBuffer())
|
|
115
|
+
return await pendingResponse
|
|
83
116
|
} catch (cause) {
|
|
84
117
|
// @ts-expect-error - TS thinks signal?.aborted can only be false now
|
|
85
118
|
// because it was checked for true above.
|
|
@@ -88,6 +121,8 @@ export class TrustlessGateway {
|
|
|
88
121
|
}
|
|
89
122
|
this.#errors++
|
|
90
123
|
throw new Error(`unable to fetch raw block for CID ${cid}`)
|
|
124
|
+
} finally {
|
|
125
|
+
this.#pendingResponses.delete(blockId)
|
|
91
126
|
}
|
|
92
127
|
}
|
|
93
128
|
|
|
@@ -130,4 +165,14 @@ export class TrustlessGateway {
|
|
|
130
165
|
incrementInvalidBlocks (): void {
|
|
131
166
|
this.#invalidBlocks++
|
|
132
167
|
}
|
|
168
|
+
|
|
169
|
+
getStats (): TrustlessGatewayStats {
|
|
170
|
+
return {
|
|
171
|
+
attempts: this.#attempts,
|
|
172
|
+
errors: this.#errors,
|
|
173
|
+
invalidBlocks: this.#invalidBlocks,
|
|
174
|
+
successes: this.#successes,
|
|
175
|
+
pendingResponses: this.#pendingResponses.size
|
|
176
|
+
}
|
|
177
|
+
}
|
|
133
178
|
}
|
package/dist/typedoc-urls.json
DELETED