@helia/bitswap 1.1.3 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBitswap = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaBitswap=(()=>{var Fn=Object.create;var Je=Object.defineProperty;var zn=Object.getOwnPropertyDescriptor;var Hn=Object.getOwnPropertyNames;var Vn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var Ze=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),C=(r,e)=>{for(var t in e)Je(r,t,{get:e[t],enumerable:!0})},Rr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Hn(e))!qn.call(r,s)&&s!==t&&Je(r,s,{get:()=>e[s],enumerable:!(n=zn(e,s))||n.enumerable});return r};var _t=(r,e,t)=>(t=r!=null?Fn(Vn(r)):{},Rr(e||!r||!r.__esModule?Je(t,"default",{value:r,enumerable:!0}):t,r)),Gn=r=>Rr(Je({},"__esModule",{value:!0}),r);var zr=Ze((Wo,Fr)=>{"use strict";function Or(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function ts(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return Or(r,t)}catch{t.message=r.message,t.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Or(new s,t)}}Fr.exports=ts});var In=Ze((Ge,xt)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(o){if(!Array.isArray(o)&&!ArrayBuffer.isView(o))return!1;for(var l=0;l<o.length;l++)if(!Number.isInteger(o[l])||o[l]<0||o[l]>255)return!1;return!0}function s(o,l){return(o&65535)*l+(((o>>>16)*l&65535)<<16)}function i(o,l){return o<<l|o>>>32-l}function a(o){return o^=o>>>16,o=s(o,2246822507),o^=o>>>13,o=s(o,3266489909),o^=o>>>16,o}function c(o,l){o=[o[0]>>>16,o[0]&65535,o[1]>>>16,o[1]&65535],l=[l[0]>>>16,l[0]&65535,l[1]>>>16,l[1]&65535];var u=[0,0,0,0];return u[3]+=o[3]+l[3],u[2]+=u[3]>>>16,u[3]&=65535,u[2]+=o[2]+l[2],u[1]+=u[2]>>>16,u[2]&=65535,u[1]+=o[1]+l[1],u[0]+=u[1]>>>16,u[1]&=65535,u[0]+=o[0]+l[0],u[0]&=65535,[u[0]<<16|u[1],u[2]<<16|u[3]]}function h(o,l){o=[o[0]>>>16,o[0]&65535,o[1]>>>16,o[1]&65535],l=[l[0]>>>16,l[0]&65535,l[1]>>>16,l[1]&65535];var u=[0,0,0,0];return u[3]+=o[3]*l[3],u[2]+=u[3]>>>16,u[3]&=65535,u[2]+=o[2]*l[3],u[1]+=u[2]>>>16,u[2]&=65535,u[2]+=o[3]*l[2],u[1]+=u[2]>>>16,u[2]&=65535,u[1]+=o[1]*l[3],u[0]+=u[1]>>>16,u[1]&=65535,u[1]+=o[2]*l[2],u[0]+=u[1]>>>16,u[1]&=65535,u[1]+=o[3]*l[1],u[0]+=u[1]>>>16,u[1]&=65535,u[0]+=o[0]*l[3]+o[1]*l[2]+o[2]*l[1]+o[3]*l[0],u[0]&=65535,[u[0]<<16|u[1],u[2]<<16|u[3]]}function p(o,l){return l%=64,l===32?[o[1],o[0]]:l<32?[o[0]<<l|o[1]>>>32-l,o[1]<<l|o[0]>>>32-l]:(l-=32,[o[1]<<l|o[0]>>>32-l,o[0]<<l|o[1]>>>32-l])}function y(o,l){return l%=64,l===0?o:l<32?[o[0]<<l|o[1]>>>32-l,o[1]<<l]:[o[1]<<l-32,0]}function m(o,l){return[o[0]^l[0],o[1]^l[1]]}function L(o){return o=m(o,[0,o[0]>>>1]),o=h(o,[4283543511,3981806797]),o=m(o,[0,o[0]>>>1]),o=h(o,[3301882366,444984403]),o=m(o,[0,o[0]>>>1]),o}t.x86.hash32=function(o,l){if(t.inputValidation&&!n(o))return e;l=l||0;for(var u=o.length%4,E=o.length-u,f=l,d=0,g=3432918353,b=461845907,x=0;x<E;x=x+4)d=o[x]|o[x+1]<<8|o[x+2]<<16|o[x+3]<<24,d=s(d,g),d=i(d,15),d=s(d,b),f^=d,f=i(f,13),f=s(f,5)+3864292196;switch(d=0,u){case 3:d^=o[x+2]<<16;case 2:d^=o[x+1]<<8;case 1:d^=o[x],d=s(d,g),d=i(d,15),d=s(d,b),f^=d}return f^=o.length,f=a(f),f>>>0},t.x86.hash128=function(o,l){if(t.inputValidation&&!n(o))return e;l=l||0;for(var u=o.length%16,E=o.length-u,f=l,d=l,g=l,b=l,x=0,v=0,w=0,A=0,Q=597399067,Xe=2869860233,Qe=951274213,Ke=2716044179,S=0;S<E;S=S+16)x=o[S]|o[S+1]<<8|o[S+2]<<16|o[S+3]<<24,v=o[S+4]|o[S+5]<<8|o[S+6]<<16|o[S+7]<<24,w=o[S+8]|o[S+9]<<8|o[S+10]<<16|o[S+11]<<24,A=o[S+12]|o[S+13]<<8|o[S+14]<<16|o[S+15]<<24,x=s(x,Q),x=i(x,15),x=s(x,Xe),f^=x,f=i(f,19),f+=d,f=s(f,5)+1444728091,v=s(v,Xe),v=i(v,16),v=s(v,Qe),d^=v,d=i(d,17),d+=g,d=s(d,5)+197830471,w=s(w,Qe),w=i(w,17),w=s(w,Ke),g^=w,g=i(g,15),g+=b,g=s(g,5)+2530024501,A=s(A,Ke),A=i(A,18),A=s(A,Q),b^=A,b=i(b,13),b+=f,b=s(b,5)+850148119;switch(x=0,v=0,w=0,A=0,u){case 15:A^=o[S+14]<<16;case 14:A^=o[S+13]<<8;case 13:A^=o[S+12],A=s(A,Ke),A=i(A,18),A=s(A,Q),b^=A;case 12:w^=o[S+11]<<24;case 11:w^=o[S+10]<<16;case 10:w^=o[S+9]<<8;case 9:w^=o[S+8],w=s(w,Qe),w=i(w,17),w=s(w,Ke),g^=w;case 8:v^=o[S+7]<<24;case 7:v^=o[S+6]<<16;case 6:v^=o[S+5]<<8;case 5:v^=o[S+4],v=s(v,Xe),v=i(v,16),v=s(v,Qe),d^=v;case 4:x^=o[S+3]<<24;case 3:x^=o[S+2]<<16;case 2:x^=o[S+1]<<8;case 1:x^=o[S],x=s(x,Q),x=i(x,15),x=s(x,Xe),f^=x}return f^=o.length,d^=o.length,g^=o.length,b^=o.length,f+=d,f+=g,f+=b,d+=f,g+=f,b+=f,f=a(f),d=a(d),g=a(g),b=a(b),f+=d,f+=g,f+=b,d+=f,g+=f,b+=f,("00000000"+(f>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)},t.x64.hash128=function(o,l){if(t.inputValidation&&!n(o))return e;l=l||0;for(var u=o.length%16,E=o.length-u,f=[0,l],d=[0,l],g=[0,0],b=[0,0],x=[2277735313,289559509],v=[1291169091,658871167],w=0;w<E;w=w+16)g=[o[w+4]|o[w+5]<<8|o[w+6]<<16|o[w+7]<<24,o[w]|o[w+1]<<8|o[w+2]<<16|o[w+3]<<24],b=[o[w+12]|o[w+13]<<8|o[w+14]<<16|o[w+15]<<24,o[w+8]|o[w+9]<<8|o[w+10]<<16|o[w+11]<<24],g=h(g,x),g=p(g,31),g=h(g,v),f=m(f,g),f=p(f,27),f=c(f,d),f=c(h(f,[0,5]),[0,1390208809]),b=h(b,v),b=p(b,33),b=h(b,x),d=m(d,b),d=p(d,31),d=c(d,f),d=c(h(d,[0,5]),[0,944331445]);switch(g=[0,0],b=[0,0],u){case 15:b=m(b,y([0,o[w+14]],48));case 14:b=m(b,y([0,o[w+13]],40));case 13:b=m(b,y([0,o[w+12]],32));case 12:b=m(b,y([0,o[w+11]],24));case 11:b=m(b,y([0,o[w+10]],16));case 10:b=m(b,y([0,o[w+9]],8));case 9:b=m(b,[0,o[w+8]]),b=h(b,v),b=p(b,33),b=h(b,x),d=m(d,b);case 8:g=m(g,y([0,o[w+7]],56));case 7:g=m(g,y([0,o[w+6]],48));case 6:g=m(g,y([0,o[w+5]],40));case 5:g=m(g,y([0,o[w+4]],32));case 4:g=m(g,y([0,o[w+3]],24));case 3:g=m(g,y([0,o[w+2]],16));case 2:g=m(g,y([0,o[w+1]],8));case 1:g=m(g,[0,o[w]]),g=h(g,x),g=p(g,31),g=h(g,v),f=m(f,g)}return f=m(f,[0,o.length]),d=m(d,[0,o.length]),f=c(f,d),d=c(d,f),f=L(f),d=L(d),f=c(f,d),d=c(d,f),("00000000"+(f[0]>>>0).toString(16)).slice(-8)+("00000000"+(f[1]>>>0).toString(16)).slice(-8)+("00000000"+(d[0]>>>0).toString(16)).slice(-8)+("00000000"+(d[1]>>>0).toString(16)).slice(-8)},typeof Ge<"u"?(typeof xt<"u"&&xt.exports&&(Ge=xt.exports=t),Ge.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(Ge)});var Rn=Ze((Sl,Mn)=>{Mn.exports=In()});var Cn=Ze((sh,Bn)=>{Bn.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(i,a){t[i]=a,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var a=t[i];if(a!==void 0)return a;if((a=n[i])!==void 0)return s(i,a),a},set:function(i,a){t[i]!==void 0?t[i]=a:s(i,a)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Zi={};C(Zi,{createBitswap:()=>Ji});var Dt=Symbol.for("@libp2p/peer-id");var Z=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},B=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var U=(r,...e)=>{try{[...e]}catch{}};var W=class extends EventTarget{#e=new Map;constructor(){super(),U(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:i})=>i!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Wn(e,t))}},Tt=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Wn=globalThis.CustomEvent??Tt;function Nr(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}function V(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ye=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},fe=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ye(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Ye(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var It=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function de(r={}){return $n(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function $n(r,e){e=e??{};let t=e.onEnd,n=new fe,s,i,a,c=V(),h=async()=>{try{return n.isEmpty()?a?{done:!0}:await new Promise((E,f)=>{i=d=>{i=null,n.push(d);try{E(r(n))}catch(g){f(g)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=V()})}},p=E=>i!=null?i(E):(n.push(E),s),y=E=>(n=new fe,i!=null?i({error:E}):(n.push({error:E}),s)),m=E=>{if(a)return s;if(e?.objectMode!==!0&&E?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return p({done:!1,value:E})},L=E=>a?s:(a=!0,E!=null?y(E):p({done:!0})),o=()=>(n=new fe,L(),{done:!0}),l=E=>(L(E),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:h,return:o,throw:l,push:m,end:L,get readableLength(){return n.size},onEmpty:async E=>{let f=E?.signal;if(f?.throwIfAborted(),n.isEmpty())return;let d,g;f!=null&&(d=new Promise((b,x)=>{g=()=>{x(new It)},f.addEventListener("abort",g)}));try{await Promise.race([c.promise,d])}finally{g!=null&&f!=null&&f?.removeEventListener("abort",g)}}},t==null)return s;let u=s;return s={[Symbol.asyncIterator](){return this},next(){return u.next()},throw(E){return u.throw(E),t!=null&&(t(E),t=void 0),{done:!0}},return(){return u.return(),t!=null&&(t(),t=void 0),{done:!0}},push:m,end(E){return u.end(E),t!=null&&(t(E),t=void 0),s},get readableLength(){return u.readableLength},onEmpty:E=>u.onEmpty(E)},s}var Mt=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function q(r,e,t,n){let s=new Mt(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){t?.removeEventListener("abort",y),r.removeEventListener(e,h),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,p)}let h=m=>{try{if(n?.filter?.(m)===!1)return}catch(L){c(),a(L);return}c(),i(m)},p=m=>{c(),a(m.detail)},y=()=>{c(),a(s)};t?.addEventListener("abort",y),r.addEventListener(e,h),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,p)})}var je=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Br(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new je(t?.errorMessage,t?.errorCode));let n,s=new je(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((i,a)=>{n=()=>{a(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var et=class{deferred;signal;constructor(e){this.signal=e,this.deferred=V(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Z)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Xn(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var tt=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Xn(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,U(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Z),this.cleanup())}async join(e={}){let t=new et(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Br(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var pe=class extends W{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let n=new tt(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Z)}),this.clear()}async onEmpty(e){this.size!==0&&await q(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await q(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await q(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=de({objectMode:!0}),n=h=>{h!=null?this.abort():this.clear(),t.end(h)},s=h=>{h.detail!=null&&t.push(h.detail)},i=h=>{n(h.detail)},a=()=>{n()},c=()=>{n(new B("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",a),e?.signal?.addEventListener("abort",c);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",a),e?.signal?.removeEventListener("abort",c),n()}}};var rt=class extends pe{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function Qn(r){return r[Symbol.asyncIterator]!=null}function Kn(r){if(Qn(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Rt=Kn;function I(r=0){return new Uint8Array(r)}function M(r=0){return new Uint8Array(r)}var Jn=Math.pow(2,7),Zn=Math.pow(2,14),Yn=Math.pow(2,21),Nt=Math.pow(2,28),Bt=Math.pow(2,35),Ct=Math.pow(2,42),Ut=Math.pow(2,49),k=128,R=127;function T(r){if(r<Jn)return 1;if(r<Zn)return 2;if(r<Yn)return 3;if(r<Nt)return 4;if(r<Bt)return 5;if(r<Ct)return 6;if(r<Ut)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Pt(r,e,t=0){switch(T(r)){case 8:e[t++]=r&255|k,r/=128;case 7:e[t++]=r&255|k,r/=128;case 6:e[t++]=r&255|k,r/=128;case 5:e[t++]=r&255|k,r/=128;case 4:e[t++]=r&255|k,r>>>=7;case 3:e[t++]=r&255|k,r>>>=7;case 2:e[t++]=r&255|k,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function jn(r,e,t=0){switch(T(r)){case 8:e.set(t++,r&255|k),r/=128;case 7:e.set(t++,r&255|k),r/=128;case 6:e.set(t++,r&255|k),r/=128;case 5:e.set(t++,r&255|k),r/=128;case 4:e.set(t++,r&255|k),r>>>=7;case 3:e.set(t++,r&255|k),r>>>=7;case 2:e.set(t++,r&255|k),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Ot(r,e){let t=r[e],n=0;if(n+=t&R,t<k||(t=r[e+1],n+=(t&R)<<7,t<k)||(t=r[e+2],n+=(t&R)<<14,t<k)||(t=r[e+3],n+=(t&R)<<21,t<k)||(t=r[e+4],n+=(t&R)*Nt,t<k)||(t=r[e+5],n+=(t&R)*Bt,t<k)||(t=r[e+6],n+=(t&R)*Ct,t<k)||(t=r[e+7],n+=(t&R)*Ut,t<k))return n;throw new RangeError("Could not decode varint")}function es(r,e){let t=r.get(e),n=0;if(n+=t&R,t<k||(t=r.get(e+1),n+=(t&R)<<7,t<k)||(t=r.get(e+2),n+=(t&R)<<14,t<k)||(t=r.get(e+3),n+=(t&R)<<21,t<k)||(t=r.get(e+4),n+=(t&R)*Nt,t<k)||(t=r.get(e+5),n+=(t&R)*Bt,t<k)||(t=r.get(e+6),n+=(t&R)*Ct,t<k)||(t=r.get(e+7),n+=(t&R)*Ut,t<k))return n;throw new RangeError("Could not decode varint")}function nt(r,e,t=0){return e==null&&(e=M(T(r))),e instanceof Uint8Array?Pt(r,e,t):jn(r,e,t)}function st(r,e=0){return r instanceof Uint8Array?Ot(r,e):es(r,e)}function Ft(r,e){e==null&&(e=r.reduce((s,i)=>s+i.length,0));let t=M(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}function $(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Pr=Symbol.for("@achingbrain/uint8arraylist");function Ur(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function it(r){return!!r?.[Pr]}var Y=class r{bufs;length;[Pr]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(it(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(it(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Ur(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ur(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(it(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ft(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ft(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),i=new r;return i.length=s,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let a=this.bufs[i],c=s,h=c+a.byteLength;if(s=h,e>=h)continue;let p=e>=c&&e<h,y=t>c&&t<=h;if(p&&y){if(e===c&&t===h){n.push(a);break}let m=e-c;n.push(a.subarray(m,m+(t-e)));break}if(p){if(e===0){n.push(a);continue}n.push(a.subarray(e-c));continue}if(y){if(t===h){n.push(a);break}n.push(a.subarray(0,t-c));break}n.push(a)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!it(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,a=new Int32Array(i);for(let m=0;m<i;m++)a[m]=-1;for(let m=0;m<s;m++)a[n[m]]=m;let c=a,h=this.byteLength-n.byteLength,p=n.byteLength-1,y;for(let m=t;m<=h;m+=y){y=0;for(let L=p;L>=0;L--){let o=this.get(m+L);if(n[L]!==o){y=Math.max(1,L-c[o]);break}}if(y===0)return m}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=M(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=I(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=I(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=I(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=M(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=I(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=I(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=I(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=I(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=I(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!$(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,i)=>s+i.byteLength,0)),n.length=t,n}};function ot(r){return r[Symbol.asyncIterator]!=null}var at=r=>{let e=T(r),t=M(e);return nt(r,t),at.bytes=e,t};at.bytes=0;function ct(r,e){e=e??{};let t=e.lengthEncoder??at;function*n(s){let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return ot(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}ct.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??at;return new Y(t(r.byteLength),r)};var me=_t(zr(),1);var rs=8,ns=1024*1024*4,re;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(re||(re={}));var zt=r=>{let e=st(r);return zt.bytes=T(e),e};zt.bytes=0;function Te(r,e){let t=new Y,n=re.LENGTH,s=-1,i=e?.lengthDecoder??zt,a=e?.maxLengthLength??rs,c=e?.maxDataLength??ns;function*h(){for(;t.byteLength>0;){if(n===re.LENGTH)try{if(s=i(t),s<0)throw(0,me.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,me.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let p=i.bytes;t.consume(p),e?.onLength!=null&&e.onLength(s),n=re.DATA}catch(p){if(p instanceof RangeError){if(t.byteLength>a)throw(0,me.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw p}if(n===re.DATA){if(t.byteLength<s)break;let p=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(p),yield p,n=re.LENGTH}}}return ot(r)?async function*(){for await(let p of r)t.append(p),yield*h();if(t.byteLength>0)throw(0,me.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let p of r)t.append(p),yield*h();if(t.byteLength>0)throw(0,me.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Te.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:i,value:a}=await r.next(t);if(i===!0)return;a!=null&&(yield a)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}}();return Te(n,{...e??{},onLength:i=>{t=i}})};function is(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Hr=is;function os(r){return r[Symbol.asyncIterator]!=null}function as(r,e){let t=0;if(os(r))return async function*(){for await(let h of r)yield e(h,t++)}();let n=Hr(r),{value:s,done:i}=n.next();if(i===!0)return function*(){}();let a=e(s,t++);if(typeof a.then=="function")return async function*(){yield await a;for await(let h of n)yield e(h,t++)}();let c=e;return function*(){yield a;for(let h of n)yield c(h,t++)}()}var Vr=as;function cs(r){return r[Symbol.asyncIterator]!=null}function ls(...r){let e=[];for(let t of r)cs(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=de({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var qr=ls;function Vt(r,...e){if(r==null)throw new Error("Empty pipeline");if(Ht(r)){let n=r;r=()=>n.source}else if(Wr(r)||Gr(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Ht(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Ht(t[n])&&(t[n]=us(t[n]));return hs(...t)}var hs=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Gr=r=>r?.[Symbol.asyncIterator]!=null,Wr=r=>r?.[Symbol.iterator]!=null,Ht=r=>r==null?!1:r.sink!=null&&r.source!=null,us=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=de({objectMode:!0});t.then(()=>{n.end()},a=>{n.end(a)});let s,i=r.source;if(Gr(i))s=async function*(){yield*i,n.end()};else if(Wr(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return qr(n,s())}return r.source};function fs(r){return r[Symbol.asyncIterator]!=null}function ds(r,e){return fs(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var $r=ds;var X=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Ie="/ipfs/bitswap/1.2.0";var qt=new Float32Array([-0]),j=new Uint8Array(qt.buffer);function Xr(r,e,t){qt[0]=r,e[t]=j[0],e[t+1]=j[1],e[t+2]=j[2],e[t+3]=j[3]}function Qr(r,e){return j[0]=r[e],j[1]=r[e+1],j[2]=r[e+2],j[3]=r[e+3],qt[0]}var Gt=new Float64Array([-0]),N=new Uint8Array(Gt.buffer);function Kr(r,e,t){Gt[0]=r,e[t]=N[0],e[t+1]=N[1],e[t+2]=N[2],e[t+3]=N[3],e[t+4]=N[4],e[t+5]=N[5],e[t+6]=N[6],e[t+7]=N[7]}function Jr(r,e){return N[0]=r[e],N[1]=r[e+1],N[2]=r[e+2],N[3]=r[e+3],N[4]=r[e+4],N[5]=r[e+5],N[6]=r[e+6],N[7]=r[e+7],Gt[0]}var ps=BigInt(Number.MAX_SAFE_INTEGER),ms=BigInt(Number.MIN_SAFE_INTEGER),P=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ne;if(e<ps&&e>ms)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Zr&&(s=0n,++n>Zr&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return ne;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ne}},ne=new P(0,0);ne.toBigInt=function(){return 0n};ne.zzEncode=ne.zzDecode=function(){return this};ne.length=function(){return 1};var Zr=4294967296n;function Yr(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function jr(r,e,t){if(t-e<1)return"";let s,i=[],a=0,c;for(;e<t;)c=r[e++],c<128?i[a++]=c:c>191&&c<224?i[a++]=(c&31)<<6|r[e++]&63:c>239&&c<365?(c=((c&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[a++]=55296+(c>>10),i[a++]=56320+(c&1023)):i[a++]=(c&15)<<12|(r[e++]&63)<<6|r[e++]&63,a>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),a=0);return s!=null?(a>0&&s.push(String.fromCharCode.apply(String,i.slice(0,a))),s.join("")):String.fromCharCode.apply(String,i.slice(0,a))}function Wt(r,e,t){let n=t,s,i;for(let a=0;a<r.length;++a)s=r.charCodeAt(a),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++a,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function G(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function lt(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var $t=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,G(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw G(this,4);return lt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw G(this,4);return lt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw G(this,4);let e=Qr(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw G(this,4);let e=Jr(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw G(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return jr(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw G(this,e);this.pos+=e}else do if(this.pos>=this.len)throw G(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new P(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw G(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw G(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw G(this,8);let e=lt(this.buf,this.pos+=4),t=lt(this.buf,this.pos+=4);return new P(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Ot(this.buf,this.pos);return this.pos+=T(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Xt(r){return new $t(r instanceof Uint8Array?r:r.subarray())}function se(r,e,t){let n=Xt(r);return e.decode(n,void 0,t)}var Yt={};C(Yt,{base10:()=>Es});var ga=new Uint8Array(0);function tn(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function K(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 rn(r){return new TextEncoder().encode(r)}function nn(r){return new TextDecoder().decode(r)}function gs(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(t[a]!==255)throw new TypeError(i+" is ambiguous");t[a]=s}var c=r.length,h=r.charAt(0),p=Math.log(c)/Math.log(256),y=Math.log(256)/Math.log(c);function m(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var u=0,E=0,f=0,d=l.length;f!==d&&l[f]===0;)f++,u++;for(var g=(d-f)*y+1>>>0,b=new Uint8Array(g);f!==d;){for(var x=l[f],v=0,w=g-1;(x!==0||v<E)&&w!==-1;w--,v++)x+=256*b[w]>>>0,b[w]=x%c>>>0,x=x/c>>>0;if(x!==0)throw new Error("Non-zero carry");E=v,f++}for(var A=g-E;A!==g&&b[A]===0;)A++;for(var Q=h.repeat(u);A<g;++A)Q+=r.charAt(b[A]);return Q}function L(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var u=0;if(l[u]!==" "){for(var E=0,f=0;l[u]===h;)E++,u++;for(var d=(l.length-u)*p+1>>>0,g=new Uint8Array(d);l[u];){var b=t[l.charCodeAt(u)];if(b===255)return;for(var x=0,v=d-1;(b!==0||x<f)&&v!==-1;v--,x++)b+=c*g[v]>>>0,g[v]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");f=x,u++}if(l[u]!==" "){for(var w=d-f;w!==d&&g[w]===0;)w++;for(var A=new Uint8Array(E+(d-w)),Q=E;w!==d;)A[Q++]=g[w++];return A}}}function o(l){var u=L(l);if(u)return u;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:L,decode:o}}var ws=gs,bs=ws,on=bs;var Qt=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Kt=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return an(this,e)}},Jt=class{decoders;constructor(e){this.decoders=e}or(e){return an(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function an(r,e){return new Jt({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Zt=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Qt(e,t,n),this.decoder=new Kt(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ge({name:r,prefix:e,encode:t,decode:n}){return new Zt(r,e,t,n)}function ee({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=on(t,r);return ge({prefix:e,name:r,encode:n,decode:i=>K(s(i))})}function ys(r,e,t,n){let s={};for(let y=0;y<e.length;++y)s[e[y]]=y;let i=r.length;for(;r[i-1]==="=";)--i;let a=new Uint8Array(i*t/8|0),c=0,h=0,p=0;for(let y=0;y<i;++y){let m=s[r[y]];if(m===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<t|m,c+=t,c>=8&&(c-=8,a[p++]=255&h>>c)}if(c>=t||255&h<<8-c)throw new SyntaxError("Unexpected end of data");return a}function xs(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,i="",a=0,c=0;for(let h=0;h<r.length;++h)for(c=c<<8|r[h],a+=8;a>t;)a-=t,i+=e[s&c>>a];if(a!==0&&(i+=e[s&c<<t-a]),n)for(;i.length*t&7;)i+="=";return i}function _({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return ge({prefix:e,name:r,encode(s){return xs(s,n,t)},decode(s){return ys(s,n,t,r)}})}var Es=ee({prefix:"9",name:"base10",alphabet:"0123456789"});var jt={};C(jt,{base16:()=>vs,base16upper:()=>Ss});var vs=_({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ss=_({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var er={};C(er,{base2:()=>ks});var ks=_({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var tr={};C(tr,{base256emoji:()=>Ts});var cn=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}"),As=cn.reduce((r,e,t)=>(r[t]=e,r),[]),Ls=cn.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function _s(r){return r.reduce((e,t)=>(e+=As[t],e),"")}function Ds(r){let e=[];for(let t of r){let n=Ls[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Ts=ge({prefix:"\u{1F680}",name:"base256emoji",encode:_s,decode:Ds});var rr={};C(rr,{base32:()=>we,base32hex:()=>Ns,base32hexpad:()=>Cs,base32hexpadupper:()=>Us,base32hexupper:()=>Bs,base32pad:()=>Ms,base32padupper:()=>Rs,base32upper:()=>Is,base32z:()=>Ps});var we=_({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Is=_({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ms=_({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rs=_({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ns=_({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Bs=_({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cs=_({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Us=_({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ps=_({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var nr={};C(nr,{base36:()=>Os,base36upper:()=>Fs});var Os=ee({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Fs=ee({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var sr={};C(sr,{base58btc:()=>O,base58flickr:()=>zs});var O=ee({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zs=ee({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ir={};C(ir,{base64:()=>ie,base64pad:()=>Hs,base64url:()=>Vs,base64urlpad:()=>qs});var ie=_({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Hs=_({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Vs=_({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qs=_({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var or={};C(or,{base8:()=>Gs});var Gs=_({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ar={};C(ar,{identity:()=>Ws});var Ws=ge({prefix:"\0",name:"identity",encode:r=>nn(r),decode:r=>rn(r)});var Ra=new TextEncoder,Na=new TextDecoder;var lr={};C(lr,{identity:()=>Be});var Qs=un,ln=128,Ks=127,Js=~Ks,Zs=Math.pow(2,31);function un(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Zs;)e[t++]=r&255|ln,r/=128;for(;r&Js;)e[t++]=r&255|ln,r>>>=7;return e[t]=r|0,un.bytes=t-n+1,e}var Ys=cr,js=128,hn=127;function cr(r,n){var t=0,n=n||0,s=0,i=n,a,c=r.length;do{if(i>=c)throw cr.bytes=0,new RangeError("Could not decode varint");a=r[i++],t+=s<28?(a&hn)<<s:(a&hn)*Math.pow(2,s),s+=7}while(a>=js);return cr.bytes=i-n,t}var ei=Math.pow(2,7),ti=Math.pow(2,14),ri=Math.pow(2,21),ni=Math.pow(2,28),si=Math.pow(2,35),ii=Math.pow(2,42),oi=Math.pow(2,49),ai=Math.pow(2,56),ci=Math.pow(2,63),li=function(r){return r<ei?1:r<ti?2:r<ri?3:r<ni?4:r<si?5:r<ii?6:r<oi?7:r<ai?8:r<ci?9:10},hi={encode:Qs,decode:Ys,encodingLength:li},ui=hi,Me=ui;function Re(r,e=0){return[Me.decode(r,e),Me.decode.bytes]}function be(r,e,t=0){return Me.encode(r,e,t),e}function ye(r){return Me.encodingLength(r)}function te(r,e){let t=e.byteLength,n=ye(r),s=n+ye(t),i=new Uint8Array(s+t);return be(r,i,0),be(t,i,n),i.set(e,s),new xe(r,t,e,i)}function Ne(r){let e=K(r),[t,n]=Re(e),[s,i]=Re(e.subarray(n)),a=e.subarray(n+i);if(a.byteLength!==s)throw new Error("Incorrect length");return new xe(t,s,a,e)}function fn(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&tn(r.bytes,t.bytes)}}var xe=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var dn=0,fi="identity",pn=K;function di(r){return te(dn,pn(r))}var Be={code:dn,name:fi,encode:pn,digest:di};var fr={};C(fr,{sha256:()=>oe,sha512:()=>pi});function ur({name:r,code:e,encode:t}){return new hr(r,e,t)}var hr=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?te(this.code,t):t.then(n=>te(this.code,n))}else throw Error("Unknown type, must be binary type")}};function gn(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var oe=ur({name:"sha2-256",code:18,encode:gn("SHA-256")}),pi=ur({name:"sha2-512",code:19,encode:gn("SHA-512")});function wn(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return gi(t,dr(r),e??O.encoder);default:return wi(t,dr(r),e??we.encoder)}}var bn=new WeakMap;function dr(r){let e=bn.get(r);if(e==null){let t=new Map;return bn.set(r,t),t}return e}var F=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,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:e,multihash:t}=this;if(e!==Ce)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==bi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=te(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&fn(e.multihash,n.multihash)}toString(e){return wn(this,e)}toJSON(){return{"/":wn(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:i,bytes:a}=t;return new r(n,s,i,a??yn(n,s,i.bytes))}else if(t[yi]===!0){let{version:n,multihash:s,code:i}=t,a=Ne(s);return r.create(n,i,a)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ce)throw new Error(`Version 0 CID must use dag-pb (code: ${Ce}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=yn(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ce,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=K(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),a=new xe(t.multihashCode,t.digestSize,i,s);return[t.version===0?r.createV0(a):r.createV1(t.codec,a),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[m,L]=Re(e.subarray(t));return t+=L,m},s=n(),i=Ce;if(s===18?(s=0,t=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let a=t,c=n(),h=n(),p=t+h,y=p-a;return{version:s,codec:i,multihashCode:c,digestSize:h,multihashSize:y,size:p}}static parse(e,t){let[n,s]=mi(e,t),i=r.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return dr(i).set(n,e),i}};function mi(r,e){switch(r[0]){case"Q":{let t=e??O;return[O.prefix,t.decode(`${O.prefix}${r}`)]}case O.prefix:{let t=e??O;return[O.prefix,t.decode(r)]}case we.prefix:{let t=e??we;return[we.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function gi(r,e,t){let{prefix:n}=t;if(n!==O.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return s}function wi(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let i=t.encode(r);return e.set(n,i),i}else return s}var Ce=112,bi=18;function yn(r,e,t){let n=ye(r),s=n+ye(e),i=new Uint8Array(s+t.byteLength);return be(r,i,0),be(e,i,n),i.set(t,s),i}var yi=Symbol.for("@ipld/js-cid/CID");var ve={...ar,...er,...or,...Yt,...jt,...rr,...nr,...sr,...ir,...tr},ec={...fr,...lr};function En(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var xn=En("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),pr=En("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=M(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),xi={utf8:xn,"utf-8":xn,hex:ve.base16,latin1:pr,ascii:pr,binary:pr,...ve},ut=xi;function ae(r,e="utf8"){let t=ut[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function mr(r){let e=r??8192,t=e>>>1,n,s=e;return function(a){if(a<1||a>t)return M(a);s+a>e&&(n=M(e),s=0);let c=n.subarray(s,s+=a);return s&7&&(s=(s|7)+1),c}}var ce=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function gr(){}var br=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ei=mr();function vi(r){return globalThis.Buffer!=null?M(r):Ei(r)}var Pe=class{len;head;tail;states;constructor(){this.len=0,this.head=new ce(gr,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ce(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new yr((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(ft,10,P.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=P.fromBigInt(e);return this._push(ft,t.length(),t)}uint64Number(e){return this._push(Pt,T(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=P.fromBigInt(e).zzEncode();return this._push(ft,t.length(),t)}sint64Number(e){let t=P.fromNumber(e).zzEncode();return this._push(ft,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(wr,1,e?1:0)}fixed32(e){return this._push(Ue,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=P.fromBigInt(e);return this._push(Ue,4,t.lo)._push(Ue,4,t.hi)}fixed64Number(e){let t=P.fromNumber(e);return this._push(Ue,4,t.lo)._push(Ue,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Xr,4,e)}double(e){return this._push(Kr,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(wr,1,0):this.uint32(t)._push(ki,t,e)}string(e){let t=Yr(e);return t!==0?this.uint32(t)._push(Wt,t,e):this._push(wr,1,0)}fork(){return this.states=new br(this),this.head=this.tail=new ce(gr,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 ce(gr,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=vi(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function wr(r,e,t){e[t]=r&255}function Si(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var yr=class extends ce{next;constructor(e,t){super(Si,e,t),this.next=void 0}};function ft(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Ue(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function ki(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Pe.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Ai,e,r),this},Pe.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Li,e,r),this});function Ai(r,e,t){e.set(r,t)}function Li(r,e,t){r.length<40?Wt(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(ae(r),t)}function xr(){return new Pe}function le(r,e){let t=xr();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Se;(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"})(Se||(Se={}));function dt(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function pt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)};return dt("enum",Se.VARINT,t,n)}function he(r,e){return dt("message",Se.LENGTH_DELIMITED,r,e)}var ke=class extends Error{code;constructor(e,t,n){super(e,n),this.code=t}};var D;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(D||(D={}));var Er;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Er||(Er={}));(function(r){r.codec=()=>pt(Er)})(D||(D={}));var Ae;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),D.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={cid:I(0),priority:0},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{i.cid=t.bytes();break}case 2:{i.priority=t.int32();break}case 3:{i.cancel=t.bool();break}case 4:{i.wantType=D.codec().decode(t);break}case 5:{i.sendDontHave=t.bool();break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(Ae||(Ae={}));var mt;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let i of t.entries)n.uint32(10),Ae.codec().encode(i,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={entries:[]},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{if(s.limits?.entries!=null&&i.entries.length===s.limits.entries)throw new ke('decode error - map field "entries" had too many elements',"ERR_MAX_LENGTH");i.entries.push(Ae.codec().decode(t,t.uint32(),{limits:s.limits?.entries$}));break}case 2:{i.full=t.bool();break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(mt||(mt={}));var Le;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={prefix:I(0),data:I(0)},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{i.prefix=t.bytes();break}case 2:{i.data=t.bytes();break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(Le||(Le={}));var z;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(z||(z={}));var gt;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(gt||(gt={}));(function(r){r.codec=()=>pt(gt)})(z||(z={}));var _e;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&gt[t.type]!==0&&(n.uint32(16),z.codec().encode(t.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={cid:I(0),type:z.HaveBlock},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{i.cid=t.bytes();break}case 2:{i.type=z.codec().decode(t);break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(_e||(_e={}));var ue;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),mt.codec().encode(t.wantlist,n)),t.blocks!=null)for(let i of t.blocks)n.uint32(26),Le.codec().encode(i,n);if(t.blockPresences!=null)for(let i of t.blockPresences)n.uint32(34),_e.codec().encode(i,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={blocks:[],blockPresences:[],pendingBytes:0},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{i.wantlist=mt.codec().decode(t,t.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&i.blocks.length===s.limits.blocks)throw new ke('decode error - map field "blocks" had too many elements',"ERR_MAX_LENGTH");i.blocks.push(Le.codec().decode(t,t.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&i.blockPresences.length===s.limits.blockPresences)throw new ke('decode error - map field "blockPresences" had too many elements',"ERR_MAX_LENGTH");i.blockPresences.push(_e.codec().decode(t,t.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{i.pendingBytes=t.int32();break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(ue||(ue={}));function vn(r,e){for(let[t,n]of e.wantlist.entries()){let s=r.wantlist.get(t);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(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var _i=4193648,Di=_i+16;function*Sn(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],i=0,a=0,c=0,h=!1;for(;;){let p={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},y=ue.encode(p).byteLength,{added:m,hasMore:L,newSize:o}=vr(s,p.blocks,c,e,y,Ti);c+=m,y=o;let l=L;({added:m,hasMore:L,newSize:o}=vr(n,p.blockPresences,a,e,y,Ii)),a+=m,y=o;let u=L;if({added:m,hasMore:L,newSize:o}=vr(t,p.wantlist.entries,i,e,y,Mi),i+=m,y=o,h=!l&&!u&&!L,h||(p.wantlist.full=!1),yield ue.encode(p),h)break}}function vr(r,e,t,n,s,i){let a=0,c=!1;for(let h=t;h<r.length;h++){let p=r[h],y=i(p);if(y>Di)throw new B("Cannot send block as after encoding it is over the max message size","ERR_BLOCK_TOO_LARGE");let m=s+y;if(m>n){c=!0;break}e.push(p),a++,s=m}return{hasMore:c,added:a,newSize:s}}function Ti(r){return Sr(3,Le.encode(r))}function Ii(r){return Sr(4,_e.encode(r))}function Mi(r){return Sr(1,Ae.encode(r))}function Sr(r,e){let t=T(r),n=T(e.byteLength);return t+n+e.byteLength}var wt=class extends W{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnTransientConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Ie],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.runOnTransientConnections=t.runOnTransientConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new rt({concurrency:t.messageSendConcurrency??50,metrics:e.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,runOnTransientConnection:this.runOnTransientConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e){if(!this.running)return;let{stream:t,connection:n}=e;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,n.remotePeer);let s=()=>{t.status==="open"?t.abort(new B(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`,"ERR_TIMEOUT")):this.log("stream aborted with status %s",t.status)},i=AbortSignal.timeout(this.messageReceiveTimeout);U(1/0,i),i.addEventListener("abort",s),await t.closeWrite(),await Vt(t,a=>Te(a,{maxDataLength:this.maxIncomingMessageSize}),async a=>{for await(let c of a)try{let h=ue.decode(c);this.log("incoming new bitswap %s message from %p on stream",t.protocol,n.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:h}}),i.removeEventListener("abort",s),i=AbortSignal.timeout(this.messageReceiveTimeout),U(1/0,i),i.addEventListener("abort",s)}catch(h){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,t.id,h),t.abort(h);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),t.abort(s)})}async*findProviders(e,t){t?.onProgress?.(new X("bitswap:network:find-providers",e));for await(let n of this.routing.findProviders(e,t))await this.libp2p.isDialable(n.multiaddrs,{runOnTransientConnection:this.runOnTransientConnections})&&(yield n)}async findAndConnect(e,t){await Rt(Vr($r(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(i=>e.equals(i.options.peerId)&&i.status==="queued");if(s!=null){s.options.message=vn(s.options.message,t),await s.join({signal:n?.signal});return}await this.sendQueue.add(async i=>{let a=i?.message;if(a==null)throw new B("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p",e),i?.onProgress?.(new X("bitswap:network:send-wantlist",e));let c=await this.libp2p.dialProtocol(e,Ie,i);await c.closeRead();try{await Vt(Sn(a,this.maxOutgoingMessageSize),h=>ct(h),c),await c.close(i)}catch(h){i?.onProgress?.(new X("bitswap:network:send-wantlist:error",{peer:e,error:h})),this.log.error("error sending message to %p",e,h),c.abort(h)}this._updateSentStats(a.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new B("Network isn't running","ERR_NOT_STARTED");t?.onProgress?.(new X("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),q(this.libp2p,"peer:identify",t?.signal,{filter:s=>{if(!s.detail.peerId.equals(e))return!1;if(s.detail.protocols.includes(Ie))return!0;throw new B(`${e} did not support ${Ie}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function H(r,e="utf8"){let t=ut[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var An=Symbol.for("nodejs.util.inspect.custom"),kn=Object.values(ve).map(r=>r.decoder).reduce((r,e)=>r.or(e),ve.identity.decoder),Ln=114,_n=36,Dn=37,Oe=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Dt]=!0;toString(){return this.string==null&&(this.string=O.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return F.createV1(Ln,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return $(this.multihash.bytes,e);if(typeof e=="string")return Ve(e).equals(this);if(e?.multihash?.bytes!=null)return $(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[An](){return`PeerId(${this.toString()})`}},Fe=class extends Oe{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ze=class extends Oe{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},He=class extends Oe{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},kr=2336,Ar=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Be.digest(ae(this.url))}[An](){return`PeerId(${this.url})`}[Dt]=!0;toString(){return this.toCID().toString()}toCID(){return F.createV1(kr,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};function Ve(r,e){if(e=e??kn,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Ne(O.decode(`z${r}`));return r.startsWith("12D")?new ze({multihash:t}):r.startsWith("16U")?new He({multihash:t}):new Fe({multihash:t})}return zi(kn.decode(r))}function zi(r){try{let e=Ne(r);if(e.code===Be.code){if(e.digest.length===_n)return new ze({multihash:e});if(e.digest.length===Dn)return new He({multihash:e})}if(e.code===oe.code)return new Fe({multihash:e})}catch{return Hi(F.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Hi(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Ln&&r.code!==kr)throw new Error("Supplied PeerID CID is invalid");if(r.code===kr){let t=H(r.multihash.digest);return new Ar(new URL(t))}let e=r.multihash;if(e.code===oe.code)return new Fe({multihash:r.multihash});if(e.code===Be.code){if(e.digest.length===_n)return new ze({multihash:r.multihash});if(e.digest.length===Dn)return new He({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function Lr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var qe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Lr(this.map.entries(),e=>[Ve(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,Ve(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return Lr(this.map.keys(),e=>Ve(e))}values(){return this.map.values()}get size(){return this.map.size}};var bt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var ml=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var gl={}.toString;function Tn(r=32){if(bt&&typeof bt.getRandomValues=="function")return bt.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function yt(r){if(isNaN(r)||r<=0)throw new B("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Tn(r)}var _r=class extends qe{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function We(r){let{name:e,metrics:t}=r,n;return t!=null?n=new _r({name:e,metrics:t}):n=new qe,n}var J=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=ie.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=ie.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=ie.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Vi(r){let e=new Uint8Array(r.reduce((n,s)=>n+T(s),0)),t=0;for(let n of r)e=nt(n,e,t),t+=T(n);return e}var Nn=Vi;function Dr(r){return Nn([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Et=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new J,n=new Set;for(let[s,i]of this.wants.entries())try{let a=await this.blockstore.get(i.cid,e);i.wantType===D.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:Dr(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:z.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:Dr(i.cid)}))}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a;if(this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:z.DontHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var vt=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=We({name:"helia_bitswap_ledger_map",metrics:e.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(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new Et({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((s,i)=>s+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let s of t.wantlist.entries){let i=F.decode(s.cid),a=H(i.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(a)):(s.wantType===D.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(a,{cid:i,priority:s.priority,wantType:s.wantType??D.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=H(e.multihash.bytes,"base64"),s=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&s.push(i);await Promise.all(s.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var Wi=_t(Cn(),1);var De;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(De||(De={}));var Tr=_t(Rn(),1);var $i=Math.LN2*Math.LN2,St=class r{static create(e,t=.005){let n=Xi(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=Qi(e.hashes??8),this.bits=e.bits??1024,this.buffer=I(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=ae(e));for(let t=0;t<this.seeds.length;t++){let s=Tr.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(s)}}has(e){typeof e=="string"&&(e=ae(e));for(let t=0;t<this.seeds.length;t++){let s=Tr.default.x86.hash32(e,this.seeds[t])%this.bits;if(!this.getbit(s))return!1}return!0}clear(){this.buffer.fill(0)}setbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;let s=this.buffer[t];s|=1<<n,this.buffer[t]=s}getbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;return(this.buffer[t]&1<<n)!==0}};function Xi(r,e=.005){let t=Math.round(-1*r*Math.log(e)/$i),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function Qi(r){let e,t,n=[];for(let s=0;s<r;s++)for(e=new Y(yt(4)),n[s]=e.getUint32(0,!0),t=0;t<s;t++)if(n[s]===n[t]){s--;break}return n}var $e=class extends W{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),U(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=St.create(this.maxProviders)}async retrieve(e,t={}){let n=ie.encode(e.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",e),s;let i=V();if(this.requests.set(n,i.promise),this.providers.length===0){let p=!1;this.intialPeerSearchComplete==null&&(p=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,p&&this.log("found initial session peers for %c",e)}let a=!1,c=new pe({concurrency:this.maxProviders});c.addEventListener("error",()=>{}),c.addEventListener("failure",p=>{this.log.error("error querying provider %o, evicting from session",p.detail.job.options.provider,p.detail.error),this.evict(p.detail.job.options.provider)}),c.addEventListener("success",p=>{a=!0,i.resolve(p.detail.result)}),c.addEventListener("idle",()=>{a||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let p=0;p<this.minProviders&&this.providers.length!==0;p++){let y=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(y)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(p=>{this.log.error("could not find new providers for %c",e,p),i.reject(p)})});let h=p=>{c.add(async()=>this.queryProvider(e,p.detail,t),{provider:p.detail}).catch(y=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,y)})};this.addEventListener("provider",h),Promise.all([...this.providers].map(async p=>c.add(async()=>this.queryProvider(e,p,t),{provider:p}))).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,p)});try{return await i.promise}finally{this.removeEventListener("provider",h),c.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let s=V(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let a of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(a)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),i++,i===t&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new B(`Found ${i} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(a=>{this.log.error("error searching routing for potential session peers for %c",e,a.errors??a),s.reject(a)}),s.promise}};var Ir=class extends $e{wantList;network;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let s=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toBytes()}equals(e,t){return e.equals(t)}};function Un(r,e){return new Ir(r,e)}var kt=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var Mr=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Pn(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Mr({name:e,metrics:t}):n=new Map,n}function Ki(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=st(r);e.push(t),r=r.slice(T(t))}return e}var On=Ki;var At=class extends W{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),U(1/0,this),this.peers=We({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Pn({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(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(e,t){let n=H(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??D.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===D.WantHave&&t.wantType===D.WantBlock&&(s.wantType=D.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===D.WantBlock?(await q(this,"block",t?.signal,{filter:c=>$(e.multihash.digest,c.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await q(this,"presence",t?.signal,{filter:a=>$(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=V(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,s=new J;for(let[i,a]of this.wants.entries())t.has(i)||a.cancel||(n.add(i),s.addWantlistEntry(a.cid,{cid:a.cid.bytes,priority:a.priority,wantType:a.wantType,cancel:a.cancel,sendDontHave:a.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(e,s);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=H(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let s=new J;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:D.WantHave,priority:1}),await this.network.sendMessage(t,s),(await q(this,"presence",n.signal,{filter:a=>t.equals(a.detail.sender)&&$(e.multihash.digest,a.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:D.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new J;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:D.WantBlock,priority:1}),await this.network.sendMessage(t,s),(await q(this,"presence",n.signal,{filter:a=>t.equals(a.detail.sender)&&$(e.multihash.digest,a.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=H(e.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let s of t.blocks){if(s.prefix==null||s.data==null)continue;let i=On(s.prefix),a=i[0],c=i[1],h=i[2],p=h===oe.code?oe:await this.hashLoader?.getHasher(h);if(p==null){this.log.error("unknown hash algorithm",h);continue}let y=p.digest(s.data);y.then!=null&&(y=await y);let m=F.create(a===0?0:1,c,y);this.log("received block from %p for %c",e,m),this.safeDispatchEvent("block",{detail:{sender:e,cid:m,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:m,has:!0,block:s.data}});let L=H(m.multihash.bytes,"base64"),o=this.wants.get(L);o!=null&&(o.cancel=!0,n=!0)}for(let{cid:s,type:i}of t.blockPresences){let a=F.decode(s);this.log("received %s from %p for %c",i,e,a),this.safeDispatchEvent("presence",{detail:{sender:e,cid:a,has:i===z.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new J(!0);for(let[s,i]of this.wants.entries())i.cancel||(t.add(s),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:D.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(s){this.log.error("error sending full wantlist to new peer %p",e,s)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Lt=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new kt(e),this.network=new wt(e,t),this.peerWantLists=new vt({...e,network:this.network},t),this.wantList=new At({...e,network:this.network},t)}createSession(e={}){return Un({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,s=Nr([n.signal,t.signal]);U(1/0,n.signal,s),this.network.findAndConnect(e,{...t,signal:s}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,i)});try{return(await this.wantList.wantBlock(e,{...t,signal:s})).block}finally{n.abort(),s.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Ji=(r,e={})=>new Lt(r,e);return Gn(Zi);})();
2
+ "use strict";var HeliaBitswap=(()=>{var On=Object.create;var Ye=Object.defineProperty;var zn=Object.getOwnPropertyDescriptor;var Hn=Object.getOwnPropertyNames;var Vn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var It=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),C=(r,e)=>{for(var t in e)Ye(r,t,{get:e[t],enumerable:!0})},Br=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Hn(e))!qn.call(r,s)&&s!==t&&Ye(r,s,{get:()=>e[s],enumerable:!(n=zn(e,s))||n.enumerable});return r};var Cr=(r,e,t)=>(t=r!=null?On(Vn(r)):{},Br(e||!r||!r.__esModule?Ye(t,"default",{value:r,enumerable:!0}):t,r)),Gn=r=>Br(Ye({},"__esModule",{value:!0}),r);var In=It(($e,St)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(o){if(!Array.isArray(o)&&!ArrayBuffer.isView(o))return!1;for(var l=0;l<o.length;l++)if(!Number.isInteger(o[l])||o[l]<0||o[l]>255)return!1;return!0}function s(o,l){return(o&65535)*l+(((o>>>16)*l&65535)<<16)}function i(o,l){return o<<l|o>>>32-l}function a(o){return o^=o>>>16,o=s(o,2246822507),o^=o>>>13,o=s(o,3266489909),o^=o>>>16,o}function c(o,l){o=[o[0]>>>16,o[0]&65535,o[1]>>>16,o[1]&65535],l=[l[0]>>>16,l[0]&65535,l[1]>>>16,l[1]&65535];var u=[0,0,0,0];return u[3]+=o[3]+l[3],u[2]+=u[3]>>>16,u[3]&=65535,u[2]+=o[2]+l[2],u[1]+=u[2]>>>16,u[2]&=65535,u[1]+=o[1]+l[1],u[0]+=u[1]>>>16,u[1]&=65535,u[0]+=o[0]+l[0],u[0]&=65535,[u[0]<<16|u[1],u[2]<<16|u[3]]}function h(o,l){o=[o[0]>>>16,o[0]&65535,o[1]>>>16,o[1]&65535],l=[l[0]>>>16,l[0]&65535,l[1]>>>16,l[1]&65535];var u=[0,0,0,0];return u[3]+=o[3]*l[3],u[2]+=u[3]>>>16,u[3]&=65535,u[2]+=o[2]*l[3],u[1]+=u[2]>>>16,u[2]&=65535,u[2]+=o[3]*l[2],u[1]+=u[2]>>>16,u[2]&=65535,u[1]+=o[1]*l[3],u[0]+=u[1]>>>16,u[1]&=65535,u[1]+=o[2]*l[2],u[0]+=u[1]>>>16,u[1]&=65535,u[1]+=o[3]*l[1],u[0]+=u[1]>>>16,u[1]&=65535,u[0]+=o[0]*l[3]+o[1]*l[2]+o[2]*l[1]+o[3]*l[0],u[0]&=65535,[u[0]<<16|u[1],u[2]<<16|u[3]]}function p(o,l){return l%=64,l===32?[o[1],o[0]]:l<32?[o[0]<<l|o[1]>>>32-l,o[1]<<l|o[0]>>>32-l]:(l-=32,[o[1]<<l|o[0]>>>32-l,o[0]<<l|o[1]>>>32-l])}function y(o,l){return l%=64,l===0?o:l<32?[o[0]<<l|o[1]>>>32-l,o[1]<<l]:[o[1]<<l-32,0]}function m(o,l){return[o[0]^l[0],o[1]^l[1]]}function L(o){return o=m(o,[0,o[0]>>>1]),o=h(o,[4283543511,3981806797]),o=m(o,[0,o[0]>>>1]),o=h(o,[3301882366,444984403]),o=m(o,[0,o[0]>>>1]),o}t.x86.hash32=function(o,l){if(t.inputValidation&&!n(o))return e;l=l||0;for(var u=o.length%4,E=o.length-u,f=l,d=0,g=3432918353,b=461845907,x=0;x<E;x=x+4)d=o[x]|o[x+1]<<8|o[x+2]<<16|o[x+3]<<24,d=s(d,g),d=i(d,15),d=s(d,b),f^=d,f=i(f,13),f=s(f,5)+3864292196;switch(d=0,u){case 3:d^=o[x+2]<<16;case 2:d^=o[x+1]<<8;case 1:d^=o[x],d=s(d,g),d=i(d,15),d=s(d,b),f^=d}return f^=o.length,f=a(f),f>>>0},t.x86.hash128=function(o,l){if(t.inputValidation&&!n(o))return e;l=l||0;for(var u=o.length%16,E=o.length-u,f=l,d=l,g=l,b=l,x=0,v=0,w=0,k=0,Q=597399067,Ke=2869860233,Je=951274213,Ze=2716044179,S=0;S<E;S=S+16)x=o[S]|o[S+1]<<8|o[S+2]<<16|o[S+3]<<24,v=o[S+4]|o[S+5]<<8|o[S+6]<<16|o[S+7]<<24,w=o[S+8]|o[S+9]<<8|o[S+10]<<16|o[S+11]<<24,k=o[S+12]|o[S+13]<<8|o[S+14]<<16|o[S+15]<<24,x=s(x,Q),x=i(x,15),x=s(x,Ke),f^=x,f=i(f,19),f+=d,f=s(f,5)+1444728091,v=s(v,Ke),v=i(v,16),v=s(v,Je),d^=v,d=i(d,17),d+=g,d=s(d,5)+197830471,w=s(w,Je),w=i(w,17),w=s(w,Ze),g^=w,g=i(g,15),g+=b,g=s(g,5)+2530024501,k=s(k,Ze),k=i(k,18),k=s(k,Q),b^=k,b=i(b,13),b+=f,b=s(b,5)+850148119;switch(x=0,v=0,w=0,k=0,u){case 15:k^=o[S+14]<<16;case 14:k^=o[S+13]<<8;case 13:k^=o[S+12],k=s(k,Ze),k=i(k,18),k=s(k,Q),b^=k;case 12:w^=o[S+11]<<24;case 11:w^=o[S+10]<<16;case 10:w^=o[S+9]<<8;case 9:w^=o[S+8],w=s(w,Je),w=i(w,17),w=s(w,Ze),g^=w;case 8:v^=o[S+7]<<24;case 7:v^=o[S+6]<<16;case 6:v^=o[S+5]<<8;case 5:v^=o[S+4],v=s(v,Ke),v=i(v,16),v=s(v,Je),d^=v;case 4:x^=o[S+3]<<24;case 3:x^=o[S+2]<<16;case 2:x^=o[S+1]<<8;case 1:x^=o[S],x=s(x,Q),x=i(x,15),x=s(x,Ke),f^=x}return f^=o.length,d^=o.length,g^=o.length,b^=o.length,f+=d,f+=g,f+=b,d+=f,g+=f,b+=f,f=a(f),d=a(d),g=a(g),b=a(b),f+=d,f+=g,f+=b,d+=f,g+=f,b+=f,("00000000"+(f>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)},t.x64.hash128=function(o,l){if(t.inputValidation&&!n(o))return e;l=l||0;for(var u=o.length%16,E=o.length-u,f=[0,l],d=[0,l],g=[0,0],b=[0,0],x=[2277735313,289559509],v=[1291169091,658871167],w=0;w<E;w=w+16)g=[o[w+4]|o[w+5]<<8|o[w+6]<<16|o[w+7]<<24,o[w]|o[w+1]<<8|o[w+2]<<16|o[w+3]<<24],b=[o[w+12]|o[w+13]<<8|o[w+14]<<16|o[w+15]<<24,o[w+8]|o[w+9]<<8|o[w+10]<<16|o[w+11]<<24],g=h(g,x),g=p(g,31),g=h(g,v),f=m(f,g),f=p(f,27),f=c(f,d),f=c(h(f,[0,5]),[0,1390208809]),b=h(b,v),b=p(b,33),b=h(b,x),d=m(d,b),d=p(d,31),d=c(d,f),d=c(h(d,[0,5]),[0,944331445]);switch(g=[0,0],b=[0,0],u){case 15:b=m(b,y([0,o[w+14]],48));case 14:b=m(b,y([0,o[w+13]],40));case 13:b=m(b,y([0,o[w+12]],32));case 12:b=m(b,y([0,o[w+11]],24));case 11:b=m(b,y([0,o[w+10]],16));case 10:b=m(b,y([0,o[w+9]],8));case 9:b=m(b,[0,o[w+8]]),b=h(b,v),b=p(b,33),b=h(b,x),d=m(d,b);case 8:g=m(g,y([0,o[w+7]],56));case 7:g=m(g,y([0,o[w+6]],48));case 6:g=m(g,y([0,o[w+5]],40));case 5:g=m(g,y([0,o[w+4]],32));case 4:g=m(g,y([0,o[w+3]],24));case 3:g=m(g,y([0,o[w+2]],16));case 2:g=m(g,y([0,o[w+1]],8));case 1:g=m(g,[0,o[w]]),g=h(g,x),g=p(g,31),g=h(g,v),f=m(f,g)}return f=m(f,[0,o.length]),d=m(d,[0,o.length]),f=c(f,d),d=c(d,f),f=L(f),d=L(d),f=c(f,d),d=c(d,f),("00000000"+(f[0]>>>0).toString(16)).slice(-8)+("00000000"+(f[1]>>>0).toString(16)).slice(-8)+("00000000"+(d[0]>>>0).toString(16)).slice(-8)+("00000000"+(d[1]>>>0).toString(16)).slice(-8)},typeof $e<"u"?(typeof St<"u"&&St.exports&&($e=St.exports=t),$e.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})($e)});var Mn=It((Sl,Rn)=>{Rn.exports=In()});var Cn=It((sh,Bn)=>{Bn.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(i,a){t[i]=a,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var a=t[i];if(a!==void 0)return a;if((a=n[i])!==void 0)return s(i,a),a},set:function(i,a){t[i]!==void 0?t[i]=a:s(i,a)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Ki={};C(Ki,{createBitswap:()=>Qi});var Rt=Symbol.for("@libp2p/peer-id");var Z=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},B=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var U=(r,...e)=>{try{[...e]}catch{}};var W=class extends EventTarget{#e=new Map;constructor(){super(),U(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:i})=>i!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Wn(e,t))}},Wn=globalThis.CustomEvent;function Ur(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}function V(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var je=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},de=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new je(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new je(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Mt=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function pe(r={}){return $n(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function $n(r,e){e=e??{};let t=e.onEnd,n=new de,s,i,a,c=V(),h=async()=>{try{return n.isEmpty()?a?{done:!0}:await new Promise((E,f)=>{i=d=>{i=null,n.push(d);try{E(r(n))}catch(g){f(g)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=V()})}},p=E=>i!=null?i(E):(n.push(E),s),y=E=>(n=new de,i!=null?i({error:E}):(n.push({error:E}),s)),m=E=>{if(a)return s;if(e?.objectMode!==!0&&E?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return p({done:!1,value:E})},L=E=>a?s:(a=!0,E!=null?y(E):p({done:!0})),o=()=>(n=new de,L(),{done:!0}),l=E=>(L(E),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:h,return:o,throw:l,push:m,end:L,get readableLength(){return n.size},onEmpty:async E=>{let f=E?.signal;if(f?.throwIfAborted(),n.isEmpty())return;let d,g;f!=null&&(d=new Promise((b,x)=>{g=()=>{x(new Mt)},f.addEventListener("abort",g)}));try{await Promise.race([c.promise,d])}finally{g!=null&&f!=null&&f?.removeEventListener("abort",g)}}},t==null)return s;let u=s;return s={[Symbol.asyncIterator](){return this},next(){return u.next()},throw(E){return u.throw(E),t!=null&&(t(E),t=void 0),{done:!0}},return(){return u.return(),t!=null&&(t(),t=void 0),{done:!0}},push:m,end(E){return u.end(E),t!=null&&(t(E),t=void 0),s},get readableLength(){return u.readableLength},onEmpty:E=>u.onEmpty(E)},s}var Nt=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function q(r,e,t,n){let s=new Nt(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){t?.removeEventListener("abort",y),r.removeEventListener(e,h),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,p)}let h=m=>{try{if(n?.filter?.(m)===!1)return}catch(L){c(),a(L);return}c(),i(m)},p=m=>{c(),a(m.detail)},y=()=>{c(),a(s)};t?.addEventListener("abort",y),r.addEventListener(e,h),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,p)})}var et=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Pr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new et(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new et(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,a)=>{n=()=>{a(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var tt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=V(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Z)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Xn(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var rt=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Xn(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,U(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Z),this.cleanup())}async join(e={}){let t=new tt(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Pr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var me=class extends W{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let n=new rt(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Z)}),this.clear()}async onEmpty(e){this.size!==0&&await q(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await q(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await q(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=pe({objectMode:!0}),n=h=>{h!=null?this.abort():this.clear(),t.end(h)},s=h=>{h.detail!=null&&t.push(h.detail)},i=h=>{n(h.detail)},a=()=>{n()},c=()=>{n(new B("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",a),e?.signal?.addEventListener("abort",c);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",a),e?.signal?.removeEventListener("abort",c),n()}}};var nt=class extends me{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function Qn(r){return r[Symbol.asyncIterator]!=null}function Kn(r){if(Qn(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Bt=Kn;function I(r=0){return new Uint8Array(r)}function R(r=0){return new Uint8Array(r)}var Jn=Math.pow(2,7),Zn=Math.pow(2,14),Yn=Math.pow(2,21),Ct=Math.pow(2,28),Ut=Math.pow(2,35),Pt=Math.pow(2,42),Ft=Math.pow(2,49),A=128,M=127;function T(r){if(r<Jn)return 1;if(r<Zn)return 2;if(r<Yn)return 3;if(r<Ct)return 4;if(r<Ut)return 5;if(r<Pt)return 6;if(r<Ft)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ot(r,e,t=0){switch(T(r)){case 8:e[t++]=r&255|A,r/=128;case 7:e[t++]=r&255|A,r/=128;case 6:e[t++]=r&255|A,r/=128;case 5:e[t++]=r&255|A,r/=128;case 4:e[t++]=r&255|A,r>>>=7;case 3:e[t++]=r&255|A,r>>>=7;case 2:e[t++]=r&255|A,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function jn(r,e,t=0){switch(T(r)){case 8:e.set(t++,r&255|A),r/=128;case 7:e.set(t++,r&255|A),r/=128;case 6:e.set(t++,r&255|A),r/=128;case 5:e.set(t++,r&255|A),r/=128;case 4:e.set(t++,r&255|A),r>>>=7;case 3:e.set(t++,r&255|A),r>>>=7;case 2:e.set(t++,r&255|A),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function zt(r,e){let t=r[e],n=0;if(n+=t&M,t<A||(t=r[e+1],n+=(t&M)<<7,t<A)||(t=r[e+2],n+=(t&M)<<14,t<A)||(t=r[e+3],n+=(t&M)<<21,t<A)||(t=r[e+4],n+=(t&M)*Ct,t<A)||(t=r[e+5],n+=(t&M)*Ut,t<A)||(t=r[e+6],n+=(t&M)*Pt,t<A)||(t=r[e+7],n+=(t&M)*Ft,t<A))return n;throw new RangeError("Could not decode varint")}function es(r,e){let t=r.get(e),n=0;if(n+=t&M,t<A||(t=r.get(e+1),n+=(t&M)<<7,t<A)||(t=r.get(e+2),n+=(t&M)<<14,t<A)||(t=r.get(e+3),n+=(t&M)<<21,t<A)||(t=r.get(e+4),n+=(t&M)*Ct,t<A)||(t=r.get(e+5),n+=(t&M)*Ut,t<A)||(t=r.get(e+6),n+=(t&M)*Pt,t<A)||(t=r.get(e+7),n+=(t&M)*Ft,t<A))return n;throw new RangeError("Could not decode varint")}function st(r,e,t=0){return e==null&&(e=R(T(r))),e instanceof Uint8Array?Ot(r,e,t):jn(r,e,t)}function it(r,e=0){return r instanceof Uint8Array?zt(r,e):es(r,e)}function Ht(r,e){e==null&&(e=r.reduce((s,i)=>s+i.length,0));let t=R(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}function $(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var zr=Symbol.for("@achingbrain/uint8arraylist");function Or(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function ot(r){return!!r?.[zr]}var Y=class r{bufs;length;[zr]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ot(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ot(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Or(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Or(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ot(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ht(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ht(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),i=new r;return i.length=s,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let a=this.bufs[i],c=s,h=c+a.byteLength;if(s=h,e>=h)continue;let p=e>=c&&e<h,y=t>c&&t<=h;if(p&&y){if(e===c&&t===h){n.push(a);break}let m=e-c;n.push(a.subarray(m,m+(t-e)));break}if(p){if(e===0){n.push(a);continue}n.push(a.subarray(e-c));continue}if(y){if(t===h){n.push(a);break}n.push(a.subarray(0,t-c));break}n.push(a)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ot(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,a=new Int32Array(i);for(let m=0;m<i;m++)a[m]=-1;for(let m=0;m<s;m++)a[n[m]]=m;let c=a,h=this.byteLength-n.byteLength,p=n.byteLength-1,y;for(let m=t;m<=h;m+=y){y=0;for(let L=p;L>=0;L--){let o=this.get(m+L);if(n[L]!==o){y=Math.max(1,L-c[o]);break}}if(y===0)return m}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=I(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=I(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=I(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=I(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=I(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=I(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=I(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=I(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!$(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,i)=>s+i.byteLength,0)),n.length=t,n}};function at(r){return r[Symbol.asyncIterator]!=null}var ct=r=>{let e=T(r),t=R(e);return st(r,t),ct.bytes=e,t};ct.bytes=0;function lt(r,e){e=e??{};let t=e.lengthEncoder??ct;function*n(s){let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return at(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}lt.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ct;return new Y(t(r.byteLength),r)};var ht=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ut=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ft=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Te=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ts=8,rs=1024*1024*4,re;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(re||(re={}));var Vt=r=>{let e=it(r);return Vt.bytes=T(e),e};Vt.bytes=0;function Ie(r,e){let t=new Y,n=re.LENGTH,s=-1,i=e?.lengthDecoder??Vt,a=e?.maxLengthLength??ts,c=e?.maxDataLength??rs;function*h(){for(;t.byteLength>0;){if(n===re.LENGTH)try{if(s=i(t),s<0)throw new ht("Invalid message length");if(s>c)throw new ut("Message length too long");let p=i.bytes;t.consume(p),e?.onLength!=null&&e.onLength(s),n=re.DATA}catch(p){if(p instanceof RangeError){if(t.byteLength>a)throw new ft("Message length length too long");break}throw p}if(n===re.DATA){if(t.byteLength<s)break;let p=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(p),yield p,n=re.LENGTH}}}return at(r)?async function*(){for await(let p of r)t.append(p),yield*h();if(t.byteLength>0)throw new Te("Unexpected end of input")}():function*(){for(let p of r)t.append(p),yield*h();if(t.byteLength>0)throw new Te("Unexpected end of input")}()}Ie.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:i,value:a}=await r.next(t);if(i===!0)return;a!=null&&(yield a)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}}();return Ie(n,{...e??{},onLength:i=>{t=i}})};function ss(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Hr=ss;function is(r){return r[Symbol.asyncIterator]!=null}function os(r,e){let t=0;if(is(r))return async function*(){for await(let h of r)yield e(h,t++)}();let n=Hr(r),{value:s,done:i}=n.next();if(i===!0)return function*(){}();let a=e(s,t++);if(typeof a.then=="function")return async function*(){yield await a;for await(let h of n)yield e(h,t++)}();let c=e;return function*(){yield a;for(let h of n)yield c(h,t++)}()}var Vr=os;function as(r){return r[Symbol.asyncIterator]!=null}function cs(...r){let e=[];for(let t of r)as(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=pe({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var qr=cs;function Gt(r,...e){if(r==null)throw new Error("Empty pipeline");if(qt(r)){let n=r;r=()=>n.source}else if(Wr(r)||Gr(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&qt(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)qt(t[n])&&(t[n]=hs(t[n]));return ls(...t)}var ls=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Gr=r=>r?.[Symbol.asyncIterator]!=null,Wr=r=>r?.[Symbol.iterator]!=null,qt=r=>r==null?!1:r.sink!=null&&r.source!=null,hs=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=pe({objectMode:!0});t.then(()=>{n.end()},a=>{n.end(a)});let s,i=r.source;if(Gr(i))s=async function*(){yield*i,n.end()};else if(Wr(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return qr(n,s())}return r.source};function us(r){return r[Symbol.asyncIterator]!=null}function fs(r,e){return us(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var $r=fs;var X=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Re="/ipfs/bitswap/1.2.0";var Wt=new Float32Array([-0]),j=new Uint8Array(Wt.buffer);function Xr(r,e,t){Wt[0]=r,e[t]=j[0],e[t+1]=j[1],e[t+2]=j[2],e[t+3]=j[3]}function Qr(r,e){return j[0]=r[e],j[1]=r[e+1],j[2]=r[e+2],j[3]=r[e+3],Wt[0]}var $t=new Float64Array([-0]),N=new Uint8Array($t.buffer);function Kr(r,e,t){$t[0]=r,e[t]=N[0],e[t+1]=N[1],e[t+2]=N[2],e[t+3]=N[3],e[t+4]=N[4],e[t+5]=N[5],e[t+6]=N[6],e[t+7]=N[7]}function Jr(r,e){return N[0]=r[e],N[1]=r[e+1],N[2]=r[e+2],N[3]=r[e+3],N[4]=r[e+4],N[5]=r[e+5],N[6]=r[e+6],N[7]=r[e+7],$t[0]}var ds=BigInt(Number.MAX_SAFE_INTEGER),ps=BigInt(Number.MIN_SAFE_INTEGER),P=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ne;if(e<ds&&e>ps)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Zr&&(s=0n,++n>Zr&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return ne;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ne}},ne=new P(0,0);ne.toBigInt=function(){return 0n};ne.zzEncode=ne.zzDecode=function(){return this};ne.length=function(){return 1};var Zr=4294967296n;function Yr(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function jr(r,e,t){if(t-e<1)return"";let s,i=[],a=0,c;for(;e<t;)c=r[e++],c<128?i[a++]=c:c>191&&c<224?i[a++]=(c&31)<<6|r[e++]&63:c>239&&c<365?(c=((c&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[a++]=55296+(c>>10),i[a++]=56320+(c&1023)):i[a++]=(c&15)<<12|(r[e++]&63)<<6|r[e++]&63,a>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),a=0);return s!=null?(a>0&&s.push(String.fromCharCode.apply(String,i.slice(0,a))),s.join("")):String.fromCharCode.apply(String,i.slice(0,a))}function Xt(r,e,t){let n=t,s,i;for(let a=0;a<r.length;++a)s=r.charCodeAt(a),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++a,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function G(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function dt(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Qt=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,G(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw G(this,4);return dt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw G(this,4);return dt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw G(this,4);let e=Qr(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw G(this,4);let e=Jr(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw G(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return jr(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw G(this,e);this.pos+=e}else do if(this.pos>=this.len)throw G(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new P(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw G(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw G(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw G(this,8);let e=dt(this.buf,this.pos+=4),t=dt(this.buf,this.pos+=4);return new P(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=zt(this.buf,this.pos);return this.pos+=T(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Kt(r){return new Qt(r instanceof Uint8Array?r:r.subarray())}function se(r,e,t){let n=Kt(r);return e.decode(n,void 0,t)}var er={};C(er,{base10:()=>xs});var ma=new Uint8Array(0);function tn(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function K(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 rn(r){return new TextEncoder().encode(r)}function nn(r){return new TextDecoder().decode(r)}function ms(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(t[a]!==255)throw new TypeError(i+" is ambiguous");t[a]=s}var c=r.length,h=r.charAt(0),p=Math.log(c)/Math.log(256),y=Math.log(256)/Math.log(c);function m(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var u=0,E=0,f=0,d=l.length;f!==d&&l[f]===0;)f++,u++;for(var g=(d-f)*y+1>>>0,b=new Uint8Array(g);f!==d;){for(var x=l[f],v=0,w=g-1;(x!==0||v<E)&&w!==-1;w--,v++)x+=256*b[w]>>>0,b[w]=x%c>>>0,x=x/c>>>0;if(x!==0)throw new Error("Non-zero carry");E=v,f++}for(var k=g-E;k!==g&&b[k]===0;)k++;for(var Q=h.repeat(u);k<g;++k)Q+=r.charAt(b[k]);return Q}function L(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var u=0;if(l[u]!==" "){for(var E=0,f=0;l[u]===h;)E++,u++;for(var d=(l.length-u)*p+1>>>0,g=new Uint8Array(d);l[u];){var b=t[l.charCodeAt(u)];if(b===255)return;for(var x=0,v=d-1;(b!==0||x<f)&&v!==-1;v--,x++)b+=c*g[v]>>>0,g[v]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");f=x,u++}if(l[u]!==" "){for(var w=d-f;w!==d&&g[w]===0;)w++;for(var k=new Uint8Array(E+(d-w)),Q=E;w!==d;)k[Q++]=g[w++];return k}}}function o(l){var u=L(l);if(u)return u;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:L,decode:o}}var gs=ms,ws=gs,on=ws;var Jt=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Zt=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return an(this,e)}},Yt=class{decoders;constructor(e){this.decoders=e}or(e){return an(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function an(r,e){return new Yt({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var jt=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Jt(e,t,n),this.decoder=new Zt(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ge({name:r,prefix:e,encode:t,decode:n}){return new jt(r,e,t,n)}function ee({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=on(t,r);return ge({prefix:e,name:r,encode:n,decode:i=>K(s(i))})}function bs(r,e,t,n){let s={};for(let y=0;y<e.length;++y)s[e[y]]=y;let i=r.length;for(;r[i-1]==="=";)--i;let a=new Uint8Array(i*t/8|0),c=0,h=0,p=0;for(let y=0;y<i;++y){let m=s[r[y]];if(m===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<t|m,c+=t,c>=8&&(c-=8,a[p++]=255&h>>c)}if(c>=t||255&h<<8-c)throw new SyntaxError("Unexpected end of data");return a}function ys(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,i="",a=0,c=0;for(let h=0;h<r.length;++h)for(c=c<<8|r[h],a+=8;a>t;)a-=t,i+=e[s&c>>a];if(a!==0&&(i+=e[s&c<<t-a]),n)for(;i.length*t&7;)i+="=";return i}function _({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return ge({prefix:e,name:r,encode(s){return ys(s,n,t)},decode(s){return bs(s,n,t,r)}})}var xs=ee({prefix:"9",name:"base10",alphabet:"0123456789"});var tr={};C(tr,{base16:()=>Es,base16upper:()=>vs});var Es=_({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),vs=_({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rr={};C(rr,{base2:()=>Ss});var Ss=_({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var nr={};C(nr,{base256emoji:()=>Ds});var cn=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}"),As=cn.reduce((r,e,t)=>(r[t]=e,r),[]),ks=cn.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Ls(r){return r.reduce((e,t)=>(e+=As[t],e),"")}function _s(r){let e=[];for(let t of r){let n=ks[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Ds=ge({prefix:"\u{1F680}",name:"base256emoji",encode:Ls,decode:_s});var sr={};C(sr,{base32:()=>we,base32hex:()=>Ms,base32hexpad:()=>Bs,base32hexpadupper:()=>Cs,base32hexupper:()=>Ns,base32pad:()=>Is,base32padupper:()=>Rs,base32upper:()=>Ts,base32z:()=>Us});var we=_({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ts=_({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Is=_({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rs=_({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ms=_({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ns=_({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Bs=_({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Cs=_({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Us=_({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ir={};C(ir,{base36:()=>Me,base36upper:()=>Ps});var Me=ee({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ps=ee({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var or={};C(or,{base58btc:()=>F,base58flickr:()=>Fs});var F=ee({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Fs=ee({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ar={};C(ar,{base64:()=>ie,base64pad:()=>Os,base64url:()=>zs,base64urlpad:()=>Hs});var ie=_({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Os=_({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),zs=_({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hs=_({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var cr={};C(cr,{base8:()=>Vs});var Vs=_({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var lr={};C(lr,{identity:()=>qs});var qs=ge({prefix:"\0",name:"identity",encode:r=>nn(r),decode:r=>rn(r)});var Ra=new TextEncoder,Ma=new TextDecoder;var ur={};C(ur,{identity:()=>Ue});var $s=un,ln=128,Xs=127,Qs=~Xs,Ks=Math.pow(2,31);function un(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Ks;)e[t++]=r&255|ln,r/=128;for(;r&Qs;)e[t++]=r&255|ln,r>>>=7;return e[t]=r|0,un.bytes=t-n+1,e}var Js=hr,Zs=128,hn=127;function hr(r,n){var t=0,n=n||0,s=0,i=n,a,c=r.length;do{if(i>=c)throw hr.bytes=0,new RangeError("Could not decode varint");a=r[i++],t+=s<28?(a&hn)<<s:(a&hn)*Math.pow(2,s),s+=7}while(a>=Zs);return hr.bytes=i-n,t}var Ys=Math.pow(2,7),js=Math.pow(2,14),ei=Math.pow(2,21),ti=Math.pow(2,28),ri=Math.pow(2,35),ni=Math.pow(2,42),si=Math.pow(2,49),ii=Math.pow(2,56),oi=Math.pow(2,63),ai=function(r){return r<Ys?1:r<js?2:r<ei?3:r<ti?4:r<ri?5:r<ni?6:r<si?7:r<ii?8:r<oi?9:10},ci={encode:$s,decode:Js,encodingLength:ai},li=ci,Ne=li;function Be(r,e=0){return[Ne.decode(r,e),Ne.decode.bytes]}function be(r,e,t=0){return Ne.encode(r,e,t),e}function ye(r){return Ne.encodingLength(r)}function te(r,e){let t=e.byteLength,n=ye(r),s=n+ye(t),i=new Uint8Array(s+t);return be(r,i,0),be(t,i,n),i.set(e,s),new xe(r,t,e,i)}function Ce(r){let e=K(r),[t,n]=Be(e),[s,i]=Be(e.subarray(n)),a=e.subarray(n+i);if(a.byteLength!==s)throw new Error("Incorrect length");return new xe(t,s,a,e)}function fn(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&tn(r.bytes,t.bytes)}}var xe=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var dn=0,hi="identity",pn=K;function ui(r){return te(dn,pn(r))}var Ue={code:dn,name:hi,encode:pn,digest:ui};var pr={};C(pr,{sha256:()=>oe,sha512:()=>fi});function dr({name:r,code:e,encode:t}){return new fr(r,e,t)}var fr=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?te(this.code,t):t.then(n=>te(this.code,n))}else throw Error("Unknown type, must be binary type")}};function gn(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var oe=dr({name:"sha2-256",code:18,encode:gn("SHA-256")}),fi=dr({name:"sha2-512",code:19,encode:gn("SHA-512")});function wn(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return pi(t,mr(r),e??F.encoder);default:return mi(t,mr(r),e??we.encoder)}}var bn=new WeakMap;function mr(r){let e=bn.get(r);if(e==null){let t=new Map;return bn.set(r,t),t}return e}var O=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,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:e,multihash:t}=this;if(e!==Pe)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==gi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=te(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&fn(e.multihash,n.multihash)}toString(e){return wn(this,e)}toJSON(){return{"/":wn(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:i,bytes:a}=t;return new r(n,s,i,a??yn(n,s,i.bytes))}else if(t[wi]===!0){let{version:n,multihash:s,code:i}=t,a=Ce(s);return r.create(n,i,a)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Pe)throw new Error(`Version 0 CID must use dag-pb (code: ${Pe}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=yn(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pe,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=K(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),a=new xe(t.multihashCode,t.digestSize,i,s);return[t.version===0?r.createV0(a):r.createV1(t.codec,a),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[m,L]=Be(e.subarray(t));return t+=L,m},s=n(),i=Pe;if(s===18?(s=0,t=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let a=t,c=n(),h=n(),p=t+h,y=p-a;return{version:s,codec:i,multihashCode:c,digestSize:h,multihashSize:y,size:p}}static parse(e,t){let[n,s]=di(e,t),i=r.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return mr(i).set(n,e),i}};function di(r,e){switch(r[0]){case"Q":{let t=e??F;return[F.prefix,t.decode(`${F.prefix}${r}`)]}case F.prefix:{let t=e??F;return[F.prefix,t.decode(r)]}case we.prefix:{let t=e??we;return[we.prefix,t.decode(r)]}case Me.prefix:{let t=e??Me;return[Me.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function pi(r,e,t){let{prefix:n}=t;if(n!==F.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return s}function mi(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let i=t.encode(r);return e.set(n,i),i}else return s}var Pe=112,gi=18;function yn(r,e,t){let n=ye(r),s=n+ye(e),i=new Uint8Array(s+t.byteLength);return be(r,i,0),be(e,i,n),i.set(t,s),i}var wi=Symbol.for("@ipld/js-cid/CID");var ve={...lr,...rr,...cr,...er,...tr,...sr,...ir,...or,...ar,...nr},ec={...pr,...ur};function En(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var xn=En("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),gr=En("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=R(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),bi={utf8:xn,"utf-8":xn,hex:ve.base16,latin1:gr,ascii:gr,binary:gr,...ve},mt=bi;function ae(r,e="utf8"){let t=mt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function wr(r){let e=r??8192,t=e>>>1,n,s=e;return function(a){if(a<1||a>t)return R(a);s+a>e&&(n=R(e),s=0);let c=n.subarray(s,s+=a);return s&7&&(s=(s|7)+1),c}}var ce=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function br(){}var xr=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},yi=wr();function xi(r){return globalThis.Buffer!=null?R(r):yi(r)}var Oe=class{len;head;tail;states;constructor(){this.len=0,this.head=new ce(br,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ce(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Er((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(gt,10,P.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=P.fromBigInt(e);return this._push(gt,t.length(),t)}uint64Number(e){return this._push(Ot,T(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=P.fromBigInt(e).zzEncode();return this._push(gt,t.length(),t)}sint64Number(e){let t=P.fromNumber(e).zzEncode();return this._push(gt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(yr,1,e?1:0)}fixed32(e){return this._push(Fe,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=P.fromBigInt(e);return this._push(Fe,4,t.lo)._push(Fe,4,t.hi)}fixed64Number(e){let t=P.fromNumber(e);return this._push(Fe,4,t.lo)._push(Fe,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Xr,4,e)}double(e){return this._push(Kr,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(yr,1,0):this.uint32(t)._push(vi,t,e)}string(e){let t=Yr(e);return t!==0?this.uint32(t)._push(Xt,t,e):this._push(yr,1,0)}fork(){return this.states=new xr(this),this.head=this.tail=new ce(br,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 ce(br,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=xi(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function yr(r,e,t){e[t]=r&255}function Ei(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Er=class extends ce{next;constructor(e,t){super(Ei,e,t),this.next=void 0}};function gt(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Fe(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function vi(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Oe.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Si,e,r),this},Oe.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Ai,e,r),this});function Si(r,e,t){e.set(r,t)}function Ai(r,e,t){r.length<40?Xt(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(ae(r),t)}function vr(){return new Oe}function le(r,e){let t=vr();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Se;(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"})(Se||(Se={}));function wt(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function bt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)};return wt("enum",Se.VARINT,t,n)}function he(r,e){return wt("message",Se.LENGTH_DELIMITED,r,e)}var Ae=class extends Error{code;constructor(e,t){super(e),this.code=t}};var D;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(D||(D={}));var Sr;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Sr||(Sr={}));(function(r){r.codec=()=>bt(Sr)})(D||(D={}));var ke;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),D.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={cid:I(0),priority:0},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{i.cid=t.bytes();break}case 2:{i.priority=t.int32();break}case 3:{i.cancel=t.bool();break}case 4:{i.wantType=D.codec().decode(t);break}case 5:{i.sendDontHave=t.bool();break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(ke||(ke={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let i of t.entries)n.uint32(10),ke.codec().encode(i,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={entries:[]},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{if(s.limits?.entries!=null&&i.entries.length===s.limits.entries)throw new Ae('decode error - map field "entries" had too many elements',"ERR_MAX_LENGTH");i.entries.push(ke.codec().decode(t,t.uint32(),{limits:s.limits?.entries$}));break}case 2:{i.full=t.bool();break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(yt||(yt={}));var Le;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={prefix:I(0),data:I(0)},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{i.prefix=t.bytes();break}case 2:{i.data=t.bytes();break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(Le||(Le={}));var z;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(z||(z={}));var xt;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(xt||(xt={}));(function(r){r.codec=()=>bt(xt)})(z||(z={}));var _e;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&xt[t.type]!==0&&(n.uint32(16),z.codec().encode(t.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={cid:I(0),type:z.HaveBlock},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{i.cid=t.bytes();break}case 2:{i.type=z.codec().decode(t);break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(_e||(_e={}));var ue;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),yt.codec().encode(t.wantlist,n)),t.blocks!=null)for(let i of t.blocks)n.uint32(26),Le.codec().encode(i,n);if(t.blockPresences!=null)for(let i of t.blockPresences)n.uint32(34),_e.codec().encode(i,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let i={blocks:[],blockPresences:[],pendingBytes:0},a=n==null?t.len:t.pos+n;for(;t.pos<a;){let c=t.uint32();switch(c>>>3){case 1:{i.wantlist=yt.codec().decode(t,t.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&i.blocks.length===s.limits.blocks)throw new Ae('decode error - map field "blocks" had too many elements',"ERR_MAX_LENGTH");i.blocks.push(Le.codec().decode(t,t.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&i.blockPresences.length===s.limits.blockPresences)throw new Ae('decode error - map field "blockPresences" had too many elements',"ERR_MAX_LENGTH");i.blockPresences.push(_e.codec().decode(t,t.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{i.pendingBytes=t.int32();break}default:{t.skipType(c&7);break}}}return i})),e),r.encode=t=>le(t,r.codec()),r.decode=(t,n)=>se(t,r.codec(),n)})(ue||(ue={}));function vn(r,e){for(let[t,n]of e.wantlist.entries()){let s=r.wantlist.get(t);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(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var ki=4193648,Li=ki+16;function*Sn(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],i=0,a=0,c=0,h=!1;for(;;){let p={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},y=ue.encode(p).byteLength,{added:m,hasMore:L,newSize:o}=Ar(s,p.blocks,c,e,y,_i);c+=m,y=o;let l=L;({added:m,hasMore:L,newSize:o}=Ar(n,p.blockPresences,a,e,y,Di)),a+=m,y=o;let u=L;if({added:m,hasMore:L,newSize:o}=Ar(t,p.wantlist.entries,i,e,y,Ti),i+=m,y=o,h=!l&&!u&&!L,h||(p.wantlist.full=!1),yield ue.encode(p),h)break}}function Ar(r,e,t,n,s,i){let a=0,c=!1;for(let h=t;h<r.length;h++){let p=r[h],y=i(p);if(y>Li)throw new B("Cannot send block as after encoding it is over the max message size","ERR_BLOCK_TOO_LARGE");let m=s+y;if(m>n){c=!0;break}e.push(p),a++,s=m}return{hasMore:c,added:a,newSize:s}}function _i(r){return kr(3,Le.encode(r))}function Di(r){return kr(4,_e.encode(r))}function Ti(r){return kr(1,ke.encode(r))}function kr(r,e){let t=T(r),n=T(e.byteLength);return t+n+e.byteLength}var Et=class extends W{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnTransientConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Re],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.runOnTransientConnections=t.runOnTransientConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new nt({concurrency:t.messageSendConcurrency??50,metrics:e.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,runOnTransientConnection:this.runOnTransientConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e){if(!this.running)return;let{stream:t,connection:n}=e;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,n.remotePeer);let s=()=>{t.status==="open"?t.abort(new B(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`,"ERR_TIMEOUT")):this.log("stream aborted with status %s",t.status)},i=AbortSignal.timeout(this.messageReceiveTimeout);U(1/0,i),i.addEventListener("abort",s),await t.closeWrite(),await Gt(t,a=>Ie(a,{maxDataLength:this.maxIncomingMessageSize}),async a=>{for await(let c of a)try{let h=ue.decode(c);this.log("incoming new bitswap %s message from %p on stream",t.protocol,n.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:h}}),i.removeEventListener("abort",s),i=AbortSignal.timeout(this.messageReceiveTimeout),U(1/0,i),i.addEventListener("abort",s)}catch(h){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,t.id,h),t.abort(h);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),t.abort(s)})}async*findProviders(e,t){t?.onProgress?.(new X("bitswap:network:find-providers",e));for await(let n of this.routing.findProviders(e,t))await this.libp2p.isDialable(n.multiaddrs,{runOnTransientConnection:this.runOnTransientConnections})&&(yield n)}async findAndConnect(e,t){await Bt(Vr($r(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(i=>e.equals(i.options.peerId)&&i.status==="queued");if(s!=null){s.options.message=vn(s.options.message,t),await s.join({signal:n?.signal});return}await this.sendQueue.add(async i=>{let a=i?.message;if(a==null)throw new B("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p",e),i?.onProgress?.(new X("bitswap:network:send-wantlist",e));let c=await this.libp2p.dialProtocol(e,Re,i);await c.closeRead();try{await Gt(Sn(a,this.maxOutgoingMessageSize),h=>lt(h),c),await c.close(i)}catch(h){i?.onProgress?.(new X("bitswap:network:send-wantlist:error",{peer:e,error:h})),this.log.error("error sending message to %p",e,h),c.abort(h)}this._updateSentStats(a.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new B("Network isn't running","ERR_NOT_STARTED");t?.onProgress?.(new X("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),q(this.libp2p,"peer:identify",t?.signal,{filter:s=>{if(!s.detail.peerId.equals(e))return!1;if(s.detail.protocols.includes(Re))return!0;throw new B(`${e} did not support ${Re}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function H(r,e="utf8"){let t=mt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var kn=Symbol.for("nodejs.util.inspect.custom"),An=Object.values(ve).map(r=>r.decoder).reduce((r,e)=>r.or(e),ve.identity.decoder),Ln=114,_n=36,Dn=37,ze=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Rt]=!0;toString(){return this.string==null&&(this.string=F.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return O.createV1(Ln,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return $(this.multihash.bytes,e);if(typeof e=="string")return Ge(e).equals(this);if(e?.multihash?.bytes!=null)return $(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[kn](){return`PeerId(${this.toString()})`}},He=class extends ze{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ve=class extends ze{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},qe=class extends ze{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},Lr=2336,_r=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ue.digest(ae(this.url))}[kn](){return`PeerId(${this.url})`}[Rt]=!0;toString(){return this.toCID().toString()}toCID(){return O.createV1(Lr,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};function Ge(r,e){if(e=e??An,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Ce(F.decode(`z${r}`));return r.startsWith("12D")?new Ve({multihash:t}):r.startsWith("16U")?new qe({multihash:t}):new He({multihash:t})}return Fi(An.decode(r))}function Fi(r){try{let e=Ce(r);if(e.code===Ue.code){if(e.digest.length===_n)return new Ve({multihash:e});if(e.digest.length===Dn)return new qe({multihash:e})}if(e.code===oe.code)return new He({multihash:e})}catch{return Oi(O.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Oi(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ln&&r.code!==Lr)throw new Error("Supplied PeerID CID is invalid");if(r.code===Lr){let t=H(r.multihash.digest);return new _r(new URL(t))}let e=r.multihash;if(e.code===oe.code)return new He({multihash:r.multihash});if(e.code===Ue.code){if(e.digest.length===_n)return new Ve({multihash:r.multihash});if(e.digest.length===Dn)return new qe({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function Dr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var We=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Dr(this.map.entries(),e=>[Ge(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,Ge(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return Dr(this.map.keys(),e=>Ge(e))}values(){return this.map.values()}get size(){return this.map.size}};var fe=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var ml=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var gl={}.toString;function Tn(r=32){if(fe&&typeof fe.getRandomValues=="function")return fe.getRandomValues(new Uint8Array(r));if(fe&&typeof fe.randomBytes=="function")return fe.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function vt(r){if(isNaN(r)||r<=0)throw new B("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Tn(r)}var Tr=class extends We{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Xe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Tr({name:e,metrics:t}):n=new We,n}var J=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=ie.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=ie.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=ie.encode(e.multihash.bytes);this.blocks.set(n,t)}};function zi(r){let e=new Uint8Array(r.reduce((n,s)=>n+T(s),0)),t=0;for(let n of r)e=st(n,e,t),t+=T(n);return e}var Nn=zi;function Ir(r){return Nn([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var At=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new J,n=new Set;for(let[s,i]of this.wants.entries())try{let a=await this.blockstore.get(i.cid,e);i.wantType===D.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:Ir(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:z.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:Ir(i.cid)}))}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a;if(this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:z.DontHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var kt=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Xe({name:"helia_bitswap_ledger_map",metrics:e.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(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new At({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((s,i)=>s+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let s of t.wantlist.entries){let i=O.decode(s.cid),a=H(i.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(a)):(s.wantType===D.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(a,{cid:i,priority:s.priority,wantType:s.wantType??D.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=H(e.multihash.bytes,"base64"),s=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&s.push(i);await Promise.all(s.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var qi=Cr(Cn(),1);var De;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(De||(De={}));var Rr=Cr(Mn(),1);var Gi=Math.LN2*Math.LN2,Lt=class r{static create(e,t=.005){let n=Wi(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=$i(e.hashes??8),this.bits=e.bits??1024,this.buffer=I(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=ae(e));for(let t=0;t<this.seeds.length;t++){let s=Rr.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(s)}}has(e){typeof e=="string"&&(e=ae(e));for(let t=0;t<this.seeds.length;t++){let s=Rr.default.x86.hash32(e,this.seeds[t])%this.bits;if(!this.getbit(s))return!1}return!0}clear(){this.buffer.fill(0)}setbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;let s=this.buffer[t];s|=1<<n,this.buffer[t]=s}getbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;return(this.buffer[t]&1<<n)!==0}};function Wi(r,e=.005){let t=Math.round(-1*r*Math.log(e)/Gi),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function $i(r){let e,t,n=[];for(let s=0;s<r;s++)for(e=new Y(vt(4)),n[s]=e.getUint32(0,!0),t=0;t<s;t++)if(n[s]===n[t]){s--;break}return n}var Qe=class extends W{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),U(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Lt.create(this.maxProviders)}async retrieve(e,t={}){let n=ie.encode(e.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",e),s;let i=V();if(this.requests.set(n,i.promise),this.providers.length===0){let p=!1;this.intialPeerSearchComplete==null&&(p=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,p&&this.log("found initial session peers for %c",e)}let a=!1,c=new me({concurrency:this.maxProviders});c.addEventListener("error",()=>{}),c.addEventListener("failure",p=>{this.log.error("error querying provider %o, evicting from session",p.detail.job.options.provider,p.detail.error),this.evict(p.detail.job.options.provider)}),c.addEventListener("success",p=>{a=!0,i.resolve(p.detail.result)}),c.addEventListener("idle",()=>{a||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let p=0;p<this.minProviders&&this.providers.length!==0;p++){let y=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(y)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(p=>{this.log.error("could not find new providers for %c",e,p),i.reject(p)})});let h=p=>{c.add(async()=>this.queryProvider(e,p.detail,t),{provider:p.detail}).catch(y=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,y)})};this.addEventListener("provider",h),Promise.all([...this.providers].map(async p=>c.add(async()=>this.queryProvider(e,p,t),{provider:p}))).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,p)});try{return await i.promise}finally{this.removeEventListener("provider",h),c.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let s=V(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let a of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(a)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),i++,i===t&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new B(`Found ${i} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(a=>{this.log.error("error searching routing for potential session peers for %c",e,a.errors??a),s.reject(a)}),s.promise}};var Mr=class extends Qe{wantList;network;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let s=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toBytes()}equals(e,t){return e.equals(t)}};function Un(r,e){return new Mr(r,e)}var _t=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var Nr=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Pn(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Nr({name:e,metrics:t}):n=new Map,n}function Xi(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=it(r);e.push(t),r=r.slice(T(t))}return e}var Fn=Xi;var Dt=class extends W{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),U(1/0,this),this.peers=Xe({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Pn({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(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(e,t){let n=H(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??D.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===D.WantHave&&t.wantType===D.WantBlock&&(s.wantType=D.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===D.WantBlock?(await q(this,"block",t?.signal,{filter:c=>$(e.multihash.digest,c.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await q(this,"presence",t?.signal,{filter:a=>$(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=V(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,s=new J;for(let[i,a]of this.wants.entries())t.has(i)||a.cancel||(n.add(i),s.addWantlistEntry(a.cid,{cid:a.cid.bytes,priority:a.priority,wantType:a.wantType,cancel:a.cancel,sendDontHave:a.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(e,s);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=H(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let s=new J;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:D.WantHave,priority:1}),await this.network.sendMessage(t,s),(await q(this,"presence",n.signal,{filter:a=>t.equals(a.detail.sender)&&$(e.multihash.digest,a.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:D.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new J;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:D.WantBlock,priority:1}),await this.network.sendMessage(t,s),(await q(this,"presence",n.signal,{filter:a=>t.equals(a.detail.sender)&&$(e.multihash.digest,a.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=H(e.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let s of t.blocks){if(s.prefix==null||s.data==null)continue;let i=Fn(s.prefix),a=i[0],c=i[1],h=i[2],p=h===oe.code?oe:await this.hashLoader?.getHasher(h);if(p==null){this.log.error("unknown hash algorithm",h);continue}let y=p.digest(s.data);y.then!=null&&(y=await y);let m=O.create(a===0?0:1,c,y);this.log("received block from %p for %c",e,m),this.safeDispatchEvent("block",{detail:{sender:e,cid:m,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:m,has:!0,block:s.data}});let L=H(m.multihash.bytes,"base64"),o=this.wants.get(L);o!=null&&(o.cancel=!0,n=!0)}for(let{cid:s,type:i}of t.blockPresences){let a=O.decode(s);this.log("received %s from %p for %c",i,e,a),this.safeDispatchEvent("presence",{detail:{sender:e,cid:a,has:i===z.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new J(!0);for(let[s,i]of this.wants.entries())i.cancel||(t.add(s),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:D.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(s){this.log.error("error sending full wantlist to new peer %p",e,s)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Tt=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new _t(e),this.network=new Et(e,t),this.peerWantLists=new kt({...e,network:this.network},t),this.wantList=new Dt({...e,network:this.network},t)}createSession(e={}){return Un({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,s=Ur([n.signal,t.signal]);U(1/0,n.signal,s),this.network.findAndConnect(e,{...t,signal:s}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,i)});try{return(await this.wantList.wantBlock(e,{...t,signal:s})).block}finally{n.abort(),s.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Qi=(r,e={})=>new Tt(r,e);return Gn(Ki);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/hashes/esm/utils.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@helia/bitswap",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "JavaScript implementation of the Bitswap data exchange protocol used by Helia",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/ipfs/helia/tree/main/packages/bitswap#readme",
@@ -150,7 +150,7 @@
150
150
  "dependencies": {
151
151
  "@helia/interface": "^4.3.1",
152
152
  "@helia/utils": "^0.3.3",
153
- "@libp2p/interface": "^1.1.2",
153
+ "@libp2p/interface": "^1.1.4",
154
154
  "@libp2p/logger": "^4.0.5",
155
155
  "@libp2p/peer-collections": "^5.1.6",
156
156
  "@libp2p/utils": "^5.2.3",