@helia/http 3.0.10 → 3.0.11

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
@@ -7,10 +7,10 @@ ${e}${n.split(`
7
7
  `).join(`
8
8
  ${e}`)}`:n!=null?`${n.split(`
9
9
  `).join(`
10
- ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function tI(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function lb(r,e=""){if(tI(r)){let t=ab(r,e);return r.errors.length>0?(e=`${e} `,t+=`${r.errors.map(n=>`
11
- ${e}${lb(n,`${e}`)}`).join(`
10
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function tI(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function lb(r,e=""){if(tI(r)){let t=ab(r,e);return r.errors.length>0?(e=`${e} `,t+=`
11
+ ${e}${r.errors.map(n=>`${lb(n,`${e}`)}`).join(`
12
12
  ${e}`)}`):t+=`
13
- ${e}[Error list was empty]`,t.trim()}return ab(r,e)}ct.formatters.e=r=>r==null?"undefined":lb(r);function rI(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function dr(r){return{forComponent(e){return Ct(e,r)}}}function Ct(r,e){let t=rI(`${r}:trace`);return ct.enabled(`${r}:trace`)&&ct.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=ct(`${r}:trace`,e)),Object.assign(ct(r,e),{error:ct(`${r}:error`,e),trace:t,newScope:n=>Ct(`${r}:${n}`,e)})}function cb(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var ns=class extends qt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var qc=class extends qt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var zc=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new gp}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ic("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},gp=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var yp=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Xe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new yp({name:e,metrics:t}):n=new Map,n}function nI(r){return r[Symbol.asyncIterator]!=null}function oI(r){if(nI(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ii=oI;function sI(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 os=sI;function iI(r){return r[Symbol.asyncIterator]!=null}function aI(r,e){let t=0;if(iI(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=os(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Gc=aI;function cI(r){return r[Symbol.asyncIterator]!=null}function lI(r,e){return cI(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Wc=lI;var xt=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function jc(r,e,t,n){let o=new xt(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){bp(t,"abort",u),bp(r,e,l),bp(r,s,f)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},f=d=>{if(c(),d instanceof Error){a(d);return}a(d.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.`))},u=()=>{c(),a(o)};wp(t,"abort",u),wp(r,e,l),wp(r,s,f)})}function wp(r,e,t){r!=null&&(ub(r)?r.addEventListener(e,t):r.addListener(e,t))}function bp(r,e,t){r!=null&&(ub(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function ub(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var fb=Symbol.for("nodejs.util.inspect.custom"),uI=114,ki=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ca]=!0;toString(){return this.string==null&&(this.string=le.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return H.createV1(uI,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return X(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return X(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[fb](){return`PeerId(${this.toString()})`}},_i=class extends ki{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ci=class extends ki{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ti=class extends ki{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},fI=2336,Bi=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ge.digest(B(this.url))}[fb](){return`PeerId(${this.url})`}[Ca]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return H.createV1(fI,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=U(e)),e.toString()===this.toString())}};var dI=114,db=2336;function Tt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=dt(le.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Wn(H.parse(r));if(e==null)throw new k('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=dt(e.decode(r))}return ss(t)}function xp(r){if(r.type==="Ed25519")return new Ci({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Ti({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new _i({multihash:r.toCID().multihash,publicKey:r});throw new Dt}function hb(r){return xp(r.publicKey)}function ss(r){if(pI(r))return new _i({multihash:r});if(hI(r))try{let e=Ja(r);if(e.type==="Ed25519")return new Ci({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Ti({multihash:r,publicKey:e})}catch{let t=U(r.digest);return new Bi(new URL(t))}throw new Vr("Supplied PeerID Multihash is invalid")}function Wn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==dI&&r.code!==db)throw new va("Supplied PeerID CID is invalid");if(r.code===db){let e=U(r.multihash.digest);return new Bi(new URL(e))}return ss(r.multihash)}function hI(r){return r.code===Ge.code}function pI(r){return r.code===Rt.code}function jn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Yc(r){let e=dt(le.decode(`z${r}`));return ss(e)}var Bt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return jn(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return jn(this.map.values(),e=>e.key)}values(){return jn(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Yn=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return jn(this.set.entries(),e=>{let t=Yc(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Yc(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return jn(this.set.values(),e=>Yc(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var vp=class extends Bt{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ep(r){let{name:e,metrics:t}=r,n;return t!=null?n=new vp({name:e,metrics:t}):n=new Bt,n}function mI(r){return r[Symbol.asyncIterator]!=null}function gI(r){if(mI(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Ce([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ce(e,t)}var pb=gI;var Sp=pn(gb(),1);var Ip=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},yb=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function kp(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,f=new Promise((u,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(yb(i));return}if(i&&(c=()=>{d(yb(i))},i.addEventListener("abort",c,{once:!0})),r.then(u,d),t===Number.POSITIVE_INFINITY)return;let h=new Ip;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}function _p(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Pi=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},s={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(s);return}let i=_p(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(i,0,s)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Zn=class extends Sp.default{#e;#t;#r=0;#i;#s=!1;#f=!1;#d;#b=0;#g=0;#a;#c;#n;#x;#o=0;#h;#l;#k=1n;#p=new Map;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Pi,...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(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#i=e.intervalCap,this.#d=e.interval,this.#n=new e.queueClass,this.#x=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.#N()}get#_(){return this.#t||this.#r<this.#i}get#C(){return this.#o<this.#h}#T(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#y(),this.emit("next")}#B(){this.#S(),this.#A(),this.#c=void 0}get#L(){let e=Date.now();if(this.#a===void 0){let t=this.#b-e;if(t<0){if(this.#g>0){let n=e-this.#g;if(n<this.#d)return this.#v(this.#d-n),!0}this.#r=this.#e?this.#o:0}else return this.#v(t),!0}return!1}#v(e){this.#c===void 0&&(this.#c=setTimeout(()=>{this.#B()},e))}#E(){this.#a&&(clearInterval(this.#a),this.#a=void 0)}#P(){this.#c&&(clearTimeout(this.#c),this.#c=void 0)}#y(){if(this.#n.size===0)return this.#E(),this.emit("empty"),this.#o===0&&(this.#P(),this.emit("idle")),!1;let e=!1;if(!this.#l){let t=!this.#L;if(this.#_&&this.#C){let n=this.#n.dequeue();this.#t||(this.#r++,this.#m()),this.emit("active"),this.#g=Date.now(),n(),t&&this.#A(),e=!0}}return e}#A(){this.#t||this.#a!==void 0||(this.#a=setInterval(()=>{this.#S()},this.#d),this.#b=Date.now()+this.#d)}#S(){this.#r===0&&this.#o===0&&this.#a&&this.#E(),this.#r=this.#e?this.#o:0,this.#w(),this.#m()}#w(){for(;this.#y(););}get concurrency(){return this.#h}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.#h=e,this.#w()}async#D(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}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.#n.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#k++).toString(),t={timeout:this.timeout,...t},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`);this.#n.enqueue(async()=>{this.#o++,this.#p.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});try{try{t.signal?.throwIfAborted()}catch(c){throw this.#t||this.#r--,this.#p.delete(s),c}let i=e({signal:t.signal});t.timeout&&(i=kp(Promise.resolve(i),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#n.size} waiting)`})),t.signal&&(i=Promise.race([i,this.#D(t.signal)]));let a=await i;n(a),this.emit("completed",a)}catch(i){o(i),this.emit("error",i)}finally{this.#p.delete(s),queueMicrotask(()=>{this.#T()})}},t),this.emit("add"),this.#y()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#l?(this.#l=!1,this.#w(),this):this}pause(){this.#l=!0}clear(){this.#n=new this.#x,this.#I()}async onEmpty(){this.#n.size!==0&&await this.#u("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#u("next",()=>this.#n.size<e)}async onIdle(){this.#o===0&&this.#n.size===0||await this.#u("idle")}async onPendingZero(){this.#o!==0&&await this.#u("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#u("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#u("rateLimitCleared")}async onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#u(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#l}#N(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#m()}),this.on("next",()=>{this.#m()}))}#m(){this.#t||this.#f||(this.#f=!0,queueMicrotask(()=>{this.#f=!1,this.#I()}))}#I(){let e=this.#s,t=!this.#t&&this.#r>=this.#i&&this.#n.size>0;t!==e&&(this.#s=t,this.emit(t?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#s}get isSaturated(){return this.#o===this.#h&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#p.values()].map(e=>({...e}))}};function Xc(r){let e=[vt.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Cp=60;function Jc(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:vt[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:vt[e.type],TTL:e.TTL??e.ttl??Cp,data:e.data instanceof Uint8Array?U(e.data):e.data}))}}var bI=4;function Tp(r,e={}){let t=new Zn({concurrency:e.queryConcurrency??bI});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Xc(o.types).forEach(a=>{s.append("type",vt[a])}),o.onProgress?.(new W("dns:query",n));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Jc(await a.json());return o.onProgress?.(new W("dns:response",c)),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function wb(){return[Tp("https://cloudflare-dns.com/dns-query"),Tp("https://dns.google/resolve")]}var vb=pn(xb(),1);var Bp=class{lru;constructor(e){this.lru=(0,vb.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return Jc({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:vt[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Cp)*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 Eb(r){return new Bp(r)}var xI=1e3,Qc=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Eb(e.cacheSize??xI),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["."]=wb())}async query(e,t={}){let n=Xc(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new W("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new W("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var vt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(vt||(vt={}));function el(r={}){return new Qc(r)}var Tr="/",Ab=new TextEncoder().encode(Tr),tl=Ab[0],ge=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=B(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==tl)throw new Error("Invalid key")}toString(e="utf8"){return U(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Tr))}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=Ab),this._buf[0]!==tl){let e=new Uint8Array(this._buf.byteLength+1);e.fill(tl,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===tl;)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 s=t[o],i=n[o];if(s<i)return!0;if(s>i)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(Tr).slice(1)}type(){return vI(this.baseNamespace())}name(){return EI(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Tr)||(e+=Tr),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Tr):new r(e.slice(0,-1).join(Tr))}child(e){return this.toString()===Tr?e:e.toString()===Tr?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(),...AI(e.map(t=>t.namespaces()))])}};function vI(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function EI(r){let e=r.split(":");return e[e.length-1]}function AI(r){return[].concat(...r)}function rl({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*SI(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],s=H.asCID(n);s!=null?yield[o.join("/"),s]:typeof n=="object"&&(yield*Lp(n,o))}else{let t=H.asCID(e);t!=null?yield[r.join("/"),t]:yield*Lp(e,r)}}function*Lp(r,e){if(r==null||r instanceof Uint8Array)return;let t=H.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let s=[...e,n];yield*SI(s,o)}}function*II(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&H.asCID(n)==null&&(yield*Pp(n,o))}else yield*Pp(e,r)}function*Pp(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"&&H.asCID(n)==null&&(yield*II(o,n))}}function kI(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(i=>`[${JSON.stringify(i)}]`).join("")}`);let s=H.asCID(t);if(s!=null)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:t}}var Dp=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:rl(),bytes:rl(),value:rl(),asBlock:rl()})}links(){return Lp(this.value,[])}tree(){return Pp(this.value,[])}get(e="/"){return kI(this.value,e.split("/").filter(Boolean))}};function Sb({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 Dp({cid:e,bytes:r,value:o})}var nl=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},Di=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},ol=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},sl=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"};var _b="/pin/",Ib="/pinned-block/",Np=sr,kb=1;function il(r){return r.version===0&&(r=r.toV1()),new ge(`${_b}${r.toString(Np)}`)}var al=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=il(e);if(await this.datastore.has(n))throw new nl("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new k("Depth must be greater than or equal to 0");let s=new qt({concurrency:kb});for await(let a of this.#e(e,s,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>X(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,an(i),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),s=await pb(this.blockstore.get(e,n)),i=Sb({bytes:s,cid:e,codec:o});yield e;for(let[,a]of i.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new ge(`${Ib}${Np.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=bt(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,an(s),n),n.onProgress?.(new W("helia:pin:add",e))}}async*rm(e,t={}){let n=il(e),o=await this.datastore.get(n,t),s=bt(o);await this.datastore.delete(n,t);let i=new qt({concurrency:kb});for await(let a of this.#e(e,i,{...t,depth:s.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>X(l,e.bytes)),!0),{...t,depth:s.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:_b+(e.cid!=null?`${e.cid.toString(sr)}`:"")},e)){let o=H.parse(t.toString().substring(5),sr),s=bt(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new ge(`${Ib}${Np.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=il(e),o=await this.datastore.get(n,t);return bt(o)}async setMetadata(e,t,n){let o=il(e),s=await this.datastore.get(o,n),i=bt(s);i.metadata=t??{},await this.datastore.put(o,an(i),n)}};var Rp=1,Mp=5;var Ni=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},cn=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},Ri=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},Mi=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},Op=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}};var _I=5,cl=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??_I,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 nr(...this.routers)}async stop(){await or(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new cn("No content routers available");let n=new ns({concurrency:this.providerLookupConcurrency});for await(let o of It(n.toGenerator(),...Xn(this.routers,"findProviders").map(s=>s.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let s=await this.findPeer(o.id,t);return s.multiaddrs.length===0?null:{...s,protocols:o.protocols,routing:o.routing}}catch(s){return this.log.error("could not load multiaddrs for peer %p - %e",o.id,s),null}},{peerId:o.id,signal:t.signal}).catch(s=>{this.log.error("could not load multiaddrs for peer %p - %e",o.id,s)});continue}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new cn("No content routers available");await Promise.all(Xn(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Xn(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Xn(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(Xn(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new cn("No peer routers available");let n=this,o=It(...Xn(this.routers,"findPeer").map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}})()));for await(let s of o)if(s!=null)return s;throw new ke("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new cn("No peer routers available");for await(let n of It(...Xn(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Xn(r,e){return r.filter(t=>t[e]!=null)}var ll=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ul=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Cb(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new ul(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new ul(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var fl=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 xt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function CI(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var dl=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=CI(),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 xt),this.cleanup())}async join(e={}){let t=new fl(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 Cb(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 Up(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 Oi=class extends _e{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=Up(this.emitEmpty.bind(this),1),this.emitIdle=Up(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 ll;let n=new dl(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 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:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new xt)}),this.clear()}async onEmpty(e){this.size!==0&&await jc(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await jc(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await jc(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=Ko({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new xt("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var hl="lock:worker:request-read",pl="lock:worker:abort-read-request",ml="lock:worker:release-read",gl="lock:master:grant-read",yl="lock:master:error-read",wl="lock:worker:request-write",bl="lock:worker:abort-write-request",xl="lock:worker:release-write",vl="lock:master:grant-write",El="lock:master:error-write",Al="lock:worker:finalize",Sl="mortice",Tb={singleProcess:!1};var Fp=(r,e,t,n,o,s,i,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(u=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===f.identifier&&(e.removeEventListener("message",d),u())};e.addEventListener("message",d)})},onError:u=>{e.postMessage({type:i,name:f.name,identifier:f.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),f.type===s&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===Al&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var Bb=(r=10)=>Math.random().toString().substring(2,r+2);var Il=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Sl)}readLock(e){return this.sendRequest(hl,pl,gl,yl,ml,e)}writeLock(e){return this.sendRequest(wl,bl,vl,El,xl,e)}finalize(){this.channel.postMessage({type:Al,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Bb();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})};i?.signal?.addEventListener("abort",f,{once:!0});let u=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",u)})}};var Lb=r=>{if(r=Object.assign({},Tb,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Sl),n=new _e;return t.addEventListener("message",Fp(n,t,"requestReadLock","abortReadLockRequest",hl,pl,yl,ml,gl)),t.addEventListener("message",Fp(n,t,"requestWriteLock","abortWriteLockRequest",wl,bl,El,xl,vl)),n}return new Il(r.name)};var Jn=new Map,Ui;function Pb(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function TI(r){if(Ui==null&&(Ui=Lb(r),!Pb(Ui))){let e=Ui;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Jn.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.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,s=Jn.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.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=Jn.get(n);o?.finalize()})}return Ui}async function $p(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new xt)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var Db=(r,e)=>{let t=Jn.get(r);if(t!=null)return t;let n=TI(e);if(Pb(n))return t=n,Jn.set(r,t),t;let o=new Oi({concurrency:1}),s;return t={async readLock(i){if(s!=null)return $p(s,i);s=new Oi({concurrency:e.concurrency,autoStart:!1});let a=s,c=$p(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,$p(o,i)},finalize:()=>{Jn.delete(r)},queue:o},Jn.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var BI={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Fi(r){let e=Object.assign({},BI,r);return Db(e.name,e)}var kl=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Fi({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await nr(this.child),this.started=!0}async stop(){await or(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 Di("Block was pinned - please unpin and try again");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 s of e){if(await o.pins.isPinned(s))throw new Di("Block was pinned - please unpin and try again");yield s}})(),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 Vp=new ge("/version"),Nb=1;async function Rb(r){if(!await r.has(Vp)){await r.put(Vp,B(`${Nb}`));return}let e=await r.get(Vp),t=U(e);if(parseInt(t,10)!==Nb)throw new ol("Invalid datastore version, a datastore migration may be required")}var qp={};Ae(qp,{code:()=>Hp,decode:()=>$I,decodeOptions:()=>OI,encode:()=>FI,encodeOptions:()=>RI,name:()=>UI,toByteView:()=>Ob});var Mb=42;function Ob(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function LI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=H.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new I(m.tag,Mb),new I(m.bytes,t)]}function PI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function DI(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 NI(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 Kp={float64:!0,typeEncoders:{Map:NI,Object:LI,undefined:PI,number:DI}},RI={...Kp,typeEncoders:{...Kp.typeEncoders}};function MI(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return H.decode(r.subarray(1))}var _l={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};_l.tags[Mb]=MI;var OI={..._l,tags:_l.tags.slice()},UI="dag-cbor",Hp=113,FI=r=>an(r,Kp),$I=r=>bt(Ob(r),_l);var Xp={};Ae(Xp,{code:()=>Zp,decode:()=>Fb,encode:()=>Ub,format:()=>XI,name:()=>ZI,parse:()=>QI,stringify:()=>XI});var zp=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===m.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===m.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[m.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[m.negint.major](e,t){this[m.uint.major](e,t)}[m.bytes.major](e,t){throw new Error(`${_r} unsupported type: Uint8Array`)}[m.string.major](e,t){this.prefix(e);let n=Ec(JSON.stringify(t.value));e.push(n.length>32?wi(n):n)}[m.array.major](e,t){this.prefix(e),this.inRecursive.push({type:m.array,elements:0}),e.push([91])}[m.map.major](e,t){this.prefix(e),this.inRecursive.push({type:m.map,elements:0}),e.push([123])}[m.tag.major](e,t){}[m.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===m.array)e.push([93]);else if(i.type===m.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(`${_r} 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=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};function VI(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${_r} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==m.string||n.type!==m.string)throw new Error(`${_r} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${_r} unexpected duplicate map keys, this is not supported`)}var KI={addBreakTokens:!0,mapSorter:VI};function Gp(r,e){return e=Object.assign({},KI,e),Dc(r,new zp,e)}var is=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(`${F} 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(`${F} 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 I(m.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(`${F} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${F} 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 s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new I(m.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new I(i>=0?m.uint:m.negint,i,this._pos-e):new I(i>=0?m.uint:m.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${F} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new I(m.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${F} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){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(`${F} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${F} unexpected unicode sequence at position ${this._pos}`);let c,l,f,u;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(s&31)<<6|c&63,u>127&&(i=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(s&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(i=u));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&&(u=(s&15)<<18|(c&63)<<12|(l&63)<<6|f&63,u>65535&&u<1114112&&(i=u))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${F} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);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(`${F} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new I(m.string,np(t),this._pos-e);default:if(s<32)throw new Error(`${F} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${F} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new I(m.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new I(m.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new I(m.null,null,4);case 102:return this.expect([102,97,108,115,101]),new I(m.false,!1,5);case 116:return this.expect([116,114,117,101]),new I(m.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(`${F} 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 I(m.break,void 0,1);if(this.ch()!==44)throw new Error(`${F} 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 I(m.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 I(m.break,void 0,1);if(this.ch()!==44)throw new Error(`${F} 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 I(m.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${F} 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(`${F} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Wp(r,e){return e=Object.assign({tokenizer:new is(r,e)},e),bt(r,e)}function qI(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function zI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=H.asCID(r);if(!e)return null;let t=e.toString();return[new I(m.map,1/0,1),new I(m.string,"/",1),new I(m.string,t,t.length),new I(m.break,void 0,1)]}function Cl(r){let e=je.encode(r).slice(1);return[new I(m.map,1/0,1),new I(m.string,"/",1),new I(m.map,1/0,1),new I(m.string,"bytes",5),new I(m.string,e,e.length),new I(m.break,void 0,1),new I(m.break,void 0,1)]}function Wt(r){return Cl(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function GI(r){return Cl(new Uint8Array(r))}function WI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function jI(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 YI={typeEncoders:{Object:zI,Buffer:Cl,Uint8Array:Cl,Int8Array:Wt,Uint16Array:Wt,Int16Array:Wt,Uint32Array:Wt,Int32Array:Wt,Float32Array:Wt,Float64Array:Wt,Uint8ClampedArray:Wt,BigInt64Array:Wt,BigUint64Array:Wt,DataView:Wt,ArrayBuffer:GI,undefined:WI,number:jI}},jp=class extends is{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===m.map){let t=this._next();if(t.type===m.string&&t.value==="/"){let n=this._next();if(n.type===m.string){if(this._next().type!==m.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new I(m.tag,42,0)}if(n.type===m.map){let o=this._next();if(o.type===m.string&&o.value==="bytes"){let s=this._next();if(s.type===m.string){for(let a=0;a<2;a++)if(this._next().type!==m.break)throw new Error("Invalid encoded Bytes form");let i=je.decode(`m${s.value}`);return new I(m.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Yp={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Yp.tags[42]=H.parse;var ZI="dag-json",Zp=297,Ub=r=>Gp(r,YI),Fb=r=>{let e=qI(r),t=Object.assign(Yp,{tokenizer:new jp(e,Yp)});return Wp(e,t)},XI=r=>JI.decode(Ub(r));var JI=new TextDecoder,QI=r=>Fb(ek.encode(r)),ek=new TextEncoder;var nm={};Ae(nm,{code:()=>rm,createLink:()=>Yb,createNode:()=>jb,decode:()=>hk,encode:()=>dk,name:()=>fk,prepare:()=>em,validate:()=>tm});var tk=new TextDecoder;function Jp(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 Tl(r,e){let t;[t,e]=Jp(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 $b(r,e){let t;return[t,e]=Jp(r,e),[t&7,t>>3,e]}function rk(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=$b(r,n),s===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]=Tl(r,n)}else if(s===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 i;[i,n]=Tl(r,n),e.Name=tk.decode(i)}else if(s===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]=Jp(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Vb(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=$b(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Tl(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]=Tl(r,t),n.push(rk(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 i={};return s&&(i.Data=s),i.Links=n||[],i}var Hb=new TextEncoder,Kb=2**32,nk=2**31;function ok(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=$i(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Hb.encode(r.Name);t-=n.length,e.set(n,t),t=$i(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=$i(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function qb(r){let e=ik(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=$i(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let s=ok(r.Links[o],t.subarray(0,n));n-=s,n=$i(t,n,s)-1,t[n]=18}return t}function sk(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+as(t)}if(typeof r.Name=="string"){let t=Hb.encode(r.Name).length;e+=1+t+as(t)}return typeof r.Tsize=="number"&&(e+=1+as(r.Tsize)),e}function ik(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+as(t)}if(r.Links)for(let t of r.Links){let n=sk(t);e+=1+n+as(n)}return e}function $i(r,e,t){e-=as(t);let n=e;for(;t>=nk;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function as(r){return r%2===0&&r++,Math.floor((ak(r)+6)/7)}function ak(r){let e=0;return r>=Kb&&(r=Math.floor(r/Kb),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+ck[r]}var ck=[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 lk=["Data","Links"],uk=["Hash","Name","Tsize"],Qp=new TextEncoder;function Gb(r,e){if(r===e)return 0;let t=r.Name?Qp.encode(r.Name):[],n=e.Name?Qp.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function zb(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Wb(r){if(typeof r.asCID=="object"){let t=H.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=H.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=H.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=H.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 em(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=Qp.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(Wb),e.Links.sort(Gb);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function tm(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!zb(r,lk))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(!zb(t,uk))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&&Gb(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function jb(r,e=[]){return em({Data:r,Links:e})}function Yb(r,e,t){return Wb({Hash:t,Name:r,Tsize:e})}function Zb(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var fk="dag-pb",rm=112;function dk(r){tm(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),qb(e)}function hk(r){let e=Zb(r),t=Vb(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=H.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function cs(r){return r?.then!=null}function Xb(r=[],e){let t={[rm]:nm,[Ps]:Ds,[Hp]:qp,[Zp]:Xp,[ud]:Pa};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);cs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Mi(`Could not load codec for ${n}`)}}function Jb(r=[],e){let t={[Rt.code]:Rt,[Da.code]:Da,[Ge.code]:Ge};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);cs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Ri(`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 Lt=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Br=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 Bl=0,ls=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},Ll=class extends Br{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===Bl){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new ls(`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)}*get(e,t){if(e.multihash.code===Bl){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new ls(`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 Lt;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===Bl){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new ls(`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===Bl){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new ls(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function pk(r){return r[Symbol.asyncIterator]!=null}function mk(r,e){let t=0;if(pk(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=os(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var jt=mk;function gk(r){return r[Symbol.asyncIterator]!=null}function Qb(r){return r?.then!=null}function yk(r,e){let t=0;if(gk(r))return(async function*(){for await(let c of r){let l=e(c,t++);Qb(l)&&await l,yield c}})();let n=os(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();if(typeof e(o,t++)?.then=="function")return(async function*(){yield o;for(let c of n){let l=e(c,t++);Qb(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var om=yk;var wk=128,Pl=class{child;getHasher;log;logger;components;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Ll(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??wk}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new W("blocks:put:duplicate",e)),e):(n.onProgress?.(new W("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new W("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=jt(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new W("blocks:put-many:duplicate",s)),!i}),o=om(n,async({cid:s})=>{t.onProgress?.(new W("blocks:put-many:providers:notify",s)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(s,t)))});t.onProgress?.(new W("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new W("blocks:get:providers:get",e));let o=await ex(e,this.components.blockBrokers,n,{...t,log:this.log});t.onProgress?.(new W("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new W("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(e,t))),yield o;return}t.onProgress?.(new W("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new W("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(om(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new W("blocks:get-many:providers:get",n));let s=await ex(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new W("blocks:get-many:blockstore:put",n)),await this.child.put(n,s,t),t.onProgress?.(new W("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new W("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new W("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 W("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},Dl=class extends Pl{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await nr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await or(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new sm({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},sm=class extends Pl{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=pe([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=pe([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function bk(r){return typeof r.retrieve=="function"}var xk=(r,e)=>{if(e==null)throw new k(`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(cs(o)?n=await o:n=o,!X(n.digest,r.multihash.digest))throw new Vr("Hash of downloaded block did not match multihash from passed CID")}};async function ex(r,e,t,n){let o=xk(r,t),s=new AbortController,i=pe([s.signal,n.signal]);s.signal;let a=[];for(let c of e)bk(c)&&a.push(c);if(a.length===0)throw new sl(`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:i,validateFn:async u=>{await o(u),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 - %e",r,l),l}}))}finally{s.abort(),i.clear()}}var Ki=class extends _e{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Un(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=je.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let s=ae();if(this.requests.set(n,s.promise),this.providers.length===0){let f=!1;this.initialPeerSearchComplete==null&&(f=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));try{await St(this.initialPeerSearchComplete,t.signal),f&&this.log("found initial session peers for %c",e)}catch(u){throw f&&this.log("failed to find initial session peers for %c - %e",e,u),this.requests.delete(n),s.reject(u),u}}let i=!1,a=new qt({concurrency:this.maxProviders});a.addEventListener("failure",f=>{this.log.error("error querying provider %o, evicting from session",f.detail.job.options.provider,f.detail.error),this.evict(f.detail.job.options.provider)}),a.addEventListener("success",f=>{i=!0,s.resolve(f.detail.result)}),a.addEventListener("idle",()=>{if(i){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 f=0;f<this.minProviders&&this.providers.length!==0;f++){let u=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(u)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(f=>{this.log.error("could not find new providers for %c - %e",e,f),s.reject(f)})});let c=f=>{a.add(async()=>this.queryProvider(e,f.detail,t),{provider:f.detail}).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,u)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async f=>a.add(async()=>this.queryProvider(e,f,t),{provider:f}))).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,f)});let l=()=>{s.reject(new ft(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",l);try{return await St(s.promise,t.signal)}finally{this.removeEventListener("provider",c),t.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=ae(),s=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e),this.initialProviders.length>0)for(;s<t&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(s<this.maxProviders)for await(let i of this.findNewProviders(e,n)){if(s===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(this.log("found %d/%d new session peers",s,this.maxProviders),s<t)throw new Ni(`Found ${s} of ${t} ${this.name} providers for ${e}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};var Nl=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??dr(),this.log=this.logger.forComponent("helia"),this.getHasher=Jb(e.hashers,e.loadHasher),this.getCodec=Xb(e.codecs,e.loadCodec),this.dns=e.dns??el(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new _e;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 cl(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let s=[o],i=vk(o);i!=null&&s.push(i);let a=Ek(o);return a!=null&&s.push(a),s}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Dl(t,e);this.pins=new al(e.datastore,n,this.getCodec),this.blockstore=new kl(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await Rb(this.datastore),await nr(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await or(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 Ii(o.deleteMany((async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new W("helia:gc:deleted",s))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new W("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};function vk(r){return r?.[mn]}function Ek(r){return r?.[yn]}var Ak=[6,53,56,54,55];function tx(r){return ox("sni",r)?.value}function rx(r){let e=ox("tcp",r)?.value;return e==null?"":`:${e}`}function ox(r,e){return e.find(t=>t.name===r)}function nx(r){return r.some(({code:e})=>e===448)}function Yt(r,e){let t=sx[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var sx={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Yt(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Yt(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Yt(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Yt(t,e)}`},http:(r,e)=>{let t=nx(e),n=tx(e),o=rx(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Yt(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Yt(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Yt(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Yt(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Yt(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=nx(e),n=tx(e),o=rx(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Yt(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Yt(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function Rl(r,e){let n=ee(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=sx[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&Ak.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var fe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),q=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),ix=r=>({match:e=>r.match(e)===!1?e:!1}),te=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Qe=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),ce=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function de(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Sk=q(421),ax=de(Sk),Ol=q(54),Ul=q(55),Fl=q(56),am=q(53),_O=de(Ol,te(q(421))),CO=de(Ul,te(q(421))),TO=de(Fl,te(q(421))),cx=de(Qe(am,Fl,Ol,Ul),te(q(421))),lx=ce(q(4),te(q(43))),ux=ce(te(q(42)),q(41),te(q(43))),cm=Qe(lx,ux),Qn=Qe(cm,am,Ol,Ul,Fl),BO=de(Qe(cm,ce(Qe(am,Fl,Ol,Ul),te(q(421))))),lm=de(lx),um=de(ux),LO=de(cm),fm=ce(Qn,q(6)),Hi=ce(Qn,q(273)),qi=de(ce(fm,te(q(421)))),PO=de(Hi),dm=ce(Hi,fe(460),te(q(421))),$l=ce(Hi,fe(461),te(q(421))),Ik=Qe(dm,$l),DO=de(dm),fx=de($l),im=Qe(Qn,fm,Hi,dm,$l),dx=Qe(ce(im,fe(477),te(q(421)))),eo=de(dx),hx=Qe(ce(im,fe(478),te(q(421))),ce(im,fe(448),te(q(449)),fe(477),te(q(421)))),zi=de(hx),px=ce(Hi,fe(280),te(q(466)),te(q(466)),te(q(421))),hm=de(px),mx=ce($l,fe(465),te(q(466)),te(q(466)),te(q(421))),pm=de(mx),Ml=Qe(dx,hx,ce(fm,te(q(421))),ce(Ik,te(q(421))),ce(Qn,te(q(421))),px,mx,q(421)),NO=de(Ml),kk=ce(te(Ml),fe(290),ix(fe(281)),te(q(421))),to=de(kk),_k=Qe(ce(Ml,fe(290),fe(281),te(q(421))),ce(Ml,fe(281),te(q(421))),ce(fe(281),te(q(421)))),mm=de(_k),Ck=Qe(ce(Qn,q(6),fe(480),te(q(421))),ce(Qn,fe(480),te(q(421)))),gx=de(Ck),Tk=ce(Qn,Qe(ce(q(6,"443"),fe(480)),ce(q(6),fe(443)),ce(q(6),fe(448),fe(480)),ce(fe(448),fe(480)),fe(448),fe(443)),te(q(421))),yx=de(Tk),Bk=Qe(ce(q(777),te(q(421)))),RO=de(Bk),Lk=Qe(ce(q(400),te(q(421)))),MO=de(Lk);function gm(r,e,t){return r.filter(n=>{if(yx.matches(n)||e&&gx.matches(n))return t||cx.matches(n)?!0:Ht(n)===!1;if(!e&&t){let{host:o}=Q(n);if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*Vl(r,e,t,n,o,s={}){for await(let i of e.findProviders(r,s)){let a=gm(i.multiaddrs,n,o);if(a.length===0)continue;let c=Rl(a[0]),l={type:"trustless-gateway",cid:r,url:c.toString(),routing:i.routing};s?.onProgress?.(new W("trustless-gateway:found-provider",l)),yield new us(c,{logger:t,transformRequestInit:s.transformRequestInit})}}async function wx(r,e,t){let{signal:n,log:o}=t??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>e)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,e),r.body!=null&&await r.body.cancel().catch(l=>{o?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new se;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var us=class{url;#e=0;#t=0;#r=0;#i=0;#s=new Map;log;transformRequestInit;constructor(e,{logger:t,transformRequestInit:n}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#f(e){let t=e.multihash.bytes;return je.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=bx}={}){let o=new URL(this.url.toString());if(o.pathname=`/ipfs/${e.toString()}`,o.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let s=this.#f(e),i=new AbortController,a=()=>{i.abort()};t?.addEventListener("abort",a);try{let c=this.#s.get(s);if(c==null){this.#e++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},f=this.transformRequestInit!=null?await this.transformRequestInit(l):l;c=fetch(o.toString(),f).then(async u=>{if(this.log("GET %s %d",o,u.status),!u.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);let d=await wx(u,n,{signal:i.signal,log:this.log});return this.#i++,d}),this.#s.set(s,c)}return await c}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",a),this.#s.delete(s)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#i/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#i,pendingResponses:this.#s.size}}};var ym=class extends Ki{routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Kl,this.allowLocal=t.allowLocal??Hl,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*Vl(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t){if(rr(e))return;let n=gm(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(n.length===0)return;let o=Rl(n[0]);return new us(o,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function xx(r,e){return new ym(r,e)}var ql=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Kl,this.allowLocal=t.allowLocal??Hl,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of Vl(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return xx({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Kl=!1,Hl=!1,bx=2097152;function wm(r={}){return e=>new ql(e,r)}async function*zl(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var Ok=pn(xm(),1);var Zt=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},Gl=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},fs=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},Wl=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},jl=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},Yl=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Gi=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var Xt;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),(function(o){o.codec=()=>Xs(t)})(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=Fe((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.value!=null&&(s.uint32(10),s.bytes(o.value)),o.signatureV1!=null&&(s.uint32(18),s.bytes(o.signatureV1)),o.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(o.validityType,s)),o.validity!=null&&(s.uint32(34),s.bytes(o.validity)),o.sequence!=null&&(s.uint32(40),s.uint64(o.sequence)),o.ttl!=null&&(s.uint32(48),s.uint64(o.ttl)),o.pubKey!=null&&(s.uint32(58),s.bytes(o.pubKey)),o.signatureV2!=null&&(s.uint32(66),s.bytes(o.signatureV2)),o.data!=null&&(s.uint32(74),s.bytes(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Ue(o,r.codec()),r.decode=(o,s)=>Oe(o,r.codec(),s)})(Xt||(Xt={}));var Pk=Ct("ipns:utils"),vx=B("/ipns/");var Dk=0,Nk=18;function Ex(r){let e;if(r.pubKey!=null)try{e=en(r.pubKey)}catch(t){throw Pk.error(t),t}if(e!=null)return e}function Ax(r){let e=B("ipns-signature:");return Ce([e,r])}function Wi(r){return"signatureV1"in r?Xt.encode({value:B(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:B(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Xt.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function ln(r){let e=Xt.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new Zt("Missing data or signatureV2");let t=Sx(e.data),n=Rk(t.Value),o=U(t.Validity);if(e.value!=null&&e.signatureV1!=null)return Mk(e),{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function ji(r){return Ce([vx,r.bytes])}function ds(r){let e=dt(r.slice(vx.length));if(!Zl(e,Dk)&&!Zl(e,Nk))throw new Vr("Multihash in IPNS key was not identity or sha2-256");return e}function Sx(r){let e=bt(r);if(e.ValidityType===0)e.ValidityType=Xt.ValidityType.EOL;else throw new fs("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function Rk(r){let e=U(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${H.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${H.parse(e).toV1().toString()}`}catch{}throw new jl("Value must be a valid content path starting with /")}function Mk(r){if(r.data==null)throw new Yl("Record data is missing");let e=Sx(r.data);if(!X(e.Value,r.value??new Uint8Array(0)))throw new Zt('Field "value" did not match between protobuf and CBOR');if(!X(e.Validity,r.validity??new Uint8Array(0)))throw new Zt('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new Zt('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new Zt('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new Zt('Field "ttl" did not match between protobuf and CBOR')}function Zl(r,e){return r.code===e}var PU=Ct("ipns"),DU=300*1e9,Uk="/ipns/",NU=Uk.length;var Ix=pn(xm(),1);var Xl=Ct("ipns:validator"),Fk=1024*10;async function $k(r,e){let t=ln(e),n;try{let o=Ax(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw Xl.error("record signature verification failed"),new Zt("Record signature verification failed");if(t.validityType===Xt.ValidityType.EOL){if(Ix.default.fromString(t.validity).toDate().getTime()<Date.now())throw Xl.error("record has expired"),new Gl("record has expired")}else if(t.validityType!=null)throw Xl.error("the validity type is unsupported"),new fs("The validity type is unsupported");Xl("ipns record for %s is valid",t.value)}async function kx(r,e){if(e.byteLength>Fk)throw new Wl("The record is too large");let t=ds(r),n;Zl(t,0)&&(n=Ja(t));let o=ln(e),s=Ex(o)??n;if(s==null)throw new Gi("Could not extract public key from IPNS record or routing key");let i=ji(s.toMultihash());if(!X(i,r))throw new Gi("Embedded public key did not match routing key");await $k(s,e)}var Jl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Yi(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),wo(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new Jl("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var hs=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},Jt=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function Vk(r){return r[Symbol.asyncIterator]!=null}function Kk(r){if(Vk(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var _x=Kk;var Cx=B("/ipns/");function Tx(r){return X(r.subarray(0,Cx.byteLength),Cx)}var Ql=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){try{yield*Gc(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof ke)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!Tx(e))return;let o=ds(e),s=H.createV1(114,o),i=ln(t);await this.client.putIPNS(s,i,n)}async get(e,t){if(!Tx(e))throw new ke("Not found");let n=ds(e),o=H.createV1(114,n);try{let s=await this.client.getIPNS(o,t);return Wi(s)}catch(s){throw s.name==="BadResponseError"?new ke("Not found"):s}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},eu=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await _x(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new ke("Not found")}async*getClosestPeers(e,t={}){}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};var tu={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},ru=class{url;started;httpQueue;shutDownController;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new Zn({concurrency:t.concurrentRequests??tu.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??tu.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new Ql(this),this.peerRouting=new eu(this),this.cacheName=t.cacheName??tu.cacheName,this.cacheTTL=t.cacheTTL??tu.cacheTTL}get[mn](){return this.contentRouting}get[yn](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=pe([this.shutDownController.signal,n,t.signal]);let s=ae(),i=ae();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(!l.ok){if(l.status===404)return;throw l.status===422?new hs("Request does not conform to schema or semantic constraints"):new Jt(`Unexpected status code: ${l.status}`)}if(l.body==null)throw new Jt("Routing response had no body");let f=l.headers.get("Content-Type");if(f==null)throw new Jt("No Content-Type header received");if(f.startsWith("application/json")){let d=(await l.json()).Providers??[];for(let h of d){let p=this.#e(h);p!=null&&(yield p)}}else if(f.includes("application/x-ndjson"))for await(let u of Yi(zl(l.body))){let d=this.#e(u);d!=null&&(yield d)}else throw new Jt(`Unsupported Content-Type: ${f}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished: %c",e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=pe([this.shutDownController.signal,n,t.signal]);let s=ae(),i=ae();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)return;if(l.status===422)throw new hs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Jt("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let d=(await l.json()).Peers??[];for(let h of d){let p=this.#e(h);p!=null&&(yield p)}}else for await(let u of Yi(zl(l.body))){let d=this.#e(u);d!=null&&(yield d)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async getIPNS(e,t={}){this.log("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=pe([this.shutDownController.signal,n,t.signal]);let s=ae(),i=ae();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o},l=await this.#r(a,c);if(this.log("getIPNS GET %s %d",a,l.status),l.status===404)throw new ke("No matching records found");if(l.status===422)throw new hs("Request does not conform to schema or semantic constraints");if(!l.ok)throw new Jt(`Unexpected status code: ${l.status}`);let f=l.headers.get("Content-Type");if(f==null||!f.includes("application/vnd.ipfs.ipns-record"))throw new ke("No matching records found");if(l.body==null)throw new Jt("GET ipns response had no body");let u=await l.arrayBuffer(),d=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await kx(ji(e.multihash),d),ln(d)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=pe([this.shutDownController.signal,o,n.signal]);let i=ae(),a=ae();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await i.promise;let l=Wi(t),f={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:s},u=await this.#r(c,f);if(this.log("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new Jt("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(ee)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Tt(e.ID),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),c;await this.cache?.delete(e)}}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),c.clone()}let i=fetch(e,t).then(async c=>{if(this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,f=new Headers(c.headers);f.set("x-cache-expires",l.toString());let u=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:f});await this.cache.put(e,u)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}};function Bx(r,e={}){return new ru({logger:dr()},{...e,url:new URL(r)})}var Lx="[a-fA-F\\d:]",un=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Lx})|(?<=${Lx})(?=\\s|$))`:"",Qt="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Ie="[a-fA-F\\d]{1,4}",nu=`
13
+ ${e}[Error list was empty]`,t.trim()}return ab(r,e)}ct.formatters.e=r=>r==null?"undefined":lb(r);function rI(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function dr(r){return{forComponent(e){return Ct(e,r)}}}function Ct(r,e){let t=rI(`${r}:trace`);return ct.enabled(`${r}:trace`)&&ct.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=ct(`${r}:trace`,e)),Object.assign(ct(r,e),{error:ct(`${r}:error`,e),trace:t,newScope:n=>Ct(`${r}:${n}`,e)})}function cb(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var ns=class extends qt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var qc=class extends qt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var zc=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new gp}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ic("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},gp=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var yp=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Xe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new yp({name:e,metrics:t}):n=new Map,n}function nI(r){return r[Symbol.asyncIterator]!=null}function oI(r){if(nI(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ii=oI;function sI(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 os=sI;function iI(r){return r[Symbol.asyncIterator]!=null}function aI(r,e){let t=0;if(iI(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=os(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Gc=aI;function cI(r){return r[Symbol.asyncIterator]!=null}function lI(r,e){return cI(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Wc=lI;var xt=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function jc(r,e,t,n){let o=new xt(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){bp(t,"abort",u),bp(r,e,l),bp(r,s,f)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},f=d=>{if(c(),d instanceof Error){a(d);return}a(d.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.`))},u=()=>{c(),a(o)};wp(t,"abort",u),wp(r,e,l),wp(r,s,f)})}function wp(r,e,t){r!=null&&(ub(r)?r.addEventListener(e,t):r.addListener(e,t))}function bp(r,e,t){r!=null&&(ub(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function ub(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var fb=Symbol.for("nodejs.util.inspect.custom"),uI=114,ki=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ca]=!0;toString(){return this.string==null&&(this.string=le.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return H.createV1(uI,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return X(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return X(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[fb](){return`PeerId(${this.toString()})`}},_i=class extends ki{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ci=class extends ki{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ti=class extends ki{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},fI=2336,Bi=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ge.digest(B(this.url))}[fb](){return`PeerId(${this.url})`}[Ca]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return H.createV1(fI,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=U(e)),e.toString()===this.toString())}};var dI=114,db=2336;function Tt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=dt(le.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Wn(H.parse(r));if(e==null)throw new k('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=dt(e.decode(r))}return ss(t)}function xp(r){if(r.type==="Ed25519")return new Ci({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Ti({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new _i({multihash:r.toCID().multihash,publicKey:r});throw new Dt}function hb(r){return xp(r.publicKey)}function ss(r){if(pI(r))return new _i({multihash:r});if(hI(r))try{let e=Ja(r);if(e.type==="Ed25519")return new Ci({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Ti({multihash:r,publicKey:e})}catch{let t=U(r.digest);return new Bi(new URL(t))}throw new Vr("Supplied PeerID Multihash is invalid")}function Wn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==dI&&r.code!==db)throw new va("Supplied PeerID CID is invalid");if(r.code===db){let e=U(r.multihash.digest);return new Bi(new URL(e))}return ss(r.multihash)}function hI(r){return r.code===Ge.code}function pI(r){return r.code===Rt.code}function jn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Yc(r){let e=dt(le.decode(`z${r}`));return ss(e)}var Bt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return jn(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return jn(this.map.values(),e=>e.key)}values(){return jn(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Yn=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return jn(this.set.entries(),e=>{let t=Yc(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Yc(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return jn(this.set.values(),e=>Yc(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var vp=class extends Bt{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ep(r){let{name:e,metrics:t}=r,n;return t!=null?n=new vp({name:e,metrics:t}):n=new Bt,n}function mI(r){return r[Symbol.asyncIterator]!=null}function gI(r){if(mI(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Ce([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ce(e,t)}var pb=gI;var Sp=pn(gb(),1);var Ip=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},yb=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function kp(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,f=new Promise((u,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(yb(i));return}if(i&&(c=()=>{d(yb(i))},i.addEventListener("abort",c,{once:!0})),r.then(u,d),t===Number.POSITIVE_INFINITY)return;let h=new Ip;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}function _p(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Pi=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},s={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(s);return}let i=_p(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(i,0,s)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Zn=class extends Sp.default{#e;#t;#r=0;#i;#s=!1;#f=!1;#d;#b=0;#g=0;#a;#c;#n;#x;#o=0;#h;#l;#k=1n;#p=new Map;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Pi,...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(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#i=e.intervalCap,this.#d=e.interval,this.#n=new e.queueClass,this.#x=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.#D()}get#_(){return this.#t||this.#r<this.#i}get#C(){return this.#o<this.#h}#T(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#y(),this.emit("next")}#B(){this.#S(),this.#A(),this.#c=void 0}get#L(){let e=Date.now();if(this.#a===void 0){let t=this.#b-e;if(t<0){if(this.#g>0){let n=e-this.#g;if(n<this.#d)return this.#v(this.#d-n),!0}this.#r=this.#e?this.#o:0}else return this.#v(t),!0}return!1}#v(e){this.#c===void 0&&(this.#c=setTimeout(()=>{this.#B()},e))}#E(){this.#a&&(clearInterval(this.#a),this.#a=void 0)}#P(){this.#c&&(clearTimeout(this.#c),this.#c=void 0)}#y(){if(this.#n.size===0)return this.#E(),this.emit("empty"),this.#o===0&&(this.#P(),this.emit("idle")),!1;let e=!1;if(!this.#l){let t=!this.#L;if(this.#_&&this.#C){let n=this.#n.dequeue();this.#t||(this.#r++,this.#m()),this.emit("active"),this.#g=Date.now(),n(),t&&this.#A(),e=!0}}return e}#A(){this.#t||this.#a!==void 0||(this.#a=setInterval(()=>{this.#S()},this.#d),this.#b=Date.now()+this.#d)}#S(){this.#r===0&&this.#o===0&&this.#a&&this.#E(),this.#r=this.#e?this.#o:0,this.#w(),this.#m()}#w(){for(;this.#y(););}get concurrency(){return this.#h}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.#h=e,this.#w()}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.#n.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#k++).toString(),t={timeout:this.timeout,...t},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`);this.#n.enqueue(async()=>{this.#o++,this.#p.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let i;try{try{t.signal?.throwIfAborted()}catch(l){throw this.#t||this.#r--,this.#p.delete(s),l}let a=e({signal:t.signal});if(t.timeout&&(a=kp(Promise.resolve(a),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#n.size} waiting)`})),t.signal){let{signal:l}=t;a=Promise.race([a,new Promise((f,u)=>{i=()=>{u(l.reason)},l.addEventListener("abort",i,{once:!0})})])}let c=await a;n(c),this.emit("completed",c)}catch(a){o(a),this.emit("error",a)}finally{i&&t.signal?.removeEventListener("abort",i),this.#p.delete(s),queueMicrotask(()=>{this.#T()})}},t),this.emit("add"),this.#y()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#l?(this.#l=!1,this.#w(),this):this}pause(){this.#l=!0}clear(){this.#n=new this.#x,this.#I()}async onEmpty(){this.#n.size!==0&&await this.#u("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#u("next",()=>this.#n.size<e)}async onIdle(){this.#o===0&&this.#n.size===0||await this.#u("idle")}async onPendingZero(){this.#o!==0&&await this.#u("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#u("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#u("rateLimitCleared")}async onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#u(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#l}#D(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#m()}),this.on("next",()=>{this.#m()}))}#m(){this.#t||this.#f||(this.#f=!0,queueMicrotask(()=>{this.#f=!1,this.#I()}))}#I(){let e=this.#s,t=!this.#t&&this.#r>=this.#i&&this.#n.size>0;t!==e&&(this.#s=t,this.emit(t?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#s}get isSaturated(){return this.#o===this.#h&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#p.values()].map(e=>({...e}))}};function Xc(r){let e=[vt.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Cp=60;function Jc(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:vt[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:vt[e.type],TTL:e.TTL??e.ttl??Cp,data:e.data instanceof Uint8Array?U(e.data):e.data}))}}var bI=4;function Tp(r,e={}){let t=new Zn({concurrency:e.queryConcurrency??bI});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Xc(o.types).forEach(a=>{s.append("type",vt[a])}),o.onProgress?.(new W("dns:query",n));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Jc(await a.json());return o.onProgress?.(new W("dns:response",c)),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function wb(){return[Tp("https://cloudflare-dns.com/dns-query"),Tp("https://dns.google/resolve")]}var vb=pn(xb(),1);var Bp=class{lru;constructor(e){this.lru=(0,vb.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return Jc({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:vt[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Cp)*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 Eb(r){return new Bp(r)}var xI=1e3,Qc=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Eb(e.cacheSize??xI),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["."]=wb())}async query(e,t={}){let n=Xc(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new W("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new W("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var vt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(vt||(vt={}));function el(r={}){return new Qc(r)}var Tr="/",Ab=new TextEncoder().encode(Tr),tl=Ab[0],ge=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=B(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==tl)throw new Error("Invalid key")}toString(e="utf8"){return U(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Tr))}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=Ab),this._buf[0]!==tl){let e=new Uint8Array(this._buf.byteLength+1);e.fill(tl,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===tl;)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 s=t[o],i=n[o];if(s<i)return!0;if(s>i)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(Tr).slice(1)}type(){return vI(this.baseNamespace())}name(){return EI(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Tr)||(e+=Tr),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Tr):new r(e.slice(0,-1).join(Tr))}child(e){return this.toString()===Tr?e:e.toString()===Tr?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(),...AI(e.map(t=>t.namespaces()))])}};function vI(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function EI(r){let e=r.split(":");return e[e.length-1]}function AI(r){return[].concat(...r)}function rl({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*SI(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],s=H.asCID(n);s!=null?yield[o.join("/"),s]:typeof n=="object"&&(yield*Lp(n,o))}else{let t=H.asCID(e);t!=null?yield[r.join("/"),t]:yield*Lp(e,r)}}function*Lp(r,e){if(r==null||r instanceof Uint8Array)return;let t=H.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let s=[...e,n];yield*SI(s,o)}}function*II(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&H.asCID(n)==null&&(yield*Pp(n,o))}else yield*Pp(e,r)}function*Pp(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"&&H.asCID(n)==null&&(yield*II(o,n))}}function kI(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(i=>`[${JSON.stringify(i)}]`).join("")}`);let s=H.asCID(t);if(s!=null)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:t}}var Dp=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:rl(),bytes:rl(),value:rl(),asBlock:rl()})}links(){return Lp(this.value,[])}tree(){return Pp(this.value,[])}get(e="/"){return kI(this.value,e.split("/").filter(Boolean))}};function Sb({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 Dp({cid:e,bytes:r,value:o})}var nl=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},Di=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},ol=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},sl=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"};var _b="/pin/",Ib="/pinned-block/",Np=sr,kb=1;function il(r){return r.version===0&&(r=r.toV1()),new ge(`${_b}${r.toString(Np)}`)}var al=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=il(e);if(await this.datastore.has(n))throw new nl("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new k("Depth must be greater than or equal to 0");let s=new qt({concurrency:kb});for await(let a of this.#e(e,s,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>X(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,an(i),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),s=await pb(this.blockstore.get(e,n)),i=Sb({bytes:s,cid:e,codec:o});yield e;for(let[,a]of i.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new ge(`${Ib}${Np.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=bt(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,an(s),n),n.onProgress?.(new W("helia:pin:add",e))}}async*rm(e,t={}){let n=il(e),o=await this.datastore.get(n,t),s=bt(o);await this.datastore.delete(n,t);let i=new qt({concurrency:kb});for await(let a of this.#e(e,i,{...t,depth:s.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>X(l,e.bytes)),!0),{...t,depth:s.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:_b+(e.cid!=null?`${e.cid.toString(sr)}`:"")},e)){let o=H.parse(t.toString().substring(5),sr),s=bt(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new ge(`${Ib}${Np.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=il(e),o=await this.datastore.get(n,t);return bt(o)}async setMetadata(e,t,n){let o=il(e),s=await this.datastore.get(o,n),i=bt(s);i.metadata=t??{},await this.datastore.put(o,an(i),n)}};var Rp=1,Mp=5;var Ni=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},cn=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},Ri=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},Mi=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},Op=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}};var _I=5,cl=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??_I,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 nr(...this.routers)}async stop(){await or(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new cn("No content routers available");let n=new ns({concurrency:this.providerLookupConcurrency});for await(let o of It(n.toGenerator(),...Xn(this.routers,"findProviders").map(s=>s.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let s=await this.findPeer(o.id,t);return s.multiaddrs.length===0?null:{...s,protocols:o.protocols,routing:o.routing}}catch(s){return this.log.error("could not load multiaddrs for peer %p - %e",o.id,s),null}},{peerId:o.id,signal:t.signal}).catch(s=>{this.log.error("could not load multiaddrs for peer %p - %e",o.id,s)});continue}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new cn("No content routers available");await Promise.all(Xn(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Xn(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Xn(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(Xn(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new cn("No peer routers available");let n=this,o=It(...Xn(this.routers,"findPeer").map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}})()));for await(let s of o)if(s!=null)return s;throw new ke("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new cn("No peer routers available");for await(let n of It(...Xn(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Xn(r,e){return r.filter(t=>t[e]!=null)}var ll=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ul=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Cb(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new ul(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new ul(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var fl=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 xt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function CI(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var dl=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=CI(),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 xt),this.cleanup())}async join(e={}){let t=new fl(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 Cb(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 Up(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 Oi=class extends _e{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=Up(this.emitEmpty.bind(this),1),this.emitIdle=Up(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 ll;let n=new dl(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 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:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new xt)}),this.clear()}async onEmpty(e){this.size!==0&&await jc(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await jc(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await jc(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=Ko({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new xt("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var hl="lock:worker:request-read",pl="lock:worker:abort-read-request",ml="lock:worker:release-read",gl="lock:master:grant-read",yl="lock:master:error-read",wl="lock:worker:request-write",bl="lock:worker:abort-write-request",xl="lock:worker:release-write",vl="lock:master:grant-write",El="lock:master:error-write",Al="lock:worker:finalize",Sl="mortice",Tb={singleProcess:!1};var Fp=(r,e,t,n,o,s,i,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(u=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===f.identifier&&(e.removeEventListener("message",d),u())};e.addEventListener("message",d)})},onError:u=>{e.postMessage({type:i,name:f.name,identifier:f.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),f.type===s&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===Al&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var Bb=(r=10)=>Math.random().toString().substring(2,r+2);var Il=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Sl)}readLock(e){return this.sendRequest(hl,pl,gl,yl,ml,e)}writeLock(e){return this.sendRequest(wl,bl,vl,El,xl,e)}finalize(){this.channel.postMessage({type:Al,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Bb();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})};i?.signal?.addEventListener("abort",f,{once:!0});let u=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",u)})}};var Lb=r=>{if(r=Object.assign({},Tb,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Sl),n=new _e;return t.addEventListener("message",Fp(n,t,"requestReadLock","abortReadLockRequest",hl,pl,yl,ml,gl)),t.addEventListener("message",Fp(n,t,"requestWriteLock","abortWriteLockRequest",wl,bl,El,xl,vl)),n}return new Il(r.name)};var Jn=new Map,Ui;function Pb(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function TI(r){if(Ui==null&&(Ui=Lb(r),!Pb(Ui))){let e=Ui;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Jn.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.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,s=Jn.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.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=Jn.get(n);o?.finalize()})}return Ui}async function $p(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new xt)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var Db=(r,e)=>{let t=Jn.get(r);if(t!=null)return t;let n=TI(e);if(Pb(n))return t=n,Jn.set(r,t),t;let o=new Oi({concurrency:1}),s;return t={async readLock(i){if(s!=null)return $p(s,i);s=new Oi({concurrency:e.concurrency,autoStart:!1});let a=s,c=$p(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,$p(o,i)},finalize:()=>{Jn.delete(r)},queue:o},Jn.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var BI={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Fi(r){let e=Object.assign({},BI,r);return Db(e.name,e)}var kl=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Fi({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await nr(this.child),this.started=!0}async stop(){await or(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 Di("Block was pinned - please unpin and try again");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 s of e){if(await o.pins.isPinned(s))throw new Di("Block was pinned - please unpin and try again");yield s}})(),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 Vp=new ge("/version"),Nb=1;async function Rb(r){if(!await r.has(Vp)){await r.put(Vp,B(`${Nb}`));return}let e=await r.get(Vp),t=U(e);if(parseInt(t,10)!==Nb)throw new ol("Invalid datastore version, a datastore migration may be required")}var qp={};Ae(qp,{code:()=>Hp,decode:()=>$I,decodeOptions:()=>OI,encode:()=>FI,encodeOptions:()=>RI,name:()=>UI,toByteView:()=>Ob});var Mb=42;function Ob(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function LI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=H.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new I(m.tag,Mb),new I(m.bytes,t)]}function PI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function DI(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 NI(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 Kp={float64:!0,typeEncoders:{Map:NI,Object:LI,undefined:PI,number:DI}},RI={...Kp,typeEncoders:{...Kp.typeEncoders}};function MI(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return H.decode(r.subarray(1))}var _l={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};_l.tags[Mb]=MI;var OI={..._l,tags:_l.tags.slice()},UI="dag-cbor",Hp=113,FI=r=>an(r,Kp),$I=r=>bt(Ob(r),_l);var Xp={};Ae(Xp,{code:()=>Zp,decode:()=>Fb,encode:()=>Ub,format:()=>XI,name:()=>ZI,parse:()=>QI,stringify:()=>XI});var zp=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===m.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===m.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[m.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[m.negint.major](e,t){this[m.uint.major](e,t)}[m.bytes.major](e,t){throw new Error(`${_r} unsupported type: Uint8Array`)}[m.string.major](e,t){this.prefix(e);let n=Ec(JSON.stringify(t.value));e.push(n.length>32?wi(n):n)}[m.array.major](e,t){this.prefix(e),this.inRecursive.push({type:m.array,elements:0}),e.push([91])}[m.map.major](e,t){this.prefix(e),this.inRecursive.push({type:m.map,elements:0}),e.push([123])}[m.tag.major](e,t){}[m.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===m.array)e.push([93]);else if(i.type===m.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(`${_r} 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=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};function VI(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${_r} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==m.string||n.type!==m.string)throw new Error(`${_r} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${_r} unexpected duplicate map keys, this is not supported`)}var KI={addBreakTokens:!0,mapSorter:VI};function Gp(r,e){return e=Object.assign({},KI,e),Dc(r,new zp,e)}var is=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(`${F} 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(`${F} 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 I(m.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(`${F} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${F} 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 s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new I(m.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new I(i>=0?m.uint:m.negint,i,this._pos-e):new I(i>=0?m.uint:m.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${F} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new I(m.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${F} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){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(`${F} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${F} unexpected unicode sequence at position ${this._pos}`);let c,l,f,u;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(s&31)<<6|c&63,u>127&&(i=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(s&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(i=u));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&&(u=(s&15)<<18|(c&63)<<12|(l&63)<<6|f&63,u>65535&&u<1114112&&(i=u))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${F} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);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(`${F} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new I(m.string,np(t),this._pos-e);default:if(s<32)throw new Error(`${F} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${F} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new I(m.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new I(m.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new I(m.null,null,4);case 102:return this.expect([102,97,108,115,101]),new I(m.false,!1,5);case 116:return this.expect([116,114,117,101]),new I(m.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(`${F} 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 I(m.break,void 0,1);if(this.ch()!==44)throw new Error(`${F} 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 I(m.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 I(m.break,void 0,1);if(this.ch()!==44)throw new Error(`${F} 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 I(m.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${F} 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(`${F} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Wp(r,e){return e=Object.assign({tokenizer:new is(r,e)},e),bt(r,e)}function qI(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function zI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=H.asCID(r);if(!e)return null;let t=e.toString();return[new I(m.map,1/0,1),new I(m.string,"/",1),new I(m.string,t,t.length),new I(m.break,void 0,1)]}function Cl(r){let e=je.encode(r).slice(1);return[new I(m.map,1/0,1),new I(m.string,"/",1),new I(m.map,1/0,1),new I(m.string,"bytes",5),new I(m.string,e,e.length),new I(m.break,void 0,1),new I(m.break,void 0,1)]}function Wt(r){return Cl(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function GI(r){return Cl(new Uint8Array(r))}function WI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function jI(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 YI={typeEncoders:{Object:zI,Buffer:Cl,Uint8Array:Cl,Int8Array:Wt,Uint16Array:Wt,Int16Array:Wt,Uint32Array:Wt,Int32Array:Wt,Float32Array:Wt,Float64Array:Wt,Uint8ClampedArray:Wt,BigInt64Array:Wt,BigUint64Array:Wt,DataView:Wt,ArrayBuffer:GI,undefined:WI,number:jI}},jp=class extends is{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===m.map){let t=this._next();if(t.type===m.string&&t.value==="/"){let n=this._next();if(n.type===m.string){if(this._next().type!==m.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new I(m.tag,42,0)}if(n.type===m.map){let o=this._next();if(o.type===m.string&&o.value==="bytes"){let s=this._next();if(s.type===m.string){for(let a=0;a<2;a++)if(this._next().type!==m.break)throw new Error("Invalid encoded Bytes form");let i=je.decode(`m${s.value}`);return new I(m.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Yp={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Yp.tags[42]=H.parse;var ZI="dag-json",Zp=297,Ub=r=>Gp(r,YI),Fb=r=>{let e=qI(r),t=Object.assign(Yp,{tokenizer:new jp(e,Yp)});return Wp(e,t)},XI=r=>JI.decode(Ub(r));var JI=new TextDecoder,QI=r=>Fb(ek.encode(r)),ek=new TextEncoder;var nm={};Ae(nm,{code:()=>rm,createLink:()=>Yb,createNode:()=>jb,decode:()=>hk,encode:()=>dk,name:()=>fk,prepare:()=>em,validate:()=>tm});var tk=new TextDecoder;function Jp(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 Tl(r,e){let t;[t,e]=Jp(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 $b(r,e){let t;return[t,e]=Jp(r,e),[t&7,t>>3,e]}function rk(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=$b(r,n),s===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]=Tl(r,n)}else if(s===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 i;[i,n]=Tl(r,n),e.Name=tk.decode(i)}else if(s===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]=Jp(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Vb(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=$b(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Tl(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]=Tl(r,t),n.push(rk(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 i={};return s&&(i.Data=s),i.Links=n||[],i}var Hb=new TextEncoder,Kb=2**32,nk=2**31;function ok(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=$i(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Hb.encode(r.Name);t-=n.length,e.set(n,t),t=$i(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=$i(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function qb(r){let e=ik(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=$i(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let s=ok(r.Links[o],t.subarray(0,n));n-=s,n=$i(t,n,s)-1,t[n]=18}return t}function sk(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+as(t)}if(typeof r.Name=="string"){let t=Hb.encode(r.Name).length;e+=1+t+as(t)}return typeof r.Tsize=="number"&&(e+=1+as(r.Tsize)),e}function ik(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+as(t)}if(r.Links)for(let t of r.Links){let n=sk(t);e+=1+n+as(n)}return e}function $i(r,e,t){e-=as(t);let n=e;for(;t>=nk;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function as(r){return r%2===0&&r++,Math.floor((ak(r)+6)/7)}function ak(r){let e=0;return r>=Kb&&(r=Math.floor(r/Kb),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+ck[r]}var ck=[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 lk=["Data","Links"],uk=["Hash","Name","Tsize"],Qp=new TextEncoder;function Gb(r,e){if(r===e)return 0;let t=r.Name?Qp.encode(r.Name):[],n=e.Name?Qp.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function zb(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Wb(r){if(typeof r.asCID=="object"){let t=H.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=H.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=H.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=H.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 em(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=Qp.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(Wb),e.Links.sort(Gb);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function tm(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!zb(r,lk))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(!zb(t,uk))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&&Gb(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function jb(r,e=[]){return em({Data:r,Links:e})}function Yb(r,e,t){return Wb({Hash:t,Name:r,Tsize:e})}function Zb(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var fk="dag-pb",rm=112;function dk(r){tm(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),qb(e)}function hk(r){let e=Zb(r),t=Vb(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=H.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function cs(r){return r?.then!=null}function Xb(r=[],e){let t={[rm]:nm,[Ps]:Ds,[Hp]:qp,[Zp]:Xp,[ud]:Pa};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);cs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Mi(`Could not load codec for ${n}`)}}function Jb(r=[],e){let t={[Rt.code]:Rt,[Da.code]:Da,[Ge.code]:Ge};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);cs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Ri(`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 Lt=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Br=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 Bl=0,ls=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},Ll=class extends Br{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===Bl){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new ls(`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)}*get(e,t){if(e.multihash.code===Bl){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new ls(`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 Lt;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===Bl){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new ls(`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===Bl){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new ls(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function pk(r){return r[Symbol.asyncIterator]!=null}function mk(r,e){let t=0;if(pk(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=os(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var jt=mk;function gk(r){return r[Symbol.asyncIterator]!=null}function Qb(r){return r?.then!=null}function yk(r,e){let t=0;if(gk(r))return(async function*(){for await(let c of r){let l=e(c,t++);Qb(l)&&await l,yield c}})();let n=os(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();if(typeof e(o,t++)?.then=="function")return(async function*(){yield o;for(let c of n){let l=e(c,t++);Qb(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var om=yk;var wk=128,Pl=class{child;getHasher;log;logger;components;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Ll(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??wk}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new W("blocks:put:duplicate",e)),e):(n.onProgress?.(new W("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new W("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=jt(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new W("blocks:put-many:duplicate",s)),!i}),o=om(n,async({cid:s})=>{t.onProgress?.(new W("blocks:put-many:providers:notify",s)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(s,t)))});t.onProgress?.(new W("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new W("blocks:get:providers:get",e));let o=await ex(e,this.components.blockBrokers,n,{...t,log:this.log});t.onProgress?.(new W("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new W("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(e,t))),yield o;return}t.onProgress?.(new W("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new W("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(om(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new W("blocks:get-many:providers:get",n));let s=await ex(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new W("blocks:get-many:blockstore:put",n)),await this.child.put(n,s,t),t.onProgress?.(new W("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new W("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new W("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 W("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},Dl=class extends Pl{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await nr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await or(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new sm({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},sm=class extends Pl{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=pe([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=pe([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=pe([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function bk(r){return typeof r.retrieve=="function"}var xk=(r,e)=>{if(e==null)throw new k(`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(cs(o)?n=await o:n=o,!X(n.digest,r.multihash.digest))throw new Vr("Hash of downloaded block did not match multihash from passed CID")}};async function ex(r,e,t,n){let o=xk(r,t),s=new AbortController,i=pe([s.signal,n.signal]);s.signal;let a=[];for(let c of e)bk(c)&&a.push(c);if(a.length===0)throw new sl(`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:i,validateFn:async u=>{await o(u),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 - %e",r,l),l}}))}finally{s.abort(),i.clear()}}var Ki=class extends _e{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Un(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=je.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let s=ae();if(this.requests.set(n,s.promise),this.providers.length===0){let f=!1;this.initialPeerSearchComplete==null&&(f=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));try{await St(this.initialPeerSearchComplete,t.signal),f&&this.log("found initial session peers for %c",e)}catch(u){throw f&&this.log("failed to find initial session peers for %c - %e",e,u),this.requests.delete(n),s.reject(u),u}}let i=!1,a=new qt({concurrency:this.maxProviders});a.addEventListener("failure",f=>{this.log.error("error querying provider %o, evicting from session",f.detail.job.options.provider,f.detail.error),this.evict(f.detail.job.options.provider)}),a.addEventListener("success",f=>{i=!0,s.resolve(f.detail.result)}),a.addEventListener("idle",()=>{if(i){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 f=0;f<this.minProviders&&this.providers.length!==0;f++){let u=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(u)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(f=>{this.log.error("could not find new providers for %c - %e",e,f),s.reject(f)})});let c=f=>{a.add(async()=>this.queryProvider(e,f.detail,t),{provider:f.detail}).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,u)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async f=>a.add(async()=>this.queryProvider(e,f,t),{provider:f}))).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,f)});let l=()=>{s.reject(new ft(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",l);try{return await St(s.promise,t.signal)}finally{this.removeEventListener("provider",c),t.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=ae(),s=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e),this.initialProviders.length>0)for(;s<t&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(s<this.maxProviders)for await(let i of this.findNewProviders(e,n)){if(s===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(this.log("found %d/%d new session peers",s,this.maxProviders),s<t)throw new Ni(`Found ${s} of ${t} ${this.name} providers for ${e}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};var Nl=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??dr(),this.log=this.logger.forComponent("helia"),this.getHasher=Jb(e.hashers,e.loadHasher),this.getCodec=Xb(e.codecs,e.loadCodec),this.dns=e.dns??el(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new _e;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 cl(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let s=[o],i=vk(o);i!=null&&s.push(i);let a=Ek(o);return a!=null&&s.push(a),s}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Dl(t,e);this.pins=new al(e.datastore,n,this.getCodec),this.blockstore=new kl(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await Rb(this.datastore),await nr(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await or(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 Ii(o.deleteMany((async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new W("helia:gc:deleted",s))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new W("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};function vk(r){return r?.[mn]}function Ek(r){return r?.[yn]}var Ak=[6,53,56,54,55];function tx(r){return ox("sni",r)?.value}function rx(r){let e=ox("tcp",r)?.value;return e==null?"":`:${e}`}function ox(r,e){return e.find(t=>t.name===r)}function nx(r){return r.some(({code:e})=>e===448)}function Yt(r,e){let t=sx[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var sx={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Yt(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Yt(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Yt(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Yt(t,e)}`},http:(r,e)=>{let t=nx(e),n=tx(e),o=rx(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Yt(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Yt(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Yt(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Yt(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Yt(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=nx(e),n=tx(e),o=rx(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Yt(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Yt(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function Rl(r,e){let n=ee(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=sx[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&Ak.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var fe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),q=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),ix=r=>({match:e=>r.match(e)===!1?e:!1}),te=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Qe=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),ce=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function de(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Sk=q(421),ax=de(Sk),Ol=q(54),Ul=q(55),Fl=q(56),am=q(53),_O=de(Ol,te(q(421))),CO=de(Ul,te(q(421))),TO=de(Fl,te(q(421))),cx=de(Qe(am,Fl,Ol,Ul),te(q(421))),lx=ce(q(4),te(q(43))),ux=ce(te(q(42)),q(41),te(q(43))),cm=Qe(lx,ux),Qn=Qe(cm,am,Ol,Ul,Fl),BO=de(Qe(cm,ce(Qe(am,Fl,Ol,Ul),te(q(421))))),lm=de(lx),um=de(ux),LO=de(cm),fm=ce(Qn,q(6)),Hi=ce(Qn,q(273)),qi=de(ce(fm,te(q(421)))),PO=de(Hi),dm=ce(Hi,fe(460),te(q(421))),$l=ce(Hi,fe(461),te(q(421))),Ik=Qe(dm,$l),DO=de(dm),fx=de($l),im=Qe(Qn,fm,Hi,dm,$l),dx=Qe(ce(im,fe(477),te(q(421)))),eo=de(dx),hx=Qe(ce(im,fe(478),te(q(421))),ce(im,fe(448),te(q(449)),fe(477),te(q(421)))),zi=de(hx),px=ce(Hi,fe(280),te(q(466)),te(q(466)),te(q(421))),hm=de(px),mx=ce($l,fe(465),te(q(466)),te(q(466)),te(q(421))),pm=de(mx),Ml=Qe(dx,hx,ce(fm,te(q(421))),ce(Ik,te(q(421))),ce(Qn,te(q(421))),px,mx,q(421)),NO=de(Ml),kk=ce(te(Ml),fe(290),ix(fe(281)),te(q(421))),to=de(kk),_k=Qe(ce(Ml,fe(290),fe(281),te(q(421))),ce(Ml,fe(281),te(q(421))),ce(fe(281),te(q(421)))),mm=de(_k),Ck=Qe(ce(Qn,q(6),fe(480),te(q(421))),ce(Qn,fe(480),te(q(421)))),gx=de(Ck),Tk=ce(Qn,Qe(ce(q(6,"443"),fe(480)),ce(q(6),fe(443)),ce(q(6),fe(448),fe(480)),ce(fe(448),fe(480)),fe(448),fe(443)),te(q(421))),yx=de(Tk),Bk=Qe(ce(q(777),te(q(421)))),RO=de(Bk),Lk=Qe(ce(q(400),te(q(421)))),MO=de(Lk);function gm(r,e,t){return r.filter(n=>{if(yx.matches(n)||e&&gx.matches(n))return t||cx.matches(n)?!0:Ht(n)===!1;if(!e&&t){let{host:o}=Q(n);if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*Vl(r,e,t,n,o,s={}){for await(let i of e.findProviders(r,s)){let a=gm(i.multiaddrs,n,o);if(a.length===0)continue;let c=Rl(a[0]),l={type:"trustless-gateway",cid:r,url:c.toString(),routing:i.routing};s?.onProgress?.(new W("trustless-gateway:found-provider",l)),yield new us(c,{logger:t,transformRequestInit:s.transformRequestInit})}}async function wx(r,e,t){let{signal:n,log:o}=t??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>e)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,e),r.body!=null&&await r.body.cancel().catch(l=>{o?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new se;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var us=class{url;#e=0;#t=0;#r=0;#i=0;#s=new Map;log;transformRequestInit;constructor(e,{logger:t,transformRequestInit:n}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#f(e){let t=e.multihash.bytes;return je.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=bx}={}){let o=new URL(this.url.toString());if(o.pathname=`/ipfs/${e.toString()}`,o.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let s=this.#f(e),i=new AbortController,a=()=>{i.abort()};t?.addEventListener("abort",a);try{let c=this.#s.get(s);if(c==null){this.#e++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},f=this.transformRequestInit!=null?await this.transformRequestInit(l):l;c=fetch(o.toString(),f).then(async u=>{if(this.log("GET %s %d",o,u.status),!u.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);let d=await wx(u,n,{signal:i.signal,log:this.log});return this.#i++,d}),this.#s.set(s,c)}return await c}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",a),this.#s.delete(s)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#i/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#i,pendingResponses:this.#s.size}}};var ym=class extends Ki{routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Kl,this.allowLocal=t.allowLocal??Hl,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*Vl(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t){if(rr(e))return;let n=gm(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(n.length===0)return;let o=Rl(n[0]);return new us(o,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function xx(r,e){return new ym(r,e)}var ql=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Kl,this.allowLocal=t.allowLocal??Hl,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of Vl(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return xx({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Kl=!1,Hl=!1,bx=2097152;function wm(r={}){return e=>new ql(e,r)}async function*zl(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var Ok=pn(xm(),1);var Zt=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},Gl=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},fs=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},Wl=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},jl=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},Yl=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Gi=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var Xt;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),(function(o){o.codec=()=>Xs(t)})(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=Fe((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.value!=null&&(s.uint32(10),s.bytes(o.value)),o.signatureV1!=null&&(s.uint32(18),s.bytes(o.signatureV1)),o.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(o.validityType,s)),o.validity!=null&&(s.uint32(34),s.bytes(o.validity)),o.sequence!=null&&(s.uint32(40),s.uint64(o.sequence)),o.ttl!=null&&(s.uint32(48),s.uint64(o.ttl)),o.pubKey!=null&&(s.uint32(58),s.bytes(o.pubKey)),o.signatureV2!=null&&(s.uint32(66),s.bytes(o.signatureV2)),o.data!=null&&(s.uint32(74),s.bytes(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Ue(o,r.codec()),r.decode=(o,s)=>Oe(o,r.codec(),s)})(Xt||(Xt={}));var Pk=Ct("ipns:utils"),vx=B("/ipns/");var Dk=0,Nk=18;function Ex(r){let e;if(r.pubKey!=null)try{e=en(r.pubKey)}catch(t){throw Pk.error(t),t}if(e!=null)return e}function Ax(r){let e=B("ipns-signature:");return Ce([e,r])}function Wi(r){return"signatureV1"in r?Xt.encode({value:B(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:B(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Xt.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function ln(r){let e=Xt.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new Zt("Missing data or signatureV2");let t=Sx(e.data),n=Rk(t.Value),o=U(t.Validity);if(e.value!=null&&e.signatureV1!=null)return Mk(e),{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function ji(r){return Ce([vx,r.bytes])}function ds(r){let e=dt(r.slice(vx.length));if(!Zl(e,Dk)&&!Zl(e,Nk))throw new Vr("Multihash in IPNS key was not identity or sha2-256");return e}function Sx(r){let e=bt(r);if(e.ValidityType===0)e.ValidityType=Xt.ValidityType.EOL;else throw new fs("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function Rk(r){let e=U(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${H.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${H.parse(e).toV1().toString()}`}catch{}throw new jl("Value must be a valid content path starting with /")}function Mk(r){if(r.data==null)throw new Yl("Record data is missing");let e=Sx(r.data);if(!X(e.Value,r.value??new Uint8Array(0)))throw new Zt('Field "value" did not match between protobuf and CBOR');if(!X(e.Validity,r.validity??new Uint8Array(0)))throw new Zt('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new Zt('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new Zt('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new Zt('Field "ttl" did not match between protobuf and CBOR')}function Zl(r,e){return r.code===e}var PU=Ct("ipns"),DU=300*1e9,Uk="/ipns/",NU=Uk.length;var Ix=pn(xm(),1);var Xl=Ct("ipns:validator"),Fk=1024*10;async function $k(r,e){let t=ln(e),n;try{let o=Ax(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw Xl.error("record signature verification failed"),new Zt("Record signature verification failed");if(t.validityType===Xt.ValidityType.EOL){if(Ix.default.fromString(t.validity).toDate().getTime()<Date.now())throw Xl.error("record has expired"),new Gl("record has expired")}else if(t.validityType!=null)throw Xl.error("the validity type is unsupported"),new fs("The validity type is unsupported");Xl("ipns record for %s is valid",t.value)}async function kx(r,e){if(e.byteLength>Fk)throw new Wl("The record is too large");let t=ds(r),n;Zl(t,0)&&(n=Ja(t));let o=ln(e),s=Ex(o)??n;if(s==null)throw new Gi("Could not extract public key from IPNS record or routing key");let i=ji(s.toMultihash());if(!X(i,r))throw new Gi("Embedded public key did not match routing key");await $k(s,e)}var Jl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Yi(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),wo(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new Jl("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var hs=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},Jt=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function Vk(r){return r[Symbol.asyncIterator]!=null}function Kk(r){if(Vk(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var _x=Kk;var Cx=B("/ipns/");function Tx(r){return X(r.subarray(0,Cx.byteLength),Cx)}var Ql=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){try{yield*Gc(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof ke)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!Tx(e))return;let o=ds(e),s=H.createV1(114,o),i=ln(t);await this.client.putIPNS(s,i,n)}async get(e,t){if(!Tx(e))throw new ke("Not found");let n=ds(e),o=H.createV1(114,n);try{let s=await this.client.getIPNS(o,t);return Wi(s)}catch(s){throw s.name==="BadResponseError"?new ke("Not found"):s}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},eu=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await _x(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new ke("Not found")}async*getClosestPeers(e,t={}){}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};var tu={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},ru=class{url;started;httpQueue;shutDownController;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new Zn({concurrency:t.concurrentRequests??tu.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??tu.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new Ql(this),this.peerRouting=new eu(this),this.cacheName=t.cacheName??tu.cacheName,this.cacheTTL=t.cacheTTL??tu.cacheTTL}get[mn](){return this.contentRouting}get[yn](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=pe([this.shutDownController.signal,n,t.signal]);let s=ae(),i=ae();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(!l.ok){if(l.status===404)return;throw l.status===422?new hs("Request does not conform to schema or semantic constraints"):new Jt(`Unexpected status code: ${l.status}`)}if(l.body==null)throw new Jt("Routing response had no body");let f=l.headers.get("Content-Type");if(f==null)throw new Jt("No Content-Type header received");if(f.startsWith("application/json")){let d=(await l.json()).Providers??[];for(let h of d){let p=this.#e(h);p!=null&&(yield p)}}else if(f.includes("application/x-ndjson"))for await(let u of Yi(zl(l.body))){let d=this.#e(u);d!=null&&(yield d)}else throw new Jt(`Unsupported Content-Type: ${f}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished: %c",e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=pe([this.shutDownController.signal,n,t.signal]);let s=ae(),i=ae();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)return;if(l.status===422)throw new hs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Jt("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let d=(await l.json()).Peers??[];for(let h of d){let p=this.#e(h);p!=null&&(yield p)}}else for await(let u of Yi(zl(l.body))){let d=this.#e(u);d!=null&&(yield d)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async getIPNS(e,t={}){this.log("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=pe([this.shutDownController.signal,n,t.signal]);let s=ae(),i=ae();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o},l=await this.#r(a,c);if(this.log("getIPNS GET %s %d",a,l.status),l.status===404)throw new ke("No matching records found");if(l.status===422)throw new hs("Request does not conform to schema or semantic constraints");if(!l.ok)throw new Jt(`Unexpected status code: ${l.status}`);let f=l.headers.get("Content-Type");if(f==null||!f.includes("application/vnd.ipfs.ipns-record"))throw new ke("No matching records found");if(l.body==null)throw new Jt("GET ipns response had no body");let u=await l.arrayBuffer(),d=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await kx(ji(e.multihash),d),ln(d)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=pe([this.shutDownController.signal,o,n.signal]);let i=ae(),a=ae();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await i.promise;let l=Wi(t),f={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:s},u=await this.#r(c,f);if(this.log("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new Jt("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(ee)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Tt(e.ID),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),c;await this.cache?.delete(e)}}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),c.clone()}let i=fetch(e,t).then(async c=>{if(this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,f=new Headers(c.headers);f.set("x-cache-expires",l.toString());let u=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:f});await this.cache.put(e,u)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}};function Bx(r,e={}){return new ru({logger:dr()},{...e,url:new URL(r)})}var Lx="[a-fA-F\\d:]",un=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Lx})|(?<=${Lx})(?=\\s|$))`:"",Qt="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Ie="[a-fA-F\\d]{1,4}",nu=`
14
14
  (?:
15
15
  (?:${Ie}:){7}(?:${Ie}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
16
16
  (?:${Ie}:){6}(?:${Qt}|:${Ie}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
@@ -35,7 +35,7 @@ ${[...t.errors.entries()].map(([s,i])=>`
35
35
  `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new se(...e.map(a=>Vc.single(B(`${a}
36
36
  `))),B(`
37
37
  `));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(B(`na
38
- `),t),n('responded with "na" for "%s"',s)}}var tg=class extends _e{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=$m(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new _a(n.local,n.error))})}[Symbol.toStringTag]="Connection";[mg]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new fn("Connection is not multiplexed");if(this.muxer.status!=="open")throw new gn(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new gn(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Is("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await ys(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=J_(n.protocol,this.components.registrar,t),s=vv(n.protocol,"outbound",this);if(s>o){let a=new ka(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await ws(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=X_(t.protocol,this.components.registrar);if(vv(t.protocol,"inbound",this)>o)throw new Ia(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Is("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,f,u)=>{await i(l,f),u(l,f)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,f)=>{e=l,t=f,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function Ev(r,e){return new tg(r,e)}function X_(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Jm}function J_(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Qm}function vv(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Hu=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Xe({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Xe({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Su(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=pe([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Iu("Connection denied");await St(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=Tt(n),await St(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),o=await u.protect(o,n))}try{if(Q_(n)){if(n.remotePeer==null)throw new $r(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let u=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;u!=null&&(d=Tt(u)),n?.onProgress?.(new W(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let u=new fo("Can not dial self");throw e.abort(u),u}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new W(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(u){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,u),u}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let f=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return f.log("successfully upgraded connection"),f}_createConnection(e){let t=Ev(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await ws(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new so(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new so(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await ys(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new so(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new so(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await ys(e,o,n),i=t.get(s);if(i==null)throw new fn(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new fn(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await ws(e,o,n),i=t.get(s);if(i==null)throw new fn(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function Q_(r){return r.skipEncryption===!0}var qu="3.1.1",zu="js-libp2p";function Gu(r,e){return`${r??zu}/${e??qu} browser/${globalThis.navigator.userAgent}`}var aa=class extends _e{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new _e,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let f=n(l),u=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return f||u},this.peerId=e.peerId,this.logger=e.logger??dr(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??zu,s=e.nodeInfo?.version??qu,i=this.components=iv({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Gu(o,s)},logger:this.logger,events:t,datastore:e.datastore??new no,connectionGater:cv(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",tv(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let f={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:f})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Hu(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,f)=>this.configureComponent(`connection-encryption-${f}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,f)=>this.configureComponent(`stream-muxers-${f}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Ku(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ru(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Mu(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Vu(this.components)),this.configureComponent("addressManager",new mu(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,f)=>this.configureComponent(`peer-router-${f}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Fu(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,f)=>this.configureComponent(`content-router-${f}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ou(this.components,{routers:c})),this.configureComponent("randomWalk",new $u(this.components)),(e.peerDiscovery??[]).forEach((l,f)=>{this.configureComponent(`peer-discovery-${f}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,f)=>{this.components.transportManager.add(this.configureComponent(`transport-${f}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let f=e.services[l],u=f(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=u,this.configureComponent(l,u),u[mn]!=null&&(this.log("registering service %s for content routing",l),c.push(u[mn])),u[yn]!=null&&(this.log("registering service %s for peer routing",l),a.push(u[yn])),u[Kf]!=null&&(this.log("registering service %s for peer discovery",l),u[Kf].addEventListener?.("peer",d=>{this.#e(d)}))}av(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Yn;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new k("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new k("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){nn(e)&&(e=Tt(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ce([B("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=en(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function Sv(r={}){r.privateKey??=await Xa("Ed25519");let e=new aa({...await $x(r),peerId:hb(r.privateKey)});return r.start!==!1&&await e.start(),e}var eC=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Iv(r){return r==null?!1:r instanceof aa?!0:eC.every(e=>typeof r[e]=="function")}var SE=pn(Nv(),1);var rg={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var bs={};Ae(bs,{create:()=>hC,derivedEmptyPasswordKey:()=>Wu});var Wu={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function hC(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Se.get();t*=8;async function c(u,d){let h=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),w={name:e,iv:p};typeof d=="string"&&(d=B(d));let y;if(d.length===0){y=await a.subtle.importKey("jwk",Wu,{name:"AES-GCM"},!0,["encrypt"]);try{let T={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},S=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(T,S,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Wu,{name:"AES-GCM"},!0,["encrypt"])}}else{let T={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},S=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(T,S,{name:e,length:t},!0,["encrypt"])}let b=await a.subtle.encrypt(w,y,u);return Ce([h,w.iv,new Uint8Array(b)])}async function l(u,d){let h=u.subarray(0,s),p=u.subarray(s,s+n),w=u.subarray(s+n),y={name:e,iv:p};typeof d=="string"&&(d=B(d));let b;if(d.length===0)try{let S={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},D=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);b=await a.subtle.deriveKey(S,D,{name:e,length:t},!0,["decrypt"])}catch{b=await a.subtle.importKey("jwk",Wu,{name:"AES-GCM"},!0,["decrypt"])}else{let S={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},D=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);b=await a.subtle.deriveKey(S,D,{name:e,length:t},!0,["decrypt"])}let T=await a.subtle.decrypt(y,b,w);return new Uint8Array(T)}return{encrypt:c,decrypt:l}}var re=pn(Rv());function io(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function dn(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let f=a-1;f>=0;f--){let u=Math.pow(2,f*e);l[s-f-1]=Math.floor(o/u),o-=l[s-f-1]*u}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function Zu(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function og(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=io(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,io(s,8)-n}function Mv(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=dn(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=dn(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Ov(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function lt(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var Uq=Math.log(2);function Xu(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function sg(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ur(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var ua=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return sg(this.items)}},ca=[new Uint8Array([1])],Uv="0123456789";var vs="",er=new ArrayBuffer(0),ig=new Uint8Array(0),fa="EndOfContent",$v="OCTET STRING",Vv="BIT STRING";function Fr(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?re.BufferSourceConverter.toUint8Array(s.valueHex):ig}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ur(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",er)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:re.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Nr=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=vs,warnings:n=[],valueBeforeDecode:o=ig}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=re.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:re.Convert.ToHex(this.valueBeforeDecodeView)}}};Nr.NAME="baseBlock";var et=class extends Nr{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};et.NAME="valueBlock";var Ju=class extends Fr(Nr){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?re.BufferSourceConverter.toUint8Array(e.valueHex):ig,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",er}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=dn(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=re.BufferSourceConverter.toUint8Array(e);if(!Ur(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let d=new Uint8Array(f);for(let h=0;h<l.length;h++)d[h]=l[h];l=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,l[c-1]=s[c]&127;let u=new Uint8Array(c);for(let d=0;d<c;d++)u[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(u),this.blockLength<=9?this.tagNumber=io(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Ju.NAME="identificationBlock";var Qu=class extends Nr{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=re.BufferSourceConverter.toUint8Array(e);if(!Ur(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=io(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=dn(this.length,8);if(o.byteLength>127)return this.error="Too big length",er;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Qu.NAME="lengthBlock";var O={},He=class extends Nr{constructor({name:e=vs,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Ju(o),this.lenBlock=new Qu(o),this.valueBlock=s?new s(o):new et(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new ua;t||Kv(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?er:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():re.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=re.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Ov(t,n)}};He.NAME="BaseBlock";function Kv(r){var e;if(r instanceof O.Constructed)for(let t of r.valueBlock.value)Kv(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var ef=class extends He{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=vs,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ef.NAME="BaseStringBlock";var tf=class extends Fr(et){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};tf.NAME="PrimitiveValueBlock";var Hv,rf=class extends He{constructor(e={}){super(e,tf),this.idBlock.isConstructed=!1}};Hv=rf;O.Primitive=Hv;rf.NAME="PRIMITIVE";function EC(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Of(r,e=0,t=r.length){let n=e,o=new He({},et),s=new Nr;if(!Ur(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=He;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=O.EndOfContent;break;case 1:c=O.Boolean;break;case 2:c=O.Integer;break;case 3:c=O.BitString;break;case 4:c=O.OctetString;break;case 5:c=O.Null;break;case 6:c=O.ObjectIdentifier;break;case 10:c=O.Enumerated;break;case 12:c=O.Utf8String;break;case 13:c=O.RelativeObjectIdentifier;break;case 14:c=O.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=O.Sequence;break;case 17:c=O.Set;break;case 18:c=O.NumericString;break;case 19:c=O.PrintableString;break;case 20:c=O.TeletexString;break;case 21:c=O.VideotexString;break;case 22:c=O.IA5String;break;case 23:c=O.UTCTime;break;case 24:c=O.GeneralizedTime;break;case 25:c=O.GraphicString;break;case 26:c=O.VisibleString;break;case 27:c=O.GeneralString;break;case 28:c=O.UniversalString;break;case 29:c=O.CharacterString;break;case 30:c=O.BmpString;break;case 31:c=O.DATE;break;case 32:c=O.TimeOfDay;break;case 33:c=O.DateTime;break;case 34:c=O.Duration;break;default:{let l=o.idBlock.isConstructed?new O.Constructed:new O.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?O.Constructed:O.Primitive}return o=EC(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Uf(r){if(!r.byteLength){let e=new He({},et);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Of(re.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function AC(r,e){return r?1:e}var pr=class extends et{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=re.BufferSourceConverter.toUint8Array(e);if(!Ur(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;AC(this.isIndefiniteForm,n)>0;){let i=Of(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===fa)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===fa?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new ua;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?er:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};pr.NAME="ConstructedValueBlock";var qv,hn=class extends He{constructor(e={}){super(e,pr),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
38
+ `),t),n('responded with "na" for "%s"',s)}}var tg=class extends _e{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=$m(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new _a(n.local,n.error))})}[Symbol.toStringTag]="Connection";[mg]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new fn("Connection is not multiplexed");if(this.muxer.status!=="open")throw new gn(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new gn(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Is("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await ys(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=J_(n.protocol,this.components.registrar,t),s=vv(n.protocol,"outbound",this);if(s>o){let a=new ka(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await ws(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=X_(t.protocol,this.components.registrar);if(vv(t.protocol,"inbound",this)>o)throw new Ia(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Is("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,f,u)=>{await i(l,f),u(l,f)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,f)=>{e=l,t=f,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function Ev(r,e){return new tg(r,e)}function X_(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Jm}function J_(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Qm}function vv(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Hu=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Xe({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Xe({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Su(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=pe([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Iu("Connection denied");await St(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=Tt(n),await St(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),o=await u.protect(o,n))}try{if(Q_(n)){if(n.remotePeer==null)throw new $r(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let u=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;u!=null&&(d=Tt(u)),n?.onProgress?.(new W(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let u=new fo("Can not dial self");throw e.abort(u),u}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new W(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(u){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,u),u}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let f=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return f.log("successfully upgraded connection"),f}_createConnection(e){let t=Ev(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await ws(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new so(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new so(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await ys(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new so(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new so(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await ys(e,o,n),i=t.get(s);if(i==null)throw new fn(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new fn(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await ws(e,o,n),i=t.get(s);if(i==null)throw new fn(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function Q_(r){return r.skipEncryption===!0}var qu="3.1.2",zu="js-libp2p";function Gu(r,e){return`${r??zu}/${e??qu} browser/${globalThis.navigator.userAgent}`}var aa=class extends _e{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new _e,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let f=n(l),u=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return f||u},this.peerId=e.peerId,this.logger=e.logger??dr(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??zu,s=e.nodeInfo?.version??qu,i=this.components=iv({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Gu(o,s)},logger:this.logger,events:t,datastore:e.datastore??new no,connectionGater:cv(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",tv(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let f={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:f})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Hu(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,f)=>this.configureComponent(`connection-encryption-${f}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,f)=>this.configureComponent(`stream-muxers-${f}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Ku(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ru(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Mu(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Vu(this.components)),this.configureComponent("addressManager",new mu(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,f)=>this.configureComponent(`peer-router-${f}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Fu(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,f)=>this.configureComponent(`content-router-${f}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ou(this.components,{routers:c})),this.configureComponent("randomWalk",new $u(this.components)),(e.peerDiscovery??[]).forEach((l,f)=>{this.configureComponent(`peer-discovery-${f}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,f)=>{this.components.transportManager.add(this.configureComponent(`transport-${f}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let f=e.services[l],u=f(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=u,this.configureComponent(l,u),u[mn]!=null&&(this.log("registering service %s for content routing",l),c.push(u[mn])),u[yn]!=null&&(this.log("registering service %s for peer routing",l),a.push(u[yn])),u[Kf]!=null&&(this.log("registering service %s for peer discovery",l),u[Kf].addEventListener?.("peer",d=>{this.#e(d)}))}av(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Yn;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new k("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new k("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){nn(e)&&(e=Tt(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ce([B("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=en(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function Sv(r={}){r.privateKey??=await Xa("Ed25519");let e=new aa({...await $x(r),peerId:hb(r.privateKey)});return r.start!==!1&&await e.start(),e}var eC=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Iv(r){return r==null?!1:r instanceof aa?!0:eC.every(e=>typeof r[e]=="function")}var SE=pn(Nv(),1);var rg={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var bs={};Ae(bs,{create:()=>hC,derivedEmptyPasswordKey:()=>Wu});var Wu={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function hC(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Se.get();t*=8;async function c(u,d){let h=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),w={name:e,iv:p};typeof d=="string"&&(d=B(d));let y;if(d.length===0){y=await a.subtle.importKey("jwk",Wu,{name:"AES-GCM"},!0,["encrypt"]);try{let T={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},S=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(T,S,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Wu,{name:"AES-GCM"},!0,["encrypt"])}}else{let T={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},S=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(T,S,{name:e,length:t},!0,["encrypt"])}let b=await a.subtle.encrypt(w,y,u);return Ce([h,w.iv,new Uint8Array(b)])}async function l(u,d){let h=u.subarray(0,s),p=u.subarray(s,s+n),w=u.subarray(s+n),y={name:e,iv:p};typeof d=="string"&&(d=B(d));let b;if(d.length===0)try{let S={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},D=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);b=await a.subtle.deriveKey(S,D,{name:e,length:t},!0,["decrypt"])}catch{b=await a.subtle.importKey("jwk",Wu,{name:"AES-GCM"},!0,["decrypt"])}else{let S={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},D=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);b=await a.subtle.deriveKey(S,D,{name:e,length:t},!0,["decrypt"])}let T=await a.subtle.decrypt(y,b,w);return new Uint8Array(T)}return{encrypt:c,decrypt:l}}var re=pn(Rv());function io(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function dn(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let f=a-1;f>=0;f--){let u=Math.pow(2,f*e);l[s-f-1]=Math.floor(o/u),o-=l[s-f-1]*u}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function Zu(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function og(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=io(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,io(s,8)-n}function Mv(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=dn(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=dn(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Ov(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function lt(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var Uq=Math.log(2);function Xu(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function sg(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ur(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var ua=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return sg(this.items)}},ca=[new Uint8Array([1])],Uv="0123456789";var vs="",er=new ArrayBuffer(0),ig=new Uint8Array(0),fa="EndOfContent",$v="OCTET STRING",Vv="BIT STRING";function Fr(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?re.BufferSourceConverter.toUint8Array(s.valueHex):ig}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ur(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",er)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:re.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Nr=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=vs,warnings:n=[],valueBeforeDecode:o=ig}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=re.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:re.Convert.ToHex(this.valueBeforeDecodeView)}}};Nr.NAME="baseBlock";var et=class extends Nr{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};et.NAME="valueBlock";var Ju=class extends Fr(Nr){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?re.BufferSourceConverter.toUint8Array(e.valueHex):ig,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",er}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=dn(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=re.BufferSourceConverter.toUint8Array(e);if(!Ur(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let d=new Uint8Array(f);for(let h=0;h<l.length;h++)d[h]=l[h];l=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,l[c-1]=s[c]&127;let u=new Uint8Array(c);for(let d=0;d<c;d++)u[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(u),this.blockLength<=9?this.tagNumber=io(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Ju.NAME="identificationBlock";var Qu=class extends Nr{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=re.BufferSourceConverter.toUint8Array(e);if(!Ur(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=io(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=dn(this.length,8);if(o.byteLength>127)return this.error="Too big length",er;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Qu.NAME="lengthBlock";var O={},He=class extends Nr{constructor({name:e=vs,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Ju(o),this.lenBlock=new Qu(o),this.valueBlock=s?new s(o):new et(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new ua;t||Kv(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?er:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():re.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=re.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Ov(t,n)}};He.NAME="BaseBlock";function Kv(r){var e;if(r instanceof O.Constructed)for(let t of r.valueBlock.value)Kv(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var ef=class extends He{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=vs,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ef.NAME="BaseStringBlock";var tf=class extends Fr(et){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};tf.NAME="PrimitiveValueBlock";var Hv,rf=class extends He{constructor(e={}){super(e,tf),this.idBlock.isConstructed=!1}};Hv=rf;O.Primitive=Hv;rf.NAME="PRIMITIVE";function EC(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Of(r,e=0,t=r.length){let n=e,o=new He({},et),s=new Nr;if(!Ur(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=He;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=O.EndOfContent;break;case 1:c=O.Boolean;break;case 2:c=O.Integer;break;case 3:c=O.BitString;break;case 4:c=O.OctetString;break;case 5:c=O.Null;break;case 6:c=O.ObjectIdentifier;break;case 10:c=O.Enumerated;break;case 12:c=O.Utf8String;break;case 13:c=O.RelativeObjectIdentifier;break;case 14:c=O.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=O.Sequence;break;case 17:c=O.Set;break;case 18:c=O.NumericString;break;case 19:c=O.PrintableString;break;case 20:c=O.TeletexString;break;case 21:c=O.VideotexString;break;case 22:c=O.IA5String;break;case 23:c=O.UTCTime;break;case 24:c=O.GeneralizedTime;break;case 25:c=O.GraphicString;break;case 26:c=O.VisibleString;break;case 27:c=O.GeneralString;break;case 28:c=O.UniversalString;break;case 29:c=O.CharacterString;break;case 30:c=O.BmpString;break;case 31:c=O.DATE;break;case 32:c=O.TimeOfDay;break;case 33:c=O.DateTime;break;case 34:c=O.Duration;break;default:{let l=o.idBlock.isConstructed?new O.Constructed:new O.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?O.Constructed:O.Primitive}return o=EC(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Uf(r){if(!r.byteLength){let e=new He({},et);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Of(re.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function AC(r,e){return r?1:e}var pr=class extends et{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=re.BufferSourceConverter.toUint8Array(e);if(!Ur(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;AC(this.isIndefiniteForm,n)>0;){let i=Of(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===fa)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===fa?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new ua;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?er:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};pr.NAME="ConstructedValueBlock";var qv,hn=class extends He{constructor(e={}){super(e,pr),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
39
39
  `).map(o=>` ${o}`).join(`
40
40
  `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
41
41
  ${e.join(`