@helia/utils 1.2.0 → 1.2.1-2c7185c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/package.json +5 -5
- package/dist/typedoc-urls.json +0 -12
package/dist/index.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaUtils = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaUtils=(()=>{var Is=Object.create;var gt=Object.defineProperty;var Ts=Object.getOwnPropertyDescriptor;var Ps=Object.getOwnPropertyNames;var Ls=Object.getPrototypeOf,Ns=Object.prototype.hasOwnProperty;var yt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),U=(r,e)=>{for(var t in e)gt(r,t,{get:e[t],enumerable:!0})},to=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ps(e))!Ns.call(r,o)&&o!==t&>(r,o,{get:()=>e[o],enumerable:!(n=Ts(e,o))||n.enumerable});return r};var Cr=(r,e,t)=>(t=r!=null?Is(Ls(r)):{},to(e||!r||!r.__esModule?gt(t,"default",{value:r,enumerable:!0}):t,r)),Ds=r=>to(gt({},"__esModule",{value:!0}),r);var ho=yt((Af,$r)=>{"use strict";var da=Object.prototype.hasOwnProperty,M="~";function Qe(){}Object.create&&(Qe.prototype=Object.create(null),new Qe().__proto__||(M=!1));function ha(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function lo(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new ha(t,n||r,o),s=M?M+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function kt(r,e){--r._eventsCount===0?r._events=new Qe:delete r._events[e]}function z(){this._events=new Qe,this._eventsCount=0}z.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)da.call(t,n)&&e.push(M?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};z.prototype.listeners=function(e){var t=M?M+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};z.prototype.listenerCount=function(e){var t=M?M+e:e,n=this._events[t];return n?n.fn?1:n.length:0};z.prototype.emit=function(e,t,n,o,i,s){var c=M?M+e:e;if(!this._events[c])return!1;var f=this._events[c],p=arguments.length,d,l;if(f.fn){switch(f.once&&this.removeListener(e,f.fn,void 0,!0),p){case 1:return f.fn.call(f.context),!0;case 2:return f.fn.call(f.context,t),!0;case 3:return f.fn.call(f.context,t,n),!0;case 4:return f.fn.call(f.context,t,n,o),!0;case 5:return f.fn.call(f.context,t,n,o,i),!0;case 6:return f.fn.call(f.context,t,n,o,i,s),!0}for(l=1,d=new Array(p-1);l<p;l++)d[l-1]=arguments[l];f.fn.apply(f.context,d)}else{var S=f.length,a;for(l=0;l<S;l++)switch(f[l].once&&this.removeListener(e,f[l].fn,void 0,!0),p){case 1:f[l].fn.call(f[l].context);break;case 2:f[l].fn.call(f[l].context,t);break;case 3:f[l].fn.call(f[l].context,t,n);break;case 4:f[l].fn.call(f[l].context,t,n,o);break;default:if(!d)for(a=1,d=new Array(p-1);a<p;a++)d[a-1]=arguments[a];f[l].fn.apply(f[l].context,d)}}return!0};z.prototype.on=function(e,t,n){return lo(this,e,t,n,!1)};z.prototype.once=function(e,t,n){return lo(this,e,t,n,!0)};z.prototype.removeListener=function(e,t,n,o){var i=M?M+e:e;if(!this._events[i])return this;if(!t)return kt(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&kt(this,i);else{for(var c=0,f=[],p=s.length;c<p;c++)(s[c].fn!==t||o&&!s[c].once||n&&s[c].context!==n)&&f.push(s[c]);f.length?this._events[i]=f.length===1?f[0]:f:kt(this,i)}return this};z.prototype.removeAllListeners=function(e){var t;return e?(t=M?M+e:e,this._events[t]&&kt(this,t)):(this._events=new Qe,this._eventsCount=0),this};z.prototype.off=z.prototype.removeListener;z.prototype.addListener=z.prototype.on;z.prefixed=M;z.EventEmitter=z;typeof $r<"u"&&($r.exports=z)});var Bo=yt((Dl,Uo)=>{Uo.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var vs=yt((ft,vr)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(a){if(!Array.isArray(a)&&!ArrayBuffer.isView(a))return!1;for(var h=0;h<a.length;h++)if(!Number.isInteger(a[h])||a[h]<0||a[h]>255)return!1;return!0}function o(a,h){return(a&65535)*h+(((a>>>16)*h&65535)<<16)}function i(a,h){return a<<h|a>>>32-h}function s(a){return a^=a>>>16,a=o(a,2246822507),a^=a>>>13,a=o(a,3266489909),a^=a>>>16,a}function c(a,h){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var g=[0,0,0,0];return g[3]+=a[3]+h[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=a[2]+h[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=a[1]+h[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=a[0]+h[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function f(a,h){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var g=[0,0,0,0];return g[3]+=a[3]*h[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=a[2]*h[3],g[1]+=g[2]>>>16,g[2]&=65535,g[2]+=a[3]*h[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=a[1]*h[3],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=a[2]*h[2],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=a[3]*h[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=a[0]*h[3]+a[1]*h[2]+a[2]*h[1]+a[3]*h[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function p(a,h){return h%=64,h===32?[a[1],a[0]]:h<32?[a[0]<<h|a[1]>>>32-h,a[1]<<h|a[0]>>>32-h]:(h-=32,[a[1]<<h|a[0]>>>32-h,a[0]<<h|a[1]>>>32-h])}function d(a,h){return h%=64,h===0?a:h<32?[a[0]<<h|a[1]>>>32-h,a[1]<<h]:[a[1]<<h-32,0]}function l(a,h){return[a[0]^h[0],a[1]^h[1]]}function S(a){return a=l(a,[0,a[0]>>>1]),a=f(a,[4283543511,3981806797]),a=l(a,[0,a[0]>>>1]),a=f(a,[3301882366,444984403]),a=l(a,[0,a[0]>>>1]),a}t.x86.hash32=function(a,h){if(t.inputValidation&&!n(a))return e;h=h||0;for(var g=a.length%4,k=a.length-g,y=h,w=0,b=3432918353,E=461845907,C=0;C<k;C=C+4)w=a[C]|a[C+1]<<8|a[C+2]<<16|a[C+3]<<24,w=o(w,b),w=i(w,15),w=o(w,E),y^=w,y=i(y,13),y=o(y,5)+3864292196;switch(w=0,g){case 3:w^=a[C+2]<<16;case 2:w^=a[C+1]<<8;case 1:w^=a[C],w=o(w,b),w=i(w,15),w=o(w,E),y^=w}return y^=a.length,y=s(y),y>>>0},t.x86.hash128=function(a,h){if(t.inputValidation&&!n(a))return e;h=h||0;for(var g=a.length%16,k=a.length-g,y=h,w=h,b=h,E=h,C=0,A=0,v=0,T=0,Q=597399067,ht=2869860233,pt=951274213,mt=2716044179,I=0;I<k;I=I+16)C=a[I]|a[I+1]<<8|a[I+2]<<16|a[I+3]<<24,A=a[I+4]|a[I+5]<<8|a[I+6]<<16|a[I+7]<<24,v=a[I+8]|a[I+9]<<8|a[I+10]<<16|a[I+11]<<24,T=a[I+12]|a[I+13]<<8|a[I+14]<<16|a[I+15]<<24,C=o(C,Q),C=i(C,15),C=o(C,ht),y^=C,y=i(y,19),y+=w,y=o(y,5)+1444728091,A=o(A,ht),A=i(A,16),A=o(A,pt),w^=A,w=i(w,17),w+=b,w=o(w,5)+197830471,v=o(v,pt),v=i(v,17),v=o(v,mt),b^=v,b=i(b,15),b+=E,b=o(b,5)+2530024501,T=o(T,mt),T=i(T,18),T=o(T,Q),E^=T,E=i(E,13),E+=y,E=o(E,5)+850148119;switch(C=0,A=0,v=0,T=0,g){case 15:T^=a[I+14]<<16;case 14:T^=a[I+13]<<8;case 13:T^=a[I+12],T=o(T,mt),T=i(T,18),T=o(T,Q),E^=T;case 12:v^=a[I+11]<<24;case 11:v^=a[I+10]<<16;case 10:v^=a[I+9]<<8;case 9:v^=a[I+8],v=o(v,pt),v=i(v,17),v=o(v,mt),b^=v;case 8:A^=a[I+7]<<24;case 7:A^=a[I+6]<<16;case 6:A^=a[I+5]<<8;case 5:A^=a[I+4],A=o(A,ht),A=i(A,16),A=o(A,pt),w^=A;case 4:C^=a[I+3]<<24;case 3:C^=a[I+2]<<16;case 2:C^=a[I+1]<<8;case 1:C^=a[I],C=o(C,Q),C=i(C,15),C=o(C,ht),y^=C}return y^=a.length,w^=a.length,b^=a.length,E^=a.length,y+=w,y+=b,y+=E,w+=y,b+=y,E+=y,y=s(y),w=s(w),b=s(b),E=s(E),y+=w,y+=b,y+=E,w+=y,b+=y,E+=y,("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)},t.x64.hash128=function(a,h){if(t.inputValidation&&!n(a))return e;h=h||0;for(var g=a.length%16,k=a.length-g,y=[0,h],w=[0,h],b=[0,0],E=[0,0],C=[2277735313,289559509],A=[1291169091,658871167],v=0;v<k;v=v+16)b=[a[v+4]|a[v+5]<<8|a[v+6]<<16|a[v+7]<<24,a[v]|a[v+1]<<8|a[v+2]<<16|a[v+3]<<24],E=[a[v+12]|a[v+13]<<8|a[v+14]<<16|a[v+15]<<24,a[v+8]|a[v+9]<<8|a[v+10]<<16|a[v+11]<<24],b=f(b,C),b=p(b,31),b=f(b,A),y=l(y,b),y=p(y,27),y=c(y,w),y=c(f(y,[0,5]),[0,1390208809]),E=f(E,A),E=p(E,33),E=f(E,C),w=l(w,E),w=p(w,31),w=c(w,y),w=c(f(w,[0,5]),[0,944331445]);switch(b=[0,0],E=[0,0],g){case 15:E=l(E,d([0,a[v+14]],48));case 14:E=l(E,d([0,a[v+13]],40));case 13:E=l(E,d([0,a[v+12]],32));case 12:E=l(E,d([0,a[v+11]],24));case 11:E=l(E,d([0,a[v+10]],16));case 10:E=l(E,d([0,a[v+9]],8));case 9:E=l(E,[0,a[v+8]]),E=f(E,A),E=p(E,33),E=f(E,C),w=l(w,E);case 8:b=l(b,d([0,a[v+7]],56));case 7:b=l(b,d([0,a[v+6]],48));case 6:b=l(b,d([0,a[v+5]],40));case 5:b=l(b,d([0,a[v+4]],32));case 4:b=l(b,d([0,a[v+3]],24));case 3:b=l(b,d([0,a[v+2]],16));case 2:b=l(b,d([0,a[v+1]],8));case 1:b=l(b,[0,a[v]]),b=f(b,C),b=p(b,31),b=f(b,A),y=l(y,b)}return y=l(y,[0,a.length]),w=l(w,[0,a.length]),y=c(y,w),w=c(w,y),y=S(y),w=S(w),y=c(y,w),w=c(w,y),("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)+("00000000"+(w[0]>>>0).toString(16)).slice(-8)+("00000000"+(w[1]>>>0).toString(16)).slice(-8)},typeof ft<"u"?(typeof vr<"u"&&vr.exports&&(ft=vr.exports=t),ft.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(ft)});var ks=yt((nm,_s)=>{_s.exports=vs()});var Qu={};U(Qu,{AbstractSession:()=>kr,Helia:()=>eo});var Sr=Symbol.for("@libp2p/content-routing");var Ar=Symbol.for("@libp2p/peer-routing");var ie=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var wt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var xt=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var bt=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var F=(r,...e)=>{try{[...e]}catch{}};var Ne=class extends EventTarget{#e=new Map;constructor(){super(),F(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function ro(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function he(...r){let e=[];for(let t of r)ro(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function pe(...r){let e=[];for(let t of r)ro(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Dr={};U(Dr,{base32:()=>ge,base32hex:()=>qs,base32hexpad:()=>Vs,base32hexpadupper:()=>Hs,base32hexupper:()=>js,base32pad:()=>Rs,base32padupper:()=>Os,base32upper:()=>Ms,base32z:()=>Ks});var of=new Uint8Array(0);function no(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function J(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function oo(r){return new TextEncoder().encode(r)}function io(r){return new TextDecoder().decode(r)}function Us(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var c=r.length,f=r.charAt(0),p=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var g=0,k=0,y=0,w=h.length;y!==w&&h[y]===0;)y++,g++;for(var b=(w-y)*d+1>>>0,E=new Uint8Array(b);y!==w;){for(var C=h[y],A=0,v=b-1;(C!==0||A<k)&&v!==-1;v--,A++)C+=256*E[v]>>>0,E[v]=C%c>>>0,C=C/c>>>0;if(C!==0)throw new Error("Non-zero carry");k=A,y++}for(var T=b-k;T!==b&&E[T]===0;)T++;for(var Q=f.repeat(g);T<b;++T)Q+=r.charAt(E[T]);return Q}function S(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var g=0;if(h[g]!==" "){for(var k=0,y=0;h[g]===f;)k++,g++;for(var w=(h.length-g)*p+1>>>0,b=new Uint8Array(w);h[g];){var E=t[h.charCodeAt(g)];if(E===255)return;for(var C=0,A=w-1;(E!==0||C<y)&&A!==-1;A--,C++)E+=c*b[A]>>>0,b[A]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");y=C,g++}if(h[g]!==" "){for(var v=w-y;v!==w&&b[v]===0;)v++;for(var T=new Uint8Array(k+(w-v)),Q=k;v!==w;)T[Q++]=b[v++];return T}}}function a(h){var g=S(h);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:S,decode:a}}var Bs=Us,Fs=Bs,so=Fs;var Tr=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Pr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ao(this,e)}},Lr=class{decoders;constructor(e){this.decoders=e}or(e){return ao(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ao(r,e){return new Lr({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Nr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Tr(e,t,n),this.decoder=new Pr(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function De({name:r,prefix:e,encode:t,decode:n}){return new Nr(r,e,t,n)}function me({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=so(t,r);return De({prefix:e,name:r,encode:n,decode:i=>J(o(i))})}function $s(r,e,t,n){let o={};for(let d=0;d<e.length;++d)o[e[d]]=d;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),c=0,f=0,p=0;for(let d=0;d<i;++d){let l=o[r[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);f=f<<t|l,c+=t,c>=8&&(c-=8,s[p++]=255&f>>c)}if(c>=t||255&f<<8-c)throw new SyntaxError("Unexpected end of data");return s}function zs(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,c=0;for(let f=0;f<r.length;++f)for(c=c<<8|r[f],s+=8;s>t;)s-=t,i+=e[o&c>>s];if(s!==0&&(i+=e[o&c<<t-s]),n)for(;i.length*t&7;)i+="=";return i}function D({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return De({prefix:e,name:r,encode(o){return zs(o,n,t)},decode(o){return $s(o,n,t,r)}})}var ge=D({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ms=D({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Rs=D({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Os=D({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qs=D({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),js=D({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Vs=D({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Hs=D({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ks=D({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ur={};U(Ur,{base58btc:()=>K,base58flickr:()=>Gs});var K=me({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gs=me({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Br={};U(Br,{base64:()=>ye,base64pad:()=>Ws,base64url:()=>Qs,base64urlpad:()=>Js});var ye=D({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ws=D({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Qs=D({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Js=D({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Xs(r,e){try{if(typeof r=="string"&&r.length>0)return Ys(r);if(typeof r=="number"&&isFinite(r))return e?.long?ea(r):Zs(r);throw new Error("Value is not a string or number.")}catch(t){let n=ta(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function Ys(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var vt=Xs;function Zs(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function ea(r){let e=Math.abs(r);return e>=864e5?Et(r,e,864e5,"day"):e>=36e5?Et(r,e,36e5,"hour"):e>=6e4?Et(r,e,6e4,"minute"):e>=1e3?Et(r,e,1e3,"second"):`${r} ms`}function Et(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function ta(r){return typeof r=="object"&&r!==null&&"message"in r}function Fr(r){t.debug=t,t.default=t,t.coerce=f,t.disable=i,t.enable=o,t.enabled=s,t.humanize=vt,t.destroy=p,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let l=0;for(let S=0;S<d.length;S++)l=(l<<5)-l+d.charCodeAt(S),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(d){let l,S=null,a,h;function g(...k){if(!g.enabled)return;let y=g,w=Number(new Date),b=w-(l||w);y.diff=b,y.prev=l,y.curr=w,l=w,k[0]=t.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let E=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(A,v)=>{if(A==="%%")return"%";E++;let T=t.formatters[v];if(typeof T=="function"){let Q=k[E];A=T.call(y,Q),k.splice(E,1),E--}return A}),t.formatArgs.call(y,k),(y.log||t.log).apply(y,k)}return g.namespace=d,g.useColors=t.useColors(),g.color=t.selectColor(d),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>S!==null?S:(a!==t.namespaces&&(a=t.namespaces,h=t.enabled(d)),h),set:k=>{S=k}}),typeof t.init=="function"&&t.init(g),g}function n(d,l){let S=t(this.namespace+(typeof l>"u"?":":l)+d);return S.log=this.log,S}function o(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let l,S=(typeof d=="string"?d:"").split(/[\s,]+/),a=S.length;for(l=0;l<a;l++)S[l]&&(d=S[l].replace(/\*/g,".*?"),d[0]==="-"?t.skips.push(new RegExp("^"+d.substr(1)+"$")):t.names.push(new RegExp("^"+d+"$")))}function i(){let d=[...t.names.map(c),...t.skips.map(c).map(l=>"-"+l)].join(",");return t.enable(""),d}function s(d){if(d[d.length-1]==="*")return!0;let l,S;for(l=0,S=t.skips.length;l<S;l++)if(t.skips[l].test(d))return!1;for(l=0,S=t.names.length;l<S;l++)if(t.names[l].test(d))return!0;return!1}function c(d){return d.toString().substring(2,d.toString().length-2).replace(/\.\*\?$/,"*")}function f(d){return d instanceof Error?d.stack??d.message:d}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var _t=ca(),ra=["#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 na(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function oa(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vt(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var ia=console.debug??console.log??(()=>{});function sa(r){try{r?_t?.setItem("debug",r):_t?.removeItem("debug")}catch{}}function aa(){let r;try{r=_t?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function ca(){try{return localStorage}catch{}}function ua(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var co=Fr({formatArgs:oa,save:sa,load:aa,useColors:na,setupFormatters:ua,colors:ra,storage:_t,log:ia});var R=co;R.formatters.b=r=>r==null?"undefined":K.baseEncode(r);R.formatters.t=r=>r==null?"undefined":ge.baseEncode(r);R.formatters.m=r=>r==null?"undefined":ye.baseEncode(r);R.formatters.p=r=>r==null?"undefined":r.toString();R.formatters.c=r=>r==null?"undefined":r.toString();R.formatters.k=r=>r==null?"undefined":r.toString();R.formatters.a=r=>r==null?"undefined":r.toString();R.formatters.e=r=>r==null?"undefined":uo(r.stack)??uo(r.message)??r.toString();function fa(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function fo(){return{forComponent(r){return la(r)}}}function la(r){let e=fa(`${r}:trace`);return R.enabled(`${r}:trace`)&&R.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=R(`${r}:trace`)),Object.assign(R(r),{error:R(`${r}:error`),trace:e})}function uo(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var L=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var zr=Cr(ho(),1);var Je=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Mr=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},po=r=>globalThis.DOMException===void 0?new Mr(r):new DOMException(r),mo=r=>{let e=r.reason===void 0?po("This operation was aborted."):r.reason;return e instanceof Error?e:po(e)};function Xe(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,c,p=new Promise((d,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:a}=e;a.aborted&&l(mo(a)),c=()=>{l(mo(a))},a.addEventListener("abort",c,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(d,l);return}let S=new Je;s=i.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(a){l(a)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?l(o):(S.message=o??`Promise timed out after ${t} milliseconds`,l(S))},t),(async()=>{try{d(await r)}catch(a){l(a)}})()}).finally(()=>{p.clear(),c&&e.signal&&e.signal.removeEventListener("abort",c)});return p.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},p}function Rr(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var Ye=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Rr(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var we=class extends zr.default{#e;#o;#s=0;#h;#a;#p=0;#r;#c;#t;#m;#n=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ye,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#o=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#x(){return this.#o||this.#s<this.#h}get#b(){return this.#n<this.#u}#E(){this.#n--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#c=void 0}get#_(){let e=Date.now();if(this.#r===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#n:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#t.size===0)return this.#r&&clearInterval(this.#r),this.#r=void 0,this.emit("empty"),this.#n===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#_;if(this.#x&&this.#b){let t=this.#t.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#o||this.#r!==void 0||(this.#r=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#s===0&&this.#n===0&&this.#r&&(clearInterval(this.#r),this.#r=void 0),this.#s=this.#e?this.#n:0,this.#l()}#l(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#l()}async#k(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#t.enqueue(async()=>{this.#n++,this.#s++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=Xe(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#k(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof Je&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#E()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#l(),this):this}pause(){this.#i=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#d("next",()=>this.#t.size<e)}async onIdle(){this.#n===0&&this.#t.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#i}};function Ct(r){let e=[X.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Or={};U(Or,{base10:()=>pa});var pa=me({prefix:"9",name:"base10",alphabet:"0123456789"});var qr={};U(qr,{base16:()=>ma,base16upper:()=>ga});var ma=D({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ga=D({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var jr={};U(jr,{base2:()=>ya});var ya=D({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vr={};U(Vr,{base256emoji:()=>va});var go=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}"),wa=go.reduce((r,e,t)=>(r[t]=e,r),[]),xa=go.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function ba(r){return r.reduce((e,t)=>(e+=wa[t],e),"")}function Ea(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=xa[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var va=De({prefix:"\u{1F680}",name:"base256emoji",encode:ba,decode:Ea});var Hr={};U(Hr,{base36:()=>se,base36upper:()=>_a});var se=me({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_a=me({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Kr={};U(Kr,{base8:()=>ka});var ka=D({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Gr={};U(Gr,{identity:()=>Ca});var Ca=De({prefix:"\0",name:"identity",encode:r=>io(r),decode:r=>oo(r)});var St={};U(St,{code:()=>Wr,decode:()=>Pa,encode:()=>Ta,name:()=>Ia});var Sa=new TextEncoder,Aa=new TextDecoder,Ia="json",Wr=512;function Ta(r){return Sa.encode(JSON.stringify(r))}function Pa(r){return JSON.parse(Aa.decode(r))}var At={};U(At,{code:()=>Qr,decode:()=>Da,encode:()=>Na,name:()=>La});var La="raw",Qr=85;function Na(r){return J(r)}function Da(r){return J(r)}var Xr={};U(Xr,{identity:()=>Tt});var Ua=xo,yo=128,Ba=127,Fa=~Ba,$a=Math.pow(2,31);function xo(r,e,t){e=e||[],t=t||0;for(var n=t;r>=$a;)e[t++]=r&255|yo,r/=128;for(;r&Fa;)e[t++]=r&255|yo,r>>>=7;return e[t]=r|0,xo.bytes=t-n+1,e}var za=Jr,Ma=128,wo=127;function Jr(r,n){var t=0,n=n||0,o=0,i=n,s,c=r.length;do{if(i>=c)throw Jr.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&wo)<<o:(s&wo)*Math.pow(2,o),o+=7}while(s>=Ma);return Jr.bytes=i-n,t}var Ra=Math.pow(2,7),Oa=Math.pow(2,14),qa=Math.pow(2,21),ja=Math.pow(2,28),Va=Math.pow(2,35),Ha=Math.pow(2,42),Ka=Math.pow(2,49),Ga=Math.pow(2,56),Wa=Math.pow(2,63),Qa=function(r){return r<Ra?1:r<Oa?2:r<qa?3:r<ja?4:r<Va?5:r<Ha?6:r<Ka?7:r<Ga?8:r<Wa?9:10},Ja={encode:Ua,decode:za,encodingLength:Qa},Xa=Ja,Ze=Xa;function et(r,e=0){return[Ze.decode(r,e),Ze.decode.bytes]}function Ue(r,e,t=0){return Ze.encode(r,e,t),e}function Be(r){return Ze.encodingLength(r)}function _e(r,e){let t=e.byteLength,n=Be(r),o=n+Be(t),i=new Uint8Array(o+t);return Ue(r,i,0),Ue(t,i,n),i.set(e,o),new Fe(r,t,e,i)}function bo(r){let e=J(r),[t,n]=et(e),[o,i]=et(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Fe(t,o,s,e)}function Eo(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&no(r.bytes,t.bytes)}}var Fe=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var vo=0,Ya="identity",_o=J;function Za(r){return _e(vo,_o(r))}var Tt={code:vo,name:Ya,encode:_o,digest:Za};var en={};U(en,{sha256:()=>Pt,sha512:()=>Lt});function Zr({name:r,code:e,encode:t}){return new Yr(r,e,t)}var Yr=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?_e(this.code,t):t.then(n=>_e(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Co(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Pt=Zr({name:"sha2-256",code:18,encode:Co("SHA-256")}),Lt=Zr({name:"sha2-512",code:19,encode:Co("SHA-512")});function So(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return tc(t,tn(r),e??K.encoder);default:return rc(t,tn(r),e??ge.encoder)}}var Ao=new WeakMap;function tn(r){let e=Ao.get(r);if(e==null){let t=new Map;return Ao.set(r,t),t}return e}var N=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==rt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==nc)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=_e(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Eo(e.multihash,n.multihash)}toString(e){return So(this,e)}toJSON(){return{"/":So(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??Io(n,o,i.bytes))}else if(t[oc]===!0){let{version:n,multihash:o,code:i}=t,s=bo(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==rt)throw new Error(`Version 0 CID must use dag-pb (code: ${rt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Io(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,rt,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=J(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Fe(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,S]=et(e.subarray(t));return t+=S,l},o=n(),i=rt;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,c=n(),f=n(),p=t+f,d=p-s;return{version:o,codec:i,multihashCode:c,digestSize:f,multihashSize:d,size:p}}static parse(e,t){let[n,o]=ec(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return tn(i).set(n,e),i}};function ec(r,e){switch(r[0]){case"Q":{let t=e??K;return[K.prefix,t.decode(`${K.prefix}${r}`)]}case K.prefix:{let t=e??K;return[K.prefix,t.decode(r)]}case ge.prefix:{let t=e??ge;return[ge.prefix,t.decode(r)]}case se.prefix:{let t=e??se;return[se.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function tc(r,e,t){let{prefix:n}=t;if(n!==K.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function rc(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var rt=112,nc=18;function Io(r,e,t){let n=Be(r),o=n+Be(e),i=new Uint8Array(o+t.byteLength);return Ue(r,i,0),Ue(e,i,n),i.set(t,o),i}var oc=Symbol.for("@ipld/js-cid/CID");var rn={...Gr,...jr,...Kr,...Or,...qr,...Dr,...Hr,...Ur,...Br,...Vr},pl={...en,...Xr};function To(r=0){return new Uint8Array(r)}function Po(r=0){return new Uint8Array(r)}function No(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Lo=No("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),nn=No("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Po(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ic={utf8:Lo,"utf-8":Lo,hex:rn.base16,latin1:nn,ascii:nn,binary:nn,...rn},Nt=ic;function $e(r,e="utf8"){let t=Nt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var on=60;function Dt(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:X[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:X[e.type],TTL:e.TTL??e.ttl??on,data:e.data instanceof Uint8Array?$e(e.data):e.data}))}}var sc=4;function sn(r,e={}){let t=new we({concurrency:e.queryConcurrency??sc});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),Ct(o.types).forEach(c=>{i.append("type",X[c])}),o.onProgress?.(new L("dns:query",{detail:n}));let s=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let f=Dt(await c.json());return o.onProgress?.(new L("dns:response",{detail:f})),f},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Do(){return[sn("https://cloudflare-dns.com/dns-query"),sn("https://dns.google/resolve")]}var Fo=Cr(Bo(),1);var an=class{lru;constructor(e){this.lru=(0,Fo.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return Dt({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:c})=>({...c,TTL:Math.round((s-Date.now())/1e3),type:X[c.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??on)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function $o(r){return new an(r)}var ac=1e3,Ut=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=$o(e.cacheSize??ac),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Do())}async query(e,t={}){let n=Ct(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new L("dns:cache",{detail:o})),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),c=[];for(let f of s){if(t.signal?.aborted===!0)break;try{let p=await f(e,{...t,types:n});for(let d of p.Answer)this.cache.add(e,d);return p}catch(p){c.push(p),t.onProgress?.(new L("dns:error",{detail:p}))}}throw c.length===1?c[0]:new AggregateError(c,`DNS lookup of ${e} ${n} failed`)}};var X;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(X||(X={}));function zo(r={}){return new Ut(r)}function cc(r){return r[Symbol.asyncIterator]!=null}function uc(r){if(cc(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Mo=uc;function ae(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Bt=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},ze=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Bt(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Bt(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var cn=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ft(r={}){return fc(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function fc(r,e){e=e??{};let t=e.onEnd,n=new ze,o,i,s,c=ae(),f=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((k,y)=>{i=w=>{i=null,n.push(w);try{k(r(n))}catch(b){y(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=ae()})}},p=k=>i!=null?i(k):(n.push(k),o),d=k=>(n=new ze,i!=null?i({error:k}):(n.push({error:k}),o)),l=k=>{if(s)return o;if(e?.objectMode!==!0&&k?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return p({done:!1,value:k})},S=k=>s?o:(s=!0,k!=null?d(k):p({done:!0})),a=()=>(n=new ze,S(),{done:!0}),h=k=>(S(k),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:f,return:a,throw:h,push:l,end:S,get readableLength(){return n.size},onEmpty:async k=>{let y=k?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let w,b;y!=null&&(w=new Promise((E,C)=>{b=()=>{C(new cn)},y.addEventListener("abort",b)}));try{await Promise.race([c.promise,w])}finally{b!=null&&y!=null&&y?.removeEventListener("abort",b)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(k){return g.throw(k),t!=null&&(t(k),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(k){return g.end(k),t!=null&&(t(k),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:k=>g.onEmpty(k)},o}var un=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function $t(r,e,t,n){let o=new un(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function c(){t?.removeEventListener("abort",d),r.removeEventListener(e,f),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,p)}let f=l=>{try{if(n?.filter?.(l)===!1)return}catch(S){c(),s(S);return}c(),i(l)},p=l=>{c(),s(l.detail)},d=()=>{c(),s(o)};t?.addEventListener("abort",d),r.addEventListener(e,f),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,p)})}var zt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Mt=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Ro(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Mt(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Mt(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Rt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ae(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ie)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function lc(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ot=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=lc(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,F(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new ie),this.cleanup())}async join(e={}){let t=new Rt(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ro(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var ce=class extends Ne{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new zt;let n=new Ot(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ie)}),this.clear()}async onEmpty(e){this.size!==0&&await $t(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await $t(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await $t(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ft({objectMode:!0}),n=f=>{f!=null?this.abort():this.clear(),t.end(f)},o=f=>{f.detail!=null&&t.push(f.detail)},i=f=>{n(f.detail)},s=()=>{n()},c=()=>{n(new ie("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",c);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",c),n()}}};var dc=["string","number","bigint","symbol"],hc=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Oo(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(dc.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(pc(r))return"Buffer";let t=mc(r);return t||"Object"}function pc(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function mc(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(hc.includes(e))return e}var u=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};u.uint=new u(0,"uint",!0);u.negint=new u(1,"negint",!0);u.bytes=new u(2,"bytes",!0);u.string=new u(3,"string",!0);u.array=new u(4,"array",!1);u.map=new u(5,"map",!1);u.tag=new u(6,"tag",!1);u.float=new u(7,"float",!0);u.false=new u(7,"false",!0);u.true=new u(7,"true",!0);u.null=new u(7,"null",!0);u.undefined=new u(7,"undefined",!0);u.break=new u(7,"break",!0);var m=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Me=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",gc=new TextDecoder,yc=new TextEncoder;function qt(r){return Me&&globalThis.Buffer.isBuffer(r)}function nt(r){return r instanceof Uint8Array?qt(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Ho=Me?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):jo(r,e,t):(r,e,t)=>t-e>64?gc.decode(r.subarray(e,t)):jo(r,e,t),jt=Me?r=>r.length>64?globalThis.Buffer.from(r):qo(r):r=>r.length>64?yc.encode(r):qo(r),ne=r=>Uint8Array.from(r),Re=Me?(r,e,t)=>qt(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Ko=Me?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),nt(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},Go=Me?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Wo(r,e){if(qt(r)&&qt(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function qo(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function jo(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let c,f,p,d;switch(s){case 1:o<128&&(i=o);break;case 2:c=r[e+1],(c&192)===128&&(d=(o&31)<<6|c&63,d>127&&(i=d));break;case 3:c=r[e+1],f=r[e+2],(c&192)===128&&(f&192)===128&&(d=(o&15)<<12|(c&63)<<6|f&63,d>2047&&(d<55296||d>57343)&&(i=d));break;case 4:c=r[e+1],f=r[e+2],p=r[e+3],(c&192)===128&&(f&192)===128&&(p&192)===128&&(d=(o&15)<<18|(c&63)<<12|(f&63)<<6|p&63,d>65535&&d<1114112&&(i=d))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return fn(n)}var Vo=4096;function fn(r){let e=r.length;if(e<=Vo)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Vo));return t}var wc=256,ot=class{constructor(e=wc){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Go(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Re(n,0,this.cursor)}else t=Ko(this.chunks,this.cursor);return e&&this.reset(),t}};var _="CBOR decode error:",ue="CBOR encode error:",it=[];it[23]=1;it[24]=2;it[25]=3;it[26]=5;it[27]=9;function fe(r,e,t){if(r.length-e<t)throw new Error(`${_} not enough data for type`)}var B=[24,256,65536,4294967296,BigInt("18446744073709551616")];function q(r,e,t){fe(r,e,1);let n=r[e];if(t.strict===!0&&n<B[0])throw new Error(`${_} integer encoded in more bytes than necessary (strict decode)`);return n}function j(r,e,t){fe(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<B[1])throw new Error(`${_} integer encoded in more bytes than necessary (strict decode)`);return n}function V(r,e,t){fe(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<B[2])throw new Error(`${_} integer encoded in more bytes than necessary (strict decode)`);return n}function H(r,e,t){fe(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<B[3])throw new Error(`${_} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${_} integers outside of the safe integer range are not supported`)}function Qo(r,e,t,n){return new m(u.uint,q(r,e+1,n),2)}function Jo(r,e,t,n){return new m(u.uint,j(r,e+1,n),3)}function Xo(r,e,t,n){return new m(u.uint,V(r,e+1,n),5)}function Yo(r,e,t,n){return new m(u.uint,H(r,e+1,n),9)}function G(r,e){return $(r,0,e.value)}function $(r,e,t){if(t<B[0]){let n=Number(t);r.push([e|n])}else if(t<B[1]){let n=Number(t);r.push([e|24,n])}else if(t<B[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<B[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<B[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${_} encountered BigInt larger than allowable range`)}}G.encodedSize=function(e){return $.encodedSize(e.value)};$.encodedSize=function(e){return e<B[0]?1:e<B[1]?2:e<B[2]?3:e<B[3]?5:9};G.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Zo(r,e,t,n){return new m(u.negint,-1-q(r,e+1,n),2)}function ei(r,e,t,n){return new m(u.negint,-1-j(r,e+1,n),3)}function ti(r,e,t,n){return new m(u.negint,-1-V(r,e+1,n),5)}var ln=BigInt(-1),ri=BigInt(1);function ni(r,e,t,n){let o=H(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new m(u.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${_} integers outside of the safe integer range are not supported`);return new m(u.negint,ln-BigInt(o),9)}function Vt(r,e){let t=e.value,n=typeof t=="bigint"?t*ln-ri:t*-1-1;$(r,e.type.majorEncoded,n)}Vt.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*ln-ri:t*-1-1;return n<B[0]?1:n<B[1]?2:n<B[2]?3:n<B[3]?5:9};Vt.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function st(r,e,t,n){fe(r,e,t+n);let o=Re(r,e+t,e+t+n);return new m(u.bytes,o,t+n)}function oi(r,e,t,n){return st(r,e,1,t)}function ii(r,e,t,n){return st(r,e,2,q(r,e+1,n))}function si(r,e,t,n){return st(r,e,3,j(r,e+1,n))}function ai(r,e,t,n){return st(r,e,5,V(r,e+1,n))}function ci(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${_} 64-bit integer bytes lengths not supported`);return st(r,e,9,o)}function Ht(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===u.string?jt(r.value):r.value),r.encodedBytes}function Oe(r,e){let t=Ht(e);$(r,e.type.majorEncoded,t.length),r.push(t)}Oe.encodedSize=function(e){let t=Ht(e);return $.encodedSize(t.length)+t.length};Oe.compareTokens=function(e,t){return bc(Ht(e),Ht(t))};function bc(r,e){return r.length<e.length?-1:r.length>e.length?1:Wo(r,e)}function at(r,e,t,n,o){let i=t+n;fe(r,e,i);let s=new m(u.string,Ho(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Re(r,e+t,e+i)),s}function ui(r,e,t,n){return at(r,e,1,t,n)}function fi(r,e,t,n){return at(r,e,2,q(r,e+1,n),n)}function li(r,e,t,n){return at(r,e,3,j(r,e+1,n),n)}function di(r,e,t,n){return at(r,e,5,V(r,e+1,n),n)}function hi(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${_} 64-bit integer string lengths not supported`);return at(r,e,9,o,n)}var pi=Oe;function qe(r,e,t,n){return new m(u.array,n,t)}function mi(r,e,t,n){return qe(r,e,1,t)}function gi(r,e,t,n){return qe(r,e,2,q(r,e+1,n))}function yi(r,e,t,n){return qe(r,e,3,j(r,e+1,n))}function wi(r,e,t,n){return qe(r,e,5,V(r,e+1,n))}function xi(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${_} 64-bit integer array lengths not supported`);return qe(r,e,9,o)}function bi(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${_} indefinite length items not allowed`);return qe(r,e,1,1/0)}function Kt(r,e){$(r,u.array.majorEncoded,e.value)}Kt.compareTokens=G.compareTokens;Kt.encodedSize=function(e){return $.encodedSize(e.value)};function je(r,e,t,n){return new m(u.map,n,t)}function Ei(r,e,t,n){return je(r,e,1,t)}function vi(r,e,t,n){return je(r,e,2,q(r,e+1,n))}function _i(r,e,t,n){return je(r,e,3,j(r,e+1,n))}function ki(r,e,t,n){return je(r,e,5,V(r,e+1,n))}function Ci(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${_} 64-bit integer map lengths not supported`);return je(r,e,9,o)}function Si(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${_} indefinite length items not allowed`);return je(r,e,1,1/0)}function Gt(r,e){$(r,u.map.majorEncoded,e.value)}Gt.compareTokens=G.compareTokens;Gt.encodedSize=function(e){return $.encodedSize(e.value)};function Ai(r,e,t,n){return new m(u.tag,t,1)}function Ii(r,e,t,n){return new m(u.tag,q(r,e+1,n),2)}function Ti(r,e,t,n){return new m(u.tag,j(r,e+1,n),3)}function Pi(r,e,t,n){return new m(u.tag,V(r,e+1,n),5)}function Li(r,e,t,n){return new m(u.tag,H(r,e+1,n),9)}function Wt(r,e){$(r,u.tag.majorEncoded,e.value)}Wt.compareTokens=G.compareTokens;Wt.encodedSize=function(e){return $.encodedSize(e.value)};var Sc=20,Ac=21,Ic=22,Tc=23;function Ni(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${_} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new m(u.null,null,1):new m(u.undefined,void 0,1)}function Di(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${_} indefinite length items not allowed`);return new m(u.break,void 0,1)}function dn(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${_} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${_} Infinity values are not supported`)}return new m(u.float,r,e)}function Ui(r,e,t,n){return dn(hn(r,e+1),3,n)}function Bi(r,e,t,n){return dn(pn(r,e+1),5,n)}function Fi(r,e,t,n){return dn(Ri(r,e+1),9,n)}function Qt(r,e,t){let n=e.value;if(n===!1)r.push([u.float.majorEncoded|Sc]);else if(n===!0)r.push([u.float.majorEncoded|Ac]);else if(n===null)r.push([u.float.majorEncoded|Ic]);else if(n===void 0)r.push([u.float.majorEncoded|Tc]);else{let o,i=!1;(!t||t.float64!==!0)&&(zi(n),o=hn(Y,1),n===o||Number.isNaN(n)?(Y[0]=249,r.push(Y.slice(0,3)),i=!0):(Mi(n),o=pn(Y,1),n===o&&(Y[0]=250,r.push(Y.slice(0,5)),i=!0))),i||(Pc(n),o=Ri(Y,1),Y[0]=251,r.push(Y.slice(0,9)))}}Qt.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){zi(n);let o=hn(Y,1);if(n===o||Number.isNaN(n))return 3;if(Mi(n),o=pn(Y,1),n===o)return 5}return 9};var $i=new ArrayBuffer(9),W=new DataView($i,1),Y=new Uint8Array($i,0);function zi(r){if(r===1/0)W.setUint16(0,31744,!1);else if(r===-1/0)W.setUint16(0,64512,!1);else if(Number.isNaN(r))W.setUint16(0,32256,!1);else{W.setFloat32(0,r);let e=W.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)W.setUint16(0,31744,!1);else if(t===0)W.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?W.setUint16(0,0):o<-14?W.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):W.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function hn(r,e){if(r.length-e<2)throw new Error(`${_} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function Mi(r){W.setFloat32(0,r,!1)}function pn(r,e){if(r.length-e<4)throw new Error(`${_} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Pc(r){W.setFloat64(0,r,!1)}function Ri(r,e){if(r.length-e<8)throw new Error(`${_} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Qt.compareTokens=G.compareTokens;function P(r,e,t){throw new Error(`${_} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Jt(r){return()=>{throw new Error(`${_} ${r}`)}}var x=[];for(let r=0;r<=23;r++)x[r]=P;x[24]=Qo;x[25]=Jo;x[26]=Xo;x[27]=Yo;x[28]=P;x[29]=P;x[30]=P;x[31]=P;for(let r=32;r<=55;r++)x[r]=P;x[56]=Zo;x[57]=ei;x[58]=ti;x[59]=ni;x[60]=P;x[61]=P;x[62]=P;x[63]=P;for(let r=64;r<=87;r++)x[r]=oi;x[88]=ii;x[89]=si;x[90]=ai;x[91]=ci;x[92]=P;x[93]=P;x[94]=P;x[95]=Jt("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)x[r]=ui;x[120]=fi;x[121]=li;x[122]=di;x[123]=hi;x[124]=P;x[125]=P;x[126]=P;x[127]=Jt("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)x[r]=mi;x[152]=gi;x[153]=yi;x[154]=wi;x[155]=xi;x[156]=P;x[157]=P;x[158]=P;x[159]=bi;for(let r=160;r<=183;r++)x[r]=Ei;x[184]=vi;x[185]=_i;x[186]=ki;x[187]=Ci;x[188]=P;x[189]=P;x[190]=P;x[191]=Si;for(let r=192;r<=215;r++)x[r]=Ai;x[216]=Ii;x[217]=Ti;x[218]=Pi;x[219]=Li;x[220]=P;x[221]=P;x[222]=P;x[223]=P;for(let r=224;r<=243;r++)x[r]=Jt("simple values are not supported");x[244]=P;x[245]=P;x[246]=P;x[247]=Ni;x[248]=Jt("simple values are not supported");x[249]=Ui;x[250]=Bi;x[251]=Fi;x[252]=P;x[253]=P;x[254]=P;x[255]=Di;var Z=[];for(let r=0;r<24;r++)Z[r]=new m(u.uint,r,1);for(let r=-1;r>=-24;r--)Z[31-r]=new m(u.negint,r,1);Z[64]=new m(u.bytes,new Uint8Array(0),1);Z[96]=new m(u.string,"",1);Z[128]=new m(u.array,0,1);Z[160]=new m(u.map,0,1);Z[244]=new m(u.false,!1,1);Z[245]=new m(u.true,!0,1);Z[246]=new m(u.null,null,1);function Oi(r){switch(r.type){case u.false:return ne([244]);case u.true:return ne([245]);case u.null:return ne([246]);case u.bytes:return r.value.length?void 0:ne([64]);case u.string:return r.value===""?ne([96]):void 0;case u.array:return r.value===0?ne([128]):void 0;case u.map:return r.value===0?ne([160]):void 0;case u.uint:return r.value<24?ne([Number(r.value)]):void 0;case u.negint:if(r.value>=-24)return ne([31-Number(r.value)])}}var Nc={float64:!1,mapSorter:Bc,quickEncodeToken:Oi};function Dc(){let r=[];return r[u.uint.major]=G,r[u.negint.major]=Vt,r[u.bytes.major]=Oe,r[u.string.major]=pi,r[u.array.major]=Kt,r[u.map.major]=Gt,r[u.tag.major]=Wt,r[u.float.major]=Qt,r}var qi=Dc(),mn=new ot,Yt=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${ue} object contains circular references`);return new r(t,e)}},xe={null:new m(u.null,null),undefined:new m(u.undefined,void 0),true:new m(u.true,!0),false:new m(u.false,!1),emptyArray:new m(u.array,0),emptyMap:new m(u.map,0)},be={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new m(u.float,r):r>=0?new m(u.uint,r):new m(u.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new m(u.uint,r):new m(u.negint,r)},Uint8Array(r,e,t,n){return new m(u.bytes,r)},string(r,e,t,n){return new m(u.string,r)},boolean(r,e,t,n){return r?xe.true:xe.false},null(r,e,t,n){return xe.null},undefined(r,e,t,n){return xe.undefined},ArrayBuffer(r,e,t,n){return new m(u.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new m(u.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[xe.emptyArray,new m(u.break)]:xe.emptyArray;n=Yt.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Xt(s,t,n);return t.addBreakTokens?[new m(u.array,r.length),o,new m(u.break)]:[new m(u.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[xe.emptyMap,new m(u.break)]:xe.emptyMap;n=Yt.createCheck(n,r);let c=[],f=0;for(let p of i)c[f++]=[Xt(p,t,n),Xt(o?r.get(p):r[p],t,n)];return Uc(c,t),t.addBreakTokens?[new m(u.map,s),c,new m(u.break)]:[new m(u.map,s),c]}};be.Map=be.Object;be.Buffer=be.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))be[`${r}Array`]=be.DataView;function Xt(r,e={},t){let n=Oo(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||be[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=be[n];if(!i)throw new Error(`${ue} unsupported type: ${n}`);return i(r,n,e,t)}function Uc(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Bc(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=qi[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function ji(r,e,t,n){if(Array.isArray(e))for(let o of e)ji(r,o,t,n);else t[e.type.major](r,e,n)}function gn(r,e,t){let n=Xt(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),c=new ot(s);if(i(c,n,t),c.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return nt(c.chunks[0])}}return mn.reset(),ji(mn,n,e,t),mn.toBytes(!0)}function Ce(r,e){return e=Object.assign({},Nc,e),gn(r,qi,e)}var Fc={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Zt=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Z[e];if(t===void 0){let n=x[e];if(!n)throw new Error(`${_} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},ct=Symbol.for("DONE"),er=Symbol.for("BREAK");function $c(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Ve(e,t);if(i===er){if(r.value===1/0)break;throw new Error(`${_} got unexpected break to lengthed array`)}if(i===ct)throw new Error(`${_} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function zc(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let c=Ve(e,t);if(c===er){if(r.value===1/0)break;throw new Error(`${_} got unexpected break to lengthed map`)}if(c===ct)throw new Error(`${_} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof c!="string")throw new Error(`${_} non-string keys not supported (got ${typeof c})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(c)||!n&&c in o))throw new Error(`${_} found repeat map key "${c}"`);let f=Ve(e,t);if(f===ct)throw new Error(`${_} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(c,f):o[c]=f}return n?i:o}function Ve(r,e){if(r.done())return ct;let t=r.next();if(t.type===u.break)return er;if(t.type.terminal)return t.value;if(t.type===u.array)return $c(t,r,e);if(t.type===u.map)return zc(t,r,e);if(t.type===u.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Ve(r,e);return e.tags[t.value](n)}throw new Error(`${_} tag not supported (${t.value})`)}throw new Error("unsupported")}function yn(r,e){if(!(r instanceof Uint8Array))throw new Error(`${_} data to decode must be a Uint8Array`);e=Object.assign({},Fc,e);let t=e.tokenizer||new Zt(r,e),n=Ve(t,e);if(n===ct)throw new Error(`${_} did not find any content to decode`);if(n===er)throw new Error(`${_} got unexpected break`);return[n,r.subarray(t.pos())]}function ee(r,e){let[t,n]=yn(r,e);if(n.length>0)throw new Error(`${_} too many terminals, data makes no sense`);return t}function O(r,e="utf8"){let t=Nt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var le="/",Hi=new TextEncoder().encode(le),tr=Hi[0],de=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=O(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==tr)throw new Error("Invalid key")}toString(e="utf8"){return $e(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(le))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Hi),this._buf[0]!==tr){let e=new Uint8Array(this._buf.byteLength+1);e.fill(tr,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===tr;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(le).slice(1)}type(){return Mc(this.baseNamespace())}name(){return Rc(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(le)||(e+=le),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(le):new r(e.slice(0,-1).join(le))}child(e){return this.toString()===le?e:e.toString()===le?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Oc(e.map(t=>t.namespaces()))])}};function Mc(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Rc(r){let e=r.split(":");return e[e.length-1]}function Oc(r){return[].concat(...r)}function rr({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*qc(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=N.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*wn(n,o))}else{let t=N.asCID(e);t!=null?yield[r.join("/"),t]:yield*wn(e,r)}}function*wn(r,e){if(r==null||r instanceof Uint8Array)return;let t=N.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*qc(i,o)}}function*jc(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&N.asCID(n)==null&&(yield*xn(n,o))}else yield*xn(e,r)}function*xn(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&N.asCID(n)==null&&(yield*jc(o,n))}}function Vc(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=N.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var bn=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:rr(),bytes:rr(),value:rr(),asBlock:rr()})}links(){return wn(this.value,[])}tree(){return xn(this.value,[])}get(e="/"){return Vc(this.value,e.split("/").filter(Boolean))}};function Ki({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new bn({cid:e,bytes:r,value:o})}function Se(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Qi="/pin/",Gi="/pinned-block/",En=se,Wi=1;function nr(r){return r.version===0&&(r=r.toV1()),new de(`${Qi}${r.toString(En)}`)}var or=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=nr(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new ce({concurrency:Wi});for await(let c of this.#e(e,i,{...t,depth:o}))await this.#o(c,f=>f.pinnedBy.find(p=>Se(p,e.bytes))!=null?!1:(f.pinCount++,f.pinnedBy.push(e.bytes),!0),t),yield c;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ce(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await this.blockstore.get(e,n),s=Ki({bytes:i,cid:e,codec:o});yield e;for await(let[,c]of s.links())yield*await t.add(async()=>this.#e(c,t,{...n,depth:n.depth-1}))}async#o(e,t,n){let o=new de(`${Gi}${En.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=ee(await this.datastore.get(o,n))}catch(c){if(c.name!=="NotFoundError")throw c}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ce(i),n),n.onProgress?.(new L("helia:pin:add",e))}}async*rm(e,t={}){let n=nr(e),o=await this.datastore.get(n,t),i=ee(o);await this.datastore.delete(n,t);let s=new ce({concurrency:Wi});for await(let c of this.#e(e,s,{...t,depth:i.depth}))await this.#o(c,f=>(f.pinCount--,f.pinnedBy=f.pinnedBy.filter(p=>Se(p,e.bytes)),!0),{...t,depth:i.depth}),yield c}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Qi+(e.cid!=null?`${e.cid.toString(se)}`:"")},e)){let o=N.parse(t.toString().substring(5),se),i=ee(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new de(`${Gi}${En.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=nr(e),o=await this.datastore.get(n,t);return ee(o)}async setMetadata(e,t,n){let o=nr(e),i=await this.datastore.get(o,n),s=ee(i);s.metadata=t??{},await this.datastore.put(o,Ce(s),n)}};var ir=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Ae=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},sr=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},ar=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var cr=class extends ce{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function Hc(r){return r[Symbol.asyncIterator]!=null}function Kc(...r){let e=[];for(let t of r)Hc(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ft({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var ur=Kc;var Gc=5,fr=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Gc,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await he(...this.routers)}async stop(){await pe(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Ae("No content routers available");let n=new cr({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of ur(n.toGenerator(),...Ie(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new Ae("No content routers available");await Promise.all(Ie(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Ie(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Ie(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(Ie(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new Ae("No peer routers available");let n=this,o=ur(...Ie(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new xt("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ae("No peer routers available");for await(let n of ur(...Ie(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Ie(r,e){return r.filter(t=>t[e]!=null)}var Ee={},He=r=>{r.addEventListener("message",e=>{He.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{He.dispatchEvent("message",r,e)})};He.addEventListener=(r,e)=>{Ee[r]==null&&(Ee[r]=[]),Ee[r].push(e)};He.removeEventListener=(r,e)=>{Ee[r]!=null&&(Ee[r]=Ee[r].filter(t=>t===e))};He.dispatchEvent=function(r,e,t){Ee[r]!=null&&Ee[r].forEach(n=>n(e,t))};var vn=He;var _n="lock:worker:request-read",kn="lock:worker:release-read",Cn="lock:master:grant-read",Sn="lock:worker:request-write",An="lock:worker:release-write",In="lock:master:grant-write";var Ji=(r=21)=>Math.random().toString().substring(2);var Xi=(r,e,t,n,o)=>(i,s)=>{if(s.data.type!==t)return;let c={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:c.name,handler:async()=>{i.postMessage({type:o,name:c.name,identifier:c.identifier}),await new Promise(f=>{let p=d=>{if(d?.data==null)return;let l={type:d.data.type,name:d.data.name,identifier:d.data.identifier};l.type===n&&l.identifier===c.identifier&&(i.removeEventListener("message",p),f())};i.addEventListener("message",p)})}}}))},Yi=(r,e,t,n)=>async()=>{let o=Ji();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(i=>{let s=c=>{if(c?.data==null)return;let f={type:c.data.type,identifier:c.data.identifier};f.type===t&&f.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},Wc={singleProcess:!1},Zi=r=>{if(r=Object.assign({},Wc,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return vn.addEventListener("message",Xi(t,"requestReadLock",_n,kn,Cn)),vn.addEventListener("message",Xi(t,"requestWriteLock",Sn,An,In)),t}return{isWorker:!0,readLock:t=>Yi(t,_n,Cn,kn),writeLock:t=>Yi(t,Sn,In,An)}};var Te={},ve;async function Tn(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Xe((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Qc=(r,e)=>{if(ve.isWorker===!0)return{readLock:ve.readLock(r,e),writeLock:ve.writeLock(r,e)};let t=new we({concurrency:1}),n;return{async readLock(){if(n!=null)return Tn(n,e);n=new we({concurrency:e.concurrency,autoStart:!1});let o=n,i=Tn(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,Tn(t,e)}}},Jc={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Pn(r){let e=Object.assign({},Jc,r);return ve==null&&(ve=Zi(e),ve.isWorker!==!0&&(ve.addEventListener("requestReadLock",t=>{Te[t.data.name]!=null&&Te[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),ve.addEventListener("requestWriteLock",async t=>{Te[t.data.name]!=null&&Te[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Te[e.name]==null&&(Te[e.name]=Qc(e.name,e)),Te[e.name]}var lr=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Pn({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await he(this.child),this.started=!0}async stop(){await pe(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Ln=new de("/version"),es=1;async function ts(r){if(!await r.has(Ln)){await r.put(Ln,O(`${es}`));return}let e=await r.get(Ln),t=$e(e);if(parseInt(t,10)!==es)throw new Error("Unknown datastore version, a datastore migration may be required")}var Un={};U(Un,{code:()=>Dn,decode:()=>iu,decodeOptions:()=>ru,encode:()=>ou,encodeOptions:()=>eu,name:()=>nu,toByteView:()=>ns});var rs=42;function ns(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Xc(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=N.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new m(u.tag,rs),new m(u.bytes,t)]}function Yc(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Zc(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var Nn={float64:!0,typeEncoders:{Object:Xc,undefined:Yc,number:Zc}},eu={...Nn,typeEncoders:{...Nn.typeEncoders}};function tu(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return N.decode(r.subarray(1))}var dr={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};dr.tags[rs]=tu;var ru={...dr,tags:dr.tags.slice()},nu="dag-cbor",Dn=113,ou=r=>Ce(r,Nn),iu=r=>ee(ns(r),dr);var On={};U(On,{code:()=>Rn,decode:()=>is,encode:()=>os,format:()=>gu,name:()=>mu,parse:()=>wu,stringify:()=>gu});var Bn=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===u.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===u.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[u.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[u.negint.major](e,t){this[u.uint.major](e,t)}[u.bytes.major](e,t){throw new Error(`${ue} unsupported type: Uint8Array`)}[u.string.major](e,t){this.prefix(e);let n=jt(JSON.stringify(t.value));e.push(n.length>32?nt(n):n)}[u.array.major](e,t){this.prefix(e),this.inRecursive.push({type:u.array,elements:0}),e.push([91])}[u.map.major](e,t){this.prefix(e),this.inRecursive.push({type:u.map,elements:0}),e.push([123])}[u.tag.major](e,t){}[u.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===u.array)e.push([93]);else if(s.type===u.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${ue} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function su(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${ue} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==u.string||n.type!==u.string)throw new Error(`${ue} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${ue} unexpected duplicate map keys, this is not supported`)}var au={addBreakTokens:!0,mapSorter:su};function Fn(r,e){return e=Object.assign({},au,e),gn(r,new Bn,e)}var Ke=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${_} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${_} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=c=>{for(;!this.done();){let f=this.ch();if(c.includes(f))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new m(u.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${_} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${_} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new m(u.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new m(s>=0?u.uint:u.negint,s,this._pos-e):new m(s>=0?u.uint:u.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${_} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let c=this.data[i];if(c===92||c<32||c>=128)break;if(c===34){let f=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new m(u.string,f,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${_} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let c=this.ch();if(c>=48&&c<=57)c-=48;else if(c>=97&&c<=102)c=c-97+10;else if(c>=65&&c<=70)c=c-65+10;else throw new Error(`${_} unexpected unicode escape character at position ${this._pos}`);i=i*16+c,this._pos++}return i},o=()=>{let i=this.ch(),s=null,c=i>239?4:i>223?3:i>191?2:1;if(this._pos+c>this.data.length)throw new Error(`${_} unexpected unicode sequence at position ${this._pos}`);let f,p,d,l;switch(c){case 1:i<128&&(s=i);break;case 2:f=this.data[this._pos+1],(f&192)===128&&(l=(i&31)<<6|f&63,l>127&&(s=l));break;case 3:f=this.data[this._pos+1],p=this.data[this._pos+2],(f&192)===128&&(p&192)===128&&(l=(i&15)<<12|(f&63)<<6|p&63,l>2047&&(l<55296||l>57343)&&(s=l));break;case 4:f=this.data[this._pos+1],p=this.data[this._pos+2],d=this.data[this._pos+3],(f&192)===128&&(p&192)===128&&(d&192)===128&&(l=(i&15)<<18|(f&63)<<12|(p&63)<<6|d&63,l>65535&&l<1114112&&(s=l))}s===null?(s=65533,c=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=c};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${_} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${_} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new m(u.string,fn(t),this._pos-e);default:if(i<32)throw new Error(`${_} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${_} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new m(u.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new m(u.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new m(u.null,null,4);case 102:return this.expect([102,97,108,115,101]),new m(u.false,!1,5);case 116:return this.expect([116,114,117,101]),new m(u.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${_} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new m(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${_} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new m(u.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new m(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${_} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new m(u.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${_} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${_} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function $n(r,e){return e=Object.assign({tokenizer:new Ke(r,e)},e),ee(r,e)}function uu(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function fu(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=N.asCID(r);if(!e)return null;let t=e.toString();return[new m(u.map,1/0,1),new m(u.string,"/",1),new m(u.string,t,t.length),new m(u.break,void 0,1)]}function hr(r){let e=ye.encode(r).slice(1);return[new m(u.map,1/0,1),new m(u.string,"/",1),new m(u.map,1/0,1),new m(u.string,"bytes",5),new m(u.string,e,e.length),new m(u.break,void 0,1),new m(u.break,void 0,1)]}function te(r){return hr(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function lu(r){return hr(new Uint8Array(r))}function du(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function hu(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var pu={typeEncoders:{Object:fu,Buffer:hr,Uint8Array:hr,Int8Array:te,Uint16Array:te,Int16Array:te,Uint32Array:te,Int32Array:te,Float32Array:te,Float64Array:te,Uint8ClampedArray:te,BigInt64Array:te,BigUint64Array:te,DataView:te,ArrayBuffer:lu,undefined:du,number:hu}},zn=class extends Ke{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===u.map){let t=this._next();if(t.type===u.string&&t.value==="/"){let n=this._next();if(n.type===u.string){if(this._next().type!==u.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new m(u.tag,42,0)}if(n.type===u.map){let o=this._next();if(o.type===u.string&&o.value==="bytes"){let i=this._next();if(i.type===u.string){for(let c=0;c<2;c++)if(this._next().type!==u.break)throw new Error("Invalid encoded Bytes form");let s=ye.decode(`m${i.value}`);return new m(u.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Mn={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Mn.tags[42]=N.parse;var mu="dag-json",Rn=297,os=r=>Fn(r,pu),is=r=>{let e=uu(r),t=Object.assign(Mn,{tokenizer:new zn(e,Mn)});return $n(e,t)},gu=r=>yu.decode(os(r));var yu=new TextDecoder,wu=r=>is(xu.encode(r)),xu=new TextEncoder;var Gn={};U(Gn,{code:()=>Kn,createLink:()=>ms,createNode:()=>ps,decode:()=>Nu,encode:()=>Lu,name:()=>Pu,prepare:()=>Vn,validate:()=>Hn});var bu=new TextDecoder;function qn(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function pr(r,e){let t;[t,e]=qn(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function ss(r,e){let t;return[t,e]=qn(r,e),[t&7,t>>3,e]}function Eu(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=ss(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=pr(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=pr(r,n),e.Name=bu.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=qn(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function as(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let c,f;if([c,f,t]=ss(r,t),c!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${c}`);if(f===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=pr(r,t),n&&(o=!0)}else if(f===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let p;[p,t]=pr(r,t),n.push(Eu(p))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${f}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var us=new TextEncoder,cs=2**32,vu=2**31;function _u(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=ut(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=us.encode(r.Name);t-=n.length,e.set(n,t),t=ut(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=ut(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function fs(r){let e=Cu(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=ut(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=_u(r.Links[o],t.subarray(0,n));n-=i,n=ut(t,n,i)-1,t[n]=18}return t}function ku(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ge(t)}if(typeof r.Name=="string"){let t=us.encode(r.Name).length;e+=1+t+Ge(t)}return typeof r.Tsize=="number"&&(e+=1+Ge(r.Tsize)),e}function Cu(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ge(t)}if(r.Links)for(let t of r.Links){let n=ku(t);e+=1+n+Ge(n)}return e}function ut(r,e,t){e-=Ge(t);let n=e;for(;t>=vu;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ge(r){return r%2===0&&r++,Math.floor((Su(r)+6)/7)}function Su(r){let e=0;return r>=cs&&(r=Math.floor(r/cs),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+Au[r]}var Au=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var Iu=["Data","Links"],Tu=["Hash","Name","Tsize"],jn=new TextEncoder;function ds(r,e){if(r===e)return 0;let t=r.Name?jn.encode(r.Name):[],n=e.Name?jn.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,c=Math.min(o,i);s<c;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function ls(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function hs(r){if(typeof r.asCID=="object"){let t=N.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=N.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=N.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=N.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Vn(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=jn.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(hs),e.Links.sort(ds);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Hn(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!ls(r,Iu))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!ls(t,Tu))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&ds(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function ps(r,e=[]){return Vn({Data:r,Links:e})}function ms(r,e,t){return hs({Hash:t,Name:r,Tsize:e})}function gs(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var Pu="dag-pb",Kn=112;function Lu(r){Hn(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),fs(e)}function Nu(r){let e=gs(r),t=as(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=N.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function We(r){return r?.then!=null}function ys(r=[],e){let t={[Kn]:Gn,[Qr]:At,[Dn]:Un,[Rn]:On,[Wr]:St};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);We(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new ar(`Could not load codec for ${n}`)}}function ws(r=[],e){let t={[Pt.code]:Pt,[Lt.code]:Lt,[Tt.code]:Tt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);We(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new sr(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}function oe(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var mr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var gr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var yr=0,wr=class extends gr{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===yr||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===yr)return e.multihash.digest;if(this.child==null)throw new mr;return this.child.get(e)}has(e){return e.multihash.code===yr?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==yr&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function Du(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var xr=Du;function Uu(r){return r[Symbol.asyncIterator]!=null}function Bu(r,e){let t=0;if(Uu(r))return async function*(){for await(let f of r)await e(f,t++)&&(yield f)}();let n=xr(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let f of n)await e(f,t++)&&(yield f)}();let c=e;return function*(){s===!0&&(yield o);for(let f of n)c(f,t++)&&(yield f)}()}var xs=Bu;function Fu(r){return r[Symbol.asyncIterator]!=null}function bs(r){return r?.then!=null}function $u(r,e){let t=0;if(Fu(r))return async function*(){for await(let f of r){let p=e(f,t++);bs(p)&&await p,yield f}}();let n=xr(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let f of n){let p=e(f,t++);bs(p)&&await p,yield f}}();let c=e;return function*(){yield o;for(let f of n)c(f,t++),yield f}()}var Wn=$u;var br=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new wr(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new L("blocks:put:duplicate",e)),e):(n.onProgress?.(new L("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new L("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=xs(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new L("blocks:put-many:duplicate",i)),!s}),o=Wn(n,async({cid:i,block:s})=>{t.onProgress?.(new L("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async c=>c.announce?.(i,s,t)))});t.onProgress?.(new L("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new L("blocks:get:providers:get",e));let o=await Es(e,this.components.blockBrokers,n,{...t,log:this.log});return t.onProgress?.(new L("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new L("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,o,t))),o}return t.onProgress?.(new L("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new L("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Wn(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new L("blocks:get-many:providers:get",n));let i=await Es(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new L("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t),t.onProgress?.(new L("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,i,t)))}}))}async delete(e,t={}){t.onProgress?.(new L("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new L("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new L("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},Er=class extends br{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await he(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await pe(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Qn({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},Qn=class extends br{closeController;constructor(e,t){super(e),this.closeController=new AbortController,F(1/0,this.closeController.signal),this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=oe([this.closeController.signal,n.signal]);F(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=oe([this.closeController.signal,t.signal]);F(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=oe([this.closeController.signal,t.signal]);F(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=oe([this.closeController.signal,t.signal]);F(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=oe([this.closeController.signal,t.signal]);F(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=oe([this.closeController.signal,t.signal]);F(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=oe([this.closeController.signal,t.signal]);F(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=oe([this.closeController.signal,e.signal]);F(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function zu(r){return typeof r.retrieve=="function"}var Mu=(r,e)=>{if(e==null)throw new wt(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t);if(We(o)?n=await o:n=o,!Se(n.digest,r.multihash.digest))throw new bt("Hash of downloaded block did not match multihash from passed CID")}};async function Es(r,e,t,n){let o=Mu(r,t),i=new AbortController,s=oe([i.signal,n.signal]);F(1/0,i.signal,s);let c=[];for(let f of e)zu(f)&&c.push(f);try{return await Promise.any(c.map(async f=>{try{let p=!1,d=await f.retrieve(r,{...n,signal:s,validateFn:async l=>{await o(l),p=!0}});return p||await o(d),d}catch(p){throw n.log.error("could not retrieve verified block for %c",r,p),p}}))}finally{i.abort(),s.clear()}}var Jn=64,re=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Jn)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=To(o);for(let c=0;c<s.length;c++)s[c]=i[c];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Se(this.fp,e.fp):!1}};function Pe(r,e){return Math.floor(Math.random()*(e-r))+r}var Le=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof re))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof re))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof re))throw new TypeError("Invalid Fingerprint");let t=Pe(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof re))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Xn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Cs={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ss=new globalThis.TextEncoder;function Ru(r,e){let t=Xn[e],n=Cs[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Ou(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Xn[e],o=Cs[e],i=r;for(;i.length>0;){let s=Ss.encodeInto(i,t);i=i.slice(s.read);for(let c=0;c<s.written;c++)o^=BigInt(t[c]),o=BigInt.asUintN(e,o*n)}return o}function Yn(r,{size:e=32,utf8Buffer:t}={}){if(!Xn[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Ou(r,e,t);r=Ss.encode(r)}return Ru(r,e)}var qu=Cr(ks(),1);var lt={hash:r=>Number(Yn(r,{size:32})),hashV:(r,e)=>ju(lt.hash(r,e))};function ju(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),O(e,"base16")}var Vu=500,dt=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??lt,this.seed=e.seed??Pe(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=O(e));let t=new re(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Le(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Le(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[Pe(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Le(this.bucketSize));for(let c=0;c<Vu;c++){let f=this.buckets[s].swap(t);if(f!=null&&(s=(s^f.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Le(this.bucketSize)),this.buckets[s].add(f)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=O(e));let t=new re(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=O(e));let t=new re(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Hu={1:.5,2:.84,4:.95,8:.98};function Ku(r=.001){return r>.002?2:r>1e-5?4:8}function As(r,e=.001){let t=Ku(e),n=Hu[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Jn);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var _r=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??lt,this.seed=e.seed??Pe(0,Math.pow(2,10)),this.filterSeries=[new dt({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=O(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new dt({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=O(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=O(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Zn(r,e=.001,t){return new _r({...As(r,e),...t??{}})}var kr=class extends Ne{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),F(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Zn(this.maxProviders)}async retrieve(e,t={}){let n=ye.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=ae();if(this.requests.set(n,i.promise),this.providers.length===0){let p=!1;this.intialPeerSearchComplete==null&&(p=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,p&&this.log("found initial session peers for %c",e)}let s=!1,c=new ce({concurrency:this.maxProviders});c.addEventListener("error",()=>{}),c.addEventListener("failure",p=>{this.log.error("error querying provider %o, evicting from session",p.detail.job.options.provider,p.detail.error),this.evict(p.detail.job.options.provider)}),c.addEventListener("success",p=>{s=!0,i.resolve(p.detail.result)}),c.addEventListener("idle",()=>{s||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let p=0;p<this.minProviders&&this.providers.length!==0;p++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(p=>{this.log.error("could not find new providers for %c",e,p),i.reject(p)})});let f=p=>{c.add(async()=>this.queryProvider(e,p.detail,t),{provider:p.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,d)})};this.addEventListener("provider",f),Promise.all([...this.providers].map(async p=>c.add(async()=>this.queryProvider(e,p,t),{provider:p}))).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,p)});try{return await i.promise}finally{this.removeEventListener("provider",f),c.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=ae(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new ir(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var eo=class{blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??fo(),this.log=this.logger.forComponent("helia"),this.getHasher=ws(e.hashers,e.loadHasher),this.getCodec=ys(e.codecs,e.loadCodec),this.dns=e.dns??zo(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new fr(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[Sr]!=null&&i.push(o[Sr]),o[Ar]!=null&&i.push(o[Ar]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Er(t);this.pins=new or(e.datastore,n,this.getCodec),this.blockstore=new lr(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await ts(this.datastore),await he(this.blockstore,this.datastore,this.routing)}async stop(){await pe(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Mo(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new L("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new L("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};return Ds(Qu);})();
|
|
2
|
+
"use strict";var HeliaUtils=(()=>{var xs=Object.create;var lt=Object.defineProperty;var bs=Object.getOwnPropertyDescriptor;var Es=Object.getOwnPropertyNames;var _s=Object.getPrototypeOf,vs=Object.prototype.hasOwnProperty;var Kn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),T=(r,e)=>{for(var t in e)lt(r,t,{get:e[t],enumerable:!0})},Gn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Es(e))!vs.call(r,o)&&o!==t&<(r,o,{get:()=>e[o],enumerable:!(n=bs(e,o))||n.enumerable});return r};var Wn=(r,e,t)=>(t=r!=null?xs(_s(r)):{},Gn(e||!r||!r.__esModule?lt(t,"default",{value:r,enumerable:!0}):t,r)),ks=r=>Gn(lt({},"__esModule",{value:!0}),r);var io=Kn((pl,Ir)=>{"use strict";var na=Object.prototype.hasOwnProperty,D="~";function Ge(){}Object.create&&(Ge.prototype=Object.create(null),new Ge().__proto__||(D=!1));function oa(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function oo(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new oa(t,n||r,o),s=D?D+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function yt(r,e){--r._eventsCount===0?r._events=new Ge:delete r._events[e]}function N(){this._events=new Ge,this._eventsCount=0}N.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)na.call(t,n)&&e.push(D?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};N.prototype.listeners=function(e){var t=D?D+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};N.prototype.listenerCount=function(e){var t=D?D+e:e,n=this._events[t];return n?n.fn?1:n.length:0};N.prototype.emit=function(e,t,n,o,i,s){var c=D?D+e:e;if(!this._events[c])return!1;var u=this._events[c],d=arguments.length,f,h;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,o),!0;case 5:return u.fn.call(u.context,t,n,o,i),!0;case 6:return u.fn.call(u.context,t,n,o,i,s),!0}for(h=1,f=new Array(d-1);h<d;h++)f[h-1]=arguments[h];u.fn.apply(u.context,f)}else{var y=u.length,k;for(h=0;h<y;h++)switch(u[h].once&&this.removeListener(e,u[h].fn,void 0,!0),d){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,t);break;case 3:u[h].fn.call(u[h].context,t,n);break;case 4:u[h].fn.call(u[h].context,t,n,o);break;default:if(!f)for(k=1,f=new Array(d-1);k<d;k++)f[k-1]=arguments[k];u[h].fn.apply(u[h].context,f)}}return!0};N.prototype.on=function(e,t,n){return oo(this,e,t,n,!1)};N.prototype.once=function(e,t,n){return oo(this,e,t,n,!0)};N.prototype.removeListener=function(e,t,n,o){var i=D?D+e:e;if(!this._events[i])return this;if(!t)return yt(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&yt(this,i);else{for(var c=0,u=[],d=s.length;c<d;c++)(s[c].fn!==t||o&&!s[c].once||n&&s[c].context!==n)&&u.push(s[c]);u.length?this._events[i]=u.length===1?u[0]:u:yt(this,i)}return this};N.prototype.removeAllListeners=function(e){var t;return e?(t=D?D+e:e,this._events[t]&&yt(this,t)):(this._events=new Ge,this._eventsCount=0),this};N.prototype.off=N.prototype.removeListener;N.prototype.addListener=N.prototype.on;N.prefixed=D;N.EventEmitter=N;typeof Ir<"u"&&(Ir.exports=N)});var Io=Kn((Ef,So)=>{So.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Mu={};T(Mu,{AbstractSession:()=>gr,Helia:()=>Hn});var yr=Symbol.for("@libp2p/content-routing");var wr=Symbol.for("@libp2p/peer-routing");var re=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ft=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var dt=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var ht=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Pe=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function Qn(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function le(...r){let e=[];for(let t of r)Qn(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function fe(...r){let e=[];for(let t of r)Qn(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var kr={};T(kr,{base32:()=>he,base32hex:()=>Ds,base32hexpad:()=>Bs,base32hexpadupper:()=>Fs,base32hexupper:()=>Us,base32pad:()=>Ls,base32padupper:()=>Ns,base32upper:()=>Ps,base32z:()=>$s});var Ku=new Uint8Array(0);function Jn(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function G(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Xn(r){return new TextEncoder().encode(r)}function Yn(r){return new TextDecoder().decode(r)}function Cs(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var c=r.length,u=r.charAt(0),d=Math.log(c)/Math.log(256),f=Math.log(256)/Math.log(c);function h(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var w=0,g=0,_=0,A=E.length;_!==A&&E[_]===0;)_++,w++;for(var S=(A-_)*f+1>>>0,I=new Uint8Array(S);_!==A;){for(var F=E[_],q=0,$=S-1;(F!==0||q<g)&&$!==-1;$--,q++)F+=256*I[$]>>>0,I[$]=F%c>>>0,F=F/c>>>0;if(F!==0)throw new Error("Non-zero carry");g=q,_++}for(var j=S-g;j!==S&&I[j]===0;)j++;for(var Te=u.repeat(w);j<S;++j)Te+=r.charAt(I[j]);return Te}function y(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var w=0;if(E[w]!==" "){for(var g=0,_=0;E[w]===u;)g++,w++;for(var A=(E.length-w)*d+1>>>0,S=new Uint8Array(A);E[w];){var I=t[E.charCodeAt(w)];if(I===255)return;for(var F=0,q=A-1;(I!==0||F<_)&&q!==-1;q--,F++)I+=c*S[q]>>>0,S[q]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");_=F,w++}if(E[w]!==" "){for(var $=A-_;$!==A&&S[$]===0;)$++;for(var j=new Uint8Array(g+(A-$)),Te=g;$!==A;)j[Te++]=S[$++];return j}}}function k(E){var w=y(E);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:y,decode:k}}var As=Cs,Ss=As,Zn=Ss;var br=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Er=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return eo(this,e)}},_r=class{decoders;constructor(e){this.decoders=e}or(e){return eo(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function eo(r,e){return new _r({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var vr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new br(e,t,n),this.decoder=new Er(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Le({name:r,prefix:e,encode:t,decode:n}){return new vr(r,e,t,n)}function de({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Zn(t,r);return Le({prefix:e,name:r,encode:n,decode:i=>G(o(i))})}function Is(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),c=0,u=0,d=0;for(let f=0;f<i;++f){let h=o[r[f]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);u=u<<t|h,c+=t,c>=8&&(c-=8,s[d++]=255&u>>c)}if(c>=t||255&u<<8-c)throw new SyntaxError("Unexpected end of data");return s}function Ts(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,c=0;for(let u=0;u<r.length;++u)for(c=c<<8|r[u],s+=8;s>t;)s-=t,i+=e[o&c>>s];if(s!==0&&(i+=e[o&c<<t-s]),n)for(;i.length*t&7;)i+="=";return i}function C({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Le({prefix:e,name:r,encode(o){return Ts(o,n,t)},decode(o){return Is(o,n,t,r)}})}var he=C({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ps=C({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ls=C({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ns=C({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ds=C({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Us=C({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Bs=C({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Fs=C({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$s=C({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Cr={};T(Cr,{base58btc:()=>V,base58flickr:()=>zs});var V=de({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zs=de({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ar={};T(Ar,{base64:()=>pe,base64pad:()=>Ms,base64url:()=>Rs,base64urlpad:()=>Os});var pe=C({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ms=C({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Rs=C({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Os=C({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function qs(r,e){try{if(typeof r=="string"&&r.length>0)return js(r);if(typeof r=="number"&&isFinite(r))return e?.long?Hs(r):Vs(r);throw new Error("Value is not a string or number.")}catch(t){let n=Ks(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function js(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var mt=qs;function Vs(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Hs(r){let e=Math.abs(r);return e>=864e5?pt(r,e,864e5,"day"):e>=36e5?pt(r,e,36e5,"hour"):e>=6e4?pt(r,e,6e4,"minute"):e>=1e3?pt(r,e,1e3,"second"):`${r} ms`}function pt(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Ks(r){return typeof r=="object"&&r!==null&&"message"in r}function Sr(r){t.debug=t,t.default=t,t.coerce=u,t.disable=i,t.enable=o,t.enabled=s,t.humanize=mt,t.destroy=d,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let h=0;for(let y=0;y<f.length;y++)h=(h<<5)-h+f.charCodeAt(y),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(f){let h,y=null,k,E;function w(...g){if(!w.enabled)return;let _=w,A=Number(new Date),S=A-(h||A);_.diff=S,_.prev=h,_.curr=A,h=A,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let I=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(q,$)=>{if(q==="%%")return"%";I++;let j=t.formatters[$];if(typeof j=="function"){let Te=g[I];q=j.call(_,Te),g.splice(I,1),I--}return q}),t.formatArgs.call(_,g),(_.log||t.log).apply(_,g)}return w.namespace=f,w.useColors=t.useColors(),w.color=t.selectColor(f),w.extend=n,w.destroy=t.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(k!==t.namespaces&&(k=t.namespaces,E=t.enabled(f)),E),set:g=>{y=g}}),typeof t.init=="function"&&t.init(w),w}function n(f,h){let y=t(this.namespace+(typeof h>"u"?":":h)+f);return y.log=this.log,y}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let h,y=(typeof f=="string"?f:"").split(/[\s,]+/),k=y.length;for(h=0;h<k;h++)y[h]&&(f=y[h].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function i(){let f=[...t.names.map(c),...t.skips.map(c).map(h=>"-"+h)].join(",");return t.enable(""),f}function s(f){if(f[f.length-1]==="*")return!0;let h,y;for(h=0,y=t.skips.length;h<y;h++)if(t.skips[h].test(f))return!1;for(h=0,y=t.names.length;h<y;h++)if(t.names[h].test(f))return!0;return!1}function c(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function u(f){return f instanceof Error?f.stack??f.message:f}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var gt=Zs(),Gs=["#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 Ws(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Qs(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+mt(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var Js=console.debug??console.log??(()=>{});function Xs(r){try{r?gt?.setItem("debug",r):gt?.removeItem("debug")}catch{}}function Ys(){let r;try{r=gt?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Zs(){try{return localStorage}catch{}}function ea(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var to=Sr({formatArgs:Qs,save:Xs,load:Ys,useColors:Ws,setupFormatters:ea,colors:Gs,storage:gt,log:Js});var U=to;U.formatters.b=r=>r==null?"undefined":V.baseEncode(r);U.formatters.t=r=>r==null?"undefined":he.baseEncode(r);U.formatters.m=r=>r==null?"undefined":pe.baseEncode(r);U.formatters.p=r=>r==null?"undefined":r.toString();U.formatters.c=r=>r==null?"undefined":r.toString();U.formatters.k=r=>r==null?"undefined":r.toString();U.formatters.a=r=>r==null?"undefined":r.toString();U.formatters.e=r=>r==null?"undefined":ro(r.stack)??ro(r.message)??r.toString();function ta(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function no(){return{forComponent(r){return ra(r)}}}function ra(r){let e=ta(`${r}:trace`);return U.enabled(`${r}:trace`)&&U.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=U(`${r}:trace`)),Object.assign(U(r),{error:U(`${r}:error`),trace:e})}function ro(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var b=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Tr=Wn(io(),1);var We=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Pr=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},so=r=>globalThis.DOMException===void 0?new Pr(r):new DOMException(r),ao=r=>{let e=r.reason===void 0?so("This operation was aborted."):r.reason;return e instanceof Error?e:so(e)};function Qe(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,c,d=new Promise((f,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:k}=e;k.aborted&&h(ao(k)),c=()=>{h(ao(k))},k.addEventListener("abort",c,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,h);return}let y=new We;s=i.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(k){h(k)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?h(o):(y.message=o??`Promise timed out after ${t} milliseconds`,h(y))},t),(async()=>{try{f(await r)}catch(k){h(k)}})()}).finally(()=>{d.clear(),c&&e.signal&&e.signal.removeEventListener("abort",c)});return d.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},d}function Lr(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var Je=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Lr(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var me=class extends Tr.default{#e;#o;#s=0;#h;#a;#p=0;#r;#c;#t;#m;#n=0;#u;#i;#g;#x=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Je,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#o=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#o||this.#s<this.#h}get#E(){return this.#n<this.#u}#_(){this.#n--,this.#l(),this.emit("next")}#v(){this.#w(),this.#y(),this.#c=void 0}get#k(){let e=Date.now();if(this.#r===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#n:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#v()},t)),!0}return!1}#l(){if(this.#t.size===0)return this.#r&&clearInterval(this.#r),this.#r=void 0,this.emit("empty"),this.#n===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#k;if(this.#b&&this.#E){let t=this.#t.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#o||this.#r!==void 0||(this.#r=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#s===0&&this.#n===0&&this.#r&&(clearInterval(this.#r),this.#r=void 0),this.#s=this.#e?this.#n:0,this.#f()}#f(){for(;this.#l(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#f()}async#C(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#t.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#x++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#t.enqueue(async()=>{this.#n++,this.#s++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=Qe(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#C(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof We&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#_()}},t),this.emit("add"),this.#l()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#d("next",()=>this.#t.size<e)}async onIdle(){this.#n===0&&this.#t.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#i}};function wt(r){let e=[W.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Nr={};T(Nr,{base10:()=>ia});var ia=de({prefix:"9",name:"base10",alphabet:"0123456789"});var Dr={};T(Dr,{base16:()=>sa,base16upper:()=>aa});var sa=C({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),aa=C({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ur={};T(Ur,{base2:()=>ca});var ca=C({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Br={};T(Br,{base256emoji:()=>ha});var co=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}"),ua=co.reduce((r,e,t)=>(r[t]=e,r),[]),la=co.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function fa(r){return r.reduce((e,t)=>(e+=ua[t],e),"")}function da(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=la[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var ha=Le({prefix:"\u{1F680}",name:"base256emoji",encode:fa,decode:da});var Fr={};T(Fr,{base36:()=>ne,base36upper:()=>pa});var ne=de({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),pa=de({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $r={};T($r,{base8:()=>ma});var ma=C({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var zr={};T(zr,{identity:()=>ga});var ga=Le({prefix:"\0",name:"identity",encode:r=>Yn(r),decode:r=>Xn(r)});var xt={};T(xt,{code:()=>Mr,decode:()=>Ea,encode:()=>ba,name:()=>xa});var ya=new TextEncoder,wa=new TextDecoder,xa="json",Mr=512;function ba(r){return ya.encode(JSON.stringify(r))}function Ea(r){return JSON.parse(wa.decode(r))}var bt={};T(bt,{code:()=>Rr,decode:()=>ka,encode:()=>va,name:()=>_a});var _a="raw",Rr=85;function va(r){return G(r)}function ka(r){return G(r)}var qr={};T(qr,{identity:()=>_t});var Ca=fo,uo=128,Aa=127,Sa=~Aa,Ia=Math.pow(2,31);function fo(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Ia;)e[t++]=r&255|uo,r/=128;for(;r&Sa;)e[t++]=r&255|uo,r>>>=7;return e[t]=r|0,fo.bytes=t-n+1,e}var Ta=Or,Pa=128,lo=127;function Or(r,n){var t=0,n=n||0,o=0,i=n,s,c=r.length;do{if(i>=c)throw Or.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&lo)<<o:(s&lo)*Math.pow(2,o),o+=7}while(s>=Pa);return Or.bytes=i-n,t}var La=Math.pow(2,7),Na=Math.pow(2,14),Da=Math.pow(2,21),Ua=Math.pow(2,28),Ba=Math.pow(2,35),Fa=Math.pow(2,42),$a=Math.pow(2,49),za=Math.pow(2,56),Ma=Math.pow(2,63),Ra=function(r){return r<La?1:r<Na?2:r<Da?3:r<Ua?4:r<Ba?5:r<Fa?6:r<$a?7:r<za?8:r<Ma?9:10},Oa={encode:Ca,decode:Ta,encodingLength:Ra},qa=Oa,Xe=qa;function Ye(r,e=0){return[Xe.decode(r,e),Xe.decode.bytes]}function Ne(r,e,t=0){return Xe.encode(r,e,t),e}function De(r){return Xe.encodingLength(r)}function be(r,e){let t=e.byteLength,n=De(r),o=n+De(t),i=new Uint8Array(o+t);return Ne(r,i,0),Ne(t,i,n),i.set(e,o),new Ue(r,t,e,i)}function ho(r){let e=G(r),[t,n]=Ye(e),[o,i]=Ye(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Ue(t,o,s,e)}function po(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Jn(r.bytes,t.bytes)}}var Ue=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var mo=0,ja="identity",go=G;function Va(r){return be(mo,go(r))}var _t={code:mo,name:ja,encode:go,digest:Va};var Hr={};T(Hr,{sha256:()=>vt,sha512:()=>kt});function Vr({name:r,code:e,encode:t}){return new jr(r,e,t)}var jr=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?be(this.code,t):t.then(n=>be(this.code,n))}else throw Error("Unknown type, must be binary type")}};function wo(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var vt=Vr({name:"sha2-256",code:18,encode:wo("SHA-256")}),kt=Vr({name:"sha2-512",code:19,encode:wo("SHA-512")});function xo(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ka(t,Kr(r),e??V.encoder);default:return Ga(t,Kr(r),e??he.encoder)}}var bo=new WeakMap;function Kr(r){let e=bo.get(r);if(e==null){let t=new Map;return bo.set(r,t),t}return e}var v=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==et)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Wa)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=be(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&po(e.multihash,n.multihash)}toString(e){return xo(this,e)}toJSON(){return{"/":xo(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??Eo(n,o,i.bytes))}else if(t[Qa]===!0){let{version:n,multihash:o,code:i}=t,s=ho(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==et)throw new Error(`Version 0 CID must use dag-pb (code: ${et}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Eo(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,et,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=G(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Ue(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,y]=Ye(e.subarray(t));return t+=y,h},o=n(),i=et;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,c=n(),u=n(),d=t+u,f=d-s;return{version:o,codec:i,multihashCode:c,digestSize:u,multihashSize:f,size:d}}static parse(e,t){let[n,o]=Ha(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Kr(i).set(n,e),i}};function Ha(r,e){switch(r[0]){case"Q":{let t=e??V;return[V.prefix,t.decode(`${V.prefix}${r}`)]}case V.prefix:{let t=e??V;return[V.prefix,t.decode(r)]}case he.prefix:{let t=e??he;return[he.prefix,t.decode(r)]}case ne.prefix:{let t=e??ne;return[ne.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ka(r,e,t){let{prefix:n}=t;if(n!==V.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function Ga(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var et=112,Wa=18;function Eo(r,e,t){let n=De(r),o=n+De(e),i=new Uint8Array(o+t.byteLength);return Ne(r,i,0),Ne(e,i,n),i.set(t,o),i}var Qa=Symbol.for("@ipld/js-cid/CID");var Gr={...zr,...Ur,...$r,...Nr,...Dr,...kr,...Fr,...Cr,...Ar,...Br},tf={...Hr,...qr};function _o(r=0){return new Uint8Array(r)}function vo(r=0){return new Uint8Array(r)}function Co(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ko=Co("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Wr=Co("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=vo(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Ja={utf8:ko,"utf-8":ko,hex:Gr.base16,latin1:Wr,ascii:Wr,binary:Wr,...Gr},Ct=Ja;function Be(r,e="utf8"){let t=Ct[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Qr=60;function At(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:W[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:W[e.type],TTL:e.TTL??e.ttl??Qr,data:e.data instanceof Uint8Array?Be(e.data):e.data}))}}var Xa=4;function Jr(r,e={}){let t=new me({concurrency:e.queryConcurrency??Xa});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),wt(o.types).forEach(c=>{i.append("type",W[c])}),o.onProgress?.(new b("dns:query",{detail:n}));let s=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let u=At(await c.json());return o.onProgress?.(new b("dns:response",{detail:u})),u},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Ao(){return[Jr("https://cloudflare-dns.com/dns-query"),Jr("https://dns.google/resolve")]}var To=Wn(Io(),1);var Xr=class{lru;constructor(e){this.lru=(0,To.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return At({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:c})=>({...c,TTL:Math.round((s-Date.now())/1e3),type:W[c.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Qr)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Po(r){return new Xr(r)}var Ya=1e3,St=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Po(e.cacheSize??Ya),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Ao())}async query(e,t={}){let n=wt(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new b("dns:cache",{detail:o})),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),c=[];for(let u of s){if(t.signal?.aborted===!0)break;try{let d=await u(e,{...t,types:n});for(let f of d.Answer)this.cache.add(e,f);return d}catch(d){c.push(d),t.onProgress?.(new b("dns:error",{detail:d}))}}throw c.length===1?c[0]:new AggregateError(c,`DNS lookup of ${e} ${n} failed`)}};var W;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(W||(W={}));function Lo(r={}){return new St(r)}function Za(r){return r[Symbol.asyncIterator]!=null}function ec(r){if(Za(r))return(async()=>{for await(let e of r);})();for(let e of r);}var No=ec;function oe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var It=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Fe=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new It(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new It(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Yr=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Tt(r={}){return tc(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function tc(r,e){e=e??{};let t=e.onEnd,n=new Fe,o,i,s,c=oe(),u=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((g,_)=>{i=A=>{i=null,n.push(A);try{g(r(n))}catch(S){_(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=oe()})}},d=g=>i!=null?i(g):(n.push(g),o),f=g=>(n=new Fe,i!=null?i({error:g}):(n.push({error:g}),o)),h=g=>{if(s)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return d({done:!1,value:g})},y=g=>s?o:(s=!0,g!=null?f(g):d({done:!0})),k=()=>(n=new Fe,y(),{done:!0}),E=g=>(y(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:u,return:k,throw:E,push:h,end:y,get readableLength(){return n.size},onEmpty:async g=>{let _=g?.signal;if(_?.throwIfAborted(),n.isEmpty())return;let A,S;_!=null&&(A=new Promise((I,F)=>{S=()=>{F(new Yr)},_.addEventListener("abort",S)}));try{await Promise.race([c.promise,A])}finally{S!=null&&_!=null&&_?.removeEventListener("abort",S)}}},t==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(g){return w.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(g){return w.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return w.readableLength},onEmpty:g=>w.onEmpty(g)},o}var Zr=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Pt(r,e,t,n){let o=new Zr(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function c(){t?.removeEventListener("abort",f),r.removeEventListener(e,u),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,d)}let u=h=>{try{if(n?.filter?.(h)===!1)return}catch(y){c(),s(y);return}c(),i(h)},d=h=>{c(),s(h.detail)},f=()=>{c(),s(o)};t?.addEventListener("abort",f),r.addEventListener(e,u),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,d)})}var Lt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Nt=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Do(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Nt(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Nt(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Dt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=oe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new re)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function rc(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ut=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=rc(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new re),this.cleanup())}async join(e={}){let t=new Dt(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Do(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var ie=class extends Pe{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Lt;let n=new Ut(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new re)}),this.clear()}async onEmpty(e){this.size!==0&&await Pt(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Pt(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Pt(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Tt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},o=u=>{u.detail!=null&&t.push(u.detail)},i=u=>{n(u.detail)},s=()=>{n()},c=()=>{n(new re("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",c);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",c),n()}}};var nc=["string","number","bigint","symbol"],oc=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Bo(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(nc.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(ic(r))return"Buffer";let t=sc(r);return t||"Object"}function ic(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function sc(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(oc.includes(e))return e}var a=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};a.uint=new a(0,"uint",!0);a.negint=new a(1,"negint",!0);a.bytes=new a(2,"bytes",!0);a.string=new a(3,"string",!0);a.array=new a(4,"array",!1);a.map=new a(5,"map",!1);a.tag=new a(6,"tag",!1);a.float=new a(7,"float",!0);a.false=new a(7,"false",!0);a.true=new a(7,"true",!0);a.null=new a(7,"null",!0);a.undefined=new a(7,"undefined",!0);a.break=new a(7,"break",!0);var l=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var $e=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ac=new TextDecoder,cc=new TextEncoder;function Bt(r){return $e&&globalThis.Buffer.isBuffer(r)}function tt(r){return r instanceof Uint8Array?Bt(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Mo=$e?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):$o(r,e,t):(r,e,t)=>t-e>64?ac.decode(r.subarray(e,t)):$o(r,e,t),Ft=$e?r=>r.length>64?globalThis.Buffer.from(r):Fo(r):r=>r.length>64?cc.encode(r):Fo(r),ee=r=>Uint8Array.from(r),ze=$e?(r,e,t)=>Bt(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Ro=$e?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),tt(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},Oo=$e?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function qo(r,e){if(Bt(r)&&Bt(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Fo(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function $o(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let c,u,d,f;switch(s){case 1:o<128&&(i=o);break;case 2:c=r[e+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(i=f));break;case 3:c=r[e+1],u=r[e+2],(c&192)===128&&(u&192)===128&&(f=(o&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:c=r[e+1],u=r[e+2],d=r[e+3],(c&192)===128&&(u&192)===128&&(d&192)===128&&(f=(o&15)<<18|(c&63)<<12|(u&63)<<6|d&63,f>65535&&f<1114112&&(i=f))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return en(n)}var zo=4096;function en(r){let e=r.length;if(e<=zo)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=zo));return t}var uc=256,rt=class{constructor(e=uc){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Oo(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=ze(n,0,this.cursor)}else t=Ro(this.chunks,this.cursor);return e&&this.reset(),t}};var m="CBOR decode error:",se="CBOR encode error:",nt=[];nt[23]=1;nt[24]=2;nt[25]=3;nt[26]=5;nt[27]=9;function ae(r,e,t){if(r.length-e<t)throw new Error(`${m} not enough data for type`)}var P=[24,256,65536,4294967296,BigInt("18446744073709551616")];function z(r,e,t){ae(r,e,1);let n=r[e];if(t.strict===!0&&n<P[0])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function M(r,e,t){ae(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<P[1])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function R(r,e,t){ae(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<P[2])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function O(r,e,t){ae(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<P[3])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${m} integers outside of the safe integer range are not supported`)}function jo(r,e,t,n){return new l(a.uint,z(r,e+1,n),2)}function Vo(r,e,t,n){return new l(a.uint,M(r,e+1,n),3)}function Ho(r,e,t,n){return new l(a.uint,R(r,e+1,n),5)}function Ko(r,e,t,n){return new l(a.uint,O(r,e+1,n),9)}function H(r,e){return L(r,0,e.value)}function L(r,e,t){if(t<P[0]){let n=Number(t);r.push([e|n])}else if(t<P[1]){let n=Number(t);r.push([e|24,n])}else if(t<P[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<P[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<P[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${m} encountered BigInt larger than allowable range`)}}H.encodedSize=function(e){return L.encodedSize(e.value)};L.encodedSize=function(e){return e<P[0]?1:e<P[1]?2:e<P[2]?3:e<P[3]?5:9};H.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Go(r,e,t,n){return new l(a.negint,-1-z(r,e+1,n),2)}function Wo(r,e,t,n){return new l(a.negint,-1-M(r,e+1,n),3)}function Qo(r,e,t,n){return new l(a.negint,-1-R(r,e+1,n),5)}var tn=BigInt(-1),Jo=BigInt(1);function Xo(r,e,t,n){let o=O(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new l(a.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${m} integers outside of the safe integer range are not supported`);return new l(a.negint,tn-BigInt(o),9)}function $t(r,e){let t=e.value,n=typeof t=="bigint"?t*tn-Jo:t*-1-1;L(r,e.type.majorEncoded,n)}$t.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*tn-Jo:t*-1-1;return n<P[0]?1:n<P[1]?2:n<P[2]?3:n<P[3]?5:9};$t.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ot(r,e,t,n){ae(r,e,t+n);let o=ze(r,e+t,e+t+n);return new l(a.bytes,o,t+n)}function Yo(r,e,t,n){return ot(r,e,1,t)}function Zo(r,e,t,n){return ot(r,e,2,z(r,e+1,n))}function ei(r,e,t,n){return ot(r,e,3,M(r,e+1,n))}function ti(r,e,t,n){return ot(r,e,5,R(r,e+1,n))}function ri(r,e,t,n){let o=O(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer bytes lengths not supported`);return ot(r,e,9,o)}function zt(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===a.string?Ft(r.value):r.value),r.encodedBytes}function Me(r,e){let t=zt(e);L(r,e.type.majorEncoded,t.length),r.push(t)}Me.encodedSize=function(e){let t=zt(e);return L.encodedSize(t.length)+t.length};Me.compareTokens=function(e,t){return fc(zt(e),zt(t))};function fc(r,e){return r.length<e.length?-1:r.length>e.length?1:qo(r,e)}function it(r,e,t,n,o){let i=t+n;ae(r,e,i);let s=new l(a.string,Mo(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=ze(r,e+t,e+i)),s}function ni(r,e,t,n){return it(r,e,1,t,n)}function oi(r,e,t,n){return it(r,e,2,z(r,e+1,n),n)}function ii(r,e,t,n){return it(r,e,3,M(r,e+1,n),n)}function si(r,e,t,n){return it(r,e,5,R(r,e+1,n),n)}function ai(r,e,t,n){let o=O(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer string lengths not supported`);return it(r,e,9,o,n)}var ci=Me;function Re(r,e,t,n){return new l(a.array,n,t)}function ui(r,e,t,n){return Re(r,e,1,t)}function li(r,e,t,n){return Re(r,e,2,z(r,e+1,n))}function fi(r,e,t,n){return Re(r,e,3,M(r,e+1,n))}function di(r,e,t,n){return Re(r,e,5,R(r,e+1,n))}function hi(r,e,t,n){let o=O(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer array lengths not supported`);return Re(r,e,9,o)}function pi(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return Re(r,e,1,1/0)}function Mt(r,e){L(r,a.array.majorEncoded,e.value)}Mt.compareTokens=H.compareTokens;Mt.encodedSize=function(e){return L.encodedSize(e.value)};function Oe(r,e,t,n){return new l(a.map,n,t)}function mi(r,e,t,n){return Oe(r,e,1,t)}function gi(r,e,t,n){return Oe(r,e,2,z(r,e+1,n))}function yi(r,e,t,n){return Oe(r,e,3,M(r,e+1,n))}function wi(r,e,t,n){return Oe(r,e,5,R(r,e+1,n))}function xi(r,e,t,n){let o=O(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer map lengths not supported`);return Oe(r,e,9,o)}function bi(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return Oe(r,e,1,1/0)}function Rt(r,e){L(r,a.map.majorEncoded,e.value)}Rt.compareTokens=H.compareTokens;Rt.encodedSize=function(e){return L.encodedSize(e.value)};function Ei(r,e,t,n){return new l(a.tag,t,1)}function _i(r,e,t,n){return new l(a.tag,z(r,e+1,n),2)}function vi(r,e,t,n){return new l(a.tag,M(r,e+1,n),3)}function ki(r,e,t,n){return new l(a.tag,R(r,e+1,n),5)}function Ci(r,e,t,n){return new l(a.tag,O(r,e+1,n),9)}function Ot(r,e){L(r,a.tag.majorEncoded,e.value)}Ot.compareTokens=H.compareTokens;Ot.encodedSize=function(e){return L.encodedSize(e.value)};var yc=20,wc=21,xc=22,bc=23;function Ai(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${m} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new l(a.null,null,1):new l(a.undefined,void 0,1)}function Si(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return new l(a.break,void 0,1)}function rn(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${m} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${m} Infinity values are not supported`)}return new l(a.float,r,e)}function Ii(r,e,t,n){return rn(nn(r,e+1),3,n)}function Ti(r,e,t,n){return rn(on(r,e+1),5,n)}function Pi(r,e,t,n){return rn(Ui(r,e+1),9,n)}function qt(r,e,t){let n=e.value;if(n===!1)r.push([a.float.majorEncoded|yc]);else if(n===!0)r.push([a.float.majorEncoded|wc]);else if(n===null)r.push([a.float.majorEncoded|xc]);else if(n===void 0)r.push([a.float.majorEncoded|bc]);else{let o,i=!1;(!t||t.float64!==!0)&&(Ni(n),o=nn(Q,1),n===o||Number.isNaN(n)?(Q[0]=249,r.push(Q.slice(0,3)),i=!0):(Di(n),o=on(Q,1),n===o&&(Q[0]=250,r.push(Q.slice(0,5)),i=!0))),i||(Ec(n),o=Ui(Q,1),Q[0]=251,r.push(Q.slice(0,9)))}}qt.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){Ni(n);let o=nn(Q,1);if(n===o||Number.isNaN(n))return 3;if(Di(n),o=on(Q,1),n===o)return 5}return 9};var Li=new ArrayBuffer(9),K=new DataView(Li,1),Q=new Uint8Array(Li,0);function Ni(r){if(r===1/0)K.setUint16(0,31744,!1);else if(r===-1/0)K.setUint16(0,64512,!1);else if(Number.isNaN(r))K.setUint16(0,32256,!1);else{K.setFloat32(0,r);let e=K.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)K.setUint16(0,31744,!1);else if(t===0)K.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?K.setUint16(0,0):o<-14?K.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):K.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function nn(r,e){if(r.length-e<2)throw new Error(`${m} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function Di(r){K.setFloat32(0,r,!1)}function on(r,e){if(r.length-e<4)throw new Error(`${m} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Ec(r){K.setFloat64(0,r,!1)}function Ui(r,e){if(r.length-e<8)throw new Error(`${m} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}qt.compareTokens=H.compareTokens;function x(r,e,t){throw new Error(`${m} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function jt(r){return()=>{throw new Error(`${m} ${r}`)}}var p=[];for(let r=0;r<=23;r++)p[r]=x;p[24]=jo;p[25]=Vo;p[26]=Ho;p[27]=Ko;p[28]=x;p[29]=x;p[30]=x;p[31]=x;for(let r=32;r<=55;r++)p[r]=x;p[56]=Go;p[57]=Wo;p[58]=Qo;p[59]=Xo;p[60]=x;p[61]=x;p[62]=x;p[63]=x;for(let r=64;r<=87;r++)p[r]=Yo;p[88]=Zo;p[89]=ei;p[90]=ti;p[91]=ri;p[92]=x;p[93]=x;p[94]=x;p[95]=jt("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)p[r]=ni;p[120]=oi;p[121]=ii;p[122]=si;p[123]=ai;p[124]=x;p[125]=x;p[126]=x;p[127]=jt("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)p[r]=ui;p[152]=li;p[153]=fi;p[154]=di;p[155]=hi;p[156]=x;p[157]=x;p[158]=x;p[159]=pi;for(let r=160;r<=183;r++)p[r]=mi;p[184]=gi;p[185]=yi;p[186]=wi;p[187]=xi;p[188]=x;p[189]=x;p[190]=x;p[191]=bi;for(let r=192;r<=215;r++)p[r]=Ei;p[216]=_i;p[217]=vi;p[218]=ki;p[219]=Ci;p[220]=x;p[221]=x;p[222]=x;p[223]=x;for(let r=224;r<=243;r++)p[r]=jt("simple values are not supported");p[244]=x;p[245]=x;p[246]=x;p[247]=Ai;p[248]=jt("simple values are not supported");p[249]=Ii;p[250]=Ti;p[251]=Pi;p[252]=x;p[253]=x;p[254]=x;p[255]=Si;var J=[];for(let r=0;r<24;r++)J[r]=new l(a.uint,r,1);for(let r=-1;r>=-24;r--)J[31-r]=new l(a.negint,r,1);J[64]=new l(a.bytes,new Uint8Array(0),1);J[96]=new l(a.string,"",1);J[128]=new l(a.array,0,1);J[160]=new l(a.map,0,1);J[244]=new l(a.false,!1,1);J[245]=new l(a.true,!0,1);J[246]=new l(a.null,null,1);function Bi(r){switch(r.type){case a.false:return ee([244]);case a.true:return ee([245]);case a.null:return ee([246]);case a.bytes:return r.value.length?void 0:ee([64]);case a.string:return r.value===""?ee([96]):void 0;case a.array:return r.value===0?ee([128]):void 0;case a.map:return r.value===0?ee([160]):void 0;case a.uint:return r.value<24?ee([Number(r.value)]):void 0;case a.negint:if(r.value>=-24)return ee([31-Number(r.value)])}}var vc={float64:!1,mapSorter:Ac,quickEncodeToken:Bi};function kc(){let r=[];return r[a.uint.major]=H,r[a.negint.major]=$t,r[a.bytes.major]=Me,r[a.string.major]=ci,r[a.array.major]=Mt,r[a.map.major]=Rt,r[a.tag.major]=Ot,r[a.float.major]=qt,r}var Fi=kc(),sn=new rt,Ht=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${se} object contains circular references`);return new r(t,e)}},ge={null:new l(a.null,null),undefined:new l(a.undefined,void 0),true:new l(a.true,!0),false:new l(a.false,!1),emptyArray:new l(a.array,0),emptyMap:new l(a.map,0)},ye={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new l(a.float,r):r>=0?new l(a.uint,r):new l(a.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new l(a.uint,r):new l(a.negint,r)},Uint8Array(r,e,t,n){return new l(a.bytes,r)},string(r,e,t,n){return new l(a.string,r)},boolean(r,e,t,n){return r?ge.true:ge.false},null(r,e,t,n){return ge.null},undefined(r,e,t,n){return ge.undefined},ArrayBuffer(r,e,t,n){return new l(a.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new l(a.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ge.emptyArray,new l(a.break)]:ge.emptyArray;n=Ht.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Vt(s,t,n);return t.addBreakTokens?[new l(a.array,r.length),o,new l(a.break)]:[new l(a.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[ge.emptyMap,new l(a.break)]:ge.emptyMap;n=Ht.createCheck(n,r);let c=[],u=0;for(let d of i)c[u++]=[Vt(d,t,n),Vt(o?r.get(d):r[d],t,n)];return Cc(c,t),t.addBreakTokens?[new l(a.map,s),c,new l(a.break)]:[new l(a.map,s),c]}};ye.Map=ye.Object;ye.Buffer=ye.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ye[`${r}Array`]=ye.DataView;function Vt(r,e={},t){let n=Bo(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||ye[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=ye[n];if(!i)throw new Error(`${se} unsupported type: ${n}`);return i(r,n,e,t)}function Cc(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Ac(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=Fi[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function $i(r,e,t,n){if(Array.isArray(e))for(let o of e)$i(r,o,t,n);else t[e.type.major](r,e,n)}function an(r,e,t){let n=Vt(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),c=new rt(s);if(i(c,n,t),c.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return tt(c.chunks[0])}}return sn.reset(),$i(sn,n,e,t),sn.toBytes(!0)}function _e(r,e){return e=Object.assign({},vc,e),an(r,Fi,e)}var Sc={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Kt=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=J[e];if(t===void 0){let n=p[e];if(!n)throw new Error(`${m} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},st=Symbol.for("DONE"),Gt=Symbol.for("BREAK");function Ic(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=qe(e,t);if(i===Gt){if(r.value===1/0)break;throw new Error(`${m} got unexpected break to lengthed array`)}if(i===st)throw new Error(`${m} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function Tc(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let c=qe(e,t);if(c===Gt){if(r.value===1/0)break;throw new Error(`${m} got unexpected break to lengthed map`)}if(c===st)throw new Error(`${m} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof c!="string")throw new Error(`${m} non-string keys not supported (got ${typeof c})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(c)||!n&&c in o))throw new Error(`${m} found repeat map key "${c}"`);let u=qe(e,t);if(u===st)throw new Error(`${m} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(c,u):o[c]=u}return n?i:o}function qe(r,e){if(r.done())return st;let t=r.next();if(t.type===a.break)return Gt;if(t.type.terminal)return t.value;if(t.type===a.array)return Ic(t,r,e);if(t.type===a.map)return Tc(t,r,e);if(t.type===a.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=qe(r,e);return e.tags[t.value](n)}throw new Error(`${m} tag not supported (${t.value})`)}throw new Error("unsupported")}function cn(r,e){if(!(r instanceof Uint8Array))throw new Error(`${m} data to decode must be a Uint8Array`);e=Object.assign({},Sc,e);let t=e.tokenizer||new Kt(r,e),n=qe(t,e);if(n===st)throw new Error(`${m} did not find any content to decode`);if(n===Gt)throw new Error(`${m} got unexpected break`);return[n,r.subarray(t.pos())]}function X(r,e){let[t,n]=cn(r,e);if(n.length>0)throw new Error(`${m} too many terminals, data makes no sense`);return t}function B(r,e="utf8"){let t=Ct[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var ce="/",Mi=new TextEncoder().encode(ce),Wt=Mi[0],ue=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=B(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Wt)throw new Error("Invalid key")}toString(e="utf8"){return Be(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(ce))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Mi),this._buf[0]!==Wt){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Wt,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Wt;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(ce).slice(1)}type(){return Pc(this.baseNamespace())}name(){return Lc(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(ce)||(e+=ce),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(ce):new r(e.slice(0,-1).join(ce))}child(e){return this.toString()===ce?e:e.toString()===ce?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Nc(e.map(t=>t.namespaces()))])}};function Pc(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Lc(r){let e=r.split(":");return e[e.length-1]}function Nc(r){return[].concat(...r)}function Qt({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*Dc(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=v.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*un(n,o))}else{let t=v.asCID(e);t!=null?yield[r.join("/"),t]:yield*un(e,r)}}function*un(r,e){if(r==null||r instanceof Uint8Array)return;let t=v.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*Dc(i,o)}}function*Uc(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&v.asCID(n)==null&&(yield*ln(n,o))}else yield*ln(e,r)}function*ln(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&v.asCID(n)==null&&(yield*Uc(o,n))}}function Bc(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=v.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var fn=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:Qt(),bytes:Qt(),value:Qt(),asBlock:Qt()})}links(){return un(this.value,[])}tree(){return ln(this.value,[])}get(e="/"){return Bc(this.value,e.split("/").filter(Boolean))}};function Ri({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new fn({cid:e,bytes:r,value:o})}function ve(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var ji="/pin/",Oi="/pinned-block/",dn=ne,qi=1;function Jt(r){return r.version===0&&(r=r.toV1()),new ue(`${ji}${r.toString(dn)}`)}var Xt=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Jt(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new ie({concurrency:qi});for await(let c of this.#e(e,i,{...t,depth:o}))await this.#o(c,u=>u.pinnedBy.find(d=>ve(d,e.bytes))!=null?!1:(u.pinCount++,u.pinnedBy.push(e.bytes),!0),t),yield c;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,_e(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await this.blockstore.get(e,n),s=Ri({bytes:i,cid:e,codec:o});yield e;for await(let[,c]of s.links())yield*await t.add(async()=>this.#e(c,t,{...n,depth:n.depth-1}))}async#o(e,t,n){let o=new ue(`${Oi}${dn.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=X(await this.datastore.get(o,n))}catch(c){if(c.name!=="NotFoundError")throw c}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,_e(i),n),n.onProgress?.(new b("helia:pin:add",e))}}async*rm(e,t={}){let n=Jt(e),o=await this.datastore.get(n,t),i=X(o);await this.datastore.delete(n,t);let s=new ie({concurrency:qi});for await(let c of this.#e(e,s,{...t,depth:i.depth}))await this.#o(c,u=>(u.pinCount--,u.pinnedBy=u.pinnedBy.filter(d=>ve(d,e.bytes)),!0),{...t,depth:i.depth}),yield c}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:ji+(e.cid!=null?`${e.cid.toString(ne)}`:"")},e)){let o=v.parse(t.toString().substring(5),ne),i=X(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new ue(`${Oi}${dn.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Jt(e),o=await this.datastore.get(n,t);return X(o)}async setMetadata(e,t,n){let o=Jt(e),i=await this.datastore.get(o,n),s=X(i);s.metadata=t??{},await this.datastore.put(o,_e(s),n)}};var Yt=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},ke=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},Zt=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},er=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var tr=class extends ie{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function Fc(r){return r[Symbol.asyncIterator]!=null}function $c(...r){let e=[];for(let t of r)Fc(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Tt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var rr=$c;var zc=5,nr=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??zc,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await le(...this.routers)}async stop(){await fe(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new ke("No content routers available");let n=new tr({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of rr(n.toGenerator(),...Ce(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new ke("No content routers available");await Promise.all(Ce(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Ce(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Ce(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(Ce(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new ke("No peer routers available");let n=this,o=rr(...Ce(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new dt("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new ke("No peer routers available");for await(let n of rr(...Ce(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Ce(r,e){return r.filter(t=>t[e]!=null)}var we={},je=r=>{r.addEventListener("message",e=>{je.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{je.dispatchEvent("message",r,e)})};je.addEventListener=(r,e)=>{we[r]==null&&(we[r]=[]),we[r].push(e)};je.removeEventListener=(r,e)=>{we[r]!=null&&(we[r]=we[r].filter(t=>t===e))};je.dispatchEvent=function(r,e,t){we[r]!=null&&we[r].forEach(n=>n(e,t))};var hn=je;var pn="lock:worker:request-read",mn="lock:worker:release-read",gn="lock:master:grant-read",yn="lock:worker:request-write",wn="lock:worker:release-write",xn="lock:master:grant-write";var Vi=(r=21)=>Math.random().toString().substring(2);var Hi=(r,e,t,n,o)=>(i,s)=>{if(s.data.type!==t)return;let c={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:c.name,handler:async()=>{i.postMessage({type:o,name:c.name,identifier:c.identifier}),await new Promise(u=>{let d=f=>{if(f?.data==null)return;let h={type:f.data.type,name:f.data.name,identifier:f.data.identifier};h.type===n&&h.identifier===c.identifier&&(i.removeEventListener("message",d),u())};i.addEventListener("message",d)})}}}))},Ki=(r,e,t,n)=>async()=>{let o=Vi();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(i=>{let s=c=>{if(c?.data==null)return;let u={type:c.data.type,identifier:c.data.identifier};u.type===t&&u.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},Mc={singleProcess:!1},Gi=r=>{if(r=Object.assign({},Mc,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return hn.addEventListener("message",Hi(t,"requestReadLock",pn,mn,gn)),hn.addEventListener("message",Hi(t,"requestWriteLock",yn,wn,xn)),t}return{isWorker:!0,readLock:t=>Ki(t,pn,gn,mn),writeLock:t=>Ki(t,yn,xn,wn)}};var Ae={},xe;async function bn(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Qe((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Rc=(r,e)=>{if(xe.isWorker===!0)return{readLock:xe.readLock(r,e),writeLock:xe.writeLock(r,e)};let t=new me({concurrency:1}),n;return{async readLock(){if(n!=null)return bn(n,e);n=new me({concurrency:e.concurrency,autoStart:!1});let o=n,i=bn(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,bn(t,e)}}},Oc={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function En(r){let e=Object.assign({},Oc,r);return xe==null&&(xe=Gi(e),xe.isWorker!==!0&&(xe.addEventListener("requestReadLock",t=>{Ae[t.data.name]!=null&&Ae[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),xe.addEventListener("requestWriteLock",async t=>{Ae[t.data.name]!=null&&Ae[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Ae[e.name]==null&&(Ae[e.name]=Rc(e.name,e)),Ae[e.name]}var or=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=En({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await le(this.child),this.started=!0}async stop(){await fe(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var _n=new ue("/version"),Wi=1;async function Qi(r){if(!await r.has(_n)){await r.put(_n,B(`${Wi}`));return}let e=await r.get(_n),t=Be(e);if(parseInt(t,10)!==Wi)throw new Error("Unknown datastore version, a datastore migration may be required")}var Cn={};T(Cn,{code:()=>kn,decode:()=>Jc,decodeOptions:()=>Gc,encode:()=>Qc,encodeOptions:()=>Hc,name:()=>Wc,toByteView:()=>Xi});var Ji=42;function Xi(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function qc(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=v.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new l(a.tag,Ji),new l(a.bytes,t)]}function jc(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Vc(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var vn={float64:!0,typeEncoders:{Object:qc,undefined:jc,number:Vc}},Hc={...vn,typeEncoders:{...vn.typeEncoders}};function Kc(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return v.decode(r.subarray(1))}var ir={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};ir.tags[Ji]=Kc;var Gc={...ir,tags:ir.tags.slice()},Wc="dag-cbor",kn=113,Qc=r=>_e(r,vn),Jc=r=>X(Xi(r),ir);var Nn={};T(Nn,{code:()=>Ln,decode:()=>Zi,encode:()=>Yi,format:()=>au,name:()=>su,parse:()=>uu,stringify:()=>au});var An=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===a.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===a.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[a.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[a.negint.major](e,t){this[a.uint.major](e,t)}[a.bytes.major](e,t){throw new Error(`${se} unsupported type: Uint8Array`)}[a.string.major](e,t){this.prefix(e);let n=Ft(JSON.stringify(t.value));e.push(n.length>32?tt(n):n)}[a.array.major](e,t){this.prefix(e),this.inRecursive.push({type:a.array,elements:0}),e.push([91])}[a.map.major](e,t){this.prefix(e),this.inRecursive.push({type:a.map,elements:0}),e.push([123])}[a.tag.major](e,t){}[a.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===a.array)e.push([93]);else if(s.type===a.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${se} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function Xc(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${se} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==a.string||n.type!==a.string)throw new Error(`${se} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${se} unexpected duplicate map keys, this is not supported`)}var Yc={addBreakTokens:!0,mapSorter:Xc};function Sn(r,e){return e=Object.assign({},Yc,e),an(r,new An,e)}var Ve=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${m} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${m} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=c=>{for(;!this.done();){let u=this.ch();if(c.includes(u))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new l(a.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${m} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${m} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new l(a.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new l(s>=0?a.uint:a.negint,s,this._pos-e):new l(s>=0?a.uint:a.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${m} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let c=this.data[i];if(c===92||c<32||c>=128)break;if(c===34){let u=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new l(a.string,u,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${m} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let c=this.ch();if(c>=48&&c<=57)c-=48;else if(c>=97&&c<=102)c=c-97+10;else if(c>=65&&c<=70)c=c-65+10;else throw new Error(`${m} unexpected unicode escape character at position ${this._pos}`);i=i*16+c,this._pos++}return i},o=()=>{let i=this.ch(),s=null,c=i>239?4:i>223?3:i>191?2:1;if(this._pos+c>this.data.length)throw new Error(`${m} unexpected unicode sequence at position ${this._pos}`);let u,d,f,h;switch(c){case 1:i<128&&(s=i);break;case 2:u=this.data[this._pos+1],(u&192)===128&&(h=(i&31)<<6|u&63,h>127&&(s=h));break;case 3:u=this.data[this._pos+1],d=this.data[this._pos+2],(u&192)===128&&(d&192)===128&&(h=(i&15)<<12|(u&63)<<6|d&63,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:u=this.data[this._pos+1],d=this.data[this._pos+2],f=this.data[this._pos+3],(u&192)===128&&(d&192)===128&&(f&192)===128&&(h=(i&15)<<18|(u&63)<<12|(d&63)<<6|f&63,h>65535&&h<1114112&&(s=h))}s===null?(s=65533,c=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=c};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${m} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${m} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new l(a.string,en(t),this._pos-e);default:if(i<32)throw new Error(`${m} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${m} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new l(a.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new l(a.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new l(a.null,null,4);case 102:return this.expect([102,97,108,115,101]),new l(a.false,!1,5);case 116:return this.expect([116,114,117,101]),new l(a.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${m} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new l(a.break,void 0,1);if(this.ch()!==44)throw new Error(`${m} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new l(a.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new l(a.break,void 0,1);if(this.ch()!==44)throw new Error(`${m} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new l(a.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${m} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${m} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function In(r,e){return e=Object.assign({tokenizer:new Ve(r,e)},e),X(r,e)}function eu(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function tu(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=v.asCID(r);if(!e)return null;let t=e.toString();return[new l(a.map,1/0,1),new l(a.string,"/",1),new l(a.string,t,t.length),new l(a.break,void 0,1)]}function sr(r){let e=pe.encode(r).slice(1);return[new l(a.map,1/0,1),new l(a.string,"/",1),new l(a.map,1/0,1),new l(a.string,"bytes",5),new l(a.string,e,e.length),new l(a.break,void 0,1),new l(a.break,void 0,1)]}function Y(r){return sr(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function ru(r){return sr(new Uint8Array(r))}function nu(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function ou(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var iu={typeEncoders:{Object:tu,Buffer:sr,Uint8Array:sr,Int8Array:Y,Uint16Array:Y,Int16Array:Y,Uint32Array:Y,Int32Array:Y,Float32Array:Y,Float64Array:Y,Uint8ClampedArray:Y,BigInt64Array:Y,BigUint64Array:Y,DataView:Y,ArrayBuffer:ru,undefined:nu,number:ou}},Tn=class extends Ve{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===a.map){let t=this._next();if(t.type===a.string&&t.value==="/"){let n=this._next();if(n.type===a.string){if(this._next().type!==a.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new l(a.tag,42,0)}if(n.type===a.map){let o=this._next();if(o.type===a.string&&o.value==="bytes"){let i=this._next();if(i.type===a.string){for(let c=0;c<2;c++)if(this._next().type!==a.break)throw new Error("Invalid encoded Bytes form");let s=pe.decode(`m${i.value}`);return new l(a.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Pn={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Pn.tags[42]=v.parse;var su="dag-json",Ln=297,Yi=r=>Sn(r,iu),Zi=r=>{let e=eu(r),t=Object.assign(Pn,{tokenizer:new Tn(e,Pn)});return In(e,t)},au=r=>cu.decode(Yi(r));var cu=new TextDecoder,uu=r=>Zi(lu.encode(r)),lu=new TextEncoder;var zn={};T(zn,{code:()=>$n,createLink:()=>us,createNode:()=>cs,decode:()=>vu,encode:()=>_u,name:()=>Eu,prepare:()=>Bn,validate:()=>Fn});var fu=new TextDecoder;function Dn(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function ar(r,e){let t;[t,e]=Dn(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function es(r,e){let t;return[t,e]=Dn(r,e),[t&7,t>>3,e]}function du(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=es(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=ar(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=ar(r,n),e.Name=fu.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=Dn(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function ts(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let c,u;if([c,u,t]=es(r,t),c!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${c}`);if(u===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=ar(r,t),n&&(o=!0)}else if(u===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let d;[d,t]=ar(r,t),n.push(du(d))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${u}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var ns=new TextEncoder,rs=2**32,hu=2**31;function pu(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=at(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=ns.encode(r.Name);t-=n.length,e.set(n,t),t=at(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=at(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function os(r){let e=gu(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=at(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=pu(r.Links[o],t.subarray(0,n));n-=i,n=at(t,n,i)-1,t[n]=18}return t}function mu(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+He(t)}if(typeof r.Name=="string"){let t=ns.encode(r.Name).length;e+=1+t+He(t)}return typeof r.Tsize=="number"&&(e+=1+He(r.Tsize)),e}function gu(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+He(t)}if(r.Links)for(let t of r.Links){let n=mu(t);e+=1+n+He(n)}return e}function at(r,e,t){e-=He(t);let n=e;for(;t>=hu;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function He(r){return r%2===0&&r++,Math.floor((yu(r)+6)/7)}function yu(r){let e=0;return r>=rs&&(r=Math.floor(r/rs),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+wu[r]}var wu=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var xu=["Data","Links"],bu=["Hash","Name","Tsize"],Un=new TextEncoder;function ss(r,e){if(r===e)return 0;let t=r.Name?Un.encode(r.Name):[],n=e.Name?Un.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,c=Math.min(o,i);s<c;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function is(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function as(r){if(typeof r.asCID=="object"){let t=v.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=v.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=v.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=v.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Bn(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=Un.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(as),e.Links.sort(ss);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Fn(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!is(r,xu))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!is(t,bu))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&ss(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function cs(r,e=[]){return Bn({Data:r,Links:e})}function us(r,e,t){return as({Hash:t,Name:r,Tsize:e})}function ls(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var Eu="dag-pb",$n=112;function _u(r){Fn(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),os(e)}function vu(r){let e=ls(r),t=ts(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=v.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function Ke(r){return r?.then!=null}function fs(r=[],e){let t={[$n]:zn,[Rr]:bt,[kn]:Cn,[Ln]:Nn,[Mr]:xt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ke(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new er(`Could not load codec for ${n}`)}}function ds(r=[],e){let t={[vt.code]:vt,[kt.code]:kt,[_t.code]:_t};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ke(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new Zt(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}function te(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var cr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var ur=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var lr=0,fr=class extends ur{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===lr||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===lr)return e.multihash.digest;if(this.child==null)throw new cr;return this.child.get(e)}has(e){return e.multihash.code===lr?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==lr&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function ku(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var dr=ku;function Cu(r){return r[Symbol.asyncIterator]!=null}function Au(r,e){let t=0;if(Cu(r))return async function*(){for await(let u of r)await e(u,t++)&&(yield u)}();let n=dr(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let u of n)await e(u,t++)&&(yield u)}();let c=e;return function*(){s===!0&&(yield o);for(let u of n)c(u,t++)&&(yield u)}()}var hs=Au;function Su(r){return r[Symbol.asyncIterator]!=null}function ps(r){return r?.then!=null}function Iu(r,e){let t=0;if(Su(r))return async function*(){for await(let u of r){let d=e(u,t++);ps(d)&&await d,yield u}}();let n=dr(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let u of n){let d=e(u,t++);ps(d)&&await d,yield u}}();let c=e;return function*(){yield o;for(let u of n)c(u,t++),yield u}()}var Mn=Iu;var hr=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new fr(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new b("blocks:put:duplicate",e)),e):(n.onProgress?.(new b("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new b("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=hs(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new b("blocks:put-many:duplicate",i)),!s}),o=Mn(n,async({cid:i,block:s})=>{t.onProgress?.(new b("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async c=>c.announce?.(i,s,t)))});t.onProgress?.(new b("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new b("blocks:get:providers:get",e));let o=await ms(e,this.components.blockBrokers,n,{...t,log:this.log});return t.onProgress?.(new b("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new b("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,o,t))),o}return t.onProgress?.(new b("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new b("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Mn(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new b("blocks:get-many:providers:get",n));let i=await ms(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new b("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t),t.onProgress?.(new b("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,i,t)))}}))}async delete(e,t={}){t.onProgress?.(new b("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new b("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new b("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},pr=class extends hr{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await le(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await fe(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Rn({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},Rn=class extends hr{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=te([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=te([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=te([this.closeController.signal,t.signal]);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=te([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=te([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=te([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=te([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=te([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function Tu(r){return typeof r.retrieve=="function"}var Pu=(r,e)=>{if(e==null)throw new ft(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t);if(Ke(o)?n=await o:n=o,!ve(n.digest,r.multihash.digest))throw new ht("Hash of downloaded block did not match multihash from passed CID")}};async function ms(r,e,t,n){let o=Pu(r,t),i=new AbortController,s=te([i.signal,n.signal]);i.signal;let c=[];for(let u of e)Tu(u)&&c.push(u);try{return await Promise.any(c.map(async u=>{try{let d=!1,f=await u.retrieve(r,{...n,signal:s,validateFn:async h=>{await o(h),d=!0}});return d||await o(f),f}catch(d){throw n.log.error("could not retrieve verified block for %c",r,d),d}}))}finally{i.abort(),s.clear()}}var On={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},gs={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ys=new globalThis.TextEncoder;function Lu(r,e){let t=On[e],n=gs[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Nu(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=On[e],o=gs[e],i=r;for(;i.length>0;){let s=ys.encodeInto(i,t);i=i.slice(s.read);for(let c=0;c<s.written;c++)o^=BigInt(t[c]),o=BigInt.asUintN(e,o*n)}return o}function qn(r,{size:e=32,utf8Buffer:t}={}){if(!On[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Nu(r,e,t);r=ys.encode(r)}return Lu(r,e)}var ct={hash:r=>Number(qn(r,{size:32})),hashV:(r,e)=>Du(ct.hash(r,e))};function Du(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),B(e,"base16")}var jn=64,Z=class{fp;h;seed;constructor(e,t,n,o=2){if(o>jn)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=_o(o);for(let c=0;c<s.length;c++)s[c]=i[c];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ve(this.fp,e.fp):!1}};function Se(r,e){return Math.floor(Math.random()*(e-r))+r}var Ie=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Z))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Z))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Z))throw new TypeError("Invalid Fingerprint");let t=Se(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Z))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Uu=500,ut=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??ct,this.seed=e.seed??Se(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=B(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ie(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ie(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[Se(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ie(this.bucketSize));for(let c=0;c<Uu;c++){let u=this.buckets[s].swap(t);if(u!=null&&(s=(s^u.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Ie(this.bucketSize)),this.buckets[s].add(u)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=B(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=B(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Bu={1:.5,2:.84,4:.95,8:.98};function Fu(r=.001){return r>.002?2:r>1e-5?4:8}function ws(r,e=.001){let t=Fu(e),n=Bu[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),jn);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var mr=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??ct,this.seed=e.seed??Se(0,Math.pow(2,10)),this.filterSeries=[new ut({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=B(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new ut({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=B(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=B(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Vn(r,e=.001,t){return new mr({...ws(r,e),...t??{}})}var gr=class extends Pe{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Vn(this.maxProviders)}async retrieve(e,t={}){let n=pe.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=oe();if(this.requests.set(n,i.promise),this.providers.length===0){let d=!1;this.intialPeerSearchComplete==null&&(d=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,d&&this.log("found initial session peers for %c",e)}let s=!1,c=new ie({concurrency:this.maxProviders});c.addEventListener("error",()=>{}),c.addEventListener("failure",d=>{this.log.error("error querying provider %o, evicting from session",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),c.addEventListener("success",d=>{s=!0,i.resolve(d.detail.result)}),c.addEventListener("idle",()=>{s||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c",e,d),i.reject(d)})});let u=d=>{c.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,f)})};this.addEventListener("provider",u),Promise.all([...this.providers].map(async d=>c.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,d)});try{return await i.promise}finally{this.removeEventListener("provider",u),c.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=oe(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new Yt(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var Hn=class{blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??no(),this.log=this.logger.forComponent("helia"),this.getHasher=ds(e.hashers,e.loadHasher),this.getCodec=fs(e.codecs,e.loadCodec),this.dns=e.dns??Lo(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new nr(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[yr]!=null&&i.push(o[yr]),o[wr]!=null&&i.push(o[wr]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new pr(t);this.pins=new Xt(e.datastore,n,this.getCodec),this.blockstore=new or(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await Qi(this.datastore),await le(this.blockstore,this.datastore,this.routing)}async stop(){await fe(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await No(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new b("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new b("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};return ks(Mu);})();
|
|
3
3
|
return HeliaUtils}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@helia/utils",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.1-2c7185c",
|
|
4
4
|
"description": "Shared code that implements the Helia API",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/ipfs/helia/tree/main/packages/utils#readme",
|
|
@@ -54,13 +54,13 @@
|
|
|
54
54
|
"test:electron-main": "aegir test -t electron-main"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@helia/interface": "
|
|
57
|
+
"@helia/interface": "5.2.0-2c7185c",
|
|
58
58
|
"@ipld/dag-cbor": "^9.2.2",
|
|
59
59
|
"@ipld/dag-json": "^10.2.3",
|
|
60
60
|
"@ipld/dag-pb": "^4.1.3",
|
|
61
|
-
"@libp2p/interface": "^2.
|
|
62
|
-
"@libp2p/logger": "^5.1.
|
|
63
|
-
"@libp2p/utils": "^6.
|
|
61
|
+
"@libp2p/interface": "^2.5.0",
|
|
62
|
+
"@libp2p/logger": "^5.1.8",
|
|
63
|
+
"@libp2p/utils": "^6.5.1",
|
|
64
64
|
"@multiformats/dns": "^1.0.6",
|
|
65
65
|
"any-signal": "^4.1.1",
|
|
66
66
|
"blockstore-core": "^5.0.2",
|
package/dist/typedoc-urls.json
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"AbstractSession": "https://ipfs.github.io/helia/classes/_helia_utils.AbstractSession.html",
|
|
3
|
-
"BlockStorage": "https://ipfs.github.io/helia/classes/_helia_utils.BlockStorage.html",
|
|
4
|
-
"Helia": "https://ipfs.github.io/helia/classes/_helia_utils.Helia.html",
|
|
5
|
-
".:Helia": "https://ipfs.github.io/helia/classes/_helia_utils.Helia.html",
|
|
6
|
-
"AbstractCreateSessionOptions": "https://ipfs.github.io/helia/interfaces/_helia_utils.AbstractCreateSessionOptions.html",
|
|
7
|
-
"AbstractSessionComponents": "https://ipfs.github.io/helia/interfaces/_helia_utils.AbstractSessionComponents.html",
|
|
8
|
-
"BlockStorageInit": "https://ipfs.github.io/helia/interfaces/_helia_utils.BlockStorageInit.html",
|
|
9
|
-
"BlockstoreSessionEvents": "https://ipfs.github.io/helia/interfaces/_helia_utils.BlockstoreSessionEvents.html",
|
|
10
|
-
"HeliaInit": "https://ipfs.github.io/helia/interfaces/_helia_utils.HeliaInit.html",
|
|
11
|
-
".:HeliaInit": "https://ipfs.github.io/helia/interfaces/_helia_utils.HeliaInit.html"
|
|
12
|
-
}
|