@helia/block-brokers 4.2.2-a0266903 → 4.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +4 -4
- package/dist/typedoc-urls.json +9 -0
- package/package.json +4 -4
package/dist/index.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBlockBrokers = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaBlockBrokers=(()=>{var Jo=Object.create;var ke=Object.defineProperty;var jo=Object.getOwnPropertyDescriptor;var Yo=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,ei=Object.prototype.hasOwnProperty;var us=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),$=(r,t)=>{for(var e in t)ke(r,e,{get:t[e],enumerable:!0})},hs=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Yo(t))!ei.call(r,s)&&s!==e&&ke(r,s,{get:()=>t[s],enumerable:!(n=jo(t,s))||n.enumerable});return r};var fs=(r,t,e)=>(e=r!=null?Jo(ti(r)):{},hs(t||!r||!r.__esModule?ke(e,"default",{value:r,enumerable:!0}):e,r)),ri=r=>hs(ke({},"__esModule",{value:!0}),r);var io=us((Ad,oo)=>{oo.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Oo=us(ve=>{(function(){var r,t,e,n,s,o,i,a;a=function(c){var l,u,h,f;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,f=c&255,[l,u,h,f].join(".")},i=function(c){var l,u,h,f,E,p;for(l=[],h=f=0;f<=3&&c.length!==0;h=++f){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),E=p[0],u=p[1],c=c.substring(u),l.push(E)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),o=e("a"),s=e("A"),t=function(c){var l,u,h,f,E;for(f=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),E=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)f=f*l+(e(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")f=f*l+(10+e(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")f=f*l+(10+e(c[h])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");h++}if(h===E)throw new Error("empty octet");return[f,h]},r=function(){function c(l,u){var h,f,E,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(x){throw h=x,new Error("Invalid mask: "+u)}for(f=E=32;E>=0;f=--E)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(x){throw h=x,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,h,f;for(f=i(this.first),h=i(this.last),u=0;f<=h;)l(a(f),f,u),u++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),ve.ip2long=i,ve.long2ip=a,ve.Netmask=r}).call(ve)});var ol={};$(ol,{bitswap:()=>ho,trustlessGateway:()=>Ko});var ni=Symbol.for("@libp2p/peer-id");function De(r){return!!r?.[ni]}var K=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Ae=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var Ce=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var Te=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},Le=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var rt=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){super.addEventListener(t,e,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function ds(r){let t=new globalThis.AbortController;function e(){t.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function N(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Pe=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 Pe(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 Pe(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 Lr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ne(r={}){return si(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 si(r,t){t=t??{};let e=t.onEnd,n=new Mt,s,o,i,a=N(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,C)=>{o=B=>{o=null,n.push(B);try{m(r(n))}catch(L){C(L)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=N()})}},l=m=>o!=null?o(m):(n.push(m),s),u=m=>(n=new Mt,o!=null?o({error:m}):(n.push({error:m}),s)),h=m=>{if(i)return s;if(t?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},f=m=>i?s:(i=!0,m!=null?u(m):l({done:!0})),E=()=>(n=new Mt,f(),{done:!0}),p=m=>(f(m),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:E,throw:p,push:h,end:f,get readableLength(){return n.size},onEmpty:async m=>{let C=m?.signal;if(C?.throwIfAborted(),n.isEmpty())return;let B,L;C!=null&&(B=new Promise((z,G)=>{L=()=>{G(new Lr)},C.addEventListener("abort",L)}));try{await Promise.race([a.promise,B])}finally{L!=null&&C!=null&&C?.removeEventListener("abort",L)}}},e==null)return s;let x=s;return s={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(m){return x.throw(m),e!=null&&(e(m),e=void 0),{done:!0}},return(){return x.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(m){return x.end(m),e!=null&&(e(m),e=void 0),s},get readableLength(){return x.readableLength},onEmpty:m=>x.onEmpty(m)},s}var Pr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function J(r,t,e,n){let s=new Pr(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=h=>{try{if(n?.filter?.(h)===!1)return}catch(f){a(),i(f);return}a(),o(h)},l=h=>{a(),i(h.detail)},u=()=>{a(),i(s)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}function Nr(r,t){let e,n=function(){let s=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(s,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Re=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Oe=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Me(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Oe(e?.errorMessage,e?.errorCode,e?.errorName));let n,s=new Oe(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Ue=class{deferred;signal;constructor(t){this.signal=t,this.deferred=N(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new K)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function oi(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Fe=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=oi(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,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 K),this.cleanup())}async join(t={}){let e=new Ue(t.signal);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 Me(this.fn({...this.options??{},signal:this.controller.signal}),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 Ut=class extends rt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,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=Nr(this.emitEmpty.bind(this),1),this.emitIdle=Nr(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let 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 Re;let n=new Fe(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),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 o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new K)}),this.clear()}async onEmpty(t){this.size!==0&&await J(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await J(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await J(this,"idle",t?.signal)}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=Ne({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},o=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new K("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var Be=class extends Ut{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function ii(r){return r[Symbol.asyncIterator]!=null}function ai(r){if(ii(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Rr=ai;function R(r=0){return new Uint8Array(r)}function O(r=0){return new Uint8Array(r)}var ci=Math.pow(2,7),li=Math.pow(2,14),ui=Math.pow(2,21),Or=Math.pow(2,28),Mr=Math.pow(2,35),Ur=Math.pow(2,42),Fr=Math.pow(2,49),b=128,M=127;function v(r){if(r<ci)return 1;if(r<li)return 2;if(r<ui)return 3;if(r<Or)return 4;if(r<Mr)return 5;if(r<Ur)return 6;if(r<Fr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ft(r,t,e=0){switch(v(r)){case 8:t[e++]=r&255|b,r/=128;case 7:t[e++]=r&255|b,r/=128;case 6:t[e++]=r&255|b,r/=128;case 5:t[e++]=r&255|b,r/=128;case 4:t[e++]=r&255|b,r>>>=7;case 3:t[e++]=r&255|b,r>>>=7;case 2:t[e++]=r&255|b,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function hi(r,t,e=0){switch(v(r)){case 8:t.set(e++,r&255|b),r/=128;case 7:t.set(e++,r&255|b),r/=128;case 6:t.set(e++,r&255|b),r/=128;case 5:t.set(e++,r&255|b),r/=128;case 4:t.set(e++,r&255|b),r>>>=7;case 3:t.set(e++,r&255|b),r>>>=7;case 2:t.set(e++,r&255|b),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Br(r,t){let e=r[t],n=0;if(n+=e&M,e<b||(e=r[t+1],n+=(e&M)<<7,e<b)||(e=r[t+2],n+=(e&M)<<14,e<b)||(e=r[t+3],n+=(e&M)<<21,e<b)||(e=r[t+4],n+=(e&M)*Or,e<b)||(e=r[t+5],n+=(e&M)*Mr,e<b)||(e=r[t+6],n+=(e&M)*Ur,e<b)||(e=r[t+7],n+=(e&M)*Fr,e<b))return n;throw new RangeError("Could not decode varint")}function fi(r,t){let e=r.get(t),n=0;if(n+=e&M,e<b||(e=r.get(t+1),n+=(e&M)<<7,e<b)||(e=r.get(t+2),n+=(e&M)<<14,e<b)||(e=r.get(t+3),n+=(e&M)<<21,e<b)||(e=r.get(t+4),n+=(e&M)*Or,e<b)||(e=r.get(t+5),n+=(e&M)*Mr,e<b)||(e=r.get(t+6),n+=(e&M)*Ur,e<b)||(e=r.get(t+7),n+=(e&M)*Fr,e<b))return n;throw new RangeError("Could not decode varint")}function ze(r,t,e=0){return t==null&&(t=O(v(r))),t instanceof Uint8Array?Ft(r,t,e):hi(r,t,e)}function bt(r,t=0){return r instanceof Uint8Array?Br(r,t):fi(r,t)}function ht(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=O(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function j(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 ms=Symbol.for("@achingbrain/uint8arraylist");function ps(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function $e(r){return!!r?.[ms]}var ft=class r{bufs;length;[ms]=!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($e(n))e+=n.byteLength,this.bufs.push(...n.bufs);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($e(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=ps(this.bufs,t);return e.buf[e.index]}set(t,e){let n=ps(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($e(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:s}=this._subList(t,e);return ht(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:ht(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_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=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){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(u){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(!$e(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 s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<s;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let E=this.get(h+f);if(n[f]!==E){u=Math.max(1,f-a[E]);break}}if(u===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=O(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 s=R(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,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 s=R(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,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 s=R(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,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=O(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 s=R(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,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 s=R(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,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 s=R(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,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 s=R(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,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 s=R(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,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(!j(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((s,o)=>s+o.byteLength,0)),n.length=e,n}};var He=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Bt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ve=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},se=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function qe(r){return r[Symbol.asyncIterator]!=null}function gs(r,t){if(r.byteLength>t)throw new Bt("Message length too long")}var Ge=r=>{let t=v(r),e=O(t);return ze(r,e),Ge.bytes=t,e};Ge.bytes=0;function Xe(r,t){t=t??{};let e=t.lengthEncoder??Ge,n=t?.maxDataLength??4194304;function*s(o){gs(o,n);let i=e(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return qe(r)?async function*(){for await(let o of r)yield*s(o)}():function*(){for(let o of r)yield*s(o)}()}Xe.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Ge,n=t?.maxDataLength??4194304;return gs(r,n),new ft(e(r.byteLength),r)};var yt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(yt||(yt={}));var $r=r=>{let t=bt(r);return $r.bytes=v(t),t};$r.bytes=0;function oe(r,t){let e=new ft,n=yt.LENGTH,s=-1,o=t?.lengthDecoder??$r,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===yt.LENGTH)try{if(s=o(e),s<0)throw new He("Invalid message length");if(s>a)throw new Bt("Message length too long");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=yt.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Ve("Message length length too long");break}throw l}if(n===yt.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=yt.LENGTH}}}return qe(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new se("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new se("Unexpected end of input")}()}oe.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}}();return oe(n,{...t??{},onLength:o=>{e=o}})};function mi(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var ws=mi;function gi(r){return r[Symbol.asyncIterator]!=null}function wi(r,t){let e=0;if(gi(r))return async function*(){for await(let c of r)yield t(c,e++)}();let n=ws(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=t(s,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 bs=wi;var Hr=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=N(),this.haveNext=N()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=N(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=N(),await Me(this.readNext.promise,e?.signal,e)}};function ys(){return new Hr}function bi(r){return r[Symbol.asyncIterator]!=null}async function yi(r,t,e){try{await Promise.all(r.map(async n=>{for await(let s of n)await t.push(s,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*xi(r){let t=new AbortController,e=ys();yi(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*Ei(r){for(let t of r)yield*t}function _i(...r){let t=[];for(let e of r)bi(e)||t.push(e);return t.length===r.length?Ei(t):xi(r)}var xs=_i;function qr(r,...t){if(r==null)throw new Error("Empty pipeline");if(Vr(r)){let n=r;r=()=>n.source}else if(_s(r)||Es(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Vr(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Vr(e[n])&&(e[n]=Si(e[n]));return vi(...e)}var vi=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Es=r=>r?.[Symbol.asyncIterator]!=null,_s=r=>r?.[Symbol.iterator]!=null,Vr=r=>r==null?!1:r.sink!=null&&r.source!=null,Si=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ne({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Es(o))s=async function*(){yield*o,n.end()};else if(_s(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return xs(n,s())}return r.source};function Ii(r){return r[Symbol.asyncIterator]!=null}function ki(r,t){return Ii(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var vs=ki;var nt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var ie="/ipfs/bitswap/1.2.0";var Wr=new Float32Array([-0]),dt=new Uint8Array(Wr.buffer);function Ss(r,t,e){Wr[0]=r,t[e]=dt[0],t[e+1]=dt[1],t[e+2]=dt[2],t[e+3]=dt[3]}function Is(r,t){return dt[0]=r[t],dt[1]=r[t+1],dt[2]=r[t+2],dt[3]=r[t+3],Wr[0]}var Gr=new Float64Array([-0]),U=new Uint8Array(Gr.buffer);function ks(r,t,e){Gr[0]=r,t[e]=U[0],t[e+1]=U[1],t[e+2]=U[2],t[e+3]=U[3],t[e+4]=U[4],t[e+5]=U[5],t[e+6]=U[6],t[e+7]=U[7]}function Ds(r,t){return U[0]=r[t],U[1]=r[t+1],U[2]=r[t+2],U[3]=r[t+3],U[4]=r[t+4],U[5]=r[t+5],U[6]=r[t+6],U[7]=r[t+7],Gr[0]}var Di=BigInt(Number.MAX_SAFE_INTEGER),Ai=BigInt(Number.MIN_SAFE_INTEGER),H=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return xt;if(t<Di&&t>Ai)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>As&&(s=0n,++n>As&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return xt;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):xt}},xt=new H(0,0);xt.toBigInt=function(){return 0n};xt.zzEncode=xt.zzDecode=function(){return this};xt.length=function(){return 1};var As=4294967296n;function Cs(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Ts(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Xr(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function Y(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Qe(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Qr=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Y(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Y(this,4);return Qe(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Y(this,4);return Qe(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Y(this,4);let t=Is(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Y(this,4);let t=Ds(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Y(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ts(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Y(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Y(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new H(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Y(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Y(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Y(this,8);let t=Qe(this.buf,this.pos+=4),e=Qe(this.buf,this.pos+=4);return new H(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Br(this.buf,this.pos);return this.pos+=v(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Zr(r){return new Qr(r instanceof Uint8Array?r:r.subarray())}function Et(r,t,e){let n=Zr(r);return t.decode(n,void 0,e)}var tn={};$(tn,{base10:()=>Oi});var Ru=new Uint8Array(0);function Ps(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 r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ns(r){return new TextEncoder().encode(r)}function Rs(r){return new TextDecoder().decode(r)}function Ci(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var x=0,m=0,C=0,B=p.length;C!==B&&p[C]===0;)C++,x++;for(var L=(B-C)*u+1>>>0,z=new Uint8Array(L);C!==B;){for(var G=p[C],ut=0,Z=L-1;(G!==0||ut<m)&&Z!==-1;Z--,ut++)G+=256*z[Z]>>>0,z[Z]=G%a>>>0,G=G/a>>>0;if(G!==0)throw new Error("Non-zero carry");m=ut,C++}for(var st=L-m;st!==L&&z[st]===0;)st++;for(var Ie=c.repeat(x);st<L;++st)Ie+=r.charAt(z[st]);return Ie}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var x=0;if(p[x]!==" "){for(var m=0,C=0;p[x]===c;)m++,x++;for(var B=(p.length-x)*l+1>>>0,L=new Uint8Array(B);p[x];){var z=e[p.charCodeAt(x)];if(z===255)return;for(var G=0,ut=B-1;(z!==0||G<C)&&ut!==-1;ut--,G++)z+=a*L[ut]>>>0,L[ut]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");C=G,x++}if(p[x]!==" "){for(var Z=B-C;Z!==B&&L[Z]===0;)Z++;for(var st=new Uint8Array(m+(B-Z)),Ie=m;Z!==B;)st[Ie++]=L[Z++];return st}}}function E(p){var x=f(p);if(x)return x;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:E}}var Ti=Ci,Li=Ti,Ms=Li;var Kr=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")}},Jr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 Us(this,t)}},jr=class{decoders;constructor(t){this.decoders=t}or(t){return Us(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 Us(r,t){return new jr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Yr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new Kr(t,e,n),this.decoder=new Jr(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function zt({name:r,prefix:t,encode:e,decode:n}){return new Yr(r,t,e,n)}function pt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Ms(e,r);return zt({prefix:t,name:r,encode:n,decode:o=>ot(s(o))})}function Pi(r,t,e,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Ni(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;(o.length*e&7)!==0;)o+="=";return o}function Ri(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function I({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let s=Ri(n);return zt({prefix:t,name:r,encode(o){return Ni(o,n,e)},decode(o){return Pi(o,s,e,r)}})}var Oi=pt({prefix:"9",name:"base10",alphabet:"0123456789"});var en={};$(en,{base16:()=>Mi,base16upper:()=>Ui});var Mi=I({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ui=I({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rn={};$(rn,{base2:()=>Fi});var Fi=I({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var nn={};$(nn,{base256emoji:()=>Vi});var Fs=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}"),Bi=Fs.reduce((r,t,e)=>(r[e]=t,r),[]),zi=Fs.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function $i(r){return r.reduce((t,e)=>(t+=Bi[e],t),"")}function Hi(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=zi[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var Vi=zt({prefix:"\u{1F680}",name:"base256emoji",encode:$i,decode:Hi});var sn={};$(sn,{base32:()=>mt,base32hex:()=>Xi,base32hexpad:()=>Zi,base32hexpadupper:()=>Ki,base32hexupper:()=>Qi,base32pad:()=>Wi,base32padupper:()=>Gi,base32upper:()=>qi,base32z:()=>Ji});var mt=I({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),qi=I({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wi=I({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Gi=I({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xi=I({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qi=I({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zi=I({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ki=I({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ji=I({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var on={};$(on,{base36:()=>ae,base36upper:()=>ji});var ae=pt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ji=pt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var an={};$(an,{base58btc:()=>V,base58flickr:()=>Yi});var V=pt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Yi=pt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ln={};$(ln,{base64:()=>it,base64pad:()=>ta,base64url:()=>cn,base64urlpad:()=>ea});var it=I({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ta=I({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cn=I({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ea=I({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var un={};$(un,{base8:()=>ra});var ra=I({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var hn={};$(hn,{identity:()=>na});var na=zt({prefix:"\0",name:"identity",encode:r=>Rs(r),decode:r=>Ns(r)});var Ku=new TextEncoder,Ju=new TextDecoder;var pn={};$(pn,{identity:()=>ka});var ia=$s,Bs=128,aa=127,ca=~aa,la=Math.pow(2,31);function $s(r,t,e){t=t||[],e=e||0;for(var n=e;r>=la;)t[e++]=r&255|Bs,r/=128;for(;r&ca;)t[e++]=r&255|Bs,r>>>=7;return t[e]=r|0,$s.bytes=e-n+1,t}var ua=fn,ha=128,zs=127;function fn(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw fn.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&zs)<<s:(i&zs)*Math.pow(2,s),s+=7}while(i>=ha);return fn.bytes=o-n,e}var fa=Math.pow(2,7),da=Math.pow(2,14),pa=Math.pow(2,21),ma=Math.pow(2,28),ga=Math.pow(2,35),wa=Math.pow(2,42),ba=Math.pow(2,49),ya=Math.pow(2,56),xa=Math.pow(2,63),Ea=function(r){return r<fa?1:r<da?2:r<pa?3:r<ma?4:r<ga?5:r<wa?6:r<ba?7:r<ya?8:r<xa?9:10},_a={encode:ia,decode:ua,encodingLength:Ea},va=_a,ce=va;function le(r,t=0){return[ce.decode(r,t),ce.decode.bytes]}function $t(r,t,e=0){return ce.encode(r,t,e),t}function Ht(r){return ce.encodingLength(r)}function _t(r,t){let e=t.byteLength,n=Ht(r),s=n+Ht(e),o=new Uint8Array(s+e);return $t(r,o,0),$t(e,o,n),o.set(t,s),new Vt(r,e,t,o)}function dn(r){let t=ot(r),[e,n]=le(t),[s,o]=le(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Vt(e,s,i,t)}function Hs(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ps(r.bytes,e.bytes)}}var Vt=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};var Vs=0,Sa="identity",qs=ot;function Ia(r){return _t(Vs,qs(r))}var ka={code:Vs,name:Sa,encode:qs,digest:Ia};var wn={};$(wn,{sha256:()=>Ke,sha512:()=>Da});function gn({name:r,code:t,encode:e}){return new mn(r,t,e)}var mn=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?_t(this.code,e):e.then(n=>_t(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Gs(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ke=gn({name:"sha2-256",code:18,encode:Gs("SHA-256")}),Da=gn({name:"sha2-512",code:19,encode:Gs("SHA-512")});function Xs(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Ca(e,bn(r),t??V.encoder);default:return Ta(e,bn(r),t??mt.encoder)}}var Qs=new WeakMap;function bn(r){let t=Qs.get(r);if(t==null){let e=new Map;return Qs.set(r,e),e}return t}var q=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}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!==ue)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==La)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=_t(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&&Hs(t.multihash,n.multihash)}toString(t){return Xs(this,t)}toJSON(){return{"/":Xs(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:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??Zs(n,s,o.bytes))}else if(e[Pa]===!0){let{version:n,multihash:s,code:o}=e,i=dn(s);return r.create(n,o,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!==ue)throw new Error(`Version 0 CID must use dag-pb (code: ${ue}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Zs(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,ue,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,s=ot(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Vt(e.multihashCode,e.digestSize,o,s);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,f]=le(t.subarray(e));return e+=f,h},s=n(),o=ue;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,s]=Aa(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return bn(o).set(n,t),o}};function Aa(r,t){switch(r[0]){case"Q":{let e=t??V;return[V.prefix,e.decode(`${V.prefix}${r}`)]}case V.prefix:{let e=t??V;return[V.prefix,e.decode(r)]}case mt.prefix:{let e=t??mt;return[mt.prefix,e.decode(r)]}case ae.prefix:{let e=t??ae;return[ae.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 Ca(r,t,e){let{prefix:n}=e;if(n!==V.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function Ta(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var ue=112,La=18;function Zs(r,t,e){let n=Ht(r),s=n+Ht(t),o=new Uint8Array(s+e.byteLength);return $t(r,o,0),$t(t,o,n),o.set(e,s),o}var Pa=Symbol.for("@ipld/js-cid/CID");var he={...hn,...rn,...un,...tn,...en,...sn,...on,...an,...ln,...nn},yh={...wn,...pn};function Js(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ks=Js("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),yn=Js("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=O(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Na={utf8:Ks,"utf-8":Ks,hex:he.base16,latin1:yn,ascii:yn,binary:yn,...he},Je=Na;function A(r,t="utf8"){let e=Je[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function xn(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return O(i);s+i>t&&(n=O(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var vt=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function En(){}var vn=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Ra=xn();function Oa(r){return globalThis.Buffer!=null?O(r):Ra(r)}var de=class{len;head;tail;states;constructor(){this.len=0,this.head=new vt(En,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new vt(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Sn((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(je,10,H.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=H.fromBigInt(t);return this._push(je,e.length(),e)}uint64Number(t){return this._push(Ft,v(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=H.fromBigInt(t).zzEncode();return this._push(je,e.length(),e)}sint64Number(t){let e=H.fromNumber(t).zzEncode();return this._push(je,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(_n,1,t?1:0)}fixed32(t){return this._push(fe,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=H.fromBigInt(t);return this._push(fe,4,e.lo)._push(fe,4,e.hi)}fixed64Number(t){let e=H.fromNumber(t);return this._push(fe,4,e.lo)._push(fe,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Ss,4,t)}double(t){return this._push(ks,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(_n,1,0):this.uint32(e)._push(Ua,e,t)}string(t){let e=Cs(t);return e!==0?this.uint32(e)._push(Xr,e,t):this._push(_n,1,0)}fork(){return this.states=new vn(this),this.head=this.tail=new vt(En,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new vt(En,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Oa(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function _n(r,t,e){t[e]=r&255}function Ma(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Sn=class extends vt{next;constructor(t,e){super(Ma,t,e),this.next=void 0}};function je(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function fe(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Ua(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(de.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Fa,t,r),this},de.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Ba,t,r),this});function Fa(r,t,e){t.set(r,e)}function Ba(r,t,e){r.length<40?Xr(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(A(r),e)}function In(){return new de}function St(r,t){let e=In();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Wt;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Wt||(Wt={}));function Ye(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function tr(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let a=t(o);i.int32(a)},n=function(o){let i=o.int32();return t(i)};return Ye("enum",Wt.VARINT,e,n)}function It(r,t){return Ye("message",Wt.LENGTH_DELIMITED,r,t)}var Gt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var k;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(k||(k={}));var kn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(kn||(kn={}));(function(r){r.codec=()=>tr(kn)})(k||(k={}));var Xt;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.priority!=null&&e.priority!==0&&(n.uint32(16),n.int32(e.priority)),e.cancel!=null&&(n.uint32(24),n.bool(e.cancel)),e.wantType!=null&&(n.uint32(32),k.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:R(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.priority=e.int32();break}case 3:{o.cancel=e.bool();break}case 4:{o.wantType=k.codec().decode(e);break}case 5:{o.sendDontHave=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(Xt||(Xt={}));var er;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let o of e.entries)n.uint32(10),Xt.codec().encode(o,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={entries:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new Gt('Decode error - map field "entries" had too many elements');o.entries.push(Xt.codec().decode(e,e.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(er||(er={}));var Qt;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.prefix!=null&&e.prefix.byteLength>0&&(n.uint32(10),n.bytes(e.prefix)),e.data!=null&&e.data.byteLength>0&&(n.uint32(18),n.bytes(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={prefix:R(0),data:R(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.prefix=e.bytes();break}case 2:{o.data=e.bytes();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(Qt||(Qt={}));var X;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(X||(X={}));var rr;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(rr||(rr={}));(function(r){r.codec=()=>tr(rr)})(X||(X={}));var Zt;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.type!=null&&rr[e.type]!==0&&(n.uint32(16),X.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:R(0),type:X.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.type=X.codec().decode(e);break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(Zt||(Zt={}));var kt;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),er.codec().encode(e.wantlist,n)),e.blocks!=null)for(let o of e.blocks)n.uint32(26),Qt.codec().encode(o,n);if(e.blockPresences!=null)for(let o of e.blockPresences)n.uint32(34),Zt.codec().encode(o,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.wantlist=er.codec().decode(e,e.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&o.blocks.length===s.limits.blocks)throw new Gt('Decode error - map field "blocks" had too many elements');o.blocks.push(Qt.codec().decode(e,e.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&o.blockPresences.length===s.limits.blockPresences)throw new Gt('Decode error - map field "blockPresences" had too many elements');o.blockPresences.push(Zt.codec().decode(e,e.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=e.int32();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(kt||(kt={}));function js(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var nr=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var za=4193648,$a=za+16;function*Ys(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=kt.encode(l).byteLength,{added:h,hasMore:f,newSize:E}=Dn(s,l.blocks,a,t,u,Ha);a+=h,u=E;let p=f;({added:h,hasMore:f,newSize:E}=Dn(n,l.blockPresences,i,t,u,Va)),i+=h,u=E;let x=f;if({added:h,hasMore:f,newSize:E}=Dn(e,l.wantlist.entries,o,t,u,qa),o+=h,u=E,c=!p&&!x&&!f,c||(l.wantlist.full=!1),yield kt.encode(l),c)break}}function Dn(r,t,e,n,s,o){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=o(l);if(u>$a)throw new nr("Cannot send block as after encoding it is over the max message size");let h=s+u;if(h>n){a=!0;break}t.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function Ha(r){return An(3,Qt.encode(r))}function Va(r){return An(4,Zt.encode(r))}function qa(r){return An(1,Xt.encode(r))}function An(r,t){let e=v(r),n=v(t.byteLength);return e+n+t.byteLength}var sr=class extends rt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[ie],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??5e3,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Be({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t){if(!this.running)return;let{stream:e,connection:n}=t;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,n.remotePeer);let s=()=>{e.status==="open"?e.abort(new Te(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",s),await e.closeWrite(),await qr(e,i=>oe(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let a of i)try{let c=kt.decode(a);this.log("incoming new bitswap %s message from %p on stream",e.protocol,n.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),o.removeEventListener("abort",s),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",s)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,e.id,c),e.abort(c);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new nt("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})&&(yield n)}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Rr(bs(vs(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>t.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=js(s.options.message,e),await s.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let i=o?.message;if(i==null)throw new Ae("No message to send");this.log("sendMessage to %p",t),o?.onProgress?.(new nt("bitswap:network:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,ie,o);await a.closeRead();try{await qr(Ys(i,this.maxOutgoingMessageSize),c=>Xe(c),a),await a.close(o)}catch(c){o?.onProgress?.(new nt("bitswap:network:send-wantlist:error",{peer:t,error:c})),this.log.error("error sending message to %p",t,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:t,signal:n?.signal,message:e})}async connectTo(t,e){if(!this.running)throw new Le("Network isn't running");e?.onProgress?.(new nt("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),J(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(ie))return!0;throw new Ce(`${t} did not support ${ie}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};function D(r,t="utf8"){let e=Je[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function or(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var pe=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return or(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return or(this.map.values(),t=>t.key)}values(){return or(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Cn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},eo={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ro=new globalThis.TextEncoder;function Ya(r,t){let e=Cn[t],n=eo[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function tc(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Cn[t],s=eo[t],o=r;for(;o.length>0;){let i=ro.encodeInto(o,e);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function Tn(r,{size:t=32,utf8Buffer:e}={}){if(!Cn[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 tc(r,t,e);r=ro.encode(r)}return Ya(r,t)}var me={hash:r=>Number(Tn(r,{size:32})),hashV:(r,t)=>ec(me.hash(r,t))};function ec(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),A(t,"base16")}var Ln=64,tt=class{fp;h;seed;constructor(t,e,n,s=2){if(s>Ln)throw new TypeError("Invalid Fingerprint Size");let o=e.hashV(t,n),i=R(s);for(let a=0;a<i.length;a++)i[a]=o[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?j(this.fp,t.fp):!1}};function Dt(r,t){return Math.floor(Math.random()*(t-r))+r}var At=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof tt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof tt))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 tt))throw new TypeError("Invalid Fingerprint");let e=Dt(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof tt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var rc=500,ge=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??me,this.seed=t.seed??Dt(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=A(t));let e=new tt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new At(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new At(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[Dt(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new At(this.bucketSize));for(let a=0;a<rc;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 At(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=A(t));let e=new tt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let o=(n^e.hash())%this.filterSize;return this.buckets[o]?.has(e)??!1}remove(t){typeof t=="string"&&(t=A(t));let e=new tt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let o=(n^e.hash())%this.filterSize,i=this.buckets[o]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},nc={1:.5,2:.84,4:.95,8:.98};function sc(r=.001){return r>.002?2:r>1e-5?4:8}function no(r,t=.001){let e=sc(t),n=nc[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Ln);return{filterSize:s,bucketSize:e,fingerprintSize:o}}var ir=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??me,this.seed=t.seed??Dt(0,Math.pow(2,10)),this.filterSeries=[new ge({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=A(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 ge({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=A(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=A(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 Pn(r,t=.001,e){return new ir({...no(r,t),...e??{}})}var Nn=class extends pe{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function we(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Nn({name:t,metrics:e}):n=new pe,n}var at=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=it.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=it.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=it.encode(t.multihash.bytes);this.blocks.set(n,e)}};function oc(r){let t=new Uint8Array(r.reduce((n,s)=>n+v(s),0)),e=0;for(let n of r)t=ze(n,t,e),e+=v(n);return t}var so=oc;function Rn(r){return so([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var ar=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(t){let e=new at,n=new Set;for(let[s,o]of this.wants.entries())try{let i=await this.blockstore.get(o.cid,t);o.wantType===k.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:Rn(o.cid)})):(this.log("sending have for %c",o.cid),e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:X.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:Rn(o.cid)}))}catch(i){if(i.name!=="NotFoundError")throw i;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDoNotHave===!0)continue;o.sentDoNotHave=!0,e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:X.DoNotHaveBlock})}if(e.blocks.size>0||e.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((s,o)=>s+o.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var cr=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=we({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return[...e.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);if(n==null&&(n=new ar({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let o=q.decode(s.cid),i=D(o.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,o),n.wants.delete(i)):(s.wantType===k.WantHave?this.log("peer %p wanted block presence for %c",t,o):this.log("peer %p wanted block for %c",t,o),n.wants.set(i,{cid:o,priority:s.priority,wantType:s.wantType??k.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=D(t.multihash.bytes,"base64"),s=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&s.push(o);await Promise.all(s.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var cc=fs(io(),1);var Kt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Kt||(Kt={}));var lr=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Ct=class extends rt{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(t,e){super(),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=Pn(this.maxProviders),this.initialProviders=e.providers??[]}async retrieve(t,e={}){let n=it.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let o=N();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.initialPeerSearchComplete,u&&this.log("found initial session peers for %c",t)}let i=!1,a=new Ut({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),a.addEventListener("success",u=>{i=!0,o.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(i||e.signal?.aborted===!0){this.log.trace("session idle, found block");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 h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c",t,u),o.reject(u)})});let c=u=>{a.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,h)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,u)});let l=()=>{o.reject(new K(e.signal?.reason??"Session aborted")),a.abort()};e.signal?.addEventListener("abort",l);try{return await o.promise}finally{this.removeEventListener("provider",c),e.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(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.toEvictionKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let s=N(),o=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t),this.initialProviders.length>0)for(;o<e&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let i of this.findNewProviders(t,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<e)throw new lr(`Found ${o} of ${e} ${this.name} providers for ${t}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",t,i.errors??i),s.reject(i)}),s.promise}};var On=class extends Ct{wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield n.id}toEvictionKey(t){return t.toMultihash().bytes}equals(t,e){return t.equals(e)}async convertToProvider(t,e){return De(t)?t:(await this.libp2p.dial(t,e)).remotePeer}};function ao(r,t){return new On(r,t)}var ur=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};var Mn=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function co(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Mn({name:t,metrics:e}):n=new Map,n}function hc(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=bt(r);t.push(e),r=r.slice(v(e))}return t}var lo=hc;var hr=class extends rt{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),this.peers=we({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=co({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendMessagesDelay=e.sendMessagesDelay??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=e.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=D(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??k.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===k.WantHave&&e.wantType===k.WantBlock&&(s.wantType=k.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===k.WantBlock?(await J(this,"block",e?.signal,{filter:a=>j(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await J(this,"presence",e?.signal,{filter:i=>j(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers",t)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=N(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new at;for(let[o,i]of this.wants.entries())e.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s);for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer",o)}})).catch(t=>{this.log.error("error sending messages",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=D(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:k.WantHave,priority:1}),await this.network.sendMessage(e,s),(await J(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&j(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:k.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:k.WantBlock,priority:1}),await this.network.sendMessage(e,s),(await J(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&j(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=D(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=lo(s.prefix),i=o[0],a=o[1],c=o[2],l=c===Ke.code?Ke:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let u=l.digest(s.data);u.then!=null&&(u=await u);let h=q.create(i===0?0:1,a,u);this.log("received block from %p for %c",t,h),this.safeDispatchEvent("block",{detail:{sender:t,cid:h,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:h,has:!0,block:s.data}});let f=D(h.multihash.bytes,"base64"),E=this.wants.get(f);E!=null&&(E.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=q.decode(s);this.log("received %s from %p for %c",o,t,i),this.safeDispatchEvent("presence",{detail:{sender:t,cid:i,has:o===X.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new at(!0);for(let[s,o]of this.wants.entries())o.cancel||(e.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:k.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var fr=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new ur(t),this.network=new sr(t,e),this.peerWantLists=new cr({...t,network:this.network},e),this.wantList=new hr({...t,network:this.network},e)}createSession(t={}){return ao({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,s=ds([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,o)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await Promise.all([this.peerWantLists.receivedBlock(t,n),this.wantList.receivedBlock(t,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var uo=(r,t={})=>new fr(r,t);var Un=class{bitswap;started;constructor(t,e={}){let{getHasher:n}=t;this.bitswap=uo(t,{hashLoader:{getHasher:async s=>n(s)},...e}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e,n){await this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}createSession(t){let e=this.bitswap.createSession(t);return{announce:async(n,s,o)=>{await this.bitswap.notify(n,s,o)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function ho(r={}){return t=>new Un(t,r)}var P=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ct=class extends Error{static name="ValidationError";name="ValidationError"},be=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},dr=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var pr=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,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=t,o+=u,o>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:o})}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 s=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return e.set(o.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var fc=45,dc=15,mr=new pr;function Fn(r){if(!(r.length>dc))return mr.new(r).parseWith(()=>mr.readIPv4Addr())}function Bn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>fc))return mr.new(r).parseWith(()=>mr.readIPv6Addr())}function Jt(r){return!!Fn(r)}function gr(r){return!!Bn(r)}function $n(r){return t=>D(t,r)}function Hn(r){return t=>A(t,r)}function jt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Tt(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function po(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=A(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 s=Tt(n);return ht([e,s],e.length+s.length)}function mo(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=mt.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 s=Tt(n);return ht([e,s],e.length+s.length)}function Vn(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=D(t,"base32"),s=jt(e);return`${n}:${s}`}var qn=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let s=parseInt(e,10);if(isNaN(s)||s<0||s>255)throw new P("Invalid byte value in IP address");t[n]=s}),t},go=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=Jt(e[n]),i;o&&(i=qn(e[n]),e[n]=D(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,D(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 o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let o=parseInt(e[n],16);if(isNaN(o)||o<0||o>65535)throw new P("Invalid byte value in IP address");s[t++]=o>>8&255,s[t++]=o&255}return s},wo=function(r){if(r.byteLength!==4)throw new P("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},bo=function(r){if(r.byteLength!==16)throw new P("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.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 P(`Invalid IPv6 address "${e}"`)}};function yo(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new P(`Invalid IPv6 address "${r}"`)}}var zn=Object.values(he).map(r=>r.decoder),pc=function(){let r=zn[0].or(zn[1]);return zn.slice(2).forEach(t=>r=r.or(t)),r}();function xo(r){return pc.decode(r)}function Eo(r){return t=>r.encoder.encode(t)}function mc(r){if(parseInt(r).toString()!==r)throw new ct("Value must be an integer")}function gc(r){if(r<0)throw new ct("Value must be a positive integer, or zero")}function wc(r){return t=>{if(t>r)throw new ct(`Value must be smaller than or equal to ${r}`)}}function bc(...r){return t=>{for(let e of r)e(t)}}var ye=bc(mc,gc,wc(65535));var T=-1,Wn=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 dr(`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)}))}},W=new Wn,Nc=[{code:4,name:"ip4",size:32,valueToBytes:qn,bytesToValue:wo,validate:r=>{if(!Jt(r))throw new ct(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Tt,bytesToValue:jt,validate:ye},{code:273,name:"udp",size:16,valueToBytes:Tt,bytesToValue:jt,validate:ye},{code:33,name:"dccp",size:16,valueToBytes:Tt,bytesToValue:jt,validate:ye},{code:41,name:"ip6",size:128,valueToBytes:go,bytesToValue:bo,stringToValue:yo,validate:r=>{if(!gr(r))throw new ct(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:T},{code:43,name:"ipcidr",size:8,bytesToValue:$n("base10"),valueToBytes:Hn("base10")},{code:53,name:"dns",size:T,resolvable:!0},{code:54,name:"dns4",size:T,resolvable:!0},{code:55,name:"dns6",size:T,resolvable:!0},{code:56,name:"dnsaddr",size:T,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Tt,bytesToValue:jt,validate:ye},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:T,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:T,bytesToValue:$n("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Hn("base58btc")(r):q.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Vn,valueToBytes:po},{code:445,name:"onion3",size:296,bytesToValue:Vn,valueToBytes:mo},{code:446,name:"garlic64",size:T},{code:447,name:"garlic32",size:T},{code:448,name:"tls"},{code:449,name:"sni",size:T},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:T,bytesToValue:Eo(cn),valueToBytes:xo},{code:480,name:"http"},{code:481,name:"http-path",size:T,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:T}];Nc.forEach(r=>{W.addProtocol(r)});function _o(r){let t=[],e=0;for(;e<r.length;){let n=bt(r,e),s=W.getProtocol(n),o=v(n),i=Rc(s,r,e+o),a=0;i>0&&s.size===T&&(a=v(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??D(h)}t.push(l),e+=c}return t}function vo(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let s=W.getProtocol(n.code),o=v(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??A(n.value),a=i.byteLength,s.size===T&&(c=v(a)));let l=new Uint8Array(o+c+a),u=0;Ft(n.code,l,u),u+=o,i!=null&&(s.size===T&&(Ft(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return ht(e,t)}function So(r){if(r.charAt(0)!=="/")throw new P('String multiaddr must start with "/"');let t=[],e="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(e==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=W.getProtocol(s);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",s="",e="protocol";continue}else if(a)throw new P(`Component ${s} 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 P(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",s="",e="protocol"}}}if(s!==""&&n!=="")throw new P("Incomplete multiaddr");return t}function Io(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=W.getProtocol(t.code);if(e==null)throw new P(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function Rc(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:bt(t,e)}var Oc=Symbol.for("nodejs.util.inspect.custom"),es=Symbol.for("@multiformats/multiaddr"),Mc=[53,54,55,56],ts=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function Uc(r){if(r==null&&(r="/"),Do(r))return r.getComponents();if(r instanceof Uint8Array)return _o(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),So(r);if(Array.isArray(r))return r;throw new P("Must be a string, Uint8Array, Component[], or another Multiaddr")}var xr=class r{[es]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=Uc(t),e.validate!==!1&&Fc(this)}get bytes(){return this.#r==null&&(this.#r=vo(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Io(this.#t)),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,s,o="";for(let{code:a,name:c,value:l}of this.#t)a===42&&(o=`%${l??""}`),Mc.includes(a)&&(e="tcp",s=443,n=`${l??""}${o}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",s=parseInt(l??"")),(a===4||a===41)&&(e="tcp",n=`${l??""}${o}`,t=a===41?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=W.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=W.getProtocol(t),s=[t];return e!=null&&s.push(n.valueToBytes?.(e)??A(e)),s})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}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(),s=n.lastIndexOf(e);if(s<0)throw new be(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,s),{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})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:s})=>{n===421&&t.push([n,s]),n===290&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?D(V.decode(`z${n}`),"base58btc"):D(q.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(W.getProtocol(t.code).path)return t.value??null;return null}equals(t){return j(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(o=>o.resolvable);if(e==null)return[this];let n=ko.get(e.name);if(n==null)throw new ts(`no available resolver for ${e.name}`);return(await n(this,t)).map(o=>_e(o))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[Oc](){return`Multiaddr(${this.toString()})`}};function Fc(r){r.getComponents().forEach(t=>{let e=W.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}var Cm=parseInt("0xFFFF",16),Tm=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ko=new Map;function Do(r){return!!r?.[es]}function _e(r){return new xr(r)}var Vc=[6,53,56,54,55];function To(r){return No("sni",r)?.value}function Lo(r){let t=No("tcp",r)?.value;return t==null?"":`:${t}`}function No(r,t){return t.find(e=>e.name===r)}function Po(r){return r.some(({code:t})=>t===448)}function et(r,t){let e=Ro[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 Ro={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://${et(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${et(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`${et(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${et(e,t)}`},http:(r,t)=>{let e=Po(t),n=To(t),s=Lo(t);if(e&&n!=null)return`https://${n}${s}`;let o=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=et(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=et(e,t),s=decodeURIComponent(r.value??"");return`${n}${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return et(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return et(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=et(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Po(t),n=To(t),s=Lo(t);if(e&&n!=null)return`wss://${n}${s}`;let o=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=et(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=et(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Er(r,t){let n=_e(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=Ro[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return t?.assumeHttp!==!1&&Vc.includes(s.code)&&(i=i.replace(/^.*:\/\//,""),s.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 Mo=fs(Oo(),1),qc=["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"],Wc=qc.map(r=>new Mo.Netmask(r));function rs(r){for(let t of Wc)if(t.contains(r))return!0;return!1}function Gc(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Xc(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"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return rs(s)}function Qc(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Zc(r){let t=r.split(":"),e=t[t.length-1];return rs(e)}function Kc(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 Uo(r){if(Jt(r))return rs(r);if(Gc(r))return Xc(r);if(Qc(r))return Zc(r);if(gr(r))return Kc(r)}var S=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)}}),g=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),F=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1}}),y=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function _(...r){function t(s){let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:r,matches:e,exactMatch:n}}var Jc=d(421),vg=_(Jc),vr=d(54),Sr=d(55),Ir=d(56),ss=d(53),Sg=_(vr,g(d(421))),Ig=_(Sr,g(d(421))),kg=_(Ir,g(d(421))),Fo=_(F(ss,Ir,vr,Sr),g(d(421))),Bo=y(d(4),g(d(43))),zo=y(g(d(42)),d(41),g(d(43))),os=F(Bo,zo),Ot=F(os,ss,vr,Sr,Ir),Dg=_(F(os,y(F(ss,Ir,vr,Sr),g(d(421))))),Ag=_(Bo),Cg=_(zo),Tg=_(os),is=y(Ot,d(6)),Se=y(Ot,d(273)),Lg=_(y(is,g(d(421)))),Pg=_(Se),as=y(Se,S(460),g(d(421))),kr=y(Se,S(461),g(d(421))),jc=F(as,kr),Ng=_(as),Rg=_(kr),ns=F(Ot,is,Se,as,kr),$o=F(y(ns,S(477),g(d(421)))),Og=_($o),Ho=F(y(ns,S(478),g(d(421))),y(ns,S(448),g(d(449)),S(477),g(d(421)))),Mg=_(Ho),Vo=y(Se,S(280),g(d(466)),g(d(466)),g(d(421))),Ug=_(Vo),qo=y(kr,S(465),g(d(466)),g(d(466)),g(d(421))),Fg=_(qo),_r=F($o,Ho,y(is,g(d(421))),y(jc,g(d(421))),y(Ot,g(d(421))),Vo,qo,d(421)),Bg=_(_r),Yc=y(_r,S(290),d(421)),zg=_(Yc),tl=F(y(_r,S(290),S(281),g(d(421))),y(_r,S(281),g(d(421))),y(S(281),g(d(421)))),$g=_(tl),el=F(y(Ot,d(6),S(480),g(d(421))),y(Ot,S(480),g(d(421)))),Wo=_(el),rl=y(Ot,F(y(d(6,"443"),S(480)),y(d(6),S(443)),y(d(6),S(448),S(480)),y(S(448),S(480)),S(448),S(443)),g(d(421))),Go=_(rl),nl=F(y(d(777),g(d(421)))),Hg=_(nl),sl=F(y(d(400),g(d(421)))),Vg=_(sl);function cs(r,t,e){return r.filter(n=>{if(Go.matches(n)||t&&Wo.matches(n))return e||Fo.matches(n)?!0:Uo(n.toOptions().host)===!1;if(!t&&e){let{host:s}=n.toOptions();if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*Dr(r,t,e,n,s,o={}){for await(let i of t.findProviders(r,o)){let a=cs(i.multiaddrs,n,s);if(a.length===0)continue;let c=Er(a[0]);yield new ne(c,{logger:e,transformRequestInit:o.transformRequestInit})}}async function Xo(r,t,e){let{signal:n,log:s}=e??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>t)throw s?.error("content-length header (%d) is greater than the limit (%d)",c,t),r.body!=null&&await r.body.cancel().catch(l=>{s?.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 ft;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=>{s?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var ne=class{url;#t=0;#e=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;constructor(t,{logger:e,transformRequestInit:n}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#o(t){let e=t.multihash.bytes;return it.encode(e)}async getRawBlock(t,{signal:e,maxSize:n=Qo}={}){let s=new URL(this.url.toString());if(s.pathname=`/ipfs/${t.toString()}`,s.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let o=this.#o(t),i=new AbortController,a=()=>{i.abort()};e?.addEventListener("abort",a);try{let c=this.#n.get(o);if(c==null){this.#t++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l;c=fetch(s.toString(),u).then(async h=>{if(this.log("GET %s %d",s,h.status),!h.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);let f=await Xo(h,n,{signal:i.signal,log:this.log});return this.#s++,f}),this.#n.set(o,c)}return await c}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`unable to fetch raw block for CID ${t}`))}finally{e?.removeEventListener("abort",a),this.#n.delete(o)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#s/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#n.size}}};var ls=class extends Ct{routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Ar,this.allowLocal=e.allowLocal??Cr,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let s=await e.getRawBlock(t,n);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(s),s}async*findNewProviders(t,e={}){yield*Dr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e){if(De(t))return;let n=cs(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(n.length===0)return;let s=Er(n[0]);return new ne(s,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function Zo(r,t){return new ls(r,t)}var Tr=class{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??Ar,this.allowLocal=e.allowLocal??Cr,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let s of Dr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,s.url);try{await e.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s",t,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s",t,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${s.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,s.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 Zo({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Ar=!1,Cr=!1,Qo=2097152;function Ko(r={}){return t=>new Tr(t,r)}return ri(ol);})();
|
|
2
|
+
"use strict";var HeliaBlockBrokers=(()=>{var ti=Object.create;var ke=Object.defineProperty;var ei=Object.getOwnPropertyDescriptor;var ri=Object.getOwnPropertyNames;var ni=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var fs=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),$=(r,t)=>{for(var e in t)ke(r,e,{get:t[e],enumerable:!0})},ds=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ri(t))!si.call(r,s)&&s!==e&&ke(r,s,{get:()=>t[s],enumerable:!(n=ei(t,s))||n.enumerable});return r};var ps=(r,t,e)=>(e=r!=null?ti(ni(r)):{},ds(t||!r||!r.__esModule?ke(e,"default",{value:r,enumerable:!0}):e,r)),oi=r=>ds(ke({},"__esModule",{value:!0}),r);var lo=fs((Nd,co)=>{co.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Fo=fs(ve=>{(function(){var r,t,e,n,s,o,i,a;a=function(c){var l,u,h,f;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,f=c&255,[l,u,h,f].join(".")},i=function(c){var l,u,h,f,x,p;for(l=[],h=f=0;f<=3&&c.length!==0;h=++f){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),x=p[0],u=p[1],c=c.substring(u),l.push(x)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),o=e("a"),s=e("A"),t=function(c){var l,u,h,f,x;for(f=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),x=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)f=f*l+(e(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")f=f*l+(10+e(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")f=f*l+(10+e(c[h])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");h++}if(h===x)throw new Error("empty octet");return[f,h]},r=function(){function c(l,u){var h,f,x,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(E){throw h=E,new Error("Invalid mask: "+u)}for(f=x=32;x>=0;f=--x)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(E){throw h=E,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,h,f;for(f=i(this.first),h=i(this.last),u=0;f<=h;)l(a(f),f,u),u++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),ve.ip2long=i,ve.long2ip=a,ve.Netmask=r}).call(ve)});var cl={};$(cl,{bitswap:()=>mo,trustlessGateway:()=>Yo});var ii=Symbol.for("@libp2p/peer-id");function De(r){return!!r?.[ii]}var K=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Ae=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var Ce=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var Te=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},Le=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var rt=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){super.addEventListener(t,e,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function ms(r){let t=new globalThis.AbortController;function e(){t.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function N(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Pe=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 Pe(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 Pe(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 Pr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ne(r={}){return ai(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 ai(r,t){t=t??{};let e=t.onEnd,n=new Mt,s,o,i,a=N(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,C)=>{o=B=>{o=null,n.push(B);try{m(r(n))}catch(L){C(L)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=N()})}},l=m=>o!=null?o(m):(n.push(m),s),u=m=>(n=new Mt,o!=null?o({error:m}):(n.push({error:m}),s)),h=m=>{if(i)return s;if(t?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},f=m=>i?s:(i=!0,m!=null?u(m):l({done:!0})),x=()=>(n=new Mt,f(),{done:!0}),p=m=>(f(m),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:x,throw:p,push:h,end:f,get readableLength(){return n.size},onEmpty:async m=>{let C=m?.signal;if(C?.throwIfAborted(),n.isEmpty())return;let B,L;C!=null&&(B=new Promise((z,G)=>{L=()=>{G(new Pr)},C.addEventListener("abort",L)}));try{await Promise.race([a.promise,B])}finally{L!=null&&C!=null&&C?.removeEventListener("abort",L)}}},e==null)return s;let E=s;return s={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(m){return E.throw(m),e!=null&&(e(m),e=void 0),{done:!0}},return(){return E.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(m){return E.end(m),e!=null&&(e(m),e=void 0),s},get readableLength(){return E.readableLength},onEmpty:m=>E.onEmpty(m)},s}var Re=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function J(r,t,e,n){let s=new Re(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Rr(e,"abort",h),Rr(r,t,l),Rr(r,o,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(x){c(),a(x);return}c(),i(f)},u=f=>{if(c(),f instanceof Error){a(f);return}a(f.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(s)};Nr(e,"abort",h),Nr(r,t,l),Nr(r,o,u)})}function Nr(r,t,e){r!=null&&(gs(r)?r.addEventListener(t,e):r.addListener(t,e))}function Rr(r,t,e){r!=null&&(gs(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function gs(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Or(r,t){let e,n=function(){let s=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(s,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Oe=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Me=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Ue(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Me(e?.errorMessage,e?.errorCode,e?.errorName));let n,s=new Me(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Fe=class{deferred;signal;constructor(t){this.signal=t,this.deferred=N(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new K)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ci(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Be=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=ci(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,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 K),this.cleanup())}async join(t={}){let e=new Fe(t.signal);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 Ue(this.fn({...this.options??{},signal:this.controller.signal}),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 Ut=class extends rt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,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=Or(this.emitEmpty.bind(this),1),this.emitIdle=Or(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let 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 Oe;let n=new Be(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),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 o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new K)}),this.clear()}async onEmpty(t){this.size!==0&&await J(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await J(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await J(this,"idle",t?.signal)}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=Ne({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},o=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new K("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var ze=class extends Ut{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function li(r){return r[Symbol.asyncIterator]!=null}function ui(r){if(li(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Mr=ui;function R(r=0){return new Uint8Array(r)}function O(r=0){return new Uint8Array(r)}var hi=Math.pow(2,7),fi=Math.pow(2,14),di=Math.pow(2,21),Ur=Math.pow(2,28),Fr=Math.pow(2,35),Br=Math.pow(2,42),zr=Math.pow(2,49),b=128,M=127;function v(r){if(r<hi)return 1;if(r<fi)return 2;if(r<di)return 3;if(r<Ur)return 4;if(r<Fr)return 5;if(r<Br)return 6;if(r<zr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ft(r,t,e=0){switch(v(r)){case 8:t[e++]=r&255|b,r/=128;case 7:t[e++]=r&255|b,r/=128;case 6:t[e++]=r&255|b,r/=128;case 5:t[e++]=r&255|b,r/=128;case 4:t[e++]=r&255|b,r>>>=7;case 3:t[e++]=r&255|b,r>>>=7;case 2:t[e++]=r&255|b,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function pi(r,t,e=0){switch(v(r)){case 8:t.set(e++,r&255|b),r/=128;case 7:t.set(e++,r&255|b),r/=128;case 6:t.set(e++,r&255|b),r/=128;case 5:t.set(e++,r&255|b),r/=128;case 4:t.set(e++,r&255|b),r>>>=7;case 3:t.set(e++,r&255|b),r>>>=7;case 2:t.set(e++,r&255|b),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function $r(r,t){let e=r[t],n=0;if(n+=e&M,e<b||(e=r[t+1],n+=(e&M)<<7,e<b)||(e=r[t+2],n+=(e&M)<<14,e<b)||(e=r[t+3],n+=(e&M)<<21,e<b)||(e=r[t+4],n+=(e&M)*Ur,e<b)||(e=r[t+5],n+=(e&M)*Fr,e<b)||(e=r[t+6],n+=(e&M)*Br,e<b)||(e=r[t+7],n+=(e&M)*zr,e<b))return n;throw new RangeError("Could not decode varint")}function mi(r,t){let e=r.get(t),n=0;if(n+=e&M,e<b||(e=r.get(t+1),n+=(e&M)<<7,e<b)||(e=r.get(t+2),n+=(e&M)<<14,e<b)||(e=r.get(t+3),n+=(e&M)<<21,e<b)||(e=r.get(t+4),n+=(e&M)*Ur,e<b)||(e=r.get(t+5),n+=(e&M)*Fr,e<b)||(e=r.get(t+6),n+=(e&M)*Br,e<b)||(e=r.get(t+7),n+=(e&M)*zr,e<b))return n;throw new RangeError("Could not decode varint")}function $e(r,t,e=0){return t==null&&(t=O(v(r))),t instanceof Uint8Array?Ft(r,t,e):pi(r,t,e)}function bt(r,t=0){return r instanceof Uint8Array?$r(r,t):mi(r,t)}function ht(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=O(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function j(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 bs=Symbol.for("@achingbrain/uint8arraylist");function ws(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function He(r){return!!r?.[bs]}var ft=class r{bufs;length;[bs]=!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(He(n))e+=n.byteLength,this.bufs.push(...n.bufs);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(He(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=ws(this.bufs,t);return e.buf[e.index]}set(t,e){let n=ws(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(He(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:s}=this._subList(t,e);return ht(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:ht(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_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=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){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(u){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(!He(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 s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<s;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let x=this.get(h+f);if(n[f]!==x){u=Math.max(1,f-a[x]);break}}if(u===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=O(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 s=R(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,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 s=R(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,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 s=R(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,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=O(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 s=R(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,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 s=R(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,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 s=R(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,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 s=R(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,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 s=R(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,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(!j(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((s,o)=>s+o.byteLength,0)),n.length=e,n}};var Ve=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Bt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},qe=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},se=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function We(r){return r[Symbol.asyncIterator]!=null}function ys(r,t){if(r.byteLength>t)throw new Bt("Message length too long")}var Xe=r=>{let t=v(r),e=O(t);return $e(r,e),Xe.bytes=t,e};Xe.bytes=0;function Qe(r,t){t=t??{};let e=t.lengthEncoder??Xe,n=t?.maxDataLength??4194304;function*s(o){ys(o,n);let i=e(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return We(r)?async function*(){for await(let o of r)yield*s(o)}():function*(){for(let o of r)yield*s(o)}()}Qe.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Xe,n=t?.maxDataLength??4194304;return ys(r,n),new ft(e(r.byteLength),r)};var yt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(yt||(yt={}));var Vr=r=>{let t=bt(r);return Vr.bytes=v(t),t};Vr.bytes=0;function oe(r,t){let e=new ft,n=yt.LENGTH,s=-1,o=t?.lengthDecoder??Vr,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===yt.LENGTH)try{if(s=o(e),s<0)throw new Ve("Invalid message length");if(s>a)throw new Bt("Message length too long");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=yt.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new qe("Message length length too long");break}throw l}if(n===yt.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=yt.LENGTH}}}return We(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new se("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new se("Unexpected end of input")}()}oe.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}}();return oe(n,{...t??{},onLength:o=>{e=o}})};function bi(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var xs=bi;function yi(r){return r[Symbol.asyncIterator]!=null}function xi(r,t){let e=0;if(yi(r))return async function*(){for await(let c of r)yield t(c,e++)}();let n=xs(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=t(s,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 Es=xi;var qr=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=N(),this.haveNext=N()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=N(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=N(),await Ue(this.readNext.promise,e?.signal,e)}};function _s(){return new qr}function Ei(r){return r[Symbol.asyncIterator]!=null}async function _i(r,t,e){try{await Promise.all(r.map(async n=>{for await(let s of n)await t.push(s,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*vi(r){let t=new AbortController,e=_s();_i(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*Si(r){for(let t of r)yield*t}function Ii(...r){let t=[];for(let e of r)Ei(e)||t.push(e);return t.length===r.length?Si(t):vi(r)}var vs=Ii;function Gr(r,...t){if(r==null)throw new Error("Empty pipeline");if(Wr(r)){let n=r;r=()=>n.source}else if(Is(r)||Ss(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Wr(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Wr(e[n])&&(e[n]=Di(e[n]));return ki(...e)}var ki=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Ss=r=>r?.[Symbol.asyncIterator]!=null,Is=r=>r?.[Symbol.iterator]!=null,Wr=r=>r==null?!1:r.sink!=null&&r.source!=null,Di=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ne({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Ss(o))s=async function*(){yield*o,n.end()};else if(Is(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return vs(n,s())}return r.source};function Ai(r){return r[Symbol.asyncIterator]!=null}function Ci(r,t){return Ai(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var ks=Ci;var nt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var ie="/ipfs/bitswap/1.2.0";var Xr=new Float32Array([-0]),dt=new Uint8Array(Xr.buffer);function Ds(r,t,e){Xr[0]=r,t[e]=dt[0],t[e+1]=dt[1],t[e+2]=dt[2],t[e+3]=dt[3]}function As(r,t){return dt[0]=r[t],dt[1]=r[t+1],dt[2]=r[t+2],dt[3]=r[t+3],Xr[0]}var Qr=new Float64Array([-0]),U=new Uint8Array(Qr.buffer);function Cs(r,t,e){Qr[0]=r,t[e]=U[0],t[e+1]=U[1],t[e+2]=U[2],t[e+3]=U[3],t[e+4]=U[4],t[e+5]=U[5],t[e+6]=U[6],t[e+7]=U[7]}function Ts(r,t){return U[0]=r[t],U[1]=r[t+1],U[2]=r[t+2],U[3]=r[t+3],U[4]=r[t+4],U[5]=r[t+5],U[6]=r[t+6],U[7]=r[t+7],Qr[0]}var Ti=BigInt(Number.MAX_SAFE_INTEGER),Li=BigInt(Number.MIN_SAFE_INTEGER),H=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return xt;if(t<Ti&&t>Li)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>Ls&&(s=0n,++n>Ls&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return xt;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):xt}},xt=new H(0,0);xt.toBigInt=function(){return 0n};xt.zzEncode=xt.zzDecode=function(){return this};xt.length=function(){return 1};var Ls=4294967296n;function Ps(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Ns(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Zr(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function Y(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Ze(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Kr=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Y(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Y(this,4);return Ze(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Y(this,4);return Ze(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Y(this,4);let t=As(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Y(this,4);let t=Ts(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Y(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ns(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Y(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Y(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new H(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Y(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Y(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Y(this,8);let t=Ze(this.buf,this.pos+=4),e=Ze(this.buf,this.pos+=4);return new H(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=$r(this.buf,this.pos);return this.pos+=v(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Jr(r){return new Kr(r instanceof Uint8Array?r:r.subarray())}function Et(r,t,e){let n=Jr(r);return t.decode(n,void 0,e)}var rn={};$(rn,{base10:()=>Fi});var Bu=new Uint8Array(0);function Os(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 r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ms(r){return new TextEncoder().encode(r)}function Us(r){return new TextDecoder().decode(r)}function Pi(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var E=0,m=0,C=0,B=p.length;C!==B&&p[C]===0;)C++,E++;for(var L=(B-C)*u+1>>>0,z=new Uint8Array(L);C!==B;){for(var G=p[C],ut=0,Z=L-1;(G!==0||ut<m)&&Z!==-1;Z--,ut++)G+=256*z[Z]>>>0,z[Z]=G%a>>>0,G=G/a>>>0;if(G!==0)throw new Error("Non-zero carry");m=ut,C++}for(var st=L-m;st!==L&&z[st]===0;)st++;for(var Ie=c.repeat(E);st<L;++st)Ie+=r.charAt(z[st]);return Ie}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var E=0;if(p[E]!==" "){for(var m=0,C=0;p[E]===c;)m++,E++;for(var B=(p.length-E)*l+1>>>0,L=new Uint8Array(B);p[E];){var z=e[p.charCodeAt(E)];if(z===255)return;for(var G=0,ut=B-1;(z!==0||G<C)&&ut!==-1;ut--,G++)z+=a*L[ut]>>>0,L[ut]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");C=G,E++}if(p[E]!==" "){for(var Z=B-C;Z!==B&&L[Z]===0;)Z++;for(var st=new Uint8Array(m+(B-Z)),Ie=m;Z!==B;)st[Ie++]=L[Z++];return st}}}function x(p){var E=f(p);if(E)return E;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:x}}var Ni=Pi,Ri=Ni,Bs=Ri;var jr=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")}},Yr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 zs(this,t)}},tn=class{decoders;constructor(t){this.decoders=t}or(t){return zs(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 zs(r,t){return new tn({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var en=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new jr(t,e,n),this.decoder=new Yr(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function zt({name:r,prefix:t,encode:e,decode:n}){return new en(r,t,e,n)}function pt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Bs(e,r);return zt({prefix:t,name:r,encode:n,decode:o=>ot(s(o))})}function Oi(r,t,e,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Mi(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;(o.length*e&7)!==0;)o+="=";return o}function Ui(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function I({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let s=Ui(n);return zt({prefix:t,name:r,encode(o){return Mi(o,n,e)},decode(o){return Oi(o,s,e,r)}})}var Fi=pt({prefix:"9",name:"base10",alphabet:"0123456789"});var nn={};$(nn,{base16:()=>Bi,base16upper:()=>zi});var Bi=I({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zi=I({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var sn={};$(sn,{base2:()=>$i});var $i=I({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var on={};$(on,{base256emoji:()=>Gi});var $s=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}"),Hi=$s.reduce((r,t,e)=>(r[e]=t,r),[]),Vi=$s.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function qi(r){return r.reduce((t,e)=>(t+=Hi[e],t),"")}function Wi(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=Vi[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var Gi=zt({prefix:"\u{1F680}",name:"base256emoji",encode:qi,decode:Wi});var an={};$(an,{base32:()=>mt,base32hex:()=>Ki,base32hexpad:()=>ji,base32hexpadupper:()=>Yi,base32hexupper:()=>Ji,base32pad:()=>Qi,base32padupper:()=>Zi,base32upper:()=>Xi,base32z:()=>ta});var mt=I({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xi=I({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Qi=I({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zi=I({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ki=I({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ji=I({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ji=I({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Yi=I({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ta=I({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var cn={};$(cn,{base36:()=>ae,base36upper:()=>ea});var ae=pt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ea=pt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ln={};$(ln,{base58btc:()=>V,base58flickr:()=>ra});var V=pt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ra=pt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var hn={};$(hn,{base64:()=>it,base64pad:()=>na,base64url:()=>un,base64urlpad:()=>sa});var it=I({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),na=I({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),un=I({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),sa=I({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var fn={};$(fn,{base8:()=>oa});var oa=I({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var dn={};$(dn,{identity:()=>ia});var ia=zt({prefix:"\0",name:"identity",encode:r=>Us(r),decode:r=>Ms(r)});var eh=new TextEncoder,rh=new TextDecoder;var gn={};$(gn,{identity:()=>Ca});var la=qs,Hs=128,ua=127,ha=~ua,fa=Math.pow(2,31);function qs(r,t,e){t=t||[],e=e||0;for(var n=e;r>=fa;)t[e++]=r&255|Hs,r/=128;for(;r&ha;)t[e++]=r&255|Hs,r>>>=7;return t[e]=r|0,qs.bytes=e-n+1,t}var da=pn,pa=128,Vs=127;function pn(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw pn.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&Vs)<<s:(i&Vs)*Math.pow(2,s),s+=7}while(i>=pa);return pn.bytes=o-n,e}var ma=Math.pow(2,7),ga=Math.pow(2,14),wa=Math.pow(2,21),ba=Math.pow(2,28),ya=Math.pow(2,35),xa=Math.pow(2,42),Ea=Math.pow(2,49),_a=Math.pow(2,56),va=Math.pow(2,63),Sa=function(r){return r<ma?1:r<ga?2:r<wa?3:r<ba?4:r<ya?5:r<xa?6:r<Ea?7:r<_a?8:r<va?9:10},Ia={encode:la,decode:da,encodingLength:Sa},ka=Ia,ce=ka;function le(r,t=0){return[ce.decode(r,t),ce.decode.bytes]}function $t(r,t,e=0){return ce.encode(r,t,e),t}function Ht(r){return ce.encodingLength(r)}function _t(r,t){let e=t.byteLength,n=Ht(r),s=n+Ht(e),o=new Uint8Array(s+e);return $t(r,o,0),$t(e,o,n),o.set(t,s),new Vt(r,e,t,o)}function mn(r){let t=ot(r),[e,n]=le(t),[s,o]=le(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Vt(e,s,i,t)}function Ws(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Os(r.bytes,e.bytes)}}var Vt=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};var Gs=0,Da="identity",Xs=ot;function Aa(r){return _t(Gs,Xs(r))}var Ca={code:Gs,name:Da,encode:Xs,digest:Aa};var yn={};$(yn,{sha256:()=>Je,sha512:()=>Ta});function bn({name:r,code:t,encode:e}){return new wn(r,t,e)}var wn=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?_t(this.code,e):e.then(n=>_t(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Zs(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Je=bn({name:"sha2-256",code:18,encode:Zs("SHA-256")}),Ta=bn({name:"sha2-512",code:19,encode:Zs("SHA-512")});function Ks(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Pa(e,xn(r),t??V.encoder);default:return Na(e,xn(r),t??mt.encoder)}}var Js=new WeakMap;function xn(r){let t=Js.get(r);if(t==null){let e=new Map;return Js.set(r,e),e}return t}var q=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}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!==ue)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Ra)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=_t(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&&Ws(t.multihash,n.multihash)}toString(t){return Ks(this,t)}toJSON(){return{"/":Ks(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:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??js(n,s,o.bytes))}else if(e[Oa]===!0){let{version:n,multihash:s,code:o}=e,i=mn(s);return r.create(n,o,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!==ue)throw new Error(`Version 0 CID must use dag-pb (code: ${ue}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=js(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,ue,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,s=ot(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Vt(e.multihashCode,e.digestSize,o,s);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,f]=le(t.subarray(e));return e+=f,h},s=n(),o=ue;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,s]=La(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xn(o).set(n,t),o}};function La(r,t){switch(r[0]){case"Q":{let e=t??V;return[V.prefix,e.decode(`${V.prefix}${r}`)]}case V.prefix:{let e=t??V;return[V.prefix,e.decode(r)]}case mt.prefix:{let e=t??mt;return[mt.prefix,e.decode(r)]}case ae.prefix:{let e=t??ae;return[ae.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 Pa(r,t,e){let{prefix:n}=e;if(n!==V.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function Na(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var ue=112,Ra=18;function js(r,t,e){let n=Ht(r),s=n+Ht(t),o=new Uint8Array(s+e.byteLength);return $t(r,o,0),$t(t,o,n),o.set(e,s),o}var Oa=Symbol.for("@ipld/js-cid/CID");var he={...dn,...sn,...fn,...rn,...nn,...an,...cn,...ln,...hn,...on},Sh={...yn,...gn};function to(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ys=to("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),En=to("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=O(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Ma={utf8:Ys,"utf-8":Ys,hex:he.base16,latin1:En,ascii:En,binary:En,...he},je=Ma;function A(r,t="utf8"){let e=je[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function _n(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return O(i);s+i>t&&(n=O(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var vt=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function vn(){}var In=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Ua=_n();function Fa(r){return globalThis.Buffer!=null?O(r):Ua(r)}var de=class{len;head;tail;states;constructor(){this.len=0,this.head=new vt(vn,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new vt(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new kn((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Ye,10,H.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=H.fromBigInt(t);return this._push(Ye,e.length(),e)}uint64Number(t){return this._push(Ft,v(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=H.fromBigInt(t).zzEncode();return this._push(Ye,e.length(),e)}sint64Number(t){let e=H.fromNumber(t).zzEncode();return this._push(Ye,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Sn,1,t?1:0)}fixed32(t){return this._push(fe,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=H.fromBigInt(t);return this._push(fe,4,e.lo)._push(fe,4,e.hi)}fixed64Number(t){let e=H.fromNumber(t);return this._push(fe,4,e.lo)._push(fe,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Ds,4,t)}double(t){return this._push(Cs,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Sn,1,0):this.uint32(e)._push(za,e,t)}string(t){let e=Ps(t);return e!==0?this.uint32(e)._push(Zr,e,t):this._push(Sn,1,0)}fork(){return this.states=new In(this),this.head=this.tail=new vt(vn,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new vt(vn,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Fa(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Sn(r,t,e){t[e]=r&255}function Ba(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var kn=class extends vt{next;constructor(t,e){super(Ba,t,e),this.next=void 0}};function Ye(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function fe(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function za(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(de.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push($a,t,r),this},de.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Ha,t,r),this});function $a(r,t,e){t.set(r,e)}function Ha(r,t,e){r.length<40?Zr(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(A(r),e)}function Dn(){return new de}function St(r,t){let e=Dn();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Wt;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Wt||(Wt={}));function tr(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function er(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let a=t(o);i.int32(a)},n=function(o){let i=o.int32();return t(i)};return tr("enum",Wt.VARINT,e,n)}function It(r,t){return tr("message",Wt.LENGTH_DELIMITED,r,t)}var Gt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var k;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(k||(k={}));var An;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(An||(An={}));(function(r){r.codec=()=>er(An)})(k||(k={}));var Xt;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.priority!=null&&e.priority!==0&&(n.uint32(16),n.int32(e.priority)),e.cancel!=null&&(n.uint32(24),n.bool(e.cancel)),e.wantType!=null&&(n.uint32(32),k.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:R(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.priority=e.int32();break}case 3:{o.cancel=e.bool();break}case 4:{o.wantType=k.codec().decode(e);break}case 5:{o.sendDontHave=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(Xt||(Xt={}));var rr;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let o of e.entries)n.uint32(10),Xt.codec().encode(o,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={entries:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new Gt('Decode error - map field "entries" had too many elements');o.entries.push(Xt.codec().decode(e,e.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(rr||(rr={}));var Qt;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.prefix!=null&&e.prefix.byteLength>0&&(n.uint32(10),n.bytes(e.prefix)),e.data!=null&&e.data.byteLength>0&&(n.uint32(18),n.bytes(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={prefix:R(0),data:R(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.prefix=e.bytes();break}case 2:{o.data=e.bytes();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(Qt||(Qt={}));var X;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(X||(X={}));var nr;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(nr||(nr={}));(function(r){r.codec=()=>er(nr)})(X||(X={}));var Zt;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.type!=null&&nr[e.type]!==0&&(n.uint32(16),X.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:R(0),type:X.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.type=X.codec().decode(e);break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(Zt||(Zt={}));var kt;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),rr.codec().encode(e.wantlist,n)),e.blocks!=null)for(let o of e.blocks)n.uint32(26),Qt.codec().encode(o,n);if(e.blockPresences!=null)for(let o of e.blockPresences)n.uint32(34),Zt.codec().encode(o,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.wantlist=rr.codec().decode(e,e.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&o.blocks.length===s.limits.blocks)throw new Gt('Decode error - map field "blocks" had too many elements');o.blocks.push(Qt.codec().decode(e,e.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&o.blockPresences.length===s.limits.blockPresences)throw new Gt('Decode error - map field "blockPresences" had too many elements');o.blockPresences.push(Zt.codec().decode(e,e.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=e.int32();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>St(e,r.codec()),r.decode=(e,n)=>Et(e,r.codec(),n)})(kt||(kt={}));function eo(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var sr=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var Va=4193648,qa=Va+16;function*ro(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=kt.encode(l).byteLength,{added:h,hasMore:f,newSize:x}=Cn(s,l.blocks,a,t,u,Wa);a+=h,u=x;let p=f;({added:h,hasMore:f,newSize:x}=Cn(n,l.blockPresences,i,t,u,Ga)),i+=h,u=x;let E=f;if({added:h,hasMore:f,newSize:x}=Cn(e,l.wantlist.entries,o,t,u,Xa),o+=h,u=x,c=!p&&!E&&!f,c||(l.wantlist.full=!1),yield kt.encode(l),c)break}}function Cn(r,t,e,n,s,o){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=o(l);if(u>qa)throw new sr("Cannot send block as after encoding it is over the max message size");let h=s+u;if(h>n){a=!0;break}t.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function Wa(r){return Tn(3,Qt.encode(r))}function Ga(r){return Tn(4,Zt.encode(r))}function Xa(r){return Tn(1,Xt.encode(r))}function Tn(r,t){let e=v(r),n=v(t.byteLength);return e+n+t.byteLength}var or=class extends rt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[ie],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??5e3,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new ze({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t){if(!this.running)return;let{stream:e,connection:n}=t;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,n.remotePeer);let s=()=>{e.status==="open"?e.abort(new Te(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",s),await e.closeWrite(),await Gr(e,i=>oe(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let a of i)try{let c=kt.decode(a);this.log("incoming new bitswap %s message from %p on stream",e.protocol,n.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),o.removeEventListener("abort",s),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",s)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,e.id,c),e.abort(c);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new nt("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})&&(yield n)}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Mr(Es(ks(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>t.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=eo(s.options.message,e),await s.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let i=o?.message;if(i==null)throw new Ae("No message to send");this.log("sendMessage to %p",t),o?.onProgress?.(new nt("bitswap:network:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,ie,o);await a.closeRead();try{await Gr(ro(i,this.maxOutgoingMessageSize),c=>Qe(c),a),await a.close(o)}catch(c){o?.onProgress?.(new nt("bitswap:network:send-wantlist:error",{peer:t,error:c})),this.log.error("error sending message to %p",t,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:t,signal:n?.signal,message:e})}async connectTo(t,e){if(!this.running)throw new Le("Network isn't running");e?.onProgress?.(new nt("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),J(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(ie))return!0;throw new Ce(`${t} did not support ${ie}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};function D(r,t="utf8"){let e=je[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function ir(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var pe=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return ir(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return ir(this.map.values(),t=>t.key)}values(){return ir(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ln={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},so={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},oo=new globalThis.TextEncoder;function rc(r,t){let e=Ln[t],n=so[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function nc(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ln[t],s=so[t],o=r;for(;o.length>0;){let i=oo.encodeInto(o,e);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function Pn(r,{size:t=32,utf8Buffer:e}={}){if(!Ln[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 nc(r,t,e);r=oo.encode(r)}return rc(r,t)}var me={hash:r=>Number(Pn(r,{size:32})),hashV:(r,t)=>sc(me.hash(r,t))};function sc(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),A(t,"base16")}var Nn=64,tt=class{fp;h;seed;constructor(t,e,n,s=2){if(s>Nn)throw new TypeError("Invalid Fingerprint Size");let o=e.hashV(t,n),i=R(s);for(let a=0;a<i.length;a++)i[a]=o[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?j(this.fp,t.fp):!1}};function Dt(r,t){return Math.floor(Math.random()*(t-r))+r}var At=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof tt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof tt))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 tt))throw new TypeError("Invalid Fingerprint");let e=Dt(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof tt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var oc=500,ge=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??me,this.seed=t.seed??Dt(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=A(t));let e=new tt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new At(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new At(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[Dt(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new At(this.bucketSize));for(let a=0;a<oc;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 At(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=A(t));let e=new tt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let o=(n^e.hash())%this.filterSize;return this.buckets[o]?.has(e)??!1}remove(t){typeof t=="string"&&(t=A(t));let e=new tt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let o=(n^e.hash())%this.filterSize,i=this.buckets[o]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ic={1:.5,2:.84,4:.95,8:.98};function ac(r=.001){return r>.002?2:r>1e-5?4:8}function io(r,t=.001){let e=ac(t),n=ic[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Nn);return{filterSize:s,bucketSize:e,fingerprintSize:o}}var ar=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??me,this.seed=t.seed??Dt(0,Math.pow(2,10)),this.filterSeries=[new ge({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=A(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 ge({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=A(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=A(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 Rn(r,t=.001,e){return new ar({...io(r,t),...e??{}})}var On=class extends pe{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function we(r){let{name:t,metrics:e}=r,n;return e!=null?n=new On({name:t,metrics:e}):n=new pe,n}var at=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=it.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=it.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=it.encode(t.multihash.bytes);this.blocks.set(n,e)}};function cc(r){let t=new Uint8Array(r.reduce((n,s)=>n+v(s),0)),e=0;for(let n of r)t=$e(n,t,e),e+=v(n);return t}var ao=cc;function Mn(r){return ao([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var cr=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(t){let e=new at,n=new Set;for(let[s,o]of this.wants.entries())try{let i=await this.blockstore.get(o.cid,t);o.wantType===k.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:Mn(o.cid)})):(this.log("sending have for %c",o.cid),e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:X.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:Mn(o.cid)}))}catch(i){if(i.name!=="NotFoundError")throw i;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDoNotHave===!0)continue;o.sentDoNotHave=!0,e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:X.DoNotHaveBlock})}if(e.blocks.size>0||e.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((s,o)=>s+o.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var lr=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=we({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return[...e.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);if(n==null&&(n=new cr({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let o=q.decode(s.cid),i=D(o.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,o),n.wants.delete(i)):(s.wantType===k.WantHave?this.log("peer %p wanted block presence for %c",t,o):this.log("peer %p wanted block for %c",t,o),n.wants.set(i,{cid:o,priority:s.priority,wantType:s.wantType??k.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=D(t.multihash.bytes,"base64"),s=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&s.push(o);await Promise.all(s.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var hc=ps(lo(),1);var Kt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Kt||(Kt={}));var ur=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Ct=class extends rt{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(t,e){super(),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=Rn(this.maxProviders),this.initialProviders=e.providers??[]}async retrieve(t,e={}){let n=it.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let o=N();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.initialPeerSearchComplete,u&&this.log("found initial session peers for %c",t)}let i=!1,a=new Ut({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),a.addEventListener("success",u=>{i=!0,o.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(i||e.signal?.aborted===!0){this.log.trace("session idle, found block");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 h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c",t,u),o.reject(u)})});let c=u=>{a.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,h)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,u)});let l=()=>{o.reject(new K(e.signal?.reason??"Session aborted")),a.abort()};e.signal?.addEventListener("abort",l);try{return await o.promise}finally{this.removeEventListener("provider",c),e.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(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.toEvictionKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let s=N(),o=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t),this.initialProviders.length>0)for(;o<e&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let i of this.findNewProviders(t,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<e)throw new ur(`Found ${o} of ${e} ${this.name} providers for ${t}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",t,i.errors??i),s.reject(i)}),s.promise}};var Un=class extends Ct{wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield n.id}toEvictionKey(t){return t.toMultihash().bytes}equals(t,e){return t.equals(e)}async convertToProvider(t,e){return De(t)?t:(await this.libp2p.dial(t,e)).remotePeer}};function uo(r,t){return new Un(r,t)}var hr=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};var Fn=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ho(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Fn({name:t,metrics:e}):n=new Map,n}function pc(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=bt(r);t.push(e),r=r.slice(v(e))}return t}var fo=pc;var fr=class extends rt{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),this.peers=we({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=ho({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendMessagesDelay=e.sendMessagesDelay??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=e.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=D(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??k.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===k.WantHave&&e.wantType===k.WantBlock&&(s.wantType=k.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===k.WantBlock?(await J(this,"block",e?.signal,{filter:a=>j(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await J(this,"presence",e?.signal,{filter:i=>j(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers",t)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=N(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new at;for(let[o,i]of this.wants.entries())e.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s);for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer",o)}})).catch(t=>{this.log.error("error sending messages",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=D(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:k.WantHave,priority:1}),await this.network.sendMessage(e,s),(await J(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&j(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:k.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:k.WantBlock,priority:1}),await this.network.sendMessage(e,s),(await J(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&j(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=D(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=fo(s.prefix),i=o[0],a=o[1],c=o[2],l=c===Je.code?Je:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let u=l.digest(s.data);u.then!=null&&(u=await u);let h=q.create(i===0?0:1,a,u);this.log("received block from %p for %c",t,h),this.safeDispatchEvent("block",{detail:{sender:t,cid:h,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:h,has:!0,block:s.data}});let f=D(h.multihash.bytes,"base64"),x=this.wants.get(f);x!=null&&(x.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=q.decode(s);this.log("received %s from %p for %c",o,t,i),this.safeDispatchEvent("presence",{detail:{sender:t,cid:i,has:o===X.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new at(!0);for(let[s,o]of this.wants.entries())o.cancel||(e.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:k.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var dr=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new hr(t),this.network=new or(t,e),this.peerWantLists=new lr({...t,network:this.network},e),this.wantList=new fr({...t,network:this.network},e)}createSession(t={}){return uo({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,s=ms([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,o)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await Promise.all([this.peerWantLists.receivedBlock(t,n),this.wantList.receivedBlock(t,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var po=(r,t={})=>new dr(r,t);var Bn=class{bitswap;started;constructor(t,e={}){let{getHasher:n}=t;this.bitswap=po(t,{hashLoader:{getHasher:async s=>n(s)},...e}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e,n){await this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}createSession(t){let e=this.bitswap.createSession(t);return{announce:async(n,s,o)=>{await this.bitswap.notify(n,s,o)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function mo(r={}){return t=>new Bn(t,r)}var P=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ct=class extends Error{static name="ValidationError";name="ValidationError"},be=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},pr=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var mr=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,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=t,o+=u,o>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:o})}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 s=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return e.set(o.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var mc=45,gc=15,gr=new mr;function zn(r){if(!(r.length>gc))return gr.new(r).parseWith(()=>gr.readIPv4Addr())}function $n(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>mc))return gr.new(r).parseWith(()=>gr.readIPv6Addr())}function Jt(r){return!!zn(r)}function wr(r){return!!$n(r)}function Vn(r){return t=>D(t,r)}function qn(r){return t=>A(t,r)}function jt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Tt(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function wo(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=A(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 s=Tt(n);return ht([e,s],e.length+s.length)}function bo(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=mt.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 s=Tt(n);return ht([e,s],e.length+s.length)}function Wn(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=D(t,"base32"),s=jt(e);return`${n}:${s}`}var Gn=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let s=parseInt(e,10);if(isNaN(s)||s<0||s>255)throw new P("Invalid byte value in IP address");t[n]=s}),t},yo=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=Jt(e[n]),i;o&&(i=Gn(e[n]),e[n]=D(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,D(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 o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let o=parseInt(e[n],16);if(isNaN(o)||o<0||o>65535)throw new P("Invalid byte value in IP address");s[t++]=o>>8&255,s[t++]=o&255}return s},xo=function(r){if(r.byteLength!==4)throw new P("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Eo=function(r){if(r.byteLength!==16)throw new P("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.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 P(`Invalid IPv6 address "${e}"`)}};function _o(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new P(`Invalid IPv6 address "${r}"`)}}var Hn=Object.values(he).map(r=>r.decoder),wc=function(){let r=Hn[0].or(Hn[1]);return Hn.slice(2).forEach(t=>r=r.or(t)),r}();function vo(r){return wc.decode(r)}function So(r){return t=>r.encoder.encode(t)}function bc(r){if(parseInt(r).toString()!==r)throw new ct("Value must be an integer")}function yc(r){if(r<0)throw new ct("Value must be a positive integer, or zero")}function xc(r){return t=>{if(t>r)throw new ct(`Value must be smaller than or equal to ${r}`)}}function Ec(...r){return t=>{for(let e of r)e(t)}}var ye=Ec(bc,yc,xc(65535));var T=-1,Xn=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 pr(`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)}))}},W=new Xn,Mc=[{code:4,name:"ip4",size:32,valueToBytes:Gn,bytesToValue:xo,validate:r=>{if(!Jt(r))throw new ct(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Tt,bytesToValue:jt,validate:ye},{code:273,name:"udp",size:16,valueToBytes:Tt,bytesToValue:jt,validate:ye},{code:33,name:"dccp",size:16,valueToBytes:Tt,bytesToValue:jt,validate:ye},{code:41,name:"ip6",size:128,valueToBytes:yo,bytesToValue:Eo,stringToValue:_o,validate:r=>{if(!wr(r))throw new ct(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:T},{code:43,name:"ipcidr",size:8,bytesToValue:Vn("base10"),valueToBytes:qn("base10")},{code:53,name:"dns",size:T,resolvable:!0},{code:54,name:"dns4",size:T,resolvable:!0},{code:55,name:"dns6",size:T,resolvable:!0},{code:56,name:"dnsaddr",size:T,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Tt,bytesToValue:jt,validate:ye},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:T,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:T,bytesToValue:Vn("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?qn("base58btc")(r):q.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Wn,valueToBytes:wo},{code:445,name:"onion3",size:296,bytesToValue:Wn,valueToBytes:bo},{code:446,name:"garlic64",size:T},{code:447,name:"garlic32",size:T},{code:448,name:"tls"},{code:449,name:"sni",size:T},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:T,bytesToValue:So(un),valueToBytes:vo},{code:480,name:"http"},{code:481,name:"http-path",size:T,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:T}];Mc.forEach(r=>{W.addProtocol(r)});function Io(r){let t=[],e=0;for(;e<r.length;){let n=bt(r,e),s=W.getProtocol(n),o=v(n),i=Uc(s,r,e+o),a=0;i>0&&s.size===T&&(a=v(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??D(h)}t.push(l),e+=c}return t}function ko(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let s=W.getProtocol(n.code),o=v(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??A(n.value),a=i.byteLength,s.size===T&&(c=v(a)));let l=new Uint8Array(o+c+a),u=0;Ft(n.code,l,u),u+=o,i!=null&&(s.size===T&&(Ft(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return ht(e,t)}function Do(r){if(r.charAt(0)!=="/")throw new P('String multiaddr must start with "/"');let t=[],e="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(e==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=W.getProtocol(s);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",s="",e="protocol";continue}else if(a)throw new P(`Component ${s} 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 P(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",s="",e="protocol"}}}if(s!==""&&n!=="")throw new P("Incomplete multiaddr");return t}function Ao(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=W.getProtocol(t.code);if(e==null)throw new P(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function Uc(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:bt(t,e)}var Fc=Symbol.for("nodejs.util.inspect.custom"),ns=Symbol.for("@multiformats/multiaddr"),Bc=[53,54,55,56],rs=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function zc(r){if(r==null&&(r="/"),To(r))return r.getComponents();if(r instanceof Uint8Array)return Io(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Do(r);if(Array.isArray(r))return r;throw new P("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Er=class r{[ns]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=zc(t),e.validate!==!1&&$c(this)}get bytes(){return this.#r==null&&(this.#r=ko(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Ao(this.#t)),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,s,o="";for(let{code:a,name:c,value:l}of this.#t)a===42&&(o=`%${l??""}`),Bc.includes(a)&&(e="tcp",s=443,n=`${l??""}${o}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",s=parseInt(l??"")),(a===4||a===41)&&(e="tcp",n=`${l??""}${o}`,t=a===41?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=W.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=W.getProtocol(t),s=[t];return e!=null&&s.push(n.valueToBytes?.(e)??A(e)),s})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}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(),s=n.lastIndexOf(e);if(s<0)throw new be(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,s),{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})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:s})=>{n===421&&t.push([n,s]),n===290&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?D(V.decode(`z${n}`),"base58btc"):D(q.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(W.getProtocol(t.code).path)return t.value??null;return null}equals(t){return j(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(o=>o.resolvable);if(e==null)return[this];let n=Co.get(e.name);if(n==null)throw new rs(`no available resolver for ${e.name}`);return(await n(this,t)).map(o=>_e(o))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[Fc](){return`Multiaddr(${this.toString()})`}};function $c(r){r.getComponents().forEach(t=>{let e=W.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}var Rm=parseInt("0xFFFF",16),Om=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Co=new Map;function To(r){return!!r?.[ns]}function _e(r){return new Er(r)}var Gc=[6,53,56,54,55];function No(r){return Mo("sni",r)?.value}function Ro(r){let t=Mo("tcp",r)?.value;return t==null?"":`:${t}`}function Mo(r,t){return t.find(e=>e.name===r)}function Oo(r){return r.some(({code:t})=>t===448)}function et(r,t){let e=Uo[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 Uo={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://${et(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${et(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`${et(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${et(e,t)}`},http:(r,t)=>{let e=Oo(t),n=No(t),s=Ro(t);if(e&&n!=null)return`https://${n}${s}`;let o=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=et(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=et(e,t),s=decodeURIComponent(r.value??"");return`${n}${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return et(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return et(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=et(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Oo(t),n=No(t),s=Ro(t);if(e&&n!=null)return`wss://${n}${s}`;let o=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=et(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=et(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function _r(r,t){let n=_e(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=Uo[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return t?.assumeHttp!==!1&&Gc.includes(s.code)&&(i=i.replace(/^.*:\/\//,""),s.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 Bo=ps(Fo(),1),Xc=["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"],Qc=Xc.map(r=>new Bo.Netmask(r));function ss(r){for(let t of Qc)if(t.contains(r))return!0;return!1}function Zc(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Kc(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"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return ss(s)}function Jc(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function jc(r){let t=r.split(":"),e=t[t.length-1];return ss(e)}function Yc(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 zo(r){if(Jt(r))return ss(r);if(Zc(r))return Kc(r);if(Jc(r))return jc(r);if(wr(r))return Yc(r)}var S=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)}}),g=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),F=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1}}),y=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function _(...r){function t(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:r,matches:e,exactMatch:n}}var tl=d(421),Ag=_(tl),Sr=d(54),Ir=d(55),kr=d(56),is=d(53),Cg=_(Sr,g(d(421))),Tg=_(Ir,g(d(421))),Lg=_(kr,g(d(421))),$o=_(F(is,kr,Sr,Ir),g(d(421))),Ho=y(d(4),g(d(43))),Vo=y(g(d(42)),d(41),g(d(43))),as=F(Ho,Vo),Ot=F(as,is,Sr,Ir,kr),Pg=_(F(as,y(F(is,kr,Sr,Ir),g(d(421))))),Ng=_(Ho),Rg=_(Vo),Og=_(as),cs=y(Ot,d(6)),Se=y(Ot,d(273)),Mg=_(y(cs,g(d(421)))),Ug=_(Se),ls=y(Se,S(460),g(d(421))),Dr=y(Se,S(461),g(d(421))),el=F(ls,Dr),Fg=_(ls),Bg=_(Dr),os=F(Ot,cs,Se,ls,Dr),qo=F(y(os,S(477),g(d(421)))),zg=_(qo),Wo=F(y(os,S(478),g(d(421))),y(os,S(448),g(d(449)),S(477),g(d(421)))),$g=_(Wo),Go=y(Se,S(280),g(d(466)),g(d(466)),g(d(421))),Hg=_(Go),Xo=y(Dr,S(465),g(d(466)),g(d(466)),g(d(421))),Vg=_(Xo),vr=F(qo,Wo,y(cs,g(d(421))),y(el,g(d(421))),y(Ot,g(d(421))),Go,Xo,d(421)),qg=_(vr),rl=y(vr,S(290),d(421)),Wg=_(rl),nl=F(y(vr,S(290),S(281),g(d(421))),y(vr,S(281),g(d(421))),y(S(281),g(d(421)))),Gg=_(nl),sl=F(y(Ot,d(6),S(480),g(d(421))),y(Ot,S(480),g(d(421)))),Qo=_(sl),ol=y(Ot,F(y(d(6,"443"),S(480)),y(d(6),S(443)),y(d(6),S(448),S(480)),y(S(448),S(480)),S(448),S(443)),g(d(421))),Zo=_(ol),il=F(y(d(777),g(d(421)))),Xg=_(il),al=F(y(d(400),g(d(421)))),Qg=_(al);function us(r,t,e){return r.filter(n=>{if(Zo.matches(n)||t&&Qo.matches(n))return e||$o.matches(n)?!0:zo(n.toOptions().host)===!1;if(!t&&e){let{host:s}=n.toOptions();if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*Ar(r,t,e,n,s,o={}){for await(let i of t.findProviders(r,o)){let a=us(i.multiaddrs,n,s);if(a.length===0)continue;let c=_r(a[0]);yield new ne(c,{logger:e,transformRequestInit:o.transformRequestInit})}}async function Ko(r,t,e){let{signal:n,log:s}=e??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>t)throw s?.error("content-length header (%d) is greater than the limit (%d)",c,t),r.body!=null&&await r.body.cancel().catch(l=>{s?.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 ft;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=>{s?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var ne=class{url;#t=0;#e=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;constructor(t,{logger:e,transformRequestInit:n}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#o(t){let e=t.multihash.bytes;return it.encode(e)}async getRawBlock(t,{signal:e,maxSize:n=Jo}={}){let s=new URL(this.url.toString());if(s.pathname=`/ipfs/${t.toString()}`,s.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let o=this.#o(t),i=new AbortController,a=()=>{i.abort()};e?.addEventListener("abort",a);try{let c=this.#n.get(o);if(c==null){this.#t++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l;c=fetch(s.toString(),u).then(async h=>{if(this.log("GET %s %d",s,h.status),!h.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);let f=await Ko(h,n,{signal:i.signal,log:this.log});return this.#s++,f}),this.#n.set(o,c)}return await c}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`unable to fetch raw block for CID ${t}`))}finally{e?.removeEventListener("abort",a),this.#n.delete(o)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#s/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#n.size}}};var hs=class extends Ct{routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Cr,this.allowLocal=e.allowLocal??Tr,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let s=await e.getRawBlock(t,n);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(s),s}async*findNewProviders(t,e={}){yield*Ar(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e){if(De(t))return;let n=us(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(n.length===0)return;let s=_r(n[0]);return new ne(s,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function jo(r,t){return new hs(r,t)}var Lr=class{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??Cr,this.allowLocal=e.allowLocal??Tr,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let s of Ar(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,s.url);try{await e.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s",t,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s",t,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${s.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,s.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 jo({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Cr=!1,Tr=!1,Jo=2097152;function Yo(r={}){return t=>new Lr(t,r)}return oi(cl);})();
|
|
3
3
|
return HeliaBlockBrokers}));
|
|
4
4
|
//# sourceMappingURL=index.min.js.map
|