helia 0.0.0-97da23e
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/LICENSE +4 -0
- package/README.md +59 -0
- package/dist/index.min.js +3 -0
- package/dist/src/helia.d.ts +16 -0
- package/dist/src/helia.d.ts.map +1 -0
- package/dist/src/helia.js +63 -0
- package/dist/src/helia.js.map +1 -0
- package/dist/src/index.d.ts +63 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +38 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/storage.d.ts +62 -0
- package/dist/src/storage.d.ts.map +1 -0
- package/dist/src/storage.js +109 -0
- package/dist/src/storage.js.map +1 -0
- package/package.json +165 -0
- package/src/helia.ts +68 -0
- package/src/index.ts +78 -0
- package/src/storage.ts +138 -0
package/LICENSE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://github.com/ipfs/helia" title="Helia">
|
|
3
|
+
<img src="https://raw.githubusercontent.com/ipfs/helia/main/assets/helia.png" alt="Helia logo" width="300" />
|
|
4
|
+
</a>
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
# helia <!-- omit in toc -->
|
|
8
|
+
|
|
9
|
+
[](https://ipfs.tech)
|
|
10
|
+
[](https://discuss.ipfs.tech)
|
|
11
|
+
[](https://codecov.io/gh/ipfs/helia)
|
|
12
|
+
[](https://github.com/ipfs/helia/actions/workflows/main.yml?query=branch%3Amain)
|
|
13
|
+
|
|
14
|
+
> An implementation of IPFS in JavaScript
|
|
15
|
+
|
|
16
|
+
## Table of contents <!-- omit in toc -->
|
|
17
|
+
|
|
18
|
+
- [Install](#install)
|
|
19
|
+
- [Browser `<script>` tag](#browser-script-tag)
|
|
20
|
+
- [API Docs](#api-docs)
|
|
21
|
+
- [License](#license)
|
|
22
|
+
- [Contribute](#contribute)
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```console
|
|
27
|
+
$ npm i helia
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Browser `<script>` tag
|
|
31
|
+
|
|
32
|
+
Loading this module through a script tag will make it's exports available as `Helia` in the global namespace.
|
|
33
|
+
|
|
34
|
+
```html
|
|
35
|
+
<script src="https://unpkg.com/helia/dist/index.min.js"></script>
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## API Docs
|
|
39
|
+
|
|
40
|
+
- <https://ipfs.github.io/helia/modules/helia.html>
|
|
41
|
+
|
|
42
|
+
## License
|
|
43
|
+
|
|
44
|
+
Licensed under either of
|
|
45
|
+
|
|
46
|
+
- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
|
|
47
|
+
- MIT ([LICENSE-MIT](LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
|
|
48
|
+
|
|
49
|
+
## Contribute
|
|
50
|
+
|
|
51
|
+
Contributions welcome! Please check out [the issues](https://github.com/ipfs/helia/issues).
|
|
52
|
+
|
|
53
|
+
Also see our [contributing document](https://github.com/ipfs/community/blob/master/CONTRIBUTING_JS.md) for more information on how we work, and about contributing in general.
|
|
54
|
+
|
|
55
|
+
Please be aware that all interactions related to this repo are subject to the IPFS [Code of Conduct](https://github.com/ipfs/community/blob/master/code-of-conduct.md).
|
|
56
|
+
|
|
57
|
+
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
|
|
58
|
+
|
|
59
|
+
[](https://github.com/ipfs/community/blob/master/CONTRIBUTING.md)
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Helia = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
+
"use strict";var Helia=(()=>{var Ms=Object.create;var jt=Object.defineProperty;var Fs=Object.getOwnPropertyDescriptor;var Ds=Object.getOwnPropertyNames;var Ns=Object.getPrototypeOf,Os=Object.prototype.hasOwnProperty;var v=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),M=(r,t)=>{for(var e in t)jt(r,e,{get:t[e],enumerable:!0})},Wr=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ds(t))!Os.call(r,i)&&i!==e&&jt(r,i,{get:()=>t[i],enumerable:!(n=Fs(t,i))||n.enumerable});return r};var L=(r,t,e)=>(e=r!=null?Ms(Ns(r)):{},Wr(t||!r||!r.__esModule?jt(e,"default",{value:r,enumerable:!0}):e,r)),Ps=r=>Wr(jt({},"__esModule",{value:!0}),r);var ln=v((Vc,un)=>{un.exports=cn;var an=128,ko=127,Eo=~ko,So=Math.pow(2,31);function cn(r,t,e){t=t||[],e=e||0;for(var n=e;r>=So;)t[e++]=r&255|an,r/=128;for(;r&Eo;)t[e++]=r&255|an,r>>>=7;return t[e]=r|0,cn.bytes=e-n+1,t}});var dn=v(($c,fn)=>{fn.exports=$e;var Bo=128,hn=127;function $e(r,n){var e=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw $e.bytes=0,new RangeError("Could not decode varint");o=r[s++],e+=i<28?(o&hn)<<i:(o&hn)*Math.pow(2,i),i+=7}while(o>=Bo);return $e.bytes=s-n,e}});var gn=v((Gc,pn)=>{var Co=Math.pow(2,7),Ao=Math.pow(2,14),To=Math.pow(2,21),Lo=Math.pow(2,28),Mo=Math.pow(2,35),Fo=Math.pow(2,42),Do=Math.pow(2,49),No=Math.pow(2,56),Oo=Math.pow(2,63);pn.exports=function(r){return r<Co?1:r<Ao?2:r<To?3:r<Lo?4:r<Mo?5:r<Fo?6:r<Do?7:r<No?8:r<Oo?9:10}});var yn=v((jc,mn)=>{mn.exports={encode:ln(),decode:dn(),encodingLength:gn()}});var _n=v((Kc,bn)=>{"use strict";var wn=yn();bn.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=wn.decode(r);t.push(e),r=r.slice(wn.decode.bytes)}return t}});var kn=v((Qc,xn)=>{xn.exports=Ge;var vn=128,Po=127,zo=~Po,Io=Math.pow(2,31);function Ge(r,t,e){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Ge.bytes=0,new RangeError("Could not encode varint");t=t||[],e=e||0;for(var n=e;r>=Io;)t[e++]=r&255|vn,r/=128;for(;r&zo;)t[e++]=r&255|vn,r>>>=7;return t[e]=r|0,Ge.bytes=e-n+1,t}});var Bn=v((Xc,Sn)=>{Sn.exports=je;var Ro=128,En=127;function je(r,n){var e=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a||i>49)throw je.bytes=0,new RangeError("Could not decode varint");o=r[s++],e+=i<28?(o&En)<<i:(o&En)*Math.pow(2,i),i+=7}while(o>=Ro);return je.bytes=s-n,e}});var An=v((Jc,Cn)=>{var Uo=Math.pow(2,7),Ho=Math.pow(2,14),Wo=Math.pow(2,21),qo=Math.pow(2,28),Vo=Math.pow(2,35),$o=Math.pow(2,42),Go=Math.pow(2,49),jo=Math.pow(2,56),Ko=Math.pow(2,63);Cn.exports=function(r){return r<Uo?1:r<Ho?2:r<Wo?3:r<qo?4:r<Vo?5:r<$o?6:r<Go?7:r<jo?8:r<Ko?9:10}});var Ln=v((Zc,Tn)=>{Tn.exports={encode:kn(),decode:Bn(),encodingLength:An()}});var Dn=v((tu,Fn)=>{var St=1e3,Bt=St*60,Ct=Bt*60,ct=Ct*24,Xo=ct*7,Jo=ct*365.25;Fn.exports=function(r,t){t=t||{};var e=typeof r;if(e==="string"&&r.length>0)return Zo(r);if(e==="number"&&isFinite(r))return t.long?ta(r):Yo(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Zo(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*Jo;case"weeks":case"week":case"w":return e*Xo;case"days":case"day":case"d":return e*ct;case"hours":case"hour":case"hrs":case"hr":case"h":return e*Ct;case"minutes":case"minute":case"mins":case"min":case"m":return e*Bt;case"seconds":case"second":case"secs":case"sec":case"s":return e*St;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:return}}}}function Yo(r){var t=Math.abs(r);return t>=ct?Math.round(r/ct)+"d":t>=Ct?Math.round(r/Ct)+"h":t>=Bt?Math.round(r/Bt)+"m":t>=St?Math.round(r/St)+"s":r+"ms"}function ta(r){var t=Math.abs(r);return t>=ct?Qt(r,t,ct,"day"):t>=Ct?Qt(r,t,Ct,"hour"):t>=Bt?Qt(r,t,Bt,"minute"):t>=St?Qt(r,t,St,"second"):r+" ms"}function Qt(r,t,e,n){var i=t>=e*1.5;return Math.round(r/e)+" "+n+(i?"s":"")}});var On=v((eu,Nn)=>{function ea(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=i,e.enabled=o,e.humanize=Dn(),e.destroy=u,Object.keys(r).forEach(l=>{e[l]=r[l]}),e.names=[],e.skips=[],e.formatters={};function t(l){let h=0;for(let f=0;f<l.length;f++)h=(h<<5)-h+l.charCodeAt(f),h|=0;return e.colors[Math.abs(h)%e.colors.length]}e.selectColor=t;function e(l){let h,f=null,m,d;function p(...y){if(!p.enabled)return;let E=p,C=Number(new Date),P=C-(h||C);E.diff=P,E.prev=h,E.curr=C,h=C,y[0]=e.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let T=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(z,D)=>{if(z==="%%")return"%";T++;let I=e.formatters[D];if(typeof I=="function"){let bt=y[T];z=I.call(E,bt),y.splice(T,1),T--}return z}),e.formatArgs.call(E,y),(E.log||e.log).apply(E,y)}return p.namespace=l,p.useColors=e.useColors(),p.color=e.selectColor(l),p.extend=n,p.destroy=e.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(m!==e.namespaces&&(m=e.namespaces,d=e.enabled(l)),d),set:y=>{f=y}}),typeof e.init=="function"&&e.init(p),p}function n(l,h){let f=e(this.namespace+(typeof h>"u"?":":h)+l);return f.log=this.log,f}function i(l){e.save(l),e.namespaces=l,e.names=[],e.skips=[];let h,f=(typeof l=="string"?l:"").split(/[\s,]+/),m=f.length;for(h=0;h<m;h++)f[h]&&(l=f[h].replace(/\*/g,".*?"),l[0]==="-"?e.skips.push(new RegExp("^"+l.slice(1)+"$")):e.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...e.names.map(a),...e.skips.map(a).map(h=>"-"+h)].join(",");return e.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let h,f;for(h=0,f=e.skips.length;h<f;h++)if(e.skips[h].test(l))return!1;for(h=0,f=e.names.length;h<f;h++)if(e.names[h].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.enable(e.load()),e}Nn.exports=ea});var Pn=v((N,Xt)=>{N.formatArgs=na;N.save=ia;N.load=sa;N.useColors=ra;N.storage=oa();N.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`."))}})();N.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 ra(){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 na(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Xt.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,i=>{i!=="%%"&&(e++,i==="%c"&&(n=e))}),r.splice(n,0,t)}N.log=console.debug||console.log||(()=>{});function ia(r){try{r?N.storage.setItem("debug",r):N.storage.removeItem("debug")}catch{}}function sa(){let r;try{r=N.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function oa(){try{return localStorage}catch{}}Xt.exports=On()(N);var{formatters:aa}=Xt.exports;aa.j=function(r){try{return JSON.stringify(r)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Rn=v((yu,In)=>{"use strict";In.exports=ha;function ha(r,t){for(var e=new Array(arguments.length-1),n=0,i=2,s=!0;i<arguments.length;)e[n++]=arguments[i++];return new Promise(function(a,c){e[n]=function(l){if(s)if(s=!1,l)c(l);else{for(var h=new Array(arguments.length-1),f=0;f<h.length;)h[f++]=arguments[f];a.apply(null,h)}};try{r.apply(t||null,e)}catch(u){s&&(s=!1,c(u))}})}});var qn=v(Wn=>{"use strict";var Yt=Wn;Yt.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;--e%4>1&&t.charAt(e)==="=";)++n;return Math.ceil(t.length*3)/4-n};var At=new Array(64),Hn=new Array(123);for(W=0;W<64;)Hn[At[W]=W<26?W+65:W<52?W+71:W<62?W-4:W-59|43]=W++;var W;Yt.encode=function(t,e,n){for(var i=null,s=[],o=0,a=0,c;e<n;){var u=t[e++];switch(a){case 0:s[o++]=At[u>>2],c=(u&3)<<4,a=1;break;case 1:s[o++]=At[c|u>>4],c=(u&15)<<2,a=2;break;case 2:s[o++]=At[c|u>>6],s[o++]=At[u&63],a=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return a&&(s[o++]=At[c],s[o++]=61,a===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var Un="invalid encoding";Yt.decode=function(t,e,n){for(var i=n,s=0,o,a=0;a<t.length;){var c=t.charCodeAt(a++);if(c===61&&s>1)break;if((c=Hn[c])===void 0)throw Error(Un);switch(s){case 0:o=c,s=1;break;case 1:e[n++]=o<<2|(c&48)>>4,o=c,s=2;break;case 2:e[n++]=(o&15)<<4|(c&60)>>2,o=c,s=3;break;case 3:e[n++]=(o&3)<<6|c,s=0;break}}if(s===1)throw Error(Un);return n-i};Yt.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}});var $n=v((bu,Vn)=>{"use strict";Vn.exports=te;function te(){this._listeners={}}te.prototype.on=function(t,e,n){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:e,ctx:n||this}),this};te.prototype.off=function(t,e){if(t===void 0)this._listeners={};else if(e===void 0)this._listeners[t]=[];else for(var n=this._listeners[t],i=0;i<n.length;)n[i].fn===e?n.splice(i,1):++i;return this};te.prototype.emit=function(t){var e=this._listeners[t];if(e){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<e.length;)e[i].fn.apply(e[i++].ctx,n)}return this}});var Zn=v((_u,Jn)=>{"use strict";Jn.exports=Gn(Gn);function Gn(r){return typeof Float32Array<"u"?function(){var t=new Float32Array([-0]),e=new Uint8Array(t.buffer),n=e[3]===128;function i(c,u,l){t[0]=c,u[l]=e[0],u[l+1]=e[1],u[l+2]=e[2],u[l+3]=e[3]}function s(c,u,l){t[0]=c,u[l]=e[3],u[l+1]=e[2],u[l+2]=e[1],u[l+3]=e[0]}r.writeFloatLE=n?i:s,r.writeFloatBE=n?s:i;function o(c,u){return e[0]=c[u],e[1]=c[u+1],e[2]=c[u+2],e[3]=c[u+3],t[0]}function a(c,u){return e[3]=c[u],e[2]=c[u+1],e[1]=c[u+2],e[0]=c[u+3],t[0]}r.readFloatLE=n?o:a,r.readFloatBE=n?a:o}():function(){function t(n,i,s,o){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var c=Math.floor(Math.log(i)/Math.LN2),u=Math.round(i*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,s,o)}}r.writeFloatLE=t.bind(null,jn),r.writeFloatBE=t.bind(null,Kn);function e(n,i,s){var o=n(i,s),a=(o>>31)*2+1,c=o>>>23&255,u=o&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}r.readFloatLE=e.bind(null,Qn),r.readFloatBE=e.bind(null,Xn)}(),typeof Float64Array<"u"?function(){var t=new Float64Array([-0]),e=new Uint8Array(t.buffer),n=e[7]===128;function i(c,u,l){t[0]=c,u[l]=e[0],u[l+1]=e[1],u[l+2]=e[2],u[l+3]=e[3],u[l+4]=e[4],u[l+5]=e[5],u[l+6]=e[6],u[l+7]=e[7]}function s(c,u,l){t[0]=c,u[l]=e[7],u[l+1]=e[6],u[l+2]=e[5],u[l+3]=e[4],u[l+4]=e[3],u[l+5]=e[2],u[l+6]=e[1],u[l+7]=e[0]}r.writeDoubleLE=n?i:s,r.writeDoubleBE=n?s:i;function o(c,u){return e[0]=c[u],e[1]=c[u+1],e[2]=c[u+2],e[3]=c[u+3],e[4]=c[u+4],e[5]=c[u+5],e[6]=c[u+6],e[7]=c[u+7],t[0]}function a(c,u){return e[7]=c[u],e[6]=c[u+1],e[5]=c[u+2],e[4]=c[u+3],e[3]=c[u+4],e[2]=c[u+5],e[1]=c[u+6],e[0]=c[u+7],t[0]}r.readDoubleLE=n?o:a,r.readDoubleBE=n?a:o}():function(){function t(n,i,s,o,a,c){var u=o<0?1:0;if(u&&(o=-o),o===0)n(0,a,c+i),n(1/o>0?0:2147483648,a,c+s);else if(isNaN(o))n(0,a,c+i),n(2146959360,a,c+s);else if(o>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+s);else{var l;if(o<22250738585072014e-324)l=o/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+s);else{var h=Math.floor(Math.log(o)/Math.LN2);h===1024&&(h=1023),l=o*Math.pow(2,-h),n(l*4503599627370496>>>0,a,c+i),n((u<<31|h+1023<<20|l*1048576&1048575)>>>0,a,c+s)}}}r.writeDoubleLE=t.bind(null,jn,0,4),r.writeDoubleBE=t.bind(null,Kn,4,0);function e(n,i,s,o,a){var c=n(o,a+i),u=n(o,a+s),l=(u>>31)*2+1,h=u>>>20&2047,f=4294967296*(u&1048575)+c;return h===2047?f?NaN:l*(1/0):h===0?l*5e-324*f:l*Math.pow(2,h-1075)*(f+4503599627370496)}r.readDoubleLE=e.bind(null,Qn,0,4),r.readDoubleBE=e.bind(null,Xn,4,0)}(),r}function jn(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 Kn(r,t,e){t[e]=r>>>24,t[e+1]=r>>>16&255,t[e+2]=r>>>8&255,t[e+3]=r&255}function Qn(r,t){return(r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24)>>>0}function Xn(r,t){return(r[t]<<24|r[t+1]<<16|r[t+2]<<8|r[t+3])>>>0}});var Yn=v((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(r){}return null}});var ei=v(ti=>{"use strict";var Xe=ti;Xe.length=function(t){for(var e=0,n=0,i=0;i<t.length;++i)n=t.charCodeAt(i),n<128?e+=1:n<2048?e+=2:(n&64512)===55296&&(t.charCodeAt(i+1)&64512)===56320?(++i,e+=4):e+=3;return e};Xe.read=function(t,e,n){var i=n-e;if(i<1)return"";for(var s=null,o=[],a=0,c;e<n;)c=t[e++],c<128?o[a++]=c:c>191&&c<224?o[a++]=(c&31)<<6|t[e++]&63:c>239&&c<365?(c=((c&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,o[a++]=55296+(c>>10),o[a++]=56320+(c&1023)):o[a++]=(c&15)<<12|(t[e++]&63)<<6|t[e++]&63,a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};Xe.write=function(t,e,n){for(var i=n,s,o,a=0;a<t.length;++a)s=t.charCodeAt(a),s<128?e[n++]=s:s<2048?(e[n++]=s>>6|192,e[n++]=s&63|128):(s&64512)===55296&&((o=t.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++a,e[n++]=s>>18|240,e[n++]=s>>12&63|128,e[n++]=s>>6&63|128,e[n++]=s&63|128):(e[n++]=s>>12|224,e[n++]=s>>6&63|128,e[n++]=s&63|128);return n-i}});var ni=v((xu,ri)=>{"use strict";ri.exports=fa;function fa(r,t,e){var n=e||8192,i=n>>>1,s=null,o=n;return function(c){if(c<1||c>i)return r(c);o+c>n&&(s=r(n),o=0);var u=t.call(s,o,o+=c);return o&7&&(o=(o|7)+1),u}}});var si=v((ku,ii)=>{"use strict";ii.exports=A;var zt=ht();function A(r,t){this.lo=r>>>0,this.hi=t>>>0}var lt=A.zero=new A(0,0);lt.toNumber=function(){return 0};lt.zzEncode=lt.zzDecode=function(){return this};lt.length=function(){return 1};var da=A.zeroHash="\0\0\0\0\0\0\0\0";A.fromNumber=function(t){if(t===0)return lt;var e=t<0;e&&(t=-t);var n=t>>>0,i=(t-n)/4294967296>>>0;return e&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new A(n,i)};A.from=function(t){if(typeof t=="number")return A.fromNumber(t);if(zt.isString(t))if(zt.Long)t=zt.Long.fromString(t);else return A.fromNumber(parseInt(t,10));return t.low||t.high?new A(t.low>>>0,t.high>>>0):lt};A.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var e=~this.lo+1>>>0,n=~this.hi>>>0;return e||(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296};A.prototype.toLong=function(t){return zt.Long?new zt.Long(this.lo|0,this.hi|0,Boolean(t)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(t)}};var rt=String.prototype.charCodeAt;A.fromHash=function(t){return t===da?lt:new A((rt.call(t,0)|rt.call(t,1)<<8|rt.call(t,2)<<16|rt.call(t,3)<<24)>>>0,(rt.call(t,4)|rt.call(t,5)<<8|rt.call(t,6)<<16|rt.call(t,7)<<24)>>>0)};A.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};A.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this};A.prototype.zzDecode=function(){var t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this};A.prototype.length=function(){var 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}});var ht=v(Je=>{"use strict";var g=Je;g.asPromise=Rn();g.base64=qn();g.EventEmitter=$n();g.float=Zn();g.inquire=Yn();g.utf8=ei();g.pool=ni();g.LongBits=si();g.isNode=Boolean(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);g.global=g.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||Je;g.emptyArray=Object.freeze?Object.freeze([]):[];g.emptyObject=Object.freeze?Object.freeze({}):{};g.isInteger=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t};g.isString=function(t){return typeof t=="string"||t instanceof String};g.isObject=function(t){return t&&typeof t=="object"};g.isset=g.isSet=function(t,e){var n=t[e];return n!=null&&t.hasOwnProperty(e)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};g.Buffer=function(){try{var r=g.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();g._Buffer_from=null;g._Buffer_allocUnsafe=null;g.newBuffer=function(t){return typeof t=="number"?g.Buffer?g._Buffer_allocUnsafe(t):new g.Array(t):g.Buffer?g._Buffer_from(t):typeof Uint8Array>"u"?t:new Uint8Array(t)};g.Array=typeof Uint8Array<"u"?Uint8Array:Array;g.Long=g.global.dcodeIO&&g.global.dcodeIO.Long||g.global.Long||g.inquire("long");g.key2Re=/^true|false|0|1$/;g.key32Re=/^-?(?:0|[1-9][0-9]*)$/;g.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;g.longToHash=function(t){return t?g.LongBits.from(t).toHash():g.LongBits.zeroHash};g.longFromHash=function(t,e){var n=g.LongBits.fromHash(t);return g.Long?g.Long.fromBits(n.lo,n.hi,e):n.toNumber(Boolean(e))};function oi(r,t,e){for(var n=Object.keys(t),i=0;i<n.length;++i)(r[n[i]]===void 0||!e)&&(r[n[i]]=t[n[i]]);return r}g.merge=oi;g.lcFirst=function(t){return t.charAt(0).toLowerCase()+t.substring(1)};function ai(r){function t(e,n){if(!(this instanceof t))return new t(e,n);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&oi(this,n)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return r},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}g.newError=ai;g.ProtocolError=ai("ProtocolError");g.oneOfGetter=function(t){for(var e={},n=0;n<t.length;++n)e[t[n]]=1;return function(){for(var i=Object.keys(this),s=i.length-1;s>-1;--s)if(e[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};g.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}};g.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};g._configure=function(){var r=g.Buffer;if(!r){g._Buffer_from=g._Buffer_allocUnsafe=null;return}g._Buffer_from=r.from!==Uint8Array.from&&r.from||function(e,n){return new r(e,n)},g._Buffer_allocUnsafe=r.allocUnsafe||function(e){return new r(e)}}});var tr=v((Su,fi)=>{"use strict";fi.exports=B;var $=ht(),Ye,li=$.LongBits,pa=$.utf8;function q(r,t){return RangeError("index out of range: "+r.pos+" + "+(t||1)+" > "+r.len)}function B(r){this.buf=r,this.pos=0,this.len=r.length}var ci=typeof Uint8Array<"u"?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new B(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new B(t);throw Error("illegal buffer")},hi=function(){return $.Buffer?function(e){return(B.create=function(i){return $.Buffer.isBuffer(i)?new Ye(i):ci(i)})(e)}:ci};B.create=hi();B.prototype._slice=$.Array.prototype.subarray||$.Array.prototype.slice;B.prototype.uint32=function(){var t=4294967295;return function(){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,q(this,10);return t}}();B.prototype.int32=function(){return this.uint32()|0};B.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(t&1)|0};function Ze(){var r=new li(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(r.lo=(r.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw q(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,r}if(this.len-this.pos>4){for(;t<5;++t)if(r.hi=(r.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return r}else for(;t<5;++t){if(this.pos>=this.len)throw q(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}B.prototype.bool=function(){return this.uint32()!==0};function ee(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}B.prototype.fixed32=function(){if(this.pos+4>this.len)throw q(this,4);return ee(this.buf,this.pos+=4)};B.prototype.sfixed32=function(){if(this.pos+4>this.len)throw q(this,4);return ee(this.buf,this.pos+=4)|0};function ui(){if(this.pos+8>this.len)throw q(this,8);return new li(ee(this.buf,this.pos+=4),ee(this.buf,this.pos+=4))}B.prototype.float=function(){if(this.pos+4>this.len)throw q(this,4);var t=$.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t};B.prototype.double=function(){if(this.pos+8>this.len)throw q(this,4);var t=$.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t};B.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw q(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,n):e===n?new this.buf.constructor(0):this._slice.call(this.buf,e,n)};B.prototype.string=function(){var t=this.bytes();return pa.read(t,0,t.length)};B.prototype.skip=function(t){if(typeof t=="number"){if(this.pos+t>this.len)throw q(this,t);this.pos+=t}else do if(this.pos>=this.len)throw q(this);while(this.buf[this.pos++]&128);return this};B.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};B._configure=function(r){Ye=r,B.create=hi(),Ye._configure();var t=$.Long?"toLong":"toNumber";$.merge(B.prototype,{int64:function(){return Ze.call(this)[t](!1)},uint64:function(){return Ze.call(this)[t](!0)},sint64:function(){return Ze.call(this).zzDecode()[t](!1)},fixed64:function(){return ui.call(this)[t](!0)},sfixed64:function(){return ui.call(this)[t](!1)}})}});var mi=v((Bu,gi)=>{"use strict";gi.exports=ft;var pi=tr();(ft.prototype=Object.create(pi.prototype)).constructor=ft;var di=ht();function ft(r){pi.call(this,r)}ft._configure=function(){di.Buffer&&(ft.prototype._slice=di.Buffer.prototype.slice)};ft.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))};ft._configure()});var ar=v((Cu,_i)=>{"use strict";_i.exports=_;var U=ht(),er,re=U.LongBits,yi=U.base64,wi=U.utf8;function It(r,t,e){this.fn=r,this.len=t,this.next=void 0,this.val=e}function nr(){}function ga(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function _(){this.len=0,this.head=new It(nr,0,0),this.tail=this.head,this.states=null}var bi=function(){return U.Buffer?function(){return(_.create=function(){return new er})()}:function(){return new _}};_.create=bi();_.alloc=function(t){return new U.Array(t)};U.Array!==Array&&(_.alloc=U.pool(_.alloc,U.Array.prototype.subarray));_.prototype._push=function(t,e,n){return this.tail=this.tail.next=new It(t,e,n),this.len+=e,this};function ir(r,t,e){t[e]=r&255}function ma(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}function sr(r,t){this.len=r,this.next=void 0,this.val=t}sr.prototype=Object.create(It.prototype);sr.prototype.fn=ma;_.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new sr((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this};_.prototype.int32=function(t){return t<0?this._push(or,10,re.fromNumber(t)):this.uint32(t)};_.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)};function or(r,t,e){for(;r.hi;)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}_.prototype.uint64=function(t){var e=re.from(t);return this._push(or,e.length(),e)};_.prototype.int64=_.prototype.uint64;_.prototype.sint64=function(t){var e=re.from(t).zzEncode();return this._push(or,e.length(),e)};_.prototype.bool=function(t){return this._push(ir,1,t?1:0)};function rr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}_.prototype.fixed32=function(t){return this._push(rr,4,t>>>0)};_.prototype.sfixed32=_.prototype.fixed32;_.prototype.fixed64=function(t){var e=re.from(t);return this._push(rr,4,e.lo)._push(rr,4,e.hi)};_.prototype.sfixed64=_.prototype.fixed64;_.prototype.float=function(t){return this._push(U.float.writeFloatLE,4,t)};_.prototype.double=function(t){return this._push(U.float.writeDoubleLE,8,t)};var ya=U.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var i=0;i<t.length;++i)e[n+i]=t[i]};_.prototype.bytes=function(t){var e=t.length>>>0;if(!e)return this._push(ir,1,0);if(U.isString(t)){var n=_.alloc(e=yi.length(t));yi.decode(t,n,0),t=n}return this.uint32(e)._push(ya,e,t)};_.prototype.string=function(t){var e=wi.length(t);return e?this.uint32(e)._push(wi.write,e,t):this._push(ir,1,0)};_.prototype.fork=function(){return this.states=new ga(this),this.head=this.tail=new It(nr,0,0),this.len=0,this};_.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new It(nr,0,0),this.len=0),this};_.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this};_.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e};_._configure=function(r){er=r,_.create=bi(),er._configure()}});var ki=v((Au,xi)=>{"use strict";xi.exports=G;var vi=ar();(G.prototype=Object.create(vi.prototype)).constructor=G;var nt=ht();function G(){vi.call(this)}G._configure=function(){G.alloc=nt._Buffer_allocUnsafe,G.writeBytesBuffer=nt.Buffer&&nt.Buffer.prototype instanceof Uint8Array&&nt.Buffer.prototype.set.name==="set"?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var i=0;i<t.length;)e[n++]=t[i++]}};G.prototype.bytes=function(t){nt.isString(t)&&(t=nt._Buffer_from(t,"base64"));var e=t.length>>>0;return this.uint32(e),e&&this._push(G.writeBytesBuffer,e,t),this};function wa(r,t,e){r.length<40?nt.utf8.write(r,t,e):t.utf8Write?t.utf8Write(r,e):t.write(r,e)}G.prototype.string=function(t){var e=nt.Buffer.byteLength(t);return this.uint32(e),e&&this._push(wa,e,t),this};G._configure()});var gr=v((ql,Ri)=>{"use strict";function Ii(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function Na(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 Ii(r,e)}catch{e.message=r.message,e.stack=r.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(r)),Ii(new i,e)}}Ri.exports=Na});var Vi=v((oh,qi)=>{"use strict";qi.exports=function(){return Date.now()}});var Gi=v((ah,$i)=>{"use strict";var de=Vi(),vr=class{constructor(t,e,n){let i=this;this._started=de(),this._rescheduled=0,this._scheduled=e,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(de()-i._started),i._schedule(i._scheduled)):(i._triggered=!0,t.apply(null,i._args))},this._timer=setTimeout(this._timerWrapper,e)}reschedule(t){t||(t=this._scheduled);let e=de();e+t-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(t)):this._triggered?this._schedule(t):(this._started=e,this._rescheduled=t)}_schedule(t){this._triggered=!1,this._started=de(),this._rescheduled=0,this._scheduled=t,this._timer=setTimeout(this._timerWrapper,t)}clear(){clearTimeout(this._timer)}};function Ha(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let r;if(arguments.length>0){r=new Array(arguments.length-2);for(var t=0;t<r.length;t++)r[t]=arguments[t+2]}return new vr(arguments[0],arguments[1],r)}$i.exports=Ha});var Qi=v((ch,Ki)=>{"use strict";var{AbortController:Wa}=globalThis,ji=Gi(),qt=class extends Wa{constructor(t){super(),this._ms=t,this._timer=ji(()=>this.abort(),t),Object.setPrototypeOf(this,qt.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=ji(()=>this.abort(),this._ms)}};Ki.exports={TimeoutController:qt}});var ve=v((Ph,Br)=>{"use strict";var Mt=typeof Reflect=="object"?Reflect:null,es=Mt&&typeof Mt.apply=="function"?Mt.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},be;Mt&&typeof Mt.ownKeys=="function"?be=Mt.ownKeys:Object.getOwnPropertySymbols?be=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:be=function(t){return Object.getOwnPropertyNames(t)};function Ja(r){console&&console.warn&&console.warn(r)}var ns=Number.isNaN||function(t){return t!==t};function k(){k.init.call(this)}Br.exports=k;Br.exports.once=ec;k.EventEmitter=k;k.prototype._events=void 0;k.prototype._eventsCount=0;k.prototype._maxListeners=void 0;var rs=10;function _e(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(k,"defaultMaxListeners",{enumerable:!0,get:function(){return rs},set:function(r){if(typeof r!="number"||r<0||ns(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");rs=r}});k.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};k.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||ns(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function is(r){return r._maxListeners===void 0?k.defaultMaxListeners:r._maxListeners}k.prototype.getMaxListeners=function(){return is(this)};k.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var i=t==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")es(c,this,e);else for(var u=c.length,l=us(c,u),n=0;n<u;++n)es(l[n],this,e);return!0};function ss(r,t,e,n){var i,s,o;if(_e(e),s=r._events,s===void 0?(s=r._events=Object.create(null),r._eventsCount=0):(s.newListener!==void 0&&(r.emit("newListener",t,e.listener?e.listener:e),s=r._events),o=s[t]),o===void 0)o=s[t]=e,++r._eventsCount;else if(typeof o=="function"?o=s[t]=n?[e,o]:[o,e]:n?o.unshift(e):o.push(e),i=is(r),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=t,a.count=o.length,Ja(a)}return r}k.prototype.addListener=function(t,e){return ss(this,t,e,!1)};k.prototype.on=k.prototype.addListener;k.prototype.prependListener=function(t,e){return ss(this,t,e,!0)};function Za(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function os(r,t,e){var n={fired:!1,wrapFn:void 0,target:r,type:t,listener:e},i=Za.bind(n);return i.listener=e,n.wrapFn=i,i}k.prototype.once=function(t,e){return _e(e),this.on(t,os(this,t,e)),this};k.prototype.prependOnceListener=function(t,e){return _e(e),this.prependListener(t,os(this,t,e)),this};k.prototype.removeListener=function(t,e){var n,i,s,o,a;if(_e(e),i=this._events,i===void 0)return this;if(n=i[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===e||n[o].listener===e){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():Ya(n,s),n.length===1&&(i[t]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this};k.prototype.off=k.prototype.removeListener;k.prototype.removeAllListeners=function(t){var e,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function as(r,t,e){var n=r._events;if(n===void 0)return[];var i=n[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?tc(i):us(i,i.length)}k.prototype.listeners=function(t){return as(this,t,!0)};k.prototype.rawListeners=function(t){return as(this,t,!1)};k.listenerCount=function(r,t){return typeof r.listenerCount=="function"?r.listenerCount(t):cs.call(r,t)};k.prototype.listenerCount=cs;function cs(r){var t=this._events;if(t!==void 0){var e=t[r];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}k.prototype.eventNames=function(){return this._eventsCount>0?be(this._events):[]};function us(r,t){for(var e=new Array(t),n=0;n<t;++n)e[n]=r[n];return e}function Ya(r,t){for(;t+1<r.length;t++)r[t]=r[t+1];r.pop()}function tc(r){for(var t=new Array(r.length),e=0;e<t.length;++e)t[e]=r[e].listener||r[e];return t}function ec(r,t){return new Promise(function(e,n){function i(o){r.removeListener(t,s),n(o)}function s(){typeof r.removeListener=="function"&&r.removeListener("error",i),e([].slice.call(arguments))}ls(r,t,s,{once:!0}),t!=="error"&&rc(r,i,{once:!0})})}function rc(r,t,e){typeof r.on=="function"&&ls(r,"error",t,e)}function ls(r,t,e,n){if(typeof r.on=="function")n.once?r.once(t,e):r.on(t,e);else if(typeof r.addEventListener=="function")r.addEventListener(t,function i(s){n.once&&r.removeEventListener(t,i),e(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var vs=v((bs,_s)=>{"use strict";var wc=Math.exp;bs=_s.exports=function(t){if(typeof t!="number")throw new Error("must provide a timespan to the moving average constructor");if(t<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let e,n=0,i=0,s=0,o,a={};function c(u,l){return 1-wc(-(u-l)/t)}return a.push=function(l,h){if(o){let f=c(l,o),m=h-e,d=f*m;e=f*h+(1-f)*e,n=(1-f)*(n+m*d),i=Math.sqrt(n),s=e+f*m}else e=h;o=l},a.movingAverage=function(){return e},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return s},a}});var Bs=v((df,Ir)=>{function Ss(r){let t=new globalThis.AbortController;function e(){t.abort();for(let n of r)!n||!n.removeEventListener||n.removeEventListener("abort",e)}for(let n of r)if(!(!n||!n.addEventListener)){if(n.aborted){e();break}n.addEventListener("abort",e)}return t.signal}Ir.exports=Ss;Ir.exports.anySignal=Ss});var Sc={};M(Sc,{createHelia:()=>Ec});var De={};M(De,{identity:()=>Fe});var Cc=new Uint8Array(0);var qr=(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},Q=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var Vr=r=>new TextEncoder().encode(r),$r=r=>new TextDecoder().decode(r);var zs=Qr,jr=128,Is=127,Rs=~Is,Us=Math.pow(2,31);function Qr(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Us;)t[e++]=r&255|jr,r/=128;for(;r&Rs;)t[e++]=r&255|jr,r>>>=7;return t[e]=r|0,Qr.bytes=e-n+1,t}var Hs=Le,Ws=128,Kr=127;function Le(r,n){var e=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw Le.bytes=0,new RangeError("Could not decode varint");o=r[s++],e+=i<28?(o&Kr)<<i:(o&Kr)*Math.pow(2,i),i+=7}while(o>=Ws);return Le.bytes=s-n,e}var qs=Math.pow(2,7),Vs=Math.pow(2,14),$s=Math.pow(2,21),Gs=Math.pow(2,28),js=Math.pow(2,35),Ks=Math.pow(2,42),Qs=Math.pow(2,49),Xs=Math.pow(2,56),Js=Math.pow(2,63),Zs=function(r){return r<qs?1:r<Vs?2:r<$s?3:r<Gs?4:r<js?5:r<Ks?6:r<Qs?7:r<Xs?8:r<Js?9:10},Ys={encode:zs,decode:Hs,encodingLength:Zs},to=Ys,Dt=to;var Nt=(r,t=0)=>[Dt.decode(r,t),Dt.decode.bytes],_t=(r,t,e=0)=>(Dt.encode(r,t,e),t),vt=r=>Dt.encodingLength(r);var ot=(r,t)=>{let e=t.byteLength,n=vt(r),i=n+vt(e),s=new Uint8Array(i+e);return _t(r,s,0),_t(e,s,n),s.set(t,i),new xt(r,e,t,s)},Me=r=>{let t=Q(r),[e,n]=Nt(t),[i,s]=Nt(t.subarray(n)),o=t.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new xt(e,i,o,t)},Xr=(r,t)=>{if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&qr(r.bytes,e.bytes)}},xt=class{constructor(t,e,n,i){this.code=t,this.size=e,this.digest=n,this.bytes=i}};var Jr=0,eo="identity",Zr=Q,ro=r=>ot(Jr,Zr(r)),Fe={code:Jr,name:eo,encode:Zr,digest:ro};var ze={};M(ze,{sha256:()=>at,sha512:()=>Pe});var Oe=({name:r,code:t,encode:e})=>new Ne(r,t,e),Ne=class{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?ot(this.code,e):e.then(n=>ot(this.code,n))}else throw Error("Unknown type, must be binary type")}};var tn=r=>async t=>new Uint8Array(await crypto.subtle.digest(r,t)),at=Oe({name:"sha2-256",code:18,encode:tn("SHA-256")}),Pe=Oe({name:"sha2-512",code:19,encode:tn("SHA-512")});var We={};M(We,{base58btc:()=>w,base58flickr:()=>co});function no(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 i=0;i<r.length;i++){var s=r.charAt(i),o=s.charCodeAt(0);if(e[o]!==255)throw new TypeError(s+" is ambiguous");e[o]=i}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(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,y=0,E=0,C=d.length;E!==C&&d[E]===0;)E++,p++;for(var P=(C-E)*l+1>>>0,T=new Uint8Array(P);E!==C;){for(var H=d[E],z=0,D=P-1;(H!==0||z<y)&&D!==-1;D--,z++)H+=256*T[D]>>>0,T[D]=H%a>>>0,H=H/a>>>0;if(H!==0)throw new Error("Non-zero carry");y=z,E++}for(var I=P-y;I!==P&&T[I]===0;)I++;for(var bt=c.repeat(p);I<P;++I)bt+=r.charAt(T[I]);return bt}function f(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 y=0,E=0;d[p]===c;)y++,p++;for(var C=(d.length-p)*u+1>>>0,P=new Uint8Array(C);d[p];){var T=e[d.charCodeAt(p)];if(T===255)return;for(var H=0,z=C-1;(T!==0||H<E)&&z!==-1;z--,H++)T+=a*P[z]>>>0,P[z]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");E=H,p++}if(d[p]!==" "){for(var D=C-E;D!==C&&P[D]===0;)D++;for(var I=new Uint8Array(y+(C-D)),bt=y;D!==C;)I[bt++]=P[D++];return I}}}function m(d){var p=f(d);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:m}}var io=no,so=io,en=so;var Ie=class{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")}},Re=class{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 rn(this,t)}},Ue=class{constructor(t){this.decoders=t}or(t){return rn(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},rn=(r,t)=>new Ue({...r.decoders||{[r.prefix]:r},...t.decoders||{[t.prefix]:t}}),He=class{constructor(t,e,n,i){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=i,this.encoder=new Ie(t,e,n),this.decoder=new Re(t,e,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},Et=({name:r,prefix:t,encode:e,decode:n})=>new He(r,t,e,n),tt=({prefix:r,name:t,alphabet:e})=>{let{encode:n,decode:i}=en(e,t);return Et({prefix:r,name:t,encode:n,decode:s=>Q(i(s))})},oo=(r,t,e,n)=>{let i={};for(let l=0;l<t.length;++l)i[t[l]]=l;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),a=0,c=0,u=0;for(let l=0;l<s;++l){let h=i[r[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|h,a+=e,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},ao=(r,t,e)=>{let n=t[t.length-1]==="=",i=(1<<e)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>e;)o-=e,s+=t[i&a>>o];if(o&&(s+=t[i&a<<e-o]),n)for(;s.length*e&7;)s+="=";return s},S=({name:r,prefix:t,bitsPerChar:e,alphabet:n})=>Et({prefix:t,name:r,encode(i){return ao(i,n,e)},decode(i){return oo(i,n,e,r)}});var w=tt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),co=tt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qe={};M(qe,{base32:()=>X,base32hex:()=>fo,base32hexpad:()=>go,base32hexpadupper:()=>mo,base32hexupper:()=>po,base32pad:()=>lo,base32padupper:()=>ho,base32upper:()=>uo,base32z:()=>yo});var X=S({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),uo=S({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),lo=S({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ho=S({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fo=S({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),po=S({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),go=S({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mo=S({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yo=S({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var nn=(r,t)=>{let{bytes:e,version:n}=r;switch(n){case 0:return bo(e,Ve(r),t||w.encoder);default:return _o(e,Ve(r),t||X.encoder)}};var sn=new WeakMap,Ve=r=>{let t=sn.get(r);if(t==null){let e=new Map;return sn.set(r,e),e}return t},b=class{constructor(t,e,n,i){this.code=e,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Ot)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==vo)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return b.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=ot(t,e);return b.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 b.equals(this,t)}static equals(t,e){let n=e;return n&&t.code===n.code&&t.version===n.version&&Xr(t.multihash,n.multihash)}toString(t){return nn(this,t)}toJSON(){return{"/":nn(this)}}link(){return this}get[Symbol.toStringTag](){return"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 b)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:i,multihash:s,bytes:o}=e;return new b(n,i,s,o||on(n,i,s.bytes))}else if(e[xo]===!0){let{version:n,multihash:i,code:s}=e,o=Me(i);return b.create(n,s,o)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Ot)throw new Error(`Version 0 CID must use dag-pb (code: ${Ot}) block encoding`);return new b(t,e,n,n.bytes)}case 1:{let i=on(t,e,n.bytes);return new b(t,e,n,i)}default:throw new Error("Invalid version")}}static createV0(t){return b.create(0,Ot,t)}static createV1(t,e){return b.create(1,t,e)}static decode(t){let[e,n]=b.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=b.inspectBytes(t),n=e.size-e.multihashSize,i=Q(t.subarray(n,n+e.multihashSize));if(i.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=i.subarray(e.multihashSize-e.digestSize),o=new xt(e.multihashCode,e.digestSize,s,i);return[e.version===0?b.createV0(o):b.createV1(e.codec,o),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=Nt(t.subarray(e));return e+=f,h},i=n(),s=Ot;if(i===18?(i=0,e=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=e,a=n(),c=n(),u=e+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(t,e){let[n,i]=wo(t,e),s=b.decode(i);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ve(s).set(n,t),s}},wo=(r,t)=>{switch(r[0]){case"Q":{let e=t||w;return[w.prefix,e.decode(`${w.prefix}${r}`)]}case w.prefix:{let e=t||w;return[w.prefix,e.decode(r)]}case X.prefix:{let e=t||X;return[X.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)]}}},bo=(r,t,e)=>{let{prefix:n}=e;if(n!==w.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let i=t.get(n);if(i==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return i},_o=(r,t,e)=>{let{prefix:n}=e,i=t.get(n);if(i==null){let s=e.encode(r);return t.set(n,s),s}else return i},Ot=112,vo=18,on=(r,t,e)=>{let n=vt(r),i=n+vt(t),s=new Uint8Array(i+e.byteLength);return _t(r,s,0),_t(t,s,n),s.set(e,i),s},xo=Symbol.for("@ipld/js-cid/CID");var Ai=L(_n(),1);var Pt=L(Ln(),1);function Qo(r){let t=new Uint8Array(r.reduce((n,i)=>n+Pt.default.encodingLength(i),0)),e=0;for(let n of r)t=Pt.encode(n,t,e),e+=Pt.default.encodingLength(n);return t}var Mn=Qo;var V=L(Pn(),1);var Qe={};M(Qe,{base64:()=>Ke,base64pad:()=>ca,base64url:()=>ua,base64urlpad:()=>la});var Ke=S({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ca=S({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ua=S({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),la=S({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});V.default.formatters.b=r=>r==null?"undefined":w.baseEncode(r);V.default.formatters.t=r=>r==null?"undefined":X.baseEncode(r);V.default.formatters.m=r=>r==null?"undefined":Ke.baseEncode(r);V.default.formatters.p=r=>r==null?"undefined":r.toString();V.default.formatters.c=r=>r==null?"undefined":r.toString();V.default.formatters.k=r=>r==null?"undefined":r.toString();function zn(r){return Object.assign((0,V.default)(r),{error:(0,V.default)(`${r}:error`),trace:(0,V.default)(`${r}:trace`)})}function Jt(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 ut=class{constructor(t,e,n){this._refCounter=1,this.cid=t,this.priority=e??1,this.wantType=n}inc(){this._refCounter+=1}dec(){this._refCounter=Math.max(0,this._refCounter-1)}hasRefs(){return this._refCounter>0}get[Symbol.toStringTag](){return`WantlistEntry <key: ${this.cid.toString(w)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(t){return this._refCounter===t._refCounter&&this.cid.equals(t.cid)&&this.priority===t.priority&&this.wantType===t.wantType}};var et=class{constructor(t,e,n,i,s){this.entry=new ut(t,e,n),this.cancel=Boolean(i),this.sendDontHave=Boolean(s)}get cid(){return this.entry.cid}set cid(t){this.entry.cid=t}get priority(){return this.entry.priority}set priority(t){this.entry.priority=t}get wantType(){return this.entry.wantType}set wantType(t){this.entry.wantType=t}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(w)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(t){return this.cancel===t.cancel&&this.sendDontHave===t.sendDontHave&&this.wantType===t.wantType&&this.entry.equals(t.entry)}};var R=(r,t)=>{let e=["bitswap"];return t!=null&&e.push(t),r!=null&&e.push(`${r.toString().slice(0,8)}`),zn(e.join(":"))};var Zt=(r,t)=>{if(r.size!==t.size)return!1;for(let[e,n]of r){let i=t.get(e);if(i===void 0||n instanceof Uint8Array&&i instanceof Uint8Array&&!Jt(n,i)||n instanceof et&&i instanceof et&&!n.equals(i))return!1}return!0};var cr=L(tr(),1),Ei=L(mi(),1),Si=L(ht(),1),ur=L(ar(),1),Bi=L(ki(),1);function ba(){Si.default._configure(),cr.default._configure(Ei.default),ur.default._configure(Bi.default)}ba();var Ci=["uint64","int64","sint64","fixed64","sfixed64"];function _a(r){for(let t of Ci){if(r[t]==null)continue;let e=r[t];r[t]=function(){return BigInt(e.call(this).toString())}}return r}function lr(r){return _a(new cr.default(r))}function va(r){for(let t of Ci){if(r[t]==null)continue;let e=r[t];r[t]=function(n){return e.call(this,n.toString())}}return r}function hr(){return va(ur.default.create())}function dt(r,t){let e=lr(r instanceof Uint8Array?r:r.subarray());return t.decode(e)}function pt(r,t){let e=hr();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Tt;(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"})(Tt||(Tt={}));function ne(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function ie(r){function t(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let e=function(s,o){let a=t(s);o.int32(a)},n=function(s){let o=s.int32();return t(o)};return ne("enum",Tt.VARINT,e,n)}function gt(r,t){return ne("message",Tt.LENGTH_DELIMITED,r,t)}var F;(function(r){let t;(function(a){let c;(function(f){f.Block="Block",f.Have="Have"})(c=a.WantType||(a.WantType={}));let u;(function(f){f[f.Block=0]="Block",f[f.Have=1]="Have"})(u||(u={})),function(f){f.codec=()=>ie(u)}(c=a.WantType||(a.WantType={}));let l;(function(f){let m;f.codec=()=>(m==null&&(m=gt((d,p,y={})=>{y.lengthDelimited!==!1&&p.fork(),d.block!=null&&d.block.byteLength>0&&(p.uint32(10),p.bytes(d.block)),d.priority!=null&&d.priority!==0&&(p.uint32(16),p.int32(d.priority)),d.cancel!=null&&d.cancel!==!1&&(p.uint32(24),p.bool(d.cancel)),d.wantType!=null&&u[d.wantType]!==0&&(p.uint32(32),r.Wantlist.WantType.codec().encode(d.wantType,p)),d.sendDontHave!=null&&d.sendDontHave!==!1&&(p.uint32(40),p.bool(d.sendDontHave)),y.lengthDelimited!==!1&&p.ldelim()},(d,p)=>{let y={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},E=p==null?d.len:d.pos+p;for(;d.pos<E;){let C=d.uint32();switch(C>>>3){case 1:y.block=d.bytes();break;case 2:y.priority=d.int32();break;case 3:y.cancel=d.bool();break;case 4:y.wantType=r.Wantlist.WantType.codec().decode(d);break;case 5:y.sendDontHave=d.bool();break;default:d.skipType(C&7);break}}return y})),m),f.encode=d=>pt(d,f.codec()),f.decode=d=>dt(d,f.codec())})(l=a.Entry||(a.Entry={}));let h;a.codec=()=>(h==null&&(h=gt((f,m,d={})=>{if(d.lengthDelimited!==!1&&m.fork(),f.entries!=null)for(let p of f.entries)m.uint32(10),r.Wantlist.Entry.codec().encode(p,m);f.full!=null&&f.full!==!1&&(m.uint32(16),m.bool(f.full)),d.lengthDelimited!==!1&&m.ldelim()},(f,m)=>{let d={entries:[],full:!1},p=m==null?f.len:f.pos+m;for(;f.pos<p;){let y=f.uint32();switch(y>>>3){case 1:d.entries.push(r.Wantlist.Entry.codec().decode(f,f.uint32()));break;case 2:d.full=f.bool();break;default:f.skipType(y&7);break}}return d})),h),a.encode=f=>pt(f,a.codec()),a.decode=f=>dt(f,a.codec())})(t=r.Wantlist||(r.Wantlist={}));let e;(function(a){let c;a.codec=()=>(c==null&&(c=gt((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.prefix!=null&&u.prefix.byteLength>0&&(l.uint32(10),l.bytes(u.prefix)),u.data!=null&&u.data.byteLength>0&&(l.uint32(18),l.bytes(u.data)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={prefix:new Uint8Array(0),data:new Uint8Array(0)},f=l==null?u.len:u.pos+l;for(;u.pos<f;){let m=u.uint32();switch(m>>>3){case 1:h.prefix=u.bytes();break;case 2:h.data=u.bytes();break;default:u.skipType(m&7);break}}return h})),c),a.encode=u=>pt(u,a.codec()),a.decode=u=>dt(u,a.codec())})(e=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(i||(i={})),function(a){a.codec=()=>ie(i)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let s;(function(a){let c;a.codec=()=>(c==null&&(c=gt((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.cid!=null&&u.cid.byteLength>0&&(l.uint32(10),l.bytes(u.cid)),u.type!=null&&i[u.type]!==0&&(l.uint32(16),r.BlockPresenceType.codec().encode(u.type,l)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={cid:new Uint8Array(0),type:n.Have},f=l==null?u.len:u.pos+l;for(;u.pos<f;){let m=u.uint32();switch(m>>>3){case 1:h.cid=u.bytes();break;case 2:h.type=r.BlockPresenceType.codec().decode(u);break;default:u.skipType(m&7);break}}return h})),c),a.encode=u=>pt(u,a.codec()),a.decode=u=>dt(u,a.codec())})(s=r.BlockPresence||(r.BlockPresence={}));let o;r.codec=()=>(o==null&&(o=gt((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let l of a.blocks)c.uint32(18),c.bytes(l);if(a.payload!=null)for(let l of a.payload)c.uint32(26),r.Block.codec().encode(l,c);if(a.blockPresences!=null)for(let l of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(l,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={blocks:[],payload:[],blockPresences:[],pendingBytes:0},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:u.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:u.blocks.push(a.bytes());break;case 3:u.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:u.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:u.pendingBytes=a.int32();break;default:a.skipType(h&7);break}}return u})),o),r.encode=a=>pt(a,r.codec()),r.decode=a=>dt(a,r.codec())})(F||(F={}));var se=class extends Error{constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var xa,x=class{constructor(t){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}get empty(){return this.blocks.size===0&&this.wantlist.size===0&&this.blockPresences.size===0}addEntry(t,e,n,i,s){n==null&&(n=x.WantType.Block);let o=t.toString(w),a=this.wantlist.get(o);a!=null?(a.wantType===n&&(a.priority=e),i===!0&&(a.cancel=Boolean(i)),s===!0&&(a.sendDontHave=Boolean(s)),n===x.WantType.Block&&a.wantType===x.WantType.Have&&(a.wantType=n)):this.wantlist.set(o,new et(t,e,n,i,s))}addBlock(t,e){let n=t.toString(w);this.blocks.set(n,e)}addHave(t){let e=t.toString(w);this.blockPresences.has(e)||this.blockPresences.set(e,x.BlockPresenceType.Have)}addDontHave(t){let e=t.toString(w);this.blockPresences.has(e)||this.blockPresences.set(e,x.BlockPresenceType.DontHave)}cancel(t){let e=t.toString(w);this.wantlist.delete(e),this.addEntry(t,0,x.WantType.Block,!0,!1)}setPendingBytes(t){this.pendingBytes=t}serializeToBitswap100(){return F.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),cancel:Boolean(t.cancel),wantType:F.Wantlist.WantType.Block,sendDontHave:!1})),full:Boolean(this.full)},blocks:Array.from(this.blocks.values())})}serializeToBitswap110(){let t={wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),wantType:e.wantType,cancel:Boolean(e.cancel),sendDontHave:Boolean(e.sendDontHave)})),full:Boolean(this.full)},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[e,n]of this.blocks.entries()){let i=b.parse(e),s=i.version,o=i.code,a=i.multihash.code,c=i.multihash.digest.length,u=Mn([s,o,a,c]);t.payload.push({prefix:u,data:n})}for(let[e,n]of this.blockPresences)t.blockPresences.push({cid:b.parse(e).bytes,type:n});return this.pendingBytes>0&&(t.pendingBytes=this.pendingBytes),F.encode(t)}equals(t){return!(this.full!==t.full||this.pendingBytes!==t.pendingBytes||!Zt(this.wantlist,t.wantlist)||!Zt(this.blocks,t.blocks)||!Zt(this.blockPresences,t.blockPresences))}get[Symbol.toStringTag](){let t=Array.from(this.wantlist.keys()),e=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${t}, blocks: ${e}>`}};xa=x;x.Entry=et;x.WantType={Block:F.Wantlist.WantType.Block,Have:F.Wantlist.WantType.Have};x.BlockPresenceType={Have:F.BlockPresenceType.Have,DontHave:F.BlockPresenceType.DontHave};x.deserialize=async(r,t)=>{let e=F.decode(r),n=e.wantlist?.full===!0,i=new x(n);return e.wantlist?.entries.forEach(s=>{if(s.block==null)return;let o=b.decode(s.block);i.addEntry(o,s.priority??0,s.wantType,Boolean(s.cancel),Boolean(s.sendDontHave))}),e.blockPresences.forEach(s=>{if(s.cid==null)return;let o=b.decode(s.cid);s.type===x.BlockPresenceType.Have?i.addHave(o):i.addDontHave(o)}),e.blocks.length>0?(await Promise.all(e.blocks.map(async s=>{let o=await at.digest(s),a=b.createV0(o);i.addBlock(a,s)})),i):(e.payload.length>0&&(await Promise.all(e.payload.map(async s=>{if(s.prefix==null||s.data==null)return;let o=(0,Ai.default)(s.prefix),a=o[0],c=o[1],u=o[2],l=u===at.code?at:await t?.getHasher(u);if(l==null)throw new se("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let h=await l.digest(s.data),f=b.create(a,c,h);i.addBlock(f,s.data)})),i.setPendingBytes(e.pendingBytes)),i)};x.blockPresenceSize=r=>r.bytes.length+1;var fr=class extends Map{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 it(r){let{name:t,metrics:e}=r,n;return e!=null?n=new fr({name:t,metrics:e}):n=new Map,n}var Ti={Block:F.Wantlist.WantType.Block,Have:F.Wantlist.WantType.Have},ka=(r,t)=>Array.prototype.slice.call(t,0).sort((e,n)=>{let i=r(e),s=r(n);return i<s?-1:i>s?1:0}),J=class{constructor(t,e){this.set=e!=null?it({name:"ipfs_bitswap_wantlist",metrics:e.metrics}):new Map,this._stats=t}get length(){return this.set.size}add(t,e,n){let i=t.toString(w),s=this.set.get(i);s!=null?(s.inc(),s.priority=e,s.wantType===Ti.Have&&n===Ti.Block&&(s.wantType=n)):(this.set.set(i,new ut(t,e,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(t){let e=t.toString(w),n=this.set.get(e);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(e),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(t){this.set.has(t)&&this.set.delete(t)}forEach(t){this.set.forEach(t)}entries(){return this.set.entries()}sortedEntries(){return new Map(ka(t=>t[1].key,Array.from(this.set.entries())))}contains(t){let e=t.toString(w);return this.set.has(e)}get(t){let e=t.toString(w);return this.set.get(e)}};J.Entry=ut;var Li=Math.pow(2,31)-1,Mi=1e3,Fi=1;var Di=Ea;function Ea(r,t,e){var n=null,i=null,s=function(){n&&(clearTimeout(n),i=null,n=null)},o=function(){var c=i;s(),c&&c()},a=function(){if(!t)return r.apply(this,arguments);var c=this,u=arguments,l=e&&!n;if(s(),i=function(){r.apply(c,u)},n=setTimeout(function(){if(n=null,!l){var h=i;return i=null,h()}},t),l)return i()};return a.cancel=s,a.flush=o,a}var oe=class{constructor(t,e,n){this.peerId=e,this.network=n,this.refcnt=1,this._entries=[],this._log=R(t,"msgqueue"),this.sendEntries=Di(this.sendEntries.bind(this),Fi)}addMessage(t){t.empty||this.send(t)}addEntries(t){this._entries=this._entries.concat(t),this.sendEntries()}sendEntries(){if(this._entries.length===0)return;let t=new x(!1);this._entries.forEach(e=>{e.cancel===!0?t.cancel(e.cid):t.addEntry(e.cid,e.priority)}),this._entries=[],this.addMessage(t)}async send(t){try{await this.network.connectTo(this.peerId)}catch(e){this._log.error("cant connect to peer %p: %s",this.peerId,e.message);return}this._log("sending message to peer %p",this.peerId),this.network.sendMessage(this.peerId,t).catch(e=>{this._log.error("send error",e)})}};var ae=class{constructor(t,e,n,i){this.peers=it({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new J(n,i),this.network=e,this._peerId=t,this._log=R(t,"want")}_addEntries(t,e,n){let i=t.map((s,o)=>new x.Entry(s,Li-o,x.WantType.Block,e));i.forEach(s=>{s.cancel?n===!0?this.wantlist.removeForce(s.cid.toString(w)):this.wantlist.remove(s.cid):(this._log("adding to wantlist"),this.wantlist.add(s.cid,s.priority))});for(let s of this.peers.values())s.addEntries(i)}_startPeerHandler(t){let e=this.peers.get(t.toString());if(e!=null){e.refcnt++;return}e=new oe(this._peerId,t,this.network);let n=new x(!0);for(let i of this.wantlist.entries())n.addEntry(i[1].cid,i[1].priority);return e.addMessage(n),this.peers.set(t.toString(),e),e}_stopPeerHandler(t){let e=this.peers.get(t.toString());e!=null&&(e.refcnt--,!(e.refcnt>0)&&this.peers.delete(t.toString()))}wantBlocks(t,e={}){this._addEntries(t,!1),e.signal?.addEventListener("abort",()=>{this.cancelWants(t)})}unwantBlocks(t){this._log("unwant blocks: %s",t.length),this._addEntries(t,!0,!0)}cancelWants(t){this._log("cancel wants: %s",t.length),this._addEntries(t,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(t){this._startPeerHandler(t)}disconnected(t){this._stopPeerHandler(t)}start(){}stop(){this.peers.forEach(t=>{this.disconnected(t.peerId)})}};function Rt(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Z(r=0){return globalThis.Buffer?.alloc!=null?Rt(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Y(r=0){return globalThis.Buffer?.allocUnsafe!=null?Rt(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function pr(r,t){t==null&&(t=r.reduce((i,s)=>i+s.length,0));let e=Y(t),n=0;for(let i of r)e.set(i,n),n+=i.length;return Rt(e)}var Oi=Symbol.for("@achingbrain/uint8arraylist");function Ni(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let i=e+n.byteLength;if(t<i)return{buf:n,index:t-e};e=i}throw new RangeError("index is out of bounds")}function ce(r){return Boolean(r?.[Oi])}var j=class{constructor(...t){Object.defineProperty(this,Oi,{value:!0}),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(ce(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(ce(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=Ni(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ni(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(ce(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:i}=this._subList(t,e);return pr(n,i)}subarray(t,e){let{bufs:n,length:i}=this._subList(t,e);return n.length===1?n[0]:pr(n,i)}sublist(t,e){let{bufs:n,length:i}=this._subList(t,e),s=new j;return s.length=i,s.bufs=n,s}_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=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,t>=c)continue;let u=t>=a&&t<c,l=e>a&&e<=c;if(u&&l){if(t===a&&e===c){n.push(o);break}let h=t-a;n.push(o.subarray(h,h+(e-t)));break}if(u){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(l){if(e===c){n.push(o);break}n.push(o.subarray(0,e-a));break}n.push(o)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!ce(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 i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let h=0;h<s;h++)o[h]=-1;for(let h=0;h<i;h++)o[n[h]]=h;let a=o,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let h=e;h<=c;h+=l){l=0;for(let f=u;f>=0;f--){let m=this.get(h+f);if(n[f]!==m){l=Math.max(1,f-a[m]);break}}if(l===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Y(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 i=Z(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,e,n),this.write(i,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 i=Z(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,e,n),this.write(i,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 i=Z(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,e,n),this.write(i,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=Y(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 i=Z(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,e,n),this.write(i,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 i=Z(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,e,n),this.write(i,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 i=Z(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,e,n),this.write(i,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 i=Z(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,e,n),this.write(i,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 i=Z(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,e,n),this.write(i,t)}equals(t){if(t==null||!(t instanceof j)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Jt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new j;return n.bufs=t,e==null&&(e=t.reduce((i,s)=>i+s.byteLength,0)),n.length=e,n}};function ue(r){return r instanceof Uint8Array?{get(t){return r[t]},set(t,e){r[t]=e}}:{get(t){return r.get(t)},set(t,e){r.set(t,e)}}}var Pi=4294967296,O=class{constructor(t=0,e=0){this.hi=t,this.lo=e}toBigInt(t){if(t===!0)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)}toNumber(t){return Number(this.toBigInt(t))}zzDecode(){let t=-(this.lo&1),e=((this.lo>>>1|this.hi<<31)^t)>>>0,n=(this.hi>>>1^t)>>>0;return new O(n,e)}zzEncode(){let t=this.hi>>31,e=((this.hi<<1|this.lo>>>31)^t)>>>0,n=(this.lo<<1^t)>>>0;return new O(e,n)}toBytes(t,e=0){let n=ue(t);for(;this.hi>0;)n.set(e++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(e++,this.lo&127|128),this.lo=this.lo>>>7;n.set(e++,this.lo)}static fromBigInt(t){if(t===0n)return new O;let e=t<0;e&&(t=-t);let n=Number(t>>32n)|0,i=Number(t-(BigInt(n)<<32n))|0;return e&&(n=~n>>>0,i=~i>>>0,++i>Pi&&(i=0,++n>Pi&&(n=0))),new O(n,i)}static fromNumber(t){if(t===0)return new O;let e=t<0;e&&(t=-t);let n=t>>>0,i=(t-n)/4294967296>>>0;return e&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new O(i,n)}static fromBytes(t,e=0){let n=ue(t),i=new O,s=0;if(t.length-e>4){for(;s<4;++s)if(i.lo=(i.lo|(n.get(e)&127)<<s*7)>>>0,n.get(e++)<128)return i;if(i.lo=(i.lo|(n.get(e)&127)<<28)>>>0,i.hi=(i.hi|(n.get(e)&127)>>4)>>>0,n.get(e++)<128)return i;s=0}else for(;s<4;++s){if(e>=t.length)throw RangeError(`index out of range: ${e} > ${t.length}`);if(i.lo=(i.lo|(n.get(e)&127)<<s*7)>>>0,n.get(e++)<128)return i}if(t.length-e>4){for(;s<5;++s)if(i.hi=(i.hi|(n.get(e)&127)<<s*7+3)>>>0,n.get(e++)<128)return i}else if(e<t.byteLength)for(;s<5;++s){if(e>=t.length)throw RangeError(`index out of range: ${e} > ${t.length}`);if(i.hi=(i.hi|(n.get(e)&127)<<s*7+3)>>>0,n.get(e++)<128)return i}throw RangeError("invalid varint encoding")}};var Sa=Math.pow(2,7),Ba=Math.pow(2,14),Ca=Math.pow(2,21),Aa=Math.pow(2,28),Ta=Math.pow(2,35),La=Math.pow(2,42),Ma=Math.pow(2,49),Fa=Math.pow(2,56),Da=Math.pow(2,63),mt={encodingLength(r){return r<Sa?1:r<Ba?2:r<Ca?3:r<Aa?4:r<Ta?5:r<La?6:r<Ma?7:r<Fa?8:r<Da?9:10},encode(r,t,e=0){if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return t==null&&(t=Y(mt.encodingLength(r))),O.fromNumber(r).toBytes(t,e),t},decode(r,t=0){return O.fromBytes(r,t).toNumber(!0)}};function zi(r){return globalThis?.Buffer?.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}var le=r=>{let t=mt.encodingLength(r),e=zi(t);return mt.encode(r,e),le.bytes=t,e};le.bytes=0;function he(r){r=r??{};let t=r.lengthEncoder??le;return async function*(n){for await(let i of n){let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}}}he.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??le;return new j(e(r.byteLength),r)};var Ut=L(gr(),1),Oa=8,Pa=1024*1024*4,yt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(yt||(yt={}));var mr=r=>{let t=mt.decode(r);return mr.bytes=mt.encodingLength(t),t};mr.bytes=0;function Ht(r){return async function*(e){let n=new j,i=yt.LENGTH,s=-1,o=r?.lengthDecoder??mr,a=r?.maxLengthLength??Oa,c=r?.maxDataLength??Pa;for await(let u of e)for(n.append(u);n.byteLength>0;){if(i===yt.LENGTH)try{if(s=o(n),s<0)throw(0,Ut.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,Ut.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=o.bytes;n.consume(l),r?.onLength!=null&&r.onLength(s),i=yt.DATA}catch(l){if(l instanceof RangeError){if(n.byteLength>a)throw(0,Ut.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(i===yt.DATA){if(n.byteLength<s)break;let l=n.sublist(0,s);n.consume(s),r?.onData!=null&&r.onData(l),yield l,i=yt.LENGTH}}if(n.byteLength>0)throw(0,Ut.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}}Ht.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(e);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return Ht({...t??{},onLength:s=>{e=s}})(n)};var fe=class{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}},Lt=class{constructor(t={}){this.hwm=t.splitLimit??16,this.head=new fe(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 fe(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()}};function wt(r={}){return Ia(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 Ia(r,t){t=t??{};let e=t.onEnd,n=new Lt,i,s,o,a=async()=>n.isEmpty()?o?{done:!0}:await new Promise((p,y)=>{s=E=>{s=null,n.push(E);try{p(r(n))}catch(C){y(C)}return i}}):r(n),c=p=>s!=null?s(p):(n.push(p),i),u=p=>(n=new Lt,s!=null?s({error:p}):(n.push({error:p}),i)),l=p=>{if(o)return i;if(t?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:p})},h=p=>o?i:(o=!0,p!=null?u(p):c({done:!0})),f=()=>(n=new Lt,h(),{done:!0}),m=p=>(h(p),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:f,throw:m,push:l,end:h,get readableLength(){return n.size}},e==null)return i;let d=i;return i={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(p){return d.throw(p),e!=null&&(e(p),e=void 0),{done:!0}},return(){return d.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(p){return d.end(p),e!=null&&(e(p),e=void 0),i},get readableLength(){return d.readableLength}},i}async function*Wt(...r){let t=wt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async e=>{for await(let n of e)t.push(n)})),t.end()}catch(e){t.end(e)}}),yield*t}var Ra=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Ui=r=>r!=null&&(typeof r[Symbol.asyncIterator]=="function"||typeof r[Symbol.iterator]=="function"||typeof r.next=="function"),yr=r=>r!=null&&typeof r.sink=="function"&&Ui(r.source),Ua=r=>t=>{let e=r.sink(t);if(e.then!=null){let n=wt({objectMode:!0});return e.then(()=>{n.end()},s=>{n.end(s)}),Wt(n,async function*(){yield*r.source,n.end()}())}return r.source};function wr(r,...t){if(yr(r)){let n=r;r=()=>n.source}else if(Ui(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&yr(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++)yr(e[n])&&(e[n]=Ua(e[n]));return Ra(...e)}var br=Symbol.for("@libp2p/topology");var Hi=()=>{},_r=class{constructor(t){this.min=t.min??0,this.max=t.max??1/0,this.peers=new Set,this.onConnect=t.onConnect??Hi,this.onDisconnect=t.onDisconnect??Hi}get[Symbol.toStringTag](){return br.toString()}get[br](){return!0}async setRegistrar(t){this.registrar=t}disconnect(t){this.onDisconnect(t)}};function Wi(r){return new _r(r)}var Zi=L(Qi(),1);var Vt=class extends Error{constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Xi(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Ji(r,t,e){let n=e??{},i=Xi(r);async function*s(){let o,a=()=>{o?.()};for(t.addEventListener("abort",a);;){let c;try{if(t.aborted){let{abortMessage:l,abortCode:h}=n;throw new Vt(l,h)}let u=new Promise((l,h)=>{o=()=>{let{abortMessage:f,abortCode:m}=n;h(new Vt(f,m))}});c=await Promise.race([u,i.next()]),o=null}catch(u){t.removeEventListener("abort",a);let l=u.type==="aborted"&&t.aborted;if(l&&n.onAbort!=null&&await n.onAbort(r),typeof i.return=="function")try{let h=i.return();h instanceof Promise&&h.catch(f=>{n.onReturnError!=null&&n.onReturnError(f)})}catch(h){n.onReturnError!=null&&n.onReturnError(h)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}t.removeEventListener("abort",a)}return s()}var xr="/ipfs/bitswap/1.0.0",kr="/ipfs/bitswap/1.1.0",Er="/ipfs/bitswap/1.2.0",Va=32,$a=128,Ga=3e4,pe=class{constructor(t,e,n,i={}){this._log=R(t.peerId,"network"),this._libp2p=t,this._bitswap=e,this._protocols=[xr],i.b100Only!==!0&&(this._protocols.unshift(kr),this._protocols.unshift(Er)),this._stats=n,this._running=!1,this._onPeerConnect=this._onPeerConnect.bind(this),this._onPeerDisconnect=this._onPeerDisconnect.bind(this),this._onConnection=this._onConnection.bind(this),this._hashLoader=i.hashLoader??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=i.maxInboundStreams??Va,this._maxOutboundStreams=i.maxOutboundStreams??$a,this._incomingStreamTimeout=i.incomingStreamTimeout??Ga}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let t=Wi({onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect});this._registrarIds=[];for(let e of this._protocols)this._registrarIds.push(await this._libp2p.register(e,t));this._libp2p.getConnections().forEach(e=>{this._onPeerConnect(e.remotePeer)})}async stop(){if(this._running=!1,await this._libp2p.unhandle(this._protocols),this._registrarIds!=null){for(let t of this._registrarIds)this._libp2p.unregister(t);this._registrarIds=[]}}_onConnection(t){if(!this._running)return;let{stream:e,connection:n}=t,i=new Zi.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",e.stat.protocol,n.remotePeer),await wr(Ji(e.source,i.signal),Ht(),async s=>{for await(let o of s){try{let a=await x.deserialize(o.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,a)}catch(a){this._bitswap._receiveError(a);break}i.reset()}})}).catch(s=>{this._log(s),e.abort(s)}).finally(()=>{i.clear(),e.close()})}_onPeerConnect(t){this._bitswap._onPeerConnected(t)}_onPeerDisconnect(t){this._bitswap._onPeerDisconnected(t)}findProviders(t,e={}){return this._libp2p.contentRouting.findProviders(t,e)}async findAndConnect(t,e){let n=[],i=0;for await(let s of this.findProviders(t,e))if(this._log(`connecting to provider ${s.id}`),n.push(this.connectTo(s.id,e).catch(o=>{this._log.error(o)})),i++,i===3)break;await Promise.all(n)}async provide(t,e){await this._libp2p.contentRouting.provide(t,e)}async sendMessage(t,e){if(!this._running)throw new Error("network isn't running");let n=t.toString();this._log("sendMessage to %s",n,e);let s=await(await this._libp2p.dial(t)).newStream([Er,kr,xr]);await ja(s,e,this._log),this._updateSentStats(t,e.blocks)}async connectTo(t,e){if(!this._running)throw new Error("network isn't running");return await this._libp2p.dial(t,e)}_updateSentStats(t,e){let n=t.toString();if(this._stats!=null){for(let i of e.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",e.size)}}};async function ja(r,t,e){try{let n;switch(r.stat.protocol){case xr:n=t.serializeToBitswap100();break;case kr:case Er:n=t.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${r.stat.protocol}`)}await wr([n],he(),r)}catch(n){e(n)}finally{r.close()}}var ge=class{constructor(t){this.partner=t,this.wantlist=new J,this.exchangeCount=0,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=t}wants(t,e,n){this.wantlist.add(t,e,n)}cancelWant(t){this.wantlist.remove(t)}wantlistContains(t){return this.wantlist.get(t)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var $t=class extends Map{constructor(t,e){super(),this._cmp=e??this._defaultSort,this._keys=[];for(let[n,i]of t??[])this.set(n,i)}update(t){if(t<0||t>=this._keys.length)return;let e=this._keys[t];this._keys.splice(t,1);let n=this._find(e);this._keys.splice(n,0,e)}set(t,e){if(this.has(t)){let i=this.indexOf(t);this._keys.splice(i,1)}super.set(t,e);let n=this._find(t);return this._keys.splice(n,0,t),this}clear(){super.clear(),this._keys=[]}delete(t){if(!this.has(t))return!1;let e=this.indexOf(t);return this._keys.splice(e,1),super.delete(t)}indexOf(t){if(!this.has(t))return-1;let e=this._find(t);if(this._keys[e]===t)return e;for(let n=1;n<this._keys.length;n++){if(this._keys[e+n]===t)return e+n;if(this._keys[e-n]===t)return e-n}return-1}_find(t){let e=0,n=this._keys.length;for(;e<n;){let i=e+n>>>1,s=this._kCmp(this._keys[i],t);if(s<0)e=i+1;else if(s>0)n=i;else return i}return e}*keys(){for(let t of this._keys)yield t}*values(){for(let t of this._keys)yield this.get(t)}*entries(){for(let t of this._keys)yield[t,this.get(t)]}*[Symbol.iterator](){yield*this.entries()}forEach(t,e=this){if(t!=null)for(let n of this._keys){let i=this.get(n);if(i==null)throw new Error("Value cannot be undefined");t.apply(e,[[n,i]])}}_defaultSort(t,e){return t[0]<e[0]?-1:e[0]<t[0]?1:0}_kCmp(t,e){return this._cmp([t,this.get(t)],[e,this.get(e)])}};var Ka={hasNewInfo(){return!1},merge(){}},me=class{constructor(t=Ka){this._taskMerger=t,this._byPeer=new $t([],ye.compare)}pushTasks(t,e){let n=this._byPeer.get(t.toString());n==null&&(n=new ye(t,this._taskMerger)),n.pushTasks(e),this._byPeer.set(t.toString(),n)}popTasks(t){let e=this._head();if(e===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:i}=e.popTasks(t);if(n.length===0)return{tasks:n,pendingSize:i};let s=e.peerId;return e.isIdle()?this._byPeer.delete(s.toString()):this._byPeer.update(0),{peerId:s,tasks:n,pendingSize:i}}_head(){if(this._byPeer.size!==0)for(let[,t]of this._byPeer)return t}remove(t,e){this._byPeer.get(e.toString())?.remove(t)}tasksDone(t,e){let n=this._byPeer.get(t.toString());if(n==null)return;let i=this._byPeer.indexOf(t.toString());for(let s of e)n.taskDone(s);this._byPeer.update(i)}},ye=class{constructor(t,e){this.peerId=t,this._taskMerger=e,this._activeTotalSize=0,this._pending=new Sr,this._active=new Set}pushTasks(t){for(let e of t)this._pushTask(e)}_pushTask(t){if(!this._taskHasMoreInfoThanActiveTasks(t))return;let e=this._pending.get(t.topic);if(e!=null){t.priority>e.priority&&this._pending.updatePriority(t.topic,t.priority),this._taskMerger.merge(t,e);return}this._pending.add(t)}_taskHasMoreInfoThanActiveTasks(t){let e=[];for(let n of this._active)n.topic===t.topic&&e.push(n);return e.length===0?!0:this._taskMerger.hasNewInfo(t,e)}popTasks(t){let e=0,n=[],i=this._pending.tasks();for(let s=0;s<i.length&&e<t;s++){let o=i[s];n.push(o),e+=o.size,this._pending.delete(o.topic),this._activeTotalSize+=o.size,this._active.add(o)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(t){this._active.has(t)&&(this._activeTotalSize-=t.size,this._active.delete(t))}remove(t){this._pending.delete(t)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(t,e){return t[1]._pending.length===0?1:e[1]._pending.length===0?-1:t[1]._activeTotalSize===e[1]._activeTotalSize?e[1]._pending.length-t[1]._pending.length:t[1]._activeTotalSize-e[1]._activeTotalSize}},Sr=class{constructor(){this._tasks=new $t([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((t,e)=>t+e.task.size,0)}get(t){return this._tasks?.get(t)?.task}add(t){this._tasks.set(t.topic,{created:Date.now(),task:t})}delete(t){this._tasks.delete(t)}tasks(){return[...this._tasks.values()].map(t=>t.task)}updatePriority(t,e){let n=this._tasks.get(t);if(n==null)return;let i=this._tasks.indexOf(t);n.task.priority=e,this._tasks.update(i)}_compare(t,e){return t[1].task.priority===e[1].task.priority?t[1].created-e[1].created:e[1].task.priority-t[1].task.priority}};var Yi={hasNewInfo(r,t){let e=!1,n=!1;for(let i of t)i.data.haveBlock&&(e=!0),i.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!e&&r.data.haveBlock)},merge(r,t){let e=r.data,n=t.data;!n.haveBlock&&e.haveBlock&&(n.haveBlock=e.haveBlock,n.blockSize=e.blockSize),!n.isWantBlock&&e.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||e.haveBlock)&&(n.haveBlock=e.haveBlock,t.size=r.size)),n.isWantBlock&&n.haveBlock&&(t.size=n.blockSize)}};var ts=x.WantType,Qa=16*1024,Xa=1024,we=class{constructor(t,e,n,i,s,o={}){this._log=R(t,"engine"),this.blockstore=e,this.network=n,this._stats=i,this._opts=this._processOpts(o),this.ledgerMap=it({name:"ipfs_bitswap_ledger_map",metrics:s.metrics}),this._running=!1,this._requestQueue=new me(Yi)}_processOpts(t){return{maxSizeReplaceHasWithBlock:Xa,targetMessageSize:Qa,...t}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(t=>{this._log.error("error processing stats",t)})})}async _processTasks(){if(!this._running)return;let{peerId:t,tasks:e,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(e.length===0)return;let i=new x(!1);i.setPendingBytes(n);let s=[],o=new Map;for(let c of e){let u=b.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(s.push(u),o.set(c.topic,c.data)):i.addHave(u):i.addDontHave(u)}let a=await this._getBlocks(s);for(let[c,u]of o){let l=b.parse(c),h=a.get(c);h!=null?i.addBlock(l,h):u.sendDontHave&&i.addDontHave(l)}if(i.empty){t!=null&&this._requestQueue.tasksDone(t,e),this._scheduleProcessTasks();return}try{t!=null&&await this.network.sendMessage(t,i);for(let[c,u]of a.entries())t!=null&&this.messageSent(t,b.parse(c),u)}catch(c){this._log.error(c)}t!=null&&this._requestQueue.tasksDone(t,e),this._scheduleProcessTasks()}wantlistForPeer(t){let e=t.toString(),n=this.ledgerMap.get(e);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(t){let e=t.toString(),n=this.ledgerMap.get(e);if(n!=null)return{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.partner)}receivedBlocks(t){if(t.length!==0){for(let e of this.ledgerMap.values())for(let n of t){let i=e.wantlistContains(n.cid);if(i==null)continue;let s=n.data.length,o=this._sendAsBlock(i.wantType,s),a=s;o||(a=x.blockPresenceSize(i.cid)),this._requestQueue.pushTasks(e.partner,[{topic:i.cid.toString(w),priority:i.priority,size:a,data:{blockSize:s,isWantBlock:o,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(t,e){let n=this._findOrCreate(t);if(e.empty)return;if(e.full&&(n.wantlist=new J),this._updateBlockAccounting(e.blocks,n),e.wantlist.size===0){this._scheduleProcessTasks();return}let i=[],s=[];e.wantlist.forEach(o=>{o.cancel?(n.cancelWant(o.cid),i.push(o.cid)):(n.wants(o.cid,o.priority,o.wantType),s.push(o))}),this._cancelWants(t,i),await this._addWants(t,s),this._scheduleProcessTasks()}_cancelWants(t,e){for(let n of e)this._requestQueue.remove(n.toString(w),t)}async _addWants(t,e){let n=await this._getBlockSizes(e.map(s=>s.cid)),i=[];for(let s of e){let o=s.cid.toString(w),a=n.get(o);if(a==null)s.sendDontHave&&i.push({topic:o,priority:s.priority,size:x.blockPresenceSize(s.cid),data:{isWantBlock:s.wantType===ts.Block,blockSize:0,haveBlock:!1,sendDontHave:s.sendDontHave}});else{let c=this._sendAsBlock(s.wantType,a),u=a;c||(u=x.blockPresenceSize(s.cid)),i.push({topic:o,priority:s.priority,size:u,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:s.sendDontHave}})}this._requestQueue.pushTasks(t,i)}}_sendAsBlock(t,e){return t===ts.Block||e<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(t){let e=await this._getBlocks(t);return new Map([...e].map(([n,i])=>[n,i.length]))}async _getBlocks(t){let e=new Map;return await Promise.all(t.map(async n=>{try{let i=await this.blockstore.get(n);e.set(n.toString(w),i)}catch(i){i.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,i)}})),e}_updateBlockAccounting(t,e){for(let n of t.values())this._log("got block (%s bytes)",n.length),e.receivedBytes(n.length)}messageSent(t,e,n){let i=this._findOrCreate(t);i.sentBytes(n.length),i.wantlist.remove(e)}numBytesSentTo(t){return this._findOrCreate(t).accounting.bytesSent}numBytesReceivedFrom(t){return this._findOrCreate(t).accounting.bytesRecv}peerDisconnected(t){this.ledgerMap.delete(t.toString())}_findOrCreate(t){let e=t.toString(),n=this.ledgerMap.get(e);if(n!=null)return n;let i=new ge(t);return this.ledgerMap.set(e,i),this._stats!=null&&this._stats.push(e,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var ws=L(ve(),1);var Cr={};M(Cr,{identity:()=>nc});var nc=Et({prefix:"\0",name:"identity",encode:r=>$r(r),decode:r=>Vr(r)});var Ar={};M(Ar,{base2:()=>ic});var ic=S({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Tr={};M(Tr,{base8:()=>sc});var sc=S({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Lr={};M(Lr,{base10:()=>oc});var oc=tt({prefix:"9",name:"base10",alphabet:"0123456789"});var Mr={};M(Mr,{base16:()=>ac,base16upper:()=>cc});var ac=S({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),cc=S({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Fr={};M(Fr,{base36:()=>uc,base36upper:()=>lc});var uc=tt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lc=tt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Dr={};M(Dr,{base256emoji:()=>gc});var hs=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}"),hc=hs.reduce((r,t,e)=>(r[e]=t,r),[]),fc=hs.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function dc(r){return r.reduce((t,e)=>(t+=hc[e],t),"")}function pc(r){let t=[];for(let e of r){let n=fc[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var gc=Et({prefix:"\u{1F680}",name:"base256emoji",encode:dc,decode:pc});var Gh=new TextEncoder,jh=new TextDecoder;var Nr={...Cr,...Ar,...Tr,...Lr,...Mr,...qe,...Fr,...We,...Qe,...Dr},Zh={...ze,...De};function ps(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ds=ps("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Or=ps("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=Y(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),yc={utf8:ds,"utf-8":ds,hex:Nr.base16,latin1:Or,ascii:Or,binary:Or,...Nr},gs=yc;function Pr(r,t="utf8"){let e=gs[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):e.encoder.encode(r).substring(1)}var ms=r=>`unwant:${Pr(r.multihash.bytes,"base64")}`,ys=r=>`block:${Pr(r.multihash.bytes,"base64")}`,xe=class extends ws.EventEmitter{constructor(t){super(),this.setMaxListeners(Mi),this._log=R(t,"notif")}hasBlock(t,e){let n=ys(t);this._log(n),this.emit(n,e)}async wantBlock(t,e={}){if(t==null)throw new Error("Not a valid cid");let n=ys(t),i=ms(t);return this._log(`wantBlock:${t}`),await new Promise((s,o)=>{let a=()=>{this.removeListener(n,c),o(new Error(`Block for ${t} unwanted`))},c=u=>{this.removeListener(i,a),s(u)};this.once(i,a),this.once(n,c),e.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),o(new Error(`Want for ${t} aborted`))})})}unwantBlock(t){let e=ms(t);this._log(e),this.emit(e)}};var Es=L(ve(),1);var xs=L(ve(),1),zr=L(vs(),1),Gt=class extends xs.EventEmitter{constructor(t,e){super(),this._options=e,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),t.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(i=>{(this._movingAverages[n][i]=(0,zr.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}stop(){this._timeout!=null&&clearTimeout(this._timeout)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}push(t,e){this._enabled&&(this._queue.push([t,e,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout!=null&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let t=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-t),0)}_update(){if(this._timeout=void 0,this._queue.length>0){let t;for(;this._queue.length>0;){let e=t=this._queue.shift();e!=null&&this._applyOp(e)}t!=null&&this._updateFrequency(t[2]),this.emit("update",this._stats)}}_updateFrequency(t){let e=t-this._frequencyLastTime;e>0&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,e,t)}),this._frequencyLastTime=t}_updateFrequencyFor(t,e,n){let i=this._frequencyAccumulators[t]??0;this._frequencyAccumulators[t]=0;let s=i/e*1e3,o=this._movingAverages[t];o==null&&(o=this._movingAverages[t]={}),this._options.movingAverageIntervals.forEach(a=>{let c=o[a];c==null&&(c=o[a]=(0,zr.default)(a)),c.push(n,s)})}_applyOp(t){let e=t[0],n=t[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,e)||(this._stats[e]=BigInt(0)),this._stats[e]=BigInt(this._stats[e])+BigInt(n),this._frequencyAccumulators[e]==null&&(this._frequencyAccumulators[e]=0),this._frequencyAccumulators[e]+=n}};var ks={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},ke=class extends Es.EventEmitter{constructor(t,e=[],n=ks){super();let i=Object.assign({},ks,n);if(typeof i.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof i.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=e,this._options=i,this._enabled=this._options.enabled,this._global=new Gt(e,i),this._global.on("update",s=>this.emit("update",s)),this._peers=it({name:"ipfs_bitswap_stats_peers",metrics:t.metrics})}enable(){this._enabled=!0,this._options.enabled=!0,this._global.enable()}disable(){this._enabled=!1,this._options.enabled=!1,this._global.disable()}stop(){this._enabled=!1,this._global.stop();for(let t of this._peers)t[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(t){let e=t.toString();return this._peers.get(e)}push(t,e,n){if(this._enabled&&(this._global.push(e,n),t!=null)){let i=this._peers.get(t);i==null&&(i=new Gt(this._initialCounters,this._options),this._peers.set(t,i)),i.push(e,n)}}disconnected(t){let e=t.toString(),n=this._peers.get(e);n!=null&&(n.stop(),this._peers.delete(e))}};var As=L(Bs(),1);async function Ee(r){for await(let t of r);}async function*K(r,t){for await(let e of r)await t(e)&&(yield e)}async function*Se(r,t){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}async function Rr(r){let t=[];for await(let e of r)t.push(e);return t}var Cs=(r,t)=>async function*(){yield*(await Rr(r)).sort(t)}(),st=class{open(){return Promise.reject(new Error(".open is not implemented"))}close(){return Promise.reject(new Error(".close is not implemented"))}put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:i}of t)await this.put(n,i,e),yield{key:n,value:i}}async*getMany(t,e={}){for await(let n of t)yield this.get(n,e)}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,i){t.push({key:n,value:i})},delete(n){e.push(n)},commit:async n=>{await Ee(this.putMany(t,n)),t=[],await Ee(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null&&(n=K(n,i=>i.key.toString().startsWith(t.prefix||""))),Array.isArray(t.filters)&&(n=t.filters.reduce((i,s)=>K(i,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((i,s)=>Cs(i,s),n)),t.offset!=null){let i=0;n=K(n,()=>i++>=(t.offset||0))}return t.limit!=null&&(n=Se(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null&&(n=K(n,i=>i.toString().startsWith(t.prefix||""))),Array.isArray(t.filters)&&(n=t.filters.reduce((i,s)=>K(i,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((i,s)=>Cs(i,s),n)),t.offset!=null){let i=0;n=K(n,()=>i++>=t.offset)}return t.limit!=null&&(n=Se(n,t.limit)),n}};var bc={async getHasher(){throw new Error("Not implemented")}},_c={maxInboundStreams:32,maxOutboundStreams:128,incomingStreamTimeout:3e4,hashLoader:bc,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},vc=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],Be=class extends st{constructor(t,e,n={}){super(),this._libp2p=t,this._log=R(this.peerId),this._options=Object.assign({},_c,n),this._stats=new ke(t,vc,{enabled:this._options.statsEnabled,computeThrottleTimeout:this._options.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:this._options.statsComputeThrottleMaxQueueSize}),this.network=new pe(t,this,this._stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=e,this.engine=new we(this.peerId,e,this.network,this._stats,t),this.wm=new ae(this.peerId,this.network,this._stats,t),this.notifications=new xe(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(t,e){try{await this.engine.messageReceived(t,e)}catch{this._log("failed to receive message",e)}if(e.blocks.size===0)return;let n=[];for(let[i,s]of e.blocks.entries()){let o=b.parse(i);n.push({wasWanted:this.wm.wantlist.contains(o),cid:o,data:s})}this.wm.cancelWants(n.filter(({wasWanted:i})=>i).map(({cid:i})=>i)),await Promise.all(n.map(async({cid:i,wasWanted:s,data:o})=>{await this._handleReceivedBlock(t,i,o,s)}))}async _handleReceivedBlock(t,e,n,i){this._log("received block");let s=await this.blockstore.has(e);this._updateReceiveCounters(t.toString(),e,n,s),i&&await this.put(e,n)}_updateReceiveCounters(t,e,n,i){this._stats.push(t,"blocksReceived",1),this._stats.push(t,"dataReceived",n.length),i&&(this._stats.push(t,"dupBlksReceived",1),this._stats.push(t,"dupDataReceived",n.length))}_receiveError(t){this._log.error("ReceiveError",t)}_onPeerConnected(t){this.wm.connected(t)}_onPeerDisconnected(t){this.wm.disconnected(t),this.engine.peerDisconnected(t),this._stats.disconnected(t)}enableStats(){this._stats.enable()}disableStats(){this._stats.disable()}wantlistForPeer(t,e){return this.engine.wantlistForPeer(t)}ledgerForPeer(t){return this.engine.ledgerForPeer(t)}async get(t,e={}){let n=async(c,u)=>(this.wm.wantBlocks([c],u),await this.notifications.wantBlock(c,u)),i=!1,s=async(c,u)=>{try{return await this.blockstore.get(c,u)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l;return i||(i=!0,this.network.findAndConnect(c,u).catch(h=>{this._log.error(h)})),await n(c,u)}},o=new AbortController,a=e.signal!=null?(0,As.anySignal)([e.signal,o.signal]):o.signal;try{return await Promise.race([this.notifications.wantBlock(t,{signal:a}),s(t,{signal:a})])}finally{o.abort()}}async*getMany(t,e={}){for await(let n of t)yield this.get(n,e)}unwant(t){let e=Array.isArray(t)?t:[t];this.wm.unwantBlocks(e),e.forEach(n=>{this.notifications.unwantBlock(n)})}cancelWants(t){this.wm.cancelWants(Array.isArray(t)?t:[t])}async put(t,e,n){await this.blockstore.put(t,e),this._sendHaveBlockNotifications(t,e)}async*putMany(t,e){for await(let{key:n,value:i}of this.blockstore.putMany(t,e))this._sendHaveBlockNotifications(n,i),yield{key:n,value:i}}_sendHaveBlockNotifications(t,e){this.notifications.hasBlock(t,e),this.engine.receivedBlocks([{cid:t,data:e}]),this.network.provide(t).catch(n=>{this._log.error("Failed to provide: %s",n.message)})}getWantlist(){return this.wm.wantlist.entries()}peers(){return this.engine.peers()}stat(){return this._stats}async start(){this.wm.start(),await this.network.start(),this.engine.start(),this.started=!0}async stop(){this._stats.stop(),this.wm.stop(),await this.network.stop(),this.engine.stop(),this.started=!1}unwrap(){return this.blockstore}async has(t){return await this.blockstore.has(t)}};var Ts=(r,t,e={})=>new Be(r,t,e);var Ce={};M(Ce,{abortedError:()=>xc,notFoundError:()=>Ls});var Ur=L(gr(),1);function Ls(r){return r=r||new Error("Not Found"),(0,Ur.default)(r,"ERR_NOT_FOUND")}function xc(r){return r=r||new Error("Aborted"),(0,Ur.default)(r,"ERR_ABORTED")}var Uf={...Ce};var Ae=class extends st{constructor(t,e){super(),this.child=t,this.bitswap=e}async open(){await this.child.open()}async close(){await this.child.close()}unwrap(){return this.child}async put(t,e,n={}){await this.has(t)||(this.bitswap.isStarted()?await this.bitswap.put(t,e,n):await this.child.put(t,e,n))}async*putMany(t,e={}){let n=K(t,async({key:i})=>!await this.has(i));this.bitswap.isStarted()?yield*this.bitswap.putMany(n,e):yield*this.child.putMany(n,e)}async get(t,e={}){return!await this.has(t)&&this.bitswap.isStarted()?await this.bitswap.get(t,e):await this.child.get(t,e)}async*getMany(t,e={}){let n=wt({objectMode:!0}),i=wt({objectMode:!0});Promise.resolve().then(async()=>{for await(let s of t)!await this.has(s)&&this.bitswap.isStarted()?n.push(s):i.push(s);n.end(),i.end()}).catch(s=>{n.throw(s)}),yield*Wt(this.bitswap.getMany(n,e),this.child.getMany(i,e))}async delete(t,e={}){await this.child.delete(t,e)}async*deleteMany(t,e={}){yield*this.child.deleteMany(t,e)}async has(t,e={}){return await this.child.has(t,e)}async*query(t,e={}){yield*this.child.query(t,e)}async*queryKeys(t,e={}){yield*this.child.queryKeys(t,e)}};var kc=function(r,t,e,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?r!==t||!i:!t.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,e):i?i.value=e:t.set(r,e),e},Hr=function(r,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?r!==t||!n:!t.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(r):n?n.value:t.get(r)},Ft,Te=class{constructor(t){Ft.set(this,void 0);let e=[at,Pe,Fe,...t.hashers??[]];kc(this,Ft,Ts(t.libp2p,t.blockstore,{hashLoader:{getHasher:async n=>{let i=e.find(s=>s.code===n||s.name===n);if(i!=null)return await Promise.resolve(i);throw new Error(`Could not load hasher for code/name "${n}"`)}}}),"f"),this.libp2p=t.libp2p,this.blockstore=new Ae(t.blockstore,Hr(this,Ft,"f")),this.datastore=t.datastore}async start(){Hr(this,Ft,"f").start(),await this.libp2p.start()}async stop(){Hr(this,Ft,"f").stop(),await this.libp2p.stop()}async info(){return{peerId:this.libp2p.peerId,multiaddrs:this.libp2p.getMultiaddrs(),agentVersion:this.libp2p.identifyService.host.agentVersion,protocolVersion:this.libp2p.identifyService.host.protocolVersion,protocols:this.libp2p.getProtocols(),status:this.libp2p.isStarted()?"running":"stopped"}}};Ft=new WeakMap;async function Ec(r){let t=new Te(r);return r.start!==!1&&await t.start(),t}return Ps(Sc);})();
|
|
3
|
+
return Helia}));
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Helia, InfoResponse } from '@helia/interface';
|
|
2
|
+
import type { Libp2p } from '@libp2p/interface-libp2p';
|
|
3
|
+
import type { Blockstore } from 'interface-blockstore';
|
|
4
|
+
import type { Datastore } from 'interface-datastore';
|
|
5
|
+
import type { HeliaInit } from '.';
|
|
6
|
+
export declare class HeliaImpl implements Helia {
|
|
7
|
+
#private;
|
|
8
|
+
libp2p: Libp2p;
|
|
9
|
+
blockstore: Blockstore;
|
|
10
|
+
datastore: Datastore;
|
|
11
|
+
constructor(init: HeliaInit);
|
|
12
|
+
start(): Promise<void>;
|
|
13
|
+
stop(): Promise<void>;
|
|
14
|
+
info(): Promise<InfoResponse>;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=helia.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helia.d.ts","sourceRoot":"","sources":["../../src/helia.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAC3D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAA;AACtD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACtD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAIpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,GAAG,CAAA;AAIlC,qBAAa,SAAU,YAAW,KAAK;;IAC9B,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,UAAU,CAAA;IACtB,SAAS,EAAE,SAAS,CAAA;gBAId,IAAI,EAAE,SAAS;IA6BtB,KAAK,IAAK,OAAO,CAAC,IAAI,CAAC;IAKvB,IAAI,IAAK,OAAO,CAAC,IAAI,CAAC;IAKtB,IAAI,IAAK,OAAO,CAAC,YAAY,CAAC;CAUrC"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
5
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
+
};
|
|
7
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
9
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
+
};
|
|
12
|
+
var _HeliaImpl_bitswap;
|
|
13
|
+
import { identity } from 'multiformats/hashes/identity';
|
|
14
|
+
import { sha256, sha512 } from 'multiformats/hashes/sha2';
|
|
15
|
+
import { createBitswap } from 'ipfs-bitswap';
|
|
16
|
+
import { BlockStorage } from './storage.js';
|
|
17
|
+
export class HeliaImpl {
|
|
18
|
+
constructor(init) {
|
|
19
|
+
_HeliaImpl_bitswap.set(this, void 0);
|
|
20
|
+
const hashers = [
|
|
21
|
+
sha256,
|
|
22
|
+
sha512,
|
|
23
|
+
identity,
|
|
24
|
+
...(init.hashers ?? [])
|
|
25
|
+
];
|
|
26
|
+
__classPrivateFieldSet(this, _HeliaImpl_bitswap, createBitswap(init.libp2p, init.blockstore, {
|
|
27
|
+
hashLoader: {
|
|
28
|
+
getHasher: async (codecOrName) => {
|
|
29
|
+
const hasher = hashers.find(hasher => {
|
|
30
|
+
return hasher.code === codecOrName || hasher.name === codecOrName;
|
|
31
|
+
});
|
|
32
|
+
if (hasher != null) {
|
|
33
|
+
return await Promise.resolve(hasher);
|
|
34
|
+
}
|
|
35
|
+
throw new Error(`Could not load hasher for code/name "${codecOrName}"`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}), "f");
|
|
39
|
+
this.libp2p = init.libp2p;
|
|
40
|
+
this.blockstore = new BlockStorage(init.blockstore, __classPrivateFieldGet(this, _HeliaImpl_bitswap, "f"));
|
|
41
|
+
this.datastore = init.datastore;
|
|
42
|
+
}
|
|
43
|
+
async start() {
|
|
44
|
+
__classPrivateFieldGet(this, _HeliaImpl_bitswap, "f").start();
|
|
45
|
+
await this.libp2p.start();
|
|
46
|
+
}
|
|
47
|
+
async stop() {
|
|
48
|
+
__classPrivateFieldGet(this, _HeliaImpl_bitswap, "f").stop();
|
|
49
|
+
await this.libp2p.stop();
|
|
50
|
+
}
|
|
51
|
+
async info() {
|
|
52
|
+
return {
|
|
53
|
+
peerId: this.libp2p.peerId,
|
|
54
|
+
multiaddrs: this.libp2p.getMultiaddrs(),
|
|
55
|
+
agentVersion: this.libp2p.identifyService.host.agentVersion,
|
|
56
|
+
protocolVersion: this.libp2p.identifyService.host.protocolVersion,
|
|
57
|
+
protocols: this.libp2p.getProtocols(),
|
|
58
|
+
status: this.libp2p.isStarted() ? 'running' : 'stopped'
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
_HeliaImpl_bitswap = new WeakMap();
|
|
63
|
+
//# sourceMappingURL=helia.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helia.js","sourceRoot":"","sources":["../../src/helia.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAA;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAA;AAGzD,OAAO,EAAW,aAAa,EAAE,MAAM,cAAc,CAAA;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAE3C,MAAM,OAAO,SAAS;IAOpB,YAAa,IAAe;QAF5B,qCAAiB;QAGf,MAAM,OAAO,GAAsB;YACjC,MAAM;YACN,MAAM;YACN,QAAQ;YACR,GAAG,CAAC,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;SACxB,CAAA;QAED,uBAAA,IAAI,sBAAY,aAAa,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE;YAC1D,UAAU,EAAE;gBACV,SAAS,EAAE,KAAK,EAAE,WAA4B,EAAE,EAAE;oBAChD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;wBACnC,OAAO,MAAM,CAAC,IAAI,KAAK,WAAW,IAAI,MAAM,CAAC,IAAI,KAAK,WAAW,CAAA;oBACnE,CAAC,CAAC,CAAA;oBAEF,IAAI,MAAM,IAAI,IAAI,EAAE;wBAClB,OAAO,MAAM,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;qBACrC;oBAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,WAAW,GAAG,CAAC,CAAA;gBACzE,CAAC;aACF;SACF,CAAC,MAAA,CAAA;QAEF,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QACzB,IAAI,CAAC,UAAU,GAAG,IAAI,YAAY,CAAC,IAAI,CAAC,UAAU,EAAE,uBAAA,IAAI,0BAAS,CAAC,CAAA;QAClE,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAA;IACjC,CAAC;IAED,KAAK,CAAC,KAAK;QACT,uBAAA,IAAI,0BAAS,CAAC,KAAK,EAAE,CAAA;QACrB,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;IAC3B,CAAC;IAED,KAAK,CAAC,IAAI;QACR,uBAAA,IAAI,0BAAS,CAAC,IAAI,EAAE,CAAA;QACpB,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAA;IAC1B,CAAC;IAED,KAAK,CAAC,IAAI;QACR,OAAO;YACL,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM;YAC1B,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,aAAa,EAAE;YACvC,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,CAAC,YAAY;YAC3D,eAAe,EAAE,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,CAAC,eAAe;YACjE,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE;YACrC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS;SACxD,CAAA;IACH,CAAC;CACF"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
*
|
|
4
|
+
* Create a Helia node.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
*
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { createLibp2p } from 'libp2p'
|
|
10
|
+
* import { MemoryDatastore } from 'datastore-core'
|
|
11
|
+
* import { MemoryBlockstore } from 'blockstore-core'
|
|
12
|
+
* import { createHelia } from 'helia'
|
|
13
|
+
* import { unixfs } from '@helia/unixfs'
|
|
14
|
+
* import { CID } from 'multiformats/cid'
|
|
15
|
+
*
|
|
16
|
+
* const node = await createHelia({
|
|
17
|
+
* blockstore: new MemoryBlockstore(),
|
|
18
|
+
* datastore: new MemoryDatastore(),
|
|
19
|
+
* libp2p: await createLibp2p({
|
|
20
|
+
* //... libp2p options
|
|
21
|
+
* })
|
|
22
|
+
* })
|
|
23
|
+
* const fs = unixfs(node)
|
|
24
|
+
* fs.cat(CID.parse('bafyFoo'))
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
import type { Helia } from '@helia/interface';
|
|
28
|
+
import type { Libp2p } from '@libp2p/interface-libp2p';
|
|
29
|
+
import type { Blockstore } from 'interface-blockstore';
|
|
30
|
+
import type { Datastore } from 'interface-datastore';
|
|
31
|
+
import type { MultihashHasher } from 'multiformats/hashes/interface';
|
|
32
|
+
/**
|
|
33
|
+
* Options used to create a Helia node.
|
|
34
|
+
*/
|
|
35
|
+
export interface HeliaInit {
|
|
36
|
+
/**
|
|
37
|
+
* A libp2p node is required to perform network operations
|
|
38
|
+
*/
|
|
39
|
+
libp2p: Libp2p;
|
|
40
|
+
/**
|
|
41
|
+
* The blockstore is where blocks are stored
|
|
42
|
+
*/
|
|
43
|
+
blockstore: Blockstore;
|
|
44
|
+
/**
|
|
45
|
+
* The datastore is where data is stored
|
|
46
|
+
*/
|
|
47
|
+
datastore: Datastore;
|
|
48
|
+
/**
|
|
49
|
+
* By default sha256, sha512 and identity hashes are supported for
|
|
50
|
+
* bitswap operations. To bitswap blocks with CIDs using other hashes
|
|
51
|
+
* pass appropriate MultihashHashers here.
|
|
52
|
+
*/
|
|
53
|
+
hashers?: MultihashHasher[];
|
|
54
|
+
/**
|
|
55
|
+
* Pass `false` to not start the helia node
|
|
56
|
+
*/
|
|
57
|
+
start?: boolean;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Create and return a Helia node
|
|
61
|
+
*/
|
|
62
|
+
export declare function createHelia(init: HeliaInit): Promise<Helia>;
|
|
63
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;AAC7C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAA;AACtD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACtD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AACpD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAA;AAGpE;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAA;IAEd;;OAEG;IACH,UAAU,EAAE,UAAU,CAAA;IAEtB;;OAEG;IACH,SAAS,EAAE,SAAS,CAAA;IAEpB;;;;OAIG;IACH,OAAO,CAAC,EAAE,eAAe,EAAE,CAAA;IAE3B;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB;AAED;;GAEG;AACH,wBAAsB,WAAW,CAAE,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,CAQlE"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
*
|
|
4
|
+
* Create a Helia node.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
*
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { createLibp2p } from 'libp2p'
|
|
10
|
+
* import { MemoryDatastore } from 'datastore-core'
|
|
11
|
+
* import { MemoryBlockstore } from 'blockstore-core'
|
|
12
|
+
* import { createHelia } from 'helia'
|
|
13
|
+
* import { unixfs } from '@helia/unixfs'
|
|
14
|
+
* import { CID } from 'multiformats/cid'
|
|
15
|
+
*
|
|
16
|
+
* const node = await createHelia({
|
|
17
|
+
* blockstore: new MemoryBlockstore(),
|
|
18
|
+
* datastore: new MemoryDatastore(),
|
|
19
|
+
* libp2p: await createLibp2p({
|
|
20
|
+
* //... libp2p options
|
|
21
|
+
* })
|
|
22
|
+
* })
|
|
23
|
+
* const fs = unixfs(node)
|
|
24
|
+
* fs.cat(CID.parse('bafyFoo'))
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
import { HeliaImpl } from './helia.js';
|
|
28
|
+
/**
|
|
29
|
+
* Create and return a Helia node
|
|
30
|
+
*/
|
|
31
|
+
export async function createHelia(init) {
|
|
32
|
+
const helia = new HeliaImpl(init);
|
|
33
|
+
if (init.start !== false) {
|
|
34
|
+
await helia.start();
|
|
35
|
+
}
|
|
36
|
+
return helia;
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAOH,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAkCtC;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAE,IAAe;IAChD,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,IAAI,CAAC,CAAA;IAEjC,IAAI,IAAI,CAAC,KAAK,KAAK,KAAK,EAAE;QACxB,MAAM,KAAK,CAAC,KAAK,EAAE,CAAA;KACpB;IAED,OAAO,KAAK,CAAA;AACd,CAAC"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { BaseBlockstore } from 'blockstore-core';
|
|
2
|
+
import type { Blockstore, KeyQuery, Query } from 'interface-blockstore';
|
|
3
|
+
import type { Bitswap } from 'ipfs-bitswap';
|
|
4
|
+
import type { CID } from 'multiformats/cid';
|
|
5
|
+
import type { AbortOptions } from '@libp2p/interfaces';
|
|
6
|
+
import type { AwaitIterable } from 'interface-store';
|
|
7
|
+
export interface BlockStorageOptions extends AbortOptions {
|
|
8
|
+
progress?: (evt: Event) => void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* BlockStorage is a hybrid blockstore that puts/gets blocks from a configured
|
|
12
|
+
* blockstore (that may be on disk, s3, or something else). If the blocks are
|
|
13
|
+
* not present Bitswap will be used to fetch them from network peers.
|
|
14
|
+
*/
|
|
15
|
+
export declare class BlockStorage extends BaseBlockstore implements Blockstore {
|
|
16
|
+
private readonly child;
|
|
17
|
+
private readonly bitswap;
|
|
18
|
+
/**
|
|
19
|
+
* Create a new BlockStorage
|
|
20
|
+
*/
|
|
21
|
+
constructor(blockstore: Blockstore, bitswap: Bitswap);
|
|
22
|
+
open(): Promise<void>;
|
|
23
|
+
close(): Promise<void>;
|
|
24
|
+
unwrap(): Blockstore;
|
|
25
|
+
/**
|
|
26
|
+
* Put a block to the underlying datastore
|
|
27
|
+
*/
|
|
28
|
+
put(cid: CID, block: Uint8Array, options?: AbortOptions): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Put a multiple blocks to the underlying datastore
|
|
31
|
+
*/
|
|
32
|
+
putMany(blocks: AwaitIterable<{
|
|
33
|
+
key: CID;
|
|
34
|
+
value: Uint8Array;
|
|
35
|
+
}>, options?: AbortOptions): AsyncGenerator<{
|
|
36
|
+
key: CID;
|
|
37
|
+
value: Uint8Array;
|
|
38
|
+
}, void, undefined>;
|
|
39
|
+
/**
|
|
40
|
+
* Get a block by cid
|
|
41
|
+
*/
|
|
42
|
+
get(cid: CID, options?: BlockStorageOptions): Promise<Uint8Array>;
|
|
43
|
+
/**
|
|
44
|
+
* Get multiple blocks back from an array of cids
|
|
45
|
+
*/
|
|
46
|
+
getMany(cids: AwaitIterable<CID>, options?: BlockStorageOptions): AsyncGenerator<Uint8Array, void, undefined>;
|
|
47
|
+
/**
|
|
48
|
+
* Delete a block from the blockstore
|
|
49
|
+
*/
|
|
50
|
+
delete(cid: CID, options?: AbortOptions): Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Delete multiple blocks from the blockstore
|
|
53
|
+
*/
|
|
54
|
+
deleteMany(cids: AwaitIterable<CID>, options?: AbortOptions): AsyncGenerator<CID, void, undefined>;
|
|
55
|
+
has(cid: CID, options?: AbortOptions): Promise<boolean>;
|
|
56
|
+
query(q: Query, options?: AbortOptions): AsyncGenerator<{
|
|
57
|
+
key: CID;
|
|
58
|
+
value: Uint8Array;
|
|
59
|
+
}, void, undefined>;
|
|
60
|
+
queryKeys(q: KeyQuery, options?: AbortOptions): AsyncGenerator<CID, void, undefined>;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../src/storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAIhD,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAA;AACvE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACtD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAEpD,MAAM,WAAW,mBAAoB,SAAQ,YAAY;IACvD,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAA;CAChC;AAED;;;;GAIG;AACH,qBAAa,YAAa,SAAQ,cAAe,YAAW,UAAU;IACpE,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAY;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IAEjC;;OAEG;gBACU,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO;IAO/C,IAAI,IAAK,OAAO,CAAC,IAAI,CAAC;IAItB,KAAK,IAAK,OAAO,CAAC,IAAI,CAAC;IAI7B,MAAM,IAAK,UAAU;IAIrB;;OAEG;IACG,GAAG,CAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,UAAU,EAAE,OAAO,GAAE,YAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAYlF;;OAEG;IACK,OAAO,CAAE,MAAM,EAAE,aAAa,CAAC;QAAE,GAAG,EAAE,GAAG,CAAC;QAAC,KAAK,EAAE,UAAU,CAAA;KAAE,CAAC,EAAE,OAAO,GAAE,YAAiB,GAAG,cAAc,CAAC;QAAE,GAAG,EAAE,GAAG,CAAC;QAAC,KAAK,EAAE,UAAU,CAAA;KAAE,EAAE,IAAI,EAAE,SAAS,CAAC;IAUtK;;OAEG;IACG,GAAG,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,UAAU,CAAC;IAQ5E;;OAEG;IACK,OAAO,CAAE,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,mBAAwB,GAAG,cAAc,CAAC,UAAU,EAAE,IAAI,EAAE,SAAS,CAAC;IAyB1H;;OAEG;IACG,MAAM,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,YAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlE;;OAEG;IACK,UAAU,CAAE,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,YAAiB,GAAG,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,SAAS,CAAC;IAIzG,GAAG,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,YAAiB,GAAG,OAAO,CAAC,OAAO,CAAC;IAI1D,KAAK,CAAE,CAAC,EAAE,KAAK,EAAE,OAAO,GAAE,YAAiB,GAAG,cAAc,CAAC;QAAE,GAAG,EAAE,GAAG,CAAC;QAAC,KAAK,EAAE,UAAU,CAAA;KAAE,EAAE,IAAI,EAAE,SAAS,CAAC;IAI9G,SAAS,CAAE,CAAC,EAAE,QAAQ,EAAE,OAAO,GAAE,YAAiB,GAAG,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,SAAS,CAAC;CAGlG"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { BaseBlockstore } from 'blockstore-core';
|
|
2
|
+
import merge from 'it-merge';
|
|
3
|
+
import { pushable } from 'it-pushable';
|
|
4
|
+
import filter from 'it-filter';
|
|
5
|
+
/**
|
|
6
|
+
* BlockStorage is a hybrid blockstore that puts/gets blocks from a configured
|
|
7
|
+
* blockstore (that may be on disk, s3, or something else). If the blocks are
|
|
8
|
+
* not present Bitswap will be used to fetch them from network peers.
|
|
9
|
+
*/
|
|
10
|
+
export class BlockStorage extends BaseBlockstore {
|
|
11
|
+
/**
|
|
12
|
+
* Create a new BlockStorage
|
|
13
|
+
*/
|
|
14
|
+
constructor(blockstore, bitswap) {
|
|
15
|
+
super();
|
|
16
|
+
this.child = blockstore;
|
|
17
|
+
this.bitswap = bitswap;
|
|
18
|
+
}
|
|
19
|
+
async open() {
|
|
20
|
+
await this.child.open();
|
|
21
|
+
}
|
|
22
|
+
async close() {
|
|
23
|
+
await this.child.close();
|
|
24
|
+
}
|
|
25
|
+
unwrap() {
|
|
26
|
+
return this.child;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Put a block to the underlying datastore
|
|
30
|
+
*/
|
|
31
|
+
async put(cid, block, options = {}) {
|
|
32
|
+
if (await this.has(cid)) {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (this.bitswap.isStarted()) {
|
|
36
|
+
await this.bitswap.put(cid, block, options);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
await this.child.put(cid, block, options);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Put a multiple blocks to the underlying datastore
|
|
44
|
+
*/
|
|
45
|
+
async *putMany(blocks, options = {}) {
|
|
46
|
+
const missingBlocks = filter(blocks, async ({ key }) => { return !(await this.has(key)); });
|
|
47
|
+
if (this.bitswap.isStarted()) {
|
|
48
|
+
yield* this.bitswap.putMany(missingBlocks, options);
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
yield* this.child.putMany(missingBlocks, options);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Get a block by cid
|
|
56
|
+
*/
|
|
57
|
+
async get(cid, options = {}) {
|
|
58
|
+
if (!(await this.has(cid)) && this.bitswap.isStarted()) {
|
|
59
|
+
return await this.bitswap.get(cid, options);
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
return await this.child.get(cid, options);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Get multiple blocks back from an array of cids
|
|
67
|
+
*/
|
|
68
|
+
async *getMany(cids, options = {}) {
|
|
69
|
+
const getFromBitswap = pushable({ objectMode: true });
|
|
70
|
+
const getFromChild = pushable({ objectMode: true });
|
|
71
|
+
void Promise.resolve().then(async () => {
|
|
72
|
+
for await (const cid of cids) {
|
|
73
|
+
if (!(await this.has(cid)) && this.bitswap.isStarted()) {
|
|
74
|
+
getFromBitswap.push(cid);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
getFromChild.push(cid);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
getFromBitswap.end();
|
|
81
|
+
getFromChild.end();
|
|
82
|
+
}).catch(err => {
|
|
83
|
+
getFromBitswap.throw(err);
|
|
84
|
+
});
|
|
85
|
+
yield* merge(this.bitswap.getMany(getFromBitswap, options), this.child.getMany(getFromChild, options));
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Delete a block from the blockstore
|
|
89
|
+
*/
|
|
90
|
+
async delete(cid, options = {}) {
|
|
91
|
+
await this.child.delete(cid, options);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Delete multiple blocks from the blockstore
|
|
95
|
+
*/
|
|
96
|
+
async *deleteMany(cids, options = {}) {
|
|
97
|
+
yield* this.child.deleteMany(cids, options);
|
|
98
|
+
}
|
|
99
|
+
async has(cid, options = {}) {
|
|
100
|
+
return await this.child.has(cid, options);
|
|
101
|
+
}
|
|
102
|
+
async *query(q, options = {}) {
|
|
103
|
+
yield* this.child.query(q, options);
|
|
104
|
+
}
|
|
105
|
+
async *queryKeys(q, options = {}) {
|
|
106
|
+
yield* this.child.queryKeys(q, options);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
//# sourceMappingURL=storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAChD,OAAO,KAAK,MAAM,UAAU,CAAA;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AACtC,OAAO,MAAM,MAAM,WAAW,CAAA;AAW9B;;;;GAIG;AACH,MAAM,OAAO,YAAa,SAAQ,cAAc;IAI9C;;OAEG;IACH,YAAa,UAAsB,EAAE,OAAgB;QACnD,KAAK,EAAE,CAAA;QAEP,IAAI,CAAC,KAAK,GAAG,UAAU,CAAA;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,KAAK,CAAC,IAAI;QACR,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAA;IACzB,CAAC;IAED,KAAK,CAAC,KAAK;QACT,MAAM,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAA;IAC1B,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,KAAK,CAAA;IACnB,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,GAAG,CAAE,GAAQ,EAAE,KAAiB,EAAE,UAAwB,EAAE;QAChE,IAAI,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YACvB,OAAM;SACP;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE;YAC5B,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,CAAA;SAC5C;aAAM;YACL,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,CAAA;SAC1C;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,CAAE,OAAO,CAAE,MAAsD,EAAE,UAAwB,EAAE;QACjG,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAA,CAAC,CAAC,CAAC,CAAA;QAE1F,IAAI,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE;YAC5B,KAAM,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,OAAO,CAAC,CAAA;SACrD;aAAM;YACL,KAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,aAAa,EAAE,OAAO,CAAC,CAAA;SACnD;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,GAAG,CAAE,GAAQ,EAAE,UAA+B,EAAE;QACpD,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE;YACtD,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;SAC5C;aAAM;YACL,OAAO,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;SAC1C;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,CAAE,OAAO,CAAE,IAAwB,EAAE,UAA+B,EAAE;QAC1E,MAAM,cAAc,GAAG,QAAQ,CAAM,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAA;QAC1D,MAAM,YAAY,GAAG,QAAQ,CAAM,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAA;QAExD,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;YACrC,IAAI,KAAK,EAAE,MAAM,GAAG,IAAI,IAAI,EAAE;gBAC5B,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE;oBACtD,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;iBACzB;qBAAM;oBACL,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;iBACvB;aACF;YAED,cAAc,CAAC,GAAG,EAAE,CAAA;YACpB,YAAY,CAAC,GAAG,EAAE,CAAA;QACpB,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;YACb,cAAc,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QAC3B,CAAC,CAAC,CAAA;QAEF,KAAM,CAAC,CAAC,KAAK,CACX,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,EAAE,OAAO,CAAC,EAC7C,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,OAAO,CAAC,CAC1C,CAAA;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,MAAM,CAAE,GAAQ,EAAE,UAAwB,EAAE;QAChD,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;IACvC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,CAAE,UAAU,CAAE,IAAwB,EAAE,UAAwB,EAAE;QACtE,KAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IAC9C,CAAC;IAED,KAAK,CAAC,GAAG,CAAE,GAAQ,EAAE,UAAwB,EAAE;QAC7C,OAAO,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;IAC3C,CAAC;IAED,KAAK,CAAC,CAAE,KAAK,CAAE,CAAQ,EAAE,UAAwB,EAAE;QACjD,KAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;IACtC,CAAC;IAED,KAAK,CAAC,CAAE,SAAS,CAAE,CAAW,EAAE,UAAwB,EAAE;QACxD,KAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;IAC1C,CAAC;CACF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "helia",
|
|
3
|
+
"version": "0.0.0-97da23e",
|
|
4
|
+
"description": "An implementation of IPFS in JavaScript",
|
|
5
|
+
"license": "Apache-2.0 OR MIT",
|
|
6
|
+
"homepage": "https://github.com/ipfs/helia/tree/master/packages/helia#readme",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/ipfs/helia.git"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/ipfs/helia/issues"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"IPFS"
|
|
16
|
+
],
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=16.0.0",
|
|
19
|
+
"npm": ">=7.0.0"
|
|
20
|
+
},
|
|
21
|
+
"type": "module",
|
|
22
|
+
"types": "./dist/src/index.d.ts",
|
|
23
|
+
"files": [
|
|
24
|
+
"src",
|
|
25
|
+
"dist",
|
|
26
|
+
"!dist/test",
|
|
27
|
+
"!**/*.tsbuildinfo"
|
|
28
|
+
],
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/src/index.d.ts",
|
|
32
|
+
"import": "./dist/src/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"eslintConfig": {
|
|
36
|
+
"extends": "ipfs",
|
|
37
|
+
"parserOptions": {
|
|
38
|
+
"sourceType": "module"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"release": {
|
|
42
|
+
"branches": [
|
|
43
|
+
"main"
|
|
44
|
+
],
|
|
45
|
+
"plugins": [
|
|
46
|
+
[
|
|
47
|
+
"@semantic-release/commit-analyzer",
|
|
48
|
+
{
|
|
49
|
+
"preset": "conventionalcommits",
|
|
50
|
+
"releaseRules": [
|
|
51
|
+
{
|
|
52
|
+
"breaking": true,
|
|
53
|
+
"release": "major"
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
"revert": true,
|
|
57
|
+
"release": "patch"
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"type": "feat",
|
|
61
|
+
"release": "minor"
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
"type": "fix",
|
|
65
|
+
"release": "patch"
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
"type": "docs",
|
|
69
|
+
"release": "patch"
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"type": "test",
|
|
73
|
+
"release": "patch"
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
"type": "deps",
|
|
77
|
+
"release": "patch"
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
"scope": "no-release",
|
|
81
|
+
"release": false
|
|
82
|
+
}
|
|
83
|
+
]
|
|
84
|
+
}
|
|
85
|
+
],
|
|
86
|
+
[
|
|
87
|
+
"@semantic-release/release-notes-generator",
|
|
88
|
+
{
|
|
89
|
+
"preset": "conventionalcommits",
|
|
90
|
+
"presetConfig": {
|
|
91
|
+
"types": [
|
|
92
|
+
{
|
|
93
|
+
"type": "feat",
|
|
94
|
+
"section": "Features"
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"type": "fix",
|
|
98
|
+
"section": "Bug Fixes"
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
"type": "chore",
|
|
102
|
+
"section": "Trivial Changes"
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"type": "docs",
|
|
106
|
+
"section": "Documentation"
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
"type": "deps",
|
|
110
|
+
"section": "Dependencies"
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
"type": "test",
|
|
114
|
+
"section": "Tests"
|
|
115
|
+
}
|
|
116
|
+
]
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
],
|
|
120
|
+
"@semantic-release/changelog",
|
|
121
|
+
"@semantic-release/npm",
|
|
122
|
+
"@semantic-release/github",
|
|
123
|
+
"@semantic-release/git"
|
|
124
|
+
]
|
|
125
|
+
},
|
|
126
|
+
"scripts": {
|
|
127
|
+
"clean": "aegir clean",
|
|
128
|
+
"lint": "aegir lint",
|
|
129
|
+
"dep-check": "aegir dep-check",
|
|
130
|
+
"build": "aegir build",
|
|
131
|
+
"test": "aegir test",
|
|
132
|
+
"test:chrome": "aegir test -t browser --cov",
|
|
133
|
+
"test:chrome-webworker": "aegir test -t webworker",
|
|
134
|
+
"test:firefox": "aegir test -t browser -- --browser firefox",
|
|
135
|
+
"test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
|
|
136
|
+
"test:node": "aegir test -t node --cov",
|
|
137
|
+
"test:electron-main": "aegir test -t electron-main",
|
|
138
|
+
"release": "aegir release"
|
|
139
|
+
},
|
|
140
|
+
"dependencies": {
|
|
141
|
+
"@helia/interface": "0.0.0-97da23e",
|
|
142
|
+
"@libp2p/interface-libp2p": "^1.1.0",
|
|
143
|
+
"@libp2p/interfaces": "^3.3.1",
|
|
144
|
+
"blockstore-core": "^3.0.0",
|
|
145
|
+
"interface-blockstore": "^4.0.1",
|
|
146
|
+
"interface-datastore": "^7.0.3",
|
|
147
|
+
"interface-store": "^3.0.4",
|
|
148
|
+
"ipfs-bitswap": "^16.0.0",
|
|
149
|
+
"it-filter": "^2.0.0",
|
|
150
|
+
"it-merge": "^2.0.0",
|
|
151
|
+
"it-pushable": "^3.1.2",
|
|
152
|
+
"multiformats": "^11.0.1"
|
|
153
|
+
},
|
|
154
|
+
"devDependencies": {
|
|
155
|
+
"@chainsafe/libp2p-noise": "^11.0.0",
|
|
156
|
+
"@chainsafe/libp2p-yamux": "^3.0.5",
|
|
157
|
+
"@libp2p/websockets": "^5.0.3",
|
|
158
|
+
"aegir": "^38.1.0",
|
|
159
|
+
"datastore-core": "^8.0.4",
|
|
160
|
+
"libp2p": "^0.42.2"
|
|
161
|
+
},
|
|
162
|
+
"typedoc": {
|
|
163
|
+
"entryPoint": "./src/index.ts"
|
|
164
|
+
}
|
|
165
|
+
}
|
package/src/helia.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { Helia, InfoResponse } from '@helia/interface'
|
|
2
|
+
import type { Libp2p } from '@libp2p/interface-libp2p'
|
|
3
|
+
import type { Blockstore } from 'interface-blockstore'
|
|
4
|
+
import type { Datastore } from 'interface-datastore'
|
|
5
|
+
import { identity } from 'multiformats/hashes/identity'
|
|
6
|
+
import { sha256, sha512 } from 'multiformats/hashes/sha2'
|
|
7
|
+
import type { MultihashHasher } from 'multiformats/hashes/interface'
|
|
8
|
+
import type { HeliaInit } from '.'
|
|
9
|
+
import { Bitswap, createBitswap } from 'ipfs-bitswap'
|
|
10
|
+
import { BlockStorage } from './storage.js'
|
|
11
|
+
|
|
12
|
+
export class HeliaImpl implements Helia {
|
|
13
|
+
public libp2p: Libp2p
|
|
14
|
+
public blockstore: Blockstore
|
|
15
|
+
public datastore: Datastore
|
|
16
|
+
|
|
17
|
+
#bitswap: Bitswap
|
|
18
|
+
|
|
19
|
+
constructor (init: HeliaInit) {
|
|
20
|
+
const hashers: MultihashHasher[] = [
|
|
21
|
+
sha256,
|
|
22
|
+
sha512,
|
|
23
|
+
identity,
|
|
24
|
+
...(init.hashers ?? [])
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
this.#bitswap = createBitswap(init.libp2p, init.blockstore, {
|
|
28
|
+
hashLoader: {
|
|
29
|
+
getHasher: async (codecOrName: string | number) => {
|
|
30
|
+
const hasher = hashers.find(hasher => {
|
|
31
|
+
return hasher.code === codecOrName || hasher.name === codecOrName
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
if (hasher != null) {
|
|
35
|
+
return await Promise.resolve(hasher)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
throw new Error(`Could not load hasher for code/name "${codecOrName}"`)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
this.libp2p = init.libp2p
|
|
44
|
+
this.blockstore = new BlockStorage(init.blockstore, this.#bitswap)
|
|
45
|
+
this.datastore = init.datastore
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async start (): Promise<void> {
|
|
49
|
+
this.#bitswap.start()
|
|
50
|
+
await this.libp2p.start()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async stop (): Promise<void> {
|
|
54
|
+
this.#bitswap.stop()
|
|
55
|
+
await this.libp2p.stop()
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async info (): Promise<InfoResponse> {
|
|
59
|
+
return {
|
|
60
|
+
peerId: this.libp2p.peerId,
|
|
61
|
+
multiaddrs: this.libp2p.getMultiaddrs(),
|
|
62
|
+
agentVersion: this.libp2p.identifyService.host.agentVersion,
|
|
63
|
+
protocolVersion: this.libp2p.identifyService.host.protocolVersion,
|
|
64
|
+
protocols: this.libp2p.getProtocols(),
|
|
65
|
+
status: this.libp2p.isStarted() ? 'running' : 'stopped'
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
*
|
|
4
|
+
* Create a Helia node.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
*
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { createLibp2p } from 'libp2p'
|
|
10
|
+
* import { MemoryDatastore } from 'datastore-core'
|
|
11
|
+
* import { MemoryBlockstore } from 'blockstore-core'
|
|
12
|
+
* import { createHelia } from 'helia'
|
|
13
|
+
* import { unixfs } from '@helia/unixfs'
|
|
14
|
+
* import { CID } from 'multiformats/cid'
|
|
15
|
+
*
|
|
16
|
+
* const node = await createHelia({
|
|
17
|
+
* blockstore: new MemoryBlockstore(),
|
|
18
|
+
* datastore: new MemoryDatastore(),
|
|
19
|
+
* libp2p: await createLibp2p({
|
|
20
|
+
* //... libp2p options
|
|
21
|
+
* })
|
|
22
|
+
* })
|
|
23
|
+
* const fs = unixfs(node)
|
|
24
|
+
* fs.cat(CID.parse('bafyFoo'))
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import type { Helia } from '@helia/interface'
|
|
29
|
+
import type { Libp2p } from '@libp2p/interface-libp2p'
|
|
30
|
+
import type { Blockstore } from 'interface-blockstore'
|
|
31
|
+
import type { Datastore } from 'interface-datastore'
|
|
32
|
+
import type { MultihashHasher } from 'multiformats/hashes/interface'
|
|
33
|
+
import { HeliaImpl } from './helia.js'
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Options used to create a Helia node.
|
|
37
|
+
*/
|
|
38
|
+
export interface HeliaInit {
|
|
39
|
+
/**
|
|
40
|
+
* A libp2p node is required to perform network operations
|
|
41
|
+
*/
|
|
42
|
+
libp2p: Libp2p
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The blockstore is where blocks are stored
|
|
46
|
+
*/
|
|
47
|
+
blockstore: Blockstore
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The datastore is where data is stored
|
|
51
|
+
*/
|
|
52
|
+
datastore: Datastore
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* By default sha256, sha512 and identity hashes are supported for
|
|
56
|
+
* bitswap operations. To bitswap blocks with CIDs using other hashes
|
|
57
|
+
* pass appropriate MultihashHashers here.
|
|
58
|
+
*/
|
|
59
|
+
hashers?: MultihashHasher[]
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Pass `false` to not start the helia node
|
|
63
|
+
*/
|
|
64
|
+
start?: boolean
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Create and return a Helia node
|
|
69
|
+
*/
|
|
70
|
+
export async function createHelia (init: HeliaInit): Promise<Helia> {
|
|
71
|
+
const helia = new HeliaImpl(init)
|
|
72
|
+
|
|
73
|
+
if (init.start !== false) {
|
|
74
|
+
await helia.start()
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return helia
|
|
78
|
+
}
|
package/src/storage.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { BaseBlockstore } from 'blockstore-core'
|
|
2
|
+
import merge from 'it-merge'
|
|
3
|
+
import { pushable } from 'it-pushable'
|
|
4
|
+
import filter from 'it-filter'
|
|
5
|
+
import type { Blockstore, KeyQuery, Query } from 'interface-blockstore'
|
|
6
|
+
import type { Bitswap } from 'ipfs-bitswap'
|
|
7
|
+
import type { CID } from 'multiformats/cid'
|
|
8
|
+
import type { AbortOptions } from '@libp2p/interfaces'
|
|
9
|
+
import type { AwaitIterable } from 'interface-store'
|
|
10
|
+
|
|
11
|
+
export interface BlockStorageOptions extends AbortOptions {
|
|
12
|
+
progress?: (evt: Event) => void
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* BlockStorage is a hybrid blockstore that puts/gets blocks from a configured
|
|
17
|
+
* blockstore (that may be on disk, s3, or something else). If the blocks are
|
|
18
|
+
* not present Bitswap will be used to fetch them from network peers.
|
|
19
|
+
*/
|
|
20
|
+
export class BlockStorage extends BaseBlockstore implements Blockstore {
|
|
21
|
+
private readonly child: Blockstore
|
|
22
|
+
private readonly bitswap: Bitswap
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Create a new BlockStorage
|
|
26
|
+
*/
|
|
27
|
+
constructor (blockstore: Blockstore, bitswap: Bitswap) {
|
|
28
|
+
super()
|
|
29
|
+
|
|
30
|
+
this.child = blockstore
|
|
31
|
+
this.bitswap = bitswap
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async open (): Promise<void> {
|
|
35
|
+
await this.child.open()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async close (): Promise<void> {
|
|
39
|
+
await this.child.close()
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
unwrap (): Blockstore {
|
|
43
|
+
return this.child
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Put a block to the underlying datastore
|
|
48
|
+
*/
|
|
49
|
+
async put (cid: CID, block: Uint8Array, options: AbortOptions = {}): Promise<void> {
|
|
50
|
+
if (await this.has(cid)) {
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (this.bitswap.isStarted()) {
|
|
55
|
+
await this.bitswap.put(cid, block, options)
|
|
56
|
+
} else {
|
|
57
|
+
await this.child.put(cid, block, options)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Put a multiple blocks to the underlying datastore
|
|
63
|
+
*/
|
|
64
|
+
async * putMany (blocks: AwaitIterable<{ key: CID, value: Uint8Array }>, options: AbortOptions = {}): AsyncGenerator<{ key: CID, value: Uint8Array }, void, undefined> {
|
|
65
|
+
const missingBlocks = filter(blocks, async ({ key }) => { return !(await this.has(key)) })
|
|
66
|
+
|
|
67
|
+
if (this.bitswap.isStarted()) {
|
|
68
|
+
yield * this.bitswap.putMany(missingBlocks, options)
|
|
69
|
+
} else {
|
|
70
|
+
yield * this.child.putMany(missingBlocks, options)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Get a block by cid
|
|
76
|
+
*/
|
|
77
|
+
async get (cid: CID, options: BlockStorageOptions = {}): Promise<Uint8Array> {
|
|
78
|
+
if (!(await this.has(cid)) && this.bitswap.isStarted()) {
|
|
79
|
+
return await this.bitswap.get(cid, options)
|
|
80
|
+
} else {
|
|
81
|
+
return await this.child.get(cid, options)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Get multiple blocks back from an array of cids
|
|
87
|
+
*/
|
|
88
|
+
async * getMany (cids: AwaitIterable<CID>, options: BlockStorageOptions = {}): AsyncGenerator<Uint8Array, void, undefined> {
|
|
89
|
+
const getFromBitswap = pushable<CID>({ objectMode: true })
|
|
90
|
+
const getFromChild = pushable<CID>({ objectMode: true })
|
|
91
|
+
|
|
92
|
+
void Promise.resolve().then(async () => {
|
|
93
|
+
for await (const cid of cids) {
|
|
94
|
+
if (!(await this.has(cid)) && this.bitswap.isStarted()) {
|
|
95
|
+
getFromBitswap.push(cid)
|
|
96
|
+
} else {
|
|
97
|
+
getFromChild.push(cid)
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
getFromBitswap.end()
|
|
102
|
+
getFromChild.end()
|
|
103
|
+
}).catch(err => {
|
|
104
|
+
getFromBitswap.throw(err)
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
yield * merge(
|
|
108
|
+
this.bitswap.getMany(getFromBitswap, options),
|
|
109
|
+
this.child.getMany(getFromChild, options)
|
|
110
|
+
)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Delete a block from the blockstore
|
|
115
|
+
*/
|
|
116
|
+
async delete (cid: CID, options: AbortOptions = {}): Promise<void> {
|
|
117
|
+
await this.child.delete(cid, options)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Delete multiple blocks from the blockstore
|
|
122
|
+
*/
|
|
123
|
+
async * deleteMany (cids: AwaitIterable<CID>, options: AbortOptions = {}): AsyncGenerator<CID, void, undefined> {
|
|
124
|
+
yield * this.child.deleteMany(cids, options)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async has (cid: CID, options: AbortOptions = {}): Promise<boolean> {
|
|
128
|
+
return await this.child.has(cid, options)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async * query (q: Query, options: AbortOptions = {}): AsyncGenerator<{ key: CID, value: Uint8Array }, void, undefined> {
|
|
132
|
+
yield * this.child.query(q, options)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async * queryKeys (q: KeyQuery, options: AbortOptions = {}): AsyncGenerator<CID, void, undefined> {
|
|
136
|
+
yield * this.child.queryKeys(q, options)
|
|
137
|
+
}
|
|
138
|
+
}
|