helia 6.0.13 → 6.0.14-4e19769a
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 +3 -3
- package/dist/index.min.js.map +3 -3
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.d.ts.map +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/version.js.map +1 -1
- package/package.json +5 -5
- package/src/version.ts +1 -1
- package/dist/typedoc-urls.json +0 -10
package/dist/index.min.js
CHANGED
|
@@ -10,7 +10,7 @@ ${e}`)}`:n!=null?`${n.split(`
|
|
|
10
10
|
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function lL(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function ix(r,e=""){if(lL(r)){let t=nx(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
11
11
|
${e}${r.errors.map(n=>`${ix(n,`${e}`)}`).join(`
|
|
12
12
|
${e}`)}`):t+=`
|
|
13
|
-
${e}[Error list was empty]`,t.trim()}return nx(r,e)}sn.formatters.e=r=>r==null?"undefined":ix(r);function uL(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 Qo(r){return{forComponent(e){return zn(e,r)}}}function zn(r,e){let t=uL(`${r}:trace`);return sn.enabled(`${r}:trace`)&&sn.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=sn(`${r}:trace`,e)),Object.assign(sn(r,e),{error:sn(`${r}:error`,e),trace:t,newScope:n=>zn(`${r}:${n}`,e)})}function ox(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var oe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var fm=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var g6=nr(ax(),1);var y6=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},cx=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function w6(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=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(s?.aborted){d(cx(s));return}if(s&&(c=()=>{d(cx(s))},s.addEventListener("abort",c,{once:!0})),r.then(u,d),t===Number.POSITIVE_INFINITY)return;let h=new y6;a=i.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){d(m)}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&&s&&s.removeEventListener("abort",c)});return f.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},f}function b6(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var fd=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},i={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(i);return}let s=b6(this.#e,i,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,i)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var za=class extends g6.default{#e;#t;#r=0;#s;#i=!1;#f=!1;#d;#b=0;#g=0;#a;#c;#n;#v;#o=0;#h;#l;#T=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:fd,...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.#s=e.intervalCap,this.#d=e.interval,this.#n=new e.queueClass,this.#v=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#I(){return this.#t||this.#r<this.#s}get#C(){return this.#o<this.#h}#P(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#y(),this.emit("next")}#k(){this.#_(),this.#S(),this.#c=void 0}get#O(){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.#x(this.#d-n),!0}this.#r=this.#e?this.#o:0}else return this.#x(t),!0}return!1}#x(e){this.#c===void 0&&(this.#c=setTimeout(()=>{this.#k()},e))}#E(){this.#a&&(clearInterval(this.#a),this.#a=void 0)}#R(){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.#R(),this.emit("idle")),!1;let e=!1;if(!this.#l){let t=!this.#O;if(this.#I&&this.#C){let n=this.#n.dequeue();this.#t||(this.#r++,this.#m()),this.emit("active"),this.#g=Date.now(),n(),t&&this.#S(),e=!0}}return e}#S(){this.#t||this.#a!==void 0||(this.#a=setInterval(()=>{this.#_()},this.#d),this.#b=Date.now()+this.#d)}#_(){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.#T++).toString(),t={timeout:this.timeout,...t},new Promise((n,o)=>{let i=Symbol(`task-${t.id}`);this.#n.enqueue(async()=>{this.#o++,this.#p.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let s;try{try{t.signal?.throwIfAborted()}catch(l){throw this.#t||this.#r--,this.#p.delete(i),l}let a=e({signal:t.signal});if(t.timeout&&(a=w6(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)=>{s=()=>{u(l.reason)},l.addEventListener("abort",s,{once:!0})})])}let c=await a;n(c),this.emit("completed",c)}catch(a){o(a),this.emit("error",a)}finally{s&&t.signal?.removeEventListener("abort",s),this.#p.delete(i),queueMicrotask(()=>{this.#P()})}},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.#v,this.#A()}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.#A()}))}#A(){let e=this.#i,t=!this.#t&&this.#r>=this.#s&&this.#n.size>0;t!==e&&(this.#i=t,this.emit(t?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#i}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 hm(r){let e=[Tn.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var v6={};Nt(v6,{base10:()=>hL});var hL=Rs({prefix:"9",name:"base10",alphabet:"0123456789"});var x6={};Nt(x6,{base16:()=>pL,base16upper:()=>mL});var pL=Lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),mL=Lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var E6={};Nt(E6,{base2:()=>gL});var gL=Lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var S6={};Nt(S6,{base256emoji:()=>xL});var lx=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),yL=lx.reduce((r,e,t)=>(r[t]=e,r),[]),wL=lx.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function bL(r){return r.reduce((e,t)=>(e+=yL[t],e),"")}function vL(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=wL[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var xL=$l({prefix:"\u{1F680}",name:"base256emoji",encode:bL,decode:vL});var _6={};Nt(_6,{base36:()=>Gn,base36upper:()=>EL});var Gn=Rs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),EL=Rs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var A6={};Nt(A6,{base8:()=>SL});var SL=Lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var T6={};Nt(T6,{identity:()=>_L});var _L=$l({prefix:"\0",name:"identity",encode:r=>Jv(r),decode:r=>Zv(r)});var pm={};Nt(pm,{code:()=>I6,decode:()=>PL,encode:()=>CL,name:()=>IL});var AL=new TextEncoder,TL=new TextDecoder,IL="json",I6=512;function CL(r){return AL.encode(JSON.stringify(r))}function PL(r){return JSON.parse(TL.decode(r))}var jl={};Nt(jl,{code:()=>Ga,decode:()=>RL,encode:()=>OL,name:()=>kL});var kL="raw",Ga=85;function OL(r){return bo(r)}function RL(r){return bo(r)}var k6={};Nt(k6,{identity:()=>Dr});var Bt={};Nt(Bt,{Digest:()=>Xa,create:()=>Wr,decode:()=>lt,equals:()=>P6,hasCode:()=>QL});var DL=dx,ux=128,NL=127,LL=~NL,BL=Math.pow(2,31);function dx(r,e,t){e=e||[],t=t||0;for(var n=t;r>=BL;)e[t++]=r&255|ux,r/=128;for(;r&LL;)e[t++]=r&255|ux,r>>>=7;return e[t]=r|0,dx.bytes=t-n+1,e}var ML=C6,UL=128,fx=127;function C6(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw C6.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&fx)<<o:(s&fx)*Math.pow(2,o),o+=7}while(s>=UL);return C6.bytes=i-n,t}var FL=Math.pow(2,7),$L=Math.pow(2,14),jL=Math.pow(2,21),KL=Math.pow(2,28),VL=Math.pow(2,35),HL=Math.pow(2,42),qL=Math.pow(2,49),WL=Math.pow(2,56),zL=Math.pow(2,63),GL=function(r){return r<FL?1:r<$L?2:r<jL?3:r<KL?4:r<VL?5:r<HL?6:r<qL?7:r<WL?8:r<zL?9:10},XL={encode:DL,decode:ML,encodingLength:GL},YL=XL,dd=YL;function hd(r,e=0){return[dd.decode(r,e),dd.decode.bytes]}function Kl(r,e,t=0){return dd.encode(r,e,t),e}function Vl(r){return dd.encodingLength(r)}function Wr(r,e){let t=e.byteLength,n=Vl(r),o=n+Vl(t),i=new Uint8Array(o+t);return Kl(r,i,0),Kl(t,i,n),i.set(e,o),new Xa(r,t,e,i)}function lt(r){let e=bo(r),[t,n]=hd(e),[o,i]=hd(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Xa(t,o,s,e)}function P6(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Qv(r.bytes,t.bytes)}}var Xa=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function QL(r,e){return r.code===e}var hx=0,ZL="identity",px=bo;function JL(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Wr(hx,px(r))}var Dr={code:hx,name:ZL,encode:px,digest:JL};var R6={};Nt(R6,{sha256:()=>St,sha512:()=>gm});var eB=20;function pd({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new O6(r,e,t,n,o)}var O6=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??eB,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?mx(n,this.code,t?.truncate):n.then(o=>mx(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function mx(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Wr(e,r)}function yx(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var St=pd({name:"sha2-256",code:18,encode:yx("SHA-256")}),gm=pd({name:"sha2-512",code:19,encode:yx("SHA-512")});function wx(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return rB(t,D6(r),e??ft.encoder);default:return nB(t,D6(r),e??ir.encoder)}}var bx=new WeakMap;function D6(r){let e=bx.get(r);if(e==null){let t=new Map;return bx.set(r,t),t}return e}var he=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==md)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==oB)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Wr(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&P6(e.multihash,n.multihash)}toString(e){return wx(this,e)}toJSON(){return{"/":wx(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??vx(n,o,i.bytes))}else if(t[iB]===!0){let{version:n,multihash:o,code:i}=t,s=lt(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==md)throw new Error(`Version 0 CID must use dag-pb (code: ${md}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=vx(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,md,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=bo(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Xa(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,d]=hd(e.subarray(t));return t+=d,u},o=n(),i=md;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=tB(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return D6(i).set(n,e),i}};function tB(r,e){switch(r[0]){case"Q":{let t=e??ft;return[ft.prefix,t.decode(`${ft.prefix}${r}`)]}case ft.prefix:{let t=e??ft;return[ft.prefix,t.decode(r)]}case ir.prefix:{let t=e??ir;return[ir.prefix,t.decode(r)]}case Gn.prefix:{let t=e??Gn;return[Gn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function rB(r,e,t){let{prefix:n}=t;if(n!==ft.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function nB(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var md=112,oB=18;function vx(r,e,t){let n=Vl(r),o=n+Vl(e),i=new Uint8Array(o+t.byteLength);return Kl(r,i,0),Kl(e,i,n),i.set(t,o),i}var iB=Symbol.for("@ipld/js-cid/CID");var Ya={...T6,...E6,...A6,...v6,...x6,...f6,..._6,...d6,...h6,...S6},XG={...R6,...k6};function ke(r=0){return new Uint8Array(r)}function Ot(r=0){return new Uint8Array(r)}function Ex(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var xx=Ex("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),N6=Ex("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ot(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),sB={utf8:xx,"utf-8":xx,hex:Ya.base16,latin1:N6,ascii:N6,binary:N6,...Ya},ym=sB;function j(r,e="utf8"){let t=ym[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var L6=60;function wm(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:Tn[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Tn[e.type],TTL:e.TTL??e.ttl??L6,data:e.data instanceof Uint8Array?j(e.data):e.data}))}}var aB=4;function B6(r,e={}){let t=new za({concurrency:e.queryConcurrency??aB});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),hm(o.types).forEach(a=>{i.append("type",Tn[a])}),o.onProgress?.(new oe("dns:query",n));let s=await t.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=wm(await a.json());return o.onProgress?.(new oe("dns:response",c)),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Sx(){return[B6("https://cloudflare-dns.com/dns-query"),B6("https://dns.google/resolve")]}var Tx=nr(Ax(),1);var M6=class{lru;constructor(e){this.lru=(0,Tx.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return wm({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:Tn[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??L6)*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 Ix(r){return new M6(r)}var cB=1e3,bm=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Ix(e.cacheSize??cB),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["."]=Sx())}async query(e,t={}){let n=hm(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new oe("dns:cache",o)),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new oe("dns:error",l))}}throw new fm(a,`DNS lookup of ${e} ${n} failed`)}};var Tn;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Tn||(Tn={}));function vm(r={}){return new bm(r)}function lB(r){return r[Symbol.asyncIterator]!=null}function uB(r){if(lB(r))return(async()=>{for await(let e of r);})();for(let e of r);}var an=uB;var gd=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},yd=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},xm=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Cx={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new xm("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var qt=Cx;function we(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function gt(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Ot(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var kx=Symbol.for("@achingbrain/uint8arraylist");function Px(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Hl(r){return!!r?.[kx]}var fe=class r{bufs;length;[kx]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Hl(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Hl(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Px(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Px(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Hl(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return gt(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:gt(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(s);break}let u=e-a;n.push(s.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(f){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Hl(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let u=0;u<i;u++)s[u]=-1;for(let u=0;u<o;u++)s[n[u]]=u;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let u=t;u<=c;u+=f){f=0;for(let d=l;d>=0;d--){let h=this.get(u+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return u}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ot(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ke(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ke(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ke(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ot(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ke(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ke(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ke(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ke(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ke(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!we(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,i)=>o+i.byteLength,0)),n.length=t,n}};function B(r,e="utf8"){let t=ym[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var dB=parseInt("11111",2),U6=parseInt("10000000",2),hB=parseInt("01111111",2),Ox={0:wd,1:wd,2:pB,3:yB,4:wB,5:gB,6:mB,16:wd,22:wd,48:wd};function Xn(r,e={offset:0}){let t=r[e.offset]&dB;if(e.offset++,Ox[t]!=null)return Ox[t](r,e);throw new Error("No decoder for tag "+t)}function bd(r,e){let t=0;if((r[e.offset]&U6)===U6){let n=r[e.offset]&hB,o="0x";e.offset++;for(let i=0;i<n;i++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function wd(r,e){bd(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Xn(r,e);if(n===null)break;t.push(n)}return t}function pB(r,e){let t=bd(r,e),n=e.offset,o=e.offset+t,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return e.offset+=t,Uint8Array.from(i)}function mB(r,e){let t=bd(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let f=0;for(let u=0;u<c.length;u++)f+=c[u]<<u*7;a+=`.${f}`,c=[]}}return a}function gB(r,e){return e.offset++,null}function yB(r,e){let t=bd(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function wB(r,e){let t=bd(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function bB(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new fe;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Em(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=bB(r.byteLength);return new fe(Uint8Array.from([e.byteLength|U6]),e)}function zr(r){let e=new fe,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new fe(Uint8Array.from([2]),Em(e),e)}function vd(r){let e=Uint8Array.from([0]),t=new fe(e,r);return new fe(Uint8Array.from([3]),Em(t),t)}function Rx(r){return new fe(Uint8Array.from([4]),Em(r),r)}function vo(r,e=48){let t=new fe;for(let n of r)t.append(n);return new fe(Uint8Array.from([e]),Em(t),t)}var Dx="1.2.840.10045.3.1.7",Nx="1.3.132.0.34",Lx="1.3.132.0.35";async function Bx(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function Mx(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Ux(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),i}var vB=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),xB=Uint8Array.from([6,5,43,129,4,0,34]),EB=Uint8Array.from([6,5,43,129,4,0,35]),Fx={ext:!0,kty:"EC",crv:"P-256"},$x={ext:!0,kty:"EC",crv:"P-384"},jx={ext:!0,kty:"EC",crv:"P-521"},ql=32,Wl=48,zl=66;function Kx(r){let e=Xn(r);return F6(e)}function F6(r){let e=r[1],t=j(e,"base64url"),n=r[2][1][0],o=1,i,s;if(e.byteLength===ql)return i=j(n.subarray(o,o+ql),"base64url"),s=j(n.subarray(o+ql),"base64url"),new Za({...Fx,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===Wl)return i=j(n.subarray(o,o+Wl),"base64url"),s=j(n.subarray(o+Wl),"base64url"),new Za({...$x,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===zl)return i=j(n.subarray(o,o+zl),"base64url"),s=j(n.subarray(o+zl),"base64url"),new Za({...jx,key_ops:["sign"],d:t,x:i,y:s});throw new P(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function $6(r){let e=Xn(r);return Vx(e)}function Vx(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===ql*2+1)return n=j(e.subarray(t,t+ql),"base64url"),o=j(e.subarray(t+ql),"base64url"),new Qa({...Fx,key_ops:["verify"],x:n,y:o});if(e.byteLength===Wl*2+1)return n=j(e.subarray(t,t+Wl),"base64url"),o=j(e.subarray(t+Wl),"base64url"),new Qa({...$x,key_ops:["verify"],x:n,y:o});if(e.byteLength===zl*2+1)return n=j(e.subarray(t,t+zl),"base64url"),o=j(e.subarray(t+zl),"base64url"),new Qa({...jx,key_ops:["verify"],x:n,y:o});throw new P(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Hx(r){return vo([zr(Uint8Array.from([1])),Rx(B(r.d??"","base64url")),vo([Wx(r.crv)],160),vo([vd(new fe(Uint8Array.from([4]),B(r.x??"","base64url"),B(r.y??"","base64url")))],161)]).subarray()}function qx(r){return vo([zr(Uint8Array.from([1])),vo([Wx(r.crv)],160),vo([vd(new fe(Uint8Array.from([4]),B(r.x??"","base64url"),B(r.y??"","base64url")))],161)]).subarray()}function Wx(r){if(r==="P-256")return vB;if(r==="P-384")return xB;if(r==="P-521")return EB;throw new P(`Invalid curve ${r}`)}async function zx(r="P-256"){let e=await Bx(r);return new Za(e.privateKey)}var Qa=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=qx(this.jwk)),this._raw}toMultihash(){return Dr.digest(sr(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}async verify(e,t,n){return Ux(this.jwk,t,e,n)}},Za=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Qa({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Hx(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}async sign(e,t){return Mx(this.jwk,e,t)}};function Ja(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Nr(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function Oe(r,e,t=""){let n=Ja(r),o=r?.length,i=e!==void 0;if(!n||i&&o!==e){let s=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return r}function Ni(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Nr(r.outputLen),Nr(r.blockLen)}function Gl(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Xx(r,e){Oe(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Lr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ec(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function xo(r,e){return r<<32-e|r>>>e}function Sm(r,e){return r<<e|r>>>32-e>>>0}var Yx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",SB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Li(r){if(Oe(r),Yx)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=SB[r[t]];return e}var Di={_0:48,_9:57,A:65,F:70,a:97,f:102};function Gx(r){if(r>=Di._0&&r<=Di._9)return r-Di._0;if(r>=Di.A&&r<=Di.F)return r-(Di.A-10);if(r>=Di.a&&r<=Di.f)return r-(Di.a-10)}function Bi(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Yx)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,i=0;o<t;o++,i+=2){let s=Gx(r.charCodeAt(i)),a=Gx(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}var _B=async()=>{};async function Qx(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-n;i>=0&&i<e||(await _B(),n+=i)}}function AB(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function j6(r,e=""){return typeof r=="string"?AB(r):Oe(r,void 0,e)}function cn(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Oe(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function Zx(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new Error("options must be object or undefined");return Object.assign(r,e)}function xd(r,e={}){let t=(o,i)=>r(i).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Zo(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var K6=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function _m(r,e,t){return r&e^~r&t}function Am(r,e,t){return r&e^r&t^e&t}var tc=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ec(this.buffer)}update(e){Gl(this),Oe(e);let{view:t,buffer:n,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=ec(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Gl(this),Xx(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[s++]=128,Lr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let u=s;u<o;u++)t[u]=0;n.setBigUint64(o-8,BigInt(this.length*8),i),this.process(n,0);let a=ec(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Mi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var pr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Tm=BigInt(4294967295),Jx=BigInt(32);function TB(r,e=!1){return e?{h:Number(r&Tm),l:Number(r>>Jx&Tm)}:{h:Number(r>>Jx&Tm)|0,l:Number(r&Tm)|0}}function eE(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let i=0;i<t;i++){let{h:s,l:a}=TB(r[i],e);[n[i],o[i]]=[s,a]}return[n,o]}var V6=(r,e,t)=>r>>>t,H6=(r,e,t)=>r<<32-t|e>>>t,rc=(r,e,t)=>r>>>t|e<<32-t,nc=(r,e,t)=>r<<32-t|e>>>t,Ed=(r,e,t)=>r<<64-t|e>>>t-32,Sd=(r,e,t)=>r>>>t-32|e<<64-t;function Jo(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var tE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),rE=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,nE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),oE=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,iE=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),sE=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var CB=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ds=new Uint32Array(64),q6=class extends tc{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Ds[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Ds[u-15],h=Ds[u-2],m=xo(d,7)^xo(d,18)^d>>>3,w=xo(h,17)^xo(h,19)^h>>>10;Ds[u]=w+Ds[u-7]+m+Ds[u-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){let d=xo(a,6)^xo(a,11)^xo(a,25),h=f+d+_m(a,c,l)+CB[u]+Ds[u]|0,w=(xo(n,2)^xo(n,13)^xo(n,22))+Am(n,o,i)|0;f=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(n,o,i,s,a,c,l,f)}roundClean(){Lr(Ds)}destroy(){this.set(0,0,0,0,0,0,0,0),Lr(this.buffer)}},W6=class extends q6{A=Mi[0]|0;B=Mi[1]|0;C=Mi[2]|0;D=Mi[3]|0;E=Mi[4]|0;F=Mi[5]|0;G=Mi[6]|0;H=Mi[7]|0;constructor(){super(32)}};var aE=eE(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),PB=aE[0],kB=aE[1],Ns=new Uint32Array(80),Ls=new Uint32Array(80),z6=class extends tc{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:f,Fh:u,Fl:d,Gh:h,Gl:m,Hh:w,Hl:y}=this;return[e,t,n,o,i,s,a,c,l,f,u,d,h,m,w,y]}set(e,t,n,o,i,s,a,c,l,f,u,d,h,m,w,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=f|0,this.Fh=u|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=w|0,this.Hl=y|0}process(e,t){for(let O=0;O<16;O++,t+=4)Ns[O]=e.getUint32(t),Ls[O]=e.getUint32(t+=4);for(let O=16;O<80;O++){let V=Ns[O-15]|0,Q=Ls[O-15]|0,Z=rc(V,Q,1)^rc(V,Q,8)^V6(V,Q,7),se=nc(V,Q,1)^nc(V,Q,8)^H6(V,Q,7),C=Ns[O-2]|0,T=Ls[O-2]|0,K=rc(C,T,19)^Ed(C,T,61)^V6(C,T,6),z=nc(C,T,19)^Sd(C,T,61)^H6(C,T,6),U=nE(se,z,Ls[O-7],Ls[O-16]),I=oE(U,Z,K,Ns[O-7],Ns[O-16]);Ns[O]=I|0,Ls[O]=U|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:h,Fl:m,Gh:w,Gl:y,Hh:b,Hl:N}=this;for(let O=0;O<80;O++){let V=rc(u,d,14)^rc(u,d,18)^Ed(u,d,41),Q=nc(u,d,14)^nc(u,d,18)^Sd(u,d,41),Z=u&h^~u&w,se=d&m^~d&y,C=iE(N,Q,se,kB[O],Ls[O]),T=sE(C,b,V,Z,PB[O],Ns[O]),K=C|0,z=rc(n,o,28)^Ed(n,o,34)^Ed(n,o,39),U=nc(n,o,28)^Sd(n,o,34)^Sd(n,o,39),I=n&i^n&a^i&a,S=o&s^o&c^s&c;b=w|0,N=y|0,w=h|0,y=m|0,h=u|0,m=d|0,{h:u,l:d}=Jo(l|0,f|0,T|0,K|0),l=a|0,f=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let x=tE(K,U,S);n=rE(x,T,z,I),o=x|0}({h:n,l:o}=Jo(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Jo(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Jo(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=Jo(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:d}=Jo(this.Eh|0,this.El|0,u|0,d|0),{h,l:m}=Jo(this.Fh|0,this.Fl|0,h|0,m|0),{h:w,l:y}=Jo(this.Gh|0,this.Gl|0,w|0,y|0),{h:b,l:N}=Jo(this.Hh|0,this.Hl|0,b|0,N|0),this.set(n,o,i,s,a,c,l,f,u,d,h,m,w,y,b,N)}roundClean(){Lr(Ns,Ls)}destroy(){Lr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},G6=class extends z6{Ah=pr[0]|0;Al=pr[1]|0;Bh=pr[2]|0;Bl=pr[3]|0;Ch=pr[4]|0;Cl=pr[5]|0;Dh=pr[6]|0;Dl=pr[7]|0;Eh=pr[8]|0;El=pr[9]|0;Fh=pr[10]|0;Fl=pr[11]|0;Gh=pr[12]|0;Gl=pr[13]|0;Hh=pr[14]|0;Hl=pr[15]|0;constructor(){super(64)}};var Yn=xd(()=>new W6,K6(1));var Bs=xd(()=>new G6,K6(3));var Y6=BigInt(0),X6=BigInt(1);function Ui(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function cE(r){if(typeof r=="bigint"){if(!Im(r))throw new Error("positive bigint expected, got "+r)}else Nr(r);return r}function _d(r){let e=cE(r).toString(16);return e.length&1?"0"+e:e}function lE(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Y6:BigInt("0x"+r)}function Xl(r){return lE(Li(r))}function ei(r){return lE(Li(oc(Oe(r)).reverse()))}function Cm(r,e){Nr(e),r=cE(r);let t=Bi(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Ad(r,e){return Cm(r,e).reverse()}function oc(r){return Uint8Array.from(r)}var Im=r=>typeof r=="bigint"&&Y6<=r;function OB(r,e,t){return Im(r)&&Im(e)&&Im(t)&&e<=r&&r<t}function Ms(r,e,t,n){if(!OB(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Q6(r){let e;for(e=0;r>Y6;r>>=X6,e+=1);return e}var Td=r=>(X6<<BigInt(r))-X6;function uE(r,e,t){if(Nr(r,"hashLen"),Nr(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),f=0,u=()=>{c.fill(1),l.fill(0),f=0},d=(...y)=>t(l,cn(c,...y)),h=(y=o)=>{l=d(i,y),c=d(),y.length!==0&&(l=d(s,y),c=d())},m=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,b=[];for(;y<e;){c=d();let N=c.slice();b.push(N),y+=c.length}return cn(...b)};return(y,b)=>{u(),h(y);let N;for(;!(N=b(m()));)h();return u(),N}}function ti(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(i,s,a){let c=r[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>n(a,c,s));o(e,!1),o(t,!0)}function Yl(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let i=r(t,...n);return e.set(t,i),i}}var Gr=BigInt(0),ar=BigInt(1),ic=BigInt(2),hE=BigInt(3),pE=BigInt(4),mE=BigInt(5),RB=BigInt(7),gE=BigInt(8),DB=BigInt(9),yE=BigInt(16);function Pt(r,e){let t=r%e;return t>=Gr?t:e+t}function _t(r,e,t){let n=r;for(;e-- >Gr;)n*=n,n%=t;return n}function fE(r,e){if(r===Gr)throw new Error("invert: expected non-zero number");if(e<=Gr)throw new Error("invert: expected positive modulus, got "+e);let t=Pt(r,e),n=e,o=Gr,i=ar,s=ar,a=Gr;for(;t!==Gr;){let l=n/t,f=n%t,u=o-s*l,d=i-a*l;n=t,t=f,o=s,i=a,s=u,a=d}if(n!==ar)throw new Error("invert: does not exist");return Pt(o,e)}function J6(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function wE(r,e){let t=(r.ORDER+ar)/pE,n=r.pow(e,t);return J6(r,n,e),n}function NB(r,e){let t=(r.ORDER-mE)/gE,n=r.mul(e,ic),o=r.pow(n,t),i=r.mul(e,o),s=r.mul(r.mul(i,ic),o),a=r.mul(i,r.sub(s,r.ONE));return J6(r,a,e),a}function LB(r){let e=Ql(r),t=bE(r),n=t(e,e.neg(e.ONE)),o=t(e,n),i=t(e,e.neg(n)),s=(r+RB)/yE;return(a,c)=>{let l=a.pow(c,s),f=a.mul(l,n),u=a.mul(l,o),d=a.mul(l,i),h=a.eql(a.sqr(f),c),m=a.eql(a.sqr(u),c);l=a.cmov(l,f,h),f=a.cmov(d,u,m);let w=a.eql(a.sqr(f),c),y=a.cmov(l,f,w);return J6(a,y,c),y}}function bE(r){if(r<hE)throw new Error("sqrt is not defined for small field");let e=r-ar,t=0;for(;e%ic===Gr;)e/=ic,t++;let n=ic,o=Ql(r);for(;dE(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return wE;let i=o.pow(n,e),s=(e+ar)/ic;return function(c,l){if(c.is0(l))return l;if(dE(c,l)!==1)throw new Error("Cannot find square root");let f=t,u=c.mul(c.ONE,i),d=c.pow(l,e),h=c.pow(l,s);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let m=1,w=c.sqr(d);for(;!c.eql(w,c.ONE);)if(m++,w=c.sqr(w),m===f)throw new Error("Cannot find square root");let y=ar<<BigInt(f-m-1),b=c.pow(u,y);f=m,u=c.sqr(b),d=c.mul(d,u),h=c.mul(h,b)}return h}}function BB(r){return r%pE===hE?wE:r%gE===mE?NB:r%yE===DB?LB(r):bE(r)}var vE=(r,e)=>(Pt(r,e)&ar)===ar,MB=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function e5(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=MB.reduce((n,o)=>(n[o]="function",n),e);return ti(r,t),r}function UB(r,e,t){if(t<Gr)throw new Error("invalid exponent, negatives unsupported");if(t===Gr)return r.ONE;if(t===ar)return e;let n=r.ONE,o=e;for(;t>Gr;)t&ar&&(n=r.mul(n,o)),o=r.sqr(o),t>>=ar;return n}function Id(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((s,a,c)=>r.is0(a)?s:(n[c]=s,r.mul(s,a)),r.ONE),i=r.inv(o);return e.reduceRight((s,a,c)=>r.is0(a)?s:(n[c]=r.mul(s,n[c]),r.mul(s,a)),i),n}function dE(r,e){let t=(r.ORDER-ar)/ic,n=r.pow(e,t),o=r.eql(n,r.ONE),i=r.eql(n,r.ZERO),s=r.eql(n,r.neg(r.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function FB(r,e){e!==void 0&&Nr(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var Z6=class{ORDER;BITS;BYTES;isLE;ZERO=Gr;ONE=ar;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Gr)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:i}=FB(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Pt(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Gr<=e&&e<this.ORDER}is0(e){return e===Gr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ar)===ar}neg(e){return Pt(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Pt(e*e,this.ORDER)}add(e,t){return Pt(e+t,this.ORDER)}sub(e,t){return Pt(e-t,this.ORDER)}mul(e,t){return Pt(e*t,this.ORDER)}pow(e,t){return UB(this,e,t)}div(e,t){return Pt(e*fE(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return fE(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=BB(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Ad(e,this.BYTES):Cm(e,this.BYTES)}fromBytes(e,t=!1){Oe(e);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?ei(e):Xl(e);if(a&&(c=Pt(c,s)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Id(this,e)}cmov(e,t,n){return n?t:e}};function Ql(r,e={}){return new Z6(r,e)}function xE(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function t5(r){let e=xE(r);return e+Math.ceil(e/2)}function r5(r,e,t=!1){Oe(r);let n=r.length,o=xE(e),i=t5(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=t?ei(r):Xl(r),a=Pt(s,e-ar)+ar;return t?Ad(a,o):Cm(a,o)}var Zl=BigInt(0),sc=BigInt(1);function Cd(r,e){let t=e.negate();return r?t:e}function ac(r,e){let t=Id(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function AE(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function n5(r,e){AE(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,i=Td(r),s=BigInt(r);return{windows:t,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function EE(r,e,t){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=t,a=Number(r&o),c=r>>s;a>n&&(a-=i,c+=sc);let l=e*n,f=l+Math.abs(a)-1,u=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:d,isNegF:h,offsetF:l}}var o5=new WeakMap,TE=new WeakMap;function i5(r){return TE.get(r)||1}function SE(r){if(r!==Zl)throw new Error("invalid wNAF")}var Jl=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Zl;)t&sc&&(n=n.add(o)),o=o.double(),t>>=sc;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=n5(t,this.bits),i=[],s=e,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=n5(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:f,isNeg:u,isNegF:d,offsetF:h}=EE(n,a,s);n=c,f?i=i.add(Cd(d,t[h])):o=o.add(Cd(u,t[l]))}return SE(n),{p:o,f:i}}wNAFUnsafe(e,t,n,o=this.ZERO){let i=n5(e,this.bits);for(let s=0;s<i.windows&&n!==Zl;s++){let{nextN:a,offset:c,isZero:l,isNeg:f}=EE(n,s,i);if(n=a,!l){let u=t[c];o=o.add(f?u.negate():u)}}return SE(n),o}getPrecomputes(e,t,n){let o=o5.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),o5.set(t,o))),o}cached(e,t,n){let o=i5(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let i=i5(e);return i===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,o)}createCache(e,t){AE(t,this.bits),TE.set(e,t),o5.delete(e)}hasCache(e){return i5(e)!==1}};function IE(r,e,t,n){let o=e,i=r.ZERO,s=r.ZERO;for(;t>Zl||n>Zl;)t&sc&&(i=i.add(o)),n&sc&&(s=s.add(o)),o=o.double(),t>>=sc,n>>=sc;return{p1:i,p2:s}}function _E(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return e5(e),e}else return Ql(r,{isLE:t})}function Pm(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Zl))throw new Error(`CURVE.${c} must be positive bigint`)}let o=_E(e.p,t.Fp,n),i=_E(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function eu(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Us=BigInt(0),cr=BigInt(1),s5=BigInt(2),$B=BigInt(8);function jB(r,e,t,n){let o=r.sqr(t),i=r.sqr(n),s=r.add(r.mul(e.a,o),i),a=r.add(r.ONE,r.mul(e.d,r.mul(o,i)));return r.eql(s,a)}function CE(r,e={}){let t=Pm("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,i=t.CURVE,{h:s}=i;ti(e,{},{uvRatio:"function"});let a=s5<<BigInt(o.BYTES*8)-cr,c=y=>n.create(y),l=e.uvRatio||((y,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,b))}}catch{return{isValid:!1,value:Us}}});if(!jB(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(y,b,N=!1){let O=N?cr:Us;return Ms("coordinate "+y,b,O,a),b}function u(y){if(!(y instanceof m))throw new Error("EdwardsPoint expected")}let d=Yl((y,b)=>{let{X:N,Y:O,Z:V}=y,Q=y.is0();b==null&&(b=Q?$B:n.inv(V));let Z=c(N*b),se=c(O*b),C=n.mul(V,b);if(Q)return{x:Us,y:cr};if(C!==cr)throw new Error("invZ was invalid");return{x:Z,y:se}}),h=Yl(y=>{let{a:b,d:N}=i;if(y.is0())throw new Error("bad point: ZERO");let{X:O,Y:V,Z:Q,T:Z}=y,se=c(O*O),C=c(V*V),T=c(Q*Q),K=c(T*T),z=c(se*b),U=c(T*c(z+C)),I=c(K+c(N*c(se*C)));if(U!==I)throw new Error("bad point: equation left != right (1)");let S=c(O*V),x=c(Q*Z);if(S!==x)throw new Error("bad point: equation left != right (2)");return!0});class m{static BASE=new m(i.Gx,i.Gy,cr,c(i.Gx*i.Gy));static ZERO=new m(Us,cr,cr,Us);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,N,O,V){this.X=f("x",b),this.Y=f("y",N),this.Z=f("z",O,!0),this.T=f("t",V),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){if(b instanceof m)throw new Error("extended point not allowed");let{x:N,y:O}=b||{};return f("x",N),f("y",O),new m(N,O,cr,c(N*O))}static fromBytes(b,N=!1){let O=n.BYTES,{a:V,d:Q}=i;b=oc(Oe(b,O,"point")),Ui(N,"zip215");let Z=oc(b),se=b[O-1];Z[O-1]=se&-129;let C=ei(Z),T=N?a:n.ORDER;Ms("point.y",C,Us,T);let K=c(C*C),z=c(K-cr),U=c(Q*K-V),{isValid:I,value:S}=l(z,U);if(!I)throw new Error("bad point: invalid y coordinate");let x=(S&cr)===cr,D=(se&128)!==0;if(!N&&S===Us&&D)throw new Error("bad point: x=0 and x_0=1");return D!==x&&(S=c(-S)),m.fromAffine({x:S,y:C})}static fromHex(b,N=!1){return m.fromBytes(Bi(b),N)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,N=!0){return w.createCache(this,b),N||this.multiply(s5),this}assertValidity(){h(this)}equals(b){u(b);let{X:N,Y:O,Z:V}=this,{X:Q,Y:Z,Z:se}=b,C=c(N*se),T=c(Q*V),K=c(O*se),z=c(Z*V);return C===T&&K===z}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=i,{X:N,Y:O,Z:V}=this,Q=c(N*N),Z=c(O*O),se=c(s5*c(V*V)),C=c(b*Q),T=N+O,K=c(c(T*T)-Q-Z),z=C+Z,U=z-se,I=C-Z,S=c(K*U),x=c(z*I),D=c(K*I),q=c(U*z);return new m(S,x,q,D)}add(b){u(b);let{a:N,d:O}=i,{X:V,Y:Q,Z,T:se}=this,{X:C,Y:T,Z:K,T:z}=b,U=c(V*C),I=c(Q*T),S=c(se*O*z),x=c(Z*K),D=c((V+Q)*(C+T)-U-I),q=x-S,H=x+S,M=c(I-N*U),G=c(D*q),te=c(H*M),F=c(D*M),Le=c(q*H);return new m(G,te,Le,F)}subtract(b){return this.add(b.negate())}multiply(b){if(!o.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:N,f:O}=w.cached(this,b,V=>ac(m,V));return ac(m,[N,O])[0]}multiplyUnsafe(b,N=m.ZERO){if(!o.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===Us?m.ZERO:this.is0()||b===cr?this:w.unsafe(this,b,O=>ac(m,O),N)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return w.unsafe(this,i.n).is0()}toAffine(b){return d(this,b)}clearCofactor(){return s===cr?this:this.multiplyUnsafe(s)}toBytes(){let{x:b,y:N}=this.toAffine(),O=n.toBytes(N);return O[O.length-1]|=b&cr?128:0,O}toHex(){return Li(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=new Jl(m,o.BITS);return m.BASE.precompute(8),m}function PE(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');ti(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:i,Fn:s}=r,a=t.randomBytes||Zo,c=t.adjustScalarBytes||(C=>C),l=t.domain||((C,T,K)=>{if(Ui(K,"phflag"),T.length||K)throw new Error("Contexts/pre-hash are not supported");return C});function f(C){return s.create(ei(C))}function u(C){let T=O.secretKey;Oe(C,O.secretKey,"secretKey");let K=Oe(e(C),2*T,"hashedSecretKey"),z=c(K.slice(0,T)),U=K.slice(T,2*T),I=f(z);return{head:z,prefix:U,scalar:I}}function d(C){let{head:T,prefix:K,scalar:z}=u(C),U=o.multiply(z),I=U.toBytes();return{head:T,prefix:K,scalar:z,point:U,pointBytes:I}}function h(C){return d(C).pointBytes}function m(C=Uint8Array.of(),...T){let K=cn(...T);return f(e(l(K,Oe(C,void 0,"context"),!!n)))}function w(C,T,K={}){C=Oe(C,void 0,"message"),n&&(C=n(C));let{prefix:z,scalar:U,pointBytes:I}=d(T),S=m(K.context,z,C),x=o.multiply(S).toBytes(),D=m(K.context,x,I,C),q=s.create(S+D*U);if(!s.isValid(q))throw new Error("sign failed: invalid s");let H=cn(x,s.toBytes(q));return Oe(H,O.signature,"result")}let y={zip215:!0};function b(C,T,K,z=y){let{context:U,zip215:I}=z,S=O.signature;C=Oe(C,S,"signature"),T=Oe(T,void 0,"message"),K=Oe(K,O.publicKey,"publicKey"),I!==void 0&&Ui(I,"zip215"),n&&(T=n(T));let x=S/2,D=C.subarray(0,x),q=ei(C.subarray(x,S)),H,M,G;try{H=r.fromBytes(K,I),M=r.fromBytes(D,I),G=o.multiplyUnsafe(q)}catch{return!1}if(!I&&H.isSmallOrder())return!1;let te=m(U,M.toBytes(),H.toBytes(),T);return M.add(H.multiplyUnsafe(te)).subtract(G).clearCofactor().is0()}let N=i.BYTES,O={secretKey:N,publicKey:N,signature:2*N,seed:N};function V(C=a(O.seed)){return Oe(C,O.seed,"seed")}function Q(C){return Ja(C)&&C.length===s.BYTES}function Z(C,T){try{return!!r.fromBytes(C,T)}catch{return!1}}let se={getExtendedPublicKey:d,randomSecretKey:V,isValidSecretKey:Q,isValidPublicKey:Z,toMontgomery(C){let{y:T}=r.fromBytes(C),K=O.publicKey,z=K===32;if(!z&&K!==57)throw new Error("only defined for 25519 and 448");let U=z?i.div(cr+T,cr-T):i.div(T-cr,T+cr);return i.toBytes(U)},toMontgomerySecret(C){let T=O.secretKey;Oe(C,T);let K=e(C.subarray(0,T));return c(K).subarray(0,T)}};return Object.freeze({keygen:eu(V,h),getPublicKey:h,sign:w,verify:b,utils:se,Point:r,lengths:O})}var Pd=BigInt(0),tu=BigInt(1),km=BigInt(2);function KB(r){return ti(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function kE(r){let e=KB(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:i,randomBytes:s}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=s||Zo,l=a?255:448,f=a?32:56,u=BigInt(a?9:5),d=BigInt(a?121665:39081),h=a?km**BigInt(254):km**BigInt(447),m=a?BigInt(8)*km**BigInt(251)-tu:BigInt(4)*km**BigInt(445)-tu,w=h+m+tu,y=S=>Pt(S,t),b=N(u);function N(S){return Ad(y(S),f)}function O(S){let x=oc(Oe(S,f,"uCoordinate"));return a&&(x[31]&=127),y(ei(x))}function V(S){return ei(o(oc(Oe(S,f,"scalar"))))}function Q(S,x){let D=K(O(x),V(S));if(D===Pd)throw new Error("invalid private or public key received");return N(D)}function Z(S){return Q(S,b)}let se=Z,C=Q;function T(S,x,D){let q=y(S*(x-D));return x=y(x-q),D=y(D+q),{x_2:x,x_3:D}}function K(S,x){Ms("u",S,Pd,t),Ms("scalar",x,h,w);let D=x,q=S,H=tu,M=Pd,G=S,te=tu,F=Pd;for(let Fe=BigInt(l-1);Fe>=Pd;Fe--){let me=D>>Fe&tu;F^=me,{x_2:H,x_3:G}=T(F,H,G),{x_2:M,x_3:te}=T(F,M,te),F=me;let He=H+M,ot=y(He*He),Ct=H-M,ze=y(Ct*Ct),it=ot-ze,Pi=G+te,mo=G-te,Is=y(mo*He),Z1=y(Pi*Ct),Nl=Is+Z1,rd=Is-Z1;G=y(Nl*Nl),te=y(q*y(rd*rd)),H=y(ot*ze),M=y(it*(ot+y(d*it)))}({x_2:H,x_3:G}=T(F,H,G)),{x_2:M,x_3:te}=T(F,M,te);let Le=i(M);return y(H*Le)}let z={secretKey:f,publicKey:f,seed:f},U=(S=c(f))=>(Oe(S,z.seed,"seed"),S),I={randomSecretKey:U};return Object.freeze({keygen:eu(U,se),getSharedSecret:C,getPublicKey:se,scalarMult:Q,scalarMultBase:Z,utils:I,GuBytes:b.slice(),lengths:z})}var VB=BigInt(1),OE=BigInt(2),HB=BigInt(3),qB=BigInt(5),WB=BigInt(8),Om=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),zB={p:Om,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:WB,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function DE(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),i=Om,a=r*r%i*r%i,c=_t(a,OE,i)*a%i,l=_t(c,VB,i)*r%i,f=_t(l,qB,i)*l%i,u=_t(f,e,i)*f%i,d=_t(u,t,i)*u%i,h=_t(d,n,i)*d%i,m=_t(h,o,i)*h%i,w=_t(m,o,i)*h%i,y=_t(w,e,i)*f%i;return{pow_p_5_8:_t(y,OE,i)*r%i,b2:a}}function NE(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var RE=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function GB(r,e){let t=Om,n=Pt(e*e*e,t),o=Pt(n*n*e,t),i=DE(r*o).pow_p_5_8,s=Pt(r*n*i,t),a=Pt(e*s*s,t),c=s,l=Pt(s*RE,t),f=a===r,u=a===Pt(-r,t),d=a===Pt(-r*RE,t);return f&&(s=c),(u||d)&&(s=l),vE(s,t)&&(s=Pt(-s,t)),{isValid:f||u,value:s}}var XB=CE(zB,{uvRatio:GB});function YB(r){return PE(XB,Bs,Object.assign({adjustScalarBytes:NE},r))}var kd=YB({});var Od=(()=>{let r=Om;return kE({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=DE(e);return Pt(_t(t,HB,r)*n,r)},adjustScalarBytes:NE})})();var cc=32,In=64,a5=32;var ru,LE=(async()=>{try{return await qt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function BE(){let r=kd.utils.randomSecretKey(),e=kd.getPublicKey(r);return{privateKey:tM(r,e),publicKey:e}}async function QB(r,e){let t;r.length===In?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:j(r.subarray(32),"base64url"),d:j(t,"base64url"),ext:!0,key_ops:["sign"]},o=await qt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await qt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(i,0,i.byteLength)}function ZB(r,e){let t=r.subarray(0,a5);return kd.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function ME(r,e){return ru==null&&(ru=await LE),ru?QB(r,e):ZB(r,e)}async function JB(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await qt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await qt.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function eM(r,e,t){return kd.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function UE(r,e,t){return ru==null&&(ru=await LE),ru?JB(r,e,t):eM(r,e,t)}function tM(r,e){let t=new Uint8Array(In);for(let n=0;n<a5;n++)t[n]=r[n],t[a5+n]=e[n];return t}function nu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Rd=class{type="Ed25519";raw;constructor(e){this.raw=iu(e,cc)}toMultihash(){return Dr.digest(sr(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=UE(this.raw,t,e);return nu(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}},ou=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=iu(e,In),this.publicKey=new Rd(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=ME(this.raw,e);return nu(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function c5(r){if(r.length>In){r=iu(r,In+cc);let n=r.subarray(0,In),o=r.subarray(In,r.length);return new ou(n,o)}r=iu(r,In);let e=r.subarray(0,In),t=r.subarray(cc);return new ou(e,t)}function l5(r){return r=iu(r,cc),new Rd(r)}async function $E(){let{privateKey:r,publicKey:e}=BE();return new ou(r,e)}function iu(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new P(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var rM=Math.pow(2,7),nM=Math.pow(2,14),oM=Math.pow(2,21),u5=Math.pow(2,28),f5=Math.pow(2,35),d5=Math.pow(2,42),h5=Math.pow(2,49),st=128,Br=127;function je(r){if(r<rM)return 1;if(r<nM)return 2;if(r<oM)return 3;if(r<u5)return 4;if(r<f5)return 5;if(r<d5)return 6;if(r<h5)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function su(r,e,t=0){switch(je(r)){case 8:e[t++]=r&255|st,r/=128;case 7:e[t++]=r&255|st,r/=128;case 6:e[t++]=r&255|st,r/=128;case 5:e[t++]=r&255|st,r/=128;case 4:e[t++]=r&255|st,r>>>=7;case 3:e[t++]=r&255|st,r>>>=7;case 2:e[t++]=r&255|st,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function iM(r,e,t=0){switch(je(r)){case 8:e.set(t++,r&255|st),r/=128;case 7:e.set(t++,r&255|st),r/=128;case 6:e.set(t++,r&255|st),r/=128;case 5:e.set(t++,r&255|st),r/=128;case 4:e.set(t++,r&255|st),r>>>=7;case 3:e.set(t++,r&255|st),r>>>=7;case 2:e.set(t++,r&255|st),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function p5(r,e){let t=r[e],n=0;if(n+=t&Br,t<st||(t=r[e+1],n+=(t&Br)<<7,t<st)||(t=r[e+2],n+=(t&Br)<<14,t<st)||(t=r[e+3],n+=(t&Br)<<21,t<st)||(t=r[e+4],n+=(t&Br)*u5,t<st)||(t=r[e+5],n+=(t&Br)*f5,t<st)||(t=r[e+6],n+=(t&Br)*d5,t<st)||(t=r[e+7],n+=(t&Br)*h5,t<st))return n;throw new RangeError("Could not decode varint")}function sM(r,e){let t=r.get(e),n=0;if(n+=t&Br,t<st||(t=r.get(e+1),n+=(t&Br)<<7,t<st)||(t=r.get(e+2),n+=(t&Br)<<14,t<st)||(t=r.get(e+3),n+=(t&Br)<<21,t<st)||(t=r.get(e+4),n+=(t&Br)*u5,t<st)||(t=r.get(e+5),n+=(t&Br)*f5,t<st)||(t=r.get(e+6),n+=(t&Br)*d5,t<st)||(t=r.get(e+7),n+=(t&Br)*h5,t<st))return n;throw new RangeError("Could not decode varint")}function Mr(r,e,t=0){return e==null&&(e=Ot(je(r))),e instanceof Uint8Array?su(r,e,t):iM(r,e,t)}function Cn(r,e=0){return r instanceof Uint8Array?p5(r,e):sM(r,e)}var m5=new Float32Array([-0]),Fs=new Uint8Array(m5.buffer);function jE(r,e,t){m5[0]=r,e[t]=Fs[0],e[t+1]=Fs[1],e[t+2]=Fs[2],e[t+3]=Fs[3]}function KE(r,e){return Fs[0]=r[e],Fs[1]=r[e+1],Fs[2]=r[e+2],Fs[3]=r[e+3],m5[0]}var g5=new Float64Array([-0]),Ur=new Uint8Array(g5.buffer);function VE(r,e,t){g5[0]=r,e[t]=Ur[0],e[t+1]=Ur[1],e[t+2]=Ur[2],e[t+3]=Ur[3],e[t+4]=Ur[4],e[t+5]=Ur[5],e[t+6]=Ur[6],e[t+7]=Ur[7]}function HE(r,e){return Ur[0]=r[e],Ur[1]=r[e+1],Ur[2]=r[e+2],Ur[3]=r[e+3],Ur[4]=r[e+4],Ur[5]=r[e+5],Ur[6]=r[e+6],Ur[7]=r[e+7],g5[0]}var aM=BigInt(Number.MAX_SAFE_INTEGER),cM=BigInt(Number.MIN_SAFE_INTEGER),Pn=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return lc;if(e<aM&&e>cM)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>qE&&(o=0n,++n>qE&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return lc;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):lc}},lc=new Pn(0,0);lc.toBigInt=function(){return 0n};lc.zzEncode=lc.zzDecode=function(){return this};lc.length=function(){return 1};var qE=4294967296n;function WE(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function zE(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function y5(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Eo(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Rm(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var w5=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Eo(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Eo(this,4);return Rm(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Eo(this,4);return Rm(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Eo(this,4);let e=KE(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Eo(this,4);let e=HE(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Eo(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return zE(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Eo(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Eo(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Pn(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Eo(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Eo(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Eo(this,8);let e=Rm(this.buf,this.pos+=4),t=Rm(this.buf,this.pos+=4);return new Pn(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=p5(this.buf,this.pos);return this.pos+=je(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function b5(r){return new w5(r instanceof Uint8Array?r:r.subarray())}function Ae(r,e,t){let n=b5(r);return e.decode(n,void 0,t)}function v5(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return Ot(s);o+s>e&&(n=Ot(e),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var uc=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function x5(){}var S5=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},lM=v5();function uM(r){return globalThis.Buffer!=null?Ot(r):lM(r)}var Nd=class{len;head;tail;states;constructor(){this.len=0,this.head=new uc(x5,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new uc(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new _5((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Dm,10,Pn.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Pn.fromBigInt(e);return this._push(Dm,t.length(),t)}uint64Number(e){return this._push(su,je(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Pn.fromBigInt(e).zzEncode();return this._push(Dm,t.length(),t)}sint64Number(e){let t=Pn.fromNumber(e).zzEncode();return this._push(Dm,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(E5,1,e?1:0)}fixed32(e){return this._push(Dd,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Pn.fromBigInt(e);return this._push(Dd,4,t.lo)._push(Dd,4,t.hi)}fixed64Number(e){let t=Pn.fromNumber(e);return this._push(Dd,4,t.lo)._push(Dd,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(jE,4,e)}double(e){return this._push(VE,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(E5,1,0):this.uint32(t)._push(dM,t,e)}string(e){let t=WE(e);return t!==0?this.uint32(t)._push(y5,t,e):this._push(E5,1,0)}fork(){return this.states=new S5(this),this.head=this.tail=new uc(x5,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new uc(x5,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=uM(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function E5(r,e,t){e[t]=r&255}function fM(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var _5=class extends uc{next;constructor(e,t){super(fM,e,t),this.next=void 0}};function Dm(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Dd(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function dM(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Nd.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(hM,e,r),this},Nd.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(pM,e,r),this});function hM(r,e,t){e.set(r,t)}function pM(r,e,t){r.length<40?y5(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(B(r),t)}function A5(){return new Nd}function Te(r,e){let t=A5();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var au;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(au||(au={}));function Nm(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function kt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,s){let a=e(i);s.int32(a)},n=function(i){let s=i.int32();return e(s)};return Nm("enum",au.VARINT,t,n)}function Ie(r,e){return Nm("message",au.LENGTH_DELIMITED,r,e)}var dt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Ld=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var wt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(wt||(wt={}));var T5;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(T5||(T5={}));(function(r){r.codec=()=>kt(T5)})(wt||(wt={}));var ri;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),wt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=wt.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(ri||(ri={}));var Bd;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),wt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=wt.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Bd||(Bd={}));function Xr(r){if(isNaN(r)||r<=0)throw new P("random bytes length must be a Number bigger than 0");return Zo(r)}var Ud={};Nt(Ud,{MAX_RSA_KEY_SIZE:()=>I5,generateRSAKeyPair:()=>B5,jwkToJWKKeyPair:()=>ZE,jwkToPkcs1:()=>wM,jwkToPkix:()=>O5,jwkToRSAPrivateKey:()=>L5,pkcs1MessageToJwk:()=>P5,pkcs1MessageToRSAPrivateKey:()=>Lm,pkcs1ToJwk:()=>yM,pkcs1ToRSAPrivateKey:()=>R5,pkixMessageToJwk:()=>k5,pkixMessageToRSAPublicKey:()=>N5,pkixToJwk:()=>bM,pkixToRSAPublicKey:()=>D5});var cu=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ud.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return he.createV1(114,this._multihash)}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,t,n){return QE(this.jwk,t,e,n)}},Md=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ud.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}sign(e,t){return YE(this.jwk,e,t)}};var I5=8192,C5=18,mM=1062,gM=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function yM(r){let e=Xn(r);return P5(e)}function P5(r){return{n:j(r[1],"base64url"),e:j(r[2],"base64url"),d:j(r[3],"base64url"),p:j(r[4],"base64url"),q:j(r[5],"base64url"),dp:j(r[6],"base64url"),dq:j(r[7],"base64url"),qi:j(r[8],"base64url"),kty:"RSA"}}function wM(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new P("JWK was missing components");return vo([zr(Uint8Array.from([0])),zr(B(r.n,"base64url")),zr(B(r.e,"base64url")),zr(B(r.d,"base64url")),zr(B(r.p,"base64url")),zr(B(r.q,"base64url")),zr(B(r.dp,"base64url")),zr(B(r.dq,"base64url")),zr(B(r.qi,"base64url"))]).subarray()}function bM(r){let e=Xn(r,{offset:0});return k5(e)}function k5(r){let e=Xn(r[1],{offset:0});return{kty:"RSA",n:j(e[0],"base64url"),e:j(e[1],"base64url")}}function O5(r){if(r.n==null||r.e==null)throw new P("JWK was missing components");return vo([gM,vd(vo([zr(B(r.n,"base64url")),zr(B(r.e,"base64url"))]))]).subarray()}function R5(r){let e=Xn(r);return Lm(e)}function Lm(r){let e=P5(r);return L5(e)}function D5(r,e){if(r.byteLength>=mM)throw new Oi("Key size is too large");let t=Xn(r,{offset:0});return N5(t,r,e)}function N5(r,e,t){let n=k5(r);if(t==null){let o=Yn(ri.encode({Type:wt.RSA,Data:e}));t=Wr(C5,o)}return new cu(n,t)}function L5(r){if(eS(r)>I5)throw new P("Key size is too large");let e=ZE(r),t=Yn(ri.encode({Type:wt.RSA,Data:O5(e.publicKey)})),n=Wr(C5,t);return new Md(e.privateKey,new cu(e.publicKey,n))}async function B5(r){if(r>I5)throw new P("Key size is too large");let e=await JE(r),t=Yn(ri.encode({Type:wt.RSA,Data:O5(e.publicKey)})),n=Wr(C5,t);return new Md(e.privateKey,new cu(e.publicKey,n))}function ZE(r){if(r==null)throw new P("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function JE(r,e){let t=await qt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await vM(t,e);return{privateKey:n[0],publicKey:n[1]}}async function YE(r,e,t){let n=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await qt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function QE(r,e,t,n){let o=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await qt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),i}async function vM(r,e){if(r.privateKey==null||r.publicKey==null)throw new P("Private and public key are required");let t=await Promise.all([qt.get().subtle.exportKey("jwk",r.privateKey),qt.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function eS(r){if(r.kty!=="RSA")throw new P("invalid key type");if(r.n==null)throw new P("invalid key modulus");return B(r.n,"base64url").length*8}var Bm=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Ni(e),Oe(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Lr(o)}update(e){return Gl(this),this.iHash.update(e),this}digestInto(e){Gl(this),Oe(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},$s=(r,e,t)=>new Bm(r,e).update(t).digest();$s.create=(r,e)=>new Bm(r,e);var tS=(r,e)=>(r+(r>=0?e:-e)/rS)/e;function xM(r,e,t){let[[n,o],[i,s]]=e,a=tS(s*r,t),c=tS(-o*r,t),l=r-a*n-c*i,f=-a*o-c*s,u=l<$i,d=f<$i;u&&(l=-l),d&&(f=-f);let h=Td(Math.ceil(Q6(t)/2))+lu;if(l<$i||l>=h||f<$i||f>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:l,k2neg:d,k2:f}}function U5(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function M5(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ui(t.lowS,"lowS"),Ui(t.prehash,"prehash"),t.format!==void 0&&U5(t.format),t}var F5=class extends Error{constructor(e=""){super(e)}},js={Err:F5,_tlv:{encode:(r,e)=>{let{Err:t}=js;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=_d(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?_d(o.length/2|128):"";return _d(r)+i+o+e},decode(r,e){let{Err:t}=js,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of l)s=s<<8|f;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=js;if(r<$i)throw new e("integer: negative integers are not allowed");let t=_d(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=js;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Xl(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=js,o=Oe(r,void 0,"signature"),{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:f}=n.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=js,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),i=n+o;return e.encode(48,i)}},$i=BigInt(0),lu=BigInt(1),rS=BigInt(2),Mm=BigInt(3),EM=BigInt(4);function nS(r,e={}){let t=Pm("weierstrass",r,e),{Fp:n,Fn:o}=t,i=t.CURVE,{h:s,n:a}=i;ti(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=iS(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(U,I,S){let{x,y:D}=I.toAffine(),q=n.toBytes(x);if(Ui(S,"isCompressed"),S){f();let H=!n.isOdd(D);return cn(oS(H),q)}else return cn(Uint8Array.of(4),q,n.toBytes(D))}function d(U){Oe(U,void 0,"Point");let{publicKey:I,publicKeyUncompressed:S}=l,x=U.length,D=U[0],q=U.subarray(1);if(x===I&&(D===2||D===3)){let H=n.fromBytes(q);if(!n.isValid(H))throw new Error("bad point: is not on curve, wrong x");let M=w(H),G;try{G=n.sqrt(M)}catch(Le){let Fe=Le instanceof Error?": "+Le.message:"";throw new Error("bad point: is not on curve, sqrt error"+Fe)}f();let te=n.isOdd(G);return(D&1)===1!==te&&(G=n.neg(G)),{x:H,y:G}}else if(x===S&&D===4){let H=n.BYTES,M=n.fromBytes(q.subarray(0,H)),G=n.fromBytes(q.subarray(H,H*2));if(!y(M,G))throw new Error("bad point: is not on curve");return{x:M,y:G}}else throw new Error(`bad point: got length ${x}, expected compressed=${I} or uncompressed=${S}`)}let h=e.toBytes||u,m=e.fromBytes||d;function w(U){let I=n.sqr(U),S=n.mul(I,U);return n.add(n.add(S,n.mul(U,i.a)),i.b)}function y(U,I){let S=n.sqr(I),x=w(U);return n.eql(S,x)}if(!y(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(i.a,Mm),EM),N=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(b,N)))throw new Error("bad curve params: a or b");function O(U,I,S=!1){if(!n.isValid(I)||S&&n.is0(I))throw new Error(`bad point coordinate ${U}`);return I}function V(U){if(!(U instanceof T))throw new Error("Weierstrass Point expected")}function Q(U){if(!c||!c.basises)throw new Error("no endo");return xM(U,c.basises,o.ORDER)}let Z=Yl((U,I)=>{let{X:S,Y:x,Z:D}=U;if(n.eql(D,n.ONE))return{x:S,y:x};let q=U.is0();I==null&&(I=q?n.ONE:n.inv(D));let H=n.mul(S,I),M=n.mul(x,I),G=n.mul(D,I);if(q)return{x:n.ZERO,y:n.ZERO};if(!n.eql(G,n.ONE))throw new Error("invZ was invalid");return{x:H,y:M}}),se=Yl(U=>{if(U.is0()){if(e.allowInfinityPoint&&!n.is0(U.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:S}=U.toAffine();if(!n.isValid(I)||!n.isValid(S))throw new Error("bad point: x or y not field elements");if(!y(I,S))throw new Error("bad point: equation left != right");if(!U.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function C(U,I,S,x,D){return S=new T(n.mul(S.X,U),S.Y,S.Z),I=Cd(x,I),S=Cd(D,S),I.add(S)}class T{static BASE=new T(i.Gx,i.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(I,S,x){this.X=O("x",I),this.Y=O("y",S,!0),this.Z=O("z",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(I){let{x:S,y:x}=I||{};if(!I||!n.isValid(S)||!n.isValid(x))throw new Error("invalid affine point");if(I instanceof T)throw new Error("projective point not allowed");return n.is0(S)&&n.is0(x)?T.ZERO:new T(S,x,n.ONE)}static fromBytes(I){let S=T.fromAffine(m(Oe(I,void 0,"point")));return S.assertValidity(),S}static fromHex(I){return T.fromBytes(Bi(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,S=!0){return z.createCache(this,I),S||this.multiply(Mm),this}assertValidity(){se(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){V(I);let{X:S,Y:x,Z:D}=this,{X:q,Y:H,Z:M}=I,G=n.eql(n.mul(S,M),n.mul(q,D)),te=n.eql(n.mul(x,M),n.mul(H,D));return G&&te}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:S}=i,x=n.mul(S,Mm),{X:D,Y:q,Z:H}=this,M=n.ZERO,G=n.ZERO,te=n.ZERO,F=n.mul(D,D),Le=n.mul(q,q),Fe=n.mul(H,H),me=n.mul(D,q);return me=n.add(me,me),te=n.mul(D,H),te=n.add(te,te),M=n.mul(I,te),G=n.mul(x,Fe),G=n.add(M,G),M=n.sub(Le,G),G=n.add(Le,G),G=n.mul(M,G),M=n.mul(me,M),te=n.mul(x,te),Fe=n.mul(I,Fe),me=n.sub(F,Fe),me=n.mul(I,me),me=n.add(me,te),te=n.add(F,F),F=n.add(te,F),F=n.add(F,Fe),F=n.mul(F,me),G=n.add(G,F),Fe=n.mul(q,H),Fe=n.add(Fe,Fe),F=n.mul(Fe,me),M=n.sub(M,F),te=n.mul(Fe,Le),te=n.add(te,te),te=n.add(te,te),new T(M,G,te)}add(I){V(I);let{X:S,Y:x,Z:D}=this,{X:q,Y:H,Z:M}=I,G=n.ZERO,te=n.ZERO,F=n.ZERO,Le=i.a,Fe=n.mul(i.b,Mm),me=n.mul(S,q),He=n.mul(x,H),ot=n.mul(D,M),Ct=n.add(S,x),ze=n.add(q,H);Ct=n.mul(Ct,ze),ze=n.add(me,He),Ct=n.sub(Ct,ze),ze=n.add(S,D);let it=n.add(q,M);return ze=n.mul(ze,it),it=n.add(me,ot),ze=n.sub(ze,it),it=n.add(x,D),G=n.add(H,M),it=n.mul(it,G),G=n.add(He,ot),it=n.sub(it,G),F=n.mul(Le,ze),G=n.mul(Fe,ot),F=n.add(G,F),G=n.sub(He,F),F=n.add(He,F),te=n.mul(G,F),He=n.add(me,me),He=n.add(He,me),ot=n.mul(Le,ot),ze=n.mul(Fe,ze),He=n.add(He,ot),ot=n.sub(me,ot),ot=n.mul(Le,ot),ze=n.add(ze,ot),me=n.mul(He,ze),te=n.add(te,me),me=n.mul(it,ze),G=n.mul(Ct,G),G=n.sub(G,me),me=n.mul(Ct,He),F=n.mul(it,F),F=n.add(F,me),new T(G,te,F)}subtract(I){return this.add(I.negate())}is0(){return this.equals(T.ZERO)}multiply(I){let{endo:S}=e;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let x,D,q=H=>z.cached(this,H,M=>ac(T,M));if(S){let{k1neg:H,k1:M,k2neg:G,k2:te}=Q(I),{p:F,f:Le}=q(M),{p:Fe,f:me}=q(te);D=Le.add(me),x=C(S.beta,F,Fe,H,G)}else{let{p:H,f:M}=q(I);x=H,D=M}return ac(T,[x,D])[0]}multiplyUnsafe(I){let{endo:S}=e,x=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===$i||x.is0())return T.ZERO;if(I===lu)return x;if(z.hasCache(this))return this.multiply(I);if(S){let{k1neg:D,k1:q,k2neg:H,k2:M}=Q(I),{p1:G,p2:te}=IE(T,x,q,M);return C(S.beta,G,te,D,H)}else return z.unsafe(x,I)}toAffine(I){return Z(this,I)}isTorsionFree(){let{isTorsionFree:I}=e;return s===lu?!0:I?I(T,this):z.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return s===lu?this:I?I(T,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(I=!0){return Ui(I,"isCompressed"),this.assertValidity(),h(T,this,I)}toHex(I=!0){return Li(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let K=o.BITS,z=new Jl(T,e.endo?Math.ceil(K/2):K);return T.BASE.precompute(8),T}function oS(r){return Uint8Array.of(r?2:3)}function iS(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function SM(r,e={}){let{Fn:t}=r,n=e.randomBytes||Zo,o=Object.assign(iS(r.Fp,t),{seed:t5(t.ORDER)});function i(h){try{let m=t.fromBytes(h);return t.isValidNot0(m)}catch{return!1}}function s(h,m){let{publicKey:w,publicKeyUncompressed:y}=o;try{let b=h.length;return m===!0&&b!==w||m===!1&&b!==y?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return r5(Oe(h,o.seed,"seed"),t.ORDER)}function c(h,m=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(m)}function l(h){let{secretKey:m,publicKey:w,publicKeyUncompressed:y}=o;if(!Ja(h)||"_lengths"in t&&t._lengths||m===w)return;let b=Oe(h,void 0,"key").length;return b===w||b===y}function f(h,m,w=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(h);return r.fromBytes(m).multiply(y).toBytes(w)}let u={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},d=eu(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:u,lengths:o})}function sS(r,e,t={}){Ni(e),ti(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Zo,o=t.hmac||((S,x)=>$s(e,S,x)),{Fp:i,Fn:s}=r,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h}=SM(r,t),m={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},w=a*rS<i.ORDER;function y(S){let x=a>>lu;return S>x}function b(S,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return x}function N(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(S,x){U5(x);let D=h.signature,q=x==="compact"?D:x==="recovered"?D+1:void 0;return Oe(S,q)}class V{r;s;recovery;constructor(x,D,q){if(this.r=b("r",x),this.s=b("s",D),q!=null){if(N(),![0,1,2,3].includes(q))throw new Error("invalid recovery id");this.recovery=q}Object.freeze(this)}static fromBytes(x,D=m.format){O(x,D);let q;if(D==="der"){let{r:te,s:F}=js.toSig(Oe(x));return new V(te,F)}D==="recovered"&&(q=x[0],D="compact",x=x.subarray(1));let H=h.signature/2,M=x.subarray(0,H),G=x.subarray(H,H*2);return new V(s.fromBytes(M),s.fromBytes(G),q)}static fromHex(x,D){return this.fromBytes(Bi(x),D)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new V(this.r,this.s,x)}recoverPublicKey(x){let{r:D,s:q}=this,H=this.assertRecovery(),M=H===2||H===3?D+a:D;if(!i.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let G=i.toBytes(M),te=r.fromBytes(cn(oS((H&1)===0),G)),F=s.inv(M),Le=Z(Oe(x,void 0,"msgHash")),Fe=s.create(-Le*F),me=s.create(q*F),He=r.BASE.multiplyUnsafe(Fe).add(te.multiplyUnsafe(me));if(He.is0())throw new Error("invalid recovery: point at infinify");return He.assertValidity(),He}hasHighS(){return y(this.s)}toBytes(x=m.format){if(U5(x),x==="der")return Bi(js.hexFromSig(this));let{r:D,s:q}=this,H=s.toBytes(D),M=s.toBytes(q);return x==="recovered"?(N(),cn(Uint8Array.of(this.assertRecovery()),H,M)):cn(H,M)}toHex(x){return Li(this.toBytes(x))}}let Q=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let D=Xl(x),q=x.length*8-c;return q>0?D>>BigInt(q):D},Z=t.bits2int_modN||function(x){return s.create(Q(x))},se=Td(c);function C(S){return Ms("num < 2^"+c,S,$i,se),s.toBytes(S)}function T(S,x){return Oe(S,void 0,"message"),x?Oe(e(S),void 0,"prehashed message"):S}function K(S,x,D){let{lowS:q,prehash:H,extraEntropy:M}=M5(D,m);S=T(S,H);let G=Z(S),te=s.fromBytes(x);if(!s.isValidNot0(te))throw new Error("invalid private key");let F=[C(te),C(G)];if(M!=null&&M!==!1){let He=M===!0?n(h.secretKey):M;F.push(Oe(He,void 0,"extraEntropy"))}let Le=cn(...F),Fe=G;function me(He){let ot=Q(He);if(!s.isValidNot0(ot))return;let Ct=s.inv(ot),ze=r.BASE.multiply(ot).toAffine(),it=s.create(ze.x);if(it===$i)return;let Pi=s.create(Ct*s.create(Fe+it*te));if(Pi===$i)return;let mo=(ze.x===it?0:2)|Number(ze.y&lu),Is=Pi;return q&&y(Pi)&&(Is=s.neg(Pi),mo^=1),new V(it,Is,w?void 0:mo)}return{seed:Le,k2sig:me}}function z(S,x,D={}){let{seed:q,k2sig:H}=K(S,x,D);return uE(e.outputLen,s.BYTES,o)(q,H).toBytes(D.format)}function U(S,x,D,q={}){let{lowS:H,prehash:M,format:G}=M5(q,m);if(D=Oe(D,void 0,"publicKey"),x=T(x,M),!Ja(S)){let te=S instanceof V?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+te)}O(S,G);try{let te=V.fromBytes(S,G),F=r.fromBytes(D);if(H&&te.hasHighS())return!1;let{r:Le,s:Fe}=te,me=Z(x),He=s.inv(Fe),ot=s.create(me*He),Ct=s.create(Le*He),ze=r.BASE.multiplyUnsafe(ot).add(F.multiplyUnsafe(Ct));return ze.is0()?!1:s.create(ze.x)===Le}catch{return!1}}function I(S,x,D={}){let{prehash:q}=M5(D,m);return x=T(x,q),V.fromBytes(S,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h,Point:r,sign:z,verify:U,recoverPublicKey:I,Signature:V,hash:e})}var j5={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},_M={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var aS=BigInt(2);function AM(r){let e=j5.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,f=l*l*r%e,u=_t(f,t,e)*f%e,d=_t(u,t,e)*f%e,h=_t(d,aS,e)*l%e,m=_t(h,o,e)*h%e,w=_t(m,i,e)*m%e,y=_t(w,a,e)*w%e,b=_t(y,c,e)*y%e,N=_t(b,a,e)*w%e,O=_t(N,t,e)*f%e,V=_t(O,s,e)*m%e,Q=_t(V,n,e)*l%e,Z=_t(Q,aS,e);if(!$5.eql($5.sqr(Z),r))throw new Error("Cannot find square root");return Z}var $5=Ql(j5.p,{sqrt:AM}),TM=nS(j5,{Fp:$5,endo:_M}),So=sS(TM,Yn);var cS=32;function lS(r,e,t){let n=St.digest(e instanceof Uint8Array?e:e.subarray());if(nu(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),So.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new gd(String(o))});try{return So.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new gd(String(o))}}function uS(r,e,t,n){let o=St.digest(t instanceof Uint8Array?t:t.subarray());if(nu(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),So.verify(e,i,r,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new yd(String(i))});try{return n?.signal?.throwIfAborted(),So.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(i){throw new yd(String(i))}}var Fd=class{type="secp256k1";raw;_key;constructor(e){this._key=hS(e),this.raw=fS(this._key)}toMultihash(){return Dr.digest(sr(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,t,n){return uS(this._key,t,e,n)}},$d=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=dS(e),this.publicKey=new Fd(t??pS(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}sign(e,t){return lS(this.raw,e,t)}};function K5(r){return new $d(r)}function V5(r){return new Fd(r)}async function mS(){let r=IM();return new $d(r)}function fS(r){return So.Point.fromBytes(r).toBytes()}function dS(r){try{return So.getPublicKey(r,!0),r}catch(e){throw new od(String(e))}}function hS(r){try{return So.Point.fromBytes(r),r}catch(e){throw new Oi(String(e))}}function pS(r){try{return So.getPublicKey(r,!0)}catch(e){throw new od(String(e))}}function IM(){return So.utils.randomSecretKey()}async function uu(r,e){if(r==="Ed25519")return $E();if(r==="secp256k1")return mS();if(r==="RSA")return B5(CM(e));if(r==="ECDSA")return zx(PM(e));throw new wo}function Kt(r,e){let{Type:t,Data:n}=ri.decode(r),o=n??new Uint8Array;switch(t){case wt.RSA:return D5(o,e);case wt.Ed25519:return l5(o);case wt.secp256k1:return V5(o);case wt.ECDSA:return $6(o);default:throw new wo}}function Um(r){let{Type:e,Data:t}=ri.decode(r.digest),n=t??new Uint8Array;switch(e){case wt.Ed25519:return l5(n);case wt.secp256k1:return V5(n);case wt.ECDSA:return $6(n);default:throw new wo}}function sr(r){return ri.encode({Type:wt[r.type],Data:r.raw})}function gS(r){let e=Bd.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case wt.RSA:return R5(t);case wt.Ed25519:return c5(t);case wt.secp256k1:return K5(t);case wt.ECDSA:return Kx(t);default:throw new wo}}function yS(r){if(r.byteLength===In)return c5(r);if(r.byteLength===cS)return K5(r);let e=Xn(r),t=e[2]?.[0];if(t===Dx||t===Nx||t===Lx)return F6(e);if(e.length>8)return Lm(e);throw new P("Could not extract private key from raw bytes")}function fc(r){return Bd.encode({Type:wt[r.type],Data:r.raw})}function CM(r){return r==null?2048:parseInt(r,10)}function PM(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new P("Unsupported curve, should be P-256, P-384 or P-521")}async function Fm(r){if(r.type==="RSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])};if(r.type==="ECDSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"ECDSA",namedCurve:r.jwk.crv??"P-256"},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"ECDSA",namedCurve:r.publicKey.jwk.crv??"P-256"},!0,["verify"])};throw new P("Only RSA and ECDSA keys are supported")}var jd=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ks=new Uint32Array(80),H5=class extends tc{A=jd[0]|0;B=jd[1]|0;C=jd[2]|0;D=jd[3]|0;E=jd[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ks[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ks[c]=Sm(Ks[c-3]^Ks[c-8]^Ks[c-14]^Ks[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,f;c<20?(l=_m(o,i,s),f=1518500249):c<40?(l=o^i^s,f=1859775393):c<60?(l=Am(o,i,s),f=2400959708):(l=o^i^s,f=3395469782);let u=Sm(n,5)+l+a+f+Ks[c]|0;a=s,s=i,i=Sm(o,30),o=n,n=u}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){Lr(Ks)}destroy(){this.set(0,0,0,0,0),Lr(this.buffer)}},wS=xd(()=>new H5);function bS(r,e,t,n){Ni(r);let o=Zx({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(Nr(i,"c"),Nr(s,"dkLen"),Nr(a,"asyncTick"),i<1)throw new Error("iterations (c) must be >= 1");let c=j6(e,"password"),l=j6(t,"salt"),f=new Uint8Array(s),u=$s.create(r,c),d=u._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:f,PRF:u,PRFSalt:d}}function vS(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),Lr(o),t}function xS(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=bS(r,e,t,n),l,f=new Uint8Array(4),u=ec(f),d=new Uint8Array(a.outputLen);for(let h=1,m=0;m<i;h++,m+=a.outputLen){let w=s.subarray(m,m+a.outputLen);u.setInt32(0,h,!1),(l=c._cloneInto(l)).update(f).digestInto(d),w.set(d.subarray(0,w.length));for(let y=1;y<o;y++){a._cloneInto(l).update(d).digestInto(d);for(let b=0;b<w.length;b++)w[b]^=d[b]}}return vS(a,c,s,l,d)}async function $m(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=bS(r,e,t,n),f,u=new Uint8Array(4),d=ec(u),h=new Uint8Array(c.outputLen);for(let m=1,w=0;w<i;m++,w+=c.outputLen){let y=a.subarray(w,w+c.outputLen);d.setInt32(0,m,!1),(f=l._cloneInto(f)).update(u).digestInto(h),y.set(h.subarray(0,y.length)),await Qx(o-1,s,()=>{c._cloneInto(f).update(h).digestInto(h);for(let b=0;b<y.length;b++)y[b]^=h[b]})}return vS(c,l,a,f,h)}var ES={sha1:wS,"sha2-256":Yn,"sha2-512":Bs};function Kd(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(ES).join(" / ");throw new P(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=ES[o],s=xS(i,r,e,{c:t,dkLen:n});return Ht.encode(s).substring(1)}var q5={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},SS={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},_S=new globalThis.TextEncoder;function kM(r,e){let t=q5[e],n=SS[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function OM(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=q5[e],o=SS[e],i=r;for(;i.length>0;){let s=_S.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function W5(r,{size:e=32,utf8Buffer:t}={}){if(!q5[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return OM(r,e,t);r=_S.encode(r)}return kM(r,e)}var Vd={hash:r=>Number(W5(r,{size:32})),hashV:(r,e)=>RM(Vd.hash(r,e))};function RM(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),B(e,"base16")}var z5=64,_o=class{fp;h;seed;constructor(e,t,n,o=2){if(o>z5)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=ke(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?we(this.fp,e.fp):!1}};function dc(r,e){return Math.floor(Math.random()*(e-r))+r}var hc=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof _o))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof _o))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof _o))throw new TypeError("Invalid Fingerprint");let t=dc(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof _o))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var DM=500,Hd=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??Vd,this.seed=e.seed??dc(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=B(e));let t=new _o(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new hc(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new hc(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[dc(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new hc(this.bucketSize));for(let a=0;a<DM;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new hc(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=B(e));let t=new _o(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=B(e));let t=new _o(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},NM={1:.5,2:.84,4:.95,8:.98};function LM(r=.001){return r>.002?2:r>1e-5?4:8}function AS(r,e=.001){let t=LM(e),n=NM[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),z5);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var jm=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Vd,this.seed=e.seed??dc(0,Math.pow(2,10)),this.filterSeries=[new Hd({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=B(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Hd({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=B(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=B(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Fr(r,e=.001,t){return new jm({...AS(r,e),...t??{}})}function Ce(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new P(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var Km=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let d=Number.parseInt(u,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(i*=e,i+=f,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var TS=45,BM=15,fu=new Km;function Vm(r){if(!(r.length>BM))return fu.new(r).parseWith(()=>fu.readIPv4Addr())}function Hm(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>TS))return fu.new(r).parseWith(()=>fu.readIPv6Addr())}function du(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>TS)return;let t=fu.new(r).parseWith(()=>fu.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function IS(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function CS(r,e,t,n){let o=0;for(let i of r)if(!(o<t)){if(o>n)break;if(i!==e[o])return!1;o++}return!0}function G5(r){switch(r.length){case pc:return r.join(".");case mc:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function PS(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function kS(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var pc=4,mc=16,UJ=parseInt("0xFFFF",16),MM=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function qd(r,e){e.length===mc&&r.length===pc&&IS(e,0,11)&&(e=e.slice(12)),e.length===pc&&r.length===mc&&CS(r,MM,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function OS(r,e){if(typeof e=="string"&&(e=du(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function X5(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=pc,o=Vm(e);if(o==null&&(n=mc,o=Hm(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=Y5(i,8*n);return{network:qd(o,s),mask:s}}function Y5(r,e){if(e!==8*pc&&e!==8*mc)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var gc=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=X5(e));else{let n=du(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let i=du(t);if(i==null)throw new Error("Failed to parse mask");this.mask=i}else this.mask=Y5(o,8*n.length);this.network=qd(n,this.mask)}}contains(e){return OS({network:this.network,mask:this.mask},e)}toString(){let e=PS(this.mask),t=e!==-1?String(e):kS(this.mask);return G5(this.network)+"/"+t}};function RS(r,e){return new gc(r).contains(e)}function qm(r){try{let e=Ce(r);switch(e.type){case"ip6":return RS("2000::/3",e.host);default:return!1}}catch{return!1}}function DS(r){try{let e=Ce(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function NS(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Wd(r){try{let e=Ce(r);switch(e.type){case"ip4":case"ip6":return NS(e.host);default:return!1}}catch{return!1}}function mr(r){try{return Ce(r),!0}catch{return!1}}function Ao(r){return!!Vm(r)}function Wm(r){return!!Hm(r)}var BS=nr(LS(),1),UM=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],FM=UM.map(r=>new BS.Netmask(r));function Q5(r){for(let e of FM)if(e.contains(r))return!0;return!1}function $M(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function jM(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Q5(o)}function KM(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function VM(r){let e=r.split(":"),t=e[e.length-1];return Q5(t)}function HM(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function hu(r){if(Ao(r))return Q5(r);if($M(r))return jM(r);if(KM(r))return VM(r);if(Wm(r))return HM(r)}function Mt(r){try{let e=Ce(r);switch(e.type){case"ip4":case"ip6":return hu(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function Ve(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var zm=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},pu=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new zm(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new zm(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Z5=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function gr(r={}){return qM(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function qM(r,e){e=e??{};let t=e.onEnd,n=new pu,o,i,s,a=Ve(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,b)=>{i=N=>{i=null,n.push(N);try{y(r(n))}catch(O){b(O)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ve()})}},l=y=>i!=null?i(y):(n.push(y),o),f=y=>(n=new pu,i!=null?i({error:y}):(n.push({error:y}),o)),u=y=>{if(s)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},d=y=>s?o:(s=!0,y!=null?f(y):l({done:!0})),h=()=>(n=new pu,d(),{done:!0}),m=y=>(d(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:u,end:d,get readableLength(){return n.size},onEmpty:async y=>{let b=y?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let N,O;b!=null&&(N=new Promise((V,Q)=>{O=()=>{Q(new Z5)},b.addEventListener("abort",O)}));try{await Promise.race([a.promise,N])}finally{O!=null&&b!=null&&b?.removeEventListener("abort",O)}}},t==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(y){return w.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return w.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return w.readableLength},onEmpty:y=>w.onEmpty(y)},o}var J5=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},e8=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},MS=r=>globalThis.DOMException===void 0?new e8(r):new DOMException(r),US=r=>{let e=r.reason===void 0?MS("This operation was aborted."):r.reason;return e instanceof Error?e:MS(e)};function t8(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(US(h)),a=()=>{u(US(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let d=new J5;s=i.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?u(o):(d.message=o??`Promise timed out after ${t} milliseconds`,u(d))},t),(async()=>{try{f(await r)}catch(h){u(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},l}var WM=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function zM(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=WM(r),u=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(w){n(),s(w);return}c.push(m),t.count===c.length&&(n(),i(c))},d=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)l(h,u);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=t8(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function Qn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=zM(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function ji(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 Gm=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Xm=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},yc=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Ym=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Qm=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function GM(r){return r.reason}async function ut(r,e,t){if(e==null)return r;let n=t?.translateError??GM;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Zm=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Ve(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Hr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function XM(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Jm=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=XM(),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 Hr),this.cleanup())}async join(e={}){let t=new Zm(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 ut(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var yr=class extends _e{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=ji(this.emitEmpty.bind(this),1),this.emitIdle=ji(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Xm;let n=new Jm(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Hr)}),this.clear()}async onEmpty(e){this.size!==0&&await Qn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Qn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Qn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=gr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new Hr("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var YM=Math.pow(2,20)*4,Vs=class extends _e{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??YM,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new fe,this.writeBuffer=new fe,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new Qm)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),ut(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=gr(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let n=i=>{e.end(i.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Go(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new im(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Go("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Go("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Go(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Go(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Bl;this.dispatchEvent(new sm(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new ks))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let i=this.writeBuffer.sublist(0,o),s=new fe(i);this.writeBuffer.consume(i.byteLength);let a=this.sendData(i);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==s.byteLength&&(s.consume(a.sentBytes),this.writeBuffer.prepend(s)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new om(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new sd(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new sd(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var Hs=class extends Vs{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Qn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Qn(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function e0(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var qs=class extends _e{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=s=>{try{this.onData(s.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await ut(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new yo;let t=this.onCreateStream({...this.streamOptions,...e});return e0(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Ym(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let o=this.streams.findIndex(i=>i===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var Ws=class extends Vs{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Qn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Qn(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function De(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var mu=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,i=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var QM=1.2,ZM=2,JM=5e3,eU=6e4,tU=5e3,To=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??tU;this.success=new mu(t),this.failure=new mu(t),this.next=new mu(t),this.failureMultiplier=e.failureMultiplier??ZM,this.timeoutMultiplier=e.timeoutMultiplier??QM,this.minTimeout=e.minTimeout??JM,this.maxTimeout=e.maxTimeout??eU,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=De([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var wr=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ki=class extends Error{static name="ValidationError";name="ValidationError"},t0=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},r0=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function n8(r){return e=>j(e,r)}function o8(r){return e=>B(e,r)}function gu(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function wc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function FS(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=B(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=wc(n);return gt([t,o],t.length+o.length)}function $S(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ir.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=wc(n);return gt([t,o],t.length+o.length)}function i8(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=j(e,"base32"),o=gu(t);return`${n}:${o}`}var s8=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new wr("Invalid byte value in IP address");e[n]=o}),e},jS=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=Ao(t[n]),s;i&&(s=s8(t[n]),t[n]=j(s.subarray(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,j(s.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let i=parseInt(t[n],16);if(isNaN(i)||i<0||i>65535)throw new wr("Invalid byte value in IP address");o[e++]=i>>8&255,o[e++]=i&255}return o},KS=function(r){if(r.byteLength!==4)throw new wr("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},VS=function(r){if(r.byteLength!==16)throw new wr("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],i=r[n+1],s=`${o.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;e.push(s)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new wr(`Invalid IPv6 address "${t}"`)}};function HS(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new wr(`Invalid IPv6 address "${r}"`)}}var r8=Object.values(Ya).map(r=>r.decoder),rU=(function(){let r=r8[0].or(r8[1]);return r8.slice(2).forEach(e=>r=r.or(e)),r})();function qS(r){return rU.decode(r)}function WS(r){return e=>r.encoder.encode(e)}function nU(r){if(parseInt(r).toString()!==r)throw new Ki("Value must be an integer")}function oU(r){if(r<0)throw new Ki("Value must be a positive integer, or zero")}function iU(r){return e=>{if(e>r)throw new Ki(`Value must be smaller than or equal to ${r}`)}}function sU(...r){return e=>{for(let t of r)t(e)}}var Gd=sU(nU,oU,iU(65535));var lr=-1,a8=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new r0(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},qi=new a8,xU=[{code:4,name:"ip4",size:32,valueToBytes:s8,bytesToValue:KS,validate:r=>{if(!Ao(r))throw new Ki(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:wc,bytesToValue:gu,validate:Gd},{code:273,name:"udp",size:16,valueToBytes:wc,bytesToValue:gu,validate:Gd},{code:33,name:"dccp",size:16,valueToBytes:wc,bytesToValue:gu,validate:Gd},{code:41,name:"ip6",size:128,valueToBytes:jS,bytesToValue:VS,stringToValue:HS,validate:r=>{if(!Wm(r))throw new Ki(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:lr},{code:43,name:"ipcidr",size:8,bytesToValue:n8("base10"),valueToBytes:o8("base10")},{code:53,name:"dns",size:lr},{code:54,name:"dns4",size:lr},{code:55,name:"dns6",size:lr},{code:56,name:"dnsaddr",size:lr},{code:132,name:"sctp",size:16,valueToBytes:wc,bytesToValue:gu,validate:Gd},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:lr,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:lr,bytesToValue:n8("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?o8("base58btc")(r):he.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:i8,valueToBytes:FS},{code:445,name:"onion3",size:296,bytesToValue:i8,valueToBytes:$S},{code:446,name:"garlic64",size:lr},{code:447,name:"garlic32",size:lr},{code:448,name:"tls"},{code:449,name:"sni",size:lr},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:lr,bytesToValue:WS(qa),valueToBytes:qS},{code:480,name:"http"},{code:481,name:"http-path",size:lr,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:lr}];xU.forEach(r=>{qi.addProtocol(r)});function zS(r){let e=[],t=0;for(;t<r.length;){let n=Cn(r,t),o=qi.getProtocol(n),i=je(n),s=EU(o,r,t+i),a=0;s>0&&o.size===lr&&(a=je(s));let c=i+a+s,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(s>0){let f=t+i+a,u=r.subarray(f,f+s);l.value=o.bytesToValue?.(u)??j(u)}e.push(l),t+=c}return e}function GS(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=qi.getProtocol(n.code),i=je(n.code),s,a=0,c=0;n.value!=null&&(s=o.valueToBytes?.(n.value)??B(n.value),a=s.byteLength,o.size===lr&&(c=je(a)));let l=new Uint8Array(i+c+a),f=0;su(n.code,l,f),f+=i,s!=null&&(o.size===lr&&(su(a,l,f),f+=c),l.set(s,f)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return gt(t,e)}function XS(r){if(r.charAt(0)!=="/")throw new wr('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let i=1;i<r.length;i++){let s=r.charAt(i);s!=="/"&&(t==="protocol"?o+=r.charAt(i):n+=r.charAt(i));let a=i===r.length-1;if(s==="/"||a){let c=qi.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new wr(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new wr(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new wr("Incomplete multiaddr");return e}function YS(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=qi.getProtocol(e.code);if(t==null)throw new wr(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function EU(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Cn(e,t)}var SU=Symbol.for("nodejs.util.inspect.custom"),g8=Symbol.for("@multiformats/multiaddr");function _U(r){if(r==null&&(r="/"),oi(r))return r.getComponents();if(r instanceof Uint8Array)return zS(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),XS(r);if(Array.isArray(r))return r;throw new wr("Must be a string, Uint8Array, Component[], or another Multiaddr")}var s0=class r{[g8]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=_U(e),t.validate!==!1&&AU(this)}get bytes(){return this.#r==null&&(this.#r=GS(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=YS(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new t0(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return we(this.bytes,e.bytes)}[SU](){return`Multiaddr(${this.toString()})`}};function AU(r){r.getComponents().forEach(e=>{let t=qi.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function oi(r){return!!r?.[g8]}function ie(r){return new s0(r)}var y8=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ve(),this.haveNext=Ve()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ve(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ve(),await ut(this.readNext.promise,t?.signal,t)}};function QS(){return new y8}function TU(r){return r[Symbol.asyncIterator]!=null}async function IU(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*CU(r){let e=new AbortController,t=QS();IU(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*PU(r){for(let e of r)yield*e}function kU(...r){let e=[];for(let t of r)TU(t)||e.push(t);return e.length===r.length?PU(e):CU(r)}var Yr=kU;function vu(r,...e){if(r==null)throw new Error("Empty pipeline");if(w8(r)){let n=r;r=()=>n.source}else if(JS(r)||ZS(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&w8(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)w8(t[n])&&(t[n]=RU(t[n]));return OU(...t)}var OU=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},ZS=r=>r?.[Symbol.asyncIterator]!=null,JS=r=>r?.[Symbol.iterator]!=null,w8=r=>r==null?!1:r.sink!=null&&r.source!=null,RU=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=gr({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(ZS(i))o=async function*(){yield*i,n.end()};else if(JS(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Yr(n,o())}return r.source};var DU=4194304,a0=class extends Error{static name="UnwrappedError";name="UnwrappedError"},eh=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},v8=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},x8=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function NU(r){return typeof r?.closeRead=="function"}function LU(r){return typeof r?.close=="function"}function b8(r){return NU(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:LU(r)?r.status!=="open":!1}function BU(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function c0(r,e){let t=e?.maxBufferSize??DU,n=new fe,o,i=!1;if(!BU(r))throw new P("Argument should be a Stream or a Multiaddr");let s=f=>{if(n.append(f.data),n.byteLength>t){let u=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${t}`))}o?.resolve()};r.addEventListener("message",s);let a=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(f){if(i===!0)throw new a0("Stream was unwrapped");if(b8(r)){if(f?.bytes==null)return null;if(n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new yc(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let u=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=u){o.resolve();break}if(await ut(o.promise,f?.signal),b8(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(b8(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new yc(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(f)}let h=n.sublist(0,d);return n.consume(d),h},async write(f,u){if(i===!0)throw new a0("Stream was unwrapped");r.send(f)||await Qn(r,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return i||(i=!0,r.removeEventListener("message",s),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function Gs(r,e={}){let t=c0(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=je(e.maxDataLength));let n=e?.lengthDecoder??Cn,o=e?.lengthEncoder??Mr;return{async read(s){let a=-1,c=new fe;for(;;){let f=await t.read({...s,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new eh("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new x8(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new v8(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...s,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new yc(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new yc(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(s,a){await t.write(new fe(o(s.byteLength),s),a)},async writeV(s,a){let c=new fe(...s.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function bt(r,e){let t=Gs(r,e),n={read:async(o,i)=>{let s=await t.read(i);return o.decode(s)},write:async(o,i,s)=>{await t.write(i.encode(o),s)},writeV:async(o,i,s)=>{await t.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var MU=1024*1024*4,UU=1024*1024*4,l0=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new fe,this.maxBufferSize=e.maxBufferSize??MU,this.maxDataLength=e.maxDataLength??UU,this.lengthDecoder=e.lengthDecoder??Cn,this.encodingLength=e.encodingLength??je}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new P(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(i){if(i instanceof RangeError)break;throw i}if(t<0||t>this.maxDataLength)throw new eh("Invalid message length");let n=this.encodingLength(t),o=n+t;if(this.buffer.byteLength>=o){let i=this.buffer.sublist(n,o);this.buffer.consume(o),i.byteLength>0&&(yield i)}else break}}};var FU=["string","number","bigint","symbol"],$U=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function e_(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(FU.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(jU(r))return"Buffer";let t=KU(r);return t||"Object"}function jU(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function KU(r){let e=Object.prototype.toString.call(r).slice(8,-1);if($U.includes(e))return e}var v=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};v.uint=new v(0,"uint",!0);v.negint=new v(1,"negint",!0);v.bytes=new v(2,"bytes",!0);v.string=new v(3,"string",!0);v.array=new v(4,"array",!1);v.map=new v(5,"map",!1);v.tag=new v(6,"tag",!1);v.float=new v(7,"float",!0);v.false=new v(7,"false",!0);v.true=new v(7,"true",!0);v.null=new v(7,"null",!0);v.undefined=new v(7,"undefined",!0);v.break=new v(7,"break",!0);var W=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var xu=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",VU=new TextDecoder,HU=new TextEncoder;function u0(r){return xu&&globalThis.Buffer.isBuffer(r)}function th(r){return r instanceof Uint8Array?u0(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var o_=xu?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):r_(r,e,t):(r,e,t)=>t-e>64?VU.decode(r.subarray(e,t)):r_(r,e,t),f0=xu?r=>r.length>64?globalThis.Buffer.from(r):t_(r):r=>r.length>64?HU.encode(r):t_(r),ii=r=>Uint8Array.from(r),Eu=xu?(r,e,t)=>u0(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),i_=xu?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),th(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},s_=xu?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function d0(r,e){if(u0(r)&&u0(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function t_(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function r_(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,c,l,f;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(f=(o&31)<<6|a&63,f>127&&(i=f));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(f=(o&15)<<12|(a&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(f=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,f>65535&&f<1114112&&(i=f))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return E8(n)}var n_=4096;function E8(r){let e=r.length;if(e<=n_)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=n_));return t}var qU=256,rh=class{constructor(e=qU){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=s_(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Eu(n,0,this.cursor)}else t=i_(this.chunks,this.cursor);return e&&this.reset(),t}};var ye="CBOR decode error:",Wi="CBOR encode error:",nh=[];nh[23]=1;nh[24]=2;nh[25]=3;nh[26]=5;nh[27]=9;function zi(r,e,t){if(r.length-e<t)throw new Error(`${ye} not enough data for type`)}var ur=[24,256,65536,4294967296,BigInt("18446744073709551616")];function kn(r,e,t){zi(r,e,1);let n=r[e];if(t.strict===!0&&n<ur[0])throw new Error(`${ye} integer encoded in more bytes than necessary (strict decode)`);return n}function On(r,e,t){zi(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<ur[1])throw new Error(`${ye} integer encoded in more bytes than necessary (strict decode)`);return n}function Rn(r,e,t){zi(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<ur[2])throw new Error(`${ye} integer encoded in more bytes than necessary (strict decode)`);return n}function Dn(r,e,t){zi(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<ur[3])throw new Error(`${ye} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${ye} integers outside of the safe integer range are not supported`)}function a_(r,e,t,n){return new W(v.uint,kn(r,e+1,n),2)}function c_(r,e,t,n){return new W(v.uint,On(r,e+1,n),3)}function l_(r,e,t,n){return new W(v.uint,Rn(r,e+1,n),5)}function u_(r,e,t,n){return new W(v.uint,Dn(r,e+1,n),9)}function Zn(r,e){return br(r,0,e.value)}function br(r,e,t){if(t<ur[0]){let n=Number(t);r.push([e|n])}else if(t<ur[1]){let n=Number(t);r.push([e|24,n])}else if(t<ur[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<ur[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<ur[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${ye} encountered BigInt larger than allowable range`)}}Zn.encodedSize=function(e){return br.encodedSize(e.value)};br.encodedSize=function(e){return e<ur[0]?1:e<ur[1]?2:e<ur[2]?3:e<ur[3]?5:9};Zn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function f_(r,e,t,n){return new W(v.negint,-1-kn(r,e+1,n),2)}function d_(r,e,t,n){return new W(v.negint,-1-On(r,e+1,n),3)}function h_(r,e,t,n){return new W(v.negint,-1-Rn(r,e+1,n),5)}var S8=BigInt(-1),p_=BigInt(1);function m_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new W(v.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${ye} integers outside of the safe integer range are not supported`);return new W(v.negint,S8-BigInt(o),9)}function h0(r,e){let t=e.value,n=typeof t=="bigint"?t*S8-p_:t*-1-1;br(r,e.type.majorEncoded,n)}h0.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*S8-p_:t*-1-1;return n<ur[0]?1:n<ur[1]?2:n<ur[2]?3:n<ur[3]?5:9};h0.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function oh(r,e,t,n){zi(r,e,t+n);let o=Eu(r,e+t,e+t+n);return new W(v.bytes,o,t+n)}function g_(r,e,t,n){return oh(r,e,1,t)}function y_(r,e,t,n){return oh(r,e,2,kn(r,e+1,n))}function w_(r,e,t,n){return oh(r,e,3,On(r,e+1,n))}function b_(r,e,t,n){return oh(r,e,5,Rn(r,e+1,n))}function v_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ye} 64-bit integer bytes lengths not supported`);return oh(r,e,9,o)}function p0(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===v.string?f0(r.value):r.value),r.encodedBytes}function Su(r,e){let t=p0(e);br(r,e.type.majorEncoded,t.length),r.push(t)}Su.encodedSize=function(e){let t=p0(e);return br.encodedSize(t.length)+t.length};Su.compareTokens=function(e,t){return zU(p0(e),p0(t))};function zU(r,e){return r.length<e.length?-1:r.length>e.length?1:d0(r,e)}function ih(r,e,t,n,o){let i=t+n;zi(r,e,i);let s=new W(v.string,o_(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Eu(r,e+t,e+i)),s}function x_(r,e,t,n){return ih(r,e,1,t,n)}function E_(r,e,t,n){return ih(r,e,2,kn(r,e+1,n),n)}function S_(r,e,t,n){return ih(r,e,3,On(r,e+1,n),n)}function __(r,e,t,n){return ih(r,e,5,Rn(r,e+1,n),n)}function A_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ye} 64-bit integer string lengths not supported`);return ih(r,e,9,o,n)}var T_=Su;function _u(r,e,t,n){return new W(v.array,n,t)}function I_(r,e,t,n){return _u(r,e,1,t)}function C_(r,e,t,n){return _u(r,e,2,kn(r,e+1,n))}function P_(r,e,t,n){return _u(r,e,3,On(r,e+1,n))}function k_(r,e,t,n){return _u(r,e,5,Rn(r,e+1,n))}function O_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ye} 64-bit integer array lengths not supported`);return _u(r,e,9,o)}function R_(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ye} indefinite length items not allowed`);return _u(r,e,1,1/0)}function m0(r,e){br(r,v.array.majorEncoded,e.value)}m0.compareTokens=Zn.compareTokens;m0.encodedSize=function(e){return br.encodedSize(e.value)};function Au(r,e,t,n){return new W(v.map,n,t)}function D_(r,e,t,n){return Au(r,e,1,t)}function N_(r,e,t,n){return Au(r,e,2,kn(r,e+1,n))}function L_(r,e,t,n){return Au(r,e,3,On(r,e+1,n))}function B_(r,e,t,n){return Au(r,e,5,Rn(r,e+1,n))}function M_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ye} 64-bit integer map lengths not supported`);return Au(r,e,9,o)}function U_(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ye} indefinite length items not allowed`);return Au(r,e,1,1/0)}function g0(r,e){br(r,v.map.majorEncoded,e.value)}g0.compareTokens=Zn.compareTokens;g0.encodedSize=function(e){return br.encodedSize(e.value)};function F_(r,e,t,n){return new W(v.tag,t,1)}function $_(r,e,t,n){return new W(v.tag,kn(r,e+1,n),2)}function j_(r,e,t,n){return new W(v.tag,On(r,e+1,n),3)}function K_(r,e,t,n){return new W(v.tag,Rn(r,e+1,n),5)}function V_(r,e,t,n){return new W(v.tag,Dn(r,e+1,n),9)}function y0(r,e){br(r,v.tag.majorEncoded,e.value)}y0.compareTokens=Zn.compareTokens;y0.encodedSize=function(e){return br.encodedSize(e.value)};var JU=20,eF=21,tF=22,rF=23;function H_(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${ye} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new W(v.null,null,1):new W(v.undefined,void 0,1)}function q_(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ye} indefinite length items not allowed`);return new W(v.break,void 0,1)}function _8(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${ye} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${ye} Infinity values are not supported`)}return new W(v.float,r,e)}function W_(r,e,t,n){return _8(A8(r,e+1),3,n)}function z_(r,e,t,n){return _8(T8(r,e+1),5,n)}function G_(r,e,t,n){return _8(Z_(r,e+1),9,n)}function w0(r,e,t){let n=e.value;if(n===!1)r.push([v.float.majorEncoded|JU]);else if(n===!0)r.push([v.float.majorEncoded|eF]);else if(n===null)r.push([v.float.majorEncoded|tF]);else if(n===void 0)r.push([v.float.majorEncoded|rF]);else{let o,i=!1;(!t||t.float64!==!0)&&(Y_(n),o=A8(Co,1),n===o||Number.isNaN(n)?(Co[0]=249,r.push(Co.slice(0,3)),i=!0):(Q_(n),o=T8(Co,1),n===o&&(Co[0]=250,r.push(Co.slice(0,5)),i=!0))),i||(nF(n),o=Z_(Co,1),Co[0]=251,r.push(Co.slice(0,9)))}}w0.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){Y_(n);let o=A8(Co,1);if(n===o||Number.isNaN(n))return 3;if(Q_(n),o=T8(Co,1),n===o)return 5}return 9};var X_=new ArrayBuffer(9),Jn=new DataView(X_,1),Co=new Uint8Array(X_,0);function Y_(r){if(r===1/0)Jn.setUint16(0,31744,!1);else if(r===-1/0)Jn.setUint16(0,64512,!1);else if(Number.isNaN(r))Jn.setUint16(0,32256,!1);else{Jn.setFloat32(0,r);let e=Jn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Jn.setUint16(0,31744,!1);else if(t===0)Jn.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Jn.setUint16(0,0):o<-14?Jn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Jn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function A8(r,e){if(r.length-e<2)throw new Error(`${ye} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function Q_(r){Jn.setFloat32(0,r,!1)}function T8(r,e){if(r.length-e<4)throw new Error(`${ye} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function nF(r){Jn.setFloat64(0,r,!1)}function Z_(r,e){if(r.length-e<8)throw new Error(`${ye} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}w0.compareTokens=Zn.compareTokens;function Ye(r,e,t){throw new Error(`${ye} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function b0(r){return()=>{throw new Error(`${ye} ${r}`)}}var ne=[];for(let r=0;r<=23;r++)ne[r]=Ye;ne[24]=a_;ne[25]=c_;ne[26]=l_;ne[27]=u_;ne[28]=Ye;ne[29]=Ye;ne[30]=Ye;ne[31]=Ye;for(let r=32;r<=55;r++)ne[r]=Ye;ne[56]=f_;ne[57]=d_;ne[58]=h_;ne[59]=m_;ne[60]=Ye;ne[61]=Ye;ne[62]=Ye;ne[63]=Ye;for(let r=64;r<=87;r++)ne[r]=g_;ne[88]=y_;ne[89]=w_;ne[90]=b_;ne[91]=v_;ne[92]=Ye;ne[93]=Ye;ne[94]=Ye;ne[95]=b0("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)ne[r]=x_;ne[120]=E_;ne[121]=S_;ne[122]=__;ne[123]=A_;ne[124]=Ye;ne[125]=Ye;ne[126]=Ye;ne[127]=b0("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)ne[r]=I_;ne[152]=C_;ne[153]=P_;ne[154]=k_;ne[155]=O_;ne[156]=Ye;ne[157]=Ye;ne[158]=Ye;ne[159]=R_;for(let r=160;r<=183;r++)ne[r]=D_;ne[184]=N_;ne[185]=L_;ne[186]=B_;ne[187]=M_;ne[188]=Ye;ne[189]=Ye;ne[190]=Ye;ne[191]=U_;for(let r=192;r<=215;r++)ne[r]=F_;ne[216]=$_;ne[217]=j_;ne[218]=K_;ne[219]=V_;ne[220]=Ye;ne[221]=Ye;ne[222]=Ye;ne[223]=Ye;for(let r=224;r<=243;r++)ne[r]=b0("simple values are not supported");ne[244]=Ye;ne[245]=Ye;ne[246]=Ye;ne[247]=H_;ne[248]=b0("simple values are not supported");ne[249]=W_;ne[250]=z_;ne[251]=G_;ne[252]=Ye;ne[253]=Ye;ne[254]=Ye;ne[255]=q_;var Po=[];for(let r=0;r<24;r++)Po[r]=new W(v.uint,r,1);for(let r=-1;r>=-24;r--)Po[31-r]=new W(v.negint,r,1);Po[64]=new W(v.bytes,new Uint8Array(0),1);Po[96]=new W(v.string,"",1);Po[128]=new W(v.array,0,1);Po[160]=new W(v.map,0,1);Po[244]=new W(v.false,!1,1);Po[245]=new W(v.true,!0,1);Po[246]=new W(v.null,null,1);function I8(r){switch(r.type){case v.false:return ii([244]);case v.true:return ii([245]);case v.null:return ii([246]);case v.bytes:return r.value.length?void 0:ii([64]);case v.string:return r.value===""?ii([96]):void 0;case v.array:return r.value===0?ii([128]):void 0;case v.map:return r.value===0?ii([160]):void 0;case v.uint:return r.value<24?ii([Number(r.value)]):void 0;case v.negint:if(r.value>=-24)return ii([31-Number(r.value)])}}var iF={float64:!1,mapSorter:cF,quickEncodeToken:I8},eA=Object.freeze({float64:!0,mapSorter:lF,quickEncodeToken:I8});function sF(){let r=[];return r[v.uint.major]=Zn,r[v.negint.major]=h0,r[v.bytes.major]=Su,r[v.string.major]=T_,r[v.array.major]=m0,r[v.map.major]=g0,r[v.tag.major]=y0,r[v.float.major]=w0,r}var P8=sF(),C8=new rh,x0=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Wi} object contains circular references`);return new r(t,e)}},Xs={null:new W(v.null,null),undefined:new W(v.undefined,void 0),true:new W(v.true,!0),false:new W(v.false,!1),emptyArray:new W(v.array,0),emptyMap:new W(v.map,0)},Ys={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new W(v.float,r):r>=0?new W(v.uint,r):new W(v.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new W(v.uint,r):new W(v.negint,r)},Uint8Array(r,e,t,n){return new W(v.bytes,r)},string(r,e,t,n){return new W(v.string,r)},boolean(r,e,t,n){return r?Xs.true:Xs.false},null(r,e,t,n){return Xs.null},undefined(r,e,t,n){return Xs.undefined},ArrayBuffer(r,e,t,n){return new W(v.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new W(v.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Xs.emptyArray,new W(v.break)]:Xs.emptyArray;n=x0.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=v0(s,t,n);return t.addBreakTokens?[new W(v.array,r.length),o,new W(v.break)]:[new W(v.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[Xs.emptyMap,new W(v.break)]:Xs.emptyMap;n=x0.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[v0(l,t,n),v0(o?r.get(l):r[l],t,n)];return aF(a,t),t.addBreakTokens?[new W(v.map,s),a,new W(v.break)]:[new W(v.map,s),a]}};Ys.Map=Ys.Object;Ys.Buffer=Ys.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Ys[`${r}Array`]=Ys.DataView;function v0(r,e={},t){let n=e_(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Ys[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Ys[n];if(!i)throw new Error(`${Wi} unsupported type: ${n}`);return i(r,n,e,t)}function aF(r,e){e.mapSorter&&r.sort(e.mapSorter)}function cF(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=P8[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function lF(r,e){if(r[0]instanceof W&&e[0]instanceof W){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=J_(t.value)),n._keyBytes||(n._keyBytes=J_(n.value)),d0(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function J_(r){return E0(r,P8,eA)}function tA(r,e,t,n){if(Array.isArray(e))for(let o of e)tA(r,o,t,n);else t[e.type.major](r,e,n)}function E0(r,e,t){let n=v0(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new rh(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return th(a.chunks[0])}}return C8.reset(),tA(C8,n,e,t),C8.toBytes(!0)}function Qs(r,e){return e=Object.assign({},iF,e),E0(r,P8,e)}var uF={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},S0=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Po[e];if(t===void 0){let n=ne[e];if(!n)throw new Error(`${ye} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},sh=Symbol.for("DONE"),_0=Symbol.for("BREAK");function fF(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Tu(e,t);if(i===_0){if(r.value===1/0)break;throw new Error(`${ye} got unexpected break to lengthed array`)}if(i===sh)throw new Error(`${ye} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function dF(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=Tu(e,t);if(a===_0){if(r.value===1/0)break;throw new Error(`${ye} got unexpected break to lengthed map`)}if(a===sh)throw new Error(`${ye} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${ye} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${ye} found repeat map key "${a}"`);let c=Tu(e,t);if(c===sh)throw new Error(`${ye} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function Tu(r,e){if(r.done())return sh;let t=r.next();if(t.type===v.break)return _0;if(t.type.terminal)return t.value;if(t.type===v.array)return fF(t,r,e);if(t.type===v.map)return dF(t,r,e);if(t.type===v.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Tu(r,e);return e.tags[t.value](n)}throw new Error(`${ye} tag not supported (${t.value})`)}throw new Error("unsupported")}function k8(r,e){if(!(r instanceof Uint8Array))throw new Error(`${ye} data to decode must be a Uint8Array`);e=Object.assign({},uF,e);let t=e.tokenizer||new S0(r,e),n=Tu(t,e);if(n===sh)throw new Error(`${ye} did not find any content to decode`);if(n===_0)throw new Error(`${ye} got unexpected break`);return[n,r.subarray(t.pos())]}function Nn(r,e){let[t,n]=k8(r,e);if(n.length>0)throw new Error(`${ye} too many terminals, data makes no sense`);return t}var A0=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Iu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},T0=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},ah=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function I0(r){return r[Symbol.asyncIterator]!=null}function rA(r,e){if(r.byteLength>e)throw new Iu("Message length too long")}var P0=r=>{let e=je(r),t=Ot(e);return Mr(r,t),P0.bytes=e,t};P0.bytes=0;function Gi(r,e){e=e??{};let t=e.lengthEncoder??P0,n=e?.maxDataLength??4194304;function*o(i){rA(i,n);let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return I0(r)?(async function*(){for await(let i of r)yield*o(i)})():(function*(){for(let i of r)yield*o(i)})()}Gi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??P0,n=e?.maxDataLength??4194304;return rA(r,n),new fe(t(r.byteLength),r)};var xc;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(xc||(xc={}));var R8=r=>{let e=Cn(r);return R8.bytes=je(e),e};R8.bytes=0;function Ec(r,e){let t=new fe,n=xc.LENGTH,o=-1,i=e?.lengthDecoder??R8,s=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===xc.LENGTH)try{if(o=i(t),o<0)throw new A0("Invalid message length");if(o>a)throw new Iu("Message length too long");let l=i.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=xc.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>s)throw new T0("Message length length too long");break}throw l}if(n===xc.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=xc.LENGTH}}}return I0(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ah("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ah("Unexpected end of input")})()}Ec.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:i,value:s}=await r.next(t);if(i===!0)return;s!=null&&(yield s)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}})();return Ec(n,{...e??{},onLength:i=>{t=i}})};var oA=Symbol.for("sindresorhus/unlimited-timeout#brand");function iA(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,o={[oA]:!0,id:void 0,cleared:!1,ref(){return n=!1,o.id?.ref?.(),o},unref(){return n=!0,o.id?.unref?.(),o}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return o;(!Number.isFinite(e)||e<0)&&(e=0);let i=performance.now()+e,s=a=>{o.cleared||(a<=2147483647?(o.id=globalThis.setTimeout(()=>{o.cleared||r(...t)},a),n&&o.id?.unref?.()):(o.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,i-c);s(l)},2147483647),n&&o.id?.unref?.()))};return s(e),o}function sA(r){!r||typeof r!="object"||!r[oA]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var pF=new WeakMap;function mF({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(o.reason);let i,s,a,c=r??clearTimeout,l=()=>{c(i),a(o.reason)},f=()=>{o&&o.removeEventListener("abort",l)},u=new Promise((d,h)=>{s=()=>{f(),d(n)},a=h,i=(e??setTimeout)(s,t)});return o&&o.addEventListener("abort",l,{once:!0}),pF.set(u,()=>{c(i),i=null,s()}),u}}var gF=mF({setTimeout:iA,clearTimeout:sA}),aA=gF;var vr=class extends yr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var k0=class extends yr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Cu=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 D8}consume(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,t,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(o,s.consumedPoints,this.blockDuration)),new Gm("Rate limit exceeded",s);return s}penalty(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,-t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}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)}},D8=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let i=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||i>0?(o.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,i=this.storage.get(e);i!=null&&clearTimeout(i.timeoutId);let s={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,s),o>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),s.timeoutId.unref!=null&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:s.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}};function Pu(r,e,t){let n,o,i=!1;function s(){let l={signal:o.signal};if(t?.timeout!=null){let f=De([o.signal,AbortSignal.timeout(t.timeout)]);l.signal=f}i=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{i=!1,!o.signal.aborted&&(n=setTimeout(s,e))})}let a=ji(s,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(s,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{i||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{s()}):n=setTimeout(s,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var N8=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 Wt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new N8({name:e,metrics:t}):n=new Map,n}var Xi="/",cA=new TextEncoder().encode(Xi),O0=cA[0],ht=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]!==O0)throw new Error("Invalid key")}toString(e="utf8"){return j(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Xi))}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=cA),this._buf[0]!==O0){let e=new Uint8Array(this._buf.byteLength+1);e.fill(O0,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===O0;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Xi).slice(1)}type(){return yF(this.baseNamespace())}name(){return wF(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Xi)||(e+=Xi),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Xi):new r(e.slice(0,-1).join(Xi))}child(e){return this.toString()===Xi?e:e.toString()===Xi?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(),...bF(e.map(t=>t.namespaces()))])}};function yF(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function wF(r){let e=r.split(":");return e[e.length-1]}function bF(r){return[].concat(...r)}function vF(r){return r[Symbol.asyncIterator]!=null}function xF(r){if(vF(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=gt([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return gt(e,t)}var R0=xF;function D0({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*EF(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=he.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*L8(n,o))}else{let t=he.asCID(e);t!=null?yield[r.join("/"),t]:yield*L8(e,r)}}function*L8(r,e){if(r==null||r instanceof Uint8Array)return;let t=he.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*EF(i,o)}}function*SF(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&he.asCID(n)==null&&(yield*B8(n,o))}else yield*B8(e,r)}function*B8(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"&&he.asCID(n)==null&&(yield*SF(o,n))}}function _F(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=he.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var M8=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:D0(),bytes:D0(),value:D0(),asBlock:D0()})}links(){return L8(this.value,[])}tree(){return B8(this.value,[])}get(e="/"){return _F(this.value,e.split("/").filter(Boolean))}};function lA({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 M8({cid:e,bytes:r,value:o})}var N0=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},ch=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},L0=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},B0=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},M0=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},U0=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},lh=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var dA="/pin/",uA="/pinned-block/",U8=Gn,fA=1;function F0(r){return r.version===0&&(r=r.toV1()),new ht(`${dA}${r.toString(U8)}`)}var $0=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=F0(e);if(await this.datastore.has(n))throw new N0("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new P("Depth must be greater than or equal to 0");let i=new yr({concurrency:fA});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>we(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Qs(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await R0(this.blockstore.get(e,n)),s=lA({bytes:i,cid:e,codec:o});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new ht(`${uA}${U8.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=Nn(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Qs(i),n),n.onProgress?.(new oe("helia:pin:add",e))}}async*rm(e,t={}){let n=F0(e),o=await this.datastore.get(n,t),i=Nn(o);await this.datastore.delete(n,t);let s=new yr({concurrency:fA});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>we(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:dA+(e.cid!=null?`${e.cid.toString(Gn)}`:"")},e)){let o=he.parse(t.toString().substring(5),Gn),i=Nn(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new ht(`${uA}${U8.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=F0(e),o=await this.datastore.get(n,t);return Nn(o)}async setMetadata(e,t,n){let o=F0(e),i=await this.datastore.get(o,n),s=Nn(i);s.metadata=t??{},await this.datastore.put(o,Qs(s),n)}};var F8=1,$8=5;var uh=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Zs=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},fh=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},dh=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},j8=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}};var AF=5,j0=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??AF,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 er(...this.routers)}async stop(){await or(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Zs("No content routers available");let n=new vr({concurrency:this.providerLookupConcurrency}),o=0,i=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let c=Sc(this.routers,"findProviders").map(async function*(l){let f=0;try{for await(let u of l.findProviders(e,t))f++,yield u}catch(u){i.push(u)}finally{s.log("router %s found %d providers for %c",l,f,e),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let l of Yr(n.toGenerator(),...c))if(l!=null){if(l.multiaddrs.length===0){if(n.find(l.id)!=null)continue;n.add(async()=>{try{let f=await this.findPeer(l.id,t);return f.multiaddrs.length===0?null:{...f,protocols:l.protocols,routing:l.routing}}catch(f){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,f),null}},{peerId:l.id,signal:t.signal}).catch(f=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,f)});continue}o++,yield l}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new Zs("No content routers available");await Promise.all(Sc(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Sc(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Sc(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){let n=[],o;try{o=await Promise.any(Sc(this.routers,"get").map(async i=>{try{return await i.get(e,t)}catch(s){this.log("router %s failed with %e",i,s),n.push(s)}}))}catch{}if(o==null)throw new M0(n,`Failed to get value key ${j(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new Zs("No peer routers available");let n=this,o=Yr(...Sc(this.routers,"findPeer").map(i=>(async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let i of o)if(i!=null)return i;throw new Xe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Zs("No peer routers available");for await(let n of Yr(...Sc(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Sc(r,e){return r.filter(t=>t[e]!=null)}var Ln=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Qr(r,e,t,n){let o=new Ln(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let i=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((s,a)=>{function c(){V8(t,"abort",u),V8(r,e,l),V8(r,i,f)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),s(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)};K8(t,"abort",u),K8(r,e,l),K8(r,i,f)})}function K8(r,e,t){r!=null&&(hA(r)?r.addEventListener(e,t):r.addListener(e,t))}function V8(r,e,t){r!=null&&(hA(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function hA(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var K0=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var V0=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 Ln)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function TF(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var H0=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=TF(),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 Ln),this.cleanup())}async join(e={}){let t=new V0(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 ut(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 H8(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 hh=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=H8(this.emitEmpty.bind(this),1),this.emitIdle=H8(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 K0;let n=new H0(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ln)}),this.clear()}async onEmpty(e){this.size!==0&&await Qr(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Qr(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Qr(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=gr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new Ln("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var q0="lock:worker:request-read",W0="lock:worker:abort-read-request",z0="lock:worker:release-read",G0="lock:master:grant-read",X0="lock:master:error-read",Y0="lock:worker:request-write",Q0="lock:worker:abort-write-request",Z0="lock:worker:release-write",J0="lock:master:grant-write",e2="lock:master:error-write",t2="lock:worker:finalize",r2="mortice",pA={singleProcess:!1};var q8=(r,e,t,n,o,i,s,a,c)=>l=>{if(l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===o&&r.safeDispatchEvent(t,{detail:{name:f.name,identifier:f.identifier,handler:async()=>{e.postMessage({type:c,name:f.name,identifier:f.identifier}),await new Promise(u=>{let d=h=>{if(h?.data==null)return;let m={type:h.data.type,name:h.data.name,identifier:h.data.identifier};m.type===a&&m.identifier===f.identifier&&(e.removeEventListener("message",d),u())};e.addEventListener("message",d)})},onError:u=>{e.postMessage({type:s,name:f.name,identifier:f.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),f.type===i&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===t2&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var mA=(r=10)=>Math.random().toString().substring(2,r+2);var n2=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(r2)}readLock(e){return this.sendRequest(q0,W0,G0,X0,z0,e)}writeLock(e){return this.sendRequest(Y0,Q0,J0,e2,Z0,e)}finalize(){this.channel.postMessage({type:t2,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=mA();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let f=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",f,{once:!0});let u=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",u),s?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",u),s?.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 gA=r=>{if(r=Object.assign({},pA,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(r2),n=new _e;return t.addEventListener("message",q8(n,t,"requestReadLock","abortReadLockRequest",q0,W0,X0,z0,G0)),t.addEventListener("message",q8(n,t,"requestWriteLock","abortWriteLockRequest",Y0,Q0,e2,Z0,J0)),n}return new n2(r.name)};var _c=new Map,ph;function yA(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function IF(r){if(ph==null&&(ph=gA(r),!yA(ph))){let e=ph;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=_c.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=_c.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=_c.get(n);o?.finalize()})}return ph}async function W8(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new Ln)};return e?.signal?.addEventListener("abort",i,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",i),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),o}var wA=(r,e)=>{let t=_c.get(r);if(t!=null)return t;let n=IF(e);if(yA(n))return t=n,_c.set(r,t),t;let o=new hh({concurrency:1}),i;return t={async readLock(s){if(i!=null)return W8(i,s);i=new hh({concurrency:e.concurrency,autoStart:!1});let a=i,c=W8(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(s){return i=null,W8(o,s)},finalize:()=>{_c.delete(r)},queue:o},_c.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var CF={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function mh(r){let e=Object.assign({},CF,r);return wA(e.name,e)}var o2=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=mh({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await er(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 ch("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 i of e){if(await o.pins.isPinned(i))throw new ch("Block was pinned - please unpin and try again");yield i}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var z8=new ht("/version"),bA=1;async function vA(r){if(!await r.has(z8)){await r.put(z8,B(`${bA}`));return}let e=await r.get(z8),t=j(e);if(parseInt(t,10)!==bA)throw new L0("Invalid datastore version, a datastore migration may be required")}var Y8={};Nt(Y8,{code:()=>X8,decode:()=>UF,decodeOptions:()=>LF,encode:()=>MF,encodeOptions:()=>DF,name:()=>BF,toByteView:()=>EA});var xA=42;function EA(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function PF(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=he.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new W(v.tag,xA),new W(v.bytes,t)]}function kF(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function OF(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 RF(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 G8={float64:!0,typeEncoders:{Map:RF,Object:PF,undefined:kF,number:OF}},DF={...G8,typeEncoders:{...G8.typeEncoders}};function NF(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return he.decode(r.subarray(1))}var i2={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};i2.tags[xA]=NF;var LF={...i2,tags:i2.tags.slice()},BF="dag-cbor",X8=113,MF=r=>Qs(r,G8),UF=r=>Nn(EA(r),i2);var nw={};Nt(nw,{code:()=>rw,decode:()=>_A,encode:()=>SA,format:()=>XF,name:()=>GF,parse:()=>QF,stringify:()=>XF});var Q8=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===v.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===v.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[v.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[v.negint.major](e,t){this[v.uint.major](e,t)}[v.bytes.major](e,t){throw new Error(`${Wi} unsupported type: Uint8Array`)}[v.string.major](e,t){this.prefix(e);let n=f0(JSON.stringify(t.value));e.push(n.length>32?th(n):n)}[v.array.major](e,t){this.prefix(e),this.inRecursive.push({type:v.array,elements:0}),e.push([91])}[v.map.major](e,t){this.prefix(e),this.inRecursive.push({type:v.map,elements:0}),e.push([123])}[v.tag.major](e,t){}[v.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===v.array)e.push([93]);else if(s.type===v.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(`${Wi} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function FF(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Wi} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==v.string||n.type!==v.string)throw new Error(`${Wi} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Wi} unexpected duplicate map keys, this is not supported`)}var $F={addBreakTokens:!0,mapSorter:FF};function Z8(r,e){return e=Object.assign({},$F,e),E0(r,new Q8,e)}var ku=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(`${ye} 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(`${ye} 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 W(v.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(`${ye} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${ye} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new W(v.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new W(s>=0?v.uint:v.negint,s,this._pos-e):new W(s>=0?v.uint:v.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${ye} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new W(v.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${ye} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${ye} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${ye} unexpected unicode sequence at position ${this._pos}`);let c,l,f,u;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(i&31)<<6|c&63,u>127&&(s=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(i&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(s=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=(i&15)<<18|(c&63)<<12|(l&63)<<6|f&63,u>65535&&u<1114112&&(s=u))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${ye} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${ye} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new W(v.string,E8(t),this._pos-e);default:if(i<32)throw new Error(`${ye} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${ye} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new W(v.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new W(v.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new W(v.null,null,4);case 102:return this.expect([102,97,108,115,101]),new W(v.false,!1,5);case 116:return this.expect([116,114,117,101]),new W(v.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(`${ye} 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 W(v.break,void 0,1);if(this.ch()!==44)throw new Error(`${ye} 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 W(v.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 W(v.break,void 0,1);if(this.ch()!==44)throw new Error(`${ye} 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 W(v.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${ye} 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(`${ye} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function J8(r,e){return e=Object.assign({tokenizer:new ku(r,e)},e),Nn(r,e)}function KF(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function VF(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=he.asCID(r);if(!e)return null;let t=e.toString();return[new W(v.map,1/0,1),new W(v.string,"/",1),new W(v.string,t,t.length),new W(v.break,void 0,1)]}function s2(r){let e=Ht.encode(r).slice(1);return[new W(v.map,1/0,1),new W(v.string,"/",1),new W(v.map,1/0,1),new W(v.string,"bytes",5),new W(v.string,e,e.length),new W(v.break,void 0,1),new W(v.break,void 0,1)]}function ko(r){return s2(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function HF(r){return s2(new Uint8Array(r))}function qF(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function WF(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 zF={typeEncoders:{Object:VF,Buffer:s2,Uint8Array:s2,Int8Array:ko,Uint16Array:ko,Int16Array:ko,Uint32Array:ko,Int32Array:ko,Float32Array:ko,Float64Array:ko,Uint8ClampedArray:ko,BigInt64Array:ko,BigUint64Array:ko,DataView:ko,ArrayBuffer:HF,undefined:qF,number:WF}},ew=class extends ku{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===v.map){let t=this._next();if(t.type===v.string&&t.value==="/"){let n=this._next();if(n.type===v.string){if(this._next().type!==v.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new W(v.tag,42,0)}if(n.type===v.map){let o=this._next();if(o.type===v.string&&o.value==="bytes"){let i=this._next();if(i.type===v.string){for(let a=0;a<2;a++)if(this._next().type!==v.break)throw new Error("Invalid encoded Bytes form");let s=Ht.decode(`m${i.value}`);return new W(v.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},tw={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};tw.tags[42]=he.parse;var GF="dag-json",rw=297,SA=r=>Z8(r,zF),_A=r=>{let e=KF(r),t=Object.assign(tw,{tokenizer:new ew(e,tw)});return J8(e,t)},XF=r=>YF.decode(SA(r));var YF=new TextDecoder,QF=r=>_A(ZF.encode(r)),ZF=new TextEncoder;var lw={};Nt(lw,{code:()=>cw,createLink:()=>NA,createNode:()=>DA,decode:()=>f$,encode:()=>u$,name:()=>l$,prepare:()=>sw,validate:()=>aw});var JF=new TextDecoder;function ow(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 a2(r,e){let t;[t,e]=ow(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 AA(r,e){let t;return[t,e]=ow(r,e),[t&7,t>>3,e]}function e$(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=AA(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=a2(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=a2(r,n),e.Name=JF.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=ow(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function TA(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=AA(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=a2(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]=a2(r,t),n.push(e$(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var CA=new TextEncoder,IA=2**32,t$=2**31;function r$(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=gh(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=CA.encode(r.Name);t-=n.length,e.set(n,t),t=gh(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=gh(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function PA(r){let e=o$(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=gh(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=r$(r.Links[o],t.subarray(0,n));n-=i,n=gh(t,n,i)-1,t[n]=18}return t}function n$(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ou(t)}if(typeof r.Name=="string"){let t=CA.encode(r.Name).length;e+=1+t+Ou(t)}return typeof r.Tsize=="number"&&(e+=1+Ou(r.Tsize)),e}function o$(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ou(t)}if(r.Links)for(let t of r.Links){let n=n$(t);e+=1+n+Ou(n)}return e}function gh(r,e,t){e-=Ou(t);let n=e;for(;t>=t$;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ou(r){return r%2===0&&r++,Math.floor((i$(r)+6)/7)}function i$(r){let e=0;return r>=IA&&(r=Math.floor(r/IA),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+s$[r]}var s$=[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 a$=["Data","Links"],c$=["Hash","Name","Tsize"],iw=new TextEncoder;function OA(r,e){if(r===e)return 0;let t=r.Name?iw.encode(r.Name):[],n=e.Name?iw.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function kA(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function RA(r){if(typeof r.asCID=="object"){let t=he.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=he.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=he.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=he.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 sw(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=iw.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(RA),e.Links.sort(OA);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function aw(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!kA(r,a$))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(!kA(t,c$))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&&OA(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function DA(r,e=[]){return sw({Data:r,Links:e})}function NA(r,e,t){return RA({Hash:t,Name:r,Tsize:e})}function LA(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var l$="dag-pb",cw=112;function u$(r){aw(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),PA(e)}function f$(r){let e=LA(r),t=TA(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=he.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function Ru(r){return r?.then!=null}function BA(r=[],e){let t={[cw]:lw,[Ga]:jl,[X8]:Y8,[rw]:nw,[I6]:pm};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ru(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new dh(`Could not load codec for ${n}`)}}function MA(r=[],e){let t={[St.code]:St,[gm.code]:gm,[Dr.code]:Dr};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ru(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new fh(`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 eo=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 Yi=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 c2=0,Du=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},l2=class extends Yi{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===c2){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Du(`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===c2){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Du(`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 eo;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===c2){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Du(`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===c2){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Du(`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 d$(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 Nu=d$;function h$(r){return r[Symbol.asyncIterator]!=null}function p$(r,e){let t=0;if(h$(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Nu(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Oo=p$;function m$(r){return r[Symbol.asyncIterator]!=null}function UA(r){return r?.then!=null}function g$(r,e){let t=0;if(m$(r))return(async function*(){for await(let c of r){let l=e(c,t++);UA(l)&&await l,yield c}})();let n=Nu(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s?.then=="function")return(async function*(){await s,yield o;for(let c of n){let l=e(c,t++);UA(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var uw=g$;var y$=128,u2=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 l2(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??y$}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new oe("blocks:put:duplicate",e)),e):(n.onProgress?.(new oe("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new oe("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Oo(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new oe("blocks:put-many:duplicate",i)),!s}),o=uw(n,async({cid:i})=>{t.onProgress?.(new oe("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new oe("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new lh("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new oe("blocks:get:providers:get",e));let s=await FA(e,this.components.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new oe("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new oe("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new oe("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new oe("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(uw(e,async n=>{let o=await this.child.has(n,t),i=t.offline===!0;if(!o){if(i)throw new lh("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new oe("blocks:get-many:providers:get",n));let a=await FA(n,this.components.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new oe("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new oe("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new oe("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new oe("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 oe("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},f2=class extends u2{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await er(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 fw({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},fw=class extends u2{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=De([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=De([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=De([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=De([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=De([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=De([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=De([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=De([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function w$(r){return typeof r.retrieve=="function"}var b$=(r,e)=>{if(e==null)throw new P(`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(Ru(o)?n=await o:n=o,!we(n.digest,r.multihash.digest))throw new Cs("Hash of downloaded block did not match multihash from passed CID")}};async function FA(r,e,t,n){let o=b$(r,t),i=new AbortController,s=De([i.signal,n.signal]);i.signal;let a=[];for(let c of e)w$(c)&&a.push(c);if(a.length===0)throw new B0(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,f=await c.retrieve(r,{...n,signal:s,validateFn:async 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}}))}catch(c){throw new U0(c.errors,`Failed to load block for ${r}`)}finally{i.abort(),s.clear()}}var Ac=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=Fr(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=Ht.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=Ve();if(this.requests.set(n,i.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 ut(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),i.reject(u),u}}let s=!1,a=new yr({concurrency:this.maxProviders});a.addEventListener("failure",f=>{this.log.error("error querying provider %s, evicting from session - %e",f.detail.job.options.provider,f.detail.error),this.evict(f.detail.job.options.provider)}),a.addEventListener("success",f=>{s=!0,i.resolve(f.detail.result)}),a.addEventListener("idle",()=>{if(s){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),i.resolve(await this.retrieve(e,t))}).catch(f=>{this.log.error("could not find new providers for %c - %e",e,f),i.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=()=>{i.reject(new Hr(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",l);try{return await ut(i.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=Ve(),i=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(;i<t&&this.initialProviders.length>0;){let s=this.initialProviders.pop();if(s==null)break;let a=await this.convertToProvider(s,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(i<this.maxProviders)for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new uh(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),o.reject(s)}),o.promise}};var d2=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??Qo(),this.log=this.logger.forComponent("helia"),this.getHasher=MA(e.hashers,e.loadHasher),this.getCodec=BA(e.codecs,e.loadCodec),this.dns=e.dns??vm(),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 j0(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let i=[o],s=v$(o);s!=null&&i.push(s);let a=x$(o);return a!=null&&i.push(a),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new f2(t,e);this.pins=new $0(e.datastore,n,this.getCodec),this.blockstore=new o2(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await vA(this.datastore),await er(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 an(o.deleteMany((async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new oe("helia:gc:deleted",i))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new oe("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function v$(r){return r?.[ki]}function x$(r){return r?.[Ri]}function E$(r){return r[Symbol.asyncIterator]!=null}function S$(r,e){let t=0;if(E$(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=Nu(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s.then=="function")return(async function*(){yield await s;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield s;for(let c of n)yield a(c,t++)})()}var to=S$;function _$(r){return r[Symbol.asyncIterator]!=null}function A$(r,e){return _$(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 Js=A$;var yh="/ipfs/bitswap/1.2.0";var Vt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(Vt||(Vt={}));var dw;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(dw||(dw={}));(function(r){r.codec=()=>kt(dw)})(Vt||(Vt={}));var Lu;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),Vt.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={cid:ke(0),priority:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.cid=t.bytes();break}case 2:{i.priority=t.int32();break}case 3:{i.cancel=t.bool();break}case 4:{i.wantType=Vt.codec().decode(t);break}case 5:{i.sendDontHave=t.bool();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Lu||(Lu={}));var h2;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let i of t.entries)n.uint32(10),Lu.codec().encode(i,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={entries:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.entries!=null&&i.entries.length===o.limits.entries)throw new dt('Decode error - map field "entries" had too many elements');i.entries.push(Lu.codec().decode(t,t.uint32(),{limits:o.limits?.entries$}));break}case 2:{i.full=t.bool();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(h2||(h2={}));var Bu;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={prefix:ke(0),data:ke(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.prefix=t.bytes();break}case 2:{i.data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Bu||(Bu={}));var ro;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(ro||(ro={}));var p2;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(p2||(p2={}));(function(r){r.codec=()=>kt(p2)})(ro||(ro={}));var Mu;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&p2[t.type]!==0&&(n.uint32(16),ro.codec().encode(t.type,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={cid:ke(0),type:ro.HaveBlock},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.cid=t.bytes();break}case 2:{i.type=ro.codec().decode(t);break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Mu||(Mu={}));var Tc;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),h2.codec().encode(t.wantlist,n)),t.blocks!=null)for(let i of t.blocks)n.uint32(26),Bu.codec().encode(i,n);if(t.blockPresences!=null)for(let i of t.blockPresences)n.uint32(34),Mu.codec().encode(i,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={blocks:[],blockPresences:[],pendingBytes:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.wantlist=h2.codec().decode(t,t.uint32(),{limits:o.limits?.wantlist});break}case 3:{if(o.limits?.blocks!=null&&i.blocks.length===o.limits.blocks)throw new dt('Decode error - map field "blocks" had too many elements');i.blocks.push(Bu.codec().decode(t,t.uint32(),{limits:o.limits?.blocks$}));break}case 4:{if(o.limits?.blockPresences!=null&&i.blockPresences.length===o.limits.blockPresences)throw new dt('Decode error - map field "blockPresences" had too many elements');i.blockPresences.push(Mu.codec().decode(t,t.uint32(),{limits:o.limits?.blockPresences$}));break}case 5:{i.pendingBytes=t.int32();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Tc||(Tc={}));function $A(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var m2=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var T$=4193648,I$=T$+16;function*jA(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],i=0,s=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},f=Tc.encode(l).byteLength,{added:u,hasMore:d,newSize:h}=hw(o,l.blocks,a,e,f,C$);a+=u,f=h;let m=d;({added:u,hasMore:d,newSize:h}=hw(n,l.blockPresences,s,e,f,P$)),s+=u,f=h;let w=d;if({added:u,hasMore:d,newSize:h}=hw(t,l.wantlist.entries,i,e,f,k$),i+=u,f=h,c=!m&&!w&&!d,c||(l.wantlist.full=!1),yield Tc.encode(l),c)break}}function hw(r,e,t,n,o,i){let s=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],f=i(l);if(f>I$)throw new m2("Cannot send block as after encoding it is over the max message size");let u=o+f;if(u>n){a=!0;break}e.push(l),s++,o=u}return{hasMore:a,added:s,newSize:o}}function C$(r){return pw(3,Bu.encode(r))}function P$(r){return pw(4,Mu.encode(r))}function k$(r){return pw(1,Lu.encode(r))}function pw(r,e){let t=je(r),n=je(e.byteLength);return t+n+e.byteLength}var g2=class extends _e{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[yh],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new vr({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new Yo(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let i=gr();e.addEventListener("message",s=>{i.push(s.data)}),e.addEventListener("remoteCloseWrite",()=>{i.end()}),e.addEventListener("close",s=>{s.error!=null&&i.end(s.error)});for await(let s of Ec(i,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Tc.decode(s);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new oe("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a[]",n.id,n.multiaddrs);continue}t?.onProgress?.(new oe("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await an(to(Js(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(i=>e.equals(i.options.peerId)&&i.status==="queued");if(o!=null){o.options.message=$A(o.options.message,t),await o.join({signal:n?.signal});return}await this.sendQueue.add(async i=>{let s=i?.message;if(s==null)throw new P("No message to send");this.log("sendMessage to %p",e),i?.onProgress?.(new oe("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,yh,i);await a.closeRead();try{for(let c of jA(s,this.maxOutgoingMessageSize))a.send(Gi.single(c))||await a.onDrain(i);await a.close(i)}catch(c){i?.onProgress?.(new oe("bitswap:network:send-wantlist:error",{peer:e,error:c})),this.log.error("error sending message to %p - %e",e,c),a.abort(c)}this._updateSentStats(s.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new _n("Network isn't running");t?.onProgress?.(new oe("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),Qr(this.libp2p,"peer:identify",t?.signal,{filter:o=>{if(!o.detail.peerId.equals(e))return!1;if(o.detail.protocols.includes(yh))return!0;throw new Ul(`${e} did not support ${yh}`)}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};var KA=Symbol.for("nodejs.util.inspect.custom"),F$=114,wh=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()})`}[am]=!0;toString(){return this.string==null&&(this.string=ft.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return he.createV1(F$,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return we(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return we(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[KA](){return`PeerId(${this.toString()})`}},bh=class extends wh{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},vh=class extends wh{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},xh=class extends wh{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},$$=2336,Eh=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Dr.digest(B(this.url))}[KA](){return`PeerId(${this.url})`}[am]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return he.createV1($$,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var j$=114,VA=2336;function yt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=lt(ft.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Ro(he.parse(r));if(e==null)throw new P('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=lt(e.decode(r))}return zt(t)}function si(r){if(r.type==="Ed25519")return new vh({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new xh({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new bh({multihash:r.toCID().multihash,publicKey:r});throw new wo}function HA(r){return si(r.publicKey)}function zt(r){if(V$(r))return new bh({multihash:r});if(K$(r))try{let e=Um(r);if(e.type==="Ed25519")return new vh({multihash:r,publicKey:e});if(e.type==="secp256k1")return new xh({multihash:r,publicKey:e})}catch{let t=j(r.digest);return new Eh(new URL(t))}throw new Cs("Supplied PeerID Multihash is invalid")}function Ro(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==j$&&r.code!==VA)throw new rm("Supplied PeerID CID is invalid");if(r.code===VA){let e=j(r.multihash.digest);return new Eh(new URL(e))}return zt(r.multihash)}function K$(r){return r.code===Dr.code}function V$(r){return r.code===St.code}function Ic(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 y2(r){let e=lt(ft.decode(`z${r}`));return zt(e)}var $r=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 Ic(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 Ic(this.map.values(),e=>e.key)}values(){return Ic(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Bn=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 Ic(this.set.entries(),e=>{let t=y2(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=y2(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ic(this.set.values(),e=>y2(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}};function mw(){return new Bn}var w2=class{filter;constructor(e,t){this.filter=Fr(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function gw(r,e=.001){return new w2(r,e)}var yw=class extends $r{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 Qi(r){let{name:e,metrics:t}=r,n;return t!=null?n=new yw({name:e,metrics:t}):n=new $r,n}var Zi=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=Ht.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=Ht.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=Ht.encode(e.multihash.bytes);this.blocks.set(n,t)}};function H$(r){let e=new Uint8Array(r.reduce((n,o)=>n+je(o),0)),t=0;for(let n of r)e=Mr(n,e,t),t+=je(n);return e}var qA=H$;function ww(r){return qA([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var b2=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new Zi,n=new Set;for(let[o,i]of this.wants.entries())try{let s=await R0(this.blockstore.get(i.cid,e));i.wantType===Vt.WantHave?s.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:ww(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ro.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:ww(i.cid)}))}catch(s){if(s.name!=="NotFoundError")throw s;if(this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ro.DoNotHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var v2=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Qi({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new b2({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,i)=>o+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let i=he.decode(o.cid),s=j(i.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(s)):(o.wantType===Vt.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(s,{cid:i,priority:o.priority,wantType:o.wantType??Vt.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=j(e.multihash.bytes,"base64"),o=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&o.push(i);await Promise.all(o.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var bw=class extends Ac{wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has&&o.block!=null)return o.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}async convertToProvider(e,t){return on(e)?e:(await this.libp2p.dial(e,t)).remotePeer}};function WA(r,e){return new bw(r,e)}var x2=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};function q$(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Cn(r);e.push(t),r=r.slice(je(t))}return e}var zA=q$;var E2=class extends _e{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),this.peers=Qi({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Wt({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=j(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??Vt.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===Vt.WantHave&&t.wantType===Vt.WantBlock&&(o.wantType=Vt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===Vt.WantBlock?(await Qr(this,"block",t?.signal,{filter:a=>we(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Qr(this,"presence",t?.signal,{filter:s=>we(e.multihash.digest,s.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=Ve(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Zi;for(let[i,s]of this.wants.entries())t.has(i)||s.cancel||(n.add(i),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer - %e",i)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=j(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Zi;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:Vt.WantHave,priority:1}),await this.network.sendMessage(t,o),(await Qr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&we(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:Vt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Zi;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:Vt.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await Qr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&we(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=j(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let i=zA(o.prefix),s=i[0],a=i[1],c=i[2],l=i[3],f=c===St.code?St:await this.hashLoader?.getHasher(c);if(f==null){this.log.error("unknown hash algorithm",c);continue}let u=f.digest(o.data,{truncate:l});u.then!=null&&(u=await u);let d=he.create(s===0?0:1,a,u);this.log("received block from %p for %c",e,d),this.safeDispatchEvent("block",{detail:{sender:e,cid:d,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:d,has:!0,block:o.data}});let h=j(d.multihash.bytes,"base64"),m=this.wants.get(h);m!=null&&(m.cancel=!0,n=!0)}for(let{cid:o,type:i}of t.blockPresences){let s=he.decode(o);this.log("received %s from %p for %c",i,e,s),this.safeDispatchEvent("presence",{detail:{sender:e,cid:s,has:i===ro.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Zi(!0);for(let[o,i]of this.wants.entries())i.cancel||(t.add(o),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:Vt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var S2=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new x2(e),this.network=new g2(e,t),this.peerWantLists=new v2({...e,network:this.network},t),this.wantList=new E2({...e,network:this.network},t)}createSession(e={}){return WA({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=De([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,i)});try{let i=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new oe("bitswap:block",{cid:e,sender:i.sender})),i.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var GA=(r,e={})=>new S2(r,e);var vw=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=GA(e,{hashLoader:{getHasher:async o=>n(o)},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function xw(r={}){return e=>new vw(e,r)}var W$=[6,53,56,54,55];function XA(r){return ZA("sni",r)?.value}function YA(r){let e=ZA("tcp",r)?.value;return e==null?"":`:${e}`}function ZA(r,e){return e.find(t=>t.name===r)}function QA(r){return r.some(({code:e})=>e===448)}function Do(r,e){let t=JA[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 JA={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://${Do(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Do(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`${Do(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Do(t,e)}`},http:(r,e)=>{let t=QA(e),n=XA(e),o=YA(e);if(t&&n!=null)return`https://${n}${o}`;let i=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Do(s,e);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Do(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 Do(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Do(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Do(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=QA(e),n=XA(e),o=YA(e);if(t&&n!=null)return`wss://${n}${o}`;let i=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Do(s,e);return a=a?.replace("tcp://",""),`${i}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Do(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function ea(r,e){let n=ie(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=JA[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let s=i(o,n)??"";return e?.assumeHttp!==!1&&W$.includes(o.code)&&(s=s.replace(/^.*:\/\//,""),o.value==="443"?s=`https://${s}`:s=`http://${s}`),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}var at=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Pe=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),eT=r=>({match:e=>r.match(e)===!1?e:!1}),We=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),jr=(...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}}),Qe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ct(...r){function e(o){if(o==null)return!1;let i=o.getComponents();for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matchers:r,matches:t,exactMatch:n}}var z$=Pe(421),tT=ct(z$),A2=Pe(54),T2=Pe(55),I2=Pe(56),Sw=Pe(53),Wce=ct(A2,We(Pe(421))),zce=ct(T2,We(Pe(421))),Gce=ct(I2,We(Pe(421))),C2=ct(jr(Sw,I2,A2,T2),We(Pe(421))),rT=Qe(Pe(4),We(Pe(43))),nT=Qe(We(Pe(42)),Pe(41),We(Pe(43))),_w=jr(rT,nT),Cc=jr(_w,Sw,A2,T2,I2),oT=ct(jr(_w,Qe(jr(Sw,I2,A2,T2),We(Pe(421))))),Aw=ct(rT),Tw=ct(nT),iT=ct(_w),Iw=Qe(Cc,Pe(6)),Sh=Qe(Cc,Pe(273)),Pc=ct(Qe(Iw,We(Pe(421)))),Xce=ct(Sh),Cw=Qe(Sh,at(460),We(Pe(421))),P2=Qe(Sh,at(461),We(Pe(421))),G$=jr(Cw,P2),Yce=ct(Cw),sT=ct(P2),Ew=jr(Cc,Iw,Sh,Cw,P2),aT=jr(Qe(Ew,at(477),We(Pe(421)))),Ji=ct(aT),cT=jr(Qe(Ew,at(478),We(Pe(421))),Qe(Ew,at(448),We(Pe(449)),at(477),We(Pe(421)))),kc=ct(cT),lT=Qe(Sh,at(280),We(Pe(466)),We(Pe(466)),We(Pe(421))),_h=ct(lT),uT=Qe(P2,at(465),We(Pe(466)),We(Pe(466)),We(Pe(421))),Pw=ct(uT),_2=jr(aT,cT,Qe(Iw,We(Pe(421))),Qe(G$,We(Pe(421))),Qe(Cc,We(Pe(421))),lT,uT,Pe(421)),Uu=ct(_2),X$=Qe(We(_2),at(290),eT(at(281)),We(Pe(421))),fr=ct(X$),Y$=jr(Qe(_2,at(290),at(281),We(Pe(421))),Qe(_2,at(281),We(Pe(421))),Qe(at(281),We(Pe(421)))),Ah=ct(Y$),Q$=jr(Qe(Cc,Pe(6),at(480),We(Pe(421))),Qe(Cc,at(480),We(Pe(421)))),fT=ct(Q$),Z$=Qe(Cc,jr(Qe(Pe(6,"443"),at(480)),Qe(Pe(6),at(443)),Qe(Pe(6),at(448),at(480)),Qe(at(448),at(480)),at(448),at(443)),We(Pe(421))),dT=ct(Z$),J$=jr(Qe(Pe(777),We(Pe(421)))),Qce=ct(J$),ej=jr(Qe(Pe(400),We(Pe(421)))),Zce=ct(ej);function kw(r,e,t){return r.filter(n=>{if(dT.matches(n)||e&&fT.matches(n))return t||C2.matches(n)?!0:Mt(n)===!1;if(!e&&t){let{host:o}=Ce(n);if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*k2(r,e,t,n,o,i={}){for await(let s of e.findProviders(r,i)){let a=kw(s.multiaddrs,n,o);if(a.length===0)continue;let c=ea(a[0]),l={type:"trustless-gateway",cid:r,url:c.toString(),routing:s.routing};i?.onProgress?.(new oe("trustless-gateway:found-provider",l)),yield new Fu(c,{logger:t,transformRequestInit:i.transformRequestInit})}}async function hT(r,e,t){let{signal:n,log:o}=t??{},i=r.headers.get("content-length");if(i!=null){let c=parseInt(i,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 s=r.body?.getReader();if(s==null)throw new Error("Response body is not readable");let a=new fe;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await s.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{s.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{s.releaseLock()})}return a.subarray()}var Fu=class{url;#e=0;#t=0;#r=0;#s=0;#i=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 Ht.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=pT}={}){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 i=this.#f(e),s=new AbortController,a=()=>{s.abort()};t?.addEventListener("abort",a);try{let c=this.#i.get(i);if(c==null){this.#e++;let l={signal:s.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},f=this.transformRequestInit!=null?await this.transformRequestInit(l):l,u=new Headers(f.headers);this.log(`sending request
|
|
13
|
+
${e}[Error list was empty]`,t.trim()}return nx(r,e)}sn.formatters.e=r=>r==null?"undefined":ix(r);function uL(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 Qo(r){return{forComponent(e){return zn(e,r)}}}function zn(r,e){let t=uL(`${r}:trace`);return sn.enabled(`${r}:trace`)&&sn.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=sn(`${r}:trace`,e)),Object.assign(sn(r,e),{error:sn(`${r}:error`,e),trace:t,newScope:n=>zn(`${r}:${n}`,e)})}function ox(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var oe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var fm=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var g6=nr(ax(),1);var y6=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},cx=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function w6(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=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(s?.aborted){d(cx(s));return}if(s&&(c=()=>{d(cx(s))},s.addEventListener("abort",c,{once:!0})),r.then(u,d),t===Number.POSITIVE_INFINITY)return;let h=new y6;a=i.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){d(m)}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&&s&&s.removeEventListener("abort",c)});return f.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},f}function b6(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var fd=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},i={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(i);return}let s=b6(this.#e,i,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,i)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var za=class extends g6.default{#e;#t;#r=0;#a;#c=!1;#m=!1;#u;#T=0;#b=0;#f;#d;#l;#s=[];#i=0;#n;#I;#o=0;#y;#h;#R=1n;#w=new Map;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:fd,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#u=e.interval,this.#l=e.strict,this.#n=new e.queueClass,this.#I=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.#h=e.autoStart===!1,this.#$()}#v(e){for(;this.#i<this.#s.length;){let n=this.#s[this.#i];if(n!==void 0&&e-n>=this.#u)this.#i++;else break}(this.#i>100&&this.#i>this.#s.length/2||this.#i===this.#s.length)&&(this.#s=this.#s.slice(this.#i),this.#i=0)}#D(e){this.#l?this.#s.push(e):this.#r++}#N(){this.#l?this.#s.length>this.#i&&this.#s.pop():this.#r>0&&this.#r--}#x(){return this.#s.length-this.#i}get#L(){return this.#t?!0:this.#l?this.#x()<this.#a:this.#r<this.#a}get#B(){return this.#o<this.#y}#M(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#_(),this.emit("next")}#U(){this.#d=void 0,this.#k(),this.#P()}#F(e){if(this.#l){if(this.#v(e),this.#x()>=this.#a){let n=this.#s[this.#i],o=this.#u-(e-n);return this.#E(o),!0}return!1}if(this.#f===void 0){let t=this.#T-e;if(t<0){if(this.#b>0){let n=e-this.#b;if(n<this.#u)return this.#E(this.#u-n),!0}this.#r=this.#e?this.#o:0}else return this.#E(t),!0}return!1}#E(e){this.#d===void 0&&(this.#d=setTimeout(()=>{this.#U()},e))}#S(){this.#f&&(clearInterval(this.#f),this.#f=void 0)}#C(){this.#d&&(clearTimeout(this.#d),this.#d=void 0)}#_(){if(this.#n.size===0){if(this.#S(),this.emit("empty"),this.#o===0){if(this.#C(),this.#l&&this.#i>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#h){let t=Date.now(),n=!this.#F(t);if(this.#L&&this.#B){let o=this.#n.dequeue();this.#t||(this.#D(t),this.#g()),this.emit("active"),o(),n&&this.#P(),e=!0}}return e}#P(){this.#t||this.#f!==void 0||this.#l||(this.#f=setInterval(()=>{this.#k()},this.#u),this.#T=Date.now()+this.#u)}#k(){this.#l||(this.#r===0&&this.#o===0&&this.#f&&this.#S(),this.#r=this.#e?this.#o:0),this.#A(),this.#g()}#A(){for(;this.#_(););}get concurrency(){return this.#y}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.#y=e,this.#A()}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={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let i=Symbol(`task-${t.id}`);this.#n.enqueue(async()=>{this.#o++,this.#w.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let s;try{try{t.signal?.throwIfAborted()}catch(l){throw this.#j(),this.#w.delete(i),l}this.#b=Date.now();let a=e({signal:t.signal});if(t.timeout&&(a=w6(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)=>{s=()=>{u(l.reason)},l.addEventListener("abort",s,{once:!0})})])}let c=await a;n(c),this.emit("completed",c)}catch(a){o(a),this.emit("error",a)}finally{s&&t.signal?.removeEventListener("abort",s),this.#w.delete(i),queueMicrotask(()=>{this.#M()})}},t),this.emit("add"),this.#_()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#h?(this.#h=!1,this.#A(),this):this}pause(){this.#h=!0}clear(){this.#n=new this.#I,this.#S(),this.#O(),this.emit("empty"),this.#o===0&&(this.#C(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#o===0&&this.#n.size===0||await this.#p("idle")}async onPendingZero(){this.#o!==0&&await this.#p("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#p("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#p("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#p(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.#h}#$(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#g()}),this.on("next",()=>{this.#g()}))}#g(){this.#t||this.#m||(this.#m=!0,queueMicrotask(()=>{this.#m=!1,this.#O()}))}#j(){this.#t||(this.#N(),this.#g())}#O(){let e=this.#c;if(this.#t||this.#n.size===0){e&&(this.#c=!1,this.emit("rateLimitCleared"));return}let t;if(this.#l){let o=Date.now();this.#v(o),t=this.#x()}else t=this.#r;let n=t>=this.#a;n!==e&&(this.#c=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#c}get isSaturated(){return this.#o===this.#y&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#w.values()].map(e=>({...e}))}};function hm(r){let e=[Tn.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var v6={};Nt(v6,{base10:()=>hL});var hL=Rs({prefix:"9",name:"base10",alphabet:"0123456789"});var x6={};Nt(x6,{base16:()=>pL,base16upper:()=>mL});var pL=Lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),mL=Lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var E6={};Nt(E6,{base2:()=>gL});var gL=Lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var S6={};Nt(S6,{base256emoji:()=>xL});var lx=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),yL=lx.reduce((r,e,t)=>(r[t]=e,r),[]),wL=lx.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function bL(r){return r.reduce((e,t)=>(e+=yL[t],e),"")}function vL(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=wL[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var xL=$l({prefix:"\u{1F680}",name:"base256emoji",encode:bL,decode:vL});var _6={};Nt(_6,{base36:()=>Gn,base36upper:()=>EL});var Gn=Rs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),EL=Rs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var A6={};Nt(A6,{base8:()=>SL});var SL=Lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var T6={};Nt(T6,{identity:()=>_L});var _L=$l({prefix:"\0",name:"identity",encode:r=>Jv(r),decode:r=>Zv(r)});var pm={};Nt(pm,{code:()=>I6,decode:()=>PL,encode:()=>CL,name:()=>IL});var AL=new TextEncoder,TL=new TextDecoder,IL="json",I6=512;function CL(r){return AL.encode(JSON.stringify(r))}function PL(r){return JSON.parse(TL.decode(r))}var jl={};Nt(jl,{code:()=>Ga,decode:()=>RL,encode:()=>OL,name:()=>kL});var kL="raw",Ga=85;function OL(r){return bo(r)}function RL(r){return bo(r)}var k6={};Nt(k6,{identity:()=>Dr});var Bt={};Nt(Bt,{Digest:()=>Xa,create:()=>Wr,decode:()=>lt,equals:()=>P6,hasCode:()=>QL});var DL=dx,ux=128,NL=127,LL=~NL,BL=Math.pow(2,31);function dx(r,e,t){e=e||[],t=t||0;for(var n=t;r>=BL;)e[t++]=r&255|ux,r/=128;for(;r&LL;)e[t++]=r&255|ux,r>>>=7;return e[t]=r|0,dx.bytes=t-n+1,e}var ML=C6,UL=128,fx=127;function C6(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw C6.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&fx)<<o:(s&fx)*Math.pow(2,o),o+=7}while(s>=UL);return C6.bytes=i-n,t}var FL=Math.pow(2,7),$L=Math.pow(2,14),jL=Math.pow(2,21),KL=Math.pow(2,28),VL=Math.pow(2,35),HL=Math.pow(2,42),qL=Math.pow(2,49),WL=Math.pow(2,56),zL=Math.pow(2,63),GL=function(r){return r<FL?1:r<$L?2:r<jL?3:r<KL?4:r<VL?5:r<HL?6:r<qL?7:r<WL?8:r<zL?9:10},XL={encode:DL,decode:ML,encodingLength:GL},YL=XL,dd=YL;function hd(r,e=0){return[dd.decode(r,e),dd.decode.bytes]}function Kl(r,e,t=0){return dd.encode(r,e,t),e}function Vl(r){return dd.encodingLength(r)}function Wr(r,e){let t=e.byteLength,n=Vl(r),o=n+Vl(t),i=new Uint8Array(o+t);return Kl(r,i,0),Kl(t,i,n),i.set(e,o),new Xa(r,t,e,i)}function lt(r){let e=bo(r),[t,n]=hd(e),[o,i]=hd(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Xa(t,o,s,e)}function P6(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Qv(r.bytes,t.bytes)}}var Xa=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function QL(r,e){return r.code===e}var hx=0,ZL="identity",px=bo;function JL(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Wr(hx,px(r))}var Dr={code:hx,name:ZL,encode:px,digest:JL};var R6={};Nt(R6,{sha256:()=>St,sha512:()=>gm});var eB=20;function pd({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new O6(r,e,t,n,o)}var O6=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??eB,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?mx(n,this.code,t?.truncate):n.then(o=>mx(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function mx(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Wr(e,r)}function yx(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var St=pd({name:"sha2-256",code:18,encode:yx("SHA-256")}),gm=pd({name:"sha2-512",code:19,encode:yx("SHA-512")});function wx(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return rB(t,D6(r),e??ft.encoder);default:return nB(t,D6(r),e??ir.encoder)}}var bx=new WeakMap;function D6(r){let e=bx.get(r);if(e==null){let t=new Map;return bx.set(r,t),t}return e}var he=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==md)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==oB)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Wr(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&P6(e.multihash,n.multihash)}toString(e){return wx(this,e)}toJSON(){return{"/":wx(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??vx(n,o,i.bytes))}else if(t[iB]===!0){let{version:n,multihash:o,code:i}=t,s=lt(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==md)throw new Error(`Version 0 CID must use dag-pb (code: ${md}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=vx(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,md,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=bo(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Xa(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,d]=hd(e.subarray(t));return t+=d,u},o=n(),i=md;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=tB(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return D6(i).set(n,e),i}};function tB(r,e){switch(r[0]){case"Q":{let t=e??ft;return[ft.prefix,t.decode(`${ft.prefix}${r}`)]}case ft.prefix:{let t=e??ft;return[ft.prefix,t.decode(r)]}case ir.prefix:{let t=e??ir;return[ir.prefix,t.decode(r)]}case Gn.prefix:{let t=e??Gn;return[Gn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function rB(r,e,t){let{prefix:n}=t;if(n!==ft.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function nB(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var md=112,oB=18;function vx(r,e,t){let n=Vl(r),o=n+Vl(e),i=new Uint8Array(o+t.byteLength);return Kl(r,i,0),Kl(e,i,n),i.set(t,o),i}var iB=Symbol.for("@ipld/js-cid/CID");var Ya={...T6,...E6,...A6,...v6,...x6,...f6,..._6,...d6,...h6,...S6},XG={...R6,...k6};function ke(r=0){return new Uint8Array(r)}function Ot(r=0){return new Uint8Array(r)}function Ex(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var xx=Ex("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),N6=Ex("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ot(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),sB={utf8:xx,"utf-8":xx,hex:Ya.base16,latin1:N6,ascii:N6,binary:N6,...Ya},ym=sB;function j(r,e="utf8"){let t=ym[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var L6=60;function wm(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:Tn[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Tn[e.type],TTL:e.TTL??e.ttl??L6,data:e.data instanceof Uint8Array?j(e.data):e.data}))}}var aB=4;function B6(r,e={}){let t=new za({concurrency:e.queryConcurrency??aB});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),hm(o.types).forEach(a=>{i.append("type",Tn[a])}),o.onProgress?.(new oe("dns:query",n));let s=await t.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=wm(await a.json());return o.onProgress?.(new oe("dns:response",c)),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Sx(){return[B6("https://cloudflare-dns.com/dns-query"),B6("https://dns.google/resolve")]}var Tx=nr(Ax(),1);var M6=class{lru;constructor(e){this.lru=(0,Tx.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return wm({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:Tn[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??L6)*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 Ix(r){return new M6(r)}var cB=1e3,bm=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Ix(e.cacheSize??cB),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["."]=Sx())}async query(e,t={}){let n=hm(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new oe("dns:cache",o)),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new oe("dns:error",l))}}throw new fm(a,`DNS lookup of ${e} ${n} failed`)}};var Tn;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Tn||(Tn={}));function vm(r={}){return new bm(r)}function lB(r){return r[Symbol.asyncIterator]!=null}function uB(r){if(lB(r))return(async()=>{for await(let e of r);})();for(let e of r);}var an=uB;var gd=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},yd=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},xm=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Cx={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new xm("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var qt=Cx;function we(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function gt(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Ot(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var kx=Symbol.for("@achingbrain/uint8arraylist");function Px(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Hl(r){return!!r?.[kx]}var fe=class r{bufs;length;[kx]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Hl(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Hl(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Px(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Px(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Hl(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return gt(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:gt(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(s);break}let u=e-a;n.push(s.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(f){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Hl(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let u=0;u<i;u++)s[u]=-1;for(let u=0;u<o;u++)s[n[u]]=u;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let u=t;u<=c;u+=f){f=0;for(let d=l;d>=0;d--){let h=this.get(u+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return u}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ot(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ke(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ke(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ke(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ot(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ke(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ke(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ke(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ke(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ke(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!we(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,i)=>o+i.byteLength,0)),n.length=t,n}};function B(r,e="utf8"){let t=ym[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var dB=parseInt("11111",2),U6=parseInt("10000000",2),hB=parseInt("01111111",2),Ox={0:wd,1:wd,2:pB,3:yB,4:wB,5:gB,6:mB,16:wd,22:wd,48:wd};function Xn(r,e={offset:0}){let t=r[e.offset]&dB;if(e.offset++,Ox[t]!=null)return Ox[t](r,e);throw new Error("No decoder for tag "+t)}function bd(r,e){let t=0;if((r[e.offset]&U6)===U6){let n=r[e.offset]&hB,o="0x";e.offset++;for(let i=0;i<n;i++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function wd(r,e){bd(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Xn(r,e);if(n===null)break;t.push(n)}return t}function pB(r,e){let t=bd(r,e),n=e.offset,o=e.offset+t,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return e.offset+=t,Uint8Array.from(i)}function mB(r,e){let t=bd(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let f=0;for(let u=0;u<c.length;u++)f+=c[u]<<u*7;a+=`.${f}`,c=[]}}return a}function gB(r,e){return e.offset++,null}function yB(r,e){let t=bd(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function wB(r,e){let t=bd(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function bB(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new fe;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Em(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=bB(r.byteLength);return new fe(Uint8Array.from([e.byteLength|U6]),e)}function zr(r){let e=new fe,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new fe(Uint8Array.from([2]),Em(e),e)}function vd(r){let e=Uint8Array.from([0]),t=new fe(e,r);return new fe(Uint8Array.from([3]),Em(t),t)}function Rx(r){return new fe(Uint8Array.from([4]),Em(r),r)}function vo(r,e=48){let t=new fe;for(let n of r)t.append(n);return new fe(Uint8Array.from([e]),Em(t),t)}var Dx="1.2.840.10045.3.1.7",Nx="1.3.132.0.34",Lx="1.3.132.0.35";async function Bx(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function Mx(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Ux(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),i}var vB=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),xB=Uint8Array.from([6,5,43,129,4,0,34]),EB=Uint8Array.from([6,5,43,129,4,0,35]),Fx={ext:!0,kty:"EC",crv:"P-256"},$x={ext:!0,kty:"EC",crv:"P-384"},jx={ext:!0,kty:"EC",crv:"P-521"},ql=32,Wl=48,zl=66;function Kx(r){let e=Xn(r);return F6(e)}function F6(r){let e=r[1],t=j(e,"base64url"),n=r[2][1][0],o=1,i,s;if(e.byteLength===ql)return i=j(n.subarray(o,o+ql),"base64url"),s=j(n.subarray(o+ql),"base64url"),new Za({...Fx,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===Wl)return i=j(n.subarray(o,o+Wl),"base64url"),s=j(n.subarray(o+Wl),"base64url"),new Za({...$x,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===zl)return i=j(n.subarray(o,o+zl),"base64url"),s=j(n.subarray(o+zl),"base64url"),new Za({...jx,key_ops:["sign"],d:t,x:i,y:s});throw new P(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function $6(r){let e=Xn(r);return Vx(e)}function Vx(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===ql*2+1)return n=j(e.subarray(t,t+ql),"base64url"),o=j(e.subarray(t+ql),"base64url"),new Qa({...Fx,key_ops:["verify"],x:n,y:o});if(e.byteLength===Wl*2+1)return n=j(e.subarray(t,t+Wl),"base64url"),o=j(e.subarray(t+Wl),"base64url"),new Qa({...$x,key_ops:["verify"],x:n,y:o});if(e.byteLength===zl*2+1)return n=j(e.subarray(t,t+zl),"base64url"),o=j(e.subarray(t+zl),"base64url"),new Qa({...jx,key_ops:["verify"],x:n,y:o});throw new P(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Hx(r){return vo([zr(Uint8Array.from([1])),Rx(B(r.d??"","base64url")),vo([Wx(r.crv)],160),vo([vd(new fe(Uint8Array.from([4]),B(r.x??"","base64url"),B(r.y??"","base64url")))],161)]).subarray()}function qx(r){return vo([zr(Uint8Array.from([1])),vo([Wx(r.crv)],160),vo([vd(new fe(Uint8Array.from([4]),B(r.x??"","base64url"),B(r.y??"","base64url")))],161)]).subarray()}function Wx(r){if(r==="P-256")return vB;if(r==="P-384")return xB;if(r==="P-521")return EB;throw new P(`Invalid curve ${r}`)}async function zx(r="P-256"){let e=await Bx(r);return new Za(e.privateKey)}var Qa=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=qx(this.jwk)),this._raw}toMultihash(){return Dr.digest(sr(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}async verify(e,t,n){return Ux(this.jwk,t,e,n)}},Za=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Qa({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Hx(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}async sign(e,t){return Mx(this.jwk,e,t)}};function Ja(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Nr(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function Oe(r,e,t=""){let n=Ja(r),o=r?.length,i=e!==void 0;if(!n||i&&o!==e){let s=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return r}function Ni(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Nr(r.outputLen),Nr(r.blockLen)}function Gl(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Xx(r,e){Oe(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Lr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ec(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function xo(r,e){return r<<32-e|r>>>e}function Sm(r,e){return r<<e|r>>>32-e>>>0}var Yx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",SB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Li(r){if(Oe(r),Yx)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=SB[r[t]];return e}var Di={_0:48,_9:57,A:65,F:70,a:97,f:102};function Gx(r){if(r>=Di._0&&r<=Di._9)return r-Di._0;if(r>=Di.A&&r<=Di.F)return r-(Di.A-10);if(r>=Di.a&&r<=Di.f)return r-(Di.a-10)}function Bi(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Yx)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,i=0;o<t;o++,i+=2){let s=Gx(r.charCodeAt(i)),a=Gx(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}var _B=async()=>{};async function Qx(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-n;i>=0&&i<e||(await _B(),n+=i)}}function AB(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function j6(r,e=""){return typeof r=="string"?AB(r):Oe(r,void 0,e)}function cn(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Oe(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function Zx(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new Error("options must be object or undefined");return Object.assign(r,e)}function xd(r,e={}){let t=(o,i)=>r(i).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Zo(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var K6=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function _m(r,e,t){return r&e^~r&t}function Am(r,e,t){return r&e^r&t^e&t}var tc=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ec(this.buffer)}update(e){Gl(this),Oe(e);let{view:t,buffer:n,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=ec(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Gl(this),Xx(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[s++]=128,Lr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let u=s;u<o;u++)t[u]=0;n.setBigUint64(o-8,BigInt(this.length*8),i),this.process(n,0);let a=ec(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Mi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var pr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Tm=BigInt(4294967295),Jx=BigInt(32);function TB(r,e=!1){return e?{h:Number(r&Tm),l:Number(r>>Jx&Tm)}:{h:Number(r>>Jx&Tm)|0,l:Number(r&Tm)|0}}function eE(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let i=0;i<t;i++){let{h:s,l:a}=TB(r[i],e);[n[i],o[i]]=[s,a]}return[n,o]}var V6=(r,e,t)=>r>>>t,H6=(r,e,t)=>r<<32-t|e>>>t,rc=(r,e,t)=>r>>>t|e<<32-t,nc=(r,e,t)=>r<<32-t|e>>>t,Ed=(r,e,t)=>r<<64-t|e>>>t-32,Sd=(r,e,t)=>r>>>t-32|e<<64-t;function Jo(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var tE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),rE=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,nE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),oE=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,iE=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),sE=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var CB=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ds=new Uint32Array(64),q6=class extends tc{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Ds[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Ds[u-15],h=Ds[u-2],m=xo(d,7)^xo(d,18)^d>>>3,w=xo(h,17)^xo(h,19)^h>>>10;Ds[u]=w+Ds[u-7]+m+Ds[u-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){let d=xo(a,6)^xo(a,11)^xo(a,25),h=f+d+_m(a,c,l)+CB[u]+Ds[u]|0,w=(xo(n,2)^xo(n,13)^xo(n,22))+Am(n,o,i)|0;f=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(n,o,i,s,a,c,l,f)}roundClean(){Lr(Ds)}destroy(){this.set(0,0,0,0,0,0,0,0),Lr(this.buffer)}},W6=class extends q6{A=Mi[0]|0;B=Mi[1]|0;C=Mi[2]|0;D=Mi[3]|0;E=Mi[4]|0;F=Mi[5]|0;G=Mi[6]|0;H=Mi[7]|0;constructor(){super(32)}};var aE=eE(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),PB=aE[0],kB=aE[1],Ns=new Uint32Array(80),Ls=new Uint32Array(80),z6=class extends tc{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:f,Fh:u,Fl:d,Gh:h,Gl:m,Hh:w,Hl:y}=this;return[e,t,n,o,i,s,a,c,l,f,u,d,h,m,w,y]}set(e,t,n,o,i,s,a,c,l,f,u,d,h,m,w,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=f|0,this.Fh=u|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=w|0,this.Hl=y|0}process(e,t){for(let O=0;O<16;O++,t+=4)Ns[O]=e.getUint32(t),Ls[O]=e.getUint32(t+=4);for(let O=16;O<80;O++){let V=Ns[O-15]|0,Q=Ls[O-15]|0,Z=rc(V,Q,1)^rc(V,Q,8)^V6(V,Q,7),se=nc(V,Q,1)^nc(V,Q,8)^H6(V,Q,7),C=Ns[O-2]|0,T=Ls[O-2]|0,K=rc(C,T,19)^Ed(C,T,61)^V6(C,T,6),z=nc(C,T,19)^Sd(C,T,61)^H6(C,T,6),U=nE(se,z,Ls[O-7],Ls[O-16]),I=oE(U,Z,K,Ns[O-7],Ns[O-16]);Ns[O]=I|0,Ls[O]=U|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:h,Fl:m,Gh:w,Gl:y,Hh:b,Hl:N}=this;for(let O=0;O<80;O++){let V=rc(u,d,14)^rc(u,d,18)^Ed(u,d,41),Q=nc(u,d,14)^nc(u,d,18)^Sd(u,d,41),Z=u&h^~u&w,se=d&m^~d&y,C=iE(N,Q,se,kB[O],Ls[O]),T=sE(C,b,V,Z,PB[O],Ns[O]),K=C|0,z=rc(n,o,28)^Ed(n,o,34)^Ed(n,o,39),U=nc(n,o,28)^Sd(n,o,34)^Sd(n,o,39),I=n&i^n&a^i&a,S=o&s^o&c^s&c;b=w|0,N=y|0,w=h|0,y=m|0,h=u|0,m=d|0,{h:u,l:d}=Jo(l|0,f|0,T|0,K|0),l=a|0,f=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let x=tE(K,U,S);n=rE(x,T,z,I),o=x|0}({h:n,l:o}=Jo(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Jo(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Jo(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=Jo(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:d}=Jo(this.Eh|0,this.El|0,u|0,d|0),{h,l:m}=Jo(this.Fh|0,this.Fl|0,h|0,m|0),{h:w,l:y}=Jo(this.Gh|0,this.Gl|0,w|0,y|0),{h:b,l:N}=Jo(this.Hh|0,this.Hl|0,b|0,N|0),this.set(n,o,i,s,a,c,l,f,u,d,h,m,w,y,b,N)}roundClean(){Lr(Ns,Ls)}destroy(){Lr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},G6=class extends z6{Ah=pr[0]|0;Al=pr[1]|0;Bh=pr[2]|0;Bl=pr[3]|0;Ch=pr[4]|0;Cl=pr[5]|0;Dh=pr[6]|0;Dl=pr[7]|0;Eh=pr[8]|0;El=pr[9]|0;Fh=pr[10]|0;Fl=pr[11]|0;Gh=pr[12]|0;Gl=pr[13]|0;Hh=pr[14]|0;Hl=pr[15]|0;constructor(){super(64)}};var Yn=xd(()=>new W6,K6(1));var Bs=xd(()=>new G6,K6(3));var Y6=BigInt(0),X6=BigInt(1);function Ui(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function cE(r){if(typeof r=="bigint"){if(!Im(r))throw new Error("positive bigint expected, got "+r)}else Nr(r);return r}function _d(r){let e=cE(r).toString(16);return e.length&1?"0"+e:e}function lE(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Y6:BigInt("0x"+r)}function Xl(r){return lE(Li(r))}function ei(r){return lE(Li(oc(Oe(r)).reverse()))}function Cm(r,e){Nr(e),r=cE(r);let t=Bi(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Ad(r,e){return Cm(r,e).reverse()}function oc(r){return Uint8Array.from(r)}var Im=r=>typeof r=="bigint"&&Y6<=r;function OB(r,e,t){return Im(r)&&Im(e)&&Im(t)&&e<=r&&r<t}function Ms(r,e,t,n){if(!OB(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Q6(r){let e;for(e=0;r>Y6;r>>=X6,e+=1);return e}var Td=r=>(X6<<BigInt(r))-X6;function uE(r,e,t){if(Nr(r,"hashLen"),Nr(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),f=0,u=()=>{c.fill(1),l.fill(0),f=0},d=(...y)=>t(l,cn(c,...y)),h=(y=o)=>{l=d(i,y),c=d(),y.length!==0&&(l=d(s,y),c=d())},m=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,b=[];for(;y<e;){c=d();let N=c.slice();b.push(N),y+=c.length}return cn(...b)};return(y,b)=>{u(),h(y);let N;for(;!(N=b(m()));)h();return u(),N}}function ti(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(i,s,a){let c=r[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>n(a,c,s));o(e,!1),o(t,!0)}function Yl(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let i=r(t,...n);return e.set(t,i),i}}var Gr=BigInt(0),ar=BigInt(1),ic=BigInt(2),hE=BigInt(3),pE=BigInt(4),mE=BigInt(5),RB=BigInt(7),gE=BigInt(8),DB=BigInt(9),yE=BigInt(16);function Pt(r,e){let t=r%e;return t>=Gr?t:e+t}function _t(r,e,t){let n=r;for(;e-- >Gr;)n*=n,n%=t;return n}function fE(r,e){if(r===Gr)throw new Error("invert: expected non-zero number");if(e<=Gr)throw new Error("invert: expected positive modulus, got "+e);let t=Pt(r,e),n=e,o=Gr,i=ar,s=ar,a=Gr;for(;t!==Gr;){let l=n/t,f=n%t,u=o-s*l,d=i-a*l;n=t,t=f,o=s,i=a,s=u,a=d}if(n!==ar)throw new Error("invert: does not exist");return Pt(o,e)}function J6(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function wE(r,e){let t=(r.ORDER+ar)/pE,n=r.pow(e,t);return J6(r,n,e),n}function NB(r,e){let t=(r.ORDER-mE)/gE,n=r.mul(e,ic),o=r.pow(n,t),i=r.mul(e,o),s=r.mul(r.mul(i,ic),o),a=r.mul(i,r.sub(s,r.ONE));return J6(r,a,e),a}function LB(r){let e=Ql(r),t=bE(r),n=t(e,e.neg(e.ONE)),o=t(e,n),i=t(e,e.neg(n)),s=(r+RB)/yE;return(a,c)=>{let l=a.pow(c,s),f=a.mul(l,n),u=a.mul(l,o),d=a.mul(l,i),h=a.eql(a.sqr(f),c),m=a.eql(a.sqr(u),c);l=a.cmov(l,f,h),f=a.cmov(d,u,m);let w=a.eql(a.sqr(f),c),y=a.cmov(l,f,w);return J6(a,y,c),y}}function bE(r){if(r<hE)throw new Error("sqrt is not defined for small field");let e=r-ar,t=0;for(;e%ic===Gr;)e/=ic,t++;let n=ic,o=Ql(r);for(;dE(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return wE;let i=o.pow(n,e),s=(e+ar)/ic;return function(c,l){if(c.is0(l))return l;if(dE(c,l)!==1)throw new Error("Cannot find square root");let f=t,u=c.mul(c.ONE,i),d=c.pow(l,e),h=c.pow(l,s);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let m=1,w=c.sqr(d);for(;!c.eql(w,c.ONE);)if(m++,w=c.sqr(w),m===f)throw new Error("Cannot find square root");let y=ar<<BigInt(f-m-1),b=c.pow(u,y);f=m,u=c.sqr(b),d=c.mul(d,u),h=c.mul(h,b)}return h}}function BB(r){return r%pE===hE?wE:r%gE===mE?NB:r%yE===DB?LB(r):bE(r)}var vE=(r,e)=>(Pt(r,e)&ar)===ar,MB=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function e5(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=MB.reduce((n,o)=>(n[o]="function",n),e);return ti(r,t),r}function UB(r,e,t){if(t<Gr)throw new Error("invalid exponent, negatives unsupported");if(t===Gr)return r.ONE;if(t===ar)return e;let n=r.ONE,o=e;for(;t>Gr;)t&ar&&(n=r.mul(n,o)),o=r.sqr(o),t>>=ar;return n}function Id(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((s,a,c)=>r.is0(a)?s:(n[c]=s,r.mul(s,a)),r.ONE),i=r.inv(o);return e.reduceRight((s,a,c)=>r.is0(a)?s:(n[c]=r.mul(s,n[c]),r.mul(s,a)),i),n}function dE(r,e){let t=(r.ORDER-ar)/ic,n=r.pow(e,t),o=r.eql(n,r.ONE),i=r.eql(n,r.ZERO),s=r.eql(n,r.neg(r.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function FB(r,e){e!==void 0&&Nr(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var Z6=class{ORDER;BITS;BYTES;isLE;ZERO=Gr;ONE=ar;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Gr)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:i}=FB(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Pt(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Gr<=e&&e<this.ORDER}is0(e){return e===Gr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ar)===ar}neg(e){return Pt(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Pt(e*e,this.ORDER)}add(e,t){return Pt(e+t,this.ORDER)}sub(e,t){return Pt(e-t,this.ORDER)}mul(e,t){return Pt(e*t,this.ORDER)}pow(e,t){return UB(this,e,t)}div(e,t){return Pt(e*fE(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return fE(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=BB(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Ad(e,this.BYTES):Cm(e,this.BYTES)}fromBytes(e,t=!1){Oe(e);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?ei(e):Xl(e);if(a&&(c=Pt(c,s)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Id(this,e)}cmov(e,t,n){return n?t:e}};function Ql(r,e={}){return new Z6(r,e)}function xE(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function t5(r){let e=xE(r);return e+Math.ceil(e/2)}function r5(r,e,t=!1){Oe(r);let n=r.length,o=xE(e),i=t5(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=t?ei(r):Xl(r),a=Pt(s,e-ar)+ar;return t?Ad(a,o):Cm(a,o)}var Zl=BigInt(0),sc=BigInt(1);function Cd(r,e){let t=e.negate();return r?t:e}function ac(r,e){let t=Id(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function AE(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function n5(r,e){AE(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,i=Td(r),s=BigInt(r);return{windows:t,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function EE(r,e,t){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=t,a=Number(r&o),c=r>>s;a>n&&(a-=i,c+=sc);let l=e*n,f=l+Math.abs(a)-1,u=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:d,isNegF:h,offsetF:l}}var o5=new WeakMap,TE=new WeakMap;function i5(r){return TE.get(r)||1}function SE(r){if(r!==Zl)throw new Error("invalid wNAF")}var Jl=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Zl;)t&sc&&(n=n.add(o)),o=o.double(),t>>=sc;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=n5(t,this.bits),i=[],s=e,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=n5(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:f,isNeg:u,isNegF:d,offsetF:h}=EE(n,a,s);n=c,f?i=i.add(Cd(d,t[h])):o=o.add(Cd(u,t[l]))}return SE(n),{p:o,f:i}}wNAFUnsafe(e,t,n,o=this.ZERO){let i=n5(e,this.bits);for(let s=0;s<i.windows&&n!==Zl;s++){let{nextN:a,offset:c,isZero:l,isNeg:f}=EE(n,s,i);if(n=a,!l){let u=t[c];o=o.add(f?u.negate():u)}}return SE(n),o}getPrecomputes(e,t,n){let o=o5.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),o5.set(t,o))),o}cached(e,t,n){let o=i5(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let i=i5(e);return i===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,o)}createCache(e,t){AE(t,this.bits),TE.set(e,t),o5.delete(e)}hasCache(e){return i5(e)!==1}};function IE(r,e,t,n){let o=e,i=r.ZERO,s=r.ZERO;for(;t>Zl||n>Zl;)t&sc&&(i=i.add(o)),n&sc&&(s=s.add(o)),o=o.double(),t>>=sc,n>>=sc;return{p1:i,p2:s}}function _E(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return e5(e),e}else return Ql(r,{isLE:t})}function Pm(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Zl))throw new Error(`CURVE.${c} must be positive bigint`)}let o=_E(e.p,t.Fp,n),i=_E(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function eu(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Us=BigInt(0),cr=BigInt(1),s5=BigInt(2),$B=BigInt(8);function jB(r,e,t,n){let o=r.sqr(t),i=r.sqr(n),s=r.add(r.mul(e.a,o),i),a=r.add(r.ONE,r.mul(e.d,r.mul(o,i)));return r.eql(s,a)}function CE(r,e={}){let t=Pm("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,i=t.CURVE,{h:s}=i;ti(e,{},{uvRatio:"function"});let a=s5<<BigInt(o.BYTES*8)-cr,c=y=>n.create(y),l=e.uvRatio||((y,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,b))}}catch{return{isValid:!1,value:Us}}});if(!jB(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(y,b,N=!1){let O=N?cr:Us;return Ms("coordinate "+y,b,O,a),b}function u(y){if(!(y instanceof m))throw new Error("EdwardsPoint expected")}let d=Yl((y,b)=>{let{X:N,Y:O,Z:V}=y,Q=y.is0();b==null&&(b=Q?$B:n.inv(V));let Z=c(N*b),se=c(O*b),C=n.mul(V,b);if(Q)return{x:Us,y:cr};if(C!==cr)throw new Error("invZ was invalid");return{x:Z,y:se}}),h=Yl(y=>{let{a:b,d:N}=i;if(y.is0())throw new Error("bad point: ZERO");let{X:O,Y:V,Z:Q,T:Z}=y,se=c(O*O),C=c(V*V),T=c(Q*Q),K=c(T*T),z=c(se*b),U=c(T*c(z+C)),I=c(K+c(N*c(se*C)));if(U!==I)throw new Error("bad point: equation left != right (1)");let S=c(O*V),x=c(Q*Z);if(S!==x)throw new Error("bad point: equation left != right (2)");return!0});class m{static BASE=new m(i.Gx,i.Gy,cr,c(i.Gx*i.Gy));static ZERO=new m(Us,cr,cr,Us);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,N,O,V){this.X=f("x",b),this.Y=f("y",N),this.Z=f("z",O,!0),this.T=f("t",V),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){if(b instanceof m)throw new Error("extended point not allowed");let{x:N,y:O}=b||{};return f("x",N),f("y",O),new m(N,O,cr,c(N*O))}static fromBytes(b,N=!1){let O=n.BYTES,{a:V,d:Q}=i;b=oc(Oe(b,O,"point")),Ui(N,"zip215");let Z=oc(b),se=b[O-1];Z[O-1]=se&-129;let C=ei(Z),T=N?a:n.ORDER;Ms("point.y",C,Us,T);let K=c(C*C),z=c(K-cr),U=c(Q*K-V),{isValid:I,value:S}=l(z,U);if(!I)throw new Error("bad point: invalid y coordinate");let x=(S&cr)===cr,D=(se&128)!==0;if(!N&&S===Us&&D)throw new Error("bad point: x=0 and x_0=1");return D!==x&&(S=c(-S)),m.fromAffine({x:S,y:C})}static fromHex(b,N=!1){return m.fromBytes(Bi(b),N)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,N=!0){return w.createCache(this,b),N||this.multiply(s5),this}assertValidity(){h(this)}equals(b){u(b);let{X:N,Y:O,Z:V}=this,{X:Q,Y:Z,Z:se}=b,C=c(N*se),T=c(Q*V),K=c(O*se),z=c(Z*V);return C===T&&K===z}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=i,{X:N,Y:O,Z:V}=this,Q=c(N*N),Z=c(O*O),se=c(s5*c(V*V)),C=c(b*Q),T=N+O,K=c(c(T*T)-Q-Z),z=C+Z,U=z-se,I=C-Z,S=c(K*U),x=c(z*I),D=c(K*I),q=c(U*z);return new m(S,x,q,D)}add(b){u(b);let{a:N,d:O}=i,{X:V,Y:Q,Z,T:se}=this,{X:C,Y:T,Z:K,T:z}=b,U=c(V*C),I=c(Q*T),S=c(se*O*z),x=c(Z*K),D=c((V+Q)*(C+T)-U-I),q=x-S,H=x+S,M=c(I-N*U),G=c(D*q),te=c(H*M),F=c(D*M),Le=c(q*H);return new m(G,te,Le,F)}subtract(b){return this.add(b.negate())}multiply(b){if(!o.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:N,f:O}=w.cached(this,b,V=>ac(m,V));return ac(m,[N,O])[0]}multiplyUnsafe(b,N=m.ZERO){if(!o.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===Us?m.ZERO:this.is0()||b===cr?this:w.unsafe(this,b,O=>ac(m,O),N)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return w.unsafe(this,i.n).is0()}toAffine(b){return d(this,b)}clearCofactor(){return s===cr?this:this.multiplyUnsafe(s)}toBytes(){let{x:b,y:N}=this.toAffine(),O=n.toBytes(N);return O[O.length-1]|=b&cr?128:0,O}toHex(){return Li(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=new Jl(m,o.BITS);return m.BASE.precompute(8),m}function PE(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');ti(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:i,Fn:s}=r,a=t.randomBytes||Zo,c=t.adjustScalarBytes||(C=>C),l=t.domain||((C,T,K)=>{if(Ui(K,"phflag"),T.length||K)throw new Error("Contexts/pre-hash are not supported");return C});function f(C){return s.create(ei(C))}function u(C){let T=O.secretKey;Oe(C,O.secretKey,"secretKey");let K=Oe(e(C),2*T,"hashedSecretKey"),z=c(K.slice(0,T)),U=K.slice(T,2*T),I=f(z);return{head:z,prefix:U,scalar:I}}function d(C){let{head:T,prefix:K,scalar:z}=u(C),U=o.multiply(z),I=U.toBytes();return{head:T,prefix:K,scalar:z,point:U,pointBytes:I}}function h(C){return d(C).pointBytes}function m(C=Uint8Array.of(),...T){let K=cn(...T);return f(e(l(K,Oe(C,void 0,"context"),!!n)))}function w(C,T,K={}){C=Oe(C,void 0,"message"),n&&(C=n(C));let{prefix:z,scalar:U,pointBytes:I}=d(T),S=m(K.context,z,C),x=o.multiply(S).toBytes(),D=m(K.context,x,I,C),q=s.create(S+D*U);if(!s.isValid(q))throw new Error("sign failed: invalid s");let H=cn(x,s.toBytes(q));return Oe(H,O.signature,"result")}let y={zip215:!0};function b(C,T,K,z=y){let{context:U,zip215:I}=z,S=O.signature;C=Oe(C,S,"signature"),T=Oe(T,void 0,"message"),K=Oe(K,O.publicKey,"publicKey"),I!==void 0&&Ui(I,"zip215"),n&&(T=n(T));let x=S/2,D=C.subarray(0,x),q=ei(C.subarray(x,S)),H,M,G;try{H=r.fromBytes(K,I),M=r.fromBytes(D,I),G=o.multiplyUnsafe(q)}catch{return!1}if(!I&&H.isSmallOrder())return!1;let te=m(U,M.toBytes(),H.toBytes(),T);return M.add(H.multiplyUnsafe(te)).subtract(G).clearCofactor().is0()}let N=i.BYTES,O={secretKey:N,publicKey:N,signature:2*N,seed:N};function V(C=a(O.seed)){return Oe(C,O.seed,"seed")}function Q(C){return Ja(C)&&C.length===s.BYTES}function Z(C,T){try{return!!r.fromBytes(C,T)}catch{return!1}}let se={getExtendedPublicKey:d,randomSecretKey:V,isValidSecretKey:Q,isValidPublicKey:Z,toMontgomery(C){let{y:T}=r.fromBytes(C),K=O.publicKey,z=K===32;if(!z&&K!==57)throw new Error("only defined for 25519 and 448");let U=z?i.div(cr+T,cr-T):i.div(T-cr,T+cr);return i.toBytes(U)},toMontgomerySecret(C){let T=O.secretKey;Oe(C,T);let K=e(C.subarray(0,T));return c(K).subarray(0,T)}};return Object.freeze({keygen:eu(V,h),getPublicKey:h,sign:w,verify:b,utils:se,Point:r,lengths:O})}var Pd=BigInt(0),tu=BigInt(1),km=BigInt(2);function KB(r){return ti(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function kE(r){let e=KB(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:i,randomBytes:s}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=s||Zo,l=a?255:448,f=a?32:56,u=BigInt(a?9:5),d=BigInt(a?121665:39081),h=a?km**BigInt(254):km**BigInt(447),m=a?BigInt(8)*km**BigInt(251)-tu:BigInt(4)*km**BigInt(445)-tu,w=h+m+tu,y=S=>Pt(S,t),b=N(u);function N(S){return Ad(y(S),f)}function O(S){let x=oc(Oe(S,f,"uCoordinate"));return a&&(x[31]&=127),y(ei(x))}function V(S){return ei(o(oc(Oe(S,f,"scalar"))))}function Q(S,x){let D=K(O(x),V(S));if(D===Pd)throw new Error("invalid private or public key received");return N(D)}function Z(S){return Q(S,b)}let se=Z,C=Q;function T(S,x,D){let q=y(S*(x-D));return x=y(x-q),D=y(D+q),{x_2:x,x_3:D}}function K(S,x){Ms("u",S,Pd,t),Ms("scalar",x,h,w);let D=x,q=S,H=tu,M=Pd,G=S,te=tu,F=Pd;for(let Fe=BigInt(l-1);Fe>=Pd;Fe--){let me=D>>Fe&tu;F^=me,{x_2:H,x_3:G}=T(F,H,G),{x_2:M,x_3:te}=T(F,M,te),F=me;let He=H+M,ot=y(He*He),Ct=H-M,ze=y(Ct*Ct),it=ot-ze,Pi=G+te,mo=G-te,Is=y(mo*He),Z1=y(Pi*Ct),Nl=Is+Z1,rd=Is-Z1;G=y(Nl*Nl),te=y(q*y(rd*rd)),H=y(ot*ze),M=y(it*(ot+y(d*it)))}({x_2:H,x_3:G}=T(F,H,G)),{x_2:M,x_3:te}=T(F,M,te);let Le=i(M);return y(H*Le)}let z={secretKey:f,publicKey:f,seed:f},U=(S=c(f))=>(Oe(S,z.seed,"seed"),S),I={randomSecretKey:U};return Object.freeze({keygen:eu(U,se),getSharedSecret:C,getPublicKey:se,scalarMult:Q,scalarMultBase:Z,utils:I,GuBytes:b.slice(),lengths:z})}var VB=BigInt(1),OE=BigInt(2),HB=BigInt(3),qB=BigInt(5),WB=BigInt(8),Om=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),zB={p:Om,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:WB,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function DE(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),i=Om,a=r*r%i*r%i,c=_t(a,OE,i)*a%i,l=_t(c,VB,i)*r%i,f=_t(l,qB,i)*l%i,u=_t(f,e,i)*f%i,d=_t(u,t,i)*u%i,h=_t(d,n,i)*d%i,m=_t(h,o,i)*h%i,w=_t(m,o,i)*h%i,y=_t(w,e,i)*f%i;return{pow_p_5_8:_t(y,OE,i)*r%i,b2:a}}function NE(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var RE=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function GB(r,e){let t=Om,n=Pt(e*e*e,t),o=Pt(n*n*e,t),i=DE(r*o).pow_p_5_8,s=Pt(r*n*i,t),a=Pt(e*s*s,t),c=s,l=Pt(s*RE,t),f=a===r,u=a===Pt(-r,t),d=a===Pt(-r*RE,t);return f&&(s=c),(u||d)&&(s=l),vE(s,t)&&(s=Pt(-s,t)),{isValid:f||u,value:s}}var XB=CE(zB,{uvRatio:GB});function YB(r){return PE(XB,Bs,Object.assign({adjustScalarBytes:NE},r))}var kd=YB({});var Od=(()=>{let r=Om;return kE({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=DE(e);return Pt(_t(t,HB,r)*n,r)},adjustScalarBytes:NE})})();var cc=32,In=64,a5=32;var ru,LE=(async()=>{try{return await qt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function BE(){let r=kd.utils.randomSecretKey(),e=kd.getPublicKey(r);return{privateKey:tM(r,e),publicKey:e}}async function QB(r,e){let t;r.length===In?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:j(r.subarray(32),"base64url"),d:j(t,"base64url"),ext:!0,key_ops:["sign"]},o=await qt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await qt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(i,0,i.byteLength)}function ZB(r,e){let t=r.subarray(0,a5);return kd.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function ME(r,e){return ru==null&&(ru=await LE),ru?QB(r,e):ZB(r,e)}async function JB(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await qt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await qt.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function eM(r,e,t){return kd.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function UE(r,e,t){return ru==null&&(ru=await LE),ru?JB(r,e,t):eM(r,e,t)}function tM(r,e){let t=new Uint8Array(In);for(let n=0;n<a5;n++)t[n]=r[n],t[a5+n]=e[n];return t}function nu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Rd=class{type="Ed25519";raw;constructor(e){this.raw=iu(e,cc)}toMultihash(){return Dr.digest(sr(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=UE(this.raw,t,e);return nu(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}},ou=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=iu(e,In),this.publicKey=new Rd(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=ME(this.raw,e);return nu(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function c5(r){if(r.length>In){r=iu(r,In+cc);let n=r.subarray(0,In),o=r.subarray(In,r.length);return new ou(n,o)}r=iu(r,In);let e=r.subarray(0,In),t=r.subarray(cc);return new ou(e,t)}function l5(r){return r=iu(r,cc),new Rd(r)}async function $E(){let{privateKey:r,publicKey:e}=BE();return new ou(r,e)}function iu(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new P(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var rM=Math.pow(2,7),nM=Math.pow(2,14),oM=Math.pow(2,21),u5=Math.pow(2,28),f5=Math.pow(2,35),d5=Math.pow(2,42),h5=Math.pow(2,49),st=128,Br=127;function je(r){if(r<rM)return 1;if(r<nM)return 2;if(r<oM)return 3;if(r<u5)return 4;if(r<f5)return 5;if(r<d5)return 6;if(r<h5)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function su(r,e,t=0){switch(je(r)){case 8:e[t++]=r&255|st,r/=128;case 7:e[t++]=r&255|st,r/=128;case 6:e[t++]=r&255|st,r/=128;case 5:e[t++]=r&255|st,r/=128;case 4:e[t++]=r&255|st,r>>>=7;case 3:e[t++]=r&255|st,r>>>=7;case 2:e[t++]=r&255|st,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function iM(r,e,t=0){switch(je(r)){case 8:e.set(t++,r&255|st),r/=128;case 7:e.set(t++,r&255|st),r/=128;case 6:e.set(t++,r&255|st),r/=128;case 5:e.set(t++,r&255|st),r/=128;case 4:e.set(t++,r&255|st),r>>>=7;case 3:e.set(t++,r&255|st),r>>>=7;case 2:e.set(t++,r&255|st),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function p5(r,e){let t=r[e],n=0;if(n+=t&Br,t<st||(t=r[e+1],n+=(t&Br)<<7,t<st)||(t=r[e+2],n+=(t&Br)<<14,t<st)||(t=r[e+3],n+=(t&Br)<<21,t<st)||(t=r[e+4],n+=(t&Br)*u5,t<st)||(t=r[e+5],n+=(t&Br)*f5,t<st)||(t=r[e+6],n+=(t&Br)*d5,t<st)||(t=r[e+7],n+=(t&Br)*h5,t<st))return n;throw new RangeError("Could not decode varint")}function sM(r,e){let t=r.get(e),n=0;if(n+=t&Br,t<st||(t=r.get(e+1),n+=(t&Br)<<7,t<st)||(t=r.get(e+2),n+=(t&Br)<<14,t<st)||(t=r.get(e+3),n+=(t&Br)<<21,t<st)||(t=r.get(e+4),n+=(t&Br)*u5,t<st)||(t=r.get(e+5),n+=(t&Br)*f5,t<st)||(t=r.get(e+6),n+=(t&Br)*d5,t<st)||(t=r.get(e+7),n+=(t&Br)*h5,t<st))return n;throw new RangeError("Could not decode varint")}function Mr(r,e,t=0){return e==null&&(e=Ot(je(r))),e instanceof Uint8Array?su(r,e,t):iM(r,e,t)}function Cn(r,e=0){return r instanceof Uint8Array?p5(r,e):sM(r,e)}var m5=new Float32Array([-0]),Fs=new Uint8Array(m5.buffer);function jE(r,e,t){m5[0]=r,e[t]=Fs[0],e[t+1]=Fs[1],e[t+2]=Fs[2],e[t+3]=Fs[3]}function KE(r,e){return Fs[0]=r[e],Fs[1]=r[e+1],Fs[2]=r[e+2],Fs[3]=r[e+3],m5[0]}var g5=new Float64Array([-0]),Ur=new Uint8Array(g5.buffer);function VE(r,e,t){g5[0]=r,e[t]=Ur[0],e[t+1]=Ur[1],e[t+2]=Ur[2],e[t+3]=Ur[3],e[t+4]=Ur[4],e[t+5]=Ur[5],e[t+6]=Ur[6],e[t+7]=Ur[7]}function HE(r,e){return Ur[0]=r[e],Ur[1]=r[e+1],Ur[2]=r[e+2],Ur[3]=r[e+3],Ur[4]=r[e+4],Ur[5]=r[e+5],Ur[6]=r[e+6],Ur[7]=r[e+7],g5[0]}var aM=BigInt(Number.MAX_SAFE_INTEGER),cM=BigInt(Number.MIN_SAFE_INTEGER),Pn=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return lc;if(e<aM&&e>cM)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>qE&&(o=0n,++n>qE&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return lc;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):lc}},lc=new Pn(0,0);lc.toBigInt=function(){return 0n};lc.zzEncode=lc.zzDecode=function(){return this};lc.length=function(){return 1};var qE=4294967296n;function WE(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function zE(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function y5(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Eo(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Rm(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var w5=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Eo(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Eo(this,4);return Rm(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Eo(this,4);return Rm(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Eo(this,4);let e=KE(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Eo(this,4);let e=HE(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Eo(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return zE(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Eo(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Eo(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Pn(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Eo(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Eo(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Eo(this,8);let e=Rm(this.buf,this.pos+=4),t=Rm(this.buf,this.pos+=4);return new Pn(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=p5(this.buf,this.pos);return this.pos+=je(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function b5(r){return new w5(r instanceof Uint8Array?r:r.subarray())}function Ae(r,e,t){let n=b5(r);return e.decode(n,void 0,t)}function v5(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return Ot(s);o+s>e&&(n=Ot(e),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var uc=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function x5(){}var S5=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},lM=v5();function uM(r){return globalThis.Buffer!=null?Ot(r):lM(r)}var Nd=class{len;head;tail;states;constructor(){this.len=0,this.head=new uc(x5,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new uc(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new _5((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Dm,10,Pn.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Pn.fromBigInt(e);return this._push(Dm,t.length(),t)}uint64Number(e){return this._push(su,je(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Pn.fromBigInt(e).zzEncode();return this._push(Dm,t.length(),t)}sint64Number(e){let t=Pn.fromNumber(e).zzEncode();return this._push(Dm,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(E5,1,e?1:0)}fixed32(e){return this._push(Dd,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Pn.fromBigInt(e);return this._push(Dd,4,t.lo)._push(Dd,4,t.hi)}fixed64Number(e){let t=Pn.fromNumber(e);return this._push(Dd,4,t.lo)._push(Dd,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(jE,4,e)}double(e){return this._push(VE,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(E5,1,0):this.uint32(t)._push(dM,t,e)}string(e){let t=WE(e);return t!==0?this.uint32(t)._push(y5,t,e):this._push(E5,1,0)}fork(){return this.states=new S5(this),this.head=this.tail=new uc(x5,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new uc(x5,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=uM(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function E5(r,e,t){e[t]=r&255}function fM(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var _5=class extends uc{next;constructor(e,t){super(fM,e,t),this.next=void 0}};function Dm(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Dd(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function dM(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Nd.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(hM,e,r),this},Nd.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(pM,e,r),this});function hM(r,e,t){e.set(r,t)}function pM(r,e,t){r.length<40?y5(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(B(r),t)}function A5(){return new Nd}function Te(r,e){let t=A5();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var au;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(au||(au={}));function Nm(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function kt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,s){let a=e(i);s.int32(a)},n=function(i){let s=i.int32();return e(s)};return Nm("enum",au.VARINT,t,n)}function Ie(r,e){return Nm("message",au.LENGTH_DELIMITED,r,e)}var dt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Ld=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var wt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(wt||(wt={}));var T5;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(T5||(T5={}));(function(r){r.codec=()=>kt(T5)})(wt||(wt={}));var ri;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),wt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=wt.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(ri||(ri={}));var Bd;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),wt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=wt.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Bd||(Bd={}));function Xr(r){if(isNaN(r)||r<=0)throw new P("random bytes length must be a Number bigger than 0");return Zo(r)}var Ud={};Nt(Ud,{MAX_RSA_KEY_SIZE:()=>I5,generateRSAKeyPair:()=>B5,jwkToJWKKeyPair:()=>ZE,jwkToPkcs1:()=>wM,jwkToPkix:()=>O5,jwkToRSAPrivateKey:()=>L5,pkcs1MessageToJwk:()=>P5,pkcs1MessageToRSAPrivateKey:()=>Lm,pkcs1ToJwk:()=>yM,pkcs1ToRSAPrivateKey:()=>R5,pkixMessageToJwk:()=>k5,pkixMessageToRSAPublicKey:()=>N5,pkixToJwk:()=>bM,pkixToRSAPublicKey:()=>D5});var cu=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ud.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return he.createV1(114,this._multihash)}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,t,n){return QE(this.jwk,t,e,n)}},Md=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ud.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}sign(e,t){return YE(this.jwk,e,t)}};var I5=8192,C5=18,mM=1062,gM=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function yM(r){let e=Xn(r);return P5(e)}function P5(r){return{n:j(r[1],"base64url"),e:j(r[2],"base64url"),d:j(r[3],"base64url"),p:j(r[4],"base64url"),q:j(r[5],"base64url"),dp:j(r[6],"base64url"),dq:j(r[7],"base64url"),qi:j(r[8],"base64url"),kty:"RSA"}}function wM(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new P("JWK was missing components");return vo([zr(Uint8Array.from([0])),zr(B(r.n,"base64url")),zr(B(r.e,"base64url")),zr(B(r.d,"base64url")),zr(B(r.p,"base64url")),zr(B(r.q,"base64url")),zr(B(r.dp,"base64url")),zr(B(r.dq,"base64url")),zr(B(r.qi,"base64url"))]).subarray()}function bM(r){let e=Xn(r,{offset:0});return k5(e)}function k5(r){let e=Xn(r[1],{offset:0});return{kty:"RSA",n:j(e[0],"base64url"),e:j(e[1],"base64url")}}function O5(r){if(r.n==null||r.e==null)throw new P("JWK was missing components");return vo([gM,vd(vo([zr(B(r.n,"base64url")),zr(B(r.e,"base64url"))]))]).subarray()}function R5(r){let e=Xn(r);return Lm(e)}function Lm(r){let e=P5(r);return L5(e)}function D5(r,e){if(r.byteLength>=mM)throw new Oi("Key size is too large");let t=Xn(r,{offset:0});return N5(t,r,e)}function N5(r,e,t){let n=k5(r);if(t==null){let o=Yn(ri.encode({Type:wt.RSA,Data:e}));t=Wr(C5,o)}return new cu(n,t)}function L5(r){if(eS(r)>I5)throw new P("Key size is too large");let e=ZE(r),t=Yn(ri.encode({Type:wt.RSA,Data:O5(e.publicKey)})),n=Wr(C5,t);return new Md(e.privateKey,new cu(e.publicKey,n))}async function B5(r){if(r>I5)throw new P("Key size is too large");let e=await JE(r),t=Yn(ri.encode({Type:wt.RSA,Data:O5(e.publicKey)})),n=Wr(C5,t);return new Md(e.privateKey,new cu(e.publicKey,n))}function ZE(r){if(r==null)throw new P("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function JE(r,e){let t=await qt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await vM(t,e);return{privateKey:n[0],publicKey:n[1]}}async function YE(r,e,t){let n=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await qt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function QE(r,e,t,n){let o=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await qt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),i}async function vM(r,e){if(r.privateKey==null||r.publicKey==null)throw new P("Private and public key are required");let t=await Promise.all([qt.get().subtle.exportKey("jwk",r.privateKey),qt.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function eS(r){if(r.kty!=="RSA")throw new P("invalid key type");if(r.n==null)throw new P("invalid key modulus");return B(r.n,"base64url").length*8}var Bm=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Ni(e),Oe(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Lr(o)}update(e){return Gl(this),this.iHash.update(e),this}digestInto(e){Gl(this),Oe(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},$s=(r,e,t)=>new Bm(r,e).update(t).digest();$s.create=(r,e)=>new Bm(r,e);var tS=(r,e)=>(r+(r>=0?e:-e)/rS)/e;function xM(r,e,t){let[[n,o],[i,s]]=e,a=tS(s*r,t),c=tS(-o*r,t),l=r-a*n-c*i,f=-a*o-c*s,u=l<$i,d=f<$i;u&&(l=-l),d&&(f=-f);let h=Td(Math.ceil(Q6(t)/2))+lu;if(l<$i||l>=h||f<$i||f>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:l,k2neg:d,k2:f}}function U5(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function M5(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ui(t.lowS,"lowS"),Ui(t.prehash,"prehash"),t.format!==void 0&&U5(t.format),t}var F5=class extends Error{constructor(e=""){super(e)}},js={Err:F5,_tlv:{encode:(r,e)=>{let{Err:t}=js;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=_d(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?_d(o.length/2|128):"";return _d(r)+i+o+e},decode(r,e){let{Err:t}=js,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of l)s=s<<8|f;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=js;if(r<$i)throw new e("integer: negative integers are not allowed");let t=_d(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=js;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Xl(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=js,o=Oe(r,void 0,"signature"),{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:f}=n.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=js,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),i=n+o;return e.encode(48,i)}},$i=BigInt(0),lu=BigInt(1),rS=BigInt(2),Mm=BigInt(3),EM=BigInt(4);function nS(r,e={}){let t=Pm("weierstrass",r,e),{Fp:n,Fn:o}=t,i=t.CURVE,{h:s,n:a}=i;ti(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=iS(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(U,I,S){let{x,y:D}=I.toAffine(),q=n.toBytes(x);if(Ui(S,"isCompressed"),S){f();let H=!n.isOdd(D);return cn(oS(H),q)}else return cn(Uint8Array.of(4),q,n.toBytes(D))}function d(U){Oe(U,void 0,"Point");let{publicKey:I,publicKeyUncompressed:S}=l,x=U.length,D=U[0],q=U.subarray(1);if(x===I&&(D===2||D===3)){let H=n.fromBytes(q);if(!n.isValid(H))throw new Error("bad point: is not on curve, wrong x");let M=w(H),G;try{G=n.sqrt(M)}catch(Le){let Fe=Le instanceof Error?": "+Le.message:"";throw new Error("bad point: is not on curve, sqrt error"+Fe)}f();let te=n.isOdd(G);return(D&1)===1!==te&&(G=n.neg(G)),{x:H,y:G}}else if(x===S&&D===4){let H=n.BYTES,M=n.fromBytes(q.subarray(0,H)),G=n.fromBytes(q.subarray(H,H*2));if(!y(M,G))throw new Error("bad point: is not on curve");return{x:M,y:G}}else throw new Error(`bad point: got length ${x}, expected compressed=${I} or uncompressed=${S}`)}let h=e.toBytes||u,m=e.fromBytes||d;function w(U){let I=n.sqr(U),S=n.mul(I,U);return n.add(n.add(S,n.mul(U,i.a)),i.b)}function y(U,I){let S=n.sqr(I),x=w(U);return n.eql(S,x)}if(!y(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(i.a,Mm),EM),N=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(b,N)))throw new Error("bad curve params: a or b");function O(U,I,S=!1){if(!n.isValid(I)||S&&n.is0(I))throw new Error(`bad point coordinate ${U}`);return I}function V(U){if(!(U instanceof T))throw new Error("Weierstrass Point expected")}function Q(U){if(!c||!c.basises)throw new Error("no endo");return xM(U,c.basises,o.ORDER)}let Z=Yl((U,I)=>{let{X:S,Y:x,Z:D}=U;if(n.eql(D,n.ONE))return{x:S,y:x};let q=U.is0();I==null&&(I=q?n.ONE:n.inv(D));let H=n.mul(S,I),M=n.mul(x,I),G=n.mul(D,I);if(q)return{x:n.ZERO,y:n.ZERO};if(!n.eql(G,n.ONE))throw new Error("invZ was invalid");return{x:H,y:M}}),se=Yl(U=>{if(U.is0()){if(e.allowInfinityPoint&&!n.is0(U.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:S}=U.toAffine();if(!n.isValid(I)||!n.isValid(S))throw new Error("bad point: x or y not field elements");if(!y(I,S))throw new Error("bad point: equation left != right");if(!U.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function C(U,I,S,x,D){return S=new T(n.mul(S.X,U),S.Y,S.Z),I=Cd(x,I),S=Cd(D,S),I.add(S)}class T{static BASE=new T(i.Gx,i.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(I,S,x){this.X=O("x",I),this.Y=O("y",S,!0),this.Z=O("z",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(I){let{x:S,y:x}=I||{};if(!I||!n.isValid(S)||!n.isValid(x))throw new Error("invalid affine point");if(I instanceof T)throw new Error("projective point not allowed");return n.is0(S)&&n.is0(x)?T.ZERO:new T(S,x,n.ONE)}static fromBytes(I){let S=T.fromAffine(m(Oe(I,void 0,"point")));return S.assertValidity(),S}static fromHex(I){return T.fromBytes(Bi(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,S=!0){return z.createCache(this,I),S||this.multiply(Mm),this}assertValidity(){se(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){V(I);let{X:S,Y:x,Z:D}=this,{X:q,Y:H,Z:M}=I,G=n.eql(n.mul(S,M),n.mul(q,D)),te=n.eql(n.mul(x,M),n.mul(H,D));return G&&te}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:S}=i,x=n.mul(S,Mm),{X:D,Y:q,Z:H}=this,M=n.ZERO,G=n.ZERO,te=n.ZERO,F=n.mul(D,D),Le=n.mul(q,q),Fe=n.mul(H,H),me=n.mul(D,q);return me=n.add(me,me),te=n.mul(D,H),te=n.add(te,te),M=n.mul(I,te),G=n.mul(x,Fe),G=n.add(M,G),M=n.sub(Le,G),G=n.add(Le,G),G=n.mul(M,G),M=n.mul(me,M),te=n.mul(x,te),Fe=n.mul(I,Fe),me=n.sub(F,Fe),me=n.mul(I,me),me=n.add(me,te),te=n.add(F,F),F=n.add(te,F),F=n.add(F,Fe),F=n.mul(F,me),G=n.add(G,F),Fe=n.mul(q,H),Fe=n.add(Fe,Fe),F=n.mul(Fe,me),M=n.sub(M,F),te=n.mul(Fe,Le),te=n.add(te,te),te=n.add(te,te),new T(M,G,te)}add(I){V(I);let{X:S,Y:x,Z:D}=this,{X:q,Y:H,Z:M}=I,G=n.ZERO,te=n.ZERO,F=n.ZERO,Le=i.a,Fe=n.mul(i.b,Mm),me=n.mul(S,q),He=n.mul(x,H),ot=n.mul(D,M),Ct=n.add(S,x),ze=n.add(q,H);Ct=n.mul(Ct,ze),ze=n.add(me,He),Ct=n.sub(Ct,ze),ze=n.add(S,D);let it=n.add(q,M);return ze=n.mul(ze,it),it=n.add(me,ot),ze=n.sub(ze,it),it=n.add(x,D),G=n.add(H,M),it=n.mul(it,G),G=n.add(He,ot),it=n.sub(it,G),F=n.mul(Le,ze),G=n.mul(Fe,ot),F=n.add(G,F),G=n.sub(He,F),F=n.add(He,F),te=n.mul(G,F),He=n.add(me,me),He=n.add(He,me),ot=n.mul(Le,ot),ze=n.mul(Fe,ze),He=n.add(He,ot),ot=n.sub(me,ot),ot=n.mul(Le,ot),ze=n.add(ze,ot),me=n.mul(He,ze),te=n.add(te,me),me=n.mul(it,ze),G=n.mul(Ct,G),G=n.sub(G,me),me=n.mul(Ct,He),F=n.mul(it,F),F=n.add(F,me),new T(G,te,F)}subtract(I){return this.add(I.negate())}is0(){return this.equals(T.ZERO)}multiply(I){let{endo:S}=e;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let x,D,q=H=>z.cached(this,H,M=>ac(T,M));if(S){let{k1neg:H,k1:M,k2neg:G,k2:te}=Q(I),{p:F,f:Le}=q(M),{p:Fe,f:me}=q(te);D=Le.add(me),x=C(S.beta,F,Fe,H,G)}else{let{p:H,f:M}=q(I);x=H,D=M}return ac(T,[x,D])[0]}multiplyUnsafe(I){let{endo:S}=e,x=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===$i||x.is0())return T.ZERO;if(I===lu)return x;if(z.hasCache(this))return this.multiply(I);if(S){let{k1neg:D,k1:q,k2neg:H,k2:M}=Q(I),{p1:G,p2:te}=IE(T,x,q,M);return C(S.beta,G,te,D,H)}else return z.unsafe(x,I)}toAffine(I){return Z(this,I)}isTorsionFree(){let{isTorsionFree:I}=e;return s===lu?!0:I?I(T,this):z.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return s===lu?this:I?I(T,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(I=!0){return Ui(I,"isCompressed"),this.assertValidity(),h(T,this,I)}toHex(I=!0){return Li(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let K=o.BITS,z=new Jl(T,e.endo?Math.ceil(K/2):K);return T.BASE.precompute(8),T}function oS(r){return Uint8Array.of(r?2:3)}function iS(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function SM(r,e={}){let{Fn:t}=r,n=e.randomBytes||Zo,o=Object.assign(iS(r.Fp,t),{seed:t5(t.ORDER)});function i(h){try{let m=t.fromBytes(h);return t.isValidNot0(m)}catch{return!1}}function s(h,m){let{publicKey:w,publicKeyUncompressed:y}=o;try{let b=h.length;return m===!0&&b!==w||m===!1&&b!==y?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return r5(Oe(h,o.seed,"seed"),t.ORDER)}function c(h,m=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(m)}function l(h){let{secretKey:m,publicKey:w,publicKeyUncompressed:y}=o;if(!Ja(h)||"_lengths"in t&&t._lengths||m===w)return;let b=Oe(h,void 0,"key").length;return b===w||b===y}function f(h,m,w=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(h);return r.fromBytes(m).multiply(y).toBytes(w)}let u={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},d=eu(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:u,lengths:o})}function sS(r,e,t={}){Ni(e),ti(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Zo,o=t.hmac||((S,x)=>$s(e,S,x)),{Fp:i,Fn:s}=r,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h}=SM(r,t),m={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},w=a*rS<i.ORDER;function y(S){let x=a>>lu;return S>x}function b(S,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return x}function N(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(S,x){U5(x);let D=h.signature,q=x==="compact"?D:x==="recovered"?D+1:void 0;return Oe(S,q)}class V{r;s;recovery;constructor(x,D,q){if(this.r=b("r",x),this.s=b("s",D),q!=null){if(N(),![0,1,2,3].includes(q))throw new Error("invalid recovery id");this.recovery=q}Object.freeze(this)}static fromBytes(x,D=m.format){O(x,D);let q;if(D==="der"){let{r:te,s:F}=js.toSig(Oe(x));return new V(te,F)}D==="recovered"&&(q=x[0],D="compact",x=x.subarray(1));let H=h.signature/2,M=x.subarray(0,H),G=x.subarray(H,H*2);return new V(s.fromBytes(M),s.fromBytes(G),q)}static fromHex(x,D){return this.fromBytes(Bi(x),D)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new V(this.r,this.s,x)}recoverPublicKey(x){let{r:D,s:q}=this,H=this.assertRecovery(),M=H===2||H===3?D+a:D;if(!i.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let G=i.toBytes(M),te=r.fromBytes(cn(oS((H&1)===0),G)),F=s.inv(M),Le=Z(Oe(x,void 0,"msgHash")),Fe=s.create(-Le*F),me=s.create(q*F),He=r.BASE.multiplyUnsafe(Fe).add(te.multiplyUnsafe(me));if(He.is0())throw new Error("invalid recovery: point at infinify");return He.assertValidity(),He}hasHighS(){return y(this.s)}toBytes(x=m.format){if(U5(x),x==="der")return Bi(js.hexFromSig(this));let{r:D,s:q}=this,H=s.toBytes(D),M=s.toBytes(q);return x==="recovered"?(N(),cn(Uint8Array.of(this.assertRecovery()),H,M)):cn(H,M)}toHex(x){return Li(this.toBytes(x))}}let Q=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let D=Xl(x),q=x.length*8-c;return q>0?D>>BigInt(q):D},Z=t.bits2int_modN||function(x){return s.create(Q(x))},se=Td(c);function C(S){return Ms("num < 2^"+c,S,$i,se),s.toBytes(S)}function T(S,x){return Oe(S,void 0,"message"),x?Oe(e(S),void 0,"prehashed message"):S}function K(S,x,D){let{lowS:q,prehash:H,extraEntropy:M}=M5(D,m);S=T(S,H);let G=Z(S),te=s.fromBytes(x);if(!s.isValidNot0(te))throw new Error("invalid private key");let F=[C(te),C(G)];if(M!=null&&M!==!1){let He=M===!0?n(h.secretKey):M;F.push(Oe(He,void 0,"extraEntropy"))}let Le=cn(...F),Fe=G;function me(He){let ot=Q(He);if(!s.isValidNot0(ot))return;let Ct=s.inv(ot),ze=r.BASE.multiply(ot).toAffine(),it=s.create(ze.x);if(it===$i)return;let Pi=s.create(Ct*s.create(Fe+it*te));if(Pi===$i)return;let mo=(ze.x===it?0:2)|Number(ze.y&lu),Is=Pi;return q&&y(Pi)&&(Is=s.neg(Pi),mo^=1),new V(it,Is,w?void 0:mo)}return{seed:Le,k2sig:me}}function z(S,x,D={}){let{seed:q,k2sig:H}=K(S,x,D);return uE(e.outputLen,s.BYTES,o)(q,H).toBytes(D.format)}function U(S,x,D,q={}){let{lowS:H,prehash:M,format:G}=M5(q,m);if(D=Oe(D,void 0,"publicKey"),x=T(x,M),!Ja(S)){let te=S instanceof V?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+te)}O(S,G);try{let te=V.fromBytes(S,G),F=r.fromBytes(D);if(H&&te.hasHighS())return!1;let{r:Le,s:Fe}=te,me=Z(x),He=s.inv(Fe),ot=s.create(me*He),Ct=s.create(Le*He),ze=r.BASE.multiplyUnsafe(ot).add(F.multiplyUnsafe(Ct));return ze.is0()?!1:s.create(ze.x)===Le}catch{return!1}}function I(S,x,D={}){let{prehash:q}=M5(D,m);return x=T(x,q),V.fromBytes(S,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h,Point:r,sign:z,verify:U,recoverPublicKey:I,Signature:V,hash:e})}var j5={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},_M={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var aS=BigInt(2);function AM(r){let e=j5.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,f=l*l*r%e,u=_t(f,t,e)*f%e,d=_t(u,t,e)*f%e,h=_t(d,aS,e)*l%e,m=_t(h,o,e)*h%e,w=_t(m,i,e)*m%e,y=_t(w,a,e)*w%e,b=_t(y,c,e)*y%e,N=_t(b,a,e)*w%e,O=_t(N,t,e)*f%e,V=_t(O,s,e)*m%e,Q=_t(V,n,e)*l%e,Z=_t(Q,aS,e);if(!$5.eql($5.sqr(Z),r))throw new Error("Cannot find square root");return Z}var $5=Ql(j5.p,{sqrt:AM}),TM=nS(j5,{Fp:$5,endo:_M}),So=sS(TM,Yn);var cS=32;function lS(r,e,t){let n=St.digest(e instanceof Uint8Array?e:e.subarray());if(nu(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),So.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new gd(String(o))});try{return So.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new gd(String(o))}}function uS(r,e,t,n){let o=St.digest(t instanceof Uint8Array?t:t.subarray());if(nu(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),So.verify(e,i,r,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new yd(String(i))});try{return n?.signal?.throwIfAborted(),So.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(i){throw new yd(String(i))}}var Fd=class{type="secp256k1";raw;_key;constructor(e){this._key=hS(e),this.raw=fS(this._key)}toMultihash(){return Dr.digest(sr(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,t,n){return uS(this._key,t,e,n)}},$d=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=dS(e),this.publicKey=new Fd(t??pS(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}sign(e,t){return lS(this.raw,e,t)}};function K5(r){return new $d(r)}function V5(r){return new Fd(r)}async function mS(){let r=IM();return new $d(r)}function fS(r){return So.Point.fromBytes(r).toBytes()}function dS(r){try{return So.getPublicKey(r,!0),r}catch(e){throw new od(String(e))}}function hS(r){try{return So.Point.fromBytes(r),r}catch(e){throw new Oi(String(e))}}function pS(r){try{return So.getPublicKey(r,!0)}catch(e){throw new od(String(e))}}function IM(){return So.utils.randomSecretKey()}async function uu(r,e){if(r==="Ed25519")return $E();if(r==="secp256k1")return mS();if(r==="RSA")return B5(CM(e));if(r==="ECDSA")return zx(PM(e));throw new wo}function Kt(r,e){let{Type:t,Data:n}=ri.decode(r),o=n??new Uint8Array;switch(t){case wt.RSA:return D5(o,e);case wt.Ed25519:return l5(o);case wt.secp256k1:return V5(o);case wt.ECDSA:return $6(o);default:throw new wo}}function Um(r){let{Type:e,Data:t}=ri.decode(r.digest),n=t??new Uint8Array;switch(e){case wt.Ed25519:return l5(n);case wt.secp256k1:return V5(n);case wt.ECDSA:return $6(n);default:throw new wo}}function sr(r){return ri.encode({Type:wt[r.type],Data:r.raw})}function gS(r){let e=Bd.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case wt.RSA:return R5(t);case wt.Ed25519:return c5(t);case wt.secp256k1:return K5(t);case wt.ECDSA:return Kx(t);default:throw new wo}}function yS(r){if(r.byteLength===In)return c5(r);if(r.byteLength===cS)return K5(r);let e=Xn(r),t=e[2]?.[0];if(t===Dx||t===Nx||t===Lx)return F6(e);if(e.length>8)return Lm(e);throw new P("Could not extract private key from raw bytes")}function fc(r){return Bd.encode({Type:wt[r.type],Data:r.raw})}function CM(r){return r==null?2048:parseInt(r,10)}function PM(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new P("Unsupported curve, should be P-256, P-384 or P-521")}async function Fm(r){if(r.type==="RSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])};if(r.type==="ECDSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"ECDSA",namedCurve:r.jwk.crv??"P-256"},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"ECDSA",namedCurve:r.publicKey.jwk.crv??"P-256"},!0,["verify"])};throw new P("Only RSA and ECDSA keys are supported")}var jd=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ks=new Uint32Array(80),H5=class extends tc{A=jd[0]|0;B=jd[1]|0;C=jd[2]|0;D=jd[3]|0;E=jd[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ks[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ks[c]=Sm(Ks[c-3]^Ks[c-8]^Ks[c-14]^Ks[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,f;c<20?(l=_m(o,i,s),f=1518500249):c<40?(l=o^i^s,f=1859775393):c<60?(l=Am(o,i,s),f=2400959708):(l=o^i^s,f=3395469782);let u=Sm(n,5)+l+a+f+Ks[c]|0;a=s,s=i,i=Sm(o,30),o=n,n=u}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){Lr(Ks)}destroy(){this.set(0,0,0,0,0),Lr(this.buffer)}},wS=xd(()=>new H5);function bS(r,e,t,n){Ni(r);let o=Zx({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(Nr(i,"c"),Nr(s,"dkLen"),Nr(a,"asyncTick"),i<1)throw new Error("iterations (c) must be >= 1");let c=j6(e,"password"),l=j6(t,"salt"),f=new Uint8Array(s),u=$s.create(r,c),d=u._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:f,PRF:u,PRFSalt:d}}function vS(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),Lr(o),t}function xS(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=bS(r,e,t,n),l,f=new Uint8Array(4),u=ec(f),d=new Uint8Array(a.outputLen);for(let h=1,m=0;m<i;h++,m+=a.outputLen){let w=s.subarray(m,m+a.outputLen);u.setInt32(0,h,!1),(l=c._cloneInto(l)).update(f).digestInto(d),w.set(d.subarray(0,w.length));for(let y=1;y<o;y++){a._cloneInto(l).update(d).digestInto(d);for(let b=0;b<w.length;b++)w[b]^=d[b]}}return vS(a,c,s,l,d)}async function $m(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=bS(r,e,t,n),f,u=new Uint8Array(4),d=ec(u),h=new Uint8Array(c.outputLen);for(let m=1,w=0;w<i;m++,w+=c.outputLen){let y=a.subarray(w,w+c.outputLen);d.setInt32(0,m,!1),(f=l._cloneInto(f)).update(u).digestInto(h),y.set(h.subarray(0,y.length)),await Qx(o-1,s,()=>{c._cloneInto(f).update(h).digestInto(h);for(let b=0;b<y.length;b++)y[b]^=h[b]})}return vS(c,l,a,f,h)}var ES={sha1:wS,"sha2-256":Yn,"sha2-512":Bs};function Kd(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(ES).join(" / ");throw new P(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=ES[o],s=xS(i,r,e,{c:t,dkLen:n});return Ht.encode(s).substring(1)}var q5={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},SS={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},_S=new globalThis.TextEncoder;function kM(r,e){let t=q5[e],n=SS[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function OM(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=q5[e],o=SS[e],i=r;for(;i.length>0;){let s=_S.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function W5(r,{size:e=32,utf8Buffer:t}={}){if(!q5[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return OM(r,e,t);r=_S.encode(r)}return kM(r,e)}var Vd={hash:r=>Number(W5(r,{size:32})),hashV:(r,e)=>RM(Vd.hash(r,e))};function RM(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),B(e,"base16")}var z5=64,_o=class{fp;h;seed;constructor(e,t,n,o=2){if(o>z5)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=ke(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?we(this.fp,e.fp):!1}};function dc(r,e){return Math.floor(Math.random()*(e-r))+r}var hc=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof _o))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof _o))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof _o))throw new TypeError("Invalid Fingerprint");let t=dc(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof _o))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var DM=500,Hd=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??Vd,this.seed=e.seed??dc(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=B(e));let t=new _o(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new hc(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new hc(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[dc(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new hc(this.bucketSize));for(let a=0;a<DM;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new hc(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=B(e));let t=new _o(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=B(e));let t=new _o(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},NM={1:.5,2:.84,4:.95,8:.98};function LM(r=.001){return r>.002?2:r>1e-5?4:8}function AS(r,e=.001){let t=LM(e),n=NM[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),z5);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var jm=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Vd,this.seed=e.seed??dc(0,Math.pow(2,10)),this.filterSeries=[new Hd({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=B(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Hd({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=B(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=B(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Fr(r,e=.001,t){return new jm({...AS(r,e),...t??{}})}function Ce(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new P(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var Km=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let d=Number.parseInt(u,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(i*=e,i+=f,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var TS=45,BM=15,fu=new Km;function Vm(r){if(!(r.length>BM))return fu.new(r).parseWith(()=>fu.readIPv4Addr())}function Hm(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>TS))return fu.new(r).parseWith(()=>fu.readIPv6Addr())}function du(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>TS)return;let t=fu.new(r).parseWith(()=>fu.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function IS(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function CS(r,e,t,n){let o=0;for(let i of r)if(!(o<t)){if(o>n)break;if(i!==e[o])return!1;o++}return!0}function G5(r){switch(r.length){case pc:return r.join(".");case mc:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function PS(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function kS(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var pc=4,mc=16,UJ=parseInt("0xFFFF",16),MM=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function qd(r,e){e.length===mc&&r.length===pc&&IS(e,0,11)&&(e=e.slice(12)),e.length===pc&&r.length===mc&&CS(r,MM,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function OS(r,e){if(typeof e=="string"&&(e=du(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function X5(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=pc,o=Vm(e);if(o==null&&(n=mc,o=Hm(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=Y5(i,8*n);return{network:qd(o,s),mask:s}}function Y5(r,e){if(e!==8*pc&&e!==8*mc)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var gc=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=X5(e));else{let n=du(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let i=du(t);if(i==null)throw new Error("Failed to parse mask");this.mask=i}else this.mask=Y5(o,8*n.length);this.network=qd(n,this.mask)}}contains(e){return OS({network:this.network,mask:this.mask},e)}toString(){let e=PS(this.mask),t=e!==-1?String(e):kS(this.mask);return G5(this.network)+"/"+t}};function RS(r,e){return new gc(r).contains(e)}function qm(r){try{let e=Ce(r);switch(e.type){case"ip6":return RS("2000::/3",e.host);default:return!1}}catch{return!1}}function DS(r){try{let e=Ce(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function NS(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Wd(r){try{let e=Ce(r);switch(e.type){case"ip4":case"ip6":return NS(e.host);default:return!1}}catch{return!1}}function mr(r){try{return Ce(r),!0}catch{return!1}}function Ao(r){return!!Vm(r)}function Wm(r){return!!Hm(r)}var BS=nr(LS(),1),UM=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],FM=UM.map(r=>new BS.Netmask(r));function Q5(r){for(let e of FM)if(e.contains(r))return!0;return!1}function $M(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function jM(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Q5(o)}function KM(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function VM(r){let e=r.split(":"),t=e[e.length-1];return Q5(t)}function HM(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function hu(r){if(Ao(r))return Q5(r);if($M(r))return jM(r);if(KM(r))return VM(r);if(Wm(r))return HM(r)}function Mt(r){try{let e=Ce(r);switch(e.type){case"ip4":case"ip6":return hu(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function Ve(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var zm=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},pu=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new zm(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new zm(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Z5=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function gr(r={}){return qM(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function qM(r,e){e=e??{};let t=e.onEnd,n=new pu,o,i,s,a=Ve(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,b)=>{i=N=>{i=null,n.push(N);try{y(r(n))}catch(O){b(O)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ve()})}},l=y=>i!=null?i(y):(n.push(y),o),f=y=>(n=new pu,i!=null?i({error:y}):(n.push({error:y}),o)),u=y=>{if(s)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},d=y=>s?o:(s=!0,y!=null?f(y):l({done:!0})),h=()=>(n=new pu,d(),{done:!0}),m=y=>(d(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:u,end:d,get readableLength(){return n.size},onEmpty:async y=>{let b=y?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let N,O;b!=null&&(N=new Promise((V,Q)=>{O=()=>{Q(new Z5)},b.addEventListener("abort",O)}));try{await Promise.race([a.promise,N])}finally{O!=null&&b!=null&&b?.removeEventListener("abort",O)}}},t==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(y){return w.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return w.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return w.readableLength},onEmpty:y=>w.onEmpty(y)},o}var J5=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},e8=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},MS=r=>globalThis.DOMException===void 0?new e8(r):new DOMException(r),US=r=>{let e=r.reason===void 0?MS("This operation was aborted."):r.reason;return e instanceof Error?e:MS(e)};function t8(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(US(h)),a=()=>{u(US(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let d=new J5;s=i.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?u(o):(d.message=o??`Promise timed out after ${t} milliseconds`,u(d))},t),(async()=>{try{f(await r)}catch(h){u(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},l}var WM=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function zM(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=WM(r),u=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(w){n(),s(w);return}c.push(m),t.count===c.length&&(n(),i(c))},d=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)l(h,u);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=t8(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function Qn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=zM(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function ji(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 Gm=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Xm=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},yc=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Ym=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Qm=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function GM(r){return r.reason}async function ut(r,e,t){if(e==null)return r;let n=t?.translateError??GM;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Zm=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Ve(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Hr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function XM(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Jm=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=XM(),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 Hr),this.cleanup())}async join(e={}){let t=new Zm(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 ut(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var yr=class extends _e{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=ji(this.emitEmpty.bind(this),1),this.emitIdle=ji(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Xm;let n=new Jm(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Hr)}),this.clear()}async onEmpty(e){this.size!==0&&await Qn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Qn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Qn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=gr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new Hr("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var YM=Math.pow(2,20)*4,Vs=class extends _e{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??YM,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new fe,this.writeBuffer=new fe,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new Qm)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),ut(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=gr(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let n=i=>{e.end(i.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Go(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new im(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Go("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Go("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Go(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Go(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Bl;this.dispatchEvent(new sm(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new ks))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let i=this.writeBuffer.sublist(0,o),s=new fe(i);this.writeBuffer.consume(i.byteLength);let a=this.sendData(i);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==s.byteLength&&(s.consume(a.sentBytes),this.writeBuffer.prepend(s)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new om(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new sd(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new sd(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var Hs=class extends Vs{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Qn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Qn(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function e0(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var qs=class extends _e{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=s=>{try{this.onData(s.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await ut(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new yo;let t=this.onCreateStream({...this.streamOptions,...e});return e0(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Ym(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let o=this.streams.findIndex(i=>i===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var Ws=class extends Vs{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Qn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Qn(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function De(r){let e=new globalThis.AbortController;function t(){let i=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var mu=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,i=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var QM=1.2,ZM=2,JM=5e3,eU=6e4,tU=5e3,To=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??tU;this.success=new mu(t),this.failure=new mu(t),this.next=new mu(t),this.failureMultiplier=e.failureMultiplier??ZM,this.timeoutMultiplier=e.timeoutMultiplier??QM,this.minTimeout=e.minTimeout??JM,this.maxTimeout=e.maxTimeout??eU,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=De([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var wr=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ki=class extends Error{static name="ValidationError";name="ValidationError"},t0=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},r0=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function n8(r){return e=>j(e,r)}function o8(r){return e=>B(e,r)}function gu(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function wc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function FS(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=B(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=wc(n);return gt([t,o],t.length+o.length)}function $S(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ir.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=wc(n);return gt([t,o],t.length+o.length)}function i8(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=j(e,"base32"),o=gu(t);return`${n}:${o}`}var s8=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new wr("Invalid byte value in IP address");e[n]=o}),e},jS=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=Ao(t[n]),s;i&&(s=s8(t[n]),t[n]=j(s.subarray(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,j(s.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let i=parseInt(t[n],16);if(isNaN(i)||i<0||i>65535)throw new wr("Invalid byte value in IP address");o[e++]=i>>8&255,o[e++]=i&255}return o},KS=function(r){if(r.byteLength!==4)throw new wr("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},VS=function(r){if(r.byteLength!==16)throw new wr("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],i=r[n+1],s=`${o.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;e.push(s)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new wr(`Invalid IPv6 address "${t}"`)}};function HS(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new wr(`Invalid IPv6 address "${r}"`)}}var r8=Object.values(Ya).map(r=>r.decoder),rU=(function(){let r=r8[0].or(r8[1]);return r8.slice(2).forEach(e=>r=r.or(e)),r})();function qS(r){return rU.decode(r)}function WS(r){return e=>r.encoder.encode(e)}function nU(r){if(parseInt(r).toString()!==r)throw new Ki("Value must be an integer")}function oU(r){if(r<0)throw new Ki("Value must be a positive integer, or zero")}function iU(r){return e=>{if(e>r)throw new Ki(`Value must be smaller than or equal to ${r}`)}}function sU(...r){return e=>{for(let t of r)t(e)}}var Gd=sU(nU,oU,iU(65535));var lr=-1,a8=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new r0(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},qi=new a8,xU=[{code:4,name:"ip4",size:32,valueToBytes:s8,bytesToValue:KS,validate:r=>{if(!Ao(r))throw new Ki(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:wc,bytesToValue:gu,validate:Gd},{code:273,name:"udp",size:16,valueToBytes:wc,bytesToValue:gu,validate:Gd},{code:33,name:"dccp",size:16,valueToBytes:wc,bytesToValue:gu,validate:Gd},{code:41,name:"ip6",size:128,valueToBytes:jS,bytesToValue:VS,stringToValue:HS,validate:r=>{if(!Wm(r))throw new Ki(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:lr},{code:43,name:"ipcidr",size:8,bytesToValue:n8("base10"),valueToBytes:o8("base10")},{code:53,name:"dns",size:lr},{code:54,name:"dns4",size:lr},{code:55,name:"dns6",size:lr},{code:56,name:"dnsaddr",size:lr},{code:132,name:"sctp",size:16,valueToBytes:wc,bytesToValue:gu,validate:Gd},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:lr,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:lr,bytesToValue:n8("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?o8("base58btc")(r):he.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:i8,valueToBytes:FS},{code:445,name:"onion3",size:296,bytesToValue:i8,valueToBytes:$S},{code:446,name:"garlic64",size:lr},{code:447,name:"garlic32",size:lr},{code:448,name:"tls"},{code:449,name:"sni",size:lr},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:lr,bytesToValue:WS(qa),valueToBytes:qS},{code:480,name:"http"},{code:481,name:"http-path",size:lr,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:lr}];xU.forEach(r=>{qi.addProtocol(r)});function zS(r){let e=[],t=0;for(;t<r.length;){let n=Cn(r,t),o=qi.getProtocol(n),i=je(n),s=EU(o,r,t+i),a=0;s>0&&o.size===lr&&(a=je(s));let c=i+a+s,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(s>0){let f=t+i+a,u=r.subarray(f,f+s);l.value=o.bytesToValue?.(u)??j(u)}e.push(l),t+=c}return e}function GS(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=qi.getProtocol(n.code),i=je(n.code),s,a=0,c=0;n.value!=null&&(s=o.valueToBytes?.(n.value)??B(n.value),a=s.byteLength,o.size===lr&&(c=je(a)));let l=new Uint8Array(i+c+a),f=0;su(n.code,l,f),f+=i,s!=null&&(o.size===lr&&(su(a,l,f),f+=c),l.set(s,f)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return gt(t,e)}function XS(r){if(r.charAt(0)!=="/")throw new wr('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let i=1;i<r.length;i++){let s=r.charAt(i);s!=="/"&&(t==="protocol"?o+=r.charAt(i):n+=r.charAt(i));let a=i===r.length-1;if(s==="/"||a){let c=qi.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new wr(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new wr(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new wr("Incomplete multiaddr");return e}function YS(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=qi.getProtocol(e.code);if(t==null)throw new wr(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function EU(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Cn(e,t)}var SU=Symbol.for("nodejs.util.inspect.custom"),g8=Symbol.for("@multiformats/multiaddr");function _U(r){if(r==null&&(r="/"),oi(r))return r.getComponents();if(r instanceof Uint8Array)return zS(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),XS(r);if(Array.isArray(r))return r;throw new wr("Must be a string, Uint8Array, Component[], or another Multiaddr")}var s0=class r{[g8]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=_U(e),t.validate!==!1&&AU(this)}get bytes(){return this.#r==null&&(this.#r=GS(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=YS(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new t0(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return we(this.bytes,e.bytes)}[SU](){return`Multiaddr(${this.toString()})`}};function AU(r){r.getComponents().forEach(e=>{let t=qi.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function oi(r){return!!r?.[g8]}function ie(r){return new s0(r)}var y8=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ve(),this.haveNext=Ve()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ve(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ve(),await ut(this.readNext.promise,t?.signal,t)}};function QS(){return new y8}function TU(r){return r[Symbol.asyncIterator]!=null}async function IU(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*CU(r){let e=new AbortController,t=QS();IU(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*PU(r){for(let e of r)yield*e}function kU(...r){let e=[];for(let t of r)TU(t)||e.push(t);return e.length===r.length?PU(e):CU(r)}var Yr=kU;function vu(r,...e){if(r==null)throw new Error("Empty pipeline");if(w8(r)){let n=r;r=()=>n.source}else if(JS(r)||ZS(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&w8(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)w8(t[n])&&(t[n]=RU(t[n]));return OU(...t)}var OU=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},ZS=r=>r?.[Symbol.asyncIterator]!=null,JS=r=>r?.[Symbol.iterator]!=null,w8=r=>r==null?!1:r.sink!=null&&r.source!=null,RU=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=gr({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(ZS(i))o=async function*(){yield*i,n.end()};else if(JS(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Yr(n,o())}return r.source};var DU=4194304,a0=class extends Error{static name="UnwrappedError";name="UnwrappedError"},eh=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},v8=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},x8=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function NU(r){return typeof r?.closeRead=="function"}function LU(r){return typeof r?.close=="function"}function b8(r){return NU(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:LU(r)?r.status!=="open":!1}function BU(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function c0(r,e){let t=e?.maxBufferSize??DU,n=new fe,o,i=!1;if(!BU(r))throw new P("Argument should be a Stream or a Multiaddr");let s=f=>{if(n.append(f.data),n.byteLength>t){let u=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${t}`))}o?.resolve()};r.addEventListener("message",s);let a=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(f){if(i===!0)throw new a0("Stream was unwrapped");if(b8(r)){if(f?.bytes==null)return null;if(n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new yc(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let u=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=u){o.resolve();break}if(await ut(o.promise,f?.signal),b8(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(b8(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new yc(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(f)}let h=n.sublist(0,d);return n.consume(d),h},async write(f,u){if(i===!0)throw new a0("Stream was unwrapped");r.send(f)||await Qn(r,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return i||(i=!0,r.removeEventListener("message",s),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function Gs(r,e={}){let t=c0(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=je(e.maxDataLength));let n=e?.lengthDecoder??Cn,o=e?.lengthEncoder??Mr;return{async read(s){let a=-1,c=new fe;for(;;){let f=await t.read({...s,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new eh("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new x8(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new v8(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...s,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new yc(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new yc(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(s,a){await t.write(new fe(o(s.byteLength),s),a)},async writeV(s,a){let c=new fe(...s.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function bt(r,e){let t=Gs(r,e),n={read:async(o,i)=>{let s=await t.read(i);return o.decode(s)},write:async(o,i,s)=>{await t.write(i.encode(o),s)},writeV:async(o,i,s)=>{await t.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var MU=1024*1024*4,UU=1024*1024*4,l0=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new fe,this.maxBufferSize=e.maxBufferSize??MU,this.maxDataLength=e.maxDataLength??UU,this.lengthDecoder=e.lengthDecoder??Cn,this.encodingLength=e.encodingLength??je}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new P(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(i){if(i instanceof RangeError)break;throw i}if(t<0||t>this.maxDataLength)throw new eh("Invalid message length");let n=this.encodingLength(t),o=n+t;if(this.buffer.byteLength>=o){let i=this.buffer.sublist(n,o);this.buffer.consume(o),i.byteLength>0&&(yield i)}else break}}};var FU=["string","number","bigint","symbol"],$U=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function e_(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(FU.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(jU(r))return"Buffer";let t=KU(r);return t||"Object"}function jU(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function KU(r){let e=Object.prototype.toString.call(r).slice(8,-1);if($U.includes(e))return e}var v=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};v.uint=new v(0,"uint",!0);v.negint=new v(1,"negint",!0);v.bytes=new v(2,"bytes",!0);v.string=new v(3,"string",!0);v.array=new v(4,"array",!1);v.map=new v(5,"map",!1);v.tag=new v(6,"tag",!1);v.float=new v(7,"float",!0);v.false=new v(7,"false",!0);v.true=new v(7,"true",!0);v.null=new v(7,"null",!0);v.undefined=new v(7,"undefined",!0);v.break=new v(7,"break",!0);var W=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var xu=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",VU=new TextDecoder,HU=new TextEncoder;function u0(r){return xu&&globalThis.Buffer.isBuffer(r)}function th(r){return r instanceof Uint8Array?u0(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var o_=xu?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):r_(r,e,t):(r,e,t)=>t-e>64?VU.decode(r.subarray(e,t)):r_(r,e,t),f0=xu?r=>r.length>64?globalThis.Buffer.from(r):t_(r):r=>r.length>64?HU.encode(r):t_(r),ii=r=>Uint8Array.from(r),Eu=xu?(r,e,t)=>u0(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),i_=xu?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),th(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},s_=xu?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function d0(r,e){if(u0(r)&&u0(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function t_(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function r_(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,c,l,f;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(f=(o&31)<<6|a&63,f>127&&(i=f));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(f=(o&15)<<12|(a&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(f=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,f>65535&&f<1114112&&(i=f))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return E8(n)}var n_=4096;function E8(r){let e=r.length;if(e<=n_)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=n_));return t}var qU=256,rh=class{constructor(e=qU){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=s_(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Eu(n,0,this.cursor)}else t=i_(this.chunks,this.cursor);return e&&this.reset(),t}};var ye="CBOR decode error:",Wi="CBOR encode error:",nh=[];nh[23]=1;nh[24]=2;nh[25]=3;nh[26]=5;nh[27]=9;function zi(r,e,t){if(r.length-e<t)throw new Error(`${ye} not enough data for type`)}var ur=[24,256,65536,4294967296,BigInt("18446744073709551616")];function kn(r,e,t){zi(r,e,1);let n=r[e];if(t.strict===!0&&n<ur[0])throw new Error(`${ye} integer encoded in more bytes than necessary (strict decode)`);return n}function On(r,e,t){zi(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<ur[1])throw new Error(`${ye} integer encoded in more bytes than necessary (strict decode)`);return n}function Rn(r,e,t){zi(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<ur[2])throw new Error(`${ye} integer encoded in more bytes than necessary (strict decode)`);return n}function Dn(r,e,t){zi(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<ur[3])throw new Error(`${ye} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${ye} integers outside of the safe integer range are not supported`)}function a_(r,e,t,n){return new W(v.uint,kn(r,e+1,n),2)}function c_(r,e,t,n){return new W(v.uint,On(r,e+1,n),3)}function l_(r,e,t,n){return new W(v.uint,Rn(r,e+1,n),5)}function u_(r,e,t,n){return new W(v.uint,Dn(r,e+1,n),9)}function Zn(r,e){return br(r,0,e.value)}function br(r,e,t){if(t<ur[0]){let n=Number(t);r.push([e|n])}else if(t<ur[1]){let n=Number(t);r.push([e|24,n])}else if(t<ur[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<ur[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<ur[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${ye} encountered BigInt larger than allowable range`)}}Zn.encodedSize=function(e){return br.encodedSize(e.value)};br.encodedSize=function(e){return e<ur[0]?1:e<ur[1]?2:e<ur[2]?3:e<ur[3]?5:9};Zn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function f_(r,e,t,n){return new W(v.negint,-1-kn(r,e+1,n),2)}function d_(r,e,t,n){return new W(v.negint,-1-On(r,e+1,n),3)}function h_(r,e,t,n){return new W(v.negint,-1-Rn(r,e+1,n),5)}var S8=BigInt(-1),p_=BigInt(1);function m_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new W(v.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${ye} integers outside of the safe integer range are not supported`);return new W(v.negint,S8-BigInt(o),9)}function h0(r,e){let t=e.value,n=typeof t=="bigint"?t*S8-p_:t*-1-1;br(r,e.type.majorEncoded,n)}h0.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*S8-p_:t*-1-1;return n<ur[0]?1:n<ur[1]?2:n<ur[2]?3:n<ur[3]?5:9};h0.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function oh(r,e,t,n){zi(r,e,t+n);let o=Eu(r,e+t,e+t+n);return new W(v.bytes,o,t+n)}function g_(r,e,t,n){return oh(r,e,1,t)}function y_(r,e,t,n){return oh(r,e,2,kn(r,e+1,n))}function w_(r,e,t,n){return oh(r,e,3,On(r,e+1,n))}function b_(r,e,t,n){return oh(r,e,5,Rn(r,e+1,n))}function v_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ye} 64-bit integer bytes lengths not supported`);return oh(r,e,9,o)}function p0(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===v.string?f0(r.value):r.value),r.encodedBytes}function Su(r,e){let t=p0(e);br(r,e.type.majorEncoded,t.length),r.push(t)}Su.encodedSize=function(e){let t=p0(e);return br.encodedSize(t.length)+t.length};Su.compareTokens=function(e,t){return zU(p0(e),p0(t))};function zU(r,e){return r.length<e.length?-1:r.length>e.length?1:d0(r,e)}function ih(r,e,t,n,o){let i=t+n;zi(r,e,i);let s=new W(v.string,o_(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Eu(r,e+t,e+i)),s}function x_(r,e,t,n){return ih(r,e,1,t,n)}function E_(r,e,t,n){return ih(r,e,2,kn(r,e+1,n),n)}function S_(r,e,t,n){return ih(r,e,3,On(r,e+1,n),n)}function __(r,e,t,n){return ih(r,e,5,Rn(r,e+1,n),n)}function A_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ye} 64-bit integer string lengths not supported`);return ih(r,e,9,o,n)}var T_=Su;function _u(r,e,t,n){return new W(v.array,n,t)}function I_(r,e,t,n){return _u(r,e,1,t)}function C_(r,e,t,n){return _u(r,e,2,kn(r,e+1,n))}function P_(r,e,t,n){return _u(r,e,3,On(r,e+1,n))}function k_(r,e,t,n){return _u(r,e,5,Rn(r,e+1,n))}function O_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ye} 64-bit integer array lengths not supported`);return _u(r,e,9,o)}function R_(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ye} indefinite length items not allowed`);return _u(r,e,1,1/0)}function m0(r,e){br(r,v.array.majorEncoded,e.value)}m0.compareTokens=Zn.compareTokens;m0.encodedSize=function(e){return br.encodedSize(e.value)};function Au(r,e,t,n){return new W(v.map,n,t)}function D_(r,e,t,n){return Au(r,e,1,t)}function N_(r,e,t,n){return Au(r,e,2,kn(r,e+1,n))}function L_(r,e,t,n){return Au(r,e,3,On(r,e+1,n))}function B_(r,e,t,n){return Au(r,e,5,Rn(r,e+1,n))}function M_(r,e,t,n){let o=Dn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ye} 64-bit integer map lengths not supported`);return Au(r,e,9,o)}function U_(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ye} indefinite length items not allowed`);return Au(r,e,1,1/0)}function g0(r,e){br(r,v.map.majorEncoded,e.value)}g0.compareTokens=Zn.compareTokens;g0.encodedSize=function(e){return br.encodedSize(e.value)};function F_(r,e,t,n){return new W(v.tag,t,1)}function $_(r,e,t,n){return new W(v.tag,kn(r,e+1,n),2)}function j_(r,e,t,n){return new W(v.tag,On(r,e+1,n),3)}function K_(r,e,t,n){return new W(v.tag,Rn(r,e+1,n),5)}function V_(r,e,t,n){return new W(v.tag,Dn(r,e+1,n),9)}function y0(r,e){br(r,v.tag.majorEncoded,e.value)}y0.compareTokens=Zn.compareTokens;y0.encodedSize=function(e){return br.encodedSize(e.value)};var JU=20,eF=21,tF=22,rF=23;function H_(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${ye} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new W(v.null,null,1):new W(v.undefined,void 0,1)}function q_(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ye} indefinite length items not allowed`);return new W(v.break,void 0,1)}function _8(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${ye} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${ye} Infinity values are not supported`)}return new W(v.float,r,e)}function W_(r,e,t,n){return _8(A8(r,e+1),3,n)}function z_(r,e,t,n){return _8(T8(r,e+1),5,n)}function G_(r,e,t,n){return _8(Z_(r,e+1),9,n)}function w0(r,e,t){let n=e.value;if(n===!1)r.push([v.float.majorEncoded|JU]);else if(n===!0)r.push([v.float.majorEncoded|eF]);else if(n===null)r.push([v.float.majorEncoded|tF]);else if(n===void 0)r.push([v.float.majorEncoded|rF]);else{let o,i=!1;(!t||t.float64!==!0)&&(Y_(n),o=A8(Co,1),n===o||Number.isNaN(n)?(Co[0]=249,r.push(Co.slice(0,3)),i=!0):(Q_(n),o=T8(Co,1),n===o&&(Co[0]=250,r.push(Co.slice(0,5)),i=!0))),i||(nF(n),o=Z_(Co,1),Co[0]=251,r.push(Co.slice(0,9)))}}w0.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){Y_(n);let o=A8(Co,1);if(n===o||Number.isNaN(n))return 3;if(Q_(n),o=T8(Co,1),n===o)return 5}return 9};var X_=new ArrayBuffer(9),Jn=new DataView(X_,1),Co=new Uint8Array(X_,0);function Y_(r){if(r===1/0)Jn.setUint16(0,31744,!1);else if(r===-1/0)Jn.setUint16(0,64512,!1);else if(Number.isNaN(r))Jn.setUint16(0,32256,!1);else{Jn.setFloat32(0,r);let e=Jn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Jn.setUint16(0,31744,!1);else if(t===0)Jn.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Jn.setUint16(0,0):o<-14?Jn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Jn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function A8(r,e){if(r.length-e<2)throw new Error(`${ye} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function Q_(r){Jn.setFloat32(0,r,!1)}function T8(r,e){if(r.length-e<4)throw new Error(`${ye} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function nF(r){Jn.setFloat64(0,r,!1)}function Z_(r,e){if(r.length-e<8)throw new Error(`${ye} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}w0.compareTokens=Zn.compareTokens;function Ye(r,e,t){throw new Error(`${ye} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function b0(r){return()=>{throw new Error(`${ye} ${r}`)}}var ne=[];for(let r=0;r<=23;r++)ne[r]=Ye;ne[24]=a_;ne[25]=c_;ne[26]=l_;ne[27]=u_;ne[28]=Ye;ne[29]=Ye;ne[30]=Ye;ne[31]=Ye;for(let r=32;r<=55;r++)ne[r]=Ye;ne[56]=f_;ne[57]=d_;ne[58]=h_;ne[59]=m_;ne[60]=Ye;ne[61]=Ye;ne[62]=Ye;ne[63]=Ye;for(let r=64;r<=87;r++)ne[r]=g_;ne[88]=y_;ne[89]=w_;ne[90]=b_;ne[91]=v_;ne[92]=Ye;ne[93]=Ye;ne[94]=Ye;ne[95]=b0("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)ne[r]=x_;ne[120]=E_;ne[121]=S_;ne[122]=__;ne[123]=A_;ne[124]=Ye;ne[125]=Ye;ne[126]=Ye;ne[127]=b0("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)ne[r]=I_;ne[152]=C_;ne[153]=P_;ne[154]=k_;ne[155]=O_;ne[156]=Ye;ne[157]=Ye;ne[158]=Ye;ne[159]=R_;for(let r=160;r<=183;r++)ne[r]=D_;ne[184]=N_;ne[185]=L_;ne[186]=B_;ne[187]=M_;ne[188]=Ye;ne[189]=Ye;ne[190]=Ye;ne[191]=U_;for(let r=192;r<=215;r++)ne[r]=F_;ne[216]=$_;ne[217]=j_;ne[218]=K_;ne[219]=V_;ne[220]=Ye;ne[221]=Ye;ne[222]=Ye;ne[223]=Ye;for(let r=224;r<=243;r++)ne[r]=b0("simple values are not supported");ne[244]=Ye;ne[245]=Ye;ne[246]=Ye;ne[247]=H_;ne[248]=b0("simple values are not supported");ne[249]=W_;ne[250]=z_;ne[251]=G_;ne[252]=Ye;ne[253]=Ye;ne[254]=Ye;ne[255]=q_;var Po=[];for(let r=0;r<24;r++)Po[r]=new W(v.uint,r,1);for(let r=-1;r>=-24;r--)Po[31-r]=new W(v.negint,r,1);Po[64]=new W(v.bytes,new Uint8Array(0),1);Po[96]=new W(v.string,"",1);Po[128]=new W(v.array,0,1);Po[160]=new W(v.map,0,1);Po[244]=new W(v.false,!1,1);Po[245]=new W(v.true,!0,1);Po[246]=new W(v.null,null,1);function I8(r){switch(r.type){case v.false:return ii([244]);case v.true:return ii([245]);case v.null:return ii([246]);case v.bytes:return r.value.length?void 0:ii([64]);case v.string:return r.value===""?ii([96]):void 0;case v.array:return r.value===0?ii([128]):void 0;case v.map:return r.value===0?ii([160]):void 0;case v.uint:return r.value<24?ii([Number(r.value)]):void 0;case v.negint:if(r.value>=-24)return ii([31-Number(r.value)])}}var iF={float64:!1,mapSorter:cF,quickEncodeToken:I8},eA=Object.freeze({float64:!0,mapSorter:lF,quickEncodeToken:I8});function sF(){let r=[];return r[v.uint.major]=Zn,r[v.negint.major]=h0,r[v.bytes.major]=Su,r[v.string.major]=T_,r[v.array.major]=m0,r[v.map.major]=g0,r[v.tag.major]=y0,r[v.float.major]=w0,r}var P8=sF(),C8=new rh,x0=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Wi} object contains circular references`);return new r(t,e)}},Xs={null:new W(v.null,null),undefined:new W(v.undefined,void 0),true:new W(v.true,!0),false:new W(v.false,!1),emptyArray:new W(v.array,0),emptyMap:new W(v.map,0)},Ys={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new W(v.float,r):r>=0?new W(v.uint,r):new W(v.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new W(v.uint,r):new W(v.negint,r)},Uint8Array(r,e,t,n){return new W(v.bytes,r)},string(r,e,t,n){return new W(v.string,r)},boolean(r,e,t,n){return r?Xs.true:Xs.false},null(r,e,t,n){return Xs.null},undefined(r,e,t,n){return Xs.undefined},ArrayBuffer(r,e,t,n){return new W(v.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new W(v.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Xs.emptyArray,new W(v.break)]:Xs.emptyArray;n=x0.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=v0(s,t,n);return t.addBreakTokens?[new W(v.array,r.length),o,new W(v.break)]:[new W(v.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[Xs.emptyMap,new W(v.break)]:Xs.emptyMap;n=x0.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[v0(l,t,n),v0(o?r.get(l):r[l],t,n)];return aF(a,t),t.addBreakTokens?[new W(v.map,s),a,new W(v.break)]:[new W(v.map,s),a]}};Ys.Map=Ys.Object;Ys.Buffer=Ys.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Ys[`${r}Array`]=Ys.DataView;function v0(r,e={},t){let n=e_(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Ys[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Ys[n];if(!i)throw new Error(`${Wi} unsupported type: ${n}`);return i(r,n,e,t)}function aF(r,e){e.mapSorter&&r.sort(e.mapSorter)}function cF(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=P8[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function lF(r,e){if(r[0]instanceof W&&e[0]instanceof W){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=J_(t.value)),n._keyBytes||(n._keyBytes=J_(n.value)),d0(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function J_(r){return E0(r,P8,eA)}function tA(r,e,t,n){if(Array.isArray(e))for(let o of e)tA(r,o,t,n);else t[e.type.major](r,e,n)}function E0(r,e,t){let n=v0(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new rh(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return th(a.chunks[0])}}return C8.reset(),tA(C8,n,e,t),C8.toBytes(!0)}function Qs(r,e){return e=Object.assign({},iF,e),E0(r,P8,e)}var uF={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},S0=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Po[e];if(t===void 0){let n=ne[e];if(!n)throw new Error(`${ye} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},sh=Symbol.for("DONE"),_0=Symbol.for("BREAK");function fF(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Tu(e,t);if(i===_0){if(r.value===1/0)break;throw new Error(`${ye} got unexpected break to lengthed array`)}if(i===sh)throw new Error(`${ye} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function dF(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=Tu(e,t);if(a===_0){if(r.value===1/0)break;throw new Error(`${ye} got unexpected break to lengthed map`)}if(a===sh)throw new Error(`${ye} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${ye} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${ye} found repeat map key "${a}"`);let c=Tu(e,t);if(c===sh)throw new Error(`${ye} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function Tu(r,e){if(r.done())return sh;let t=r.next();if(t.type===v.break)return _0;if(t.type.terminal)return t.value;if(t.type===v.array)return fF(t,r,e);if(t.type===v.map)return dF(t,r,e);if(t.type===v.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Tu(r,e);return e.tags[t.value](n)}throw new Error(`${ye} tag not supported (${t.value})`)}throw new Error("unsupported")}function k8(r,e){if(!(r instanceof Uint8Array))throw new Error(`${ye} data to decode must be a Uint8Array`);e=Object.assign({},uF,e);let t=e.tokenizer||new S0(r,e),n=Tu(t,e);if(n===sh)throw new Error(`${ye} did not find any content to decode`);if(n===_0)throw new Error(`${ye} got unexpected break`);return[n,r.subarray(t.pos())]}function Nn(r,e){let[t,n]=k8(r,e);if(n.length>0)throw new Error(`${ye} too many terminals, data makes no sense`);return t}var A0=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Iu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},T0=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},ah=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function I0(r){return r[Symbol.asyncIterator]!=null}function rA(r,e){if(r.byteLength>e)throw new Iu("Message length too long")}var P0=r=>{let e=je(r),t=Ot(e);return Mr(r,t),P0.bytes=e,t};P0.bytes=0;function Gi(r,e){e=e??{};let t=e.lengthEncoder??P0,n=e?.maxDataLength??4194304;function*o(i){rA(i,n);let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return I0(r)?(async function*(){for await(let i of r)yield*o(i)})():(function*(){for(let i of r)yield*o(i)})()}Gi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??P0,n=e?.maxDataLength??4194304;return rA(r,n),new fe(t(r.byteLength),r)};var xc;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(xc||(xc={}));var R8=r=>{let e=Cn(r);return R8.bytes=je(e),e};R8.bytes=0;function Ec(r,e){let t=new fe,n=xc.LENGTH,o=-1,i=e?.lengthDecoder??R8,s=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===xc.LENGTH)try{if(o=i(t),o<0)throw new A0("Invalid message length");if(o>a)throw new Iu("Message length too long");let l=i.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=xc.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>s)throw new T0("Message length length too long");break}throw l}if(n===xc.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=xc.LENGTH}}}return I0(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ah("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ah("Unexpected end of input")})()}Ec.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:i,value:s}=await r.next(t);if(i===!0)return;s!=null&&(yield s)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}})();return Ec(n,{...e??{},onLength:i=>{t=i}})};var oA=Symbol.for("sindresorhus/unlimited-timeout#brand");function iA(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,o={[oA]:!0,id:void 0,cleared:!1,ref(){return n=!1,o.id?.ref?.(),o},unref(){return n=!0,o.id?.unref?.(),o}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return o;(!Number.isFinite(e)||e<0)&&(e=0);let i=performance.now()+e,s=a=>{o.cleared||(a<=2147483647?(o.id=globalThis.setTimeout(()=>{o.cleared||r(...t)},a),n&&o.id?.unref?.()):(o.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,i-c);s(l)},2147483647),n&&o.id?.unref?.()))};return s(e),o}function sA(r){!r||typeof r!="object"||!r[oA]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var pF=new WeakMap;function mF({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(o.reason);let i,s,a,c=r??clearTimeout,l=()=>{c(i),a(o.reason)},f=()=>{o&&o.removeEventListener("abort",l)},u=new Promise((d,h)=>{s=()=>{f(),d(n)},a=h,i=(e??setTimeout)(s,t)});return o&&o.addEventListener("abort",l,{once:!0}),pF.set(u,()=>{c(i),i=null,s()}),u}}var gF=mF({setTimeout:iA,clearTimeout:sA}),aA=gF;var vr=class extends yr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var k0=class extends yr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Cu=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 D8}consume(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,t,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(o,s.consumedPoints,this.blockDuration)),new Gm("Rate limit exceeded",s);return s}penalty(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,-t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}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)}},D8=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let i=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||i>0?(o.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,i=this.storage.get(e);i!=null&&clearTimeout(i.timeoutId);let s={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,s),o>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),s.timeoutId.unref!=null&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:s.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}};function Pu(r,e,t){let n,o,i=!1;function s(){let l={signal:o.signal};if(t?.timeout!=null){let f=De([o.signal,AbortSignal.timeout(t.timeout)]);l.signal=f}i=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{i=!1,!o.signal.aborted&&(n=setTimeout(s,e))})}let a=ji(s,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(s,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{i||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{s()}):n=setTimeout(s,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var N8=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 Wt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new N8({name:e,metrics:t}):n=new Map,n}var Xi="/",cA=new TextEncoder().encode(Xi),O0=cA[0],ht=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]!==O0)throw new Error("Invalid key")}toString(e="utf8"){return j(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Xi))}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=cA),this._buf[0]!==O0){let e=new Uint8Array(this._buf.byteLength+1);e.fill(O0,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===O0;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Xi).slice(1)}type(){return yF(this.baseNamespace())}name(){return wF(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Xi)||(e+=Xi),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Xi):new r(e.slice(0,-1).join(Xi))}child(e){return this.toString()===Xi?e:e.toString()===Xi?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(),...bF(e.map(t=>t.namespaces()))])}};function yF(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function wF(r){let e=r.split(":");return e[e.length-1]}function bF(r){return[].concat(...r)}function vF(r){return r[Symbol.asyncIterator]!=null}function xF(r){if(vF(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=gt([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return gt(e,t)}var R0=xF;function D0({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*EF(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=he.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*L8(n,o))}else{let t=he.asCID(e);t!=null?yield[r.join("/"),t]:yield*L8(e,r)}}function*L8(r,e){if(r==null||r instanceof Uint8Array)return;let t=he.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*EF(i,o)}}function*SF(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&he.asCID(n)==null&&(yield*B8(n,o))}else yield*B8(e,r)}function*B8(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"&&he.asCID(n)==null&&(yield*SF(o,n))}}function _F(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=he.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var M8=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:D0(),bytes:D0(),value:D0(),asBlock:D0()})}links(){return L8(this.value,[])}tree(){return B8(this.value,[])}get(e="/"){return _F(this.value,e.split("/").filter(Boolean))}};function lA({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 M8({cid:e,bytes:r,value:o})}var N0=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},ch=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},L0=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},B0=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},M0=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},U0=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},lh=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var dA="/pin/",uA="/pinned-block/",U8=Gn,fA=1;function F0(r){return r.version===0&&(r=r.toV1()),new ht(`${dA}${r.toString(U8)}`)}var $0=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=F0(e);if(await this.datastore.has(n))throw new N0("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new P("Depth must be greater than or equal to 0");let i=new yr({concurrency:fA});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>we(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Qs(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await R0(this.blockstore.get(e,n)),s=lA({bytes:i,cid:e,codec:o});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new ht(`${uA}${U8.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=Nn(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Qs(i),n),n.onProgress?.(new oe("helia:pin:add",e))}}async*rm(e,t={}){let n=F0(e),o=await this.datastore.get(n,t),i=Nn(o);await this.datastore.delete(n,t);let s=new yr({concurrency:fA});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>we(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:dA+(e.cid!=null?`${e.cid.toString(Gn)}`:"")},e)){let o=he.parse(t.toString().substring(5),Gn),i=Nn(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new ht(`${uA}${U8.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=F0(e),o=await this.datastore.get(n,t);return Nn(o)}async setMetadata(e,t,n){let o=F0(e),i=await this.datastore.get(o,n),s=Nn(i);s.metadata=t??{},await this.datastore.put(o,Qs(s),n)}};var F8=1,$8=5;var uh=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Zs=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},fh=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},dh=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},j8=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}};var AF=5,j0=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??AF,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 er(...this.routers)}async stop(){await or(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Zs("No content routers available");let n=new vr({concurrency:this.providerLookupConcurrency}),o=0,i=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let c=Sc(this.routers,"findProviders").map(async function*(l){let f=0;try{for await(let u of l.findProviders(e,t))f++,yield u}catch(u){i.push(u)}finally{s.log("router %s found %d providers for %c",l,f,e),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let l of Yr(n.toGenerator(),...c))if(l!=null){if(l.multiaddrs.length===0){if(n.find(l.id)!=null)continue;n.add(async()=>{try{let f=await this.findPeer(l.id,t);return f.multiaddrs.length===0?null:{...f,protocols:l.protocols,routing:l.routing}}catch(f){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,f),null}},{peerId:l.id,signal:t.signal}).catch(f=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,f)});continue}o++,yield l}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new Zs("No content routers available");await Promise.all(Sc(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Sc(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Sc(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){let n=[],o;try{o=await Promise.any(Sc(this.routers,"get").map(async i=>{try{return await i.get(e,t)}catch(s){this.log("router %s failed with %e",i,s),n.push(s)}}))}catch{}if(o==null)throw new M0(n,`Failed to get value key ${j(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new Zs("No peer routers available");let n=this,o=Yr(...Sc(this.routers,"findPeer").map(i=>(async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let i of o)if(i!=null)return i;throw new Xe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Zs("No peer routers available");for await(let n of Yr(...Sc(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Sc(r,e){return r.filter(t=>t[e]!=null)}var Ln=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Qr(r,e,t,n){let o=new Ln(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let i=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((s,a)=>{function c(){V8(t,"abort",u),V8(r,e,l),V8(r,i,f)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),s(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)};K8(t,"abort",u),K8(r,e,l),K8(r,i,f)})}function K8(r,e,t){r!=null&&(hA(r)?r.addEventListener(e,t):r.addListener(e,t))}function V8(r,e,t){r!=null&&(hA(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function hA(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var K0=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var V0=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 Ln)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function TF(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var H0=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=TF(),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 Ln),this.cleanup())}async join(e={}){let t=new V0(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 ut(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 H8(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 hh=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=H8(this.emitEmpty.bind(this),1),this.emitIdle=H8(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 K0;let n=new H0(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ln)}),this.clear()}async onEmpty(e){this.size!==0&&await Qr(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Qr(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Qr(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=gr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new Ln("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var q0="lock:worker:request-read",W0="lock:worker:abort-read-request",z0="lock:worker:release-read",G0="lock:master:grant-read",X0="lock:master:error-read",Y0="lock:worker:request-write",Q0="lock:worker:abort-write-request",Z0="lock:worker:release-write",J0="lock:master:grant-write",e2="lock:master:error-write",t2="lock:worker:finalize",r2="mortice",pA={singleProcess:!1};var q8=(r,e,t,n,o,i,s,a,c)=>l=>{if(l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===o&&r.safeDispatchEvent(t,{detail:{name:f.name,identifier:f.identifier,handler:async()=>{e.postMessage({type:c,name:f.name,identifier:f.identifier}),await new Promise(u=>{let d=h=>{if(h?.data==null)return;let m={type:h.data.type,name:h.data.name,identifier:h.data.identifier};m.type===a&&m.identifier===f.identifier&&(e.removeEventListener("message",d),u())};e.addEventListener("message",d)})},onError:u=>{e.postMessage({type:s,name:f.name,identifier:f.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),f.type===i&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===t2&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var mA=(r=10)=>Math.random().toString().substring(2,r+2);var n2=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(r2)}readLock(e){return this.sendRequest(q0,W0,G0,X0,z0,e)}writeLock(e){return this.sendRequest(Y0,Q0,J0,e2,Z0,e)}finalize(){this.channel.postMessage({type:t2,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=mA();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let f=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",f,{once:!0});let u=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",u),s?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",u),s?.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 gA=r=>{if(r=Object.assign({},pA,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(r2),n=new _e;return t.addEventListener("message",q8(n,t,"requestReadLock","abortReadLockRequest",q0,W0,X0,z0,G0)),t.addEventListener("message",q8(n,t,"requestWriteLock","abortWriteLockRequest",Y0,Q0,e2,Z0,J0)),n}return new n2(r.name)};var _c=new Map,ph;function yA(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function IF(r){if(ph==null&&(ph=gA(r),!yA(ph))){let e=ph;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=_c.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=_c.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=_c.get(n);o?.finalize()})}return ph}async function W8(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new Ln)};return e?.signal?.addEventListener("abort",i,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",i),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),o}var wA=(r,e)=>{let t=_c.get(r);if(t!=null)return t;let n=IF(e);if(yA(n))return t=n,_c.set(r,t),t;let o=new hh({concurrency:1}),i;return t={async readLock(s){if(i!=null)return W8(i,s);i=new hh({concurrency:e.concurrency,autoStart:!1});let a=i,c=W8(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(s){return i=null,W8(o,s)},finalize:()=>{_c.delete(r)},queue:o},_c.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var CF={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function mh(r){let e=Object.assign({},CF,r);return wA(e.name,e)}var o2=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=mh({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await er(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 ch("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 i of e){if(await o.pins.isPinned(i))throw new ch("Block was pinned - please unpin and try again");yield i}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var z8=new ht("/version"),bA=1;async function vA(r){if(!await r.has(z8)){await r.put(z8,B(`${bA}`));return}let e=await r.get(z8),t=j(e);if(parseInt(t,10)!==bA)throw new L0("Invalid datastore version, a datastore migration may be required")}var Y8={};Nt(Y8,{code:()=>X8,decode:()=>UF,decodeOptions:()=>LF,encode:()=>MF,encodeOptions:()=>DF,name:()=>BF,toByteView:()=>EA});var xA=42;function EA(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function PF(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=he.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new W(v.tag,xA),new W(v.bytes,t)]}function kF(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function OF(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 RF(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 G8={float64:!0,typeEncoders:{Map:RF,Object:PF,undefined:kF,number:OF}},DF={...G8,typeEncoders:{...G8.typeEncoders}};function NF(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return he.decode(r.subarray(1))}var i2={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};i2.tags[xA]=NF;var LF={...i2,tags:i2.tags.slice()},BF="dag-cbor",X8=113,MF=r=>Qs(r,G8),UF=r=>Nn(EA(r),i2);var nw={};Nt(nw,{code:()=>rw,decode:()=>_A,encode:()=>SA,format:()=>XF,name:()=>GF,parse:()=>QF,stringify:()=>XF});var Q8=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===v.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===v.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[v.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[v.negint.major](e,t){this[v.uint.major](e,t)}[v.bytes.major](e,t){throw new Error(`${Wi} unsupported type: Uint8Array`)}[v.string.major](e,t){this.prefix(e);let n=f0(JSON.stringify(t.value));e.push(n.length>32?th(n):n)}[v.array.major](e,t){this.prefix(e),this.inRecursive.push({type:v.array,elements:0}),e.push([91])}[v.map.major](e,t){this.prefix(e),this.inRecursive.push({type:v.map,elements:0}),e.push([123])}[v.tag.major](e,t){}[v.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===v.array)e.push([93]);else if(s.type===v.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(`${Wi} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function FF(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Wi} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==v.string||n.type!==v.string)throw new Error(`${Wi} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Wi} unexpected duplicate map keys, this is not supported`)}var $F={addBreakTokens:!0,mapSorter:FF};function Z8(r,e){return e=Object.assign({},$F,e),E0(r,new Q8,e)}var ku=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(`${ye} 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(`${ye} 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 W(v.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(`${ye} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${ye} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new W(v.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new W(s>=0?v.uint:v.negint,s,this._pos-e):new W(s>=0?v.uint:v.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${ye} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new W(v.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${ye} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${ye} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${ye} unexpected unicode sequence at position ${this._pos}`);let c,l,f,u;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(i&31)<<6|c&63,u>127&&(s=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(i&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(s=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=(i&15)<<18|(c&63)<<12|(l&63)<<6|f&63,u>65535&&u<1114112&&(s=u))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${ye} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${ye} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new W(v.string,E8(t),this._pos-e);default:if(i<32)throw new Error(`${ye} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${ye} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new W(v.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new W(v.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new W(v.null,null,4);case 102:return this.expect([102,97,108,115,101]),new W(v.false,!1,5);case 116:return this.expect([116,114,117,101]),new W(v.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(`${ye} 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 W(v.break,void 0,1);if(this.ch()!==44)throw new Error(`${ye} 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 W(v.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 W(v.break,void 0,1);if(this.ch()!==44)throw new Error(`${ye} 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 W(v.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${ye} 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(`${ye} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function J8(r,e){return e=Object.assign({tokenizer:new ku(r,e)},e),Nn(r,e)}function KF(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function VF(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=he.asCID(r);if(!e)return null;let t=e.toString();return[new W(v.map,1/0,1),new W(v.string,"/",1),new W(v.string,t,t.length),new W(v.break,void 0,1)]}function s2(r){let e=Ht.encode(r).slice(1);return[new W(v.map,1/0,1),new W(v.string,"/",1),new W(v.map,1/0,1),new W(v.string,"bytes",5),new W(v.string,e,e.length),new W(v.break,void 0,1),new W(v.break,void 0,1)]}function ko(r){return s2(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function HF(r){return s2(new Uint8Array(r))}function qF(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function WF(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 zF={typeEncoders:{Object:VF,Buffer:s2,Uint8Array:s2,Int8Array:ko,Uint16Array:ko,Int16Array:ko,Uint32Array:ko,Int32Array:ko,Float32Array:ko,Float64Array:ko,Uint8ClampedArray:ko,BigInt64Array:ko,BigUint64Array:ko,DataView:ko,ArrayBuffer:HF,undefined:qF,number:WF}},ew=class extends ku{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===v.map){let t=this._next();if(t.type===v.string&&t.value==="/"){let n=this._next();if(n.type===v.string){if(this._next().type!==v.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new W(v.tag,42,0)}if(n.type===v.map){let o=this._next();if(o.type===v.string&&o.value==="bytes"){let i=this._next();if(i.type===v.string){for(let a=0;a<2;a++)if(this._next().type!==v.break)throw new Error("Invalid encoded Bytes form");let s=Ht.decode(`m${i.value}`);return new W(v.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},tw={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};tw.tags[42]=he.parse;var GF="dag-json",rw=297,SA=r=>Z8(r,zF),_A=r=>{let e=KF(r),t=Object.assign(tw,{tokenizer:new ew(e,tw)});return J8(e,t)},XF=r=>YF.decode(SA(r));var YF=new TextDecoder,QF=r=>_A(ZF.encode(r)),ZF=new TextEncoder;var lw={};Nt(lw,{code:()=>cw,createLink:()=>NA,createNode:()=>DA,decode:()=>f$,encode:()=>u$,name:()=>l$,prepare:()=>sw,validate:()=>aw});var JF=new TextDecoder;function ow(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 a2(r,e){let t;[t,e]=ow(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 AA(r,e){let t;return[t,e]=ow(r,e),[t&7,t>>3,e]}function e$(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=AA(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=a2(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=a2(r,n),e.Name=JF.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=ow(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function TA(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=AA(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=a2(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]=a2(r,t),n.push(e$(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var CA=new TextEncoder,IA=2**32,t$=2**31;function r$(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=gh(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=CA.encode(r.Name);t-=n.length,e.set(n,t),t=gh(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=gh(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function PA(r){let e=o$(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=gh(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=r$(r.Links[o],t.subarray(0,n));n-=i,n=gh(t,n,i)-1,t[n]=18}return t}function n$(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ou(t)}if(typeof r.Name=="string"){let t=CA.encode(r.Name).length;e+=1+t+Ou(t)}return typeof r.Tsize=="number"&&(e+=1+Ou(r.Tsize)),e}function o$(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ou(t)}if(r.Links)for(let t of r.Links){let n=n$(t);e+=1+n+Ou(n)}return e}function gh(r,e,t){e-=Ou(t);let n=e;for(;t>=t$;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ou(r){return r%2===0&&r++,Math.floor((i$(r)+6)/7)}function i$(r){let e=0;return r>=IA&&(r=Math.floor(r/IA),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+s$[r]}var s$=[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 a$=["Data","Links"],c$=["Hash","Name","Tsize"],iw=new TextEncoder;function OA(r,e){if(r===e)return 0;let t=r.Name?iw.encode(r.Name):[],n=e.Name?iw.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function kA(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function RA(r){if(typeof r.asCID=="object"){let t=he.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=he.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=he.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=he.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 sw(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=iw.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(RA),e.Links.sort(OA);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function aw(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!kA(r,a$))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(!kA(t,c$))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&&OA(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function DA(r,e=[]){return sw({Data:r,Links:e})}function NA(r,e,t){return RA({Hash:t,Name:r,Tsize:e})}function LA(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var l$="dag-pb",cw=112;function u$(r){aw(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),PA(e)}function f$(r){let e=LA(r),t=TA(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=he.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function Ru(r){return r?.then!=null}function BA(r=[],e){let t={[cw]:lw,[Ga]:jl,[X8]:Y8,[rw]:nw,[I6]:pm};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ru(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new dh(`Could not load codec for ${n}`)}}function MA(r=[],e){let t={[St.code]:St,[gm.code]:gm,[Dr.code]:Dr};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ru(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new fh(`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 eo=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 Yi=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 c2=0,Du=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},l2=class extends Yi{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===c2){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Du(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===c2){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Du(`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 eo;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===c2){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Du(`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===c2){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Du(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function d$(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 Nu=d$;function h$(r){return r[Symbol.asyncIterator]!=null}function p$(r,e){let t=0;if(h$(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Nu(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Oo=p$;function m$(r){return r[Symbol.asyncIterator]!=null}function UA(r){return r?.then!=null}function g$(r,e){let t=0;if(m$(r))return(async function*(){for await(let c of r){let l=e(c,t++);UA(l)&&await l,yield c}})();let n=Nu(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s?.then=="function")return(async function*(){await s,yield o;for(let c of n){let l=e(c,t++);UA(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var uw=g$;var y$=128,u2=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 l2(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??y$}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new oe("blocks:put:duplicate",e)),e):(n.onProgress?.(new oe("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new oe("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Oo(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new oe("blocks:put-many:duplicate",i)),!s}),o=uw(n,async({cid:i})=>{t.onProgress?.(new oe("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new oe("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new lh("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new oe("blocks:get:providers:get",e));let s=await FA(e,this.components.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new oe("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new oe("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new oe("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new oe("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(uw(e,async n=>{let o=await this.child.has(n,t),i=t.offline===!0;if(!o){if(i)throw new lh("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new oe("blocks:get-many:providers:get",n));let a=await FA(n,this.components.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new oe("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new oe("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new oe("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new oe("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 oe("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},f2=class extends u2{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await er(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 fw({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},fw=class extends u2{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=De([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=De([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=De([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=De([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=De([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=De([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=De([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=De([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function w$(r){return typeof r.retrieve=="function"}var b$=(r,e)=>{if(e==null)throw new P(`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(Ru(o)?n=await o:n=o,!we(n.digest,r.multihash.digest))throw new Cs("Hash of downloaded block did not match multihash from passed CID")}};async function FA(r,e,t,n){let o=b$(r,t),i=new AbortController,s=De([i.signal,n.signal]);i.signal;let a=[];for(let c of e)w$(c)&&a.push(c);if(a.length===0)throw new B0(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,f=await c.retrieve(r,{...n,signal:s,validateFn:async 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}}))}catch(c){throw new U0(c.errors,`Failed to load block for ${r}`)}finally{i.abort(),s.clear()}}var Ac=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=Fr(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=Ht.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let i=Ve(),s={promise:i.promise,observers:1};if(this.requests.set(n,s),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));try{await ut(this.initialPeerSearchComplete,t.signal),u&&this.log("found initial session peers for %c",e)}catch(d){throw u&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),s.observers>1&&i.reject(d),d}}let a=!1,c=new yr({concurrency:this.maxProviders});c.addEventListener("failure",u=>{this.log.error("error querying provider %s, evicting from session - %e",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),c.addEventListener("success",u=>{a=!0,i.resolve(u.detail.result)}),c.addEventListener("idle",()=>{if(a){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 u=0;u<this.minProviders&&this.providers.length!==0;u++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(u=>{this.log.error("could not find new providers for %c - %e",e,u),i.reject(u)})});let l=u=>{c.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)})};this.addEventListener("provider",l),Promise.all([...this.providers].map(async u=>c.add(async()=>this.queryProvider(e,u,t),{provider:u}))).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,u)});let f=()=>{i.reject(new Hr(t.signal?.reason??"Session aborted")),c.abort()};t.signal?.addEventListener("abort",f);try{return await ut(i.promise,t.signal)}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",f),c.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=Ve(),i=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(;i<t&&this.initialProviders.length>0;){let s=this.initialProviders.pop();if(s==null)break;let a=await this.convertToProvider(s,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(i<this.maxProviders)for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new uh(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),o.reject(s)}),o.promise}};var d2=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??Qo(),this.log=this.logger.forComponent("helia"),this.getHasher=MA(e.hashers,e.loadHasher),this.getCodec=BA(e.codecs,e.loadCodec),this.dns=e.dns??vm(),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 j0(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let i=[o],s=v$(o);s!=null&&i.push(s);let a=x$(o);return a!=null&&i.push(a),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new f2(t,e);this.pins=new $0(e.datastore,n,this.getCodec),this.blockstore=new o2(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await vA(this.datastore),await er(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 an(o.deleteMany((async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new oe("helia:gc:deleted",i))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new oe("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function v$(r){return r?.[ki]}function x$(r){return r?.[Ri]}function E$(r){return r[Symbol.asyncIterator]!=null}function S$(r,e){let t=0;if(E$(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=Nu(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s.then=="function")return(async function*(){yield await s;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield s;for(let c of n)yield a(c,t++)})()}var to=S$;function _$(r){return r[Symbol.asyncIterator]!=null}function A$(r,e){return _$(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 Js=A$;var yh="/ipfs/bitswap/1.2.0";var Vt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(Vt||(Vt={}));var dw;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(dw||(dw={}));(function(r){r.codec=()=>kt(dw)})(Vt||(Vt={}));var Lu;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),Vt.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={cid:ke(0),priority:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.cid=t.bytes();break}case 2:{i.priority=t.int32();break}case 3:{i.cancel=t.bool();break}case 4:{i.wantType=Vt.codec().decode(t);break}case 5:{i.sendDontHave=t.bool();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Lu||(Lu={}));var h2;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let i of t.entries)n.uint32(10),Lu.codec().encode(i,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={entries:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.entries!=null&&i.entries.length===o.limits.entries)throw new dt('Decode error - map field "entries" had too many elements');i.entries.push(Lu.codec().decode(t,t.uint32(),{limits:o.limits?.entries$}));break}case 2:{i.full=t.bool();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(h2||(h2={}));var Bu;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={prefix:ke(0),data:ke(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.prefix=t.bytes();break}case 2:{i.data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Bu||(Bu={}));var ro;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(ro||(ro={}));var p2;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(p2||(p2={}));(function(r){r.codec=()=>kt(p2)})(ro||(ro={}));var Mu;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&p2[t.type]!==0&&(n.uint32(16),ro.codec().encode(t.type,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={cid:ke(0),type:ro.HaveBlock},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.cid=t.bytes();break}case 2:{i.type=ro.codec().decode(t);break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Mu||(Mu={}));var Tc;(function(r){let e;r.codec=()=>(e==null&&(e=Ie((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),h2.codec().encode(t.wantlist,n)),t.blocks!=null)for(let i of t.blocks)n.uint32(26),Bu.codec().encode(i,n);if(t.blockPresences!=null)for(let i of t.blockPresences)n.uint32(34),Mu.codec().encode(i,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={blocks:[],blockPresences:[],pendingBytes:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.wantlist=h2.codec().decode(t,t.uint32(),{limits:o.limits?.wantlist});break}case 3:{if(o.limits?.blocks!=null&&i.blocks.length===o.limits.blocks)throw new dt('Decode error - map field "blocks" had too many elements');i.blocks.push(Bu.codec().decode(t,t.uint32(),{limits:o.limits?.blocks$}));break}case 4:{if(o.limits?.blockPresences!=null&&i.blockPresences.length===o.limits.blockPresences)throw new dt('Decode error - map field "blockPresences" had too many elements');i.blockPresences.push(Mu.codec().decode(t,t.uint32(),{limits:o.limits?.blockPresences$}));break}case 5:{i.pendingBytes=t.int32();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Te(t,r.codec()),r.decode=(t,n)=>Ae(t,r.codec(),n)})(Tc||(Tc={}));function $A(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var m2=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var T$=4193648,I$=T$+16;function*jA(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],i=0,s=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},f=Tc.encode(l).byteLength,{added:u,hasMore:d,newSize:h}=hw(o,l.blocks,a,e,f,C$);a+=u,f=h;let m=d;({added:u,hasMore:d,newSize:h}=hw(n,l.blockPresences,s,e,f,P$)),s+=u,f=h;let w=d;if({added:u,hasMore:d,newSize:h}=hw(t,l.wantlist.entries,i,e,f,k$),i+=u,f=h,c=!m&&!w&&!d,c||(l.wantlist.full=!1),yield Tc.encode(l),c)break}}function hw(r,e,t,n,o,i){let s=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],f=i(l);if(f>I$)throw new m2("Cannot send block as after encoding it is over the max message size");let u=o+f;if(u>n){a=!0;break}e.push(l),s++,o=u}return{hasMore:a,added:s,newSize:o}}function C$(r){return pw(3,Bu.encode(r))}function P$(r){return pw(4,Mu.encode(r))}function k$(r){return pw(1,Lu.encode(r))}function pw(r,e){let t=je(r),n=je(e.byteLength);return t+n+e.byteLength}var g2=class extends _e{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[yh],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new vr({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new Yo(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let i=gr();e.addEventListener("message",s=>{i.push(s.data)}),e.addEventListener("remoteCloseWrite",()=>{i.end()}),e.addEventListener("close",s=>{s.error!=null&&i.end(s.error)});for await(let s of Ec(i,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Tc.decode(s);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new oe("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a[]",n.id,n.multiaddrs);continue}t?.onProgress?.(new oe("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await an(to(Js(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(i=>e.equals(i.options.peerId)&&i.status==="queued");if(o!=null){o.options.message=$A(o.options.message,t),await o.join({signal:n?.signal});return}await this.sendQueue.add(async i=>{let s=i?.message;if(s==null)throw new P("No message to send");this.log("sendMessage to %p",e),i?.onProgress?.(new oe("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,yh,i);await a.closeRead();try{for(let c of jA(s,this.maxOutgoingMessageSize))a.send(Gi.single(c))||await a.onDrain(i);await a.close(i)}catch(c){i?.onProgress?.(new oe("bitswap:network:send-wantlist:error",{peer:e,error:c})),this.log.error("error sending message to %p - %e",e,c),a.abort(c)}this._updateSentStats(s.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new _n("Network isn't running");t?.onProgress?.(new oe("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),Qr(this.libp2p,"peer:identify",t?.signal,{filter:o=>{if(!o.detail.peerId.equals(e))return!1;if(o.detail.protocols.includes(yh))return!0;throw new Ul(`${e} did not support ${yh}`)}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};var KA=Symbol.for("nodejs.util.inspect.custom"),F$=114,wh=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()})`}[am]=!0;toString(){return this.string==null&&(this.string=ft.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return he.createV1(F$,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return we(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return we(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[KA](){return`PeerId(${this.toString()})`}},bh=class extends wh{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},vh=class extends wh{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},xh=class extends wh{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},$$=2336,Eh=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Dr.digest(B(this.url))}[KA](){return`PeerId(${this.url})`}[am]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return he.createV1($$,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var j$=114,VA=2336;function yt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=lt(ft.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Ro(he.parse(r));if(e==null)throw new P('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=lt(e.decode(r))}return zt(t)}function si(r){if(r.type==="Ed25519")return new vh({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new xh({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new bh({multihash:r.toCID().multihash,publicKey:r});throw new wo}function HA(r){return si(r.publicKey)}function zt(r){if(V$(r))return new bh({multihash:r});if(K$(r))try{let e=Um(r);if(e.type==="Ed25519")return new vh({multihash:r,publicKey:e});if(e.type==="secp256k1")return new xh({multihash:r,publicKey:e})}catch{let t=j(r.digest);return new Eh(new URL(t))}throw new Cs("Supplied PeerID Multihash is invalid")}function Ro(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==j$&&r.code!==VA)throw new rm("Supplied PeerID CID is invalid");if(r.code===VA){let e=j(r.multihash.digest);return new Eh(new URL(e))}return zt(r.multihash)}function K$(r){return r.code===Dr.code}function V$(r){return r.code===St.code}function Ic(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 y2(r){let e=lt(ft.decode(`z${r}`));return zt(e)}var $r=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 Ic(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 Ic(this.map.values(),e=>e.key)}values(){return Ic(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Bn=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 Ic(this.set.entries(),e=>{let t=y2(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=y2(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ic(this.set.values(),e=>y2(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}};function mw(){return new Bn}var w2=class{filter;constructor(e,t){this.filter=Fr(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function gw(r,e=.001){return new w2(r,e)}var yw=class extends $r{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 Qi(r){let{name:e,metrics:t}=r,n;return t!=null?n=new yw({name:e,metrics:t}):n=new $r,n}var Zi=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=Ht.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=Ht.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=Ht.encode(e.multihash.bytes);this.blocks.set(n,t)}};function H$(r){let e=new Uint8Array(r.reduce((n,o)=>n+je(o),0)),t=0;for(let n of r)e=Mr(n,e,t),t+=je(n);return e}var qA=H$;function ww(r){return qA([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var b2=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new Zi,n=new Set;for(let[o,i]of this.wants.entries())try{let s=await R0(this.blockstore.get(i.cid,e));i.wantType===Vt.WantHave?s.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:ww(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ro.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:ww(i.cid)}))}catch(s){if(s.name!=="NotFoundError")throw s;if(this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ro.DoNotHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var v2=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Qi({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new b2({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,i)=>o+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let i=he.decode(o.cid),s=j(i.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(s)):(o.wantType===Vt.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(s,{cid:i,priority:o.priority,wantType:o.wantType??Vt.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=j(e.multihash.bytes,"base64"),o=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&o.push(i);await Promise.all(o.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var bw=class extends Ac{wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has&&o.block!=null)return o.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}async convertToProvider(e,t){return on(e)?e:(await this.libp2p.dial(e,t)).remotePeer}};function WA(r,e){return new bw(r,e)}var x2=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};function q$(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Cn(r);e.push(t),r=r.slice(je(t))}return e}var zA=q$;var E2=class extends _e{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),this.peers=Qi({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Wt({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=j(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??Vt.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===Vt.WantHave&&t.wantType===Vt.WantBlock&&(o.wantType=Vt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===Vt.WantBlock?(await Qr(this,"block",t?.signal,{filter:a=>we(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Qr(this,"presence",t?.signal,{filter:s=>we(e.multihash.digest,s.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=Ve(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Zi;for(let[i,s]of this.wants.entries())t.has(i)||s.cancel||(n.add(i),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer - %e",i)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=j(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Zi;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:Vt.WantHave,priority:1}),await this.network.sendMessage(t,o),(await Qr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&we(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:Vt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Zi;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:Vt.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await Qr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&we(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=j(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let i=zA(o.prefix),s=i[0],a=i[1],c=i[2],l=i[3],f=c===St.code?St:await this.hashLoader?.getHasher(c);if(f==null){this.log.error("unknown hash algorithm",c);continue}let u=f.digest(o.data,{truncate:l});u.then!=null&&(u=await u);let d=he.create(s===0?0:1,a,u);this.log("received block from %p for %c",e,d),this.safeDispatchEvent("block",{detail:{sender:e,cid:d,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:d,has:!0,block:o.data}});let h=j(d.multihash.bytes,"base64"),m=this.wants.get(h);m!=null&&(m.cancel=!0,n=!0)}for(let{cid:o,type:i}of t.blockPresences){let s=he.decode(o);this.log("received %s from %p for %c",i,e,s),this.safeDispatchEvent("presence",{detail:{sender:e,cid:s,has:i===ro.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Zi(!0);for(let[o,i]of this.wants.entries())i.cancel||(t.add(o),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:Vt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var S2=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new x2(e),this.network=new g2(e,t),this.peerWantLists=new v2({...e,network:this.network},t),this.wantList=new E2({...e,network:this.network},t)}createSession(e={}){return WA({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=De([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,i)});try{let i=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new oe("bitswap:block",{cid:e,sender:i.sender})),i.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var GA=(r,e={})=>new S2(r,e);var vw=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=GA(e,{hashLoader:{getHasher:async o=>n(o)},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function xw(r={}){return e=>new vw(e,r)}var W$=[6,53,56,54,55];function XA(r){return ZA("sni",r)?.value}function YA(r){let e=ZA("tcp",r)?.value;return e==null?"":`:${e}`}function ZA(r,e){return e.find(t=>t.name===r)}function QA(r){return r.some(({code:e})=>e===448)}function Do(r,e){let t=JA[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 JA={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://${Do(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Do(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`${Do(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Do(t,e)}`},http:(r,e)=>{let t=QA(e),n=XA(e),o=YA(e);if(t&&n!=null)return`https://${n}${o}`;let i=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Do(s,e);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Do(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 Do(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Do(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Do(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=QA(e),n=XA(e),o=YA(e);if(t&&n!=null)return`wss://${n}${o}`;let i=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Do(s,e);return a=a?.replace("tcp://",""),`${i}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Do(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function ea(r,e){let n=ie(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=JA[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let s=i(o,n)??"";return e?.assumeHttp!==!1&&W$.includes(o.code)&&(s=s.replace(/^.*:\/\//,""),o.value==="443"?s=`https://${s}`:s=`http://${s}`),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}var at=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Pe=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),eT=r=>({match:e=>r.match(e)===!1?e:!1}),We=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),jr=(...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}}),Qe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ct(...r){function e(o){if(o==null)return!1;let i=o.getComponents();for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matchers:r,matches:t,exactMatch:n}}var z$=Pe(421),tT=ct(z$),A2=Pe(54),T2=Pe(55),I2=Pe(56),Sw=Pe(53),Wce=ct(A2,We(Pe(421))),zce=ct(T2,We(Pe(421))),Gce=ct(I2,We(Pe(421))),C2=ct(jr(Sw,I2,A2,T2),We(Pe(421))),rT=Qe(Pe(4),We(Pe(43))),nT=Qe(We(Pe(42)),Pe(41),We(Pe(43))),_w=jr(rT,nT),Cc=jr(_w,Sw,A2,T2,I2),oT=ct(jr(_w,Qe(jr(Sw,I2,A2,T2),We(Pe(421))))),Aw=ct(rT),Tw=ct(nT),iT=ct(_w),Iw=Qe(Cc,Pe(6)),Sh=Qe(Cc,Pe(273)),Pc=ct(Qe(Iw,We(Pe(421)))),Xce=ct(Sh),Cw=Qe(Sh,at(460),We(Pe(421))),P2=Qe(Sh,at(461),We(Pe(421))),G$=jr(Cw,P2),Yce=ct(Cw),sT=ct(P2),Ew=jr(Cc,Iw,Sh,Cw,P2),aT=jr(Qe(Ew,at(477),We(Pe(421)))),Ji=ct(aT),cT=jr(Qe(Ew,at(478),We(Pe(421))),Qe(Ew,at(448),We(Pe(449)),at(477),We(Pe(421)))),kc=ct(cT),lT=Qe(Sh,at(280),We(Pe(466)),We(Pe(466)),We(Pe(421))),_h=ct(lT),uT=Qe(P2,at(465),We(Pe(466)),We(Pe(466)),We(Pe(421))),Pw=ct(uT),_2=jr(aT,cT,Qe(Iw,We(Pe(421))),Qe(G$,We(Pe(421))),Qe(Cc,We(Pe(421))),lT,uT,Pe(421)),Uu=ct(_2),X$=Qe(We(_2),at(290),eT(at(281)),We(Pe(421))),fr=ct(X$),Y$=jr(Qe(_2,at(290),at(281),We(Pe(421))),Qe(_2,at(281),We(Pe(421))),Qe(at(281),We(Pe(421)))),Ah=ct(Y$),Q$=jr(Qe(Cc,Pe(6),at(480),We(Pe(421))),Qe(Cc,at(480),We(Pe(421)))),fT=ct(Q$),Z$=Qe(Cc,jr(Qe(Pe(6,"443"),at(480)),Qe(Pe(6),at(443)),Qe(Pe(6),at(448),at(480)),Qe(at(448),at(480)),at(448),at(443)),We(Pe(421))),dT=ct(Z$),J$=jr(Qe(Pe(777),We(Pe(421)))),Qce=ct(J$),ej=jr(Qe(Pe(400),We(Pe(421)))),Zce=ct(ej);function kw(r,e,t){return r.filter(n=>{if(dT.matches(n)||e&&fT.matches(n))return t||C2.matches(n)?!0:Mt(n)===!1;if(!e&&t){let{host:o}=Ce(n);if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*k2(r,e,t,n,o,i={}){for await(let s of e.findProviders(r,i)){let a=kw(s.multiaddrs,n,o);if(a.length===0)continue;let c=ea(a[0]),l={type:"trustless-gateway",cid:r,url:c.toString(),routing:s.routing};i?.onProgress?.(new oe("trustless-gateway:found-provider",l)),yield new Fu(c,{logger:t,transformRequestInit:i.transformRequestInit})}}async function hT(r,e,t){let{signal:n,log:o}=t??{},i=r.headers.get("content-length");if(i!=null){let c=parseInt(i,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 s=r.body?.getReader();if(s==null)throw new Error("Response body is not readable");let a=new fe;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await s.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{s.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{s.releaseLock()})}return a.subarray()}var Fu=class{url;#e=0;#t=0;#r=0;#a=0;#c=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}`)}#m(e){let t=e.multihash.bytes;return Ht.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=pT}={}){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 i=this.#m(e),s=new AbortController,a=()=>{s.abort()};t?.addEventListener("abort",a);try{let c=this.#c.get(i);if(c==null){this.#e++;let l={signal:s.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},f=this.transformRequestInit!=null?await this.transformRequestInit(l):l,u=new Headers(f.headers);this.log(`sending request
|
|
14
14
|
%s %s HTTP/1.1
|
|
15
15
|
%s
|
|
16
16
|
`,f.method??"GET",o,[...u.entries()].map(([d,h])=>`${d}: ${h}`).join(`
|
|
@@ -18,7 +18,7 @@ ${e}[Error list was empty]`,t.trim()}return nx(r,e)}sn.formatters.e=r=>r==null?"
|
|
|
18
18
|
HTTP/1.1 %d %s
|
|
19
19
|
%s
|
|
20
20
|
`,d.status,d.statusText,[...d.headers.entries()].map(([m,w])=>`${m}: ${w}`).join(`
|
|
21
|
-
`)),!d.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, recieved ${d.status} ${d.statusText}`);let h=await hT(d,n,{signal:s.signal,log:this.log});return this.#s++,h}),this.#i.set(i,c)}return await c}catch(c){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} - ${c.message}`))}finally{t?.removeEventListener("abort",a),this.#i.delete(i)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#s/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#i.size}}toString(){return`TrustlessGateway(${this.url})`}};var Ow=class extends Ac{routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??O2,this.allowLocal=t.allowLocal??R2,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*k2(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(on(e))return;let n=kw(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(n.length===0)return;let o=ea(n[0]);return new Fu(o,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function mT(r,e){return new Ow(r,e)}var D2=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??O2,this.allowLocal=t.allowLocal??R2,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of k2(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 i=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s - %e",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,i),i instanceof Error?n.push(i):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 mT({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var O2=!1,R2=!1,pT=2097152;function Rw(r={}){return e=>new D2(e,r)}async function*N2(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 sj=nr(L2(),1);var No=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},B2=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},$u=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},M2=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},U2=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},F2=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Th=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var un;(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=()=>kt(t)})(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=Ie((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;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=>Te(o,r.codec()),r.decode=(o,i)=>Ae(o,r.codec(),i)})(un||(un={}));var tj=zn("ipns:utils"),gT=B("/ipns/");var rj=0,nj=18;function yT(r){let e;if(r.pubKey!=null)try{e=Kt(r.pubKey)}catch(t){throw tj.error(t),t}if(e!=null)return e}function wT(r){let e=B("ipns-signature:");return gt([e,r])}function Ih(r){return"signatureV1"in r?un.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}):un.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function ai(r){let e=un.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 No("Missing data or signatureV2");let t=bT(e.data),n=oj(t.Value),o=j(t.Validity);if(e.value!=null&&e.signatureV1!=null)return ij(e),{value:n,validityType:un.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:un.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 Ch(r){return gt([gT,r.bytes])}function ju(r){let e=lt(r.slice(gT.length));if(!$2(e,rj)&&!$2(e,nj))throw new Cs("Multihash in IPNS key was not identity or sha2-256");return e}function bT(r){let e=Nn(r);if(e.ValidityType===0)e.ValidityType=un.ValidityType.EOL;else throw new $u("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 oj(r){let e=j(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${he.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${he.parse(e).toV1().toString()}`}catch{}throw new U2("Value must be a valid content path starting with /")}function ij(r){if(r.data==null)throw new F2("Record data is missing");let e=bT(r.data);if(!we(e.Value,r.value??new Uint8Array(0)))throw new No('Field "value" did not match between protobuf and CBOR');if(!we(e.Validity,r.validity??new Uint8Array(0)))throw new No('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new No('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new No('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new No('Field "ttl" did not match between protobuf and CBOR')}function $2(r,e){return r.code===e}var zle=zn("ipns"),Gle=300*1e9,aj="/ipns/",Xle=aj.length;var vT=nr(L2(),1);var j2=zn("ipns:validator"),cj=1024*10;async function lj(r,e){let t=ai(e),n;try{let o=wT(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw j2.error("record signature verification failed"),new No("Record signature verification failed");if(t.validityType===un.ValidityType.EOL){if(vT.default.fromString(t.validity).toDate().getTime()<Date.now())throw j2.error("record has expired"),new B2("record has expired")}else if(t.validityType!=null)throw j2.error("the validity type is unsupported"),new $u("The validity type is unsupported");j2("ipns record for %s is valid",t.value)}async function K2(r,e){if(e.byteLength>cj)throw new M2("The record is too large");let t=ju(r),n;$2(t,0)&&(n=Um(t));let o=ai(e),i=yT(o)??n;if(i==null)throw new Th("Could not extract public key from IPNS record or routing key");let s=Ch(i.toMultihash());if(!we(s,r))throw new Th("Embedded public key did not match routing key");await lj(i,e)}var V2=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Ph(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let i of r){if(typeof i=="string"&&(i=new TextEncoder().encode(i)),Hl(i)&&(i=i.subarray()),o+=n.decode(i,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new V2("Incoming message too long");let s=o.split(t);o=s.pop()??"";for(let a=0;a<s.length;a++)yield JSON.parse(s[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Ku=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},Lo=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function uj(r){return r[Symbol.asyncIterator]!=null}function fj(r){if(uj(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var xT=fj;var ET=B("/ipns/");function ST(r){return we(r.subarray(0,ET.byteLength),ET)}var H2=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){try{yield*to(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof Xe)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!ST(e))return;let o=ju(e),i=he.createV1(114,o),s=ai(t);await this.client.putIPNS(i,s,n)}async get(e,t){if(!ST(e))throw new Xe("Not found");let n=ju(e),o=he.createV1(114,n);try{let i=await this.client.getIPNS(o,t);return Ih(i)}catch(i){throw i.name==="BadResponseError"?new Xe("Not found"):i}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},q2=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await xT(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new Xe("Not found")}async*getClosestPeers(e,t={}){}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};var W2={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},z2=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 za({concurrency:t.concurrentRequests??W2.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??W2.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new H2(this),this.peerRouting=new q2(this),this.cacheName=t.cacheName??W2.cacheName,this.cacheTTL=t.cacheTTL??W2.cacheTTL}get[ki](){return this.contentRouting}get[Ri](){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=De([this.shutDownController.signal,n,t.signal]);let i=Ve(),s=Ve(),a=0;this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l={headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o},f=await this.#r(c.toString(),l);if(!f.ok){if(f.status===404)return;throw f.status===422?new Ku("Request does not conform to schema or semantic constraints"):new Lo(`Unexpected status code: ${f.status}`)}let u=f.headers.get("Content-Type");if(u==null)throw new Lo("No Content-Type header received");if(f.body==null){if(u!=="application/x-ndjson")throw new Lo("Routing response had no body");return}if(u.startsWith("application/json")){let h=(await f.json()).Providers??[];for(let m of h){let w=this.#e(m);w!=null&&(a++,yield w)}}else if(u.includes("application/x-ndjson"))for await(let d of Ph(N2(f.body))){let h=this.#e(d);h!=null&&(a++,yield h)}else throw new Lo(`Unsupported Content-Type: ${u}`)}finally{o.clear(),s.resolve(),this.log("getProviders finished found %d providers for %c",a,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=De([this.shutDownController.signal,n,t.signal]);let i=Ve(),s=Ve();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.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 Ku("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Lo("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 m=this.#e(h);m!=null&&(yield m)}}else for await(let u of Ph(N2(l.body))){let d=this.#e(u);d!=null&&(yield d)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),s.resolve(),this.log("getPeers finished: %c",e)}}async getIPNS(e,t={}){this.log("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=De([this.shutDownController.signal,n,t.signal]);let i=Ve(),s=Ve();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await i.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 Xe("No matching records found");if(l.status===422)throw new Ku("Request does not conform to schema or semantic constraints");if(!l.ok)throw new Lo(`Unexpected status code: ${l.status}`);let f=l.headers.get("Content-Type");if(f==null||!f.includes("application/vnd.ipfs.ipns-record"))throw new Xe("No matching records found");if(l.body==null)throw new Lo("GET ipns response had no body");let u=await l.arrayBuffer(),d=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await K2(Ch(e.multihash),d),ai(d)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),s.resolve(),this.log("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=De([this.shutDownController.signal,o,n.signal]);let s=Ve(),a=Ve();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let l=Ih(t),f={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i},u=await this.#r(c,f);if(this.log("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new Lo("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{i.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(ie)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:yt(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),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let i=this.inFlightRequests.get(o);if(i!=null){let c=await i;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(e,t);let s=fetch(e,t).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),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,s),await s}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,i]of n.entries())this.log("%s: %s",o,i)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function _T(r,e={}){return new z2({logger:Qo()},{...e,url:new URL(r)})}function Nw(){return{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var AT="[a-fA-F\\d:]",ta=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${AT})|(?<=${AT})(?=\\s|$))`:"",Bo="(?: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}",Gt="[a-fA-F\\d]{1,4}",G2=`
|
|
21
|
+
`)),!d.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, recieved ${d.status} ${d.statusText}`);let h=await hT(d,n,{signal:s.signal,log:this.log});return this.#a++,h}),this.#c.set(i,c)}return await c}catch(c){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} - ${c.message}`))}finally{t?.removeEventListener("abort",a),this.#c.delete(i)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#a/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#a,pendingResponses:this.#c.size}}toString(){return`TrustlessGateway(${this.url})`}};var Ow=class extends Ac{routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??O2,this.allowLocal=t.allowLocal??R2,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*k2(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(on(e))return;let n=kw(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(n.length===0)return;let o=ea(n[0]);return new Fu(o,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function mT(r,e){return new Ow(r,e)}var D2=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??O2,this.allowLocal=t.allowLocal??R2,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of k2(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 i=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s - %e",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,i),i instanceof Error?n.push(i):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 mT({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var O2=!1,R2=!1,pT=2097152;function Rw(r={}){return e=>new D2(e,r)}async function*N2(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 sj=nr(L2(),1);var No=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},B2=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},$u=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},M2=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},U2=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},F2=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Th=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var un;(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=()=>kt(t)})(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=Ie((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;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=>Te(o,r.codec()),r.decode=(o,i)=>Ae(o,r.codec(),i)})(un||(un={}));var tj=zn("ipns:utils"),gT=B("/ipns/");var rj=0,nj=18;function yT(r){let e;if(r.pubKey!=null)try{e=Kt(r.pubKey)}catch(t){throw tj.error(t),t}if(e!=null)return e}function wT(r){let e=B("ipns-signature:");return gt([e,r])}function Ih(r){return"signatureV1"in r?un.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}):un.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function ai(r){let e=un.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 No("Missing data or signatureV2");let t=bT(e.data),n=oj(t.Value),o=j(t.Validity);if(e.value!=null&&e.signatureV1!=null)return ij(e),{value:n,validityType:un.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:un.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 Ch(r){return gt([gT,r.bytes])}function ju(r){let e=lt(r.slice(gT.length));if(!$2(e,rj)&&!$2(e,nj))throw new Cs("Multihash in IPNS key was not identity or sha2-256");return e}function bT(r){let e=Nn(r);if(e.ValidityType===0)e.ValidityType=un.ValidityType.EOL;else throw new $u("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 oj(r){let e=j(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${he.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${he.parse(e).toV1().toString()}`}catch{}throw new U2("Value must be a valid content path starting with /")}function ij(r){if(r.data==null)throw new F2("Record data is missing");let e=bT(r.data);if(!we(e.Value,r.value??new Uint8Array(0)))throw new No('Field "value" did not match between protobuf and CBOR');if(!we(e.Validity,r.validity??new Uint8Array(0)))throw new No('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new No('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new No('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new No('Field "ttl" did not match between protobuf and CBOR')}function $2(r,e){return r.code===e}var zle=zn("ipns"),Gle=300*1e9,aj="/ipns/",Xle=aj.length;var vT=nr(L2(),1);var j2=zn("ipns:validator"),cj=1024*10;async function lj(r,e){let t=ai(e),n;try{let o=wT(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw j2.error("record signature verification failed"),new No("Record signature verification failed");if(t.validityType===un.ValidityType.EOL){if(vT.default.fromString(t.validity).toDate().getTime()<Date.now())throw j2.error("record has expired"),new B2("record has expired")}else if(t.validityType!=null)throw j2.error("the validity type is unsupported"),new $u("The validity type is unsupported");j2("ipns record for %s is valid",t.value)}async function K2(r,e){if(e.byteLength>cj)throw new M2("The record is too large");let t=ju(r),n;$2(t,0)&&(n=Um(t));let o=ai(e),i=yT(o)??n;if(i==null)throw new Th("Could not extract public key from IPNS record or routing key");let s=Ch(i.toMultihash());if(!we(s,r))throw new Th("Embedded public key did not match routing key");await lj(i,e)}var V2=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Ph(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let i of r){if(typeof i=="string"&&(i=new TextEncoder().encode(i)),Hl(i)&&(i=i.subarray()),o+=n.decode(i,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new V2("Incoming message too long");let s=o.split(t);o=s.pop()??"";for(let a=0;a<s.length;a++)yield JSON.parse(s[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Ku=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},Lo=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function uj(r){return r[Symbol.asyncIterator]!=null}function fj(r){if(uj(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var xT=fj;var ET=B("/ipns/");function ST(r){return we(r.subarray(0,ET.byteLength),ET)}var H2=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){try{yield*to(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof Xe)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!ST(e))return;let o=ju(e),i=he.createV1(114,o),s=ai(t);await this.client.putIPNS(i,s,n)}async get(e,t){if(!ST(e))throw new Xe("Not found");let n=ju(e),o=he.createV1(114,n);try{let i=await this.client.getIPNS(o,t);return Ih(i)}catch(i){throw i.name==="BadResponseError"?new Xe("Not found"):i}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},q2=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await xT(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new Xe("Not found")}async*getClosestPeers(e,t={}){}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};var W2={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},z2=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 za({concurrency:t.concurrentRequests??W2.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??W2.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new H2(this),this.peerRouting=new q2(this),this.cacheName=t.cacheName??W2.cacheName,this.cacheTTL=t.cacheTTL??W2.cacheTTL}get[ki](){return this.contentRouting}get[Ri](){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=De([this.shutDownController.signal,n,t.signal]);let i=Ve(),s=Ve(),a=0;this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l={headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o},f=await this.#r(c.toString(),l);if(!f.ok){if(f.status===404)return;throw f.status===422?new Ku("Request does not conform to schema or semantic constraints"):new Lo(`Unexpected status code: ${f.status}`)}let u=f.headers.get("Content-Type");if(u==null)throw new Lo("No Content-Type header received");if(f.body==null){if(u!=="application/x-ndjson")throw new Lo("Routing response had no body");return}if(u.startsWith("application/json")){let h=(await f.json()).Providers??[];for(let m of h){let w=this.#e(m);w!=null&&(a++,yield w)}}else if(u.includes("application/x-ndjson"))for await(let d of Ph(N2(f.body))){let h=this.#e(d);h!=null&&(a++,yield h)}else throw new Lo(`Unsupported Content-Type: ${u}`)}finally{o.clear(),s.resolve(),this.log("getProviders finished found %d providers for %c",a,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=De([this.shutDownController.signal,n,t.signal]);let i=Ve(),s=Ve();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.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 Ku("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Lo("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 m=this.#e(h);m!=null&&(yield m)}}else for await(let u of Ph(N2(l.body))){let d=this.#e(u);d!=null&&(yield d)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),s.resolve(),this.log("getPeers finished: %c",e)}}async getIPNS(e,t={}){this.log("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=De([this.shutDownController.signal,n,t.signal]);let i=Ve(),s=Ve();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await i.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 Xe("No matching records found");if(l.status===422)throw new Ku("Request does not conform to schema or semantic constraints");if(!l.ok)throw new Lo(`Unexpected status code: ${l.status}`);let f=l.headers.get("Content-Type");if(f==null||!f.includes("application/vnd.ipfs.ipns-record"))throw new Xe("No matching records found");if(l.body==null)throw new Lo("GET ipns response had no body");let u=await l.arrayBuffer(),d=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await K2(Ch(e.multihash),d),ai(d)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),s.resolve(),this.log("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=De([this.shutDownController.signal,o,n.signal]);let s=Ve(),a=Ve();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let l=Ih(t),f={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i},u=await this.#r(c,f);if(this.log("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new Lo("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{i.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(ie)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:yt(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),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let i=this.inFlightRequests.get(o);if(i!=null){let c=await i;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(e,t);let s=fetch(e,t).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),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,s),await s}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,i]of n.entries())this.log("%s: %s",o,i)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function _T(r,e={}){return new z2({logger:Qo()},{...e,url:new URL(r)})}function Nw(){return{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var AT="[a-fA-F\\d:]",ta=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${AT})|(?<=${AT})(?=\\s|$))`:"",Bo="(?: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}",Gt="[a-fA-F\\d]{1,4}",G2=`
|
|
22
22
|
(?:
|
|
23
23
|
(?:${Gt}:){7}(?:${Gt}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
24
24
|
(?:${Gt}:){6}(?:${Bo}|:${Gt}|:)| // 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
|
|
@@ -107,7 +107,7 @@ a=end-of-candidates
|
|
|
107
107
|
`;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
108
108
|
a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
109
109
|
a=ice-pwd:`+e+t)}catch{}return r}var Bv=B("libp2p-webrtc-noise:");function rN(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=B(n,"hex"),i=Wr(St.code,o),s=Dv.decode(Nv(e)),a=Bv.byteLength+i.bytes.byteLength+s.byteLength;return t==="server"?gt([Bv,s,i.bytes],a):gt([Bv,i.bytes,s],a)}var zW=j3?"iceconnectionstatechange":"connectionstatechange";function GW(r,e){return r.role==="server"}async function nN(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let u=await r.createOffer();n.log.trace("client created local offer %s",u.sdp);let d=Lv(u,t);n.log.trace("client setting local offer %s",d.sdp),await r.setLocalDescription(d);let h=JD(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let u=eN(n.remoteAddr,t);n.log.trace("server setting client %s %s",u.type,u.sdp),await r.setRemoteDescription(u),n.log.trace("server creating local answer");let d=await r.createAnswer();n.log.trace("server created local answer");let h=Lv(d,t);n.log.trace("server setting local description %s",d.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await hs(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),GW(n,r)){let u=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(ZD(u))}let i=QD(r.localDescription?.sdp);if(i==null)throw new ga("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let s=rN(i,n.remoteAddr,n.role),a=py({prologueBytes:s})(n),c=Op({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=Rp({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener(zW,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(u=>{n.log.error("error closing connection - %e",u),l.abort(u)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let u=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let f=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${f.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:f.remotePeer,muxerFactory:e,signal:n.signal})}catch(i){throw o.close(),r.close(),i}}async function oN(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,i=new RTCPeerConnection({...o??{},certificates:[n]}),s=new ma({peerConnection:i,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:i,muxerFactory:s}}async function iN(r){let e=await Fm(r),t=await crypto.subtle.exportKey("pkcs8",e.privateKey);return["-----BEGIN PRIVATE KEY-----",...j(new Uint8Array(t),"base64pad").split(/(.{64})/).filter(Boolean),"-----END PRIVATE KEY-----"].join(`
|
|
110
|
-
`)}var r6=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new _e,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new P("Certificate renewal threshold must be less than certificate lifespan");e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Os]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[qe]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=yt(o));let i=mO(),{peerConnection:s,muxerFactory:a}=await oN("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await nN(s,a,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw s.close(),c}}createListener(e){if(this.certificate==null)throw new _n;return new t6(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(_h.exactMatch)}dialFilter(e){return this.listenFilter(e)}async getCertificate(e){if(XW(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:o}=await this.loadOrCreateCertificate(t,e);return{privateKey:await iN(t),pem:n,certhash:o}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??iO,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new Xe;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await uu("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,o=new ht(this.init.certificateDatastoreKey??oO),i=await Fm(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new Xe;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(o,i)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(o,i)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??Mb)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:qa.encode((await St.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),o=new td(n),i=o.notAfter.getTime()-(this.init.certificateRenewalThreshold??Mb);if(Date.now()>i)throw this.log("stored TLS certificate has expired"),new Xe;this.log("loaded certificate, expires in %d ms",i);let s=await o.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!we(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new Xe;return this.log("loaded certificate, expiry time is %o",i),o}async createCertificate(e,t){let n=new Date,o=new Date(Date.now()+(this.init.certificateLifespan??sO));n.setMilliseconds(0),o.setMilliseconds(0);let i=await e6.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:o,keys:t,extensions:[new Zf(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,B(i.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),i}getKeychain(){try{return this.components.keychain}catch{}}};function XW(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function sN(r){return e=>new r6(e,r)}function aN(r){return e=>new Y3(e,r)}var Mv=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Uv=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},cN=r=>globalThis.DOMException===void 0?new Uv(r):new DOMException(r),lN=r=>{let e=r.reason===void 0?cN("This operation was aborted."):r.reason;return e instanceof Error?e:cN(e)};function Fv(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(lN(h)),a=()=>{u(lN(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let d=new Mv;s=i.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?u(o):(d.message=o??`Promise timed out after ${t} milliseconds`,u(d))},t),(async()=>{try{f(await r)}catch(h){u(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},l}var YW=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function QW(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=YW(r),u=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(w){n(),s(w);return}c.push(m),t.count===c.length&&(n(),i(c))},d=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)l(h,u);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=Fv(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function uN(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=QW(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function fN(){throw new Error("WebSocket Servers can not be created in the browser!")}var ZW=1024*1024*4,JW=10,$v=class extends Hs{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??ZW,this.checkBufferedAmountTask=Pu(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??JW),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=B(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(n);let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function dN(r){return new $v(r)}var jv=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Os]=!0;[Symbol.toStringTag]="@libp2p/websockets";[qe]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=dN({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=ea(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new oe("websockets:open-connection")),await uN(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Ll(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return fN({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>Ji.exactMatch(t)||kc.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function hN(r={}){return e=>new jv(e,r)}var Kv=nr(L2(),1);function pN(r,e){let t=e.map((n,o)=>({record:ai(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===un.ValidityType.EOL&&o.record.validityType===un.ValidityType.EOL){let a=Kv.default.fromString(n.record.validity).toDate(),c=Kv.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var mN="6.0.13",gN="helia";var yN={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function n6(r={}){let e=`${gN}/${mN} ${Ug()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[lP(),aN(),sN(),hN()],connectionEncrypters:[py()],streamMuxers:[zC(),Hk()],peerDiscovery:[ZC(yN)],services:{autoNAT:QC(),dcutr:dP(),delegatedRouting:()=>_T("https://delegated-ipfs.dev",Nw()),dht:Fk({clientMode:!0,validators:{ipns:K2},selectors:{ipns:pN}}),identify:nk(),identifyPush:ok(),keychain:ay(r.keychain),ping:Zk(),http:QP()}}}async function wN(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await A7(r.datastore,r.keychain));let t=n6(e);return t.datastore=t.datastore??r.datastore,await yI({...t,...e,start:!1})}async function Vv(r={}){let e=r.datastore??new Oc,t=r.blockstore??new kh,n;return wI(r.libp2p)?n=r.libp2p:n=await wN({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Rw(),xw()],routers:r.routers??[qw(n),Vw()],metrics:n.metrics}}async function ez(r={}){let e=await Vv(r),t=new d2(e);return e.start!==!1&&await t.start(),t}return DN(tz);})();
|
|
110
|
+
`)}var r6=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new _e,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new P("Certificate renewal threshold must be less than certificate lifespan");e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Os]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[qe]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=yt(o));let i=mO(),{peerConnection:s,muxerFactory:a}=await oN("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await nN(s,a,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw s.close(),c}}createListener(e){if(this.certificate==null)throw new _n;return new t6(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(_h.exactMatch)}dialFilter(e){return this.listenFilter(e)}async getCertificate(e){if(XW(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:o}=await this.loadOrCreateCertificate(t,e);return{privateKey:await iN(t),pem:n,certhash:o}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??iO,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new Xe;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await uu("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,o=new ht(this.init.certificateDatastoreKey??oO),i=await Fm(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new Xe;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(o,i)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(o,i)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??Mb)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:qa.encode((await St.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),o=new td(n),i=o.notAfter.getTime()-(this.init.certificateRenewalThreshold??Mb);if(Date.now()>i)throw this.log("stored TLS certificate has expired"),new Xe;this.log("loaded certificate, expires in %d ms",i);let s=await o.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!we(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new Xe;return this.log("loaded certificate, expiry time is %o",i),o}async createCertificate(e,t){let n=new Date,o=new Date(Date.now()+(this.init.certificateLifespan??sO));n.setMilliseconds(0),o.setMilliseconds(0);let i=await e6.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:o,keys:t,extensions:[new Zf(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,B(i.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),i}getKeychain(){try{return this.components.keychain}catch{}}};function XW(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function sN(r){return e=>new r6(e,r)}function aN(r){return e=>new Y3(e,r)}var Mv=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Uv=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},cN=r=>globalThis.DOMException===void 0?new Uv(r):new DOMException(r),lN=r=>{let e=r.reason===void 0?cN("This operation was aborted."):r.reason;return e instanceof Error?e:cN(e)};function Fv(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(lN(h)),a=()=>{u(lN(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let d=new Mv;s=i.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?u(o):(d.message=o??`Promise timed out after ${t} milliseconds`,u(d))},t),(async()=>{try{f(await r)}catch(h){u(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},l}var YW=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function QW(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=YW(r),u=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(w){n(),s(w);return}c.push(m),t.count===c.length&&(n(),i(c))},d=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)l(h,u);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=Fv(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function uN(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=QW(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function fN(){throw new Error("WebSocket Servers can not be created in the browser!")}var ZW=1024*1024*4,JW=10,$v=class extends Hs{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??ZW,this.checkBufferedAmountTask=Pu(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??JW),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=B(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(n);let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function dN(r){return new $v(r)}var jv=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Os]=!0;[Symbol.toStringTag]="@libp2p/websockets";[qe]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=dN({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=ea(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new oe("websockets:open-connection")),await uN(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Ll(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return fN({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>Ji.exactMatch(t)||kc.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function hN(r={}){return e=>new jv(e,r)}var Kv=nr(L2(),1);function pN(r,e){let t=e.map((n,o)=>({record:ai(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===un.ValidityType.EOL&&o.record.validityType===un.ValidityType.EOL){let a=Kv.default.fromString(n.record.validity).toDate(),c=Kv.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var mN="6.0.14-4e19769a",gN="helia";var yN={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function n6(r={}){let e=`${gN}/${mN} ${Ug()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[lP(),aN(),sN(),hN()],connectionEncrypters:[py()],streamMuxers:[zC(),Hk()],peerDiscovery:[ZC(yN)],services:{autoNAT:QC(),dcutr:dP(),delegatedRouting:()=>_T("https://delegated-ipfs.dev",Nw()),dht:Fk({clientMode:!0,validators:{ipns:K2},selectors:{ipns:pN}}),identify:nk(),identifyPush:ok(),keychain:ay(r.keychain),ping:Zk(),http:QP()}}}async function wN(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await A7(r.datastore,r.keychain));let t=n6(e);return t.datastore=t.datastore??r.datastore,await yI({...t,...e,start:!1})}async function Vv(r={}){let e=r.datastore??new Oc,t=r.blockstore??new kh,n;return wI(r.libp2p)?n=r.libp2p:n=await wN({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Rw(),xw()],routers:r.routers??[qw(n),Vw()],metrics:n.metrics}}async function ez(r={}){let e=await Vv(r),t=new d2(e);return e.start!==!1&&await t.start(),t}return DN(tz);})();
|
|
111
111
|
/*! Bundled license information:
|
|
112
112
|
|
|
113
113
|
pvtsutils/build/index.js:
|