@helia/utils 2.5.1 → 2.5.2-6f8165b5

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 CHANGED
@@ -1,4 +1,4 @@
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 _l=Object.create;var Or=Object.defineProperty;var vl=Object.getOwnPropertyDescriptor;var kl=Object.getOwnPropertyNames;var Al=Object.getPrototypeOf,Tl=Object.prototype.hasOwnProperty;var Os=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),O=(t,e)=>{for(var r in e)Or(t,r,{get:e[r],enumerable:!0})},Ms=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kl(e))!Tl.call(t,o)&&o!==r&&Or(t,o,{get:()=>e[o],enumerable:!(n=vl(e,o))||n.enumerable});return t};var Fs=(t,e,r)=>(r=t!=null?_l(Al(t)):{},Ms(e||!t||!t.__esModule?Or(r,"default",{value:t,enumerable:!0}):r,t)),Il=t=>Ms(Or({},"__esModule",{value:!0}),t);var Hs=Os((bg,jo)=>{"use strict";var Nl=Object.prototype.hasOwnProperty,K="~";function Yt(){}Object.create&&(Yt.prototype=Object.create(null),new Yt().__proto__||(K=!1));function Cl(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function Vs(t,e,r,n,o){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new Cl(r,n||t,o),s=K?K+e:e;return t._events[s]?t._events[s].fn?t._events[s]=[t._events[s],i]:t._events[s].push(i):(t._events[s]=i,t._eventsCount++),t}function jr(t,e){--t._eventsCount===0?t._events=new Yt:delete t._events[e]}function V(){this._events=new Yt,this._eventsCount=0}V.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Nl.call(r,n)&&e.push(K?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};V.prototype.listeners=function(e){var r=K?K+e:e,n=this._events[r];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};V.prototype.listenerCount=function(e){var r=K?K+e:e,n=this._events[r];return n?n.fn?1:n.length:0};V.prototype.emit=function(e,r,n,o,i,s){var a=K?K+e:e;if(!this._events[a])return!1;var c=this._events[a],f=arguments.length,p,m;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),f){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,o),!0;case 5:return c.fn.call(c.context,r,n,o,i),!0;case 6:return c.fn.call(c.context,r,n,o,i,s),!0}for(m=1,p=new Array(f-1);m<f;m++)p[m-1]=arguments[m];c.fn.apply(c.context,p)}else{var x=c.length,A;for(m=0;m<x;m++)switch(c[m].once&&this.removeListener(e,c[m].fn,void 0,!0),f){case 1:c[m].fn.call(c[m].context);break;case 2:c[m].fn.call(c[m].context,r);break;case 3:c[m].fn.call(c[m].context,r,n);break;case 4:c[m].fn.call(c[m].context,r,n,o);break;default:if(!p)for(A=1,p=new Array(f-1);A<f;A++)p[A-1]=arguments[A];c[m].fn.apply(c[m].context,p)}}return!0};V.prototype.on=function(e,r,n){return Vs(this,e,r,n,!1)};V.prototype.once=function(e,r,n){return Vs(this,e,r,n,!0)};V.prototype.removeListener=function(e,r,n,o){var i=K?K+e:e;if(!this._events[i])return this;if(!r)return jr(this,i),this;var s=this._events[i];if(s.fn)s.fn===r&&(!o||s.once)&&(!n||s.context===n)&&jr(this,i);else{for(var a=0,c=[],f=s.length;a<f;a++)(s[a].fn!==r||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:jr(this,i)}return this};V.prototype.removeAllListeners=function(e){var r;return e?(r=K?K+e:e,this._events[r]&&jr(this,r)):(this._events=new Yt,this._eventsCount=0),this};V.prototype.off=V.prototype.removeListener;V.prototype.addListener=V.prototype.on;V.prefixed=K;V.EventEmitter=V;typeof jo<"u"&&(jo.exports=V)});var ya=Os((Ry,ga)=>{ga.exports=function(t){if(!t)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,r=Object.create(null),n=Object.create(null);function o(i,s){r[i]=s,e++,e>=t&&(e=0,n=r,r=Object.create(null))}return{has:function(i){return r[i]!==void 0||n[i]!==void 0},remove:function(i){r[i]!==void 0&&(r[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=r[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){r[i]!==void 0?r[i]=s:o(i,s)},clear:function(){r=Object.create(null),n=Object.create(null)}}}});var lg={};O(lg,{AbstractSession:()=>zo,Helia:()=>$s,breadthFirstWalker:()=>bl,depthFirstWalker:()=>xl,naturalOrderWalker:()=>El});var zs=Symbol.for("@libp2p/content-routing");var xe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var xt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Mr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var Fr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var js=Symbol.for("@libp2p/peer-routing");function qs(t){return t!=null&&typeof t.start=="function"&&typeof t.stop=="function"}async function Ke(...t){let e=[];for(let r of t)qs(r)&&e.push(r);await Promise.all(e.map(async r=>{r.beforeStart!=null&&await r.beforeStart()})),await Promise.all(e.map(async r=>{await r.start()})),await Promise.all(e.map(async r=>{r.afterStart!=null&&await r.afterStart()}))}async function We(...t){let e=[];for(let r of t)qs(r)&&e.push(r);await Promise.all(e.map(async r=>{r.beforeStop!=null&&await r.beforeStop()})),await Promise.all(e.map(async r=>{await r.stop()})),await Promise.all(e.map(async r=>{r.afterStop!=null&&await r.afterStop()}))}function Sl(t){return typeof t?.handleEvent=="function"}function Ul(t){return(t!==!0&&t!==!1&&t?.once)??!1}var le=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let o=Ul(n);super.addEventListener(e,s=>{if(o){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==r),this.#e.set(s.type,a))}Sl(r)?r.handleEvent(s):r(s)},n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:r,once:o})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==r),this.#e.set(e,o))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var T=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var zr=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var qo=Fs(Hs(),1);var Vo=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},Ks=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function Xt(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=e,a,c,p=new Promise((m,x)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(s?.aborted){x(Ks(s));return}if(s&&(c=()=>{x(Ks(s))},s.addEventListener("abort",c,{once:!0})),t.then(m,x),r===Number.POSITIVE_INFINITY)return;let A=new Vo;a=i.setTimeout.call(void 0,()=>{if(n){try{m(n())}catch(I){x(I)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?m():o instanceof Error?x(o):(A.message=o??`Promise timed out after ${r} milliseconds`,x(A))},r)}).finally(()=>{p.clear(),c&&s&&s.removeEventListener("abort",c)});return p.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},p}function Ho(t,e,r){let n=0,o=t.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;r(t[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var bt=class{#e=[];enqueue(e,r){let{priority:n=0,id:o}=r??{},i={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(i);return}let s=Ho(this.#e,i,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,i)}setPriority(e,r){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:r,id:e})}remove(e){let r=this.#e.findIndex(n=>typeof e=="string"?n.id===e:n.run===e);r!==-1&&this.#e.splice(r,1)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}};var Zt=class extends qo.default{#e;#o;#a=0;#h;#m=!1;#x=!1;#c;#I=0;#b=0;#u;#f;#s;#i=[];#n=0;#t;#S;#r=0;#g;#l;#B=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:bt,strict:!1,...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})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#o=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#c=e.interval,this.#s=e.strict,this.#t=new e.queueClass,this.#S=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#l=e.autoStart===!1,this.#z()}#_(e){for(;this.#n<this.#i.length;){let n=this.#i[this.#n];if(n!==void 0&&e-n>=this.#c)this.#n++;else break}(this.#n>100&&this.#n>this.#i.length/2||this.#n===this.#i.length)&&(this.#i=this.#i.slice(this.#n),this.#n=0)}#R(e){this.#s?this.#i.push(e):this.#a++}#D(){this.#s?this.#i.length>this.#n&&this.#i.pop():this.#a>0&&this.#a--}#v(){return this.#i.length-this.#n}get#P(){return this.#o?!0:this.#s?this.#v()<this.#h:this.#a<this.#h}get#$(){return this.#r<this.#g}#O(){this.#r--,this.#r===0&&this.emit("pendingZero"),this.#w(),this.emit("next")}#M(){this.#f=void 0,this.#C(),this.#N()}#F(e){if(this.#s){if(this.#_(e),this.#v()>=this.#h){let n=this.#i[this.#n],o=this.#c-(e-n);return this.#k(o),!0}return!1}if(this.#u===void 0){let r=this.#I-e;if(r<0){if(this.#b>0){let n=e-this.#b;if(n<this.#c)return this.#k(this.#c-n),!0}this.#a=this.#e?this.#r:0}else return this.#k(r),!0}return!1}#k(e){this.#f===void 0&&(this.#f=setTimeout(()=>{this.#M()},e))}#A(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#U(){this.#f&&(clearTimeout(this.#f),this.#f=void 0)}#w(){if(this.#t.size===0){if(this.#A(),this.emit("empty"),this.#r===0){if(this.#U(),this.#s&&this.#n>0){let r=Date.now();this.#_(r)}this.emit("idle")}return!1}let e=!1;if(!this.#l){let r=Date.now(),n=!this.#F(r);if(this.#P&&this.#$){let o=this.#t.dequeue();this.#o||(this.#R(r),this.#p()),this.emit("active"),o(),n&&this.#N(),e=!0}}return e}#N(){this.#o||this.#u!==void 0||this.#s||(this.#u=setInterval(()=>{this.#C()},this.#c),this.#I=Date.now()+this.#c)}#C(){this.#s||(this.#a===0&&this.#r===0&&this.#u&&this.#A(),this.#a=this.#e?this.#r:0),this.#T(),this.#p()}#T(){for(;this.#w(););}get concurrency(){return this.#g}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.#g=e,this.#T()}setPriority(e,r){if(typeof r!="number"||!Number.isFinite(r))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${r}\` (${typeof r})`);this.#t.setPriority(e,r)}async add(e,r={}){return r={timeout:this.timeout,...r,id:r.id??(this.#B++).toString()},new Promise((n,o)=>{let i=Symbol(`task-${r.id}`),s=()=>{},a=async()=>{s(),this.#r++,this.#y.set(i,{id:r.id,priority:r.priority??0,startTime:Date.now(),timeout:r.timeout});let f;try{try{r.signal?.throwIfAborted()}catch(x){throw this.#j(),this.#y.delete(i),x}this.#b=Date.now();let p=e({signal:r.signal});if(r.timeout&&(p=Xt(Promise.resolve(p),{milliseconds:r.timeout,message:`Task timed out after ${r.timeout}ms (queue has ${this.#r} running, ${this.#t.size} waiting)`})),r.signal){let{signal:x}=r;p=Promise.race([p,new Promise((A,I)=>{f=()=>{I(x.reason)},x.addEventListener("abort",f,{once:!0})})])}let m=await p;n(m),this.emit("completed",m)}catch(p){o(p),this.emit("error",p)}finally{f&&r.signal?.removeEventListener("abort",f),this.#y.delete(i),queueMicrotask(()=>{this.#O()})}};this.#t.enqueue(a,r);let c=()=>{if(this.#t instanceof bt){this.#t.remove(a);return}this.#t.remove?.(r.id)};if(r.signal){let{signal:f}=r,p=()=>{s(),c(),o(f.reason),this.#w(),this.emit("next")};if(s=()=>{f.removeEventListener("abort",p),this.#E.delete(s)},f.aborted){p();return}f.addEventListener("abort",p,{once:!0}),this.#E.add(s)}this.emit("add"),this.#w()})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this.#l?(this.#l=!1,this.#T(),this):this}pause(){this.#l=!0}clear(){for(let e of this.#E)e();this.#t=new this.#S,this.#A(),this.#L(),this.emit("empty"),this.#r===0&&(this.#U(),this.emit("idle")),this.emit("next")}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.#r===0&&this.#t.size===0||await this.#d("idle")}async onPendingZero(){this.#r!==0&&await this.#d("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#d("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#d("rateLimitCleared")}onError(){return new Promise((e,r)=>{let n=o=>{this.off("error",n),r(o)};this.on("error",n)})}async#d(e,r){return new Promise(n=>{let o=()=>{r&&!r()||(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.#r}get isPaused(){return this.#l}#z(){this.#o||(this.on("add",()=>{this.#t.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#o||this.#x||(this.#x=!0,queueMicrotask(()=>{this.#x=!1,this.#L()}))}#j(){this.#o||(this.#D(),this.#p())}#L(){let e=this.#m;if(this.#o||this.#t.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let r;if(this.#s){let o=Date.now();this.#_(o),r=this.#v()}else r=this.#a;let n=r>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#r===this.#g&&this.#t.size>0||this.isRateLimited&&this.#t.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e}))}};function qr(t){let e=[be.A];return t==null?e:Array.isArray(t)?t.length===0?e:t:[t]}var Yo={};O(Yo,{base10:()=>Ol});var Lg=new Uint8Array(0);function Ws(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Ee(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Gs(t){return new TextEncoder().encode(t)}function Qs(t){return new TextDecoder().decode(t)}function Ll(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var i=t.charAt(o),s=i.charCodeAt(0);if(r[s]!==255)throw new TypeError(i+" is ambiguous");r[s]=o}var a=t.length,c=t.charAt(0),f=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function m(I){if(I instanceof Uint8Array||(ArrayBuffer.isView(I)?I=new Uint8Array(I.buffer,I.byteOffset,I.byteLength):Array.isArray(I)&&(I=Uint8Array.from(I))),!(I instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(I.length===0)return"";for(var D=0,S=0,$=0,H=I.length;$!==H&&I[$]===0;)$++,D++;for(var q=(H-$)*p+1>>>0,Q=new Uint8Array(q);$!==H;){for(var fe=I[$],He=0,we=q-1;(fe!==0||He<S)&&we!==-1;we--,He++)fe+=256*Q[we]>>>0,Q[we]=fe%a>>>0,fe=fe/a>>>0;if(fe!==0)throw new Error("Non-zero carry");S=He,$++}for(var $e=q-S;$e!==q&&Q[$e]===0;)$e++;for(var $r=c.repeat(D);$e<q;++$e)$r+=t.charAt(Q[$e]);return $r}function x(I){if(typeof I!="string")throw new TypeError("Expected String");if(I.length===0)return new Uint8Array;var D=0;if(I[D]!==" "){for(var S=0,$=0;I[D]===c;)S++,D++;for(var H=(I.length-D)*f+1>>>0,q=new Uint8Array(H);I[D];){var Q=r[I.charCodeAt(D)];if(Q===255)return;for(var fe=0,He=H-1;(Q!==0||fe<$)&&He!==-1;He--,fe++)Q+=a*q[He]>>>0,q[He]=Q%256>>>0,Q=Q/256>>>0;if(Q!==0)throw new Error("Non-zero carry");$=fe,D++}if(I[D]!==" "){for(var we=H-$;we!==H&&q[we]===0;)we++;for(var $e=new Uint8Array(S+(H-we)),$r=S;we!==H;)$e[$r++]=q[we++];return $e}}}function A(I){var D=x(I);if(D)return D;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:x,decode:A}}var Bl=Ll,Rl=Bl,Js=Rl;var Wo=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Go=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.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 Ys(this,e)}},Qo=class{decoders;constructor(e){this.decoders=e}or(e){return Ys(this,e)}decode(e){let r=e[0],n=this.decoders[r];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 Ys(t,e){return new Qo({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Jo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Wo(e,r,n),this.decoder=new Go(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Et({name:t,prefix:e,encode:r,decode:n}){return new Jo(t,e,r,n)}function Ge({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=Js(r,t);return Et({prefix:e,name:t,encode:n,decode:i=>Ee(o(i))})}function Dl(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let i=new Uint8Array(o*r/8|0),s=0,a=0,c=0;for(let f=0;f<o;++f){let p=e[t[f]];if(p===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|p,s+=r,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=r||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function Pl(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,i="",s=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],s+=8;s>r;)s-=r,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<r-s]),n)for(;(i.length*r&7)!==0;)i+="=";return i}function $l(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function P({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=$l(n);return Et({prefix:e,name:t,encode(i){return Pl(i,n,r)},decode(i){return Dl(i,o,r,t)}})}var Ol=Ge({prefix:"9",name:"base10",alphabet:"0123456789"});var Xo={};O(Xo,{base16:()=>Ml,base16upper:()=>Fl});var Ml=P({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Fl=P({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Zo={};O(Zo,{base2:()=>zl});var zl=P({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ei={};O(ei,{base256emoji:()=>Kl});var Xs=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}"),jl=Xs.reduce((t,e,r)=>(t[r]=e,t),[]),ql=Xs.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function Vl(t){return t.reduce((e,r)=>(e+=jl[r],e),"")}function Hl(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=ql[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Kl=Et({prefix:"\u{1F680}",name:"base256emoji",encode:Vl,decode:Hl});var ti={};O(ti,{base32:()=>_t,base32hex:()=>Jl,base32hexpad:()=>Xl,base32hexpadupper:()=>Zl,base32hexupper:()=>Yl,base32pad:()=>Gl,base32padupper:()=>Ql,base32upper:()=>Wl,base32z:()=>ed});var _t=P({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Wl=P({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Gl=P({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ql=P({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Jl=P({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yl=P({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xl=P({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zl=P({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ed=P({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ri={};O(ri,{base36:()=>Oe,base36upper:()=>td});var Oe=Ge({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),td=Ge({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ni={};O(ni,{base58btc:()=>Ce,base58flickr:()=>rd});var Ce=Ge({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rd=Ge({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var oi={};O(oi,{base64:()=>vt,base64pad:()=>nd,base64url:()=>od,base64urlpad:()=>id});var vt=P({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),nd=P({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),od=P({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),id=P({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ii={};O(ii,{base8:()=>sd});var sd=P({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var si={};O(si,{identity:()=>ad});var ad=Et({prefix:"\0",name:"identity",encode:t=>Qs(t),decode:t=>Gs(t)});var Vr={};O(Vr,{code:()=>ai,decode:()=>dd,encode:()=>ld,name:()=>fd});var cd=new TextEncoder,ud=new TextDecoder,fd="json",ai=512;function ld(t){return cd.encode(JSON.stringify(t))}function dd(t){return JSON.parse(ud.decode(t))}var Hr={};O(Hr,{code:()=>ci,decode:()=>md,encode:()=>pd,name:()=>hd});var hd="raw",ci=85;function pd(t){return Ee(t)}function md(t){return Ee(t)}var fi={};O(fi,{identity:()=>Wr});var gd=ta,Zs=128,yd=127,wd=~yd,xd=Math.pow(2,31);function ta(t,e,r){e=e||[],r=r||0;for(var n=r;t>=xd;)e[r++]=t&255|Zs,t/=128;for(;t&wd;)e[r++]=t&255|Zs,t>>>=7;return e[r]=t|0,ta.bytes=r-n+1,e}var bd=ui,Ed=128,ea=127;function ui(t,n){var r=0,n=n||0,o=0,i=n,s,a=t.length;do{if(i>=a)throw ui.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=o<28?(s&ea)<<o:(s&ea)*Math.pow(2,o),o+=7}while(s>=Ed);return ui.bytes=i-n,r}var _d=Math.pow(2,7),vd=Math.pow(2,14),kd=Math.pow(2,21),Ad=Math.pow(2,28),Td=Math.pow(2,35),Id=Math.pow(2,42),Sd=Math.pow(2,49),Ud=Math.pow(2,56),Nd=Math.pow(2,63),Cd=function(t){return t<_d?1:t<vd?2:t<kd?3:t<Ad?4:t<Td?5:t<Id?6:t<Sd?7:t<Ud?8:t<Nd?9:10},Ld={encode:gd,decode:bd,encodingLength:Cd},Bd=Ld,er=Bd;function tr(t,e=0){return[er.decode(t,e),er.decode.bytes]}function kt(t,e,r=0){return er.encode(t,e,r),e}function At(t){return er.encodingLength(t)}function It(t,e){let r=e.byteLength,n=At(t),o=n+At(r),i=new Uint8Array(o+r);return kt(t,i,0),kt(r,i,n),i.set(e,o),new Tt(t,r,e,i)}function ra(t){let e=Ee(t),[r,n]=tr(e),[o,i]=tr(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Tt(r,o,s,e)}function na(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Ws(t.bytes,r.bytes)}}var Tt=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var oa=0,Rd="identity",ia=Ee;function Dd(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return It(oa,ia(t))}var Wr={code:oa,name:Rd,encode:ia,digest:Dd};var hi={};O(hi,{sha256:()=>Gr,sha512:()=>Qr});var Pd=20;function di({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new li(t,e,r,n,o)}var li=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,i){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Pd,this.maxDigestLength=i}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?sa(n,this.code,r?.truncate):n.then(o=>sa(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function sa(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return It(e,t)}function ca(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var Gr=di({name:"sha2-256",code:18,encode:ca("SHA-256")}),Qr=di({name:"sha2-512",code:19,encode:ca("SHA-512")});function ua(t,e){let{bytes:r,version:n}=t;return n===0?Od(r,pi(t),e??Ce.encoder):Md(r,pi(t),e??_t.encoder)}var fa=new WeakMap;function pi(t){let e=fa.get(t);if(e==null){let r=new Map;return fa.set(t,r),r}return e}var L=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,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:r}=this;if(e!==nr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Fd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:r}=this.multihash,n=It(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&na(e.multihash,n.multihash)}toString(e){return ua(this,e)}toJSON(){return{"/":ua(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 r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:i,bytes:s}=r;return new t(n,o,i,s??la(n,o,i.bytes))}else if(r[zd]===!0){let{version:n,multihash:o,code:i}=r,s=ra(o);return t.create(n,i,s)}else return null}static create(e,r,n){if(typeof r!="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(r!==nr)throw new Error(`Version 0 CID must use dag-pb (code: ${nr}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=la(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,nr,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=Ee(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let i=o.subarray(r.multihashSize-r.digestSize),s=new Tt(r.multihashCode,r.digestSize,i,o);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[m,x]=tr(e.subarray(r));return r+=x,m},o=n(),i=nr;if(o===18?(o=0,r=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=r,a=n(),c=n(),f=r+c,p=f-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:p,size:f}}static parse(e,r){let[n,o]=$d(e,r),i=t.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return pi(i).set(n,e),i}};function $d(t,e){switch(t[0]){case"Q":{let r=e??Ce;return[Ce.prefix,r.decode(`${Ce.prefix}${t}`)]}case Ce.prefix:{let r=e??Ce;return[Ce.prefix,r.decode(t)]}case _t.prefix:{let r=e??_t;return[_t.prefix,r.decode(t)]}case Oe.prefix:{let r=e??Oe;return[Oe.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function Od(t,e,r){let{prefix:n}=r;if(n!==Ce.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let i=r.encode(t).slice(1);return e.set(n,i),i}else return o}function Md(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let i=r.encode(t);return e.set(n,i),i}else return o}var nr=112,Fd=18;function la(t,e,r){let n=At(t),o=n+At(e),i=new Uint8Array(o+r.byteLength);return kt(t,i,0),kt(e,i,n),i.set(r,o),i}var zd=Symbol.for("@ipld/js-cid/CID");var mi={...si,...Zo,...ii,...Yo,...Xo,...ti,...ri,...ni,...oi,...ei},my={...hi,...fi};function da(t=0){return new Uint8Array(t)}function Jr(t=0){return new Uint8Array(t)}function pa(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var ha=pa("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),gi=pa("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Jr(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),jd={utf8:ha,"utf-8":ha,hex:mi.base16,latin1:gi,ascii:gi,binary:gi,...mi},Yr=jd;function Qe(t,e="utf8"){let r=Yr[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var yi=60;function Xr(t){return{Status:t.Status??0,TC:t.TC??t.flag_tc??!1,RD:t.RD??t.flag_rd??!1,RA:t.RA??t.flag_ra??!1,AD:t.AD??t.flag_ad??!1,CD:t.CD??t.flag_cd??!1,Question:(t.Question??t.questions??[]).map(e=>({name:e.name,type:be[e.type]})),Answer:(t.Answer??t.answers??[]).map(e=>({name:e.name,type:be[e.type],TTL:e.TTL??e.ttl??yi,data:e.data instanceof Uint8Array?Qe(e.data):e.data}))}}var qd=4;function wi(t,e={}){let r=new Zt({concurrency:e.queryConcurrency??qd});return async(n,o={})=>{let i=o?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),qr(o.types).forEach(c=>{s.append("type",be[c])}),o.onProgress?.(new T("dns:query",n)),i?.("GET %s",`${t}?${s}`);let a=await r.add(async()=>{let c=await fetch(`${t}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(i?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let f=Xr(await c.json());return o.onProgress?.(new T("dns:response",f)),f},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function ma(){return[wi("https://cloudflare-dns.com/dns-query"),wi("https://dns.google/resolve")]}var wa=Fs(ya(),1);var xi=class{lru;constructor(e){this.lru=(0,wa.default)(e)}get(e,r){let n=!0,o=[];for(let i of r){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return Xr({answers:o})}getAnswers(e,r){let n=`${e.toLowerCase()}-${r}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:be[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,r){let n=`${e.toLowerCase()}-${r.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(r.TTL??yi)*1e3,value:r}),this.lru.set(n,o)}remove(e,r){let n=`${e.toLowerCase()}-${r}`;this.lru.remove(n)}clear(){this.lru.clear()}};function xa(t){return new xi(t)}var Vd=1e3,Zr=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=xa(e.cacheSize??Vd),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([r,n])=>{Array.isArray(n)||(n=[n]),r.endsWith(".")||(r=`${r}.`),this.resolvers[r]=n}),this.resolvers["."]==null&&(this.resolvers["."]=ma())}async query(e,r={}){let n=qr(r.types),o=r.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return r.onProgress?.(new T("dns:cache",o)),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(r.signal?.aborted===!0)break;try{let f=await c(e,{...r,logger:this.logger,types:n});for(let p of f.Answer)this.cache.add(e,p);return f}catch(f){a.push(f),r.onProgress?.(new T("dns:error",f))}}throw new zr(a,`DNS lookup of ${e} ${n} failed`)}};var be;(function(t){t[t.A=1]="A",t[t.CNAME=5]="CNAME",t[t.TXT=16]="TXT",t[t.AAAA=28]="AAAA"})(be||(be={}));function ba(t={}){return new Zr(t)}function Hd(t){return t[Symbol.asyncIterator]!=null}function Kd(t){if(Hd(t))return(async()=>{for await(let e of t);})();for(let e of t);}var Ea=Kd;function at(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function bi(t,e){e==null&&(e=t.reduce((o,i)=>o+i.length,0));let r=Jr(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function W(t,e="utf8"){let r=Yr[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}var Ei={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},_a={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},va=new globalThis.TextEncoder;function Wd(t,e){let r=Ei[e],n=_a[e];for(let o=0;o<t.length;o++)n^=BigInt(t[o]),n=BigInt.asUintN(e,n*r);return n}function Gd(t,e,r){if(r.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ei[e],o=_a[e],i=t;for(;i.length>0;){let s=va.encodeInto(i,r);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(r[a]),o=BigInt.asUintN(e,o*n)}return o}function _i(t,{size:e=32,utf8Buffer:r}={}){if(!Ei[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof t=="string"){if(r)return Gd(t,e,r);t=va.encode(t)}return Wd(t,e)}var or={hash:t=>Number(_i(t,{size:32})),hashV:(t,e)=>Qd(or.hash(t,e))};function Qd(t){let e=t.toString(16);return e.length%2===1&&(e=`0${e}`),W(e,"base16")}var vi=64,_e=class{fp;h;seed;constructor(e,r,n,o=2){if(o>vi)throw new TypeError("Invalid Fingerprint Size");let i=r.hashV(e,n),s=da(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=r,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?at(this.fp,e.fp):!1}};function ct(t,e){return Math.floor(Math.random()*(e-t))+t}var ut=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof _e))throw new TypeError("Invalid Fingerprint");return this.contents.some(r=>e.equals(r))}add(e){if(!(e instanceof _e))throw new TypeError("Invalid Fingerprint");for(let r=0;r<this.contents.length;r++)if(this.contents[r]==null)return this.contents[r]=e,!0;return!0}swap(e){if(!(e instanceof _e))throw new TypeError("Invalid Fingerprint");let r=ct(0,this.contents.length-1),n=this.contents[r];return this.contents[r]=e,n}remove(e){if(!(e instanceof _e))throw new TypeError("Invalid Fingerprint");let r=this.contents.findIndex(n=>e.equals(n));return r>-1?(this.contents[r]=null,!0):!1}};var Jd=500,ir=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??or,this.seed=e.seed??ct(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=W(e));let r=new _e(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^r.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ut(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new ut(this.bucketSize)),this.buckets[n].add(r)||this.buckets[o].add(r))return this.count++,!0;let i=[n,o],s=i[ct(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new ut(this.bucketSize));for(let a=0;a<Jd;a++){let c=this.buckets[s].swap(r);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new ut(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=W(e));let r=new _e(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(r)??!1;if(o)return o;let i=(n^r.hash())%this.filterSize;return this.buckets[i]?.has(r)??!1}remove(e){typeof e=="string"&&(e=W(e));let r=new _e(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(r)??!1;if(o)return this.count--,o;let i=(n^r.hash())%this.filterSize,s=this.buckets[i]?.remove(r)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Yd={1:.5,2:.84,4:.95,8:.98};function Xd(t=.001){return t>.002?2:t>1e-5?4:8}function ka(t,e=.001){let r=Xd(e),n=Yd[r],o=Math.round(t/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*r)),vi);return{filterSize:o,bucketSize:r,fingerprintSize:i}}var en=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??or,this.seed=e.seed??ct(0,Math.pow(2,10)),this.filterSeries=[new ir({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=W(e)),this.has(e))return!0;let r=this.filterSeries.find(n=>n.reliable);if(r==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);r=new ir({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(r)}return r.add(e)}has(e){typeof e=="string"&&(e=W(e));for(let r=0;r<this.filterSeries.length;r++)if(this.filterSeries[r].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=W(e));for(let r=0;r<this.filterSeries.length;r++)if(this.filterSeries[r].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,r)=>e+r.count,0)}};function tn(t,e=.001,r){return new en({...ka(t,e),...r??{}})}function G(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var rn=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},St=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new rn(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 r=this.head;this.head=r.next=new rn(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ki=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function nn(t={}){return Zd(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Zd(t,e){e=e??{};let r=e.onEnd,n=new St,o,i,s,a=G(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((S,$)=>{i=H=>{i=null,n.push(H);try{S(t(n))}catch(q){$(q)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=G()})}},f=S=>i!=null?i(S):(n.push(S),o),p=S=>(n=new St,i!=null?i({error:S}):(n.push({error:S}),o)),m=S=>{if(s)return o;if(e?.objectMode!==!0&&S?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:S})},x=S=>s?o:(s=!0,S!=null?p(S):f({done:!0})),A=()=>(n=new St,x(),{done:!0}),I=S=>(x(S),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:A,throw:I,push:m,end:x,get readableLength(){return n.size},onEmpty:async S=>{let $=S?.signal;if($?.throwIfAborted(),n.isEmpty())return;let H,q;$!=null&&(H=new Promise((Q,fe)=>{q=()=>{fe(new ki)},$.addEventListener("abort",q)}));try{await Promise.race([a.promise,H])}finally{q!=null&&$!=null&&$?.removeEventListener("abort",q)}}},r==null)return o;let D=o;return o={[Symbol.asyncIterator](){return this},next(){return D.next()},throw(S){return D.throw(S),r!=null&&(r(S),r=void 0),{done:!0}},return(){return D.return(),r!=null&&(r(),r=void 0),{done:!0}},push:m,end(S){return D.end(S),r!=null&&(r(S),r=void 0),o},get readableLength(){return D.readableLength},onEmpty:S=>D.onEmpty(S)},o}var eh=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function th(t,e,r){let n,o=new Promise((i,s)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:p}=eh(t),m=async(...A)=>{let I=r.multiArgs?A:A[0];if(r.filter)try{if(!await r.filter(I))return}catch(D){n(),s(D);return}c.push(I),r.count===c.length&&(n(),i(c))},x=(...A)=>{n(),s(r.rejectionMultiArgs?A:A[0])};n=()=>{for(let A of a)p(A,m);for(let A of r.rejectionEvents)a.includes(A)||p(A,x)};for(let A of a)f(A,m);for(let A of r.rejectionEvents)a.includes(A)||f(A,x);r.signal&&r.signal.addEventListener("abort",()=>{x(r.signal.reason)},{once:!0}),r.resolveImmediately&&i(c)});if(o.cancel=n,typeof r.timeout=="number"){let i=Xt(o,{milliseconds:r.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function on(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=th(t,e,r),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function Ai(t,e){let r,n=function(){let o=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}var sn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function rh(t){return t.reason}async function Je(t,e,r){if(e==null)return t;let n=r?.translateError??rh;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([t,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var an=class{deferred;signal;constructor(e){this.signal=e,this.deferred=G(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new xe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function nh(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var cn=class{id;fn;options;recipients;status;timeline;controller;constructor(e,r){this.id=nh(),this.status="queued",this.fn=e,this.options=r,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((r,n)=>r&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new xe),this.cleanup())}async join(e={}){let r=new an(e.signal);return this.recipients.push(r),e.signal?.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Je(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(r=>{r.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(r=>{r.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 J=class extends le{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=[],this.emitEmpty=Ai(this.emitEmpty.bind(this),1),this.emitIdle=Ai(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let r of this.queue)if(r.status==="queued"){e=r;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let r=0;r<this.queue.length;r++)if(this.queue[r]===e){this.queue.splice(r,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,r){if(r?.signal?.throwIfAborted(),this.size===this.maxSize)throw new sn;let n=new cn(e,r);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(r).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("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new xe)}),this.clear()}async onEmpty(e){this.size!==0&&await on(this,"empty",e)}async onSizeLessThan(e,r){this.size<e||await on(this,"next",{...r,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await on(this,"idle",e)}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 r=nn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),r.end(c)},o=c=>{c.detail!=null&&r.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new xe("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*r}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function ve(t){let e=new globalThis.AbortController;function r(){let i=t.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}for(let i of t){if(i?.aborted===!0){r();break}i?.addEventListener!=null&&i.addEventListener("abort",r)}function n(){for(let i of t)i?.removeEventListener!=null&&i.removeEventListener("abort",r)}let o=e.signal;return o.clear=n,o}var Ti=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=G(),this.haveNext=G()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=G(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=G(),await Je(this.readNext.promise,r?.signal,r)}};function Aa(){return new Ti}function oh(t){return t[Symbol.asyncIterator]!=null}async function ih(t,e,r){try{await Promise.all(t.map(async n=>{for await(let o of n)await e.push(o,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*sh(t){let e=new AbortController,r=Aa();ih(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*ah(t){for(let e of t)yield*e}function ch(...t){let e=[];for(let r of t)oh(r)||e.push(r);return e.length===t.length?ah(e):sh(t)}var un=ch;var fn=class extends J{has(e){return this.find(e)!=null}find(e){return this.queue.find(r=>e.equals(r.options.peerId))}};var uh=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function Ii(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(t instanceof Uint8Array)return"Uint8Array";if(t.constructor===Object)return"Object";let r=fh(t);return r||"Object"}function fh(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(uh.includes(e))return e}var d=class{constructor(e,r,n){this.major=e,this.majorEncoded=e<<5,this.name=r,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,r){return e===r||e.major===r.major&&e.name===r.name}};d.uint=new d(0,"uint",!0);d.negint=new d(1,"negint",!0);d.bytes=new d(2,"bytes",!0);d.string=new d(3,"string",!0);d.array=new d(4,"array",!1);d.map=new d(5,"map",!1);d.tag=new d(6,"tag",!1);d.float=new d(7,"float",!0);d.false=new d(7,"false",!0);d.true=new d(7,"true",!0);d.null=new d(7,"null",!0);d.undefined=new d(7,"undefined",!0);d.break=new d(7,"break",!0);var _=class{constructor(e,r,n){this.type=e,this.value=r,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var sr=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",lh=new TextEncoder;function ln(t){return sr&&globalThis.Buffer.isBuffer(t)}function ar(t){return t instanceof Uint8Array?ln(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var dh=24,hh=200,dn=sr?t=>t.length>=dh?globalThis.Buffer.from(t):Ta(t):t=>t.length>=hh?lh.encode(t):Ta(t),Le=t=>Uint8Array.from(t),Ia=sr?(t,e,r)=>ln(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Sa=sr?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),ar(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let o of t)n+o.length>r.length&&(o=o.subarray(0,r.length-n)),r.set(o,n),n+=o.length;return r},Ua=sr?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function hn(t,e){if(ln(t)&&ln(e))return t.compare(e);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return 0}function Ta(t){let e=[],r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128)}return e}var ph=256,cr=class{constructor(e=ph){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 r=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=r.length-(this.maxCursor-this.cursor)-1;r.set(e,o)}else{if(r){let o=r.length-(this.maxCursor-this.cursor)-1;o<r.length&&(this.chunks[this.chunks.length-1]=r.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(r=Ua(this.chunkSize),this.chunks.push(r),this.maxCursor+=r.length,this._initReuseChunk===null&&(this._initReuseChunk=r),r.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let r;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(r=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):r=Ia(n,0,this.cursor)}else r=Sa(this.chunks,this.cursor);return e&&this.reset(),r}},pn=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let r=this.dest.subarray(0,this.cursor);return e&&this.reset(),r}};var v="CBOR decode error:",mn="CBOR encode error:",ur=[];ur[23]=1;ur[24]=2;ur[25]=3;ur[26]=5;ur[27]=9;function Me(t,e,r){if(t.length-e<r)throw new Error(`${v} not enough data for type`)}var M=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Y(t,e,r){Me(t,e,1);let n=t[e];if(r.strict===!0&&n<M[0])throw new Error(`${v} integer encoded in more bytes than necessary (strict decode)`);return n}function X(t,e,r){Me(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<M[1])throw new Error(`${v} integer encoded in more bytes than necessary (strict decode)`);return n}function Z(t,e,r){Me(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<M[2])throw new Error(`${v} integer encoded in more bytes than necessary (strict decode)`);return n}function ee(t,e,r){Me(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],o=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(r.strict===!0&&i<M[3])throw new Error(`${v} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(r.allowBigInt===!0)return i;throw new Error(`${v} integers outside of the safe integer range are not supported`)}function Na(t,e,r,n){return new _(d.uint,Y(t,e+1,n),2)}function Ca(t,e,r,n){return new _(d.uint,X(t,e+1,n),3)}function La(t,e,r,n){return new _(d.uint,Z(t,e+1,n),5)}function Ba(t,e,r,n){return new _(d.uint,ee(t,e+1,n),9)}function de(t,e){return B(t,0,e.value)}function B(t,e,r){if(r<M[0]){let n=Number(r);t.push([e|n])}else if(r<M[1]){let n=Number(r);t.push([e|24,n])}else if(r<M[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<M[3]){let n=Number(r);t.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(r);if(n<M[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,t.push(o)}else throw new Error(`${v} encountered BigInt larger than allowable range`)}}de.encodedSize=function(e){return B.encodedSize(e.value)};B.encodedSize=function(e){return e<M[0]?1:e<M[1]?2:e<M[2]?3:e<M[3]?5:9};de.compareTokens=function(e,r){return e.value<r.value?-1:e.value>r.value?1:0};function Ra(t,e,r,n){return new _(d.negint,-1-Y(t,e+1,n),2)}function Da(t,e,r,n){return new _(d.negint,-1-X(t,e+1,n),3)}function Pa(t,e,r,n){return new _(d.negint,-1-Z(t,e+1,n),5)}var Si=BigInt(-1),$a=BigInt(1);function Oa(t,e,r,n){let o=ee(t,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new _(d.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${v} integers outside of the safe integer range are not supported`);return new _(d.negint,Si-BigInt(o),9)}function gn(t,e){let r=e.value,n=typeof r=="bigint"?r*Si-$a:r*-1-1;B(t,e.type.majorEncoded,n)}gn.encodedSize=function(e){let r=e.value,n=typeof r=="bigint"?r*Si-$a:r*-1-1;return n<M[0]?1:n<M[1]?2:n<M[2]?3:n<M[3]?5:9};gn.compareTokens=function(e,r){return e.value<r.value?1:e.value>r.value?-1:0};function fr(t,e,r,n){Me(t,e,r+n);let o=t.slice(e+r,e+r+n);return new _(d.bytes,o,r+n)}function Ma(t,e,r,n){return fr(t,e,1,r)}function Fa(t,e,r,n){return fr(t,e,2,Y(t,e+1,n))}function za(t,e,r,n){return fr(t,e,3,X(t,e+1,n))}function ja(t,e,r,n){return fr(t,e,5,Z(t,e+1,n))}function qa(t,e,r,n){let o=ee(t,e+1,n);if(typeof o=="bigint")throw new Error(`${v} 64-bit integer bytes lengths not supported`);return fr(t,e,9,o)}function yn(t){return t.encodedBytes===void 0&&(t.encodedBytes=d.equals(t.type,d.string)?dn(t.value):t.value),t.encodedBytes}function Ut(t,e){let r=yn(e);B(t,e.type.majorEncoded,r.length),t.push(r)}Ut.encodedSize=function(e){let r=yn(e);return B.encodedSize(r.length)+r.length};Ut.compareTokens=function(e,r){return gh(yn(e),yn(r))};function gh(t,e){return t.length<e.length?-1:t.length>e.length?1:hn(t,e)}var Va=new TextDecoder,wh=32;function xh(t,e,r){if(r-e<wh){let o="";for(let i=e;i<r;i++){let s=t[i];if(s&128)return Va.decode(t.subarray(e,r));o+=String.fromCharCode(s)}return o}return Va.decode(t.subarray(e,r))}function lr(t,e,r,n,o){let i=r+n;Me(t,e,i);let s=new _(d.string,xh(t,e+r,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=t.slice(e+r,e+i)),s}function Ha(t,e,r,n){return lr(t,e,1,r,n)}function Ka(t,e,r,n){return lr(t,e,2,Y(t,e+1,n),n)}function Wa(t,e,r,n){return lr(t,e,3,X(t,e+1,n),n)}function Ga(t,e,r,n){return lr(t,e,5,Z(t,e+1,n),n)}function Qa(t,e,r,n){let o=ee(t,e+1,n);if(typeof o=="bigint")throw new Error(`${v} 64-bit integer string lengths not supported`);return lr(t,e,9,o,n)}var Ja=Ut;function Nt(t,e,r,n){return new _(d.array,n,r)}function Ya(t,e,r,n){return Nt(t,e,1,r)}function Xa(t,e,r,n){return Nt(t,e,2,Y(t,e+1,n))}function Za(t,e,r,n){return Nt(t,e,3,X(t,e+1,n))}function ec(t,e,r,n){return Nt(t,e,5,Z(t,e+1,n))}function tc(t,e,r,n){let o=ee(t,e+1,n);if(typeof o=="bigint")throw new Error(`${v} 64-bit integer array lengths not supported`);return Nt(t,e,9,o)}function rc(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${v} indefinite length items not allowed`);return Nt(t,e,1,1/0)}function wn(t,e){B(t,d.array.majorEncoded,e.value)}wn.compareTokens=de.compareTokens;wn.encodedSize=function(e){return B.encodedSize(e.value)};function Ct(t,e,r,n){return new _(d.map,n,r)}function nc(t,e,r,n){return Ct(t,e,1,r)}function oc(t,e,r,n){return Ct(t,e,2,Y(t,e+1,n))}function ic(t,e,r,n){return Ct(t,e,3,X(t,e+1,n))}function sc(t,e,r,n){return Ct(t,e,5,Z(t,e+1,n))}function ac(t,e,r,n){let o=ee(t,e+1,n);if(typeof o=="bigint")throw new Error(`${v} 64-bit integer map lengths not supported`);return Ct(t,e,9,o)}function cc(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${v} indefinite length items not allowed`);return Ct(t,e,1,1/0)}function xn(t,e){B(t,d.map.majorEncoded,e.value)}xn.compareTokens=de.compareTokens;xn.encodedSize=function(e){return B.encodedSize(e.value)};function uc(t,e,r,n){return new _(d.tag,r,1)}function fc(t,e,r,n){return new _(d.tag,Y(t,e+1,n),2)}function lc(t,e,r,n){return new _(d.tag,X(t,e+1,n),3)}function dc(t,e,r,n){return new _(d.tag,Z(t,e+1,n),5)}function hc(t,e,r,n){return new _(d.tag,ee(t,e+1,n),9)}function bn(t,e){B(t,d.tag.majorEncoded,e.value)}bn.compareTokens=de.compareTokens;bn.encodedSize=function(e){return B.encodedSize(e.value)};var Ui=20,Ni=21,Ci=22,Li=23;function pc(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${v} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new _(d.null,null,1):new _(d.undefined,void 0,1)}function mc(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${v} indefinite length items not allowed`);return new _(d.break,void 0,1)}function Bi(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${v} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${v} Infinity values are not supported`)}return new _(d.float,t,e)}function gc(t,e,r,n){return Bi(Ri(t,e+1),3,n)}function yc(t,e,r,n){return Bi(Di(t,e+1),5,n)}function wc(t,e,r,n){return Bi(_c(t,e+1),9,n)}function dr(t,e,r){let n=e.value;if(n===!1)t.push([d.float.majorEncoded|Ui]);else if(n===!0)t.push([d.float.majorEncoded|Ni]);else if(n===null)t.push([d.float.majorEncoded|Ci]);else if(n===void 0)t.push([d.float.majorEncoded|Li]);else{let o,i=!1;(!r||r.float64!==!0)&&(bc(n),o=Ri(ke,1),n===o||Number.isNaN(n)?(ke[0]=249,t.push(ke.slice(0,3)),i=!0):(Ec(n),o=Di(ke,1),n===o&&(ke[0]=250,t.push(ke.slice(0,5)),i=!0))),i||(kh(n),o=_c(ke,1),ke[0]=251,t.push(ke.slice(0,9)))}}dr.encodedSize=function(e,r){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!r||r.float64!==!0){bc(n);let o=Ri(ke,1);if(n===o||Number.isNaN(n))return 3;if(Ec(n),o=Di(ke,1),n===o)return 5}return 9};var xc=new ArrayBuffer(9),he=new DataView(xc,1),ke=new Uint8Array(xc,0);function bc(t){if(t===1/0)he.setUint16(0,31744,!1);else if(t===-1/0)he.setUint16(0,64512,!1);else if(Number.isNaN(t))he.setUint16(0,32256,!1);else{he.setFloat32(0,t);let e=he.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)he.setUint16(0,31744,!1);else if(r===0)he.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=r-127;o<-24?he.setUint16(0,0):o<-14?he.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):he.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Ri(t,e){if(t.length-e<2)throw new Error(`${v} not enough data for float16`);let r=(t[e]<<8)+t[e+1];if(r===31744)return 1/0;if(r===64512)return-1/0;if(r===32256)return NaN;let n=r>>10&31,o=r&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,r&32768?-i:i}function Ec(t){he.setFloat32(0,t,!1)}function Di(t,e){if(t.length-e<4)throw new Error(`${v} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function kh(t){he.setFloat64(0,t,!1)}function _c(t,e){if(t.length-e<8)throw new Error(`${v} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}dr.compareTokens=de.compareTokens;function U(t,e,r){throw new Error(`${v} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function En(t){return()=>{throw new Error(`${v} ${t}`)}}var g=[];for(let t=0;t<=23;t++)g[t]=U;g[24]=Na;g[25]=Ca;g[26]=La;g[27]=Ba;g[28]=U;g[29]=U;g[30]=U;g[31]=U;for(let t=32;t<=55;t++)g[t]=U;g[56]=Ra;g[57]=Da;g[58]=Pa;g[59]=Oa;g[60]=U;g[61]=U;g[62]=U;g[63]=U;for(let t=64;t<=87;t++)g[t]=Ma;g[88]=Fa;g[89]=za;g[90]=ja;g[91]=qa;g[92]=U;g[93]=U;g[94]=U;g[95]=En("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)g[t]=Ha;g[120]=Ka;g[121]=Wa;g[122]=Ga;g[123]=Qa;g[124]=U;g[125]=U;g[126]=U;g[127]=En("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)g[t]=Ya;g[152]=Xa;g[153]=Za;g[154]=ec;g[155]=tc;g[156]=U;g[157]=U;g[158]=U;g[159]=rc;for(let t=160;t<=183;t++)g[t]=nc;g[184]=oc;g[185]=ic;g[186]=sc;g[187]=ac;g[188]=U;g[189]=U;g[190]=U;g[191]=cc;for(let t=192;t<=215;t++)g[t]=uc;g[216]=fc;g[217]=lc;g[218]=dc;g[219]=hc;g[220]=U;g[221]=U;g[222]=U;g[223]=U;for(let t=224;t<=243;t++)g[t]=En("simple values are not supported");g[244]=U;g[245]=U;g[246]=U;g[247]=pc;g[248]=En("simple values are not supported");g[249]=gc;g[250]=yc;g[251]=wc;g[252]=U;g[253]=U;g[254]=U;g[255]=mc;var Ae=[];for(let t=0;t<24;t++)Ae[t]=new _(d.uint,t,1);for(let t=-1;t>=-24;t--)Ae[31-t]=new _(d.negint,t,1);Ae[64]=new _(d.bytes,new Uint8Array(0),1);Ae[96]=new _(d.string,"",1);Ae[128]=new _(d.array,0,1);Ae[160]=new _(d.map,0,1);Ae[244]=new _(d.false,!1,1);Ae[245]=new _(d.true,!0,1);Ae[246]=new _(d.null,null,1);function Pi(t){switch(t.type){case d.false:return Le([244]);case d.true:return Le([245]);case d.null:return Le([246]);case d.bytes:return t.value.length?void 0:Le([64]);case d.string:return t.value===""?Le([96]):void 0;case d.array:return t.value===0?Le([128]):void 0;case d.map:return t.value===0?Le([160]):void 0;case d.uint:return t.value<24?Le([Number(t.value)]):void 0;case d.negint:if(t.value>=-24)return Le([31-Number(t.value)])}}var Th={float64:!1,mapSorter:Uh,quickEncodeToken:Pi},Ic=Object.freeze({float64:!0,mapSorter:Nh,quickEncodeToken:Pi});function Ih(){let t=[];return t[d.uint.major]=de,t[d.negint.major]=gn,t[d.bytes.major]=Ut,t[d.string.major]=Ja,t[d.array.major]=wn,t[d.map.major]=xn,t[d.tag.major]=bn,t[d.float.major]=dr,t}var Bt=Ih(),_n=new cr,pr=class t{constructor(e,r){this.obj=e,this.parent=r}includes(e){let r=this;do if(r.obj===e)return!0;while(r=r.parent);return!1}static createCheck(e,r){if(e&&e.includes(r))throw new Error(`${mn} object contains circular references`);return new t(r,e)}},Ye={null:new _(d.null,null),undefined:new _(d.undefined,void 0),true:new _(d.true,!0),false:new _(d.false,!1),emptyArray:new _(d.array,0),emptyMap:new _(d.map,0)},Be={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new _(d.float,t):t>=0?new _(d.uint,t):new _(d.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new _(d.uint,t):new _(d.negint,t)},Uint8Array(t,e,r,n){return new _(d.bytes,t)},string(t,e,r,n){return new _(d.string,t)},boolean(t,e,r,n){return t?Ye.true:Ye.false},null(t,e,r,n){return Ye.null},undefined(t,e,r,n){return Ye.undefined},ArrayBuffer(t,e,r,n){return new _(d.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new _(d.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[Ye.emptyArray,new _(d.break)]:Ye.emptyArray;n=pr.createCheck(n,t);let o=[],i=0;for(let s of t)o[i++]=Lt(s,r,n);return r.addBreakTokens?[new _(d.array,t.length),o,new _(d.break)]:[new _(d.array,t.length),o]},Object(t,e,r,n){let o=e!=="Object",i=o?t.keys():Object.keys(t),s=o?t.size:i.length,a;if(s){a=new Array(s),n=pr.createCheck(n,t);let c=!o&&r.ignoreUndefinedProperties,f=0;for(let p of i){let m=o?t.get(p):t[p];c&&m===void 0||(a[f++]=[Lt(p,r,n),Lt(m,r,n)])}f<s&&(a.length=f)}return a?.length?(Sh(a,r),r.addBreakTokens?[new _(d.map,a.length),a,new _(d.break)]:[new _(d.map,a.length),a]):r.addBreakTokens===!0?[Ye.emptyMap,new _(d.break)]:Ye.emptyMap},Tagged(t,e,r,n){return[new _(d.tag,t.tag),Lt(t.value,r,n)]}};Be.Map=Be.Object;Be.Buffer=Be.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Be[`${t}Array`]=Be.DataView;function Lt(t,e={},r){let n=Ii(t),o=e&&e.typeEncoders&&e.typeEncoders[n]||Be[n];if(typeof o=="function"){let s=o(t,n,e,r);if(s!=null)return s}let i=Be[n];if(!i)throw new Error(`${mn} unsupported type: ${n}`);return i(t,n,e,r)}function Sh(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Uh(t,e){let r=Array.isArray(t[0])?t[0][0]:t[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(r.type!==n.type)return r.type.compare(n.type);let o=r.type.major,i=Bt[o].compareTokens(r,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function Nh(t,e){if(t[0]instanceof _&&e[0]instanceof _){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=vc(r.value)),n._keyBytes||(n._keyBytes=vc(n.value)),hn(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function vc(t){return Uc(t,Bt,Ic)}function hr(t,e,r,n){if(Array.isArray(e))for(let o of e)hr(t,o,r,n);else r[e.type.major](t,e,n)}var kc=d.uint.majorEncoded,Ac=d.negint.majorEncoded,Ch=d.bytes.majorEncoded,Lh=d.string.majorEncoded,Tc=d.array.majorEncoded,Bh=d.float.majorEncoded|Ui,Rh=d.float.majorEncoded|Ni,Dh=d.float.majorEncoded|Ci,Ph=d.float.majorEncoded|Li,$h=BigInt(-1),Oh=BigInt(1);function Mh(t){return t.addBreakTokens!==!0}function Sc(t,e,r,n){let o=Ii(e),i=r.typeEncoders&&r.typeEncoders[o];if(i){let s=i(e,o,r,n);if(s!=null){hr(t,s,Bt,r);return}}switch(o){case"null":t.push([Dh]);return;case"undefined":t.push([Ph]);return;case"boolean":t.push([e?Rh:Bh]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?dr(t,new _(d.float,e),r):e>=0?B(t,kc,e):B(t,Ac,e*-1-1);return;case"bigint":e>=BigInt(0)?B(t,kc,e):B(t,Ac,e*$h-Oh);return;case"string":{let s=dn(e);B(t,Lh,s.length),t.push(s);return}case"Uint8Array":B(t,Ch,e.length),t.push(e);return;case"Array":if(!e.length){t.push([Tc]);return}n=pr.createCheck(n,e),B(t,Tc,e.length);for(let s of e)Sc(t,s,r,n);return;case"Object":case"Map":{let s=Be.Object(e,o,r,n);hr(t,s,Bt,r)}return;default:{let s=Be[o];if(!s)throw new Error(`${mn} unsupported type: ${o}`);let a=s(e,o,r,n);hr(t,a,Bt,r)}}}function Uc(t,e,r,n){let o=n instanceof Uint8Array,i=o?new pn(n):_n,s=Lt(t,r);if(!Array.isArray(s)&&r.quickEncodeToken){let a=r.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let f=c.encodedSize(s,r);if(o||(i=new cr(f)),c(i,s,r),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():ar(i.chunks[0])}}return i.reset(),hr(i,s,e,r),i.toBytes(!0)}function mr(t,e){return e=Object.assign({},Th,e),Mh(e)?(_n.reset(),Sc(_n,t,e,void 0),_n.toBytes(!0)):Uc(t,Bt,e)}var Fh={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},vn=class{constructor(e,r={}){this._pos=0,this.data=e,this.options=r}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],r=Ae[e];if(r===void 0){let n=g[e];if(!n)throw new Error(`${v} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;r=n(this.data,this._pos,o,this.options)}return this._pos+=r.encodedLength,r}},Xe=Symbol.for("DONE"),Rt=Symbol.for("BREAK");function zh(t,e,r){let n=[];for(let o=0;o<t.value;o++){let i=Ze(e,r);if(i===Rt){if(t.value===1/0)break;throw new Error(`${v} got unexpected break to lengthed array`)}if(i===Xe)throw new Error(`${v} found array but not enough entries (got ${o}, expected ${t.value})`);n[o]=i}return n}function jh(t,e,r){let n=r.useMaps===!0,o=r.rejectDuplicateMapKeys===!0,i=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<t.value;a++){let c=Ze(e,r);if(c===Rt){if(t.value===1/0)break;throw new Error(`${v} got unexpected break to lengthed map`)}if(c===Xe)throw new Error(`${v} found map but not enough entries (got ${a} [no key], expected ${t.value})`);if(!n&&typeof c!="string")throw new Error(`${v} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${v} found repeat map key "${c}"`);let f=Ze(e,r);if(f===Xe)throw new Error(`${v} found map but not enough entries (got ${a} [no value], expected ${t.value})`);n?s.set(c,f):i[c]=f}return n?s:i}function*qh(t,e,r){for(let n=0;n<t.value;n++){let o=Ze(e,r);if(o===Rt){if(t.value===1/0)break;throw new Error(`${v} got unexpected break to lengthed map`)}if(o===Xe)throw new Error(`${v} found map but not enough entries (got ${n} [no key], expected ${t.value})`);let i=Ze(e,r);if(i===Xe)throw new Error(`${v} found map but not enough entries (got ${n} [no value], expected ${t.value})`);yield[o,i]}}function Vh(t,e){let r=!1,n=function(){if(r)throw new Error(`${v} tag decode() may only be called once`);r=!0;let o=Ze(t,e);if(o===Xe)throw new Error(`${v} tag content missing`);if(o===Rt)throw new Error(`${v} got unexpected break in tag content`);return o};return n.entries=function(){if(r)throw new Error(`${v} tag decode() may only be called once`);r=!0;let o=t.next();if(!d.equals(o.type,d.map))throw new Error(`${v} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of qh(o,t,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return r},enumerable:!1}),n}function Ze(t,e){if(t.done())return Xe;let r=t.next();if(d.equals(r.type,d.break))return Rt;if(r.type.terminal)return r.value;if(d.equals(r.type,d.array))return zh(r,t,e);if(d.equals(r.type,d.map))return jh(r,t,e);if(d.equals(r.type,d.tag)){if(e.tags&&typeof e.tags[r.value]=="function"){let n=Vh(t,e),o=e.tags[r.value](n);if(!n._called)throw new Error(`${v} tag decoder must call decode() or entries()`);return o}throw new Error(`${v} tag not supported (${r.value})`)}throw new Error("unsupported")}function Nc(t,e){if(!(t instanceof Uint8Array))throw new Error(`${v} data to decode must be a Uint8Array`);e=Object.assign({},Fh,e);let r=ar(t),n=e.tokenizer||new vn(r,e),o=Ze(n,e);if(o===Xe)throw new Error(`${v} did not find any content to decode`);if(o===Rt)throw new Error(`${v} got unexpected break`);return[o,t.subarray(n.pos())]}function lt(t,e){let[r,n]=Nc(t,e);if(n.length>0)throw new Error(`${v} too many terminals, data makes no sense`);return r}var kn=class t{constructor(e,r){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=r}static decoder(e){return r=>new t(e,r())}static preserve(...e){let r={};for(let n of e)r[n]=t.decoder(n);return r}};Object.defineProperty(kn.prototype,Symbol.toStringTag,{value:"Tagged"});var Fe="/",Cc=new TextEncoder().encode(Fe),An=Cc[0],ze=class t{_buf;constructor(e,r){if(typeof e=="string")this._buf=W(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(r==null&&(r=!0),r&&this.clean(),this._buf.byteLength===0||this._buf[0]!==An)throw new Error("Invalid key")}toString(e="utf8"){return Qe(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new t(e.join(Fe))}static random(){return new t(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new t(e):typeof e.uint8Array=="function"?new t(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Cc),this._buf[0]!==An){let e=new Uint8Array(this._buf.byteLength+1);e.fill(An,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===An;)this._buf=this._buf.subarray(0,-1)}less(e){let r=this.list(),n=e.list();for(let o=0;o<r.length;o++){if(n.length<o+1)return!1;let i=r[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return r.length<n.length}reverse(){return t.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Fe).slice(1)}type(){return Kh(this.baseNamespace())}name(){return Wh(this.baseNamespace())}instance(e){return new t(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Fe)||(e+=Fe),e+=this.type(),new t(e)}parent(){let e=this.list();return e.length===1?new t(Fe):new t(e.slice(0,-1).join(Fe))}child(e){return this.toString()===Fe?e:e.toString()===Fe?this:new t(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 t.withNamespaces([...this.namespaces(),...Gh(e.map(r=>r.namespaces()))])}};function Kh(t){let e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Wh(t){let e=t.split(":");return e[e.length-1]}function Gh(t){return[].concat(...t)}function Qh(t){return t[Symbol.asyncIterator]!=null}function Jh(t){if(Qh(t))return(async()=>{let n=new Uint8Array(0);for await(let o of t)n=bi([n,o],n.length+o.length);return n})();let e=[],r=0;for(let n of t)e.push(n),r+=n.byteLength;return bi(e,r)}var Tn=Jh;function In({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*Yh(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r],i=L.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*$i(n,o))}else{let r=L.asCID(e);r!=null?yield[t.join("/"),r]:yield*$i(e,t)}}function*$i(t,e){if(t==null||t instanceof Uint8Array)return;let r=L.asCID(t);r!=null&&(yield[e.join("/"),r]);for(let[n,o]of Object.entries(t)){let i=[...e,n];yield*Yh(i,o)}}function*Xh(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r];yield o.join("/"),typeof n=="object"&&L.asCID(n)==null&&(yield*Oi(n,o))}else yield*Oi(e,t)}function*Oi(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let o=[...e,r];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&L.asCID(n)==null&&(yield*Xh(o,n))}}function Zh(t,e){let r=t;for(let[n,o]of e.entries()){if(r=r[o],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=L.asCID(r);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:r}}var Mi=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:r,value:n}){if(e==null||r==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=r,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:In(),bytes:In(),value:In(),asBlock:In()})}links(){return $i(this.value,[])}tree(){return Oi(this.value,[])}get(e="/"){return Zh(this.value,e.split("/").filter(Boolean))}};function Sn({bytes:t,cid:e,value:r,codec:n}){let o=r!==void 0?r:n?.decode(t);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Mi({cid:e,bytes:t,value:o})}var Un=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},gr=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},Nn=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},dt=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},Cn=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},Ln=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},yr=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var Rc="/pin/",Lc="/pinned-block/",Fi=Oe,Bc=1;function Bn(t){return t.version===0&&(t=t.toV1()),new ze(`${Rc}${t.toString(Fi)}`)}var Rn=class{datastore;blockstore;getCodec;constructor(e,r,n){this.datastore=e,this.blockstore=r,this.getCodec=n}async*add(e,r={}){let n=Bn(e);if(await this.datastore.has(n))throw new Un("Already pinned");let o=Math.round(r.depth??1/0);if(o<0)throw new xt("Depth must be greater than or equal to 0");let i=new J({concurrency:Bc});for await(let a of this.#e(e,i,{...r,depth:o}))await this.#o(a,c=>c.pinnedBy.find(f=>at(f,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),r),yield a;let s={depth:o,metadata:r.metadata??{}};await this.datastore.put(n,mr(s),r)}async*#e(e,r,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await Tn(this.blockstore.get(e,n)),s=Sn({bytes:i,cid:e,codec:o});yield e;for(let[,a]of s.links())yield*await r.add(async()=>this.#e(a,r,{...n,depth:n.depth-1}))}async#o(e,r,n){let o=new ze(`${Lc}${Fi.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=lt(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(r(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,mr(i),n),n.onProgress?.(new T("helia:pin:add",e))}}async*rm(e,r={}){let n=Bn(e),o=await this.datastore.get(n,r),i=lt(o);await this.datastore.delete(n,r);let s=new J({concurrency:Bc});for await(let a of this.#e(e,s,{...r,depth:i.depth}))await this.#o(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(f=>at(f,e.bytes)),!0),{...r,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:r,value:n}of this.datastore.query({prefix:Rc+(e.cid!=null?`${e.cid.toString(Oe)}`:"")},e)){let o=L.parse(r.toString().substring(5),Oe),i=lt(n);yield{cid:o,...i}}}async isPinned(e,r={}){let n=new ze(`${Lc}${Fi.encode(e.multihash.bytes)}`);return this.datastore.has(n,r)}async get(e,r){let n=Bn(e),o=await this.datastore.get(n,r);return lt(o)}async setMetadata(e,r,n){let o=Bn(e),i=await this.datastore.get(o,n),s=lt(i);s.metadata=r??{},await this.datastore.put(o,mr(s),n)}};var Dn=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},ht=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},Pn=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},$n=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var ep=5,On=class{name;log;routers;providerLookupConcurrency;constructor(e,r){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=r.routers??[],this.providerLookupConcurrency=r.providerLookupConcurrency??ep,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 Ke(...this.routers)}async stop(){await We(...this.routers)}async*findProviders(e,r={}){if(this.routers.length===0)throw new ht("No content routers available");let n=new fn({concurrency:this.providerLookupConcurrency}),o=0,i=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(f=>f.toString()).join(", "));let c=pt(this.routers,"findProviders").map(async function*(f){let p=0;r?.onProgress?.(new T("helia:routing:find-providers:start",{routing:f.name,cid:e}));try{for await(let m of f.findProviders(e,r))p++,r?.onProgress?.(new T("helia:routing:find-providers:provider",{routing:f.name,cid:e,provider:m})),yield m}catch(m){i.push(m)}finally{s.log("router %s found %d providers for %c",f,p,e),r?.onProgress?.(new T("helia:routing:find-providers:end",{routing:f.name,cid:e,found:p})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let f of un(n.toGenerator(),...c))if(f!=null){if(f.multiaddrs.length===0){if(n.find(f.id)!=null)continue;n.add(async()=>{try{let p=await this.findPeer(f.id,r);return p.multiaddrs.length===0?null:{...p,protocols:f.protocols,routing:f.routing}}catch(p){return this.log.error("could not load multiaddrs for peer %p - %e",f.id,p),null}},{peerId:f.id,signal:r.signal}).catch(p=>{this.log.error("could not load multiaddrs for peer %p - %e",f.id,p)});continue}o++,yield f}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,r={}){if(this.routers.length===0)throw new ht("No content routers available");await Promise.all(pt(this.routers,"provide").map(async n=>{r?.onProgress?.(new T("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,r),r?.onProgress?.(new T("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,r={}){await Promise.all(pt(this.routers,"cancelReprovide").map(async n=>{r?.onProgress?.(new T("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,r),r?.onProgress?.(new T("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,r,n){await Promise.all(pt(this.routers,"put").map(async o=>{n?.onProgress?.(new T("helia:routing:put:start",{routing:o.name,key:e,value:r})),await o.put(e,r,n),n?.onProgress?.(new T("helia:routing:put:end",{routing:o.name,key:e,value:r}))}))}async get(e,r){let n=[],o;try{o=await Promise.any(pt(this.routers,"get").map(async i=>{r?.onProgress?.(new T("helia:routing:get:start",{routing:i.name,key:e}));try{return await i.get(e,r)}catch(s){this.log("router %s failed with %e",i,s),n.push(s)}finally{r?.onProgress?.(new T("helia:routing:get:end",{routing:i.name,key:e}))}}))}catch{}if(o==null)throw new Cn(n,`Failed to get value key ${Qe(e,"base58btc")}`);return o}async findPeer(e,r){if(this.routers.length===0)throw new ht("No peer routers available");let n=this,o=un(...pt(this.routers,"findPeer").map(i=>(async function*(){r?.onProgress?.(new T("helia:routing:find-peer:start",{routing:i.name,peerId:e}));try{yield await i.findPeer(e,r)}catch(s){n.log.error(s)}finally{r?.onProgress?.(new T("helia:routing:find-peer:end",{routing:i.name,peerId:e}))}})()));for await(let i of o)if(i!=null)return i;throw new Mr("Could not find peer in routing")}async*getClosestPeers(e,r={}){if(this.routers.length===0)throw new ht("No peer routers available");for await(let n of un(...pt(this.routers,"getClosestPeers").map(async function*(o){r?.onProgress?.(new T("helia:routing:get-closest-peers:start",{routing:o.name,key:e}));try{yield*o.getClosestPeers(e,r)}finally{r?.onProgress?.(new T("helia:routing:get-closest-peers:end",{routing:o.name,key:e}))}})))n!=null&&(yield n)}};function pt(t,e){return t.filter(r=>r[e]!=null)}var te=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...r){super(e,...r)}};async function Mn(t,e,r,n){let o=new te(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let i=n?.errorEvent??"error";return r?.aborted===!0?Promise.reject(o):new Promise((s,a)=>{function c(){ji(r,"abort",m),ji(t,e,f),ji(t,i,p)}let f=x=>{try{if(n?.filter?.(x)===!1)return}catch(A){c(),a(A);return}c(),s(x)},p=x=>{if(c(),x instanceof Error){a(x);return}a(x.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},m=()=>{c(),a(o)};zi(r,"abort",m),zi(t,e,f),zi(t,i,p)})}function zi(t,e,r){t!=null&&(Dc(t)?t.addEventListener(e,r):t.addListener(e,r))}function ji(t,e,r){t!=null&&(Dc(t)?t.removeEventListener(e,r):t.removeListener(e,r))}function Dc(t){return typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"}var Fn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var zn=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new te)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function tp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var jn=class{id;fn;options;recipients;status;timeline;controller;constructor(e,r){this.id=tp(),this.status="queued",this.fn=e,this.options=r,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((r,n)=>r&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new te),this.cleanup())}async join(e={}){let r=new zn(e.signal);return this.recipients.push(r),e.signal?.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Je(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(r=>{r.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(r=>{r.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)})}};function qi(t,e){let r,n=function(){let o=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}var wr=class extends le{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=qi(this.emitEmpty.bind(this),1),this.emitIdle=qi(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let r of this.queue)if(r.status==="queued"){e=r;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let r=0;r<this.queue.length;r++)if(this.queue[r]===e){this.queue.splice(r,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,r){if(r?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Fn;let n=new jn(e,r);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(r).then(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("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new te)}),this.clear()}async onEmpty(e){this.size!==0&&await Mn(this,"empty",e?.signal)}async onSizeLessThan(e,r){this.size<e||await Mn(this,"next",r?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Mn(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 r=nn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),r.end(c)},o=c=>{c.detail!=null&&r.push(c.detail.result)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new te("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*r}finally{this.removeEventListener("success",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var qn="lock:worker:request-read",Vn="lock:worker:abort-read-request",Hn="lock:worker:release-read",Kn="lock:master:grant-read",Wn="lock:master:error-read",Gn="lock:worker:request-write",Qn="lock:worker:abort-write-request",Jn="lock:worker:release-write",Yn="lock:master:grant-write",Xn="lock:master:error-write",Zn="lock:worker:finalize",eo="mortice",Pc={singleProcess:!1};var Vi=(t,e,r,n,o,i,s,a,c)=>f=>{if(f.data==null)return;let p={type:f.data.type,name:f.data.name,identifier:f.data.identifier};p.type===o&&t.safeDispatchEvent(r,{detail:{name:p.name,identifier:p.identifier,handler:async()=>{e.postMessage({type:c,name:p.name,identifier:p.identifier}),await new Promise(m=>{let x=A=>{if(A?.data==null)return;let I={type:A.data.type,name:A.data.name,identifier:A.data.identifier};I.type===a&&I.identifier===p.identifier&&(e.removeEventListener("message",x),m())};e.addEventListener("message",x)})},onError:m=>{e.postMessage({type:s,name:p.name,identifier:p.identifier,error:{message:m.message,name:m.name,stack:m.stack}})}}}),p.type===i&&t.safeDispatchEvent(n,{detail:{name:p.name,identifier:p.identifier}}),p.type===Zn&&t.safeDispatchEvent("finalizeRequest",{detail:{name:p.name}})};var $c=(t=10)=>Math.random().toString().substring(2,t+2);var to=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(eo)}readLock(e){return this.sendRequest(qn,Vn,Kn,Wn,Hn,e)}writeLock(e){return this.sendRequest(Gn,Qn,Yn,Xn,Jn,e)}finalize(){this.channel.postMessage({type:Zn,name:this.name}),this.channel.close()}async sendRequest(e,r,n,o,i,s){s?.signal?.throwIfAborted();let a=$c();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,f)=>{let p=()=>{this.channel.postMessage({type:r,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",p,{once:!0});let m=x=>{if(x.data?.identifier===a&&(x.data?.type===n&&(this.channel.removeEventListener("message",m),s?.signal?.removeEventListener("abort",p),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),x.data.type===o)){this.channel.removeEventListener("message",m),s?.signal?.removeEventListener("abort",p);let A=new Error;x.data.error!=null&&(A.message=x.data.error.message,A.name=x.data.error.name,A.stack=x.data.error.stack),f(A)}};this.channel.addEventListener("message",m)})}};var Oc=t=>{if(t=Object.assign({},Pc,t),!!globalThis.document||t.singleProcess){let r=new BroadcastChannel(eo),n=new le;return r.addEventListener("message",Vi(n,r,"requestReadLock","abortReadLockRequest",qn,Vn,Wn,Hn,Kn)),r.addEventListener("message",Vi(n,r,"requestWriteLock","abortWriteLockRequest",Gn,Qn,Xn,Jn,Yn)),n}return new to(t.name)};var mt=new Map,xr;function Mc(t){return typeof t?.readLock=="function"&&typeof t?.writeLock=="function"}function rp(t){if(xr==null&&(xr=Oc(t),!Mc(xr))){let e=xr;e.addEventListener("requestReadLock",r=>{let n=r.detail.name,o=r.detail.identifier,i=mt.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:s.signal}).then(async c=>{await r.detail.handler().finally(()=>{c()})}).catch(c=>{r.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",r=>{let n=r.detail.name,o=r.detail.identifier,i=mt.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:s.signal}).then(async c=>{await r.detail.handler().finally(()=>{c()})}).catch(c=>{r.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",r=>{let n=r.detail.name,o=mt.get(n);o?.finalize()})}return xr}async function Hi(t,e){let r,n,o=new Promise((s,a)=>{r=s,n=a}),i=()=>{n(new te)};return e?.signal?.addEventListener("abort",i,{once:!0}),t.add(async()=>{await new Promise(s=>{r(()=>{e?.signal?.removeEventListener("abort",i),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),o}var Fc=(t,e)=>{let r=mt.get(t);if(r!=null)return r;let n=rp(e);if(Mc(n))return r=n,mt.set(t,r),r;let o=new wr({concurrency:1}),i;return r={async readLock(s){if(i!=null)return Hi(i,s);i=new wr({concurrency:e.concurrency,autoStart:!1});let a=i,c=Hi(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(s){return i=null,Hi(o,s)},finalize:()=>{mt.delete(t)},queue:o},mt.set(t,r),e.autoFinalize===!0&&o.addEventListener("idle",()=>{r.finalize()},{once:!0}),r};var np={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Ki(t){let e=Object.assign({},np,t);return Fc(e.name,e)}var ro=class{lock;child;pins;started;constructor(e,r,n={}){this.child=e,this.pins=r,this.lock=Ki({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Ke(this.child),this.started=!0}async stop(){await We(this.child),this.started=!1}unwrap(){return this.child}async put(e,r,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,r,n)}finally{o()}}async*putMany(e,r={}){r?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,r)}finally{n()}}async*get(e,r={}){r?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,r)}finally{n()}}async*getMany(e,r={}){r?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,r)}finally{n()}}async delete(e,r={}){r?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new gr("Block was pinned - please unpin and try again");await this.child.delete(e,r)}finally{n()}}async*deleteMany(e,r={}){r?.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 gr("Block was pinned - please unpin and try again");yield i}})(),r)}finally{n()}}async has(e,r={}){r?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,r)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let r=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{r()}}createSession(e,r){return r?.signal?.throwIfAborted(),this.child.createSession(e,r)}};var Wi=new ze("/version"),zc=1;async function jc(t){if(!await t.has(Wi)){await t.put(Wi,W(`${zc}`));return}let e=await t.get(Wi),r=Qe(e);if(parseInt(r,10)!==zc)throw new Nn("Invalid datastore version, a datastore migration may be required")}var us={};O(us,{code:()=>cs,decode:()=>Jp,decodeOptions:()=>Wp,encode:()=>Qp,encodeOptions:()=>Hp,name:()=>Gp,toByteView:()=>Qu});var op=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function Gi(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(t instanceof Uint8Array)return"Uint8Array";if(t.constructor===Object)return"Object";let r=ip(t);return r||"Object"}function ip(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(op.includes(e))return e}var l=class{constructor(e,r,n){this.major=e,this.majorEncoded=e<<5,this.name=r,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,r){return e===r||e.major===r.major&&e.name===r.name}};l.uint=new l(0,"uint",!0);l.negint=new l(1,"negint",!0);l.bytes=new l(2,"bytes",!0);l.string=new l(3,"string",!0);l.array=new l(4,"array",!1);l.map=new l(5,"map",!1);l.tag=new l(6,"tag",!1);l.float=new l(7,"float",!0);l.false=new l(7,"false",!0);l.true=new l(7,"true",!0);l.null=new l(7,"null",!0);l.undefined=new l(7,"undefined",!0);l.break=new l(7,"break",!0);var b=class{constructor(e,r,n){this.type=e,this.value=r,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var br=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",sp=new TextEncoder;function no(t){return br&&globalThis.Buffer.isBuffer(t)}function Er(t){return t instanceof Uint8Array?no(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var ap=24,cp=200,oo=br?t=>t.length>=ap?globalThis.Buffer.from(t):qc(t):t=>t.length>=cp?sp.encode(t):qc(t),Re=t=>Uint8Array.from(t),Vc=br?(t,e,r)=>no(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Hc=br?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),Er(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let o of t)n+o.length>r.length&&(o=o.subarray(0,r.length-n)),r.set(o,n),n+=o.length;return r},Kc=br?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function io(t,e){if(no(t)&&no(e))return t.compare(e);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return 0}function qc(t){let e=[],r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128)}return e}var up=256,_r=class{constructor(e=up){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 r=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=r.length-(this.maxCursor-this.cursor)-1;r.set(e,o)}else{if(r){let o=r.length-(this.maxCursor-this.cursor)-1;o<r.length&&(this.chunks[this.chunks.length-1]=r.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(r=Kc(this.chunkSize),this.chunks.push(r),this.maxCursor+=r.length,this._initReuseChunk===null&&(this._initReuseChunk=r),r.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let r;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(r=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):r=Vc(n,0,this.cursor)}else r=Hc(this.chunks,this.cursor);return e&&this.reset(),r}},so=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let r=this.dest.subarray(0,this.cursor);return e&&this.reset(),r}};var k="CBOR decode error:",ao="CBOR encode error:",vr=[];vr[23]=1;vr[24]=2;vr[25]=3;vr[26]=5;vr[27]=9;function je(t,e,r){if(t.length-e<r)throw new Error(`${k} not enough data for type`)}var F=[24,256,65536,4294967296,BigInt("18446744073709551616")];function re(t,e,r){je(t,e,1);let n=t[e];if(r.strict===!0&&n<F[0])throw new Error(`${k} integer encoded in more bytes than necessary (strict decode)`);return n}function ne(t,e,r){je(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<F[1])throw new Error(`${k} integer encoded in more bytes than necessary (strict decode)`);return n}function oe(t,e,r){je(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<F[2])throw new Error(`${k} integer encoded in more bytes than necessary (strict decode)`);return n}function ie(t,e,r){je(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],o=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(r.strict===!0&&i<F[3])throw new Error(`${k} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(r.allowBigInt===!0)return i;throw new Error(`${k} integers outside of the safe integer range are not supported`)}function Wc(t,e,r,n){return new b(l.uint,re(t,e+1,n),2)}function Gc(t,e,r,n){return new b(l.uint,ne(t,e+1,n),3)}function Qc(t,e,r,n){return new b(l.uint,oe(t,e+1,n),5)}function Jc(t,e,r,n){return new b(l.uint,ie(t,e+1,n),9)}function pe(t,e){return R(t,0,e.value)}function R(t,e,r){if(r<F[0]){let n=Number(r);t.push([e|n])}else if(r<F[1]){let n=Number(r);t.push([e|24,n])}else if(r<F[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<F[3]){let n=Number(r);t.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(r);if(n<F[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,t.push(o)}else throw new Error(`${k} encountered BigInt larger than allowable range`)}}pe.encodedSize=function(e){return R.encodedSize(e.value)};R.encodedSize=function(e){return e<F[0]?1:e<F[1]?2:e<F[2]?3:e<F[3]?5:9};pe.compareTokens=function(e,r){return e.value<r.value?-1:e.value>r.value?1:0};function Yc(t,e,r,n){return new b(l.negint,-1-re(t,e+1,n),2)}function Xc(t,e,r,n){return new b(l.negint,-1-ne(t,e+1,n),3)}function Zc(t,e,r,n){return new b(l.negint,-1-oe(t,e+1,n),5)}var Qi=BigInt(-1),eu=BigInt(1);function tu(t,e,r,n){let o=ie(t,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new b(l.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${k} integers outside of the safe integer range are not supported`);return new b(l.negint,Qi-BigInt(o),9)}function co(t,e){let r=e.value,n=typeof r=="bigint"?r*Qi-eu:r*-1-1;R(t,e.type.majorEncoded,n)}co.encodedSize=function(e){let r=e.value,n=typeof r=="bigint"?r*Qi-eu:r*-1-1;return n<F[0]?1:n<F[1]?2:n<F[2]?3:n<F[3]?5:9};co.compareTokens=function(e,r){return e.value<r.value?1:e.value>r.value?-1:0};function kr(t,e,r,n){je(t,e,r+n);let o=t.slice(e+r,e+r+n);return new b(l.bytes,o,r+n)}function ru(t,e,r,n){return kr(t,e,1,r)}function nu(t,e,r,n){return kr(t,e,2,re(t,e+1,n))}function ou(t,e,r,n){return kr(t,e,3,ne(t,e+1,n))}function iu(t,e,r,n){return kr(t,e,5,oe(t,e+1,n))}function su(t,e,r,n){let o=ie(t,e+1,n);if(typeof o=="bigint")throw new Error(`${k} 64-bit integer bytes lengths not supported`);return kr(t,e,9,o)}function uo(t){return t.encodedBytes===void 0&&(t.encodedBytes=l.equals(t.type,l.string)?oo(t.value):t.value),t.encodedBytes}function Dt(t,e){let r=uo(e);R(t,e.type.majorEncoded,r.length),t.push(r)}Dt.encodedSize=function(e){let r=uo(e);return R.encodedSize(r.length)+r.length};Dt.compareTokens=function(e,r){return lp(uo(e),uo(r))};function lp(t,e){return t.length<e.length?-1:t.length>e.length?1:io(t,e)}var au=new TextDecoder,hp=32;function pp(t,e,r){if(r-e<hp){let o="";for(let i=e;i<r;i++){let s=t[i];if(s&128)return au.decode(t.subarray(e,r));o+=String.fromCharCode(s)}return o}return au.decode(t.subarray(e,r))}function Ar(t,e,r,n,o){let i=r+n;je(t,e,i);let s=new b(l.string,pp(t,e+r,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=t.slice(e+r,e+i)),s}function cu(t,e,r,n){return Ar(t,e,1,r,n)}function uu(t,e,r,n){return Ar(t,e,2,re(t,e+1,n),n)}function fu(t,e,r,n){return Ar(t,e,3,ne(t,e+1,n),n)}function lu(t,e,r,n){return Ar(t,e,5,oe(t,e+1,n),n)}function du(t,e,r,n){let o=ie(t,e+1,n);if(typeof o=="bigint")throw new Error(`${k} 64-bit integer string lengths not supported`);return Ar(t,e,9,o,n)}var hu=Dt;function Pt(t,e,r,n){return new b(l.array,n,r)}function pu(t,e,r,n){return Pt(t,e,1,r)}function mu(t,e,r,n){return Pt(t,e,2,re(t,e+1,n))}function gu(t,e,r,n){return Pt(t,e,3,ne(t,e+1,n))}function yu(t,e,r,n){return Pt(t,e,5,oe(t,e+1,n))}function wu(t,e,r,n){let o=ie(t,e+1,n);if(typeof o=="bigint")throw new Error(`${k} 64-bit integer array lengths not supported`);return Pt(t,e,9,o)}function xu(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${k} indefinite length items not allowed`);return Pt(t,e,1,1/0)}function fo(t,e){R(t,l.array.majorEncoded,e.value)}fo.compareTokens=pe.compareTokens;fo.encodedSize=function(e){return R.encodedSize(e.value)};function $t(t,e,r,n){return new b(l.map,n,r)}function bu(t,e,r,n){return $t(t,e,1,r)}function Eu(t,e,r,n){return $t(t,e,2,re(t,e+1,n))}function _u(t,e,r,n){return $t(t,e,3,ne(t,e+1,n))}function vu(t,e,r,n){return $t(t,e,5,oe(t,e+1,n))}function ku(t,e,r,n){let o=ie(t,e+1,n);if(typeof o=="bigint")throw new Error(`${k} 64-bit integer map lengths not supported`);return $t(t,e,9,o)}function Au(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${k} indefinite length items not allowed`);return $t(t,e,1,1/0)}function lo(t,e){R(t,l.map.majorEncoded,e.value)}lo.compareTokens=pe.compareTokens;lo.encodedSize=function(e){return R.encodedSize(e.value)};function Tu(t,e,r,n){return new b(l.tag,r,1)}function Iu(t,e,r,n){return new b(l.tag,re(t,e+1,n),2)}function Su(t,e,r,n){return new b(l.tag,ne(t,e+1,n),3)}function Uu(t,e,r,n){return new b(l.tag,oe(t,e+1,n),5)}function Nu(t,e,r,n){return new b(l.tag,ie(t,e+1,n),9)}function ho(t,e){R(t,l.tag.majorEncoded,e.value)}ho.compareTokens=pe.compareTokens;ho.encodedSize=function(e){return R.encodedSize(e.value)};var Ji=20,Yi=21,Xi=22,Zi=23;function Cu(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${k} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new b(l.null,null,1):new b(l.undefined,void 0,1)}function Lu(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${k} indefinite length items not allowed`);return new b(l.break,void 0,1)}function es(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${k} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${k} Infinity values are not supported`)}return new b(l.float,t,e)}function Bu(t,e,r,n){return es(ts(t,e+1),3,n)}function Ru(t,e,r,n){return es(rs(t,e+1),5,n)}function Du(t,e,r,n){return es(Mu(t,e+1),9,n)}function Tr(t,e,r){let n=e.value;if(n===!1)t.push([l.float.majorEncoded|Ji]);else if(n===!0)t.push([l.float.majorEncoded|Yi]);else if(n===null)t.push([l.float.majorEncoded|Xi]);else if(n===void 0)t.push([l.float.majorEncoded|Zi]);else{let o,i=!1;(!r||r.float64!==!0)&&($u(n),o=ts(Te,1),n===o||Number.isNaN(n)?(Te[0]=249,t.push(Te.slice(0,3)),i=!0):(Ou(n),o=rs(Te,1),n===o&&(Te[0]=250,t.push(Te.slice(0,5)),i=!0))),i||(xp(n),o=Mu(Te,1),Te[0]=251,t.push(Te.slice(0,9)))}}Tr.encodedSize=function(e,r){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!r||r.float64!==!0){$u(n);let o=ts(Te,1);if(n===o||Number.isNaN(n))return 3;if(Ou(n),o=rs(Te,1),n===o)return 5}return 9};var Pu=new ArrayBuffer(9),me=new DataView(Pu,1),Te=new Uint8Array(Pu,0);function $u(t){if(t===1/0)me.setUint16(0,31744,!1);else if(t===-1/0)me.setUint16(0,64512,!1);else if(Number.isNaN(t))me.setUint16(0,32256,!1);else{me.setFloat32(0,t);let e=me.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)me.setUint16(0,31744,!1);else if(r===0)me.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=r-127;o<-24?me.setUint16(0,0):o<-14?me.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):me.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function ts(t,e){if(t.length-e<2)throw new Error(`${k} not enough data for float16`);let r=(t[e]<<8)+t[e+1];if(r===31744)return 1/0;if(r===64512)return-1/0;if(r===32256)return NaN;let n=r>>10&31,o=r&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,r&32768?-i:i}function Ou(t){me.setFloat32(0,t,!1)}function rs(t,e){if(t.length-e<4)throw new Error(`${k} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function xp(t){me.setFloat64(0,t,!1)}function Mu(t,e){if(t.length-e<8)throw new Error(`${k} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}Tr.compareTokens=pe.compareTokens;function N(t,e,r){throw new Error(`${k} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function po(t){return()=>{throw new Error(`${k} ${t}`)}}var y=[];for(let t=0;t<=23;t++)y[t]=N;y[24]=Wc;y[25]=Gc;y[26]=Qc;y[27]=Jc;y[28]=N;y[29]=N;y[30]=N;y[31]=N;for(let t=32;t<=55;t++)y[t]=N;y[56]=Yc;y[57]=Xc;y[58]=Zc;y[59]=tu;y[60]=N;y[61]=N;y[62]=N;y[63]=N;for(let t=64;t<=87;t++)y[t]=ru;y[88]=nu;y[89]=ou;y[90]=iu;y[91]=su;y[92]=N;y[93]=N;y[94]=N;y[95]=po("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)y[t]=cu;y[120]=uu;y[121]=fu;y[122]=lu;y[123]=du;y[124]=N;y[125]=N;y[126]=N;y[127]=po("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)y[t]=pu;y[152]=mu;y[153]=gu;y[154]=yu;y[155]=wu;y[156]=N;y[157]=N;y[158]=N;y[159]=xu;for(let t=160;t<=183;t++)y[t]=bu;y[184]=Eu;y[185]=_u;y[186]=vu;y[187]=ku;y[188]=N;y[189]=N;y[190]=N;y[191]=Au;for(let t=192;t<=215;t++)y[t]=Tu;y[216]=Iu;y[217]=Su;y[218]=Uu;y[219]=Nu;y[220]=N;y[221]=N;y[222]=N;y[223]=N;for(let t=224;t<=243;t++)y[t]=po("simple values are not supported");y[244]=N;y[245]=N;y[246]=N;y[247]=Cu;y[248]=po("simple values are not supported");y[249]=Bu;y[250]=Ru;y[251]=Du;y[252]=N;y[253]=N;y[254]=N;y[255]=Lu;var Ie=[];for(let t=0;t<24;t++)Ie[t]=new b(l.uint,t,1);for(let t=-1;t>=-24;t--)Ie[31-t]=new b(l.negint,t,1);Ie[64]=new b(l.bytes,new Uint8Array(0),1);Ie[96]=new b(l.string,"",1);Ie[128]=new b(l.array,0,1);Ie[160]=new b(l.map,0,1);Ie[244]=new b(l.false,!1,1);Ie[245]=new b(l.true,!0,1);Ie[246]=new b(l.null,null,1);function ns(t){switch(t.type){case l.false:return Re([244]);case l.true:return Re([245]);case l.null:return Re([246]);case l.bytes:return t.value.length?void 0:Re([64]);case l.string:return t.value===""?Re([96]):void 0;case l.array:return t.value===0?Re([128]):void 0;case l.map:return t.value===0?Re([160]):void 0;case l.uint:return t.value<24?Re([Number(t.value)]):void 0;case l.negint:if(t.value>=-24)return Re([31-Number(t.value)])}}var Ep={float64:!1,mapSorter:kp,quickEncodeToken:ns},Vu=Object.freeze({float64:!0,mapSorter:Ap,quickEncodeToken:ns});function _p(){let t=[];return t[l.uint.major]=pe,t[l.negint.major]=co,t[l.bytes.major]=Dt,t[l.string.major]=hu,t[l.array.major]=fo,t[l.map.major]=lo,t[l.tag.major]=ho,t[l.float.major]=Tr,t}var Mt=_p(),mo=new _r,Sr=class t{constructor(e,r){this.obj=e,this.parent=r}includes(e){let r=this;do if(r.obj===e)return!0;while(r=r.parent);return!1}static createCheck(e,r){if(e&&e.includes(r))throw new Error(`${ao} object contains circular references`);return new t(r,e)}},et={null:new b(l.null,null),undefined:new b(l.undefined,void 0),true:new b(l.true,!0),false:new b(l.false,!1),emptyArray:new b(l.array,0),emptyMap:new b(l.map,0)},De={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new b(l.float,t):t>=0?new b(l.uint,t):new b(l.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new b(l.uint,t):new b(l.negint,t)},Uint8Array(t,e,r,n){return new b(l.bytes,t)},string(t,e,r,n){return new b(l.string,t)},boolean(t,e,r,n){return t?et.true:et.false},null(t,e,r,n){return et.null},undefined(t,e,r,n){return et.undefined},ArrayBuffer(t,e,r,n){return new b(l.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new b(l.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[et.emptyArray,new b(l.break)]:et.emptyArray;n=Sr.createCheck(n,t);let o=[],i=0;for(let s of t)o[i++]=Ot(s,r,n);return r.addBreakTokens?[new b(l.array,t.length),o,new b(l.break)]:[new b(l.array,t.length),o]},Object(t,e,r,n){let o=e!=="Object",i=o?t.keys():Object.keys(t),s=o?t.size:i.length,a;if(s){a=new Array(s),n=Sr.createCheck(n,t);let c=!o&&r.ignoreUndefinedProperties,f=0;for(let p of i){let m=o?t.get(p):t[p];c&&m===void 0||(a[f++]=[Ot(p,r,n),Ot(m,r,n)])}f<s&&(a.length=f)}return a?.length?(vp(a,r),r.addBreakTokens?[new b(l.map,a.length),a,new b(l.break)]:[new b(l.map,a.length),a]):r.addBreakTokens===!0?[et.emptyMap,new b(l.break)]:et.emptyMap},Tagged(t,e,r,n){return[new b(l.tag,t.tag),Ot(t.value,r,n)]}};De.Map=De.Object;De.Buffer=De.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))De[`${t}Array`]=De.DataView;function Ot(t,e={},r){let n=Gi(t),o=e&&e.typeEncoders&&e.typeEncoders[n]||De[n];if(typeof o=="function"){let s=o(t,n,e,r);if(s!=null)return s}let i=De[n];if(!i)throw new Error(`${ao} unsupported type: ${n}`);return i(t,n,e,r)}function vp(t,e){e.mapSorter&&t.sort(e.mapSorter)}function kp(t,e){let r=Array.isArray(t[0])?t[0][0]:t[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(r.type!==n.type)return r.type.compare(n.type);let o=r.type.major,i=Mt[o].compareTokens(r,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function Ap(t,e){if(t[0]instanceof b&&e[0]instanceof b){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=Fu(r.value)),n._keyBytes||(n._keyBytes=Fu(n.value)),io(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Fu(t){return Ku(t,Mt,Vu)}function Ir(t,e,r,n){if(Array.isArray(e))for(let o of e)Ir(t,o,r,n);else r[e.type.major](t,e,n)}var zu=l.uint.majorEncoded,ju=l.negint.majorEncoded,Tp=l.bytes.majorEncoded,Ip=l.string.majorEncoded,qu=l.array.majorEncoded,Sp=l.float.majorEncoded|Ji,Up=l.float.majorEncoded|Yi,Np=l.float.majorEncoded|Xi,Cp=l.float.majorEncoded|Zi,Lp=BigInt(-1),Bp=BigInt(1);function Rp(t){return t.addBreakTokens!==!0}function Hu(t,e,r,n){let o=Gi(e),i=r.typeEncoders&&r.typeEncoders[o];if(i){let s=i(e,o,r,n);if(s!=null){Ir(t,s,Mt,r);return}}switch(o){case"null":t.push([Np]);return;case"undefined":t.push([Cp]);return;case"boolean":t.push([e?Up:Sp]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?Tr(t,new b(l.float,e),r):e>=0?R(t,zu,e):R(t,ju,e*-1-1);return;case"bigint":e>=BigInt(0)?R(t,zu,e):R(t,ju,e*Lp-Bp);return;case"string":{let s=oo(e);R(t,Ip,s.length),t.push(s);return}case"Uint8Array":R(t,Tp,e.length),t.push(e);return;case"Array":if(!e.length){t.push([qu]);return}n=Sr.createCheck(n,e),R(t,qu,e.length);for(let s of e)Hu(t,s,r,n);return;case"Object":case"Map":{let s=De.Object(e,o,r,n);Ir(t,s,Mt,r)}return;default:{let s=De[o];if(!s)throw new Error(`${ao} unsupported type: ${o}`);let a=s(e,o,r,n);Ir(t,a,Mt,r)}}}function Ku(t,e,r,n){let o=n instanceof Uint8Array,i=o?new so(n):mo,s=Ot(t,r);if(!Array.isArray(s)&&r.quickEncodeToken){let a=r.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let f=c.encodedSize(s,r);if(o||(i=new _r(f)),c(i,s,r),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Er(i.chunks[0])}}return i.reset(),Ir(i,s,e,r),i.toBytes(!0)}function os(t,e){return e=Object.assign({},Ep,e),Rp(e)?(mo.reset(),Hu(mo,t,e,void 0),mo.toBytes(!0)):Ku(t,Mt,e)}var Dp={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},go=class{constructor(e,r={}){this._pos=0,this.data=e,this.options=r}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],r=Ie[e];if(r===void 0){let n=y[e];if(!n)throw new Error(`${k} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;r=n(this.data,this._pos,o,this.options)}return this._pos+=r.encodedLength,r}},tt=Symbol.for("DONE"),Ft=Symbol.for("BREAK");function Pp(t,e,r){let n=[];for(let o=0;o<t.value;o++){let i=rt(e,r);if(i===Ft){if(t.value===1/0)break;throw new Error(`${k} got unexpected break to lengthed array`)}if(i===tt)throw new Error(`${k} found array but not enough entries (got ${o}, expected ${t.value})`);n[o]=i}return n}function $p(t,e,r){let n=r.useMaps===!0,o=r.rejectDuplicateMapKeys===!0,i=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<t.value;a++){let c=rt(e,r);if(c===Ft){if(t.value===1/0)break;throw new Error(`${k} got unexpected break to lengthed map`)}if(c===tt)throw new Error(`${k} found map but not enough entries (got ${a} [no key], expected ${t.value})`);if(!n&&typeof c!="string")throw new Error(`${k} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${k} found repeat map key "${c}"`);let f=rt(e,r);if(f===tt)throw new Error(`${k} found map but not enough entries (got ${a} [no value], expected ${t.value})`);n?s.set(c,f):i[c]=f}return n?s:i}function*Op(t,e,r){for(let n=0;n<t.value;n++){let o=rt(e,r);if(o===Ft){if(t.value===1/0)break;throw new Error(`${k} got unexpected break to lengthed map`)}if(o===tt)throw new Error(`${k} found map but not enough entries (got ${n} [no key], expected ${t.value})`);let i=rt(e,r);if(i===tt)throw new Error(`${k} found map but not enough entries (got ${n} [no value], expected ${t.value})`);yield[o,i]}}function Mp(t,e){let r=!1,n=function(){if(r)throw new Error(`${k} tag decode() may only be called once`);r=!0;let o=rt(t,e);if(o===tt)throw new Error(`${k} tag content missing`);if(o===Ft)throw new Error(`${k} got unexpected break in tag content`);return o};return n.entries=function(){if(r)throw new Error(`${k} tag decode() may only be called once`);r=!0;let o=t.next();if(!l.equals(o.type,l.map))throw new Error(`${k} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of Op(o,t,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return r},enumerable:!1}),n}function rt(t,e){if(t.done())return tt;let r=t.next();if(l.equals(r.type,l.break))return Ft;if(r.type.terminal)return r.value;if(l.equals(r.type,l.array))return Pp(r,t,e);if(l.equals(r.type,l.map))return $p(r,t,e);if(l.equals(r.type,l.tag)){if(e.tags&&typeof e.tags[r.value]=="function"){let n=Mp(t,e),o=e.tags[r.value](n);if(!n._called)throw new Error(`${k} tag decoder must call decode() or entries()`);return o}throw new Error(`${k} tag not supported (${r.value})`)}throw new Error("unsupported")}function Wu(t,e){if(!(t instanceof Uint8Array))throw new Error(`${k} data to decode must be a Uint8Array`);e=Object.assign({},Dp,e);let r=Er(t),n=e.tokenizer||new go(r,e),o=rt(n,e);if(o===tt)throw new Error(`${k} did not find any content to decode`);if(o===Ft)throw new Error(`${k} got unexpected break`);return[o,t.subarray(n.pos())]}function is(t,e){let[r,n]=Wu(t,e);if(n.length>0)throw new Error(`${k} too many terminals, data makes no sense`);return r}var yo=class t{constructor(e,r){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=r}static decoder(e){return r=>new t(e,r())}static preserve(...e){let r={};for(let n of e)r[n]=t.decoder(n);return r}};Object.defineProperty(yo.prototype,Symbol.toStringTag,{value:"Tagged"});var Gu=42;function Qu(t){return t instanceof ArrayBuffer?new Uint8Array(t,0,t.byteLength):t}function zp(t){if(t.asCID!==t&&t["/"]!==t.bytes)return null;let e=L.asCID(t);if(!e)return null;let r=new Uint8Array(e.bytes.byteLength+1);return r.set(e.bytes,1),[new b(l.tag,Gu),new b(l.bytes,r)]}function jp(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function qp(t){if(Number.isNaN(t))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(t===1/0||t===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function Vp(t){for(let e of t.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var ss={float64:!0,typeEncoders:{Map:Vp,Object:zp,undefined:jp,number:qp}},Hp={...ss,typeEncoders:{...ss.typeEncoders}};function Kp(t){let e=t();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return L.decode(e.subarray(1))}var as={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[Gu]:Kp}},Wp={...as,tags:{...as.tags}},Gp="dag-cbor",cs=113,Qp=t=>os(t,ss),Jp=t=>is(Qu(t),as);var Ts={};O(Ts,{code:()=>As,decode:()=>nl,encode:()=>rl,format:()=>Rm,name:()=>Bm,parse:()=>Pm,stringify:()=>Rm});var Yp=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function Ju(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(t instanceof Uint8Array)return"Uint8Array";if(t.constructor===Object)return"Object";let r=Xp(t);return r||"Object"}function Xp(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(Yp.includes(e))return e}var u=class{constructor(e,r,n){this.major=e,this.majorEncoded=e<<5,this.name=r,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,r){return e===r||e.major===r.major&&e.name===r.name}};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 h=class{constructor(e,r,n){this.type=e,this.value=r,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Ur=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Zp=new TextEncoder;function wo(t){return Ur&&globalThis.Buffer.isBuffer(t)}function yt(t){return t instanceof Uint8Array?wo(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var em=24,tm=200,Nr=Ur?t=>t.length>=em?globalThis.Buffer.from(t):Yu(t):t=>t.length>=tm?Zp.encode(t):Yu(t),Pe=t=>Uint8Array.from(t),Zu=Ur?(t,e,r)=>wo(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),ef=Ur?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),yt(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let o of t)n+o.length>r.length&&(o=o.subarray(0,r.length-n)),r.set(o,n),n+=o.length;return r},tf=Ur?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function xo(t,e){if(wo(t)&&wo(e))return t.compare(e);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return 0}function Yu(t){let e=[],r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128)}return e}var Xu=4096;function rf(t){let e=t.length;if(e<=Xu)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Xu));return r}var rm=256,Cr=class{constructor(e=rm){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 r=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=r.length-(this.maxCursor-this.cursor)-1;r.set(e,o)}else{if(r){let o=r.length-(this.maxCursor-this.cursor)-1;o<r.length&&(this.chunks[this.chunks.length-1]=r.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(r=tf(this.chunkSize),this.chunks.push(r),this.maxCursor+=r.length,this._initReuseChunk===null&&(this._initReuseChunk=r),r.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let r;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(r=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):r=Zu(n,0,this.cursor)}else r=ef(this.chunks,this.cursor);return e&&this.reset(),r}},bo=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let r=this.dest.subarray(0,this.cursor);return e&&this.reset(),r}};var E="CBOR decode error:",qe="CBOR encode error:",Lr=[];Lr[23]=1;Lr[24]=2;Lr[25]=3;Lr[26]=5;Lr[27]=9;function Ve(t,e,r){if(t.length-e<r)throw new Error(`${E} not enough data for type`)}var z=[24,256,65536,4294967296,BigInt("18446744073709551616")];function se(t,e,r){Ve(t,e,1);let n=t[e];if(r.strict===!0&&n<z[0])throw new Error(`${E} integer encoded in more bytes than necessary (strict decode)`);return n}function ae(t,e,r){Ve(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<z[1])throw new Error(`${E} integer encoded in more bytes than necessary (strict decode)`);return n}function ce(t,e,r){Ve(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<z[2])throw new Error(`${E} integer encoded in more bytes than necessary (strict decode)`);return n}function ue(t,e,r){Ve(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],o=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(r.strict===!0&&i<z[3])throw new Error(`${E} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(r.allowBigInt===!0)return i;throw new Error(`${E} integers outside of the safe integer range are not supported`)}function nf(t,e,r,n){return new h(u.uint,se(t,e+1,n),2)}function of(t,e,r,n){return new h(u.uint,ae(t,e+1,n),3)}function sf(t,e,r,n){return new h(u.uint,ce(t,e+1,n),5)}function af(t,e,r,n){return new h(u.uint,ue(t,e+1,n),9)}function ge(t,e){return j(t,0,e.value)}function j(t,e,r){if(r<z[0]){let n=Number(r);t.push([e|n])}else if(r<z[1]){let n=Number(r);t.push([e|24,n])}else if(r<z[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<z[3]){let n=Number(r);t.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(r);if(n<z[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,t.push(o)}else throw new Error(`${E} encountered BigInt larger than allowable range`)}}ge.encodedSize=function(e){return j.encodedSize(e.value)};j.encodedSize=function(e){return e<z[0]?1:e<z[1]?2:e<z[2]?3:e<z[3]?5:9};ge.compareTokens=function(e,r){return e.value<r.value?-1:e.value>r.value?1:0};function cf(t,e,r,n){return new h(u.negint,-1-se(t,e+1,n),2)}function uf(t,e,r,n){return new h(u.negint,-1-ae(t,e+1,n),3)}function ff(t,e,r,n){return new h(u.negint,-1-ce(t,e+1,n),5)}var fs=BigInt(-1),lf=BigInt(1);function df(t,e,r,n){let o=ue(t,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new h(u.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${E} integers outside of the safe integer range are not supported`);return new h(u.negint,fs-BigInt(o),9)}function Eo(t,e){let r=e.value,n=typeof r=="bigint"?r*fs-lf:r*-1-1;j(t,e.type.majorEncoded,n)}Eo.encodedSize=function(e){let r=e.value,n=typeof r=="bigint"?r*fs-lf:r*-1-1;return n<z[0]?1:n<z[1]?2:n<z[2]?3:n<z[3]?5:9};Eo.compareTokens=function(e,r){return e.value<r.value?1:e.value>r.value?-1:0};function Br(t,e,r,n){Ve(t,e,r+n);let o=t.slice(e+r,e+r+n);return new h(u.bytes,o,r+n)}function hf(t,e,r,n){return Br(t,e,1,r)}function pf(t,e,r,n){return Br(t,e,2,se(t,e+1,n))}function mf(t,e,r,n){return Br(t,e,3,ae(t,e+1,n))}function gf(t,e,r,n){return Br(t,e,5,ce(t,e+1,n))}function yf(t,e,r,n){let o=ue(t,e+1,n);if(typeof o=="bigint")throw new Error(`${E} 64-bit integer bytes lengths not supported`);return Br(t,e,9,o)}function _o(t){return t.encodedBytes===void 0&&(t.encodedBytes=u.equals(t.type,u.string)?Nr(t.value):t.value),t.encodedBytes}function zt(t,e){let r=_o(e);j(t,e.type.majorEncoded,r.length),t.push(r)}zt.encodedSize=function(e){let r=_o(e);return j.encodedSize(r.length)+r.length};zt.compareTokens=function(e,r){return om(_o(e),_o(r))};function om(t,e){return t.length<e.length?-1:t.length>e.length?1:xo(t,e)}var wf=new TextDecoder,sm=32;function am(t,e,r){if(r-e<sm){let o="";for(let i=e;i<r;i++){let s=t[i];if(s&128)return wf.decode(t.subarray(e,r));o+=String.fromCharCode(s)}return o}return wf.decode(t.subarray(e,r))}function Rr(t,e,r,n,o){let i=r+n;Ve(t,e,i);let s=new h(u.string,am(t,e+r,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=t.slice(e+r,e+i)),s}function xf(t,e,r,n){return Rr(t,e,1,r,n)}function bf(t,e,r,n){return Rr(t,e,2,se(t,e+1,n),n)}function Ef(t,e,r,n){return Rr(t,e,3,ae(t,e+1,n),n)}function _f(t,e,r,n){return Rr(t,e,5,ce(t,e+1,n),n)}function vf(t,e,r,n){let o=ue(t,e+1,n);if(typeof o=="bigint")throw new Error(`${E} 64-bit integer string lengths not supported`);return Rr(t,e,9,o,n)}var kf=zt;function jt(t,e,r,n){return new h(u.array,n,r)}function Af(t,e,r,n){return jt(t,e,1,r)}function Tf(t,e,r,n){return jt(t,e,2,se(t,e+1,n))}function If(t,e,r,n){return jt(t,e,3,ae(t,e+1,n))}function Sf(t,e,r,n){return jt(t,e,5,ce(t,e+1,n))}function Uf(t,e,r,n){let o=ue(t,e+1,n);if(typeof o=="bigint")throw new Error(`${E} 64-bit integer array lengths not supported`);return jt(t,e,9,o)}function Nf(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${E} indefinite length items not allowed`);return jt(t,e,1,1/0)}function vo(t,e){j(t,u.array.majorEncoded,e.value)}vo.compareTokens=ge.compareTokens;vo.encodedSize=function(e){return j.encodedSize(e.value)};function qt(t,e,r,n){return new h(u.map,n,r)}function Cf(t,e,r,n){return qt(t,e,1,r)}function Lf(t,e,r,n){return qt(t,e,2,se(t,e+1,n))}function Bf(t,e,r,n){return qt(t,e,3,ae(t,e+1,n))}function Rf(t,e,r,n){return qt(t,e,5,ce(t,e+1,n))}function Df(t,e,r,n){let o=ue(t,e+1,n);if(typeof o=="bigint")throw new Error(`${E} 64-bit integer map lengths not supported`);return qt(t,e,9,o)}function Pf(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${E} indefinite length items not allowed`);return qt(t,e,1,1/0)}function ko(t,e){j(t,u.map.majorEncoded,e.value)}ko.compareTokens=ge.compareTokens;ko.encodedSize=function(e){return j.encodedSize(e.value)};function $f(t,e,r,n){return new h(u.tag,r,1)}function Of(t,e,r,n){return new h(u.tag,se(t,e+1,n),2)}function Mf(t,e,r,n){return new h(u.tag,ae(t,e+1,n),3)}function Ff(t,e,r,n){return new h(u.tag,ce(t,e+1,n),5)}function zf(t,e,r,n){return new h(u.tag,ue(t,e+1,n),9)}function Ao(t,e){j(t,u.tag.majorEncoded,e.value)}Ao.compareTokens=ge.compareTokens;Ao.encodedSize=function(e){return j.encodedSize(e.value)};var ls=20,ds=21,hs=22,ps=23;function jf(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${E} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new h(u.null,null,1):new h(u.undefined,void 0,1)}function qf(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${E} indefinite length items not allowed`);return new h(u.break,void 0,1)}function ms(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${E} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${E} Infinity values are not supported`)}return new h(u.float,t,e)}function Vf(t,e,r,n){return ms(gs(t,e+1),3,n)}function Hf(t,e,r,n){return ms(ys(t,e+1),5,n)}function Kf(t,e,r,n){return ms(Jf(t,e+1),9,n)}function To(t,e,r){let n=e.value;if(n===!1)t.push([u.float.majorEncoded|ls]);else if(n===!0)t.push([u.float.majorEncoded|ds]);else if(n===null)t.push([u.float.majorEncoded|hs]);else if(n===void 0)t.push([u.float.majorEncoded|ps]);else{let o,i=!1;(!r||r.float64!==!0)&&(Gf(n),o=gs(Se,1),n===o||Number.isNaN(n)?(Se[0]=249,t.push(Se.slice(0,3)),i=!0):(Qf(n),o=ys(Se,1),n===o&&(Se[0]=250,t.push(Se.slice(0,5)),i=!0))),i||(dm(n),o=Jf(Se,1),Se[0]=251,t.push(Se.slice(0,9)))}}To.encodedSize=function(e,r){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!r||r.float64!==!0){Gf(n);let o=gs(Se,1);if(n===o||Number.isNaN(n))return 3;if(Qf(n),o=ys(Se,1),n===o)return 5}return 9};var Wf=new ArrayBuffer(9),ye=new DataView(Wf,1),Se=new Uint8Array(Wf,0);function Gf(t){if(t===1/0)ye.setUint16(0,31744,!1);else if(t===-1/0)ye.setUint16(0,64512,!1);else if(Number.isNaN(t))ye.setUint16(0,32256,!1);else{ye.setFloat32(0,t);let e=ye.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)ye.setUint16(0,31744,!1);else if(r===0)ye.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=r-127;o<-24?ye.setUint16(0,0):o<-14?ye.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):ye.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function gs(t,e){if(t.length-e<2)throw new Error(`${E} not enough data for float16`);let r=(t[e]<<8)+t[e+1];if(r===31744)return 1/0;if(r===64512)return-1/0;if(r===32256)return NaN;let n=r>>10&31,o=r&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,r&32768?-i:i}function Qf(t){ye.setFloat32(0,t,!1)}function ys(t,e){if(t.length-e<4)throw new Error(`${E} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function dm(t){ye.setFloat64(0,t,!1)}function Jf(t,e){if(t.length-e<8)throw new Error(`${E} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}To.compareTokens=ge.compareTokens;function C(t,e,r){throw new Error(`${E} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function Io(t){return()=>{throw new Error(`${E} ${t}`)}}var w=[];for(let t=0;t<=23;t++)w[t]=C;w[24]=nf;w[25]=of;w[26]=sf;w[27]=af;w[28]=C;w[29]=C;w[30]=C;w[31]=C;for(let t=32;t<=55;t++)w[t]=C;w[56]=cf;w[57]=uf;w[58]=ff;w[59]=df;w[60]=C;w[61]=C;w[62]=C;w[63]=C;for(let t=64;t<=87;t++)w[t]=hf;w[88]=pf;w[89]=mf;w[90]=gf;w[91]=yf;w[92]=C;w[93]=C;w[94]=C;w[95]=Io("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)w[t]=xf;w[120]=bf;w[121]=Ef;w[122]=_f;w[123]=vf;w[124]=C;w[125]=C;w[126]=C;w[127]=Io("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)w[t]=Af;w[152]=Tf;w[153]=If;w[154]=Sf;w[155]=Uf;w[156]=C;w[157]=C;w[158]=C;w[159]=Nf;for(let t=160;t<=183;t++)w[t]=Cf;w[184]=Lf;w[185]=Bf;w[186]=Rf;w[187]=Df;w[188]=C;w[189]=C;w[190]=C;w[191]=Pf;for(let t=192;t<=215;t++)w[t]=$f;w[216]=Of;w[217]=Mf;w[218]=Ff;w[219]=zf;w[220]=C;w[221]=C;w[222]=C;w[223]=C;for(let t=224;t<=243;t++)w[t]=Io("simple values are not supported");w[244]=C;w[245]=C;w[246]=C;w[247]=jf;w[248]=Io("simple values are not supported");w[249]=Vf;w[250]=Hf;w[251]=Kf;w[252]=C;w[253]=C;w[254]=C;w[255]=qf;var Ue=[];for(let t=0;t<24;t++)Ue[t]=new h(u.uint,t,1);for(let t=-1;t>=-24;t--)Ue[31-t]=new h(u.negint,t,1);Ue[64]=new h(u.bytes,new Uint8Array(0),1);Ue[96]=new h(u.string,"",1);Ue[128]=new h(u.array,0,1);Ue[160]=new h(u.map,0,1);Ue[244]=new h(u.false,!1,1);Ue[245]=new h(u.true,!0,1);Ue[246]=new h(u.null,null,1);function Yf(t){switch(t.type){case u.false:return Pe([244]);case u.true:return Pe([245]);case u.null:return Pe([246]);case u.bytes:return t.value.length?void 0:Pe([64]);case u.string:return t.value===""?Pe([96]):void 0;case u.array:return t.value===0?Pe([128]):void 0;case u.map:return t.value===0?Pe([160]):void 0;case u.uint:return t.value<24?Pe([Number(t.value)]):void 0;case u.negint:if(t.value>=-24)return Pe([31-Number(t.value)])}}var Zf=Object.freeze({float64:!0,mapSorter:wm,quickEncodeToken:Yf});function pm(){let t=[];return t[u.uint.major]=ge,t[u.negint.major]=Eo,t[u.bytes.major]=zt,t[u.string.major]=kf,t[u.array.major]=vo,t[u.map.major]=ko,t[u.tag.major]=Ao,t[u.float.major]=To,t}var mm=pm(),gm=new Cr,So=class t{constructor(e,r){this.obj=e,this.parent=r}includes(e){let r=this;do if(r.obj===e)return!0;while(r=r.parent);return!1}static createCheck(e,r){if(e&&e.includes(r))throw new Error(`${qe} object contains circular references`);return new t(r,e)}},nt={null:new h(u.null,null),undefined:new h(u.undefined,void 0),true:new h(u.true,!0),false:new h(u.false,!1),emptyArray:new h(u.array,0),emptyMap:new h(u.map,0)},ot={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new h(u.float,t):t>=0?new h(u.uint,t):new h(u.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new h(u.uint,t):new h(u.negint,t)},Uint8Array(t,e,r,n){return new h(u.bytes,t)},string(t,e,r,n){return new h(u.string,t)},boolean(t,e,r,n){return t?nt.true:nt.false},null(t,e,r,n){return nt.null},undefined(t,e,r,n){return nt.undefined},ArrayBuffer(t,e,r,n){return new h(u.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new h(u.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[nt.emptyArray,new h(u.break)]:nt.emptyArray;n=So.createCheck(n,t);let o=[],i=0;for(let s of t)o[i++]=Vt(s,r,n);return r.addBreakTokens?[new h(u.array,t.length),o,new h(u.break)]:[new h(u.array,t.length),o]},Object(t,e,r,n){let o=e!=="Object",i=o?t.keys():Object.keys(t),s=o?t.size:i.length,a;if(s){a=new Array(s),n=So.createCheck(n,t);let c=!o&&r.ignoreUndefinedProperties,f=0;for(let p of i){let m=o?t.get(p):t[p];c&&m===void 0||(a[f++]=[Vt(p,r,n),Vt(m,r,n)])}f<s&&(a.length=f)}return a?.length?(ym(a,r),r.addBreakTokens?[new h(u.map,a.length),a,new h(u.break)]:[new h(u.map,a.length),a]):r.addBreakTokens===!0?[nt.emptyMap,new h(u.break)]:nt.emptyMap},Tagged(t,e,r,n){return[new h(u.tag,t.tag),Vt(t.value,r,n)]}};ot.Map=ot.Object;ot.Buffer=ot.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ot[`${t}Array`]=ot.DataView;function Vt(t,e={},r){let n=Ju(t),o=e&&e.typeEncoders&&e.typeEncoders[n]||ot[n];if(typeof o=="function"){let s=o(t,n,e,r);if(s!=null)return s}let i=ot[n];if(!i)throw new Error(`${qe} unsupported type: ${n}`);return i(t,n,e,r)}function ym(t,e){e.mapSorter&&t.sort(e.mapSorter)}function wm(t,e){if(t[0]instanceof h&&e[0]instanceof h){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=Xf(r.value)),n._keyBytes||(n._keyBytes=Xf(n.value)),xo(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Xf(t){return ws(t,mm,Zf)}function el(t,e,r,n){if(Array.isArray(e))for(let o of e)el(t,o,r,n);else r[e.type.major](t,e,n)}var y1=u.uint.majorEncoded,w1=u.negint.majorEncoded,x1=u.bytes.majorEncoded,b1=u.string.majorEncoded,E1=u.array.majorEncoded,_1=u.float.majorEncoded|ls,v1=u.float.majorEncoded|ds,k1=u.float.majorEncoded|hs,A1=u.float.majorEncoded|ps,T1=BigInt(-1),I1=BigInt(1);function ws(t,e,r,n){let o=n instanceof Uint8Array,i=o?new bo(n):gm,s=Vt(t,r);if(!Array.isArray(s)&&r.quickEncodeToken){let a=r.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let f=c.encodedSize(s,r);if(o||(i=new Cr(f)),c(i,s,r),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():yt(i.chunks[0])}}return i.reset(),el(i,s,e,r),i.toBytes(!0)}var xm={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Uo=class{constructor(e,r={}){this._pos=0,this.data=e,this.options=r}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],r=Ue[e];if(r===void 0){let n=w[e];if(!n)throw new Error(`${E} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;r=n(this.data,this._pos,o,this.options)}return this._pos+=r.encodedLength,r}},it=Symbol.for("DONE"),Ht=Symbol.for("BREAK");function bm(t,e,r){let n=[];for(let o=0;o<t.value;o++){let i=st(e,r);if(i===Ht){if(t.value===1/0)break;throw new Error(`${E} got unexpected break to lengthed array`)}if(i===it)throw new Error(`${E} found array but not enough entries (got ${o}, expected ${t.value})`);n[o]=i}return n}function Em(t,e,r){let n=r.useMaps===!0,o=r.rejectDuplicateMapKeys===!0,i=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<t.value;a++){let c=st(e,r);if(c===Ht){if(t.value===1/0)break;throw new Error(`${E} got unexpected break to lengthed map`)}if(c===it)throw new Error(`${E} found map but not enough entries (got ${a} [no key], expected ${t.value})`);if(!n&&typeof c!="string")throw new Error(`${E} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${E} found repeat map key "${c}"`);let f=st(e,r);if(f===it)throw new Error(`${E} found map but not enough entries (got ${a} [no value], expected ${t.value})`);n?s.set(c,f):i[c]=f}return n?s:i}function*_m(t,e,r){for(let n=0;n<t.value;n++){let o=st(e,r);if(o===Ht){if(t.value===1/0)break;throw new Error(`${E} got unexpected break to lengthed map`)}if(o===it)throw new Error(`${E} found map but not enough entries (got ${n} [no key], expected ${t.value})`);let i=st(e,r);if(i===it)throw new Error(`${E} found map but not enough entries (got ${n} [no value], expected ${t.value})`);yield[o,i]}}function vm(t,e){let r=!1,n=function(){if(r)throw new Error(`${E} tag decode() may only be called once`);r=!0;let o=st(t,e);if(o===it)throw new Error(`${E} tag content missing`);if(o===Ht)throw new Error(`${E} got unexpected break in tag content`);return o};return n.entries=function(){if(r)throw new Error(`${E} tag decode() may only be called once`);r=!0;let o=t.next();if(!u.equals(o.type,u.map))throw new Error(`${E} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of _m(o,t,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return r},enumerable:!1}),n}function st(t,e){if(t.done())return it;let r=t.next();if(u.equals(r.type,u.break))return Ht;if(r.type.terminal)return r.value;if(u.equals(r.type,u.array))return bm(r,t,e);if(u.equals(r.type,u.map))return Em(r,t,e);if(u.equals(r.type,u.tag)){if(e.tags&&typeof e.tags[r.value]=="function"){let n=vm(t,e),o=e.tags[r.value](n);if(!n._called)throw new Error(`${E} tag decoder must call decode() or entries()`);return o}throw new Error(`${E} tag not supported (${r.value})`)}throw new Error("unsupported")}function xs(t,e){if(!(t instanceof Uint8Array))throw new Error(`${E} data to decode must be a Uint8Array`);e=Object.assign({},xm,e);let r=yt(t),n=e.tokenizer||new Uo(r,e),o=st(n,e);if(o===it)throw new Error(`${E} did not find any content to decode`);if(o===Ht)throw new Error(`${E} got unexpected break`);return[o,t.subarray(n.pos())]}function bs(t,e){let[r,n]=xs(t,e);if(n.length>0)throw new Error(`${E} too many terminals, data makes no sense`);return r}var No=class t{constructor(e,r){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=r}static decoder(e){return r=>new t(e,r())}static preserve(...e){let r={};for(let n of e)r[n]=t.decoder(n);return r}};Object.defineProperty(No.prototype,Symbol.toStringTag,{value:"Tagged"});var Es=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let r=this.inRecursive[this.inRecursive.length-1];r&&(u.equals(r.type,u.array)&&(r.elements++,r.elements!==1&&e.push([44])),u.equals(r.type,u.map)&&(r.elements++,r.elements!==1&&(r.elements%2===1?e.push([44]):e.push([58]))))}[u.uint.major](e,r){this.prefix(e);let n=String(r.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[u.negint.major](e,r){this[u.uint.major](e,r)}[u.bytes.major](e,r){throw new Error(`${qe} unsupported type: Uint8Array`)}[u.string.major](e,r){this.prefix(e);let n=Nr(JSON.stringify(r.value));e.push(n.length>32?yt(n):n)}[u.array.major](e,r){this.prefix(e),this.inRecursive.push({type:u.array,elements:0}),e.push([91])}[u.map.major](e,r){this.prefix(e),this.inRecursive.push({type:u.map,elements:0}),e.push([123])}[u.tag.major](e,r){}[u.float.major](e,r){if(r.type.name==="break"){let s=this.inRecursive.pop();if(s){if(u.equals(s.type,u.array))e.push([93]);else if(u.equals(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(r.value===void 0)throw new Error(`${qe} unsupported type: undefined`);if(this.prefix(e),r.type.name==="true"){e.push([116,114,117,101]);return}else if(r.type.name==="false"){e.push([102,97,108,115,101]);return}else if(r.type.name==="null"){e.push([110,117,108,108]);return}let n=String(r.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 km(t,e){if(Array.isArray(t[0])||Array.isArray(e[0]))throw new Error(`${qe} complex map keys are not supported`);let r=t[0],n=e[0];if(r.type!==u.string||n.type!==u.string)throw new Error(`${qe} non-string map keys are not supported`);if(r<n)return-1;if(r>n)return 1;throw new Error(`${qe} unexpected duplicate map keys, this is not supported`)}var Am={addBreakTokens:!0,mapSorter:km};function _s(t,e){return e=Object.assign({},Am,e),ws(t,new Es,e)}var Kt=class{constructor(e,r={}){this._pos=0,this.data=e,this.options=r,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(`${E} unexpected end of input at position ${this._pos}`);for(let r=0;r<e.length;r++)if(this.data[this._pos++]!==e[r])throw new Error(`${E} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,r=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(r=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new h(u.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),r&&this._pos===e+1)throw new Error(`${E} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${E} 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 h(u.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new h(s>=0?u.uint:u.negint,s,this._pos-e):new h(s>=0?u.uint:u.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${E} 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 a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new h(u.string,c,s)}}let e=this._pos,r=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${E} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${E} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${E} unexpected unicode sequence at position ${this._pos}`);let c,f,p,m;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(m=(i&31)<<6|c&63,m>127&&(s=m));break;case 3:c=this.data[this._pos+1],f=this.data[this._pos+2],(c&192)===128&&(f&192)===128&&(m=(i&15)<<12|(c&63)<<6|f&63,m>2047&&(m<55296||m>57343)&&(s=m));break;case 4:c=this.data[this._pos+1],f=this.data[this._pos+2],p=this.data[this._pos+3],(c&192)===128&&(f&192)===128&&(p&192)===128&&(m=(i&15)<<18|(c&63)<<12|(f&63)<<6|p&63,m>65535&&m<1114112&&(s=m))}s===null?(s=65533,a=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|s&1023),r.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${E} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:r.push(s);break;case 98:r.push(8);break;case 116:r.push(9);break;case 110:r.push(10);break;case 102:r.push(12);break;case 114:r.push(13);break;case 117:r.push(n());break;default:throw new Error(`${E} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new h(u.string,rf(r),this._pos-e);default:if(i<32)throw new Error(`${E} invalid control character at position ${this._pos}`);i<128?(r.push(i),this._pos++):o()}}throw new Error(`${E} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new h(u.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new h(u.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new h(u.null,null,4);case 102:return this.expect([102,97,108,115,101]),new h(u.false,!1,5);case 116:return this.expect([116,114,117,101]),new h(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(`${E} 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 h(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${E} 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 h(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 h(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${E} 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 h(u.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${E} 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(`${E} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function vs(t,e){return e=Object.assign({tokenizer:new Kt(t,e)},e),bs(t,e)}function Im(t){return t instanceof ArrayBuffer?new Uint8Array(t,0,t.byteLength):t}function Sm(t){if(t.asCID!==t&&t["/"]!==t.bytes)return null;let e=L.asCID(t);if(!e)return null;let r=e.toString();return[new h(u.map,1/0,1),new h(u.string,"/",1),new h(u.string,r,r.length),new h(u.break,void 0,1)]}function Co(t){let e=vt.encode(t).slice(1);return[new h(u.map,1/0,1),new h(u.string,"/",1),new h(u.map,1/0,1),new h(u.string,"bytes",5),new h(u.string,e,e.length),new h(u.break,void 0,1),new h(u.break,void 0,1)]}function Ne(t){return Co(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function Um(t){return Co(new Uint8Array(t))}function Nm(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Cm(t){if(Number.isNaN(t))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(t===1/0||t===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var Lm={typeEncoders:{Object:Sm,Buffer:Co,Uint8Array:Co,Int8Array:Ne,Uint16Array:Ne,Int16Array:Ne,Uint32Array:Ne,Int32Array:Ne,Float32Array:Ne,Float64Array:Ne,Uint8ClampedArray:Ne,BigInt64Array:Ne,BigUint64Array:Ne,DataView:Ne,ArrayBuffer:Um,undefined:Nm,number:Cm}},ks=class extends Kt{constructor(e,r){super(e,r),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(u.equals(e.type,u.map)){let r=this._next();if(u.equals(r.type,u.string)&&r.value==="/"){let n=this._next();if(u.equals(n.type,u.string)){let o=this._next();if(!u.equals(o.type,u.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new h(u.tag,42,0)}if(u.equals(n.type,u.map)){let o=this._next();if(u.equals(o.type,u.string)&&o.value==="bytes"){let i=this._next();if(u.equals(i.type,u.string)){for(let a=0;a<2;a++){let c=this._next();if(!u.equals(c.type,u.break))throw new Error("Invalid encoded Bytes form")}let s=vt.decode(`m${i.value}`);return new h(u.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}return e}},tl={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:t=>L.parse(t())}},Bm="dag-json",As=297,rl=t=>_s(t,Lm),nl=t=>{let e=Im(t),r=Object.assign(tl,{tokenizer:new ks(e,tl)});return vs(e,r)},Rm=t=>Dm.decode(rl(t));var Dm=new TextDecoder,Pm=t=>nl($m.encode(t)),$m=new TextEncoder;var Ls={};O(Ls,{code:()=>Cs,createLink:()=>hl,createNode:()=>dl,decode:()=>Jm,encode:()=>Qm,name:()=>Gm,prepare:()=>Us,validate:()=>Ns});var Om=new TextDecoder;function Is(t,e){let r=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=t.length)throw new Error("protobuf: unexpected end of data");let o=t[e++];if(r+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[r,e]}function Lo(t,e){let r;[r,e]=Is(t,e);let n=e+r;if(r<0||n<0)throw new Error("protobuf: invalid length");if(n>t.length)throw new Error("protobuf: unexpected end of data");return[t.subarray(e,n),n]}function ol(t,e){let r;return[r,e]=Is(t,e),[r&7,r>>3,e]}function Mm(t){let e={},r=t.length,n=0;for(;n<r;){let o,i;if([o,i,n]=ol(t,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]=Lo(t,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]=Lo(t,n),e.Name=Om.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]=Is(t,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>r)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function il(t){let e=t.length,r=0,n,o=!1,i;for(;r<e;){let a,c;if([a,c,r]=ol(t,r),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,r]=Lo(t,r),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let f;[f,r]=Lo(t,r),n.push(Mm(f))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(r>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var al=new TextEncoder,sl=2**32,Fm=2**31;function zm(t,e){let r=e.length;if(typeof t.Tsize=="number"){if(t.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(t.Tsize))throw new Error("Tsize too large for encoding");r=Dr(e,r,t.Tsize)-1,e[r]=24}if(typeof t.Name=="string"){let n=al.encode(t.Name);r-=n.length,e.set(n,r),r=Dr(e,r,n.length)-1,e[r]=18}return t.Hash&&(r-=t.Hash.length,e.set(t.Hash,r),r=Dr(e,r,t.Hash.length)-1,e[r]=10),e.length-r}function cl(t){let e=qm(t),r=new Uint8Array(e),n=e;if(t.Data&&(n-=t.Data.length,r.set(t.Data,n),n=Dr(r,n,t.Data.length)-1,r[n]=10),t.Links)for(let o=t.Links.length-1;o>=0;o--){let i=zm(t.Links[o],r.subarray(0,n));n-=i,n=Dr(r,n,i)-1,r[n]=18}return r}function jm(t){let e=0;if(t.Hash){let r=t.Hash.length;e+=1+r+Wt(r)}if(typeof t.Name=="string"){let r=al.encode(t.Name).length;e+=1+r+Wt(r)}return typeof t.Tsize=="number"&&(e+=1+Wt(t.Tsize)),e}function qm(t){let e=0;if(t.Data){let r=t.Data.length;e+=1+r+Wt(r)}if(t.Links)for(let r of t.Links){let n=jm(r);e+=1+n+Wt(n)}return e}function Dr(t,e,r){e-=Wt(r);let n=e;for(;r>=Fm;)t[e++]=r&127|128,r/=128;for(;r>=128;)t[e++]=r&127|128,r>>>=7;return t[e]=r,n}function Wt(t){return t%2===0&&t++,Math.floor((Vm(t)+6)/7)}function Vm(t){let e=0;return t>=sl&&(t=Math.floor(t/sl),e=32),t>=65536&&(t>>>=16,e+=16),t>=256&&(t>>>=8,e+=8),e+Hm[t]}var Hm=[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 Km=["Data","Links"],Wm=["Hash","Name","Tsize"],Ss=new TextEncoder;function fl(t,e){if(t===e)return 0;let r=t.Name?Ss.encode(t.Name):[],n=e.Name?Ss.encode(e.Name):[],o=r.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(r[s]!==n[s]){o=r[s],i=n[s];break}return o<i?-1:i<o?1:0}function ul(t,e){return!Object.keys(t).some(r=>!e.includes(r))}function ll(t){if(typeof t.asCID=="object"){let r=L.asCID(t);if(!r)throw new TypeError("Invalid DAG-PB form");return{Hash:r}}if(typeof t!="object"||Array.isArray(t))throw new TypeError("Invalid DAG-PB form");let e={};if(t.Hash){let r=L.asCID(t.Hash);try{r||(typeof t.Hash=="string"?r=L.parse(t.Hash):t.Hash instanceof Uint8Array&&(r=L.decode(t.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}r&&(e.Hash=r)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof t.Name=="string"&&(e.Name=t.Name),typeof t.Tsize=="number"&&(e.Tsize=t.Tsize),e}function Us(t){if((t instanceof Uint8Array||typeof t=="string")&&(t={Data:t}),typeof t!="object"||Array.isArray(t))throw new TypeError("Invalid DAG-PB form");let e={};if(t.Data!==void 0)if(typeof t.Data=="string")e.Data=Ss.encode(t.Data);else if(t.Data instanceof Uint8Array)e.Data=t.Data;else throw new TypeError("Invalid DAG-PB form");if(t.Links!==void 0)if(Array.isArray(t.Links))e.Links=t.Links.map(ll),e.Links.sort(fl);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Ns(t){if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form");if(!ul(t,Km))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(t.Data!==void 0&&!(t.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(t.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<t.Links.length;e++){let r=t.Links[e];if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!ul(r,Wm))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(r.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(r.Hash==null||!r.Hash["/"]||r.Hash["/"]!==r.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(r.Name!==void 0&&typeof r.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(r.Tsize!==void 0){if(typeof r.Tsize!="number"||r.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(r.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&fl(r,t.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function dl(t,e=[]){return Us({Data:t,Links:e})}function hl(t,e,r){return ll({Hash:r,Name:t,Tsize:e})}function pl(t){return t instanceof ArrayBuffer?new Uint8Array(t,0,t.byteLength):t}var Gm="dag-pb",Cs=112;function Qm(t){Ns(t);let e={};return t.Links&&(e.Links=t.Links.map(r=>{let n={};return r.Hash&&(n.Hash=r.Hash.bytes),r.Name!==void 0&&(n.Name=r.Name),r.Tsize!==void 0&&(n.Tsize=r.Tsize),n})),t.Data&&(e.Data=t.Data),cl(e)}function Jm(t){let e=pl(t),r=il(e),n={};return r.Data&&(n.Data=r.Data),r.Links&&(n.Links=r.Links.map(o=>{let i={};try{i.Hash=L.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 Gt(t){return t?.then!=null}function ml(t=[],e){let r={[Cs]:Ls,[ci]:Hr,[cs]:us,[As]:Ts,[ai]:Vr};return t.forEach(n=>{r[n.code]=n}),async n=>{let o=r[n];if(o==null&&e!=null){let i=e(n);Gt(i)?o=await i:o=i,r[o.code]=o}if(o!=null)return o;throw new $n(`Could not load codec for ${n}`)}}function gl(t=[],e){let r={[Gr.code]:Gr,[Qr.code]:Qr,[Wr.code]:Wr};return t.forEach(n=>{r[n.code]=n}),async n=>{let o=r[n];if(o==null&&e!=null){let i=e(n);Gt(i)?o=await i:o=i,r[o.code]=o}if(o!=null)return o;throw new Pn(`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`)}}var Bo=class t extends Error{static name="NotFoundError";name=t.name;static code="ERR_NOT_FOUND";code=t.code;constructor(e="Not Found"){super(e)}};var Ro=class{has(e,r){return Promise.reject(new Error(".has is not implemented"))}put(e,r,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,r){for await(let{cid:n,bytes:o}of e)await this.put(n,o,r),yield n}get(e,r){throw new Error(".get is not implemented")}async*getMany(e,r){for await(let n of e)yield{cid:n,bytes:this.get(n,r)}}delete(e,r){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,r){for await(let n of e)await this.delete(n,r),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Do=0,Qt=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},Po=class extends Ro{child;maxDigestLength;constructor(e,r){super(),this.child=e,this.maxDigestLength=r?.maxDigestLength}put(e,r,n){if(e.multihash.code===Do){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,r,n)}async*get(e,r){if(e.multihash.code===Do){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);r?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw r?.signal?.throwIfAborted(),new Bo;yield*this.child.get(e,r)}has(e,r){if(e.multihash.code===Do){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return r?.signal?.throwIfAborted(),!0}return this.child==null?(r?.signal?.throwIfAborted(),!1):this.child.has(e,r)}delete(e,r){if(e.code===Do){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);r?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,r)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function Ym(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[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(),[r](){return this}}}var $o=Ym;function Xm(t){return t[Symbol.asyncIterator]!=null}function Zm(t,e){let r=0;if(Xm(t))return(async function*(){for await(let c of t)await e(c,r++)&&(yield c)})();let n=$o(t),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,r++);if(typeof s.then=="function")return(async function*(){await s&&(yield o);for(let c of n)await e(c,r++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield o);for(let c of n)a(c,r++)&&(yield c)})()}var Oo=Zm;function eg(t){return t[Symbol.asyncIterator]!=null}function yl(t){return t?.then!=null}function tg(t,e){let r=0;if(eg(t))return(async function*(){for await(let c of t){let f=e(c,r++);yl(f)&&await f,yield c}})();let n=$o(t),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,r++);if(typeof s?.then=="function")return(async function*(){await s,yield o;for(let c of n){let f=e(c,r++);yl(f)&&await f,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,r++),yield c})()}var Bs=tg;var ng=128,Jt=class{child;getHasher;log;logger;blockBrokers;constructor(e,r={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new Po(e.blockstore,{maxDigestLength:r.maxIdentityHashDigestLength??ng}),this.getHasher=e.getHasher}async put(e,r,n={}){return await this.child.has(e,n)?(n.onProgress?.(new T("blocks:put:duplicate",e)),e):(n.onProgress?.(new T("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new T("blocks:put:blockstore:put",e)),this.child.put(e,r,n))}async*putMany(e,r={}){let n=Oo(e,async({cid:i})=>{let s=await this.child.has(i,r);return s&&r.onProgress?.(new T("blocks:put-many:duplicate",i)),!s}),o=Bs(n,async({cid:i})=>{r.onProgress?.(new T("blocks:put-many:providers:notify",i)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(i,r)))});r.onProgress?.(new T("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,r)}async*get(e,r={}){let n=await this.child.has(e,r),o=r.offline===!0;if(!n){if(o)throw new yr("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(e.multihash.code);r?.signal?.throwIfAborted(),r.onProgress?.(new T("blocks:get:providers:get",e));let s=await wl(e,this.blockBrokers,i,{...r,log:this.log});r.onProgress?.(new T("blocks:get:blockstore:put",e)),await this.child.put(e,s,r),r.onProgress?.(new T("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,r))),yield s;return}r.onProgress?.(new T("blocks:get:blockstore:get",e)),yield*this.child.get(e,r)}async*getMany(e,r={}){r.onProgress?.(new T("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Bs(e,async n=>{let o=await this.child.has(n,r),i=r.offline===!0;if(!o){if(i)throw new yr("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(n.multihash.code);r?.signal?.throwIfAborted(),r.onProgress?.(new T("blocks:get-many:providers:get",n));let a=await wl(n,this.blockBrokers,s,{...r,log:this.log});r.onProgress?.(new T("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,r),r.onProgress?.(new T("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,r)))}}))}async delete(e,r={}){r.onProgress?.(new T("blocks:delete:blockstore:delete",e)),await this.child.delete(e,r)}async*deleteMany(e,r={}){r.onProgress?.(new T("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany((async function*(){for await(let n of e)yield n})(),r)}async has(e,r={}){return this.child.has(e,r)}async*getAll(e={}){e.onProgress?.(new T("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function wl(t,e,r,n){let o=ig(t,r),i=new AbortController,s=ve([i.signal,n.signal]);i.signal;let a=[];for(let c of e)og(c)&&a.push(c);if(a.length===0)throw new dt(`No block brokers capable of retrieving blocks are configured, the CID ${t} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let f=!1,p=await c.retrieve(t,{...n,signal:s,validateFn:async m=>{await o(m),n.signal?.throwIfAborted(),f=!0}});return f||(await o(p),n.signal?.throwIfAborted()),p}catch(f){throw n.log.error("could not retrieve verified block for %c from %s - %e",t,c.name,f),f}}))}catch(c){throw new Ln(c.errors,`Failed to load block for ${t}`)}finally{i.abort(),s.clear()}}function og(t){return typeof t.retrieve=="function"}var ig=(t,e)=>{if(e==null)throw new xt(`No hasher configured for multihash code 0x${t.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 r=>{let n,o=e.digest(r,{truncate:t.multihash.digest.byteLength});if(Gt(o)?n=await o:n=o,!at(n.digest,t.multihash.digest))throw new Fr("Hash of downloaded block did not match multihash from passed CID")}};var Mo=class extends Jt{closeController;constructor(e,r){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${r.root}`)}close(){this.closeController.abort()}async addPeer(e,r){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,r)))}async put(e,r,n={}){let o=ve([this.closeController.signal,n.signal]);try{return await super.put(e,r,{...n,signal:o})}finally{o.clear()}}async*putMany(e,r={}){let n=ve([this.closeController.signal,r.signal]);try{yield*super.putMany(e,{...r,signal:n})}finally{n.clear()}}async*get(e,r={}){let n=ve([this.closeController.signal,r.signal]);try{yield*super.get(e,{...r,signal:n})}finally{n.clear()}}async*getMany(e,r={}){let n=ve([this.closeController.signal,r.signal]);try{yield*super.getMany(e,{...r,signal:n})}finally{n.clear()}}async delete(e,r={}){let n=ve([this.closeController.signal,r.signal]);try{await super.delete(e,{...r,signal:n})}finally{n.clear()}}async*deleteMany(e,r={}){let n=ve([this.closeController.signal,r.signal]);try{yield*super.deleteMany(e,{...r,signal:n})}finally{n.clear()}}async has(e,r={}){let n=ve([this.closeController.signal,r.signal]);try{return await super.has(e,{...r,signal:n})}finally{n.clear()}}async*getAll(e={}){let r=ve([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:r})}finally{r.clear()}}};var Fo=class extends Jt{started;constructor(e,r={}){super(e,r),this.started=!1}isStarted(){return this.started}async start(){await Ke(this.child,...this.blockBrokers),this.started=!0}async stop(){await We(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,r){if(this.blockBrokers.length===0)throw new dt("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(r)).filter(o=>o!=null);if(n.length===0)throw new dt(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new Mo({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var zo=class extends le{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,r){super(),this.logName=r.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=r.minProviders??1,this.maxProviders=r.maxProviders??5,this.cidPeerFilterSize=r.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=tn(this.maxProviders),this.initialProviders=[...r.providers??[]]}async retrieve(e,r={}){let n=vt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let i=G(),s={promise:i.promise,observers:1,queryFilter:tn(this.cidPeerFilterSize)};this.requests.set(n,s);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,r));let c=!1,f=new J({concurrency:this.maxProviders});f.addEventListener("failure",x=>{this.log.error("error querying provider %s, evicting from session - %e",x.detail.job.options.provider,x.detail.error),this.evict(x.detail.job.options.provider)}),f.addEventListener("success",x=>{c=!0,i.resolve(x.detail.result)}),f.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(r.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let x=0;x<this.minProviders&&this.providers.length!==0;x++){let A=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(A)}await this.findProviders(e,this.minProviders,r),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,r))}).catch(x=>{this.log.error("could not find new providers for %c - %e",e,x),i.reject(x)})});let p=x=>{let A=this.toFilterKey(x.detail);s.queryFilter.has(A)||(s.queryFilter.add(A),this.emitFoundProviderProgressEvent(e,x.detail,r),f.add(async()=>this.queryProvider(e,x.detail,r),{provider:x.detail}).catch(I=>{r.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,I)}))};if(this.addEventListener("provider",p),a)try{await Je(this.initialPeerSearchComplete,r.signal),a&&this.log("found initial session peers for %c",e)}catch(x){throw a&&this.log("failed to find initial session peers for %c - %e",e,x),this.requests.delete(n),s.observers>1&&i.reject(x),x}Promise.all([...this.providers].filter(x=>{let A=this.toFilterKey(x),I=s.queryFilter.has(A);return I||s.queryFilter.add(this.toFilterKey(x)),!I}).map(async x=>f.add(async()=>this.queryProvider(e,x,r),{provider:x}))).catch(x=>{r.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,x)});let m=()=>{i.reject(new xe(r.signal?.reason??"Session aborted")),f.abort()};r.signal?.addEventListener("abort",m);try{return await i.promise}finally{this.removeEventListener("provider",p),r.signal?.removeEventListener("abort",m),f.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let r=this.providers.findIndex(n=>this.equals(n,e));r!==-1&&this.providers.splice(r,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(r=>this.equals(r,e))!=null||this.isEvicted(e))}async addPeer(e,r){let n=await this.convertToProvider(e,"manually-added",r);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,r,n){let o=G(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",r,this.maxProviders,e,this.initialProviders.length);let s=this,a=async function*(){for(;s.initialProviders.length>0;){let f=s.initialProviders.pop();if(f==null)continue;let p=await s.convertToProvider(f,"manual",n);p!=null&&(yield p)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let f of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(f)&&(this.log("found %d providers, %d in session",i,this.providers.length),this.providers.push(f),this.safeDispatchEvent("provider",{detail:f}),i++,this.providers.length===r&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",i,r,this.providers.length),this.providers.length<r)throw new Dn(`Found ${i} of ${r} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),o.reject(s)}),o.promise}};function xl(t){return e=>new Rs(e,t)}function bl(t){return e=>new Ds(e,t)}function El(t){return e=>new Ps(e,t)}var Pr=class{components;constructor(e,r={}){this.components=e}async*walk(e,r){let n=this.getQueue(),o=Oo(n.toGenerator(r),a=>a!=null),i=!1,s=async a=>{let c=a.cid,f=await Tn(this.components.blockstore.get(c,a)),p=Sn({cid:c,bytes:f,codec:await this.components.getCodec(c.code)});for(let[,m]of p.links())r?.includeChild?.(m,p)!==!1&&n.add(s,{...a,cid:m,depth:a.depth+1,path:[...a.path,m]}).catch(x=>{i||o.throw(x)});return{block:p,depth:a.depth,path:a.path}};n.add(s,{...r,cid:e,depth:0,path:[e]}).catch(a=>{i||o.throw(a)});try{yield*o}finally{i=!0,n.abort()}}},Rs=class extends Pr{getQueue(){return new J({concurrency:1,sort:(e,r)=>e.options.depth===r.options.depth?0:e.options.depth<r.options.depth?1:-1})}},Ds=class extends Pr{getQueue(){return new J({concurrency:1,sort:(e,r)=>e.options.depth===r.options.depth?0:e.options.depth<r.options.depth?-1:1})}},Ps=class extends Pr{getQueue(){return new J({concurrency:1})}};var $s=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??e.libp2p.logger,this.log=this.logger.forComponent("helia"),this.getHasher=gl(e.hashers,e.loadHasher),this.getCodec=ml(e.codecs,e.loadCodec),this.dns=e.dns??ba(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new le;let r={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,libp2p:this.libp2p,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=r.routing=new On(r,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(r));let i=[o],s=ug(o);s!=null&&i.push(s);let a=fg(o);return a!=null&&i.push(a),i}),providerLookupConcurrency:e.providerLookupConcurrency}),r.blockBrokers=e.blockBrokers.map(o=>o(r));let n=new Fo(r,e);this.pins=new Rn(e.datastore,n,this.getCodec),this.blockstore=new ro(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore}async start(){await jc(this.datastore),await Ke(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await We(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("stop",{detail:this}))}async gc(e={}){let r=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Ea(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 T("helia:gc:deleted",i))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new T("helia:gc:error",s))}})()))}finally{r()}this.log("gc finished")}};function ug(t){return t?.[zs]}function fg(t){return t?.[js]}return Il(lg);})();
2
+ "use strict";var HeliaUtils=(()=>{var Au=Object.create;var Zt=Object.defineProperty;var Su=Object.getOwnPropertyDescriptor;var Iu=Object.getOwnPropertyNames;var ku=Object.getPrototypeOf,Tu=Object.prototype.hasOwnProperty;var Yi=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),_=(r,e)=>{for(var t in e)Zt(r,t,{get:e[t],enumerable:!0})},Zi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Iu(e))!Tu.call(r,o)&&o!==t&&Zt(r,o,{get:()=>e[o],enumerable:!(n=Su(e,o))||n.enumerable});return r};var es=(r,e,t)=>(t=r!=null?Au(ku(r)):{},Zi(e||!r||!r.__esModule?Zt(t,"default",{value:r,enumerable:!0}):t,r)),Lu=r=>Zi(Zt({},"__esModule",{value:!0}),r);var is=Yi((Nm,Nn)=>{"use strict";var Pu=Object.prototype.hasOwnProperty,M="~";function bt(){}Object.create&&(bt.prototype=Object.create(null),new bt().__proto__||(M=!1));function Nu(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function os(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new Nu(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 nr(r,e){--r._eventsCount===0?r._events=new bt:delete r._events[e]}function O(){this._events=new bt,this._eventsCount=0}O.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Pu.call(t,n)&&e.push(M?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};O.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};O.prototype.listenerCount=function(e){var t=M?M+e:e,n=this._events[t];return n?n.fn?1:n.length:0};O.prototype.emit=function(e,t,n,o,i,s){var a=M?M+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,f,p;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,i),!0;case 6:return c.fn.call(c.context,t,n,o,i,s),!0}for(p=1,f=new Array(l-1);p<l;p++)f[p-1]=arguments[p];c.fn.apply(c.context,f)}else{var m=c.length,b;for(p=0;p<m;p++)switch(c[p].once&&this.removeListener(e,c[p].fn,void 0,!0),l){case 1:c[p].fn.call(c[p].context);break;case 2:c[p].fn.call(c[p].context,t);break;case 3:c[p].fn.call(c[p].context,t,n);break;case 4:c[p].fn.call(c[p].context,t,n,o);break;default:if(!f)for(b=1,f=new Array(l-1);b<l;b++)f[b-1]=arguments[b];c[p].fn.apply(c[p].context,f)}}return!0};O.prototype.on=function(e,t,n){return os(this,e,t,n,!1)};O.prototype.once=function(e,t,n){return os(this,e,t,n,!0)};O.prototype.removeListener=function(e,t,n,o){var i=M?M+e:e;if(!this._events[i])return this;if(!t)return nr(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&nr(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:nr(this,i)}return this};O.prototype.removeAllListeners=function(e){var t;return e?(t=M?M+e:e,this._events[t]&&nr(this,t)):(this._events=new bt,this._eventsCount=0),this};O.prototype.off=O.prototype.removeListener;O.prototype.addListener=O.prototype.on;O.prefixed=M;O.EventEmitter=O;typeof Nn<"u"&&(Nn.exports=O)});var Us=Yi((Qg,Ns)=>{Ns.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 Am={};_(Am,{AbstractSession:()=>Pn,Helia:()=>Xi,breadthFirstWalker:()=>vu,depthFirstWalker:()=>Eu,naturalOrderWalker:()=>_u});var ts=Symbol.for("@libp2p/content-routing");var X=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Oe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var er=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var tr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var rs=Symbol.for("@libp2p/peer-routing");function ns(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function be(...r){let e=[];for(let t of r)ns(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 xe(...r){let e=[];for(let t of r)ns(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()}))}function Cu(r){return typeof r?.handleEvent=="function"}function Du(r){return(r!==!0&&r!==!1&&r?.once)??!1}var G=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){let o=Du(n);super.addEventListener(e,s=>{if(o){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(s.type,a))}Cu(t)?t.handleEvent(s):t(s)},n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:o})}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))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var E=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var rr=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Un=es(is(),1);var Rn=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ss=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function xt(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=e,a,c,f=new Promise((p,m)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){m(ss(s));return}if(s&&(c=()=>{m(ss(s))},s.addEventListener("abort",c,{once:!0})),r.then(p,m),t===Number.POSITIVE_INFINITY)return;let b=new Rn;a=i.setTimeout.call(void 0,()=>{if(n){try{p(n())}catch(d){m(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?p():o instanceof Error?m(o):(b.message=o??`Promise timed out after ${t} milliseconds`,m(b))},t)}).finally(()=>{f.clear(),c&&s&&s.removeEventListener("abort",c)});return f.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},f}function Bn(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 Uu=100,Me=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:i}=this,s={priority:n,id:o,run:e};if(i===0){this.#e.length=0,this.#t=0,this.#e.push(s);return}if(this.#e.at(-1).priority>=n){this.#e.push(s);return}this.#i();let a=Bn(this.#e,s,(c,l)=>l.priority-c.priority);this.#e.splice(a,0,s)}setPriority(e,t){let n=this.#e.findIndex((i,s)=>s>=this.#t&&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})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>Uu&&this.#t>this.#e.length/2&&this.#i(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#i(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var Et=class extends Un.default{#e;#t;#i=0;#d;#m=!1;#b=!1;#c;#k=0;#x=0;#u;#l;#a;#s=[];#o=0;#r;#T;#n=0;#g;#f;#N=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Me,strict:!1,...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})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#T=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#F()}#v(e){for(;this.#o<this.#s.length;){let n=this.#s[this.#o];if(n!==void 0&&e-n>=this.#c)this.#o++;else break}(this.#o>100&&this.#o>this.#s.length/2||this.#o===this.#s.length)&&(this.#s=this.#s.slice(this.#o),this.#o=0)}#U(e){this.#a?this.#s.push(e):this.#i++}#R(){this.#a?this.#s.length>this.#o&&this.#s.pop():this.#i>0&&this.#i--}#_(){return this.#s.length-this.#o}get#B(){return this.#t?!0:this.#a?this.#_()<this.#d:this.#i<this.#d}get#z(){return this.#n<this.#g}#O(){this.#n--,this.#n===0&&this.emit("pendingZero"),this.#w(),this.emit("next")}#M(){this.#l=void 0,this.#D(),this.#C()}#$(e){if(this.#a){if(this.#v(e),this.#_()>=this.#d){let n=this.#s[this.#o],o=this.#c-(e-n);return this.#A(o),!0}return!1}if(this.#u===void 0){let t=this.#k-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#A(this.#c-n),!0}this.#i=this.#e?this.#n:0}else return this.#A(t),!0}return!1}#A(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#M()},e))}#S(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#L(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){if(this.#r.size===0){if(this.#S(),this.emit("empty"),this.#n===0){if(this.#L(),this.#a&&this.#o>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#$(t);if(this.#B&&this.#z){let o=this.#r.dequeue();this.#t||(this.#U(t),this.#p()),this.emit("active"),o(),n&&this.#C(),e=!0}}return e}#C(){this.#t||this.#u!==void 0||this.#a||(this.#u=setInterval(()=>{this.#D()},this.#c),this.#k=Date.now()+this.#c)}#D(){this.#a||(this.#i===0&&this.#n===0&&this.#u&&this.#S(),this.#i=this.#e?this.#n:0),this.#I(),this.#p()}#I(){for(;this.#w(););}get concurrency(){return this.#g}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.#g=e,this.#I()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#r.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#N++).toString()},new Promise((n,o)=>{let i=Symbol(`task-${t.id}`),s=()=>{},a=async()=>{s(),this.#n++,this.#y.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(m){throw this.#q(),this.#y.delete(i),m}this.#x=Date.now();let f=e({signal:t.signal});if(t.timeout&&(f=xt(Promise.resolve(f),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#n} running, ${this.#r.size} waiting)`})),t.signal){let{signal:m}=t;f=Promise.race([f,new Promise((b,d)=>{l=()=>{d(m.reason)},m.addEventListener("abort",l,{once:!0})})])}let p=await f;n(p),this.emit("completed",p)}catch(f){o(f),this.emit("error",f)}finally{l&&t.signal?.removeEventListener("abort",l),this.#y.delete(i),queueMicrotask(()=>{this.#O()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof Me){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:l}=t,f=()=>{s(),c(),o(l.reason),this.#w(),this.emit("next")};if(s=()=>{l.removeEventListener("abort",f),this.#E.delete(s)},l.aborted){f();return}l.addEventListener("abort",f,{once:!0}),this.#E.add(s)}this.emit("add"),this.#w()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#I(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#T,this.#S(),this.#P(),this.emit("empty"),this.#n===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#h("next",()=>this.#r.size<e)}async onIdle(){this.#n===0&&this.#r.size===0||await this.#h("idle")}async onPendingZero(){this.#n!==0&&await this.#h("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#h("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#h("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#h(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#f}#F(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#b||(this.#b=!0,queueMicrotask(()=>{this.#b=!1,this.#P()}))}#q(){this.#t||(this.#R(),this.#p())}#P(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#v(o),t=this.#_()}else t=this.#i;let n=t>=this.#d;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#n===this.#g&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function or(r){let e=[Y.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Fn={};_(Fn,{base10:()=>Fu});var Km=new Uint8Array(0);function as(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 de(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 cs(r){return new TextEncoder().encode(r)}function us(r){return new TextDecoder().decode(r)}function Ru(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 a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function p(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var w=0,x=0,v=0,I=d.length;v!==I&&d[v]===0;)v++,w++;for(var A=(I-v)*f+1>>>0,S=new Uint8Array(A);v!==I;){for(var T=d[v],D=0,k=A-1;(T!==0||D<x)&&k!==-1;k--,D++)T+=256*S[k]>>>0,S[k]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");x=D,v++}for(var C=A-x;C!==A&&S[C]===0;)C++;for(var $=c.repeat(w);C<A;++C)$+=r.charAt(S[C]);return $}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var w=0;if(d[w]!==" "){for(var x=0,v=0;d[w]===c;)x++,w++;for(var I=(d.length-w)*l+1>>>0,A=new Uint8Array(I);d[w];){var S=t[d.charCodeAt(w)];if(S===255)return;for(var T=0,D=I-1;(S!==0||T<v)&&D!==-1;D--,T++)S+=a*A[D]>>>0,A[D]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=T,w++}if(d[w]!==" "){for(var k=I-v;k!==I&&A[k]===0;)k++;for(var C=new Uint8Array(x+(I-k)),$=x;k!==I;)C[$++]=A[k++];return C}}}function b(d){var w=m(d);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:m,decode:b}}var Bu=Ru,zu=Bu,fs=zu;var zn=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")}},On=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 hs(this,e)}},Mn=class{decoders;constructor(e){this.decoders=e}or(e){return hs(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 hs(r,e){return new Mn({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var $n=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 zn(e,t,n),this.decoder=new On(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function $e({name:r,prefix:e,encode:t,decode:n}){return new $n(r,e,t,n)}function Ee({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=fs(t,r);return $e({prefix:e,name:r,encode:n,decode:i=>de(o(i))})}function Ou(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function Mu(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function $u(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function U({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=$u(n);return $e({prefix:e,name:r,encode(i){return Mu(i,n,t)},decode(i){return Ou(i,o,t,r)}})}var Fu=Ee({prefix:"9",name:"base10",alphabet:"0123456789"});var qn={};_(qn,{base16:()=>qu,base16upper:()=>ju});var qu=U({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ju=U({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var jn={};_(jn,{base2:()=>Vu});var Vu=U({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vn={};_(Vn,{base256emoji:()=>Qu});var ds=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}"),Ku=ds.reduce((r,e,t)=>(r[t]=e,r),[]),Hu=ds.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Wu(r){return r.reduce((e,t)=>(e+=Ku[t],e),"")}function Gu(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Hu[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Qu=$e({prefix:"\u{1F680}",name:"base256emoji",encode:Wu,decode:Gu});var Kn={};_(Kn,{base32:()=>Fe,base32hex:()=>Zu,base32hexpad:()=>tl,base32hexpadupper:()=>rl,base32hexupper:()=>el,base32pad:()=>Xu,base32padupper:()=>Yu,base32upper:()=>Ju,base32z:()=>nl});var Fe=U({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ju=U({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Xu=U({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yu=U({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Zu=U({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),el=U({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tl=U({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rl=U({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nl=U({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Hn={};_(Hn,{base36:()=>vt,base36upper:()=>ol});var vt=Ee({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ol=Ee({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Wn={};_(Wn,{base58btc:()=>se,base58flickr:()=>il});var se=Ee({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),il=Ee({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Gn={};_(Gn,{base64:()=>sl,base64pad:()=>al,base64url:()=>cl,base64urlpad:()=>ul});var sl=U({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),al=U({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cl=U({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ul=U({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qn={};_(Qn,{base8:()=>ll});var ll=U({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Jn={};_(Jn,{identity:()=>fl});var fl=$e({prefix:"\0",name:"identity",encode:r=>us(r),decode:r=>cs(r)});var ag=new TextEncoder,cg=new TextDecoder;var Yn={};_(Yn,{identity:()=>Ul});var pl=gs,ps=128,ml=127,gl=~ml,yl=Math.pow(2,31);function gs(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yl;)e[t++]=r&255|ps,r/=128;for(;r&gl;)e[t++]=r&255|ps,r>>>=7;return e[t]=r|0,gs.bytes=t-n+1,e}var wl=Xn,bl=128,ms=127;function Xn(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Xn.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&ms)<<o:(s&ms)*Math.pow(2,o),o+=7}while(s>=bl);return Xn.bytes=i-n,t}var xl=Math.pow(2,7),El=Math.pow(2,14),vl=Math.pow(2,21),_l=Math.pow(2,28),Al=Math.pow(2,35),Sl=Math.pow(2,42),Il=Math.pow(2,49),kl=Math.pow(2,56),Tl=Math.pow(2,63),Ll=function(r){return r<xl?1:r<El?2:r<vl?3:r<_l?4:r<Al?5:r<Sl?6:r<Il?7:r<kl?8:r<Tl?9:10},Cl={encode:pl,decode:wl,encodingLength:Ll},Dl=Cl,_t=Dl;function At(r,e=0){return[_t.decode(r,e),_t.decode.bytes]}function qe(r,e,t=0){return _t.encode(r,e,t),e}function je(r){return _t.encodingLength(r)}function Ke(r,e){let t=e.byteLength,n=je(r),o=n+je(t),i=new Uint8Array(o+t);return qe(r,i,0),qe(t,i,n),i.set(e,o),new Ve(r,t,e,i)}function ys(r){let e=de(r),[t,n]=At(e),[o,i]=At(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Ve(t,o,s,e)}function ws(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&as(r.bytes,t.bytes)}}var Ve=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var bs=0,Pl="identity",xs=de;function Nl(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ke(bs,xs(r))}var Ul={code:bs,name:Pl,encode:xs,digest:Nl};var to={};_(to,{sha256:()=>Bl,sha512:()=>zl});var Rl=20;function eo({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Zn(r,e,t,n,o)}var Zn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Rl,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Es(n,this.code,t?.truncate):n.then(o=>Es(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Es(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ke(e,r)}function _s(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Bl=eo({name:"sha2-256",code:18,encode:_s("SHA-256")}),zl=eo({name:"sha2-512",code:19,encode:_s("SHA-512")});function As(r,e){let{bytes:t,version:n}=r;return n===0?Ml(t,ro(r),e??se.encoder):$l(t,ro(r),e??Fe.encoder)}var Ss=new WeakMap;function ro(r){let e=Ss.get(r);if(e==null){let t=new Map;return Ss.set(r,t),t}return e}var sr=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!==It)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Fl)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=Ke(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&&ws(e.multihash,n.multihash)}toString(e){return As(this,e)}toJSON(){return{"/":As(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??Is(n,o,i.bytes))}else if(t[ql]===!0){let{version:n,multihash:o,code:i}=t,s=ys(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!==It)throw new Error(`Version 0 CID must use dag-pb (code: ${It}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Is(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,It,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=de(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 Ve(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[p,m]=At(e.subarray(t));return t+=m,p},o=n(),i=It;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=Ol(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 ro(i).set(n,e),i}};function Ol(r,e){switch(r[0]){case"Q":{let t=e??se;return[se.prefix,t.decode(`${se.prefix}${r}`)]}case se.prefix:{let t=e??se;return[se.prefix,t.decode(r)]}case Fe.prefix:{let t=e??Fe;return[Fe.prefix,t.decode(r)]}case vt.prefix:{let t=e??vt;return[vt.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 Ml(r,e,t){let{prefix:n}=t;if(n!==se.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 $l(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 It=112,Fl=18;function Is(r,e,t){let n=je(r),o=n+je(e),i=new Uint8Array(o+t.byteLength);return qe(r,i,0),qe(e,i,n),i.set(t,o),i}var ql=Symbol.for("@ipld/js-cid/CID");var no={...Jn,...jn,...Qn,...Fn,...qn,...Kn,...Hn,...Wn,...Gn,...Vn},Cg={...to,...Yn};function ks(r=0){return new Uint8Array(r)}function Ls(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ts=Ls("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),oo=Ls("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=ks(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),jl={utf8:Ts,"utf-8":Ts,hex:no.base16,latin1:oo,ascii:oo,binary:oo,...no},Cs=jl;function Ds(r,e="utf8"){let t=Cs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var io=60;function ar(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:Y[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Y[e.type],TTL:e.TTL??e.ttl??io,data:e.data instanceof Uint8Array?Ds(e.data):e.data}))}}var Vl=4;function so(r,e={}){let t=new Et({concurrency:e.queryConcurrency??Vl});return async(n,o={})=>{let i=o?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),or(o.types).forEach(c=>{s.append("type",Y[c])}),o.onProgress?.(new E("dns:query",n)),i?.("GET %s",`${r}?${s}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(i?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=ar(await c.json());return o.onProgress?.(new E("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function Ps(){return[so("https://cloudflare-dns.com/dns-query"),so("https://dns.google/resolve")]}var Rs=es(Us(),1);var ao=class{lru;constructor(e){this.lru=(0,Rs.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 ar({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:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:Y[a.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??io)*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 Bs(r){return new ao(r)}var Kl=1e3,cr=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=Bs(e.cacheSize??Kl),this.logger=e.logger,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["."]=Ps())}async query(e,t={}){let n=or(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new E("dns:cache",o)),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new E("dns:error",l))}}throw new rr(a,`DNS lookup of ${e} ${n} failed`)}};var Y;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Y||(Y={}));function zs(r={}){return new cr(r)}function Hl(r){return r[Symbol.asyncIterator]!=null}function Wl(r){if(Hl(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Os=Wl;function Ms(r=0){return new Uint8Array(r)}function $s(r=0){return new Uint8Array(r)}function Fs(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 ho={};_(ho,{base10:()=>ef});var ly=new Uint8Array(0);function qs(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 pe(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 js(r){return new TextEncoder().encode(r)}function Vs(r){return new TextDecoder().decode(r)}function Gl(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 a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function p(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var w=0,x=0,v=0,I=d.length;v!==I&&d[v]===0;)v++,w++;for(var A=(I-v)*f+1>>>0,S=new Uint8Array(A);v!==I;){for(var T=d[v],D=0,k=A-1;(T!==0||D<x)&&k!==-1;k--,D++)T+=256*S[k]>>>0,S[k]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");x=D,v++}for(var C=A-x;C!==A&&S[C]===0;)C++;for(var $=c.repeat(w);C<A;++C)$+=r.charAt(S[C]);return $}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var w=0;if(d[w]!==" "){for(var x=0,v=0;d[w]===c;)x++,w++;for(var I=(d.length-w)*l+1>>>0,A=new Uint8Array(I);d[w];){var S=t[d.charCodeAt(w)];if(S===255)return;for(var T=0,D=I-1;(S!==0||T<v)&&D!==-1;D--,T++)S+=a*A[D]>>>0,A[D]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=T,w++}if(d[w]!==" "){for(var k=I-v;k!==I&&A[k]===0;)k++;for(var C=new Uint8Array(x+(I-k)),$=x;k!==I;)C[$++]=A[k++];return C}}}function b(d){var w=m(d);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:m,decode:b}}var Ql=Gl,Jl=Ql,Hs=Jl;var co=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")}},uo=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 Ws(this,e)}},lo=class{decoders;constructor(e){this.decoders=e}or(e){return Ws(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 Ws(r,e){return new lo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var fo=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 co(e,t,n),this.decoder=new uo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function He({name:r,prefix:e,encode:t,decode:n}){return new fo(r,e,t,n)}function ve({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Hs(t,r);return He({prefix:e,name:r,encode:n,decode:i=>pe(o(i))})}function Xl(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function Yl(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function Zl(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function R({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Zl(n);return He({prefix:e,name:r,encode(i){return Yl(i,n,t)},decode(i){return Xl(i,o,t,r)}})}var ef=ve({prefix:"9",name:"base10",alphabet:"0123456789"});var po={};_(po,{base16:()=>tf,base16upper:()=>rf});var tf=R({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rf=R({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var mo={};_(mo,{base2:()=>nf});var nf=R({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var go={};_(go,{base256emoji:()=>uf});var Gs=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}"),of=Gs.reduce((r,e,t)=>(r[t]=e,r),[]),sf=Gs.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function af(r){return r.reduce((e,t)=>(e+=of[t],e),"")}function cf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=sf[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var uf=He({prefix:"\u{1F680}",name:"base256emoji",encode:af,decode:cf});var yo={};_(yo,{base32:()=>We,base32hex:()=>df,base32hexpad:()=>mf,base32hexpadupper:()=>gf,base32hexupper:()=>pf,base32pad:()=>ff,base32padupper:()=>hf,base32upper:()=>lf,base32z:()=>yf});var We=R({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),lf=R({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ff=R({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hf=R({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),df=R({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pf=R({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),mf=R({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gf=R({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yf=R({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var wo={};_(wo,{base36:()=>kt,base36upper:()=>wf});var kt=ve({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wf=ve({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var bo={};_(bo,{base58btc:()=>ae,base58flickr:()=>bf});var ae=ve({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),bf=ve({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xo={};_(xo,{base64:()=>xf,base64pad:()=>Ef,base64url:()=>vf,base64urlpad:()=>_f});var xf=R({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ef=R({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vf=R({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_f=R({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Eo={};_(Eo,{base8:()=>Af});var Af=R({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vo={};_(vo,{identity:()=>Sf});var Sf=He({prefix:"\0",name:"identity",encode:r=>Vs(r),decode:r=>js(r)});var Iy=new TextEncoder,ky=new TextDecoder;var Ao={};_(Ao,{identity:()=>Gf});var Tf=Xs,Qs=128,Lf=127,Cf=~Lf,Df=Math.pow(2,31);function Xs(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Df;)e[t++]=r&255|Qs,r/=128;for(;r&Cf;)e[t++]=r&255|Qs,r>>>=7;return e[t]=r|0,Xs.bytes=t-n+1,e}var Pf=_o,Nf=128,Js=127;function _o(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw _o.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&Js)<<o:(s&Js)*Math.pow(2,o),o+=7}while(s>=Nf);return _o.bytes=i-n,t}var Uf=Math.pow(2,7),Rf=Math.pow(2,14),Bf=Math.pow(2,21),zf=Math.pow(2,28),Of=Math.pow(2,35),Mf=Math.pow(2,42),$f=Math.pow(2,49),Ff=Math.pow(2,56),qf=Math.pow(2,63),jf=function(r){return r<Uf?1:r<Rf?2:r<Bf?3:r<zf?4:r<Of?5:r<Mf?6:r<$f?7:r<Ff?8:r<qf?9:10},Vf={encode:Tf,decode:Pf,encodingLength:jf},Kf=Vf,Tt=Kf;function Lt(r,e=0){return[Tt.decode(r,e),Tt.decode.bytes]}function Ge(r,e,t=0){return Tt.encode(r,e,t),e}function Qe(r){return Tt.encodingLength(r)}function Xe(r,e){let t=e.byteLength,n=Qe(r),o=n+Qe(t),i=new Uint8Array(o+t);return Ge(r,i,0),Ge(t,i,n),i.set(e,o),new Je(r,t,e,i)}function Ys(r){let e=pe(r),[t,n]=Lt(e),[o,i]=Lt(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Je(t,o,s,e)}function Zs(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&qs(r.bytes,t.bytes)}}var Je=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var ea=0,Hf="identity",ta=pe;function Wf(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Xe(ea,ta(r))}var Gf={code:ea,name:Hf,encode:ta,digest:Wf};var ko={};_(ko,{sha256:()=>Jf,sha512:()=>Xf});var Qf=20;function Io({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new So(r,e,t,n,o)}var So=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Qf,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ra(n,this.code,t?.truncate):n.then(o=>ra(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ra(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Xe(e,r)}function oa(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Jf=Io({name:"sha2-256",code:18,encode:oa("SHA-256")}),Xf=Io({name:"sha2-512",code:19,encode:oa("SHA-512")});function ia(r,e){let{bytes:t,version:n}=r;return n===0?Zf(t,To(r),e??ae.encoder):eh(t,To(r),e??We.encoder)}var sa=new WeakMap;function To(r){let e=sa.get(r);if(e==null){let t=new Map;return sa.set(r,t),t}return e}var lr=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!==Dt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==th)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=Xe(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&&Zs(e.multihash,n.multihash)}toString(e){return ia(this,e)}toJSON(){return{"/":ia(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??aa(n,o,i.bytes))}else if(t[rh]===!0){let{version:n,multihash:o,code:i}=t,s=Ys(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!==Dt)throw new Error(`Version 0 CID must use dag-pb (code: ${Dt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=aa(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Dt,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=pe(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 Je(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[p,m]=Lt(e.subarray(t));return t+=m,p},o=n(),i=Dt;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=Yf(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 To(i).set(n,e),i}};function Yf(r,e){switch(r[0]){case"Q":{let t=e??ae;return[ae.prefix,t.decode(`${ae.prefix}${r}`)]}case ae.prefix:{let t=e??ae;return[ae.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case kt.prefix:{let t=e??kt;return[kt.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 Zf(r,e,t){let{prefix:n}=t;if(n!==ae.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 eh(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 Dt=112,th=18;function aa(r,e,t){let n=Qe(r),o=n+Qe(e),i=new Uint8Array(o+t.byteLength);return Ge(r,i,0),Ge(e,i,n),i.set(t,o),i}var rh=Symbol.for("@ipld/js-cid/CID");var Lo={...vo,...mo,...Eo,...ho,...po,...yo,...wo,...bo,...xo,...go},Qy={...ko,...Ao};function ua(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ca=ua("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Co=ua("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=$s(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),nh={utf8:ca,"utf-8":ca,hex:Lo.base16,latin1:Co,ascii:Co,binary:Co,...Lo},la=nh;function ce(r,e="utf8"){let t=la[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Do={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},fa={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ha=new globalThis.TextEncoder;function oh(r,e){let t=Do[e],n=fa[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function ih(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Do[e],o=fa[e],i=r;for(;i.length>0;){let s=ha.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Po(r,{size:e=32,utf8Buffer:t}={}){if(!Do[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 ih(r,e,t);r=ha.encode(r)}return oh(r,e)}var Pt={hash:r=>Number(Po(r,{size:32})),hashV:(r,e)=>sh(Pt.hash(r,e))};function sh(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),ce(e,"base16")}var No=64,Z=class{fp;h;seed;constructor(e,t,n,o=2){if(o>No)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=Ms(o);for(let a=0;a<s.length;a++)s[a]=i[a];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?Fs(this.fp,e.fp):!1}};function Te(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 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=Te(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 ah=500,Nt=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??Pt,this.seed=e.seed??Te(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=ce(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 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[Te(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Le(this.bucketSize));for(let a=0;a<ah;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Le(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=ce(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=ce(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}},ch={1:.5,2:.84,4:.95,8:.98};function uh(r=.001){return r>.002?2:r>1e-5?4:8}function da(r,e=.001){let t=uh(e),n=ch[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),No);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var fr=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??Pt,this.seed=e.seed??Te(0,Math.pow(2,10)),this.filterSeries=[new Nt({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=ce(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 Nt({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=ce(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=ce(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 hr(r,e=.001,t){return new fr({...da(r,e),...t??{}})}function Ut(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 dr(r=0){return new Uint8Array(r)}function lh(r){return r?.buffer instanceof ArrayBuffer}function pa(r){if(lh(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Uo(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=dr(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return pa(t)}var $o={};_($o,{base10:()=>wh});var Pw=new Uint8Array(0);function ma(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 ee(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Ce(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Ce(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function ga(r){return new TextEncoder().encode(r)}function ya(r){return new TextDecoder().decode(r)}function fh(r){return r?.buffer instanceof ArrayBuffer}function Ce(r){return fh(r)?r:r.slice()}function hh(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 a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function p(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var w=0,x=0,v=0,I=d.length;v!==I&&d[v]===0;)v++,w++;for(var A=(I-v)*f+1>>>0,S=new Uint8Array(A);v!==I;){for(var T=d[v],D=0,k=A-1;(T!==0||D<x)&&k!==-1;k--,D++)T+=256*S[k]>>>0,S[k]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");x=D,v++}for(var C=A-x;C!==A&&S[C]===0;)C++;for(var $=c.repeat(w);C<A;++C)$+=r.charAt(S[C]);return $}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var w=0;if(d[w]!==" "){for(var x=0,v=0;d[w]===c;)x++,w++;for(var I=(d.length-w)*l+1>>>0,A=new Uint8Array(I);d[w];){var S=t[d.charCodeAt(w)];if(S===255)return;for(var T=0,D=I-1;(S!==0||T<v)&&D!==-1;D--,T++)S+=a*A[D]>>>0,A[D]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=T,w++}if(d[w]!==" "){for(var k=I-v;k!==I&&A[k]===0;)k++;for(var C=new Uint8Array(x+(I-k)),$=x;k!==I;)C[$++]=A[k++];return C}}}function b(d){var w=m(d);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:m,decode:b}}var dh=hh,ph=dh,wa=ph;var Bo=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")}},zo=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 ba(this,e)}},Oo=class{decoders;constructor(e){this.decoders=e}or(e){return ba(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 ba(r,e){return new Oo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Mo=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 Bo(e,t,n),this.decoder=new zo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ye({name:r,prefix:e,encode:t,decode:n}){return new Mo(r,e,t,n)}function _e({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=wa(t,r);return Ye({prefix:e,name:r,encode:n,decode:i=>ee(o(i))})}function mh(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function gh(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function yh(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function B({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=yh(n);return Ye({prefix:e,name:r,encode(i){return gh(i,n,t)},decode(i){return mh(i,o,t,r)}})}var wh=_e({prefix:"9",name:"base10",alphabet:"0123456789"});var Fo={};_(Fo,{base16:()=>bh,base16upper:()=>xh});var bh=B({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xh=B({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var qo={};_(qo,{base2:()=>Eh});var Eh=B({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jo={};_(jo,{base256emoji:()=>Ih});var xa=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}"),vh=xa.reduce((r,e,t)=>(r[t]=e,r),[]),_h=xa.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Ah(r){return r.reduce((e,t)=>(e+=vh[t],e),"")}function Sh(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=_h[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Ih=Ye({prefix:"\u{1F680}",name:"base256emoji",encode:Ah,decode:Sh});var Vo={};_(Vo,{base32:()=>Ze,base32hex:()=>Ch,base32hexpad:()=>Ph,base32hexpadupper:()=>Nh,base32hexupper:()=>Dh,base32pad:()=>Th,base32padupper:()=>Lh,base32upper:()=>kh,base32z:()=>Uh});var Ze=B({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kh=B({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Th=B({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Lh=B({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ch=B({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Dh=B({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ph=B({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Nh=B({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Uh=B({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ko={};_(Ko,{base36:()=>me,base36upper:()=>Rh});var me=_e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Rh=_e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ho={};_(Ho,{base58btc:()=>ue,base58flickr:()=>Bh});var ue=_e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bh=_e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Wo={};_(Wo,{base64:()=>et,base64pad:()=>zh,base64url:()=>Oh,base64urlpad:()=>Mh});var et=B({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),zh=B({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Oh=B({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Mh=B({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Go={};_(Go,{base8:()=>$h});var $h=B({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qo={};_(Qo,{identity:()=>Fh});var Fh=Ye({prefix:"\0",name:"identity",encode:r=>ya(r),decode:r=>ga(r)});var pr={};_(pr,{code:()=>Jo,decode:()=>Hh,encode:()=>Kh,name:()=>Vh});var qh=new TextEncoder,jh=new TextDecoder,Vh="json",Jo=512;function Kh(r){return qh.encode(JSON.stringify(r))}function Hh(r){return JSON.parse(jh.decode(r))}var mr={};_(mr,{code:()=>Xo,decode:()=>Qh,encode:()=>Gh,name:()=>Wh});var Wh="raw",Xo=85;function Gh(r){return ee(r)}function Qh(r){return ee(r)}var Zo={};_(Zo,{identity:()=>yr});var Jh=_a,Ea=128,Xh=127,Yh=~Xh,Zh=Math.pow(2,31);function _a(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Zh;)e[t++]=r&255|Ea,r/=128;for(;r&Yh;)e[t++]=r&255|Ea,r>>>=7;return e[t]=r|0,_a.bytes=t-n+1,e}var ed=Yo,td=128,va=127;function Yo(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Yo.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&va)<<o:(s&va)*Math.pow(2,o),o+=7}while(s>=td);return Yo.bytes=i-n,t}var rd=Math.pow(2,7),nd=Math.pow(2,14),od=Math.pow(2,21),id=Math.pow(2,28),sd=Math.pow(2,35),ad=Math.pow(2,42),cd=Math.pow(2,49),ud=Math.pow(2,56),ld=Math.pow(2,63),fd=function(r){return r<rd?1:r<nd?2:r<od?3:r<id?4:r<sd?5:r<ad?6:r<cd?7:r<ud?8:r<ld?9:10},hd={encode:Jh,decode:ed,encodingLength:fd},dd=hd,Rt=dd;function Bt(r,e=0){return[Rt.decode(r,e),Rt.decode.bytes]}function tt(r,e,t=0){return Rt.encode(r,e,t),e}function rt(r){return Rt.encodingLength(r)}function ot(r,e){let t=e.byteLength,n=rt(r),o=n+rt(t),i=new Uint8Array(o+t);return tt(r,i,0),tt(t,i,n),i.set(e,o),new nt(r,t,e,i)}function Aa(r){let e=ee(r),[t,n]=Bt(e),[o,i]=Bt(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new nt(t,o,s,e)}function Sa(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ma(r.bytes,t.bytes)}}var nt=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=Ce(n),this.bytes=Ce(o)}};var Ia=0,pd="identity",ka=ee;function md(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ot(Ia,ka(r))}var yr={code:Ia,name:pd,encode:ka,digest:md};var ri={};_(ri,{sha256:()=>wr,sha512:()=>br});var gd=20;function ti({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new ei(r,e,t,n,o)}var ei=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??gd,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Ta(n,this.code,t?.truncate):n.then(o=>Ta(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ta(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ot(e,r)}function Ca(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var wr=ti({name:"sha2-256",code:18,encode:Ca("SHA-256")}),br=ti({name:"sha2-512",code:19,encode:Ca("SHA-512")});function Da(r,e){let{bytes:t,version:n}=r;return n===0?wd(t,ni(r),e??ue.encoder):bd(t,ni(r),e??Ze.encoder)}var Pa=new WeakMap;function ni(r){let e=Pa.get(r);if(e==null){let t=new Map;return Pa.set(r,t),t}return e}var P=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=Ce(o),this["/"]=this.bytes}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!==Ot)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xd)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=ot(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&&Sa(e.multihash,n.multihash)}toString(e){return Da(this,e)}toJSON(){return{"/":Da(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??Na(n,o,i.bytes))}else if(t[Ed]===!0){let{version:n,multihash:o,code:i}=t,s=Aa(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!==Ot)throw new Error(`Version 0 CID must use dag-pb (code: ${Ot}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Na(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ot,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=ee(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 nt(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[p,m]=Bt(e.subarray(t));return t+=m,p},o=n(),i=Ot;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=yd(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 ni(i).set(n,e),i}};function yd(r,e){switch(r[0]){case"Q":{let t=e??ue;return[ue.prefix,t.decode(`${ue.prefix}${r}`)]}case ue.prefix:{let t=e??ue;return[ue.prefix,t.decode(r)]}case Ze.prefix:{let t=e??Ze;return[Ze.prefix,t.decode(r)]}case me.prefix:{let t=e??me;return[me.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 wd(r,e,t){let{prefix:n}=t;if(n!==ue.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 bd(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 Ot=112,xd=18;function Na(r,e,t){let n=rt(r),o=n+rt(e),i=new Uint8Array(o+t.byteLength);return tt(r,i,0),tt(e,i,n),i.set(t,o),i}var Ed=Symbol.for("@ipld/js-cid/CID");var oi={...Qo,...qo,...Go,...$o,...Fo,...Vo,...Ko,...Ho,...Wo,...jo},mb={...ri,...Zo};function Ra(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ua=Ra("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ii=Ra("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=dr(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),vd={utf8:Ua,"utf-8":Ua,hex:oi.base16,latin1:ii,ascii:ii,binary:ii,...oi},xr=vd;function Er(r,e="utf8"){let t=xr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function it(r,e="utf8"){let t=xr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function F(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var vr=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},st=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vr(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 vr(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 si=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function _r(r={}){return _d(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 _d(r,e){e=e??{};let t=e.onEnd,n=new st,o,i,s,a=F(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((x,v)=>{i=I=>{i=null,n.push(I);try{x(r(n))}catch(A){v(A)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=F()})}},l=x=>i!=null?i(x):(n.push(x),o),f=x=>(n=new st,i!=null?i({error:x}):(n.push({error:x}),o)),p=x=>{if(s)return o;if(e?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:x})},m=x=>s?o:(s=!0,x!=null?f(x):l({done:!0})),b=()=>(n=new st,m(),{done:!0}),d=x=>(m(x),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:b,throw:d,push:p,end:m,get readableLength(){return n.size},onEmpty:async x=>{let v=x?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let I,A;v!=null&&(I=new Promise((S,T)=>{A=()=>{T(new si)},v.addEventListener("abort",A)}));try{await Promise.race([a.promise,I])}finally{A!=null&&v!=null&&v?.removeEventListener("abort",A)}}},t==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(x){return w.throw(x),t!=null&&(t(x),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:p,end(x){return w.end(x),t!=null&&(t(x),t=void 0),o},get readableLength(){return w.readableLength},onEmpty:x=>w.onEmpty(x)},o}var Ad=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Sd(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=Ad(r),p=async(...b)=>{let d=t.multiArgs?b:b[0];if(t.filter)try{if(!await t.filter(d))return}catch(w){n(),s(w);return}c.push(d),t.count===c.length&&(n(),i(c))},m=(...b)=>{n(),s(t.rejectionMultiArgs?b:b[0])};n=()=>{for(let b of a)f(b,p);for(let b of t.rejectionEvents)a.includes(b)||f(b,m)};for(let b of a)l(b,p);for(let b of t.rejectionEvents)a.includes(b)||l(b,m);t.signal&&t.signal.addEventListener("abort",()=>{m(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=xt(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function Ar(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Sd(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function ai(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Sr=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Id(r){return r.reason}async function Ae(r,e,t){if(e==null)return r;let n=t?.translateError??Id;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Ir=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=F(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new X)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function kd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var kr=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=kd(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 X),this.cleanup())}async join(e){let t=new Ir(e);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 Ae(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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 q=class extends G{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=[],this.emitEmpty=ai(this.emitEmpty.bind(this),1),this.emitIdle=ai(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!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 Sr;let n=new kr(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new X)}),this.clear()}async onEmpty(e){this.size!==0&&await Ar(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Ar(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ar(this,"idle",e)}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=_r({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new X("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function te(r){let e=new globalThis.AbortController;function t(){let i=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of r)s?.removeEventListener!=null&&s.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 ci=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=F(),this.haveNext=F()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=F(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=F(),await Ae(this.readNext.promise,t?.signal,t)}};function Ba(){return new ci}function Td(r){return r[Symbol.asyncIterator]!=null}async function Ld(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Cd(r){let e=new AbortController,t=Ba();Ld(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Dd(r){for(let e of r)yield*e}function Pd(...r){let e=[];for(let t of r)Td(t)||e.push(t);return e.length===r.length?Dd(e):Cd(r)}var Tr=Pd;var Nd=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function ui(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=Ud(r);return t||"Object"}function Ud(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Nd.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}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};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 h=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 Mt=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Rd=new TextEncoder;function Lr(r){return Mt&&globalThis.Buffer.isBuffer(r)}function De(r){return r instanceof Uint8Array?Lr(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Bd=24,zd=200,at=Mt?r=>r.length>=Bd?globalThis.Buffer.from(r):za(r):r=>r.length>=zd?Rd.encode(r):za(r),le=r=>Uint8Array.from(r),Ma=Mt?(r,e,t)=>Lr(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),$a=Mt?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),De(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},Fa=Mt?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Cr(r,e){if(Lr(r)&&Lr(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 za(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):(o>=55296&&o<=57343&&(o=65533),e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}var Oa=4096;function qa(r){let e=r.length;if(e<=Oa)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Oa));return t}var Od=256,$t=class{constructor(e=Od){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=Fa(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=Ma(n,0,this.cursor)}else t=$a(this.chunks,this.cursor);return e&&this.reset(),t}},Dr=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var y="CBOR decode error:",fe="CBOR encode error:",Ft=[];Ft[23]=1;Ft[24]=2;Ft[25]=3;Ft[26]=5;Ft[27]=9;function ge(r,e,t){if(r.length-e<t)throw new Error(`${y} not enough data for type`)}var z=[24,256,65536,4294967296,BigInt("18446744073709551616")];function j(r,e,t){ge(r,e,1);let n=r[e];if(t.strict===!0&&n<z[0])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function V(r,e,t){ge(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<z[1])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function K(r,e,t){ge(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<z[2])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function H(r,e,t){ge(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<z[3])throw new Error(`${y} 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(`${y} integers outside of the safe integer range are not supported`)}function ja(r,e,t,n){return new h(u.uint,j(r,e+1,n),2)}function Va(r,e,t,n){return new h(u.uint,V(r,e+1,n),3)}function Ka(r,e,t,n){return new h(u.uint,K(r,e+1,n),5)}function Ha(r,e,t,n){return new h(u.uint,H(r,e+1,n),9)}function Q(r,e){return N(r,0,e.value)}function N(r,e,t){if(t<z[0]){let n=Number(t);r.push([e|n])}else if(t<z[1]){let n=Number(t);r.push([e|24,n])}else if(t<z[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<z[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<z[4]){let 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(`${y} encountered BigInt larger than allowable range`)}}Q.encodedSize=function(e){return N.encodedSize(e.value)};N.encodedSize=function(e){return e<z[0]?1:e<z[1]?2:e<z[2]?3:e<z[3]?5:9};Q.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Wa(r,e,t,n){return new h(u.negint,-1-j(r,e+1,n),2)}function Ga(r,e,t,n){return new h(u.negint,-1-V(r,e+1,n),3)}function Qa(r,e,t,n){return new h(u.negint,-1-K(r,e+1,n),5)}var li=BigInt(-1),Ja=BigInt(1);function Xa(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 h(u.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${y} integers outside of the safe integer range are not supported`);return new h(u.negint,li-BigInt(o),9)}function Pr(r,e){let t=e.value,n=typeof t=="bigint"?t*li-Ja:t*-1-1;N(r,e.type.majorEncoded,n)}Pr.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*li-Ja:t*-1-1;return n<z[0]?1:n<z[1]?2:n<z[2]?3:n<z[3]?5:9};Pr.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function qt(r,e,t,n){ge(r,e,t+n);let o=r.slice(e+t,e+t+n);return new h(u.bytes,o,t+n)}function Ya(r,e,t,n){return qt(r,e,1,t)}function Za(r,e,t,n){return qt(r,e,2,j(r,e+1,n))}function ec(r,e,t,n){return qt(r,e,3,V(r,e+1,n))}function tc(r,e,t,n){return qt(r,e,5,K(r,e+1,n))}function rc(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${y} 64-bit integer bytes lengths not supported`);return qt(r,e,9,o)}function Nr(r){return r.encodedBytes===void 0&&(r.encodedBytes=u.equals(r.type,u.string)?at(r.value):r.value),r.encodedBytes}function ct(r,e){let t=Nr(e);N(r,e.type.majorEncoded,t.length),r.push(t)}ct.encodedSize=function(e){let t=Nr(e);return N.encodedSize(t.length)+t.length};ct.compareTokens=function(e,t){return $d(Nr(e),Nr(t))};function $d(r,e){return r.length<e.length?-1:r.length>e.length?1:Cr(r,e)}var nc=new TextDecoder,qd=32;function jd(r,e,t){if(t-e<qd){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return nc.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return nc.decode(r.subarray(e,t))}function jt(r,e,t,n,o){let i=t+n;ge(r,e,i);let s=new h(u.string,jd(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function oc(r,e,t,n){return jt(r,e,1,t,n)}function ic(r,e,t,n){return jt(r,e,2,j(r,e+1,n),n)}function sc(r,e,t,n){return jt(r,e,3,V(r,e+1,n),n)}function ac(r,e,t,n){return jt(r,e,5,K(r,e+1,n),n)}function cc(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${y} 64-bit integer string lengths not supported`);return jt(r,e,9,o,n)}var uc=ct;function ut(r,e,t,n){return new h(u.array,n,t)}function lc(r,e,t,n){return ut(r,e,1,t)}function fc(r,e,t,n){return ut(r,e,2,j(r,e+1,n))}function hc(r,e,t,n){return ut(r,e,3,V(r,e+1,n))}function dc(r,e,t,n){return ut(r,e,5,K(r,e+1,n))}function pc(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${y} 64-bit integer array lengths not supported`);return ut(r,e,9,o)}function mc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return ut(r,e,1,1/0)}function Ur(r,e){N(r,u.array.majorEncoded,e.value)}Ur.compareTokens=Q.compareTokens;Ur.encodedSize=function(e){return N.encodedSize(e.value)};function lt(r,e,t,n){return new h(u.map,n,t)}function gc(r,e,t,n){return lt(r,e,1,t)}function yc(r,e,t,n){return lt(r,e,2,j(r,e+1,n))}function wc(r,e,t,n){return lt(r,e,3,V(r,e+1,n))}function bc(r,e,t,n){return lt(r,e,5,K(r,e+1,n))}function xc(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${y} 64-bit integer map lengths not supported`);return lt(r,e,9,o)}function Ec(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return lt(r,e,1,1/0)}function Rr(r,e){N(r,u.map.majorEncoded,e.value)}Rr.compareTokens=Q.compareTokens;Rr.encodedSize=function(e){return N.encodedSize(e.value)};function vc(r,e,t,n){return new h(u.tag,t,1)}function _c(r,e,t,n){return new h(u.tag,j(r,e+1,n),2)}function Ac(r,e,t,n){return new h(u.tag,V(r,e+1,n),3)}function Sc(r,e,t,n){return new h(u.tag,K(r,e+1,n),5)}function Ic(r,e,t,n){return new h(u.tag,H(r,e+1,n),9)}function Br(r,e){N(r,u.tag.majorEncoded,e.value)}Br.compareTokens=Q.compareTokens;Br.encodedSize=function(e){return N.encodedSize(e.value)};var fi=20,hi=21,di=22,pi=23;function kc(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${y} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new h(u.null,null,1):new h(u.undefined,void 0,1)}function Tc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return new h(u.break,void 0,1)}function mi(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${y} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${y} Infinity values are not supported`)}return new h(u.float,r,e)}function Lc(r,e,t,n){return mi(gi(r,e+1),3,n)}function Cc(r,e,t,n){return mi(yi(r,e+1),5,n)}function Dc(r,e,t,n){return mi(Rc(r,e+1),9,n)}function Vt(r,e,t){let n=e.value;if(n===!1)r.push([u.float.majorEncoded|fi]);else if(n===!0)r.push([u.float.majorEncoded|hi]);else if(n===null)r.push([u.float.majorEncoded|di]);else if(n===void 0)r.push([u.float.majorEncoded|pi]);else{let o,i=!1;(!t||t.float64!==!0)&&(Nc(n),o=gi(re,1),n===o||Number.isNaN(n)?(re[0]=249,r.push(re.slice(0,3)),i=!0):(Uc(n),o=yi(re,1),n===o&&(re[0]=250,r.push(re.slice(0,5)),i=!0))),i||(Gd(n),o=Rc(re,1),re[0]=251,r.push(re.slice(0,9)))}}Vt.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){Nc(n);let o=gi(re,1);if(n===o||Number.isNaN(n))return 3;if(Uc(n),o=yi(re,1),n===o)return 5}return 9};var Pc=new ArrayBuffer(9),J=new DataView(Pc,1),re=new Uint8Array(Pc,0);function Nc(r){if(r===1/0)J.setUint16(0,31744,!1);else if(r===-1/0)J.setUint16(0,64512,!1);else if(Number.isNaN(r))J.setUint16(0,32256,!1);else{J.setFloat32(0,r);let e=J.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)J.setUint16(0,31744,!1);else if(t===0)J.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?J.setUint16(0,0):o<-14?J.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):J.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function gi(r,e){if(r.length-e<2)throw new Error(`${y} 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 Uc(r){J.setFloat32(0,r,!1)}function yi(r,e){if(r.length-e<4)throw new Error(`${y} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Gd(r){J.setFloat64(0,r,!1)}function Rc(r,e){if(r.length-e<8)throw new Error(`${y} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Vt.compareTokens=Q.compareTokens;function L(r,e,t){throw new Error(`${y} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function zr(r){return()=>{throw new Error(`${y} ${r}`)}}var g=[];for(let r=0;r<=23;r++)g[r]=L;g[24]=ja;g[25]=Va;g[26]=Ka;g[27]=Ha;g[28]=L;g[29]=L;g[30]=L;g[31]=L;for(let r=32;r<=55;r++)g[r]=L;g[56]=Wa;g[57]=Ga;g[58]=Qa;g[59]=Xa;g[60]=L;g[61]=L;g[62]=L;g[63]=L;for(let r=64;r<=87;r++)g[r]=Ya;g[88]=Za;g[89]=ec;g[90]=tc;g[91]=rc;g[92]=L;g[93]=L;g[94]=L;g[95]=zr("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)g[r]=oc;g[120]=ic;g[121]=sc;g[122]=ac;g[123]=cc;g[124]=L;g[125]=L;g[126]=L;g[127]=zr("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)g[r]=lc;g[152]=fc;g[153]=hc;g[154]=dc;g[155]=pc;g[156]=L;g[157]=L;g[158]=L;g[159]=mc;for(let r=160;r<=183;r++)g[r]=gc;g[184]=yc;g[185]=wc;g[186]=bc;g[187]=xc;g[188]=L;g[189]=L;g[190]=L;g[191]=Ec;for(let r=192;r<=215;r++)g[r]=vc;g[216]=_c;g[217]=Ac;g[218]=Sc;g[219]=Ic;g[220]=L;g[221]=L;g[222]=L;g[223]=L;for(let r=224;r<=243;r++)g[r]=zr("simple values are not supported");g[244]=L;g[245]=L;g[246]=L;g[247]=kc;g[248]=zr("simple values are not supported");g[249]=Lc;g[250]=Cc;g[251]=Dc;g[252]=L;g[253]=L;g[254]=L;g[255]=Tc;var ne=[];for(let r=0;r<24;r++)ne[r]=new h(u.uint,r,1);for(let r=-1;r>=-24;r--)ne[31-r]=new h(u.negint,r,1);ne[64]=new h(u.bytes,new Uint8Array(0),1);ne[96]=new h(u.string,"",1);ne[128]=new h(u.array,0,1);ne[160]=new h(u.map,0,1);ne[244]=new h(u.false,!1,1);ne[245]=new h(u.true,!0,1);ne[246]=new h(u.null,null,1);function wi(r){switch(r.type){case u.false:return le([244]);case u.true:return le([245]);case u.null:return le([246]);case u.bytes:return r.value.length?void 0:le([64]);case u.string:return r.value===""?le([96]):void 0;case u.array:return r.value===0?le([128]):void 0;case u.map:return r.value===0?le([160]):void 0;case u.uint:return r.value<24?le([Number(r.value)]):void 0;case u.negint:if(r.value>=-24)return le([31-Number(r.value)])}}var Jd={float64:!1,mapSorter:Zd,quickEncodeToken:wi},$c=Object.freeze({float64:!0,mapSorter:ep,quickEncodeToken:wi});function Xd(){let r=[];return r[u.uint.major]=Q,r[u.negint.major]=Pr,r[u.bytes.major]=ct,r[u.string.major]=uc,r[u.array.major]=Ur,r[u.map.major]=Rr,r[u.tag.major]=Br,r[u.float.major]=Vt,r}var ht=Xd(),Or=new $t,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(`${fe} object contains circular references`);return new r(t,e)}},Se={null:new h(u.null,null),undefined:new h(u.undefined,void 0),true:new h(u.true,!0),false:new h(u.false,!1),emptyArray:new h(u.array,0),emptyMap:new h(u.map,0)},he={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new h(u.float,r):r>=0?new h(u.uint,r):new h(u.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new h(u.uint,r):new h(u.negint,r)},Uint8Array(r,e,t,n){return new h(u.bytes,r)},string(r,e,t,n){return new h(u.string,r)},boolean(r,e,t,n){return r?Se.true:Se.false},null(r,e,t,n){return Se.null},undefined(r,e,t,n){return Se.undefined},ArrayBuffer(r,e,t,n){return new h(u.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new h(u.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Se.emptyArray,new h(u.break)]:Se.emptyArray;n=Ht.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=ft(s,t,n);return t.addBreakTokens?[new h(u.array,r.length),o,new h(u.break)]:[new h(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,a;if(s){a=new Array(s),n=Ht.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let f of i){let p=o?r.get(f):r[f];c&&p===void 0||(a[l++]=[ft(f,t,n),ft(p,t,n)])}l<s&&(a.length=l)}return a?.length?(Yd(a,t),t.addBreakTokens?[new h(u.map,a.length),a,new h(u.break)]:[new h(u.map,a.length),a]):t.addBreakTokens===!0?[Se.emptyMap,new h(u.break)]:Se.emptyMap},Tagged(r,e,t,n){return[new h(u.tag,r.tag),ft(r.value,t,n)]}};he.Map=he.Object;he.Buffer=he.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))he[`${r}Array`]=he.DataView;function ft(r,e={},t){let n=ui(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||he[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=he[n];if(!i)throw new Error(`${fe} unsupported type: ${n}`);return i(r,n,e,t)}function Yd(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Zd(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=ht[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function ep(r,e){if(r[0]instanceof h&&e[0]instanceof h){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Bc(t.value)),n._keyBytes||(n._keyBytes=Bc(n.value)),Cr(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Bc(r){return Mr(r,ht,$c)}function Kt(r,e,t,n){if(Array.isArray(e))for(let o of e)Kt(r,o,t,n);else t[e.type.major](r,e,n)}var zc=u.uint.majorEncoded,Oc=u.negint.majorEncoded,tp=u.bytes.majorEncoded,rp=u.string.majorEncoded,Mc=u.array.majorEncoded,np=u.float.majorEncoded|fi,op=u.float.majorEncoded|hi,ip=u.float.majorEncoded|di,sp=u.float.majorEncoded|pi,ap=BigInt(-1),cp=BigInt(1);function up(r){return r.addBreakTokens!==!0}function Fc(r,e,t,n){let o=ui(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){Kt(r,s,ht,t);return}}switch(o){case"null":r.push([ip]);return;case"undefined":r.push([sp]);return;case"boolean":r.push([e?op:np]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?Vt(r,new h(u.float,e),t):e>=0?N(r,zc,e):N(r,Oc,e*-1-1);return;case"bigint":e>=BigInt(0)?N(r,zc,e):N(r,Oc,e*ap-cp);return;case"string":{let s=at(e);N(r,rp,s.length),r.push(s);return}case"Uint8Array":N(r,tp,e.length),r.push(e);return;case"Array":if(!e.length){r.push([Mc]);return}n=Ht.createCheck(n,e),N(r,Mc,e.length);for(let s of e)Fc(r,s,t,n);return;case"Object":case"Map":{let s=he.Object(e,o,t,n);Kt(r,s,ht,t)}return;default:{let s=he[o];if(!s)throw new Error(`${fe} unsupported type: ${o}`);let a=s(e,o,t,n);Kt(r,a,ht,t)}}}function Mr(r,e,t,n){let o=n instanceof Uint8Array,i=o?new Dr(n):Or,s=ft(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new $t(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():De(i.chunks[0])}}return i.reset(),Kt(i,s,e,t),i.toBytes(!0)}function Ne(r,e){return e=Object.assign({},Jd,e),up(e)?(Or.reset(),Fc(Or,r,e,void 0),Or.toBytes(!0)):Mr(r,ht,e)}var lp={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},$r=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=ne[e];if(t===void 0){let n=g[e];if(!n)throw new Error(`${y} 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}},Ie=Symbol.for("DONE"),dt=Symbol.for("BREAK");function fp(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=ke(e,t);if(i===dt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed array`)}if(i===Ie)throw new Error(`${y} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function hp(r,e,t){let n=t.useMaps===!0,o=t.rejectDuplicateMapKeys===!0,i=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=ke(e,t);if(c===dt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed map`)}if(c===Ie)throw new Error(`${y} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${y} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${y} found repeat map key "${c}"`);let l=ke(e,t);if(l===Ie)throw new Error(`${y} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*dp(r,e,t){for(let n=0;n<r.value;n++){let o=ke(e,t);if(o===dt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed map`)}if(o===Ie)throw new Error(`${y} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=ke(e,t);if(i===Ie)throw new Error(`${y} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function pp(r,e){let t=!1,n=function(){if(t)throw new Error(`${y} tag decode() may only be called once`);t=!0;let o=ke(r,e);if(o===Ie)throw new Error(`${y} tag content missing`);if(o===dt)throw new Error(`${y} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${y} tag decode() may only be called once`);t=!0;let o=r.next();if(!u.equals(o.type,u.map))throw new Error(`${y} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of dp(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function ke(r,e){if(r.done())return Ie;let t=r.next();if(u.equals(t.type,u.break))return dt;if(t.type.terminal)return t.value;if(u.equals(t.type,u.array))return fp(t,r,e);if(u.equals(t.type,u.map))return hp(t,r,e);if(u.equals(t.type,u.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=pp(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${y} tag decoder must call decode() or entries()`);return o}throw new Error(`${y} tag not supported (${t.value})`)}throw new Error("unsupported")}function bi(r,e){if(!(r instanceof Uint8Array))throw new Error(`${y} data to decode must be a Uint8Array`);e=Object.assign({},lp,e);let t=De(r),n=e.tokenizer||new $r(t,e),o=ke(n,e);if(o===Ie)throw new Error(`${y} did not find any content to decode`);if(o===dt)throw new Error(`${y} got unexpected break`);return[o,r.subarray(n.pos())]}function oe(r,e){let[t,n]=bi(r,e);if(n.length>0)throw new Error(`${y} too many terminals, data makes no sense`);return t}var Fr=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(Fr.prototype,Symbol.toStringTag,{value:"Tagged"});var qr=class extends q{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var ye="/",jc=new TextEncoder().encode(ye),jr=jc[0],we=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=Er(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]!==jr)throw new Error("Invalid key")}toString(e="utf8"){return it(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(ye))}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=jc),this._buf[0]!==jr){let e=new Uint8Array(this._buf.byteLength+1);e.fill(jr,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===jr;)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(ye).slice(1)}type(){return mp(this.baseNamespace())}name(){return gp(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(ye)||(e+=ye),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(ye):new r(e.slice(0,-1).join(ye))}child(e){return this.toString()===ye?e:e.toString()===ye?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(),...yp(e.map(t=>t.namespaces()))])}};function mp(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function gp(r){let e=r.split(":");return e[e.length-1]}function yp(r){return[].concat(...r)}function wp(r){return r[Symbol.asyncIterator]!=null}function bp(r){if(wp(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Uo([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Uo(e,t)}var Vr=bp;function Kr({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*xp(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=P.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*xi(n,o))}else{let t=P.asCID(e);t!=null?yield[r.join("/"),t]:yield*xi(e,r)}}function*xi(r,e){if(r==null||r instanceof Uint8Array)return;let t=P.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*xp(i,o)}}function*Ep(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&P.asCID(n)==null&&(yield*Ei(n,o))}else yield*Ei(e,r)}function*Ei(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"&&P.asCID(n)==null&&(yield*Ep(o,n))}}function vp(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=P.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var vi=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:Kr(),bytes:Kr(),value:Kr(),asBlock:Kr()})}links(){return xi(this.value,[])}tree(){return Ei(this.value,[])}get(e="/"){return vp(this.value,e.split("/").filter(Boolean))}};function Hr({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 vi({cid:e,bytes:r,value:o})}var Wr=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},Wt=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},Gr=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},Ue=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},Qr=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},Jr=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},Gt=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var Hc="/pin/",Vc="/pinned-block/",_i=me,Kc=1;function Xr(r){return r.version===0&&(r=r.toV1()),new we(`${Hc}${r.toString(_i)}`)}var Yr=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Xr(e);if(await this.datastore.has(n))throw new Wr("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Oe("Depth must be greater than or equal to 0");let i=new q({concurrency:Kc});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>Ut(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ne(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await Vr(this.blockstore.get(e,n)),s=Hr({bytes:i,cid:e,codec:o});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new we(`${Vc}${_i.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=oe(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ne(i),n),n.onProgress?.(new E("helia:pin:add",e))}}async*rm(e,t={}){let n=Xr(e),o=await this.datastore.get(n,t),i=oe(o);await this.datastore.delete(n,t);let s=new q({concurrency:Kc});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Ut(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Hc+(e.cid!=null?`${e.cid.toString(me)}`:"")},e)){let o=P.parse(t.toString().substring(5),me),i=oe(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new we(`${Vc}${_i.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Xr(e),o=await this.datastore.get(n,t);return oe(o)}async setMetadata(e,t,n){let o=Xr(e),i=await this.datastore.get(o,n),s=oe(i);s.metadata=t??{},await this.datastore.put(o,Ne(s),n)}};var Zr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Re=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},en=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},tn=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var _p=5,rn=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??_p,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 be(...this.routers)}async stop(){await xe(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Re("No content routers available");let n=new qr({concurrency:this.providerLookupConcurrency}),o=0,i=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let c=Be(this.routers,"findProviders").map(async function*(l){let f=0;t?.onProgress?.(new E("helia:routing:find-providers:start",{routing:l.name,cid:e}));try{for await(let p of l.findProviders(e,t))f++,t?.onProgress?.(new E("helia:routing:find-providers:provider",{routing:l.name,cid:e,provider:p})),yield p}catch(p){i.push(p)}finally{s.log("router %s found %d providers for %c",l,f,e),t?.onProgress?.(new E("helia:routing:find-providers:end",{routing:l.name,cid:e,found:f})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let l of Tr(n.toGenerator(),...c))if(l!=null){if(l.multiaddrs.length===0){if(n.find(l.id)!=null)continue;n.add(async()=>{try{let f=await this.findPeer(l.id,t);return f.multiaddrs.length===0?null:{...f,protocols:l.protocols,routing:l.routing}}catch(f){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,f),null}},{peerId:l.id,signal:t.signal}).catch(f=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,f)});continue}o++,yield l}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new Re("No content routers available");await Promise.all(Be(this.routers,"provide").map(async n=>{t?.onProgress?.(new E("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new E("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(Be(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new E("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new E("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(Be(this.routers,"put").map(async o=>{n?.onProgress?.(new E("helia:routing:put:start",{routing:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new E("helia:routing:put:end",{routing:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o;try{o=await Promise.any(Be(this.routers,"get").map(async i=>{t?.onProgress?.(new E("helia:routing:get:start",{routing:i.name,key:e}));try{return await i.get(e,t)}catch(s){this.log("router %s failed with %e",i,s),n.push(s)}finally{t?.onProgress?.(new E("helia:routing:get:end",{routing:i.name,key:e}))}}))}catch{}if(o==null)throw new Qr(n,`Failed to get value key ${it(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new Re("No peer routers available");let n=this,o=Tr(...Be(this.routers,"findPeer").map(i=>(async function*(){t?.onProgress?.(new E("helia:routing:find-peer:start",{routing:i.name,peerId:e}));try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}finally{t?.onProgress?.(new E("helia:routing:find-peer:end",{routing:i.name,peerId:e}))}})()));for await(let i of o)if(i!=null)return i;throw new er("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Re("No peer routers available");for await(let n of Tr(...Be(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new E("helia:routing:get-closest-peers:start",{routing:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new E("helia:routing:get-closest-peers:end",{routing:o.name,key:e}))}})))n!=null&&(yield n)}};function Be(r,e){return r.filter(t=>t[e]!=null)}var W=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function nn(r,e,t,n){let o=new W(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let i=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((s,a)=>{function c(){Si(t,"abort",p),Si(r,e,l),Si(r,i,f)}let l=m=>{try{if(n?.filter?.(m)===!1)return}catch(b){c(),a(b);return}c(),s(m)},f=m=>{if(c(),m instanceof Error){a(m);return}a(m.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},p=()=>{c(),a(o)};Ai(t,"abort",p),Ai(r,e,l),Ai(r,i,f)})}function Ai(r,e,t){r!=null&&(Wc(r)?r.addEventListener(e,t):r.addListener(e,t))}function Si(r,e,t){r!=null&&(Wc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Wc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var on=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var sn=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new W)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ap(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var an=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Ap(),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 W),this.cleanup())}async join(e={}){let t=new sn(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 Ae(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)})}};function Ii(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Qt=class extends G{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Ii(this.emitEmpty.bind(this),1),this.emitIdle=Ii(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new on;let n=new an(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(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("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new W)}),this.clear()}async onEmpty(e){this.size!==0&&await nn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await nn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await nn(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=_r({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new W("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var cn="lock:worker:request-read",un="lock:worker:abort-read-request",ln="lock:worker:release-read",fn="lock:master:grant-read",hn="lock:master:error-read",dn="lock:worker:request-write",pn="lock:worker:abort-write-request",mn="lock:worker:release-write",gn="lock:master:grant-write",yn="lock:master:error-write",wn="lock:worker:finalize",bn="mortice",Gc={singleProcess:!1};var ki=(r,e,t,n,o,i,s,a,c)=>l=>{if(l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===o&&r.safeDispatchEvent(t,{detail:{name:f.name,identifier:f.identifier,handler:async()=>{e.postMessage({type:c,name:f.name,identifier:f.identifier}),await new Promise(p=>{let m=b=>{if(b?.data==null)return;let d={type:b.data.type,name:b.data.name,identifier:b.data.identifier};d.type===a&&d.identifier===f.identifier&&(e.removeEventListener("message",m),p())};e.addEventListener("message",m)})},onError:p=>{e.postMessage({type:s,name:f.name,identifier:f.identifier,error:{message:p.message,name:p.name,stack:p.stack}})}}}),f.type===i&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===wn&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var Qc=(r=10)=>Math.random().toString().substring(2,r+2);var xn=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(bn)}readLock(e){return this.sendRequest(cn,un,fn,hn,ln,e)}writeLock(e){return this.sendRequest(dn,pn,gn,yn,mn,e)}finalize(){this.channel.postMessage({type:wn,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=Qc();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let f=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",f,{once:!0});let p=m=>{if(m.data?.identifier===a&&(m.data?.type===n&&(this.channel.removeEventListener("message",p),s?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),m.data.type===o)){this.channel.removeEventListener("message",p),s?.signal?.removeEventListener("abort",f);let b=new Error;m.data.error!=null&&(b.message=m.data.error.message,b.name=m.data.error.name,b.stack=m.data.error.stack),l(b)}};this.channel.addEventListener("message",p)})}};var Jc=r=>{if(r=Object.assign({},Gc,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(bn),n=new G;return t.addEventListener("message",ki(n,t,"requestReadLock","abortReadLockRequest",cn,un,hn,ln,fn)),t.addEventListener("message",ki(n,t,"requestWriteLock","abortWriteLockRequest",dn,pn,yn,mn,gn)),n}return new xn(r.name)};var ze=new Map,Jt;function Xc(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Sp(r){if(Jt==null&&(Jt=Jc(r),!Xc(Jt))){let e=Jt;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=ze.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=ze.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=ze.get(n);o?.finalize()})}return Jt}async function Ti(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new W)};return e?.signal?.addEventListener("abort",i,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",i),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),o}var Yc=(r,e)=>{let t=ze.get(r);if(t!=null)return t;let n=Sp(e);if(Xc(n))return t=n,ze.set(r,t),t;let o=new Qt({concurrency:1}),i;return t={async readLock(s){if(i!=null)return Ti(i,s);i=new Qt({concurrency:e.concurrency,autoStart:!1});let a=i,c=Ti(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(s){return i=null,Ti(o,s)},finalize:()=>{ze.delete(r)},queue:o},ze.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Ip={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Li(r){let e=Object.assign({},Ip,r);return Yc(e.name,e)}var En=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=Li({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await be(this.child),this.started=!0}async stop(){await xe(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{yield*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 Wt("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),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 Wt("Block was pinned - please unpin and try again");await o.routing.cancelReprovide(i,t),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 Ci=new we("/version"),Zc=1;async function eu(r){if(!await r.has(Ci)){await r.put(Ci,Er(`${Zc}`));return}let e=await r.get(Ci),t=it(e);if(parseInt(t,10)!==Zc)throw new Gr("Invalid datastore version, a datastore migration may be required")}var Ui={};_(Ui,{code:()=>Ni,decode:()=>Bp,decodeOptions:()=>Np,encode:()=>Rp,encodeOptions:()=>Dp,name:()=>Up,toByteView:()=>ru});var tu=42;function ru(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function kp(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=P.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new h(u.tag,tu),new h(u.bytes,t)]}function Tp(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Lp(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}function Cp(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Di={float64:!0,typeEncoders:{Map:Cp,Object:kp,undefined:Tp,number:Lp}},Dp={...Di,typeEncoders:{...Di.typeEncoders}};function Pp(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return P.decode(e.subarray(1))}var Pi={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[tu]:Pp}},Np={...Pi,tags:{...Pi.tags}},Up="dag-cbor",Ni=113,Rp=r=>Ne(r,Di),Bp=r=>oe(ru(r),Pi);var $i={};_($i,{code:()=>Mi,decode:()=>iu,encode:()=>ou,format:()=>Wp,name:()=>Hp,parse:()=>Qp,stringify:()=>Wp});var Ri=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(u.equals(t.type,u.array)&&(t.elements++,t.elements!==1&&e.push([44])),u.equals(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(`${fe} unsupported type: Uint8Array`)}[u.string.major](e,t){this.prefix(e);let n=at(JSON.stringify(t.value));e.push(n.length>32?De(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(u.equals(s.type,u.array))e.push([93]);else if(u.equals(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(`${fe} 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 zp(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${fe} 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(`${fe} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${fe} unexpected duplicate map keys, this is not supported`)}var Op={addBreakTokens:!0,mapSorter:zp};function Bi(r,e){return e=Object.assign({},Op,e),Mr(r,new Ri,e)}var pt=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(`${y} 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(`${y} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new h(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(`${y} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${y} 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 h(u.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new h(s>=0?u.uint:u.negint,s,this._pos-e):new h(s>=0?u.uint:u.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${y} 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 a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new h(u.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${y} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${y} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${y} unexpected unicode sequence at position ${this._pos}`);let c,l,f,p;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(p=(i&31)<<6|c&63,p>127&&(s=p));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(p=(i&15)<<12|(c&63)<<6|l&63,p>2047&&(p<55296||p>57343)&&(s=p));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],f=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(f&192)===128&&(p=(i&15)<<18|(c&63)<<12|(l&63)<<6|f&63,p>65535&&p<1114112&&(s=p))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${y} 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(`${y} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new h(u.string,qa(t),this._pos-e);default:if(i<32)throw new Error(`${y} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${y} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new h(u.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new h(u.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new h(u.null,null,4);case 102:return this.expect([102,97,108,115,101]),new h(u.false,!1,5);case 116:return this.expect([116,114,117,101]),new h(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(`${y} 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 h(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${y} 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 h(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 h(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${y} 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 h(u.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${y} 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(`${y} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function zi(r,e){return e=Object.assign({tokenizer:new pt(r,e)},e),oe(r,e)}function $p(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Fp(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=P.asCID(r);if(!e)return null;let t=e.toString();return[new h(u.map,1/0,1),new h(u.string,"/",1),new h(u.string,t,t.length),new h(u.break,void 0,1)]}function vn(r){let e=et.encode(r).slice(1);return[new h(u.map,1/0,1),new h(u.string,"/",1),new h(u.map,1/0,1),new h(u.string,"bytes",5),new h(u.string,e,e.length),new h(u.break,void 0,1),new h(u.break,void 0,1)]}function ie(r){return vn(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function qp(r){return vn(new Uint8Array(r))}function jp(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Vp(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 Kp={typeEncoders:{Object:Fp,Buffer:vn,Uint8Array:vn,Int8Array:ie,Uint16Array:ie,Int16Array:ie,Uint32Array:ie,Int32Array:ie,Float32Array:ie,Float64Array:ie,Uint8ClampedArray:ie,BigInt64Array:ie,BigUint64Array:ie,DataView:ie,ArrayBuffer:qp,undefined:jp,number:Vp}},Oi=class extends pt{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(u.equals(e.type,u.map)){let t=this._next();if(u.equals(t.type,u.string)&&t.value==="/"){let n=this._next();if(u.equals(n.type,u.string)){let o=this._next();if(!u.equals(o.type,u.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new h(u.tag,42,0)}if(u.equals(n.type,u.map)){let o=this._next();if(u.equals(o.type,u.string)&&o.value==="bytes"){let i=this._next();if(u.equals(i.type,u.string)){for(let a=0;a<2;a++){let c=this._next();if(!u.equals(c.type,u.break))throw new Error("Invalid encoded Bytes form")}let s=et.decode(`m${i.value}`);return new h(u.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},nu={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>P.parse(r())}},Hp="dag-json",Mi=297,ou=r=>Bi(r,Kp),iu=r=>{let e=$p(r),t=Object.assign(nu,{tokenizer:new Oi(e,nu)});return zi(e,t)},Wp=r=>Gp.decode(ou(r));var Gp=new TextDecoder,Qp=r=>iu(Jp.encode(r)),Jp=new TextEncoder;var Hi={};_(Hi,{code:()=>Ki,createLink:()=>mu,createNode:()=>pu,decode:()=>um,encode:()=>cm,name:()=>am,prepare:()=>ji,validate:()=>Vi});var Xp=new TextDecoder;function Fi(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 _n(r,e){let t;[t,e]=Fi(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 su(r,e){let t;return[t,e]=Fi(r,e),[t&7,t>>3,e]}function Yp(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=su(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]=_n(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]=_n(r,n),e.Name=Xp.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]=Fi(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 au(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=su(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=_n(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=_n(r,t),n.push(Yp(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var uu=new TextEncoder,cu=2**32,Zp=2**31;function em(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=Xt(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=uu.encode(r.Name);t-=n.length,e.set(n,t),t=Xt(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Xt(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function lu(r){let e=rm(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Xt(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=em(r.Links[o],t.subarray(0,n));n-=i,n=Xt(t,n,i)-1,t[n]=18}return t}function tm(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+mt(t)}if(typeof r.Name=="string"){let t=uu.encode(r.Name).length;e+=1+t+mt(t)}return typeof r.Tsize=="number"&&(e+=1+mt(r.Tsize)),e}function rm(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+mt(t)}if(r.Links)for(let t of r.Links){let n=tm(t);e+=1+n+mt(n)}return e}function Xt(r,e,t){e-=mt(t);let n=e;for(;t>=Zp;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function mt(r){return r%2===0&&r++,Math.floor((nm(r)+6)/7)}function nm(r){let e=0;return r>=cu&&(r=Math.floor(r/cu),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+om[r]}var om=[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 im=["Data","Links"],sm=["Hash","Name","Tsize"],qi=new TextEncoder;function hu(r,e){if(r===e)return 0;let t=r.Name?qi.encode(r.Name):[],n=e.Name?qi.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function fu(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function du(r){if(typeof r.asCID=="object"){let t=P.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=P.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=P.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=P.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 ji(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=qi.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(du),e.Links.sort(hu);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Vi(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!fu(r,im))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(!fu(t,sm))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&&hu(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function pu(r,e=[]){return ji({Data:r,Links:e})}function mu(r,e,t){return du({Hash:t,Name:r,Tsize:e})}function gu(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var am="dag-pb",Ki=112;function cm(r){Vi(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),lu(e)}function um(r){let e=gu(r),t=au(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=P.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 gt(r){return r?.then!=null}function yu(r=[],e){let t={[Ki]:Hi,[Xo]:mr,[Ni]:Ui,[Mi]:$i,[Jo]:pr};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);gt(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new tn(`Could not load codec for ${n}`)}}function wu(r=[],e){let t={[wr.code]:wr,[br.code]:br,[yr.code]:yr};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);gt(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new en(`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`)}}var An=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};var Sn=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,bytes:o}of e)await this.put(n,o,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes: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 In=0,yt=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},kn=class extends Sn{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===In){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new yt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===In){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new yt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new An;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===In){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new yt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===In){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new yt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function lm(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 Tn=lm;function fm(r){return r[Symbol.asyncIterator]!=null}function hm(r,e){let t=0;if(fm(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Tn(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(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Ln=hm;function dm(r){return r[Symbol.asyncIterator]!=null}function bu(r){return r?.then!=null}function pm(r,e){let t=0;if(dm(r))return(async function*(){for await(let c of r){let l=e(c,t++);bu(l)&&await l,yield c}})();let n=Tn(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(let c of n){let l=e(c,t++);bu(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var Wi=pm;var gm=128,wt=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new kn(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??gm}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new E("blocks:put:duplicate",e)),e):(n.onProgress?.(new E("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new E("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Ln(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new E("blocks:put-many:duplicate",i)),!s}),o=Wi(n,async({cid:i})=>{t.onProgress?.(new E("blocks:put-many:providers:notify",i)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new E("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new Gt("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new E("blocks:get:providers:get",e));let s=await xu(e,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new E("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new E("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new E("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new E("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Wi(e,async n=>{let o=await this.child.has(n,t),i=t.offline===!0;if(!o){if(i)throw new Gt("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new E("blocks:get-many:providers:get",n));let a=await xu(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new E("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new E("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new E("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new E("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 E("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function xu(r,e,t,n){let o=wm(r,t),i=new AbortController,s=te([i.signal,n.signal]);i.signal;let a=[];for(let c of e)ym(c)&&a.push(c);if(a.length===0)throw new Ue(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,f=await c.retrieve(r,{...n,signal:s,validateFn:async p=>{await o(p),n.signal?.throwIfAborted(),l=!0}});return l||(await o(f),n.signal?.throwIfAborted()),f}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new Jr(c.errors,`Failed to load block for ${r}`)}finally{i.abort(),s.clear()}}function ym(r){return typeof r.retrieve=="function"}var wm=(r,e)=>{if(e==null)throw new Oe(`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,{truncate:r.multihash.digest.byteLength});if(gt(o)?n=await o:n=o,!Ut(n.digest,r.multihash.digest))throw new tr("Hash of downloaded block did not match multihash from passed CID")}};var Cn=class extends wt{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 addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}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{yield*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()}}};var Dn=class extends wt{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await be(this.child,...this.blockBrokers),this.started=!0}async stop(){await xe(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new Ue("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new Ue(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new Cn({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var Pn=class extends G{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=hr(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=et.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let i=F(),s={promise:i.promise,observers:1,queryFilter:hr(this.cidPeerFilterSize)};this.requests.set(n,s);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,l=new q({concurrency:this.maxProviders});l.addEventListener("failure",m=>{this.log.error("error querying provider %s, evicting from session - %e",m.detail.job.options.provider,m.detail.error),this.evict(m.detail.job.options.provider)}),l.addEventListener("success",m=>{c=!0,i.resolve(m.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let m=0;m<this.minProviders&&this.providers.length!==0;m++){let b=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(b)}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(m=>{this.log.error("could not find new providers for %c - %e",e,m),i.reject(m)})});let f=m=>{let b=this.toFilterKey(m.detail);s.queryFilter.has(b)||(s.queryFilter.add(b),this.emitFoundProviderProgressEvent(e,m.detail,t),l.add(async()=>this.queryProvider(e,m.detail,t),{provider:m.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)}))};if(this.addEventListener("provider",f),a)try{await Ae(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(m){throw a&&this.log("failed to find initial session peers for %c - %e",e,m),this.requests.delete(n),s.observers>1&&i.reject(m),m}Promise.all([...this.providers].filter(m=>{let b=this.toFilterKey(m),d=s.queryFilter.has(b);return d||s.queryFilter.add(this.toFilterKey(m)),!d}).map(async m=>l.add(async()=>this.queryProvider(e,m,t),{provider:m}))).catch(m=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,m)});let p=()=>{i.reject(new X(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",p);try{return await i.promise}finally{this.removeEventListener("provider",f),t.signal?.removeEventListener("abort",p),l.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(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.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=F(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let s=this,a=async function*(){for(;s.initialProviders.length>0;){let l=s.initialProviders.pop();if(l==null)continue;let f=await s.convertToProvider(l,"manual",n);f!=null&&(yield f)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",i,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),i++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",i,t,this.providers.length),this.providers.length<t)throw new Zr(`Found ${i} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),o.reject(s)}),o.promise}};function Eu(r){return e=>new Gi(e,r)}function vu(r){return e=>new Qi(e,r)}function _u(r){return e=>new Ji(e,r)}var Yt=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),o=Ln(n.toGenerator(t),a=>a!=null),i=!1,s=async a=>{let c=a.cid,l=await Vr(this.components.blockstore.get(c,a)),f=Hr({cid:c,bytes:l,codec:await this.components.getCodec(c.code)});for(let[,p]of f.links())t?.includeChild?.(p,f)!==!1&&n.add(s,{...a,cid:p,depth:a.depth+1,path:[...a.path,p]}).catch(m=>{i||o.throw(m)});return{block:f,depth:a.depth,path:a.path}};n.add(s,{...t,cid:e,depth:0,path:[e]}).catch(a=>{i||o.throw(a)});try{yield*o}finally{i=!0,n.abort()}}},Gi=class extends Yt{getQueue(){return new q({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}},Qi=class extends Yt{getQueue(){return new q({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?-1:1})}},Ji=class extends Yt{getQueue(){return new q({concurrency:1})}};var Xi=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??e.libp2p.logger,this.log=this.logger.forComponent("helia"),this.getHasher=wu(e.hashers,e.loadHasher),this.getCodec=yu(e.codecs,e.loadCodec),this.dns=e.dns??zs(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new G;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,libp2p:this.libp2p,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new rn(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let i=[o],s=vm(o);s!=null&&i.push(s);let a=_m(o);return a!=null&&i.push(a),i}),providerLookupConcurrency:e.providerLookupConcurrency}),t.blockBrokers=e.blockBrokers.map(o=>o(t));let n=new Dn(t,e);this.pins=new Yr(e.datastore,n,this.getCodec),this.blockstore=new En(n,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore}async start(){await eu(this.datastore),await be(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await xe(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("stop",{detail:this}))}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Os(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 E("helia:gc:deleted",i))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new E("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function vm(r){return r?.[ts]}function _m(r){return r?.[rs]}return Lu(Am);})();
3
3
  return HeliaUtils}));
4
4
  //# sourceMappingURL=index.min.js.map