@helia/http 4.0.0-3a1dd561 → 4.0.0-cee53d7d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,23 +1,23 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaHttp = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaHttp=(()=>{var rs=Object.create;var fe=Object.defineProperty;var ns=Object.getOwnPropertyDescriptor;var os=Object.getOwnPropertyNames;var ss=Object.getPrototypeOf,is=Object.prototype.hasOwnProperty;var er=(r,t)=>()=>{try{return t||r((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},F=(r,t)=>{for(var e in t)fe(r,e,{get:t[e],enumerable:!0})},Sn=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of os(t))!is.call(r,o)&&o!==e&&fe(r,o,{get:()=>t[o],enumerable:!(n=ns(t,o))||n.enumerable});return r};var as=(r,t,e)=>(e=r!=null?rs(ss(r)):{},Sn(t||!r||!r.__esModule?fe(e,"default",{value:r,enumerable:!0}):e,r)),cs=r=>Sn(fe({},"__esModule",{value:!0}),r);var Ar=er(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Netmask4Impl=void 0;Nt.ip2long=kt;Nt.long2ip=Y;function Y(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[t,e,n,o].join(".")}var Ti=48,Ai=97,Di=65;function Li(r){let t=0,e=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,e=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,e=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)t=t*e+(r.charCodeAt(o)-Ti)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-Ai)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-Di)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[t,o]}function kt(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=Li(r);r=r.substring(o),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var Tr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let o=t.split("/",2);t=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=kt(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(kt(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Y(this.netLong),this.mask=Y(this.maskLong),this.hostmask=Y(~this.maskLong),this.first=this.bitmask<=30?Y(this.netLong+1):this.base,this.last=this.bitmask<=30?Y(this.netLong+this.size-2):Y(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Y(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(kt(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Y(this.netLong+this.size*t),this.mask)}forEach(t){let e=kt(this.first),n=kt(this.last),o=0;for(;e<=n;)t(Y(e),e,o),o++,e++}toString(){return this.base+"/"+this.bitmask}};Nt.Netmask4Impl=Tr});var eo=er(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.Netmask6Impl=void 0;Rt.ip6bigint=Lr;Rt.bigint2ip6=yt;var ki=Ar(),Dr=(1n<<128n)-1n;function Lr(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),o=(0,ki.ip2long)(n),s=r.substring(0,e+1)+"0:0";return to(s)&~0xffffffffn|BigInt(o)}return to(r)}function to(r){let t=r.indexOf("::"),e;if(t!==-1){let o=r.substring(0,t),s=r.substring(t+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let o=0;o<8;o++){let s=e[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function yt(r){if(r<0n||r>Dr)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)t[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(e=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(e=o,n=s),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var kr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let o=t.indexOf("/");o!==-1?(n=parseInt(t.substring(o+1),10),t=t.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=Dr>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Lr(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=yt(this.netBigint),this.mask=yt(this.maskBigint),this.hostmask=yt(~this.maskBigint&Dr),this.first=this.base,this.last=yt(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(Lr(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(yt(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;e<=o;)t(yt(e),Number(e),s),s++,e++}toString(){return this.base+"/"+this.bitmask}};Rt.Netmask6Impl=kr});var ro=er(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.long2ip=ft.ip2long=ft.Netmask=void 0;var ve=Ar();Object.defineProperty(ft,"ip2long",{enumerable:!0,get:function(){return ve.ip2long}});Object.defineProperty(ft,"long2ip",{enumerable:!0,get:function(){return ve.long2ip}});var Ni=eo(),Nr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new Ni.Netmask6Impl(t,e):this._impl=new ve.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof ve.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};ft.Netmask=Nr});var ic={};F(ic,{withHTTP:()=>sc});var V=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var _t=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var et=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}};function ls(r){return typeof r?.handleEvent=="function"}function us(r){return(r!==!0&&r!==!1&&r?.once)??!1}var It=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){let o=us(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}ls(e)?e.handleEvent(i):e(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:o})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function B(r=0){return new Uint8Array(r)}function J(r=0){return new Uint8Array(r)}function fs(r){return r?.buffer instanceof ArrayBuffer}function rr(r){if(fs(r))return r;let t=r.slice();return new Uint8Array(t.buffer,0,t.byteLength)}function rt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=J(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return rr(e)}function nt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Cn=Symbol.for("@achingbrain/uint8arraylist");function Pn(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function St(r){return!!r?.[Cn]}var he=class r{bufs;length;[Cn]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(St(n)){e+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(St(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Pn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Pn(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(St(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return rt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:rt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=n,s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,f=e>a&&e<=c;if(l&&f){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!St(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let h=e;h<=c;h+=f){f=0;for(let u=l;u>=0;u--){let p=this.get(h+u);if(n[u]!==p){f=Math.max(1,u-a[p]);break}}if(f===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=J(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=B(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=B(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=B(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=J(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=B(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=B(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=B(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=B(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=B(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!nt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var ar={};F(ar,{base10:()=>ys});var xc=new Uint8Array(0);function Tn(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ot(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return pt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return pt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function An(r){return new TextEncoder().encode(r)}function Dn(r){return new TextDecoder().decode(r)}function hs(r){return r?.buffer instanceof ArrayBuffer}function pt(r){return hs(r)?r:r.slice()}function ds(r,t,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,e){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),l!==a&&(n[l]=s)}}var f=r.length,h=r.charAt(0),u=Math.log(f)/Math.log(256),p=Math.log(256)/Math.log(f);function S(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var C=0,N=0,O=0,U=g.length;O!==U&&g[O]===0;)O++,C++;for(var X=(U-O)*p+1>>>0,$=new Uint8Array(X);O!==U;){for(var K=g[O],ct=0,q=X-1;(K!==0||ct<N)&&q!==-1;q--,ct++)K+=256*$[q]>>>0,$[q]=K%f>>>0,K=K/f>>>0;if(K!==0)throw new Error("Non-zero carry");N=ct,O++}for(var tt=X-N;tt!==X&&$[tt]===0;)tt++;for(var ue=h.repeat(C);tt<X;++tt)ue+=r.charAt($[tt]);return ue}function R(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var C=0;if(g[C]!==" "){for(var N=0,O=0;g[C]===h;)N++,C++;for(var U=(g.length-C)*u+1>>>0,X=new Uint8Array(U);g[C];){var $=n[g.charCodeAt(C)];if($===255)return;for(var K=0,ct=U-1;($!==0||K<O)&&ct!==-1;ct--,K++)$+=f*X[ct]>>>0,X[ct]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");O=K,C++}if(g[C]!==" "){for(var q=U-O;q!==U&&X[q]===0;)q++;for(var tt=new Uint8Array(N+(U-q)),ue=N;q!==U;)tt[ue++]=X[q++];return tt}}}function y(g){var C=R(g);if(C)return C;throw new Error(`Non-${t} character`)}return{encode:S,decodeUnsafe:R,decode:y}}var ps=ds,ms=ps,kn=ms;var nr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},or=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Nn(this,t)}},sr=class{decoders;constructor(t){this.decoders=t}or(t){return Nn(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Nn(r,t){return new sr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ir=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new nr(t,e,n),this.decoder=new or(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Pt({name:r,prefix:t,encode:e,decode:n}){return new ir(r,t,e,n)}function lt({name:r,prefix:t,alphabet:e,caseInsensitive:n=!1}){let{encode:o,decode:s}=kn(e,r,n);return Pt({prefix:t,name:r,encode:o,decode:i=>ot(s(i))})}function gs(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let f=t[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|f,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function ws(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function bs(r,t){let e={};for(let n=0;n<r.length;++n)if(e[r[n]]=n,t){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(e[o]=n),s!==r[n]&&(e[s]=n)}return e}function _({name:r,prefix:t,bitsPerChar:e,alphabet:n,caseInsensitive:o=!1}){let s=bs(n,o);return Pt({prefix:t,name:r,encode(i){return ws(i,n,e)},decode(i){return gs(i,s,e,r)}})}var ys=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var cr={};F(cr,{base16:()=>xs,base16upper:()=>vs});var xs=_({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),vs=_({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var lr={};F(lr,{base2:()=>Es});var Es=_({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ur={};F(ur,{base256emoji:()=>Cs});var Rn=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}"),_s=Rn.reduce((r,t,e)=>(r[e]=t,r),[]),Is=Rn.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Ss(r){return r.reduce((t,e)=>(t+=_s[e],t),"")}function Ps(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Is[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Cs=Pt({prefix:"\u{1F680}",name:"base256emoji",encode:Ss,decode:Ps});var fr={};F(fr,{base32:()=>ut,base32hex:()=>Ls,base32hexpad:()=>Ns,base32hexpadupper:()=>Rs,base32hexupper:()=>ks,base32pad:()=>As,base32padupper:()=>Ds,base32upper:()=>Ts,base32z:()=>Fs});var ut=_({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Ts=_({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),As=_({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Ds=_({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Ls=_({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),ks=_({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Ns=_({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Rs=_({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Fs=_({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var hr={};F(hr,{base36:()=>Wt,base36upper:()=>Os});var Wt=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Os=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var dr={};F(dr,{base58btc:()=>z,base58flickr:()=>Us});var z=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Us=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var mr={};F(mr,{base64:()=>Gt,base64pad:()=>$s,base64url:()=>pr,base64urlpad:()=>Bs});var Gt=_({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$s=_({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pr=_({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bs=_({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var gr={};F(gr,{base8:()=>zs});var zs=_({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var wr={};F(wr,{identity:()=>Ms});var Ms=Pt({prefix:"\0",name:"identity",encode:r=>Dn(r),decode:r=>An(r)});var Oc=new TextEncoder,Uc=new TextDecoder;var yr={};F(yr,{identity:()=>Kt});var js=Un,Fn=128,Hs=127,Ws=~Hs,Gs=Math.pow(2,31);function Un(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Gs;)t[e++]=r&255|Fn,r/=128;for(;r&Ws;)t[e++]=r&255|Fn,r>>>=7;return t[e]=r|0,Un.bytes=e-n+1,t}var Qs=br,Xs=128,On=127;function br(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw br.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&On)<<o:(i&On)*Math.pow(2,o),o+=7}while(i>=Xs);return br.bytes=s-n,e}var Ks=Math.pow(2,7),Js=Math.pow(2,14),Ys=Math.pow(2,21),Zs=Math.pow(2,28),ti=Math.pow(2,35),ei=Math.pow(2,42),ri=Math.pow(2,49),ni=Math.pow(2,56),oi=Math.pow(2,63),si=function(r){return r<Ks?1:r<Js?2:r<Ys?3:r<Zs?4:r<ti?5:r<ei?6:r<ri?7:r<ni?8:r<oi?9:10},ii={encode:js,decode:Qs,encodingLength:si},ai=ii,Qt=ai;function Xt(r,t=0){return[Qt.decode(r,t),Qt.decode.bytes]}function Ct(r,t,e=0){return Qt.encode(r,t,e),t}function Tt(r){return Qt.encodingLength(r)}function Dt(r,t){let e=t.byteLength,n=Tt(r),o=n+Tt(e),s=new Uint8Array(o+e);return Ct(r,s,0),Ct(e,s,n),s.set(t,o),new At(r,e,t,s)}function mt(r){let t=ot(r),[e,n]=Xt(t),[o,s]=Xt(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new At(e,o,i,t)}function $n(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Tn(r.bytes,e.bytes)}}var At=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=pt(n),this.bytes=pt(o)}};var Bn=0,ci="identity",zn=ot;function li(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Dt(Bn,zn(r))}var Kt={code:Bn,name:ci,encode:zn,digest:li};var Er={};F(Er,{sha256:()=>fi,sha512:()=>hi});var ui=20;function vr({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new xr(r,t,e,n,o)}var xr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??ui,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Mn(n,this.code,e?.truncate):n.then(o=>Mn(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Mn(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Dt(t,r)}function Vn(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var fi=vr({name:"sha2-256",code:18,encode:Vn("SHA-256")}),hi=vr({name:"sha2-512",code:19,encode:Vn("SHA-512")});function jn(r,t){let{bytes:e,version:n}=r;return n===0?pi(e,_r(r),t??z.encoder):mi(e,_r(r),t??ut.encoder)}var Hn=new WeakMap;function _r(r){let t=Hn.get(r);if(t==null){let e=new Map;return Hn.set(r,e),e}return t}var T=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=pt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Jt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==gi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Dt(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&$n(t.multihash,n.multihash)}toString(t){return jn(this,t)}toJSON(){return{"/":jn(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Wn(n,o,s.bytes))}else if(e[wi]===!0){let{version:n,multihash:o,code:s}=e,i=mt(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Jt)throw new Error(`Version 0 CID must use dag-pb (code: ${Jt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Wn(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Jt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ot(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new At(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,u]=Xt(t.subarray(e));return e+=u,h},o=n(),s=Jt;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,f=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(t,e){let[n,o]=di(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return _r(s).set(n,t),s}};function di(r,t){switch(r[0]){case"Q":{let e=t??z;return[z.prefix,e.decode(`${z.prefix}${r}`)]}case z.prefix:{let e=t??z;return[z.prefix,e.decode(r)]}case ut.prefix:{let e=t??ut;return[ut.prefix,e.decode(r)]}case Wt.prefix:{let e=t??Wt;return[Wt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function pi(r,t,e){let{prefix:n}=e;if(n!==z.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function mi(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Jt=112,gi=18;function Wn(r,t,e){let n=Tt(r),o=n+Tt(t),s=new Uint8Array(o+e.byteLength);return Ct(r,s,0),Ct(t,s,n),s.set(e,o),s}var wi=Symbol.for("@ipld/js-cid/CID");var Yt={...wr,...lr,...gr,...ar,...cr,...fr,...hr,...dr,...mr,...ur},sl={...Er,...yr};function Qn(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Gn=Qn("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ir=Qn("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=J(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),bi={utf8:Gn,"utf-8":Gn,hex:Yt.base16,latin1:Ir,ascii:Ir,binary:Ir,...Yt},pe=bi;function I(r,t="utf8"){let e=pe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}var Sr={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Xn={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Kn=new globalThis.TextEncoder;function yi(r,t){let e=Sr[t],n=Xn[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function xi(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Sr[t],o=Xn[t],s=r;for(;s.length>0;){let i=Kn.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Pr(r,{size:t=32,utf8Buffer:e}={}){if(!Sr[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return xi(r,t,e);r=Kn.encode(r)}return yi(r,t)}var Zt={hash:r=>Number(Pr(r,{size:32})),hashV:(r,t)=>vi(Zt.hash(r,t))};function vi(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),I(t,"base16")}var Cr=64,j=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Cr)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=B(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?nt(this.fp,t.fp):!1}};function wt(r,t){return Math.floor(Math.random()*(t-r))+r}var bt=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof j))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof j))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof j))throw new TypeError("Invalid Fingerprint");let e=wt(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof j))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Ei=500,te=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Zt,this.seed=t.seed??wt(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=I(t));let e=new j(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new bt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new bt(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[wt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new bt(this.bucketSize));for(let a=0;a<Ei;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new bt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=I(t));let e=new j(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=I(t));let e=new j(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},_i={1:.5,2:.84,4:.95,8:.98};function Ii(r=.001){return r>.002?2:r>1e-5?4:8}function Jn(r,t=.001){let e=Ii(t),n=_i[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Cr);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var me=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Zt,this.seed=t.seed??wt(0,Math.pow(2,10)),this.filterSeries=[new te({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=I(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new te({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=I(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=I(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function ge(r,t=.001,e){return new me({...Jn(r,t),...e??{}})}function Si(r){let t=r.getComponents(),e={},n=0;return t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n]?.name==="ip4"||t[n]?.name==="ip6"||t[n]?.name==="dns"||t[n]?.name==="dns4"||t[n]?.name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n]?.name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null?null:(t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e)}function we(r){let t=Si(r);if(t==null)throw new _t(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}var be=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let u=Number.parseInt(h,t);if(!Number.isNaN(u))return u});if(f===void 0)break;if(s*=t,s+=f,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Pi=45,Ci=15,ye=new be;function Yn(r){if(!(r.length>Ci))return ye.new(r).parseWith(()=>ye.readIPv4Addr())}function Zn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Pi))return ye.new(r).parseWith(()=>ye.readIPv6Addr())}function Lt(r){return!!Yn(r)}function xe(r){return!!Zn(r)}var no=as(ro(),1),Ri=["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"],Fi=Ri.map(r=>new no.Netmask(r));function Rr(r){for(let t of Fi)if(t.contains(r))return!0;return!1}function Oi(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ui(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Rr(o)}function $i(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Bi(r){let t=r.split(":"),e=t[t.length-1];return Rr(e)}function zi(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 oo(r){if(Lt(r))return Rr(r);if(Oi(r))return Ui(r);if($i(r))return Bi(r);if(xe(r))return zi(r)}function so(r){try{let t=we(r);switch(t.type){case"ip4":case"ip6":return oo(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}var Mi=Math.pow(2,7),qi=Math.pow(2,14),Vi=Math.pow(2,21),Fr=Math.pow(2,28),Or=Math.pow(2,35),Ur=Math.pow(2,42),$r=Math.pow(2,49),E=128,L=127;function Ft(r){if(r<Mi)return 1;if(r<qi)return 2;if(r<Vi)return 3;if(r<Fr)return 4;if(r<Or)return 5;if(r<Ur)return 6;if(r<$r)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Br(r,t,e=0){switch(Ft(r)){case 8:t[e++]=r&255|E,r/=128;case 7:t[e++]=r&255|E,r/=128;case 6:t[e++]=r&255|E,r/=128;case 5:t[e++]=r&255|E,r/=128;case 4:t[e++]=r&255|E,r>>>=7;case 3:t[e++]=r&255|E,r>>>=7;case 2:t[e++]=r&255|E,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function ji(r,t){let e=r[t],n=0;if(n+=e&L,e<E||(e=r[t+1],n+=(e&L)<<7,e<E)||(e=r[t+2],n+=(e&L)<<14,e<E)||(e=r[t+3],n+=(e&L)<<21,e<E)||(e=r[t+4],n+=(e&L)*Fr,e<E)||(e=r[t+5],n+=(e&L)*Or,e<E)||(e=r[t+6],n+=(e&L)*Ur,e<E)||(e=r[t+7],n+=(e&L)*$r,e<E))return n;throw new RangeError("Could not decode varint")}function Hi(r,t){let e=r.get(t),n=0;if(n+=e&L,e<E||(e=r.get(t+1),n+=(e&L)<<7,e<E)||(e=r.get(t+2),n+=(e&L)<<14,e<E)||(e=r.get(t+3),n+=(e&L)<<21,e<E)||(e=r.get(t+4),n+=(e&L)*Fr,e<E)||(e=r.get(t+5),n+=(e&L)*Or,e<E)||(e=r.get(t+6),n+=(e&L)*Ur,e<E)||(e=r.get(t+7),n+=(e&L)*$r,e<E))return n;throw new RangeError("Could not decode varint")}function zr(r,t=0){return r instanceof Uint8Array?ji(r,t):Hi(r,t)}function Gi(r){return r.buffer instanceof ArrayBuffer}function ee(r){return Gi(r)?r:r.slice()}function Z(r,t="utf8"){let e=pe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var D=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},st=class extends Error{static name="ValidationError";name="ValidationError"},Ee=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},_e=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function qr(r){return t=>Z(t,r)}function Vr(r){return t=>I(t,r)}function Ot(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function xt(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function io(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=I(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return rt([e,o],e.length+o.length)}function ao(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=ut.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return rt([e,o],e.length+o.length)}function jr(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=Z(t,"base32"),o=Ot(e);return`${n}:${o}`}var Hr=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new D("Invalid byte value in IP address");t[n]=o}),t},co=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Lt(e[n]),i;s&&(i=Hr(e[n]),e[n]=Z(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,Z(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new D("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},lo=function(r){if(r.byteLength!==4)throw new D("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},uo=function(r){if(r.byteLength!==16)throw new D("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new D(`Invalid IPv6 address "${e}"`)}};function fo(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new D(`Invalid IPv6 address "${r}"`)}}var Mr=Object.values(Yt).map(r=>r.decoder),Qi=(function(){let r=Mr[0].or(Mr[1]);return Mr.slice(2).forEach(t=>r=r.or(t)),r})();function ho(r){return Qi.decode(r)}function po(r){return t=>r.encoder.encode(t)}function Xi(r){if(parseInt(r).toString()!==r)throw new st("Value must be an integer")}function Ki(r){if(r<0)throw new st("Value must be a positive integer, or zero")}function Ji(r){return t=>{if(t>r)throw new st(`Value must be smaller than or equal to ${r}`)}}function Yi(...r){return t=>{for(let e of r)e(t)}}var re=Yi(Xi,Ki,Ji(65535));var A=-1,Wr=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new _e(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},it=new Wr,ha=[{code:4,name:"ip4",size:32,valueToBytes:Hr,bytesToValue:lo,validate:r=>{if(!Lt(r))throw new st(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:273,name:"udp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:33,name:"dccp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:41,name:"ip6",size:128,valueToBytes:co,bytesToValue:uo,stringToValue:fo,validate:r=>{if(!xe(r))throw new st(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:A},{code:43,name:"ipcidr",size:8,bytesToValue:qr("base10"),valueToBytes:Vr("base10")},{code:53,name:"dns",size:A},{code:54,name:"dns4",size:A},{code:55,name:"dns6",size:A},{code:56,name:"dnsaddr",size:A},{code:132,name:"sctp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:A,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:A,bytesToValue:qr("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Vr("base58btc")(r):T.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:jr,valueToBytes:io},{code:445,name:"onion3",size:296,bytesToValue:jr,valueToBytes:ao},{code:446,name:"garlic64",size:A},{code:447,name:"garlic32",size:A},{code:448,name:"tls"},{code:449,name:"sni",size:A},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:A,bytesToValue:po(pr),valueToBytes:ho},{code:480,name:"http"},{code:481,name:"http-path",size:A,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:A}];ha.forEach(r=>{it.addProtocol(r)});function mo(r){let t=[],e=0;for(;e<r.length;){let n=zr(r,e),o=it.getProtocol(n),s=Ft(n),i=da(o,r,e+s),a=0;i>0&&o.size===A&&(a=Ft(i));let c=s+a+i,l={code:n,name:o.name,bytes:ee(r.subarray(e,e+c))};if(i>0){let f=e+s+a,h=r.subarray(f,f+i);l.value=o.bytesToValue?.(h)??Z(h)}t.push(l),e+=c}return t}function go(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=it.getProtocol(n.code),s=Ft(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??I(n.value),a=i.byteLength,o.size===A&&(c=Ft(a)));let l=new Uint8Array(s+c+a),f=0;Br(n.code,l,f),f+=s,i!=null&&(o.size===A&&(Br(a,l,f),f+=c),l.set(i,f)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return rt(e,t)}function wo(r){if(r.charAt(0)!=="/")throw new D('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=it.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new D(`Component ${o} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new D(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new D("Incomplete multiaddr");return t}function bo(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=it.getProtocol(t.code);if(e==null)throw new D(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function da(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:zr(t,e)}var pa=Symbol.for("nodejs.util.inspect.custom"),on=Symbol.for("@multiformats/multiaddr");function ma(r){if(r==null&&(r="/"),yo(r))return r.getComponents();if(r instanceof Uint8Array)return mo(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),wo(r);if(Array.isArray(r))return r;throw new D("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ae=class r{[on]=!0;#t;#r;#e;constructor(t="/",e={}){this.#t=ma(t),e.validate!==!1&&ga(this)}get bytes(){return this.#e==null&&(this.#e=go(this.#t)),this.#e}toString(){return this.#r==null&&(this.#r=bo(this.#t)),this.#r}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Ee(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return nt(this.bytes,t.bytes)}[pa](){return`Multiaddr(${this.toString()})`}};function ga(r){r.getComponents().forEach(t=>{let e=it.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function yo(r){return!!r?.[on]}function Bt(r){return new Ae(r)}var x=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),d=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),xo=r=>({match:t=>r.match(t)===!1?t:!1}),m=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),k=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),w=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function v(...r){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var wa=d(421),af=v(wa),Le=d(54),ke=d(55),Ne=d(56),an=d(53),cf=v(Le,m(d(421))),lf=v(ke,m(d(421))),uf=v(Ne,m(d(421))),vo=v(k(an,Ne,Le,ke),m(d(421))),Eo=w(d(4),m(d(43))),_o=w(m(d(42)),d(41),m(d(43))),cn=k(Eo,_o),zt=k(cn,an,Le,ke,Ne),ff=v(k(cn,w(k(an,Ne,Le,ke),m(d(421))))),hf=v(Eo),df=v(_o),pf=v(cn),ln=w(zt,d(6)),ce=w(zt,d(273)),mf=v(w(ln,m(d(421)))),gf=v(ce),un=w(ce,x(460),m(d(421))),Re=w(ce,x(461),m(d(421))),ba=k(un,Re),wf=v(un),bf=v(Re),sn=k(zt,ln,ce,un,Re),Io=k(w(sn,x(477),m(d(421)))),yf=v(Io),So=k(w(sn,x(478),m(d(421))),w(sn,x(448),m(d(449)),x(477),m(d(421)))),xf=v(So),Po=w(ce,x(280),m(d(466)),m(d(466)),m(d(421))),vf=v(Po),Co=w(Re,x(465),m(d(466)),m(d(466)),m(d(421))),Ef=v(Co),De=k(Io,So,w(ln,m(d(421))),w(ba,m(d(421))),w(zt,m(d(421))),Po,Co,d(421)),_f=v(De),ya=w(m(De),x(290),xo(x(281)),m(d(421))),If=v(ya),xa=k(w(De,x(290),x(281),m(d(421))),w(De,x(281),m(d(421))),w(x(281),m(d(421)))),Sf=v(xa),va=w(zt,k(w(d(6,"80")),w(d(6),x(480)),x(480)),m(d(481)),m(d(421))),To=v(va),Ea=w(zt,k(w(d(6,"443")),w(d(6,"443"),x(480)),w(d(6),x(443)),w(d(6),x(448),x(480)),w(x(448),x(480)),x(448),x(443)),m(d(481)),m(d(421))),Ao=v(Ea),_a=k(w(d(777),m(d(421)))),Pf=v(_a),Ia=k(w(d(400),m(d(421)))),Cf=v(Ia);function at(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Fe=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Mt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Fe(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Fe(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var fn=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Do(r={}){return Sa(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Sa(r,t){t=t??{};let e=t.onEnd,n=new Mt,o,s,i,a=at(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,g)=>{s=C=>{s=null,n.push(C);try{y(r(n))}catch(N){g(N)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=at()})}},l=y=>s!=null?s(y):(n.push(y),o),f=y=>(n=new Mt,s!=null?s({error:y}):(n.push({error:y}),o)),h=y=>{if(i)return o;if(t?.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})},u=y=>i?o:(i=!0,y!=null?f(y):l({done:!0})),p=()=>(n=new Mt,u(),{done:!0}),S=y=>(u(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:S,push:h,end:u,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let C,N;g!=null&&(C=new Promise((O,U)=>{N=()=>{U(new fn)},g.addEventListener("abort",N)}));try{await Promise.race([a.promise,C])}finally{N!=null&&g!=null&&g?.removeEventListener("abort",N)}}},e==null)return o;let R=o;return o={[Symbol.asyncIterator](){return this},next(){return R.next()},throw(y){return R.throw(y),e!=null&&(e(y),e=void 0),{done:!0}},return(){return R.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(y){return R.end(y),e!=null&&(e(y),e=void 0),o},get readableLength(){return R.readableLength},onEmpty:y=>R.onEmpty(y)},o}var hn=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},Lo=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function dn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,f=new Promise((h,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){u(Lo(i));return}if(i&&(c=()=>{u(Lo(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,u),e===Number.POSITIVE_INFINITY)return;let p=new hn;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(S){u(S)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?u(o):(p.message=o??`Promise timed out after ${e} milliseconds`,u(p))},e)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var Pa=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Ca(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:f}=Pa(r),h=async(...p)=>{let S=e.multiArgs?p:p[0];if(e.filter)try{if(!await e.filter(S))return}catch(R){n(),i(R);return}c.push(S),e.count===c.length&&(n(),s(c))},u=(...p)=>{n(),i(e.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)f(p,h);for(let p of e.rejectionEvents)a.includes(p)||f(p,u)};for(let p of a)l(p,h);for(let p of e.rejectionEvents)a.includes(p)||l(p,u);e.signal&&e.signal.addEventListener("abort",()=>{u(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=dn(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Oe(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Ca(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function pn(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Ue=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function Ta(r){return r.reason}async function $e(r,t,e){if(t==null)return r;let n=e?.translateError??Ta;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Be=class{deferred;signal;onProgress;constructor(t){this.signal=t?.signal,this.onProgress=t?.onProgress,this.deferred=at(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new V)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Aa(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ze=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(t,e){this.id=Aa(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new V),this.cleanup())}async join(t){let e=new Be(t);return this.recipients.push(e),t?.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await $e(this.fn({...this.options??{},signal:this.controller.signal,onProgress:e=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(e)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var qt=class extends It{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=pn(this.emitEmpty.bind(this),1),this.emitIdle=pn(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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ue;let n=new ze(t,e);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{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:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new V)}),this.clear()}async onEmpty(t){this.size!==0&&await Oe(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Oe(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Oe(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Do({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new V("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};function Vt(r){let t=new globalThis.AbortController;function e(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}async function*le(r,t={}){let e=r.getReader();try{for(;;){let n=await e.read();if(n.done)return;yield n.value}}finally{t.preventCancel!==!0&&await e.cancel(),e.releaseLock()}}var Me=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*jt(r,t={}){let e=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),St(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(t?.maxMessageLength??o.length))throw new Me("Incoming message too long");let i=o.split(e);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Et=class extends Error{static name="InvalidRequestError";constructor(t="Invalid request"){super(t),this.name="InvalidRequestError"}},M=class extends Error{static name="BadResponseError";constructor(t="Bad response"){super(t),this.name="BadResponseError"}};var qe={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},Ve=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(t,e){this.log=t.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new qt({concurrency:e.concurrentRequests??qe.concurrentRequests}),this.inFlightRequests=new Map,this.url=e.url instanceof URL?e.url:new URL(e.url),this.timeout=e.timeout??qe.timeout,this.filterAddrs=e.filterAddrs,this.filterProtocols=e.filterProtocols,this.cacheName=e.cacheName??qe.cacheName,this.cacheTTL=e.cacheTTL??qe.cacheTTL}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(t,e={}){this.log("getProviders starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Vt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/providers/${t}`);this.#r(c,e.filterAddrs,e.filterProtocols);let l=await this.#e(c.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o});if(!l.ok){if(l.status===404)return;throw l.status===422?new Et("Request does not conform to schema or semantic constraints"):new M(`Unexpected status code: ${l.status}`)}let f=l.headers.get("Content-Type");if(f==null)throw new M("No Content-Type header received");if(l.body==null){if(f!=="application/x-ndjson")throw new M("Routing response had no body");return}if(f.startsWith("application/json")){let u=(await l.json()).Providers??[];for(let p of u){let S=this.#t(p);S!=null&&(a++,yield S)}}else if(f.includes("application/x-ndjson"))for await(let h of jt(le(l.body))){let u=this.#t(h);u!=null&&(a++,yield u)}else throw new M(`Unsupported Content-Type: ${f}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",a,t)}}async*getPeers(t,e={}){this.log("getPeers starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Vt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/peers/${t}`);this.#r(a,e.filterAddrs,e.filterProtocols);let c=await this.#e(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(c.status===404)return;if(c.status===422)throw new Et("Request does not conform to schema or semantic constraints");if(c.body==null)throw new M("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let h=(await c.json()).Peers??[];for(let u of h){let p=this.#t(u);p!=null&&(yield p)}}else for await(let f of jt(le(c.body))){let h=this.#t(f);h!=null&&(yield h)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",t)}}async*getClosestPeers(t,e={}){let n;if(T.asCID(t)===t||t instanceof T)n=t.toV1().toString();else throw new _t("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=Vt([this.shutDownController.signal,o,e.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#r(c,e.filterAddrs,e.filterProtocols);let l=await this.#e(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(l.status===404)return;if(l.status===422)throw new Et("Request does not conform to schema or semantic constraints");if(l.body==null)throw new M("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let u=(await l.json()).Peers??[];for(let p of u){let S=this.#t(p);S!=null&&(yield S)}}else for await(let h of jt(le(l.body))){let u=this.#t(h);u!=null&&(yield u)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{s.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(t,e={}){this.log("getIPNS starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Vt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${t}`;try{await s.promise;let c=await this.#e(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new et("No matching records found");if(c.status===422)throw new Et("Request does not conform to schema or semantic constraints");if(!c.ok)throw new M(`Unexpected status code: ${c.status}`);let l=c.headers.get("Content-Type");if(l==null||!l.includes("application/vnd.ipfs.ipns-record"))throw new et("No matching records found");if(c.body==null)throw new M("GET ipns response had no body");let f=await c.arrayBuffer();return new Uint8Array(f,0,f.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",t)}}async putIPNS(t,e,n={}){this.log("putIPNS starts: %c",t);let o=AbortSignal.timeout(this.timeout),s=Vt([this.shutDownController.signal,o,n.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${t}`;try{await i.promise;let l=await this.#e(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ee(e),signal:s});if(this.log("putIPNS PUT %s %d",c,l.status),l.status!==200)throw new M("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",t)}}#t(t){try{let e=[],n=t.Addrs?.map(Bt)??[];return t.Protocols!=null&&e.push(...t.Protocols),t.Protocol!=null&&(e.push(t.Protocol),delete t.Protocol),{...t,Schema:"peer",ID:T.createV1(114,La(t.ID)),Addrs:n,Protocols:e}}catch(e){this.log.error("could not conform record to peer schema - %e",e)}}#r(t,e,n){if(e!=null||this.filterAddrs!=null){let o=e?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&t.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&t.searchParams.set("filter-protocols",o)}}async#e(t,e){let n=e.method??"GET",o=`${n}-${t}`;if(n==="GET"){let c=await this.cache?.match(t);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(t)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(t,e);let i=fetch(t,e).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 h=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:f});await this.cache.put(t,h)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(t,e){let n=new Headers(e.headers);this.log("%s %s HTTP/1.1",e.method??"GET",t);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}logResponse(t){this.log("HTTP/1.1 %d %s",t.status,t.statusText);for(let[e,n]of t.headers.entries())this.log("%s: %s",e,n)}};function La(r){let t=z.baseDecode(r);return mt(t)}function ka(r){return r[Symbol.asyncIterator]!=null}function Na(r){if(ka(r))return(async()=>{for await(let t of r)return t})();for(let t of r)return t}var ko=Na;function Ra(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var No=Ra;function Fa(r){return r[Symbol.asyncIterator]!=null}function Oa(r,t){let e=0;if(Fa(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=No(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=t(o,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var Ro=Oa;function Fo(r){return t=>new Ve(t,r)}var je=I("/ipns/");function Oo(r){return nt(r.subarray(0,je.byteLength),je)}var He=class{name="delegated-http-router";client;constructor(t,e){this.client=Fo(e)(t)}async provide(t,e){}async cancelReprovide(t,e){}async*findProviders(t,e){yield*Ro(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,routing:"delegated-http-routing"}))}async put(t,e,n){if(!Oo(t))return;let o=mt(t.slice(je.length)),s=T.createV1(114,o);await this.client.putIPNS(s,e,n)}async get(t,e){if(!Oo(t))throw new et("Not found");let n=mt(t.slice(je.length)),o=T.createV1(114,n);try{return await this.client.getIPNS(o,e)}catch(s){throw s.name==="BadResponseError"?new et("Not found"):s}}async findPeer(t,e){let n=await ko(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new et("Not found")}async*getClosestPeers(t,e){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function Uo(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}function $o(r){return t=>new He(t,Uo(r))}var Bo="[a-fA-F\\d:]",dt=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Bo})|(?<=${Bo})(?=\\s|$))`:"",W="(?: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}",P="[a-fA-F\\d]{1,4}",We=`
2
+ "use strict";var HeliaHttp=(()=>{var ns=Object.create;var fe=Object.defineProperty;var os=Object.getOwnPropertyDescriptor;var ss=Object.getOwnPropertyNames;var is=Object.getPrototypeOf,as=Object.prototype.hasOwnProperty;var er=(r,t)=>()=>{try{return t||r((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},F=(r,t)=>{for(var e in t)fe(r,e,{get:t[e],enumerable:!0})},Sn=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ss(t))!as.call(r,o)&&o!==e&&fe(r,o,{get:()=>t[o],enumerable:!(n=os(t,o))||n.enumerable});return r};var cs=(r,t,e)=>(e=r!=null?ns(is(r)):{},Sn(t||!r||!r.__esModule?fe(e,"default",{value:r,enumerable:!0}):e,r)),ls=r=>Sn(fe({},"__esModule",{value:!0}),r);var Ar=er(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Netmask4Impl=void 0;Nt.ip2long=kt;Nt.long2ip=Z;function Z(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[t,e,n,o].join(".")}var Ai=48,Di=97,Li=65;function ki(r){let t=0,e=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,e=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,e=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)t=t*e+(r.charCodeAt(o)-Ai)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-Di)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-Li)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[t,o]}function kt(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=ki(r);r=r.substring(o),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var Tr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let o=t.split("/",2);t=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=kt(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(kt(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Z(this.netLong),this.mask=Z(this.maskLong),this.hostmask=Z(~this.maskLong),this.first=this.bitmask<=30?Z(this.netLong+1):this.base,this.last=this.bitmask<=30?Z(this.netLong+this.size-2):Z(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Z(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(kt(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Z(this.netLong+this.size*t),this.mask)}forEach(t){let e=kt(this.first),n=kt(this.last),o=0;for(;e<=n;)t(Z(e),e,o),o++,e++}toString(){return this.base+"/"+this.bitmask}};Nt.Netmask4Impl=Tr});var ro=er(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.Netmask6Impl=void 0;Rt.ip6bigint=Lr;Rt.bigint2ip6=yt;var Ni=Ar(),Dr=(1n<<128n)-1n;function Lr(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),o=(0,Ni.ip2long)(n),s=r.substring(0,e+1)+"0:0";return eo(s)&~0xffffffffn|BigInt(o)}return eo(r)}function eo(r){let t=r.indexOf("::"),e;if(t!==-1){let o=r.substring(0,t),s=r.substring(t+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let o=0;o<8;o++){let s=e[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function yt(r){if(r<0n||r>Dr)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)t[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(e=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(e=o,n=s),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var kr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let o=t.indexOf("/");o!==-1?(n=parseInt(t.substring(o+1),10),t=t.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=Dr>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Lr(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=yt(this.netBigint),this.mask=yt(this.maskBigint),this.hostmask=yt(~this.maskBigint&Dr),this.first=this.base,this.last=yt(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(Lr(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(yt(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;e<=o;)t(yt(e),Number(e),s),s++,e++}toString(){return this.base+"/"+this.bitmask}};Rt.Netmask6Impl=kr});var no=er(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.long2ip=ft.ip2long=ft.Netmask=void 0;var ve=Ar();Object.defineProperty(ft,"ip2long",{enumerable:!0,get:function(){return ve.ip2long}});Object.defineProperty(ft,"long2ip",{enumerable:!0,get:function(){return ve.long2ip}});var Ri=ro(),Nr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new Ri.Netmask6Impl(t,e):this._impl=new ve.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof ve.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};ft.Netmask=Nr});var ac={};F(ac,{withHTTP:()=>ic});var j=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var _t=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var rt=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}};function us(r){return typeof r?.handleEvent=="function"}function fs(r){return(r!==!0&&r!==!1&&r?.once)??!1}var It=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){let o=fs(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}us(e)?e.handleEvent(i):e(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:o})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function B(r=0){return new Uint8Array(r)}function Y(r=0){return new Uint8Array(r)}function hs(r){return r?.buffer instanceof ArrayBuffer}function rr(r){if(hs(r))return r;let t=r.slice();return new Uint8Array(t.buffer,0,t.byteLength)}function nt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=Y(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return rr(e)}function ot(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Cn=Symbol.for("@achingbrain/uint8arraylist");function Pn(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function St(r){return!!r?.[Cn]}var he=class r{bufs;length;[Cn]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(St(n)){e+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(St(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Pn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Pn(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(St(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return nt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:nt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=n,s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,f=e>a&&e<=c;if(l&&f){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!St(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let h=e;h<=c;h+=f){f=0;for(let u=l;u>=0;u--){let p=this.get(h+u);if(n[u]!==p){f=Math.max(1,u-a[p]);break}}if(f===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Y(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=B(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=B(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=B(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Y(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=B(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=B(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=B(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=B(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=B(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!ot(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var ar={};F(ar,{base10:()=>xs});var vc=new Uint8Array(0);function An(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function z(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return pt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return pt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Dn(r){let t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}var Tn=4096;function Ln(r){let t=r.length;if(t<=Tn)return String.fromCharCode.apply(String,r);let e="",n=0;for(;n<t;)e+=String.fromCharCode.apply(String,r.subarray(n,n+=Tn));return e}function ds(r){return r?.buffer instanceof ArrayBuffer}function pt(r){return ds(r)?r:r.slice()}function ps(r,t,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,e){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),l!==a&&(n[l]=s)}}var f=r.length,h=r.charAt(0),u=Math.log(f)/Math.log(256),p=Math.log(256)/Math.log(f);function S(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var C=0,N=0,O=0,U=g.length;O!==U&&g[O]===0;)O++,C++;for(var K=(U-O)*p+1>>>0,$=new Uint8Array(K);O!==U;){for(var J=g[O],ct=0,V=K-1;(J!==0||ct<N)&&V!==-1;V--,ct++)J+=256*$[V]>>>0,$[V]=J%f>>>0,J=J/f>>>0;if(J!==0)throw new Error("Non-zero carry");N=ct,O++}for(var et=K-N;et!==K&&$[et]===0;)et++;for(var ue=h.repeat(C);et<K;++et)ue+=r.charAt($[et]);return ue}function R(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var C=0;if(g[C]!==" "){for(var N=0,O=0;g[C]===h;)N++,C++;for(var U=(g.length-C)*u+1>>>0,K=new Uint8Array(U);g[C];){var $=n[g.charCodeAt(C)];if($===255)return;for(var J=0,ct=U-1;($!==0||J<O)&&ct!==-1;ct--,J++)$+=f*K[ct]>>>0,K[ct]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");O=J,C++}if(g[C]!==" "){for(var V=U-O;V!==U&&K[V]===0;)V++;for(var et=new Uint8Array(N+(U-V)),ue=N;V!==U;)et[ue++]=K[V++];return et}}}function y(g){var C=R(g);if(C)return C;throw new Error(`Non-${t} character`)}return{encode:S,decodeUnsafe:R,decode:y}}var ms=ps,gs=ms,Nn=gs;var nr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},or=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Rn(this,t)}},sr=class{decoders;constructor(t){this.decoders=t}or(t){return Rn(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Rn(r,t){return new sr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ir=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new nr(t,e,n),this.decoder=new or(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Pt({name:r,prefix:t,encode:e,decode:n}){return new ir(r,t,e,n)}function lt({name:r,prefix:t,alphabet:e,caseInsensitive:n=!1}){let{encode:o,decode:s}=Nn(e,r,n);return Pt({prefix:t,name:r,encode:o,decode:i=>z(s(i))})}function ws(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let f=t[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|f,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function bs(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function ys(r,t){let e={};for(let n=0;n<r.length;++n)if(e[r[n]]=n,t){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(e[o]=n),s!==r[n]&&(e[s]=n)}return e}function _({name:r,prefix:t,bitsPerChar:e,alphabet:n,caseInsensitive:o=!1}){let s=ys(n,o);return Pt({prefix:t,name:r,encode(i){return bs(i,n,e)},decode(i){return ws(i,s,e,r)}})}var xs=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var cr={};F(cr,{base16:()=>vs,base16upper:()=>Es});var vs=_({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),Es=_({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var lr={};F(lr,{base2:()=>_s});var _s=_({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ur={};F(ur,{base256emoji:()=>Ts});var Fn=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}"),Is=Fn.reduce((r,t,e)=>(r[e]=t,r),[]),Ss=Fn.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Ps(r){return r.reduce((t,e)=>(t+=Is[e],t),"")}function Cs(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Ss[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Ts=Pt({prefix:"\u{1F680}",name:"base256emoji",encode:Ps,decode:Cs});var fr={};F(fr,{base32:()=>ut,base32hex:()=>ks,base32hexpad:()=>Rs,base32hexpadupper:()=>Fs,base32hexupper:()=>Ns,base32pad:()=>Ds,base32padupper:()=>Ls,base32upper:()=>As,base32z:()=>Os});var ut=_({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),As=_({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Ds=_({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Ls=_({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),ks=_({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Ns=_({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Rs=_({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Fs=_({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Os=_({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var hr={};F(hr,{base36:()=>Wt,base36upper:()=>Us});var Wt=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Us=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var dr={};F(dr,{base58btc:()=>M,base58flickr:()=>$s});var M=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$s=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var mr={};F(mr,{base64:()=>Gt,base64pad:()=>Bs,base64url:()=>pr,base64urlpad:()=>zs});var Gt=_({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Bs=_({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pr=_({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zs=_({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var gr={};F(gr,{base8:()=>Ms});var Ms=_({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var wr={};F(wr,{identity:()=>qs});var qs=Pt({prefix:"\0",name:"identity",encode:r=>Ln(z(r)),decode:r=>z(Dn(r))});var Uc=new TextEncoder,$c=new TextDecoder;var yr={};F(yr,{identity:()=>Kt});var Hs=$n,On=128,Ws=127,Gs=~Ws,Qs=Math.pow(2,31);function $n(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Qs;)t[e++]=r&255|On,r/=128;for(;r&Gs;)t[e++]=r&255|On,r>>>=7;return t[e]=r|0,$n.bytes=e-n+1,t}var Xs=br,Ks=128,Un=127;function br(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw br.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Un)<<o:(i&Un)*Math.pow(2,o),o+=7}while(i>=Ks);return br.bytes=s-n,e}var Js=Math.pow(2,7),Ys=Math.pow(2,14),Zs=Math.pow(2,21),ti=Math.pow(2,28),ei=Math.pow(2,35),ri=Math.pow(2,42),ni=Math.pow(2,49),oi=Math.pow(2,56),si=Math.pow(2,63),ii=function(r){return r<Js?1:r<Ys?2:r<Zs?3:r<ti?4:r<ei?5:r<ri?6:r<ni?7:r<oi?8:r<si?9:10},ai={encode:Hs,decode:Xs,encodingLength:ii},ci=ai,Qt=ci;function Xt(r,t=0){return[Qt.decode(r,t),Qt.decode.bytes]}function Ct(r,t,e=0){return Qt.encode(r,t,e),t}function Tt(r){return Qt.encodingLength(r)}function Dt(r,t){let e=t.byteLength,n=Tt(r),o=n+Tt(e),s=new Uint8Array(o+e);return Ct(r,s,0),Ct(e,s,n),s.set(t,o),new At(r,e,t,s)}function mt(r){let t=z(r),[e,n]=Xt(t),[o,s]=Xt(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new At(e,o,i,t)}function Bn(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&An(r.bytes,e.bytes)}}var At=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=pt(n),this.bytes=pt(o)}};var zn=0,li="identity",Mn=z;function ui(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Dt(zn,Mn(r))}var Kt={code:zn,name:li,encode:Mn,digest:ui};var Er={};F(Er,{sha256:()=>hi,sha512:()=>di});var fi=20;function vr({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new xr(r,t,e,n,o)}var xr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??fi,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?qn(n,this.code,e?.truncate):n.then(o=>qn(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function qn(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Dt(t,r)}function jn(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var hi=vr({name:"sha2-256",code:18,encode:jn("SHA-256")}),di=vr({name:"sha2-512",code:19,encode:jn("SHA-512")});function Hn(r,t){let{bytes:e,version:n}=r;return n===0?mi(e,_r(r),t??M.encoder):gi(e,_r(r),t??ut.encoder)}var Wn=new WeakMap;function _r(r){let t=Wn.get(r);if(t==null){let e=new Map;return Wn.set(r,e),e}return t}var T=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=pt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Jt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==wi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Dt(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Bn(t.multihash,n.multihash)}toString(t){return Hn(this,t)}toJSON(){return{"/":Hn(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Gn(n,o,s.bytes))}else if(e[bi]===!0){let{version:n,multihash:o,code:s}=e,i=mt(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Jt)throw new Error(`Version 0 CID must use dag-pb (code: ${Jt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Gn(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Jt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=z(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new At(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,u]=Xt(t.subarray(e));return e+=u,h},o=n(),s=Jt;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,f=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(t,e){let[n,o]=pi(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return _r(s).set(n,t),s}};function pi(r,t){switch(r[0]){case"Q":{let e=t??M;return[M.prefix,e.decode(`${M.prefix}${r}`)]}case M.prefix:{let e=t??M;return[M.prefix,e.decode(r)]}case ut.prefix:{let e=t??ut;return[ut.prefix,e.decode(r)]}case Wt.prefix:{let e=t??Wt;return[Wt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function mi(r,t,e){let{prefix:n}=e;if(n!==M.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function gi(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Jt=112,wi=18;function Gn(r,t,e){let n=Tt(r),o=n+Tt(t),s=new Uint8Array(o+e.byteLength);return Ct(r,s,0),Ct(t,s,n),s.set(e,o),s}var bi=Symbol.for("@ipld/js-cid/CID");var Yt={...wr,...lr,...gr,...ar,...cr,...fr,...hr,...dr,...mr,...ur},il={...Er,...yr};function Xn(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Qn=Xn("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ir=Xn("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Y(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),yi={utf8:Qn,"utf-8":Qn,hex:Yt.base16,latin1:Ir,ascii:Ir,binary:Ir,...Yt},pe=yi;function I(r,t="utf8"){let e=pe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}var Sr={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Kn={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Jn=new globalThis.TextEncoder;function xi(r,t){let e=Sr[t],n=Kn[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function vi(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Sr[t],o=Kn[t],s=r;for(;s.length>0;){let i=Jn.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Pr(r,{size:t=32,utf8Buffer:e}={}){if(!Sr[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return vi(r,t,e);r=Jn.encode(r)}return xi(r,t)}var Zt={hash:r=>Number(Pr(r,{size:32})),hashV:(r,t)=>Ei(Zt.hash(r,t))};function Ei(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),I(t,"base16")}var Cr=64,H=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Cr)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=B(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?ot(this.fp,t.fp):!1}};function wt(r,t){return Math.floor(Math.random()*(t-r))+r}var bt=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof H))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof H))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof H))throw new TypeError("Invalid Fingerprint");let e=wt(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof H))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var _i=500,te=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Zt,this.seed=t.seed??wt(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=I(t));let e=new H(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new bt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new bt(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[wt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new bt(this.bucketSize));for(let a=0;a<_i;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new bt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=I(t));let e=new H(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=I(t));let e=new H(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Ii={1:.5,2:.84,4:.95,8:.98};function Si(r=.001){return r>.002?2:r>1e-5?4:8}function Yn(r,t=.001){let e=Si(t),n=Ii[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Cr);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var me=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Zt,this.seed=t.seed??wt(0,Math.pow(2,10)),this.filterSeries=[new te({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=I(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new te({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=I(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=I(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function ge(r,t=.001,e){return new me({...Yn(r,t),...e??{}})}function Pi(r){let t=r.getComponents(),e={},n=0;return t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n]?.name==="ip4"||t[n]?.name==="ip6"||t[n]?.name==="dns"||t[n]?.name==="dns4"||t[n]?.name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n]?.name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null?null:(t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e)}function we(r){let t=Pi(r);if(t==null)throw new _t(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}var be=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let u=Number.parseInt(h,t);if(!Number.isNaN(u))return u});if(f===void 0)break;if(s*=t,s+=f,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ci=45,Ti=15,ye=new be;function Zn(r){if(!(r.length>Ti))return ye.new(r).parseWith(()=>ye.readIPv4Addr())}function to(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ci))return ye.new(r).parseWith(()=>ye.readIPv6Addr())}function Lt(r){return!!Zn(r)}function xe(r){return!!to(r)}var oo=cs(no(),1),Fi=["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"],Oi=Fi.map(r=>new oo.Netmask(r));function Rr(r){for(let t of Oi)if(t.contains(r))return!0;return!1}function Ui(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function $i(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Rr(o)}function Bi(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function zi(r){let t=r.split(":"),e=t[t.length-1];return Rr(e)}function Mi(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 so(r){if(Lt(r))return Rr(r);if(Ui(r))return $i(r);if(Bi(r))return zi(r);if(xe(r))return Mi(r)}function io(r){try{let t=we(r);switch(t.type){case"ip4":case"ip6":return so(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}var qi=Math.pow(2,7),Vi=Math.pow(2,14),ji=Math.pow(2,21),Fr=Math.pow(2,28),Or=Math.pow(2,35),Ur=Math.pow(2,42),$r=Math.pow(2,49),E=128,L=127;function Ft(r){if(r<qi)return 1;if(r<Vi)return 2;if(r<ji)return 3;if(r<Fr)return 4;if(r<Or)return 5;if(r<Ur)return 6;if(r<$r)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Br(r,t,e=0){switch(Ft(r)){case 8:t[e++]=r&255|E,r/=128;case 7:t[e++]=r&255|E,r/=128;case 6:t[e++]=r&255|E,r/=128;case 5:t[e++]=r&255|E,r/=128;case 4:t[e++]=r&255|E,r>>>=7;case 3:t[e++]=r&255|E,r>>>=7;case 2:t[e++]=r&255|E,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Hi(r,t){let e=r[t],n=0;if(n+=e&L,e<E||(e=r[t+1],n+=(e&L)<<7,e<E)||(e=r[t+2],n+=(e&L)<<14,e<E)||(e=r[t+3],n+=(e&L)<<21,e<E)||(e=r[t+4],n+=(e&L)*Fr,e<E)||(e=r[t+5],n+=(e&L)*Or,e<E)||(e=r[t+6],n+=(e&L)*Ur,e<E)||(e=r[t+7],n+=(e&L)*$r,e<E))return n;throw new RangeError("Could not decode varint")}function Wi(r,t){let e=r.get(t),n=0;if(n+=e&L,e<E||(e=r.get(t+1),n+=(e&L)<<7,e<E)||(e=r.get(t+2),n+=(e&L)<<14,e<E)||(e=r.get(t+3),n+=(e&L)<<21,e<E)||(e=r.get(t+4),n+=(e&L)*Fr,e<E)||(e=r.get(t+5),n+=(e&L)*Or,e<E)||(e=r.get(t+6),n+=(e&L)*Ur,e<E)||(e=r.get(t+7),n+=(e&L)*$r,e<E))return n;throw new RangeError("Could not decode varint")}function zr(r,t=0){return r instanceof Uint8Array?Hi(r,t):Wi(r,t)}function Qi(r){return r.buffer instanceof ArrayBuffer}function ee(r){return Qi(r)?r:r.slice()}function tt(r,t="utf8"){let e=pe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var D=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},st=class extends Error{static name="ValidationError";name="ValidationError"},Ee=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},_e=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function qr(r){return t=>tt(t,r)}function Vr(r){return t=>I(t,r)}function Ot(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function xt(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function ao(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=I(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return nt([e,o],e.length+o.length)}function co(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=ut.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return nt([e,o],e.length+o.length)}function jr(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=tt(t,"base32"),o=Ot(e);return`${n}:${o}`}var Hr=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new D("Invalid byte value in IP address");t[n]=o}),t},lo=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Lt(e[n]),i;s&&(i=Hr(e[n]),e[n]=tt(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,tt(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new D("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},uo=function(r){if(r.byteLength!==4)throw new D("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},fo=function(r){if(r.byteLength!==16)throw new D("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new D(`Invalid IPv6 address "${e}"`)}};function ho(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new D(`Invalid IPv6 address "${r}"`)}}var Mr=Object.values(Yt).map(r=>r.decoder),Xi=(function(){let r=Mr[0].or(Mr[1]);return Mr.slice(2).forEach(t=>r=r.or(t)),r})();function po(r){return Xi.decode(r)}function mo(r){return t=>r.encoder.encode(t)}function Ki(r){if(parseInt(r).toString()!==r)throw new st("Value must be an integer")}function Ji(r){if(r<0)throw new st("Value must be a positive integer, or zero")}function Yi(r){return t=>{if(t>r)throw new st(`Value must be smaller than or equal to ${r}`)}}function Zi(...r){return t=>{for(let e of r)e(t)}}var re=Zi(Ki,Ji,Yi(65535));var A=-1,Wr=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new _e(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},it=new Wr,da=[{code:4,name:"ip4",size:32,valueToBytes:Hr,bytesToValue:uo,validate:r=>{if(!Lt(r))throw new st(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:273,name:"udp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:33,name:"dccp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:41,name:"ip6",size:128,valueToBytes:lo,bytesToValue:fo,stringToValue:ho,validate:r=>{if(!xe(r))throw new st(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:A},{code:43,name:"ipcidr",size:8,bytesToValue:qr("base10"),valueToBytes:Vr("base10")},{code:53,name:"dns",size:A},{code:54,name:"dns4",size:A},{code:55,name:"dns6",size:A},{code:56,name:"dnsaddr",size:A},{code:132,name:"sctp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:A,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:A,bytesToValue:qr("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Vr("base58btc")(r):T.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:jr,valueToBytes:ao},{code:445,name:"onion3",size:296,bytesToValue:jr,valueToBytes:co},{code:446,name:"garlic64",size:A},{code:447,name:"garlic32",size:A},{code:448,name:"tls"},{code:449,name:"sni",size:A},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:A,bytesToValue:mo(pr),valueToBytes:po},{code:480,name:"http"},{code:481,name:"http-path",size:A,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:A}];da.forEach(r=>{it.addProtocol(r)});function go(r){let t=[],e=0;for(;e<r.length;){let n=zr(r,e),o=it.getProtocol(n),s=Ft(n),i=pa(o,r,e+s),a=0;i>0&&o.size===A&&(a=Ft(i));let c=s+a+i,l={code:n,name:o.name,bytes:ee(r.subarray(e,e+c))};if(i>0){let f=e+s+a,h=r.subarray(f,f+i);l.value=o.bytesToValue?.(h)??tt(h)}t.push(l),e+=c}return t}function wo(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=it.getProtocol(n.code),s=Ft(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??I(n.value),a=i.byteLength,o.size===A&&(c=Ft(a)));let l=new Uint8Array(s+c+a),f=0;Br(n.code,l,f),f+=s,i!=null&&(o.size===A&&(Br(a,l,f),f+=c),l.set(i,f)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return nt(e,t)}function bo(r){if(r.charAt(0)!=="/")throw new D('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=it.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new D(`Component ${o} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new D(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new D("Incomplete multiaddr");return t}function yo(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=it.getProtocol(t.code);if(e==null)throw new D(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function pa(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:zr(t,e)}var ma=Symbol.for("nodejs.util.inspect.custom"),on=Symbol.for("@multiformats/multiaddr");function ga(r){if(r==null&&(r="/"),xo(r))return r.getComponents();if(r instanceof Uint8Array)return go(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),bo(r);if(Array.isArray(r))return r;throw new D("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ae=class r{[on]=!0;#t;#r;#e;constructor(t="/",e={}){this.#t=ga(t),e.validate!==!1&&wa(this)}get bytes(){return this.#e==null&&(this.#e=wo(this.#t)),this.#e}toString(){return this.#r==null&&(this.#r=yo(this.#t)),this.#r}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Ee(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return ot(this.bytes,t.bytes)}[ma](){return`Multiaddr(${this.toString()})`}};function wa(r){r.getComponents().forEach(t=>{let e=it.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function xo(r){return!!r?.[on]}function Bt(r){return new Ae(r)}var x=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),d=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),vo=r=>({match:t=>r.match(t)===!1?t:!1}),m=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),k=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),w=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function v(...r){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var ba=d(421),cf=v(ba),Le=d(54),ke=d(55),Ne=d(56),an=d(53),lf=v(Le,m(d(421))),uf=v(ke,m(d(421))),ff=v(Ne,m(d(421))),Eo=v(k(an,Ne,Le,ke),m(d(421))),_o=w(d(4),m(d(43))),Io=w(m(d(42)),d(41),m(d(43))),cn=k(_o,Io),zt=k(cn,an,Le,ke,Ne),hf=v(k(cn,w(k(an,Ne,Le,ke),m(d(421))))),df=v(_o),pf=v(Io),mf=v(cn),ln=w(zt,d(6)),ce=w(zt,d(273)),gf=v(w(ln,m(d(421)))),wf=v(ce),un=w(ce,x(460),m(d(421))),Re=w(ce,x(461),m(d(421))),ya=k(un,Re),bf=v(un),yf=v(Re),sn=k(zt,ln,ce,un,Re),So=k(w(sn,x(477),m(d(421)))),xf=v(So),Po=k(w(sn,x(478),m(d(421))),w(sn,x(448),m(d(449)),x(477),m(d(421)))),vf=v(Po),Co=w(ce,x(280),m(d(466)),m(d(466)),m(d(421))),Ef=v(Co),To=w(Re,x(465),m(d(466)),m(d(466)),m(d(421))),_f=v(To),De=k(So,Po,w(ln,m(d(421))),w(ya,m(d(421))),w(zt,m(d(421))),Co,To,d(421)),If=v(De),xa=w(m(De),x(290),vo(x(281)),m(d(421))),Sf=v(xa),va=k(w(De,x(290),x(281),m(d(421))),w(De,x(281),m(d(421))),w(x(281),m(d(421)))),Pf=v(va),Ea=w(zt,k(w(d(6,"80")),w(d(6),x(480)),x(480)),m(d(481)),m(d(421))),Ao=v(Ea),_a=w(zt,k(w(d(6,"443")),w(d(6,"443"),x(480)),w(d(6),x(443)),w(d(6),x(448),x(480)),w(x(448),x(480)),x(448),x(443)),m(d(481)),m(d(421))),Do=v(_a),Ia=k(w(d(777),m(d(421)))),Cf=v(Ia),Sa=k(w(d(400),m(d(421)))),Tf=v(Sa);function at(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Fe=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Mt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Fe(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Fe(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var fn=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Lo(r={}){return Pa(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Pa(r,t){t=t??{};let e=t.onEnd,n=new Mt,o,s,i,a=at(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,g)=>{s=C=>{s=null,n.push(C);try{y(r(n))}catch(N){g(N)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=at()})}},l=y=>s!=null?s(y):(n.push(y),o),f=y=>(n=new Mt,s!=null?s({error:y}):(n.push({error:y}),o)),h=y=>{if(i)return o;if(t?.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})},u=y=>i?o:(i=!0,y!=null?f(y):l({done:!0})),p=()=>(n=new Mt,u(),{done:!0}),S=y=>(u(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:S,push:h,end:u,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let C,N;g!=null&&(C=new Promise((O,U)=>{N=()=>{U(new fn)},g.addEventListener("abort",N)}));try{await Promise.race([a.promise,C])}finally{N!=null&&g!=null&&g?.removeEventListener("abort",N)}}},e==null)return o;let R=o;return o={[Symbol.asyncIterator](){return this},next(){return R.next()},throw(y){return R.throw(y),e!=null&&(e(y),e=void 0),{done:!0}},return(){return R.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(y){return R.end(y),e!=null&&(e(y),e=void 0),o},get readableLength(){return R.readableLength},onEmpty:y=>R.onEmpty(y)},o}var hn=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},ko=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function dn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,f=new Promise((h,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){u(ko(i));return}if(i&&(c=()=>{u(ko(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,u),e===Number.POSITIVE_INFINITY)return;let p=new hn;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(S){u(S)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?u(o):(p.message=o??`Promise timed out after ${e} milliseconds`,u(p))},e)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var Ca=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Ta(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:f}=Ca(r),h=async(...p)=>{let S=e.multiArgs?p:p[0];if(e.filter)try{if(!await e.filter(S))return}catch(R){n(),i(R);return}c.push(S),e.count===c.length&&(n(),s(c))},u=(...p)=>{n(),i(e.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)f(p,h);for(let p of e.rejectionEvents)a.includes(p)||f(p,u)};for(let p of a)l(p,h);for(let p of e.rejectionEvents)a.includes(p)||l(p,u);e.signal&&e.signal.addEventListener("abort",()=>{u(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=dn(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Oe(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Ta(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function pn(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Ue=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function Aa(r){return r.reason}async function $e(r,t,e){if(t==null)return r;let n=e?.translateError??Aa;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Be=class{deferred;signal;onProgress;constructor(t){this.signal=t?.signal,this.onProgress=t?.onProgress,this.deferred=at(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new j)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Da(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ze=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(t,e){this.id=Da(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new j),this.cleanup())}async join(t){let e=new Be(t);return this.recipients.push(e),t?.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await $e(this.fn({...this.options??{},signal:this.controller.signal,onProgress:e=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(e)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var qt=class extends It{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=pn(this.emitEmpty.bind(this),1),this.emitIdle=pn(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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ue;let n=new ze(t,e);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{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:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new j)}),this.clear()}async onEmpty(t){this.size!==0&&await Oe(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Oe(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Oe(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Lo({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new j("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};function Vt(r){let t=new globalThis.AbortController;function e(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}async function*le(r,t={}){let e=r.getReader();try{for(;;){let n=await e.read();if(n.done)return;yield n.value}}finally{t.preventCancel!==!0&&await e.cancel(),e.releaseLock()}}var Me=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*jt(r,t={}){let e=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),St(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(t?.maxMessageLength??o.length))throw new Me("Incoming message too long");let i=o.split(e);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Et=class extends Error{static name="InvalidRequestError";constructor(t="Invalid request"){super(t),this.name="InvalidRequestError"}},q=class extends Error{static name="BadResponseError";constructor(t="Bad response"){super(t),this.name="BadResponseError"}};var qe={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},Ve=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(t,e){this.log=t.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new qt({concurrency:e.concurrentRequests??qe.concurrentRequests}),this.inFlightRequests=new Map,this.url=e.url instanceof URL?e.url:new URL(e.url),this.timeout=e.timeout??qe.timeout,this.filterAddrs=e.filterAddrs,this.filterProtocols=e.filterProtocols,this.cacheName=e.cacheName??qe.cacheName,this.cacheTTL=e.cacheTTL??qe.cacheTTL}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(t,e={}){this.log("getProviders starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Vt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/providers/${t}`);this.#r(c,e.filterAddrs,e.filterProtocols);let l=await this.#e(c.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o});if(!l.ok){if(l.status===404)return;throw l.status===422?new Et("Request does not conform to schema or semantic constraints"):new q(`Unexpected status code: ${l.status}`)}let f=l.headers.get("Content-Type");if(f==null)throw new q("No Content-Type header received");if(l.body==null){if(f!=="application/x-ndjson")throw new q("Routing response had no body");return}if(f.startsWith("application/json")){let u=(await l.json()).Providers??[];for(let p of u){let S=this.#t(p);S!=null&&(a++,yield S)}}else if(f.includes("application/x-ndjson"))for await(let h of jt(le(l.body))){let u=this.#t(h);u!=null&&(a++,yield u)}else throw new q(`Unsupported Content-Type: ${f}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",a,t)}}async*getPeers(t,e={}){this.log("getPeers starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Vt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/peers/${t}`);this.#r(a,e.filterAddrs,e.filterProtocols);let c=await this.#e(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(c.status===404)return;if(c.status===422)throw new Et("Request does not conform to schema or semantic constraints");if(c.body==null)throw new q("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let h=(await c.json()).Peers??[];for(let u of h){let p=this.#t(u);p!=null&&(yield p)}}else for await(let f of jt(le(c.body))){let h=this.#t(f);h!=null&&(yield h)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",t)}}async*getClosestPeers(t,e={}){let n;if(T.asCID(t)===t||t instanceof T)n=t.toV1().toString();else throw new _t("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=Vt([this.shutDownController.signal,o,e.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#r(c,e.filterAddrs,e.filterProtocols);let l=await this.#e(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(l.status===404)return;if(l.status===422)throw new Et("Request does not conform to schema or semantic constraints");if(l.body==null)throw new q("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let u=(await l.json()).Peers??[];for(let p of u){let S=this.#t(p);S!=null&&(yield S)}}else for await(let h of jt(le(l.body))){let u=this.#t(h);u!=null&&(yield u)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{s.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(t,e={}){this.log("getIPNS starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Vt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${t}`;try{await s.promise;let c=await this.#e(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new rt("No matching records found");if(c.status===422)throw new Et("Request does not conform to schema or semantic constraints");if(!c.ok)throw new q(`Unexpected status code: ${c.status}`);let l=c.headers.get("Content-Type");if(l==null||!l.includes("application/vnd.ipfs.ipns-record"))throw new rt("No matching records found");if(c.body==null)throw new q("GET ipns response had no body");let f=await c.arrayBuffer();return new Uint8Array(f,0,f.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",t)}}async putIPNS(t,e,n={}){this.log("putIPNS starts: %c",t);let o=AbortSignal.timeout(this.timeout),s=Vt([this.shutDownController.signal,o,n.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${t}`;try{await i.promise;let l=await this.#e(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ee(e),signal:s});if(this.log("putIPNS PUT %s %d",c,l.status),l.status!==200)throw new q("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",t)}}#t(t){try{let e=[],n=t.Addrs?.map(Bt)??[];return t.Protocols!=null&&e.push(...t.Protocols),t.Protocol!=null&&(e.push(t.Protocol),delete t.Protocol),{...t,Schema:"peer",ID:T.createV1(114,ka(t.ID)),Addrs:n,Protocols:e}}catch(e){this.log.error("could not conform record to peer schema - %e",e)}}#r(t,e,n){if(e!=null||this.filterAddrs!=null){let o=e?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&t.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&t.searchParams.set("filter-protocols",o)}}async#e(t,e){let n=e.method??"GET",o=`${n}-${t}`;if(n==="GET"){let c=await this.cache?.match(t);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(t)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(t,e);let i=fetch(t,e).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 h=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:f});await this.cache.put(t,h)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(t,e){let n=new Headers(e.headers);this.log("%s %s HTTP/1.1",e.method??"GET",t);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}logResponse(t){this.log("HTTP/1.1 %d %s",t.status,t.statusText);for(let[e,n]of t.headers.entries())this.log("%s: %s",e,n)}};function ka(r){let t=M.baseDecode(r);return mt(t)}function Na(r){return r[Symbol.asyncIterator]!=null}function Ra(r){if(Na(r))return(async()=>{for await(let t of r)return t})();for(let t of r)return t}var No=Ra;function Fa(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Ro=Fa;function Oa(r){return r[Symbol.asyncIterator]!=null}function Ua(r,t){let e=0;if(Oa(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=Ro(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=t(o,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var Fo=Ua;function Oo(r){return t=>new Ve(t,r)}var je=I("/ipns/");function Uo(r){return ot(r.subarray(0,je.byteLength),je)}var He=class{name="delegated-http-router";client;constructor(t,e){this.client=Oo(e)(t)}async provide(t,e){}async cancelReprovide(t,e){}async*findProviders(t,e){yield*Fo(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,routing:"delegated-http-routing"}))}async put(t,e,n){if(!Uo(t))return;let o=mt(t.slice(je.length)),s=T.createV1(114,o);await this.client.putIPNS(s,e,n)}async get(t,e){if(!Uo(t))throw new rt("Not found");let n=mt(t.slice(je.length)),o=T.createV1(114,n);try{return await this.client.getIPNS(o,e)}catch(s){throw s.name==="BadResponseError"?new rt("Not found"):s}}async findPeer(t,e){let n=await No(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new rt("Not found")}async*getClosestPeers(t,e){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function $o(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}function Bo(r){return t=>new He(t,$o(r))}var zo="[a-fA-F\\d:]",dt=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${zo})|(?<=${zo})(?=\\s|$))`:"",G="(?: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}",P="[a-fA-F\\d]{1,4}",We=`
3
3
  (?:
4
4
  (?:${P}:){7}(?:${P}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
5
- (?:${P}:){6}(?:${W}|:${P}|:)| // 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
6
- (?:${P}:){5}(?::${W}|(?::${P}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
7
- (?:${P}:){4}(?:(?::${P}){0,1}:${W}|(?::${P}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
8
- (?:${P}:){3}(?:(?::${P}){0,2}:${W}|(?::${P}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
9
- (?:${P}:){2}(?:(?::${P}){0,3}:${W}|(?::${P}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
10
- (?:${P}:){1}(?:(?::${P}){0,4}:${W}|(?::${P}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
11
- (?::(?:(?::${P}){0,5}:${W}|(?::${P}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
5
+ (?:${P}:){6}(?:${G}|:${P}|:)| // 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
6
+ (?:${P}:){5}(?::${G}|(?::${P}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
7
+ (?:${P}:){4}(?:(?::${P}){0,1}:${G}|(?::${P}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
8
+ (?:${P}:){3}(?:(?::${P}){0,2}:${G}|(?::${P}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
9
+ (?:${P}:){2}(?:(?::${P}){0,3}:${G}|(?::${P}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
10
+ (?:${P}:){1}(?:(?::${P}){0,4}:${G}|(?::${P}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
11
+ (?::(?:(?::${P}){0,5}:${G}|(?::${P}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
12
12
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
13
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Ua=new RegExp(`(?:^${W}$)|(?:^${We}$)`),$a=new RegExp(`^${W}$`),Ba=new RegExp(`^${We}$`),mn=r=>r&&r.exact?Ua:new RegExp(`(?:${dt(r)}${W}${dt(r)})|(?:${dt(r)}${We}${dt(r)})`,"g");mn.v4=r=>r&&r.exact?$a:new RegExp(`${dt(r)}${W}${dt(r)}`,"g");mn.v6=r=>r&&r.exact?Ba:new RegExp(`${dt(r)}${We}${dt(r)}`,"g");var gn=mn;function wn(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function zo(){return!1}var{toString:za}=Object.prototype;function bn(r){return za.call(r)==="[object RegExp]"}var Mo={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function yn(r,t={}){if(!bn(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(Mo).map(o=>(typeof t[o]=="boolean"?t[o]:r[o])?Mo[o]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function xn(r,t,{timeout:e}={}){try{return wn(()=>yn(r).test(t),{timeout:e})()}catch(n){if(zo(n))return!1;throw n}}var Ma=15,qa=45,qo={timeout:400};function vn(r){return r.length>qa?!1:xn(gn.v6({exact:!0}),r,qo)}function Vo(r){return r.length>Ma?!1:xn(gn.v4({exact:!0}),r,qo)}var jo={http:"80",https:"443",ws:"80",wss:"443"},Va=["http","https","ws","wss"];function Ge(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=ja(r),a=[Ha(o,e),Wa(s,n),Ga(n)];i!=null&&a.push(Qa(i));let c="/"+a.filter(l=>!!l).reduce((l,f)=>l.concat(f),[]).join("/");return Bt(c)}function ja(r){let[t]=r.split(":");Va.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=Xa(t);c!=null&&(o=c),c==null&&e==="http:"&&(o="80")}let a;return s!=null&&s!==""&&s!=="/"&&(s.startsWith("/")&&(s=s.substring(1)),a=s),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:t,hostname:n,port:o,path:a}}function Ha(r,t){if(!(r==null||r==="")){if(Vo(r))return["ip4",r];if(vn(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(vn(e))return["ip6",e]}return[t,r]}}function Wa(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function Ga(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function Qa(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function Xa(r){if(!(r==null||r===""||jo[r]==null))return jo[r]}var Ka=["https://trustless-gateway.link","https://4everland.io"],Ja=2336;function Ya(r){return r=r.toString(),{id:T.createV1(Ja,Kt.digest(I(r))),multiaddrs:[Ge(r)]}}function Za(r){return new URL(Z(r.id.multihash.digest))}var En=class{name="fallback-router";gateways;shuffle;constructor(t={}){this.gateways=(t.gateways??Ka).map(e=>Ya(e)),this.shuffle=t.shuffle??!0}async*findProviders(t,e){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,id:n.id,protocols:["transport-ipfs-gateway-http"],routing:"http-gateway-routing"}))}toString(){return`HTTPGatewayRouter([${this.gateways.map(t=>Za(t)).join(", ")}])`}};function Ho(r={}){return new En(r)}var Qe=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Xe=class extends It{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=ge(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=Gt.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o.observers++,o.promise;let s=at(),i={promise:s.promise,observers:1,queryFilter:ge(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,l=new qt({concurrency:this.maxProviders});l.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)}),l.addEventListener("success",u=>{c=!0,s.resolve(u.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.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",t);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let p=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(p)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),s.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c - %e",t,u),s.reject(u)})});let f=u=>{let p=this.toFilterKey(u.detail);i.queryFilter.has(p)||(i.queryFilter.add(p),this.emitFoundProviderProgressEvent(t,u.detail,e),l.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(S=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,S)}))};if(this.addEventListener("provider",f),a)try{await $e(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(u){throw a&&this.log("failed to find initial session peers for %c - %e",t,u),this.requests.delete(n),i.observers>1&&s.reject(u),u}Promise.all([...this.providers].filter(u=>{let p=this.toFilterKey(u),S=i.queryFilter.has(p);return S||i.queryFilter.add(this.toFilterKey(u)),!S}).map(async u=>l.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,u)});let h=()=>{s.reject(new V(e.signal?.reason??"Session aborted")),l.abort()};e.signal?.addEventListener("abort",h);try{return await s.promise}finally{this.removeEventListener("provider",f),e.signal?.removeEventListener("abort",h),l.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let o=at(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let f=await i.convertToProvider(l,"manual",n);f!=null&&(yield f)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,e,this.providers.length),this.providers.length<e)throw new Qe(`Found ${s} of ${e} ${this.name} providers for ${t}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),o.reject(i)}),o.promise}};function Wo(r){return r==null?!1:T.asCID(r)!=null}var nc=[6,53,56,54,55];function Go(r){return Ko("sni",r)?.value}function Qo(r){let t=Ko("tcp",r)?.value;return t==null?"":`:${t}`}function Ko(r,t){return t.find(e=>e.name===r)}function Xo(r){return r.some(({code:t})=>t===448)}function G(r,t){let e=Jo[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var Jo={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${G(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${G(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${G(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${G(e,t)}`},http:(r,t)=>{let e=Xo(t),n=Go(t),o=Qo(t);if(e&&n!=null)return`https://${n}${o}`;let s=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=G(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=G(e,t),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return G(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return G(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=G(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Xo(t),n=Go(t),o=Qo(t);if(e&&n!=null)return`wss://${n}${o}`;let s=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=G(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=G(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Ke(r,t){let n=Bt(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=Jo[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return t?.assumeHttp!==!1&&nc.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var Q=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};function _n(r,t,e){return r.filter(n=>{let o=Ao.exactMatch(n),s=To.exactMatch(n);if(!o&&!s)return!1;if(o||t&&s)return e||vo.matches(n)?!0:so(n)===!1;if(!t&&e){let{host:i}=we(n);if(i==="127.0.0.1"||i==="localhost"||i.endsWith(".localhost"))return!0}return!1})}async function*Je(r,t,e,n,o,s={}){for await(let i of t.findProviders(r,s)){let a=_n(i.multiaddrs,n,o);if(a.length===0)continue;let c=new URL(Ke(a[0]));yield new Ht(c,{logger:e,transformRequestInit:s.transformRequestInit,routing:i.routing})}}async function Yo(r,t,e){let{signal:n,log:o}=e??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>t)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,t),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 (${t}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new he;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>t)throw new Error(`Response body is greater than the limit (${t}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var oc=2336,Ht=class{url;peer;#t=0;#r=0;#e=0;#o=0;#n=new Map;log;transformRequestInit;routing;constructor(t,{logger:e,transformRequestInit:n,routing:o}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=o,this.peer=T.createV1(oc,Kt.digest(I(this.url.toString())))}#s(t){let e=t.multihash.bytes;return Gt.encode(e)}async getRawBlock(t,e={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${t.toString()}`;let o=e.maxSize??Zo;if(n.search="?format=raw",e.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let s=this.#s(t),i=new AbortController,a=()=>{i.abort()};e.signal?.addEventListener("abort",a);try{let c=this.#n.get(s);if(c==null){this.#t++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},f=this.transformRequestInit!=null?await this.transformRequestInit(l):l,h=new Headers(f.headers);this.log(`sending request
13
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),$a=new RegExp(`(?:^${G}$)|(?:^${We}$)`),Ba=new RegExp(`^${G}$`),za=new RegExp(`^${We}$`),mn=r=>r&&r.exact?$a:new RegExp(`(?:${dt(r)}${G}${dt(r)})|(?:${dt(r)}${We}${dt(r)})`,"g");mn.v4=r=>r&&r.exact?Ba:new RegExp(`${dt(r)}${G}${dt(r)}`,"g");mn.v6=r=>r&&r.exact?za:new RegExp(`${dt(r)}${We}${dt(r)}`,"g");var gn=mn;function wn(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function Mo(){return!1}var{toString:Ma}=Object.prototype;function bn(r){return Ma.call(r)==="[object RegExp]"}var qo={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function yn(r,t={}){if(!bn(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(qo).map(o=>(typeof t[o]=="boolean"?t[o]:r[o])?qo[o]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function xn(r,t,{timeout:e}={}){try{return wn(()=>yn(r).test(t),{timeout:e})()}catch(n){if(Mo(n))return!1;throw n}}var qa=15,Va=45,Vo={timeout:400};function vn(r){return r.length>Va?!1:xn(gn.v6({exact:!0}),r,Vo)}function jo(r){return r.length>qa?!1:xn(gn.v4({exact:!0}),r,Vo)}var Ho={http:"80",https:"443",ws:"80",wss:"443"},ja=["http","https","ws","wss"];function Ge(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=Ha(r),a=[Wa(o,e),Ga(s,n),Qa(n)];i!=null&&a.push(Xa(i));let c="/"+a.filter(l=>!!l).reduce((l,f)=>l.concat(f),[]).join("/");return Bt(c)}function Ha(r){let[t]=r.split(":");ja.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=Ka(t);c!=null&&(o=c),c==null&&e==="http:"&&(o="80")}let a;return s!=null&&s!==""&&s!=="/"&&(s.startsWith("/")&&(s=s.substring(1)),a=s),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:t,hostname:n,port:o,path:a}}function Wa(r,t){if(!(r==null||r==="")){if(jo(r))return["ip4",r];if(vn(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(vn(e))return["ip6",e]}return[t,r]}}function Ga(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function Qa(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function Xa(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function Ka(r){if(!(r==null||r===""||Ho[r]==null))return Ho[r]}var Ja=["https://trustless-gateway.link","https://4everland.io"],Ya=2336;function Za(r){return r=r.toString(),{id:T.createV1(Ya,Kt.digest(I(r))),multiaddrs:[Ge(r)]}}function tc(r){return new URL(tt(r.id.multihash.digest))}var En=class{name="fallback-router";gateways;shuffle;constructor(t={}){this.gateways=(t.gateways??Ja).map(e=>Za(e)),this.shuffle=t.shuffle??!0}async*findProviders(t,e){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,id:n.id,protocols:["transport-ipfs-gateway-http"],routing:"http-gateway-routing"}))}toString(){return`HTTPGatewayRouter([${this.gateways.map(t=>tc(t)).join(", ")}])`}};function Wo(r={}){return new En(r)}var Qe=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Xe=class extends It{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=ge(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=Gt.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o.observers++,o.promise;let s=at(),i={promise:s.promise,observers:1,queryFilter:ge(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,l=new qt({concurrency:this.maxProviders});l.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)}),l.addEventListener("success",u=>{c=!0,s.resolve(u.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.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",t);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let p=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(p)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),s.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c - %e",t,u),s.reject(u)})});let f=u=>{let p=this.toFilterKey(u.detail);i.queryFilter.has(p)||(i.queryFilter.add(p),this.emitFoundProviderProgressEvent(t,u.detail,e),l.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(S=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,S)}))};if(this.addEventListener("provider",f),a)try{await $e(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(u){throw a&&this.log("failed to find initial session peers for %c - %e",t,u),this.requests.delete(n),i.observers>1&&s.reject(u),u}Promise.all([...this.providers].filter(u=>{let p=this.toFilterKey(u),S=i.queryFilter.has(p);return S||i.queryFilter.add(this.toFilterKey(u)),!S}).map(async u=>l.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,u)});let h=()=>{s.reject(new j(e.signal?.reason??"Session aborted")),l.abort()};e.signal?.addEventListener("abort",h);try{return await s.promise}finally{this.removeEventListener("provider",f),e.signal?.removeEventListener("abort",h),l.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let o=at(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let f=await i.convertToProvider(l,"manual",n);f!=null&&(yield f)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,e,this.providers.length),this.providers.length<e)throw new Qe(`Found ${s} of ${e} ${this.name} providers for ${t}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),o.reject(i)}),o.promise}};function Go(r){return r==null?!1:T.asCID(r)!=null}var oc=[6,53,56,54,55];function Qo(r){return Jo("sni",r)?.value}function Xo(r){let t=Jo("tcp",r)?.value;return t==null?"":`:${t}`}function Jo(r,t){return t.find(e=>e.name===r)}function Ko(r){return r.some(({code:t})=>t===448)}function Q(r,t){let e=Yo[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var Yo={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Q(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${Q(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Q(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Q(e,t)}`},http:(r,t)=>{let e=Ko(t),n=Qo(t),o=Xo(t);if(e&&n!=null)return`https://${n}${o}`;let s=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Q(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Q(e,t),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Q(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Q(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Q(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Ko(t),n=Qo(t),o=Xo(t);if(e&&n!=null)return`wss://${n}${o}`;let s=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Q(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Q(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Ke(r,t){let n=Bt(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=Yo[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return t?.assumeHttp!==!1&&oc.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var X=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};function _n(r,t,e){return r.filter(n=>{let o=Do.exactMatch(n),s=Ao.exactMatch(n);if(!o&&!s)return!1;if(o||t&&s)return e||Eo.matches(n)?!0:io(n)===!1;if(!t&&e){let{host:i}=we(n);if(i==="127.0.0.1"||i==="localhost"||i.endsWith(".localhost"))return!0}return!1})}async function*Je(r,t,e,n,o,s={}){for await(let i of t.findProviders(r,s)){let a=_n(i.multiaddrs,n,o);if(a.length===0)continue;let c=new URL(Ke(a[0]));yield new Ht(c,{logger:e,transformRequestInit:s.transformRequestInit,routing:i.routing})}}async function Zo(r,t,e){let{signal:n,log:o}=e??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>t)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,t),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 (${t}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new he;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>t)throw new Error(`Response body is greater than the limit (${t}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var sc=2336,Ht=class{url;peer;#t=0;#r=0;#e=0;#o=0;#n=new Map;log;transformRequestInit;routing;constructor(t,{logger:e,transformRequestInit:n,routing:o}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=o,this.peer=T.createV1(sc,Kt.digest(I(this.url.toString())))}#s(t){let e=t.multihash.bytes;return Gt.encode(e)}async getRawBlock(t,e={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${t.toString()}`;let o=e.maxSize??ts;if(n.search="?format=raw",e.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let s=this.#s(t),i=new AbortController,a=()=>{i.abort()};e.signal?.addEventListener("abort",a);try{let c=this.#n.get(s);if(c==null){this.#t++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},f=this.transformRequestInit!=null?await this.transformRequestInit(l):l,h=new Headers(f.headers);this.log(`sending request
14
14
  %s %s HTTP/1.1
15
15
  %s
16
16
  `,f.method??"GET",n,[...h.entries()].map(([u,p])=>`${u}: ${p}`).join(`
17
- `)),e.onProgress?.(new Q("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:t})),c=fetch(n.toString(),f).then(async u=>{if(this.log(`received response
17
+ `)),e.onProgress?.(new X("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:t})),c=fetch(n.toString(),f).then(async u=>{if(this.log(`received response
18
18
  HTTP/1.1 %d %s
19
19
  %s
20
20
  `,u.status,u.statusText,[...u.headers.entries()].map(([S,R])=>`${S}: ${R}`).join(`
21
- `)),!u.ok)throw this.#r++,new Error(`Unable to fetch raw block for CID ${t} from gateway ${this.url}, received ${u.status} ${u.statusText}`);e.onProgress?.(new Q("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:Ge(n.toString()),cid:t})),e.onProgress?.(new Q("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:t}));let p=await Yo(u,o,{signal:i.signal,log:this.log});return e.onProgress?.(new Q("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:t})),this.#o++,p}),this.#n.set(s,c)}return await c}catch(c){throw e.signal?.aborted===!0?new Error(`Fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#r++,new Error(`Unable to fetch raw block for CID ${t} - ${c.message}`))}finally{e.signal?.removeEventListener("abort",a),this.#n.delete(s)}}reliability(){return this.#t===0?1:this.#e>0?-1/0:this.#o/(this.#t+this.#r*3)}incrementInvalidBlocks(){this.#e++}getStats(){return{attempts:this.#t,errors:this.#r,invalidBlocks:this.#e,successes:this.#o,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var In=class extends Xe{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Ye,this.allowLocal=e.allowLocal??Ze,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url),n?.onProgress?.(new Q("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}));let o;try{o=await e.getRawBlock(t,n),this.log.trace("got block for %c from %s",t,e.url)}finally{n?.onProgress?.(new Q("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}))}return await n.validateFn?.(o),o}async*findNewProviders(t,e={}){yield*Je(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toFilterKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e,n){if(n?.signal?.throwIfAborted(),Wo(t))return;let o=_n(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(o.length===0)return;let s=Ke(o[0]);return new Ht(s,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:e})}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new Q("trustless-gateway:found-provider",{type:"trustless-gateway",cid:t,url:e.url.toJSON(),routing:e.routing}))}};function ts(r,t){return new In(r,t)}var tr=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??Ye,this.allowLocal=e.allowLocal??Ze,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let o of Je(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,o.url);try{let s=await o.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",t,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",t,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return ts({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Ye=!1,Ze=!1,Zo=2097152;function es(r={}){return t=>new tr(t,r)}function sc(r,t){return t?.routers??[Ho(),$o({url:"https://delegated-ipfs.dev"})].forEach(e=>{r.addRouter(e)}),t?.blockBrokers??[es()].forEach(e=>{r.addBlockBroker(e)}),r}return cs(ic);})();
21
+ `)),!u.ok)throw this.#r++,new Error(`Unable to fetch raw block for CID ${t} from gateway ${this.url}, received ${u.status} ${u.statusText}`);e.onProgress?.(new X("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:Ge(n.toString()),cid:t})),e.onProgress?.(new X("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:t}));let p=await Zo(u,o,{signal:i.signal,log:this.log});return e.onProgress?.(new X("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:t})),this.#o++,p}),this.#n.set(s,c)}return await c}catch(c){throw e.signal?.aborted===!0?new Error(`Fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#r++,new Error(`Unable to fetch raw block for CID ${t} - ${c.message}`))}finally{e.signal?.removeEventListener("abort",a),this.#n.delete(s)}}reliability(){return this.#t===0?1:this.#e>0?-1/0:this.#o/(this.#t+this.#r*3)}incrementInvalidBlocks(){this.#e++}getStats(){return{attempts:this.#t,errors:this.#r,invalidBlocks:this.#e,successes:this.#o,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var In=class extends Xe{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Ye,this.allowLocal=e.allowLocal??Ze,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url),n?.onProgress?.(new X("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}));let o;try{o=await e.getRawBlock(t,n),this.log.trace("got block for %c from %s",t,e.url)}finally{n?.onProgress?.(new X("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}))}return await n.validateFn?.(o),o}async*findNewProviders(t,e={}){yield*Je(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toFilterKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e,n){if(n?.signal?.throwIfAborted(),Go(t))return;let o=_n(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(o.length===0)return;let s=Ke(o[0]);return new Ht(s,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:e})}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new X("trustless-gateway:found-provider",{type:"trustless-gateway",cid:t,url:e.url.toJSON(),routing:e.routing}))}};function es(r,t){return new In(r,t)}var tr=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??Ye,this.allowLocal=e.allowLocal??Ze,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let o of Je(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,o.url);try{let s=await o.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",t,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",t,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return es({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Ye=!1,Ze=!1,ts=2097152;function rs(r={}){return t=>new tr(t,r)}function ic(r,t){return t?.routers??[Wo(),Bo({url:"https://delegated-ipfs.dev"})].forEach(e=>{r.addRouter(e)}),t?.blockBrokers??[rs()].forEach(e=>{r.addBlockBroker(e)}),r}return ls(ac);})();
22
22
  return HeliaHttp}));
23
23
  //# sourceMappingURL=index.min.js.map