@libp2p/mplex 11.0.19-21088c519 → 11.0.19-7a1665cd8

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.min.js CHANGED
@@ -1,3 +1,3 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PMplex = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PMplex=(()=>{var xe=Object.defineProperty;var zt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Bt=Object.prototype.hasOwnProperty;var I=(r,e)=>{for(var t in e)xe(r,t,{get:e[t],enumerable:!0})},Wt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vt(e))!Bt.call(r,s)&&s!==t&&xe(r,s,{get:()=>e[s],enumerable:!(n=zt(e,s))||n.enumerable});return r};var Gt=r=>Wt(xe({},"__esModule",{value:!0}),r);var Cn={};I(Cn,{mplex:()=>_n});var te=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},re=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},ne=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}};var K=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var se=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}};var tt=Symbol.for("@libp2p/service-capabilities"),Mn=Symbol.for("@libp2p/service-dependencies");function rt(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function nt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function oe(r,e){let t=rt(r).return?.();nt(t)&&t.catch(n=>{e.error("could not cause iterator to return",n)})}var st=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},$t=new WeakMap;function Kt({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(st());let o,i,a,c=r??clearTimeout,m=()=>{c(o),a(st())},f=()=>{s&&s.removeEventListener("abort",m)},l=new Promise((w,U)=>{i=()=>{f(),w(n)},a=U,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",m,{once:!0}),$t.set(l,()=>{c(o),o=null,i()}),l}}var qt=Kt(),ot=qt;var ie=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}};var ae=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Ee}async consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new ie("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await ot(a)}return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Ee=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function M(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ce=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}},z=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ce(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 ce(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 Se=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function O(r={}){return jt(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 jt(r,e){e=e??{};let t=e.onEnd,n=new z,s,o,i,a=M(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,g)=>{o=x=>{o=null,n.push(x);try{h(r(n))}catch(y){g(y)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=M()})}},m=h=>o!=null?o(h):(n.push(h),s),f=h=>(n=new z,o!=null?o({error:h}):(n.push({error:h}),s)),l=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return m({done:!1,value:h})},w=h=>i?s:(i=!0,h!=null?f(h):m({done:!0})),U=()=>(n=new z,w(),{done:!0}),d=h=>(w(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:U,throw:d,push:l,end:w,get readableLength(){return n.size},onEmpty:async h=>{let g=h?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,y;g!=null&&(x=new Promise((S,v)=>{y=()=>{v(new Se)},g.addEventListener("abort",y)}));try{await Promise.race([a.promise,x])}finally{y!=null&&g!=null&&g?.removeEventListener("abort",y)}}},t==null)return s;let b=s;return s={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(h){return b.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(h){return b.end(h),t!=null&&(t(h),t=void 0),s},get readableLength(){return b.readableLength},onEmpty:h=>b.onEmpty(h)},s}function Xt(r){return r[Symbol.asyncIterator]!=null}function Qt(...r){let e=[];for(let t of r)Xt(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=O({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 it=Qt;function at(r,...e){if(r==null)throw new Error("Empty pipeline");if(Ie(r)){let n=r;r=()=>n.source}else if(ut(r)||ct(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Ie(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++)Ie(t[n])&&(t[n]=Zt(t[n]));return Jt(...t)}var Jt=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},ct=r=>r?.[Symbol.asyncIterator]!=null,ut=r=>r?.[Symbol.iterator]!=null,Ie=r=>r==null?!1:r.sink!=null&&r.source!=null,Zt=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=O({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(ct(o))s=async function*(){yield*o,n.end()};else if(ut(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return it(n,s())}return r.source};function Ae(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 L(r=0){return new Uint8Array(r)}function A(r=0){return new Uint8Array(r)}function ue(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=A(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Te={};I(Te,{base10:()=>sr});var Ms=new Uint8Array(0);function ht(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 D(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 lt(r){return new TextEncoder().encode(r)}function dt(r){return new TextDecoder().decode(r)}function Yt(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 o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),m=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var b=0,h=0,g=0,x=d.length;g!==x&&d[g]===0;)g++,b++;for(var y=(x-g)*f+1>>>0,S=new Uint8Array(y);g!==x;){for(var v=d[g],N=0,_=y-1;(v!==0||N<h)&&_!==-1;_--,N++)v+=256*S[_]>>>0,S[_]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");h=N,g++}for(var T=y-h;T!==y&&S[T]===0;)T++;for(var ee=c.repeat(b);T<y;++T)ee+=r.charAt(S[T]);return ee}function w(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var b=0;if(d[b]!==" "){for(var h=0,g=0;d[b]===c;)h++,b++;for(var x=(d.length-b)*m+1>>>0,y=new Uint8Array(x);d[b];){var S=t[d.charCodeAt(b)];if(S===255)return;for(var v=0,N=x-1;(S!==0||v<g)&&N!==-1;N--,v++)S+=a*y[N]>>>0,y[N]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");g=v,b++}if(d[b]!==" "){for(var _=x-g;_!==x&&y[_]===0;)_++;for(var T=new Uint8Array(h+(x-_)),ee=h;_!==x;)T[ee++]=y[_++];return T}}}function U(d){var b=w(d);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:w,decode:U}}var er=Yt,tr=er,mt=tr;var ve=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")}},_e=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 pt(this,e)}},Ce=class{decoders;constructor(e){this.decoders=e}or(e){return pt(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 pt(r,e){return new Ce({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Re=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 ve(e,t,n),this.decoder=new _e(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function V({name:r,prefix:e,encode:t,decode:n}){return new Re(r,e,t,n)}function k({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=mt(t,r);return V({prefix:e,name:r,encode:n,decode:o=>D(s(o))})}function rr(r,e,t,n){let s={};for(let f=0;f<e.length;++f)s[e[f]]=f;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),a=0,c=0,m=0;for(let f=0;f<o;++f){let l=s[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[m++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function nr(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;o.length*t&7;)o+="=";return o}function p({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return V({prefix:e,name:r,encode(s){return nr(s,n,t)},decode(s){return rr(s,n,t,r)}})}var sr=k({prefix:"9",name:"base10",alphabet:"0123456789"});var Me={};I(Me,{base16:()=>or,base16upper:()=>ir});var or=p({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ir=p({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Le={};I(Le,{base2:()=>ar});var ar=p({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var De={};I(De,{base256emoji:()=>dr});var bt=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}"),cr=bt.reduce((r,e,t)=>(r[t]=e,r),[]),ur=bt.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function hr(r){return r.reduce((e,t)=>(e+=cr[t],e),"")}function lr(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=ur[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var dr=V({prefix:"\u{1F680}",name:"base256emoji",encode:hr,decode:lr});var Ue={};I(Ue,{base32:()=>B,base32hex:()=>br,base32hexpad:()=>yr,base32hexpadupper:()=>wr,base32hexupper:()=>gr,base32pad:()=>mr,base32padupper:()=>pr,base32upper:()=>fr,base32z:()=>xr});var B=p({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fr=p({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),mr=p({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pr=p({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),br=p({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gr=p({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yr=p({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wr=p({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xr=p({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ne={};I(Ne,{base36:()=>q,base36upper:()=>Er});var q=k({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Er=k({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Oe={};I(Oe,{base58btc:()=>C,base58flickr:()=>Sr});var C=k({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sr=k({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ke={};I(ke,{base64:()=>Ir,base64pad:()=>Ar,base64url:()=>vr,base64urlpad:()=>_r});var Ir=p({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ar=p({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vr=p({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_r=p({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Pe={};I(Pe,{base8:()=>Cr});var Cr=p({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Fe={};I(Fe,{identity:()=>Rr});var Rr=V({prefix:"\0",name:"identity",encode:r=>dt(r),decode:r=>lt(r)});var qs=new TextEncoder,js=new TextDecoder;var Ve={};I(Ve,{identity:()=>Zr});var Lr=wt,gt=128,Dr=127,Ur=~Dr,Nr=Math.pow(2,31);function wt(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Nr;)e[t++]=r&255|gt,r/=128;for(;r&Ur;)e[t++]=r&255|gt,r>>>=7;return e[t]=r|0,wt.bytes=t-n+1,e}var Or=ze,kr=128,yt=127;function ze(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ze.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&yt)<<s:(i&yt)*Math.pow(2,s),s+=7}while(i>=kr);return ze.bytes=o-n,t}var Pr=Math.pow(2,7),Fr=Math.pow(2,14),zr=Math.pow(2,21),Vr=Math.pow(2,28),Br=Math.pow(2,35),Wr=Math.pow(2,42),Gr=Math.pow(2,49),$r=Math.pow(2,56),Kr=Math.pow(2,63),qr=function(r){return r<Pr?1:r<Fr?2:r<zr?3:r<Vr?4:r<Br?5:r<Wr?6:r<Gr?7:r<$r?8:r<Kr?9:10},jr={encode:Lr,decode:Or,encodingLength:qr},Xr=jr,j=Xr;function X(r,e=0){return[j.decode(r,e),j.decode.bytes]}function W(r,e,t=0){return j.encode(r,e,t),e}function G(r){return j.encodingLength(r)}function P(r,e){let t=e.byteLength,n=G(r),s=n+G(t),o=new Uint8Array(s+t);return W(r,o,0),W(t,o,n),o.set(e,s),new $(r,t,e,o)}function xt(r){let e=D(r),[t,n]=X(e),[s,o]=X(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new $(t,s,i,e)}function Et(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ht(r.bytes,t.bytes)}}var $=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var St=0,Qr="identity",It=D;function Jr(r){return P(St,It(r))}var Zr={code:St,name:Qr,encode:It,digest:Jr};var Ge={};I(Ge,{sha256:()=>Hr,sha512:()=>Yr});function We({name:r,code:e,encode:t}){return new Be(r,e,t)}var Be=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?P(this.code,t):t.then(n=>P(this.code,n))}else throw Error("Unknown type, must be binary type")}};function vt(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Hr=We({name:"sha2-256",code:18,encode:vt("SHA-256")}),Yr=We({name:"sha2-512",code:19,encode:vt("SHA-512")});function _t(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return tn(t,$e(r),e??C.encoder);default:return rn(t,$e(r),e??B.encoder)}}var Ct=new WeakMap;function $e(r){let e=Ct.get(r);if(e==null){let t=new Map;return Ct.set(r,t),t}return e}var le=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!==J)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==nn)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=P(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&&Et(e.multihash,n.multihash)}toString(e){return _t(this,e)}toJSON(){return{"/":_t(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:o,bytes:i}=t;return new r(n,s,o,i??Rt(n,s,o.bytes))}else if(t[sn]===!0){let{version:n,multihash:s,code:o}=t,i=xt(s);return r.create(n,o,i)}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!==J)throw new Error(`Version 0 CID must use dag-pb (code: ${J}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Rt(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,J,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=D(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new $(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,w]=X(e.subarray(t));return t+=w,l},s=n(),o=J;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),m=t+c,f=m-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:m}}static parse(e,t){let[n,s]=en(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $e(o).set(n,e),o}};function en(r,e){switch(r[0]){case"Q":{let t=e??C;return[C.prefix,t.decode(`${C.prefix}${r}`)]}case C.prefix:{let t=e??C;return[C.prefix,t.decode(r)]}case B.prefix:{let t=e??B;return[B.prefix,t.decode(r)]}case q.prefix:{let t=e??q;return[q.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 tn(r,e,t){let{prefix:n}=t;if(n!==C.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function rn(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var J=112,nn=18;function Rt(r,e,t){let n=G(r),s=n+G(e),o=new Uint8Array(s+t.byteLength);return W(r,o,0),W(e,o,n),o.set(t,s),o}var sn=Symbol.for("@ipld/js-cid/CID");var Ke={...Fe,...Le,...Pe,...Te,...Me,...Ue,...Ne,...Oe,...ke,...De},bo={...Ge,...Ve};function Mt(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Tt=Mt("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),qe=Mt("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=A(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),on={utf8:Tt,"utf-8":Tt,hex:Ke.base16,latin1:qe,ascii:qe,binary:qe,...Ke},de=on;function je(r,e="utf8"){let t=de[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Z(r,e="utf8"){let t=de[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Dt=Symbol.for("@achingbrain/uint8arraylist");function Lt(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 fe(r){return!!r?.[Dt]}var R=class r{bufs;length;[Dt]=!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(fe(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(fe(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=Lt(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Lt(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(fe(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 ue(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:ue(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_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 o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let m=e>=a&&e<c,f=t>a&&t<=c;if(m&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(m){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!fe(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 o=256,i=new Int32Array(o);for(let l=0;l<o;l++)i[l]=-1;for(let l=0;l<s;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,m=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let w=m;w>=0;w--){let U=this.get(l+w);if(n[w]!==U){f=Math.max(1,w-a[U]);break}}if(f===0)return l}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=A(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=L(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=L(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=L(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=A(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=L(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=L(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=L(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=L(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=L(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(!Ae(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,o)=>s+o.byteLength,0)),n.length=t,n}};var u;(function(r){r[r.NEW_STREAM=0]="NEW_STREAM",r[r.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",r[r.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",r[r.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",r[r.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",r[r.RESET_RECEIVER=5]="RESET_RECEIVER",r[r.RESET_INITIATOR=6]="RESET_INITIATOR"})(u||(u={}));var H=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Xe=Object.freeze({NEW_STREAM:u.NEW_STREAM,MESSAGE:u.MESSAGE_INITIATOR,CLOSE:u.CLOSE_INITIATOR,RESET:u.RESET_INITIATOR}),Ut=Object.freeze({MESSAGE:u.MESSAGE_RECEIVER,CLOSE:u.CLOSE_RECEIVER,RESET:u.RESET_RECEIVER});var Qe=1<<20,an=4<<20,me=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Qe,t=an){this._buffer=new R,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(e==null||e.length===0)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new K("Unprocessed message queue size too large!");let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(m){if(m.name==="InvalidMessageError")throw m;break}let{id:n,type:s,length:o,offset:i}=this._headerInfo;if(this._buffer.length-i<o)break;let c={id:n,type:s};(s===u.NEW_STREAM||s===u.MESSAGE_INITIATOR||s===u.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(i,i+o)),t.push(c),this._buffer.consume(i+o),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:n}=Ot(e),{value:s,offset:o}=Ot(e,n),i=t&7;if(H[i]==null)throw new Error(`Invalid type received: ${i}`);if(s>this._maxMessageSize)throw new K("Message size too large");return{id:t>>3,type:i,offset:n+o,length:s}}},cn=128,Nt=127;function Ot(r,e=0){let t=0,n=0,s=e,o,i=r.length;do{if(s>=i||n>49)throw e=0,new RangeError("Could not decode varint");o=r.get(s++),t+=n<28?(o&Nt)<<n:(o&Nt)*Math.pow(2,n),n+=7}while(o>=cn);return e=s-e,{value:t,offset:e}}var un=Math.pow(2,7),hn=Math.pow(2,14),ln=Math.pow(2,21),dn=Math.pow(2,28),fn=Math.pow(2,35),mn=Math.pow(2,42),pn=Math.pow(2,49),E=128;function F(r){if(r<un)return 1;if(r<hn)return 2;if(r<ln)return 3;if(r<dn)return 4;if(r<fn)return 5;if(r<mn)return 6;if(r<pn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function bn(r,e,t=0){switch(F(r)){case 8:e[t++]=r&255|E,r/=128;case 7:e[t++]=r&255|E,r/=128;case 6:e[t++]=r&255|E,r/=128;case 5:e[t++]=r&255|E,r/=128;case 4:e[t++]=r&255|E,r>>>=7;case 3:e[t++]=r&255|E,r>>>=7;case 2:e[t++]=r&255|E,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function gn(r,e,t=0){switch(F(r)){case 8:e.set(t++,r&255|E),r/=128;case 7:e.set(t++,r&255|E),r/=128;case 6:e.set(t++,r&255|E),r/=128;case 5:e.set(t++,r&255|E),r/=128;case 4:e.set(t++,r&255|E),r>>>=7;case 3:e.set(t++,r&255|E),r>>>=7;case 2:e.set(t++,r&255|E),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function pe(r,e,t=0){return e==null&&(e=A(F(r))),e instanceof Uint8Array?bn(r,e,t):gn(r,e,t)}var Je=10*1024,Ze=class{_pool;_poolOffset;constructor(){this._pool=A(Je),this._poolOffset=0}write(e,t){let n=this._pool,s=this._poolOffset;pe(e.id<<3|e.type,n,s),s+=F(e.id<<3|e.type),(e.type===u.NEW_STREAM||e.type===u.MESSAGE_INITIATOR||e.type===u.MESSAGE_RECEIVER)&&e.data!=null?(pe(e.data.length,n,s),s+=F(e.data.length)):(pe(0,n,s),s+=F(0));let o=n.subarray(this._poolOffset,s);Je-s<100?(this._pool=A(Je),this._poolOffset=0):this._poolOffset=s,t.append(o),(e.type===u.NEW_STREAM||e.type===u.MESSAGE_INITIATOR||e.type===u.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},wn=new Ze;async function*kt(r){for await(let e of r){let t=new R;wn.write(e,t),yield t}}var be=class extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}};var ge=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 Y(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new ge(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new ge(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var xn=5e3;function He(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ye=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=M(),this.closed=M(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??xn,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=O({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new ne(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let s=this.sendNewStream(t);He(s)&&await s}let n=()=>{oe(e,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let s of e){s=s instanceof Uint8Array?new R(s):s;let o=this.sendData(s,t);He(o)&&(this.sendingData=M(),await o,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await Y(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await Y(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Y(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Y(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();He(t)&&t.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new re("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};var Ye=class extends ye{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?Xe:Ut,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:Xe.NEW_STREAM,data:new R(je(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}};function Pt(r){let{id:e,name:t,send:n,onEnd:s,type:o="initiator",maxMsgSize:i=Qe}=r;return new Ye({id:o==="initiator"?`i${e}`:`r${e}`,streamId:e,name:`${t??e}`,direction:o==="initiator"?"outbound":"inbound",maxDataSize:i,onEnd:s,send:n,log:r.logger.forComponent(`libp2p:mplex:stream:${o}:${e}`)})}var En=1024,Sn=1024,In=1024*1024*4,An=5,vn=500;function Ft(r){let e={...r,type:`${H[r.type]} (${r.type})`};return r.type===u.NEW_STREAM&&(e.data=Z(r.data instanceof Uint8Array?r.data:r.data.subarray())),(r.type===u.MESSAGE_INITIATOR||r.type===u.MESSAGE_RECEIVER)&&(e.data=Z(r.data instanceof Uint8Array?r.data:r.data.subarray(),"base16")),e}var we=class{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??vn,this.sink=this._createSink(),this._source=O({objectMode:!0,onEnd:()=>{for(let n of this._streams.initiators.values())n.destroy();for(let n of this._streams.receivers.values())n.destroy()}}),this.source=at(this._source,n=>kt(n)),this.closeController=new AbortController,this.rateLimiter=new ae({points:t.disconnectThreshold??An,duration:1})}get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new te("Muxer already closed");let t=this._streamId++;e=e==null?t.toString():e.toString();let n=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:n})}async close(e){if(this.closeController.signal.aborted)return;let t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async n=>n.close({signal:t}))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(n){this.abort(n)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(t=>{t.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){let{id:t,name:n}=e,s=this._streams.receivers;return this._newStream({id:t,name:n,type:"receiver",registry:s})}_newStream(e){let{id:t,name:n,type:s,registry:o}=e;if(this.log("new %s stream %s",s,t),s==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??Sn))throw new se("Too many outbound streams open");if(o.has(t))throw new Error(`${s} stream ${t} already exists!`);let c=Pt({id:t,name:n,send:async m=>{this.log.enabled&&this.log.trace("%s stream %s send",s,t,Ft(m)),this._source.push(m)},type:s,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",s,t,c.protocol),o.delete(t),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return o.set(t,c),c}_createSink(){return async t=>{let n=()=>{oe(t,this.log)};this.closeController.signal.addEventListener("abort",n);try{let s=new me(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let o of t)for(let i of s.write(o))await this._handleIncoming(i);this._source.end()}catch(s){this.log("error in sink",s),this._source.end(s)}finally{this.closeController.signal.removeEventListener("abort",n)}}}async _handleIncoming(e){let{id:t,type:n}=e;if(this.log.enabled&&this.log.trace("incoming message",Ft(e)),e.type===u.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??En)){this.log("too many inbound streams open"),this._source.push({id:t,type:u.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}let a=this._newReceiverStream({id:t,name:Z(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let o=((n&1)===1?this._streams.initiators:this._streams.receivers).get(t);if(o==null){this.log("missing stream %s for message type %s",t,H[n]);try{await this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}let i=this._init.maxStreamBufferSize??In;try{switch(n){case u.MESSAGE_INITIATOR:case u.MESSAGE_RECEIVER:if(o.sourceReadableLength()>i)throw this._source.push({id:e.id,type:n===u.MESSAGE_INITIATOR?u.RESET_RECEIVER:u.RESET_INITIATOR}),new be("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");o.sourcePush(e.data);break;case u.CLOSE_INITIATOR:case u.CLOSE_RECEIVER:o.remoteCloseWrite();break;case u.RESET_INITIATOR:case u.RESET_RECEIVER:o.reset();break;default:this.log("unknown message type %s",n)}}catch(a){this.log.error("error while processing message",a),o.abort(a)}}};var et=class{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[tt]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new we(this.components,{...e,...this._init})}};function _n(r={}){return e=>new et(e,r)}return Gt(Cn);})();
2
+ "use strict";var Libp2PMplex=(()=>{var xe=Object.defineProperty;var zt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Bt=Object.prototype.hasOwnProperty;var I=(r,e)=>{for(var t in e)xe(r,t,{get:e[t],enumerable:!0})},Wt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vt(e))!Bt.call(r,s)&&s!==t&&xe(r,s,{get:()=>e[s],enumerable:!(n=zt(e,s))||n.enumerable});return r};var Gt=r=>Wt(xe({},"__esModule",{value:!0}),r);var Cn={};I(Cn,{mplex:()=>_n});var te=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},re=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},ne=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}};var K=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var se=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}};var tt=Symbol.for("@libp2p/service-capabilities"),Mn=Symbol.for("@libp2p/service-dependencies");function rt(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function nt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function oe(r,e){let t=rt(r).return?.();nt(t)&&t.catch(n=>{e.error("could not cause iterator to return",n)})}var st=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},$t=new WeakMap;function Kt({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(st());let o,i,a,c=r??clearTimeout,m=()=>{c(o),a(st())},f=()=>{s&&s.removeEventListener("abort",m)},l=new Promise((w,U)=>{i=()=>{f(),w(n)},a=U,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",m,{once:!0}),$t.set(l,()=>{c(o),o=null,i()}),l}}var qt=Kt(),ot=qt;var ie=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}};var ae=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Ee}async consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new ie("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await ot(a)}return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Ee=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function M(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ce=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}},z=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ce(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 ce(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 Se=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function O(r={}){return jt(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 jt(r,e){e=e??{};let t=e.onEnd,n=new z,s,o,i,a=M(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,g)=>{o=x=>{o=null,n.push(x);try{h(r(n))}catch(y){g(y)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=M()})}},m=h=>o!=null?o(h):(n.push(h),s),f=h=>(n=new z,o!=null?o({error:h}):(n.push({error:h}),s)),l=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return m({done:!1,value:h})},w=h=>i?s:(i=!0,h!=null?f(h):m({done:!0})),U=()=>(n=new z,w(),{done:!0}),d=h=>(w(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:U,throw:d,push:l,end:w,get readableLength(){return n.size},onEmpty:async h=>{let g=h?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,y;g!=null&&(x=new Promise((S,v)=>{y=()=>{v(new Se)},g.addEventListener("abort",y)}));try{await Promise.race([a.promise,x])}finally{y!=null&&g!=null&&g?.removeEventListener("abort",y)}}},t==null)return s;let b=s;return s={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(h){return b.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(h){return b.end(h),t!=null&&(t(h),t=void 0),s},get readableLength(){return b.readableLength},onEmpty:h=>b.onEmpty(h)},s}function Xt(r){return r[Symbol.asyncIterator]!=null}function Qt(...r){let e=[];for(let t of r)Xt(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=O({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 it=Qt;function at(r,...e){if(r==null)throw new Error("Empty pipeline");if(Ie(r)){let n=r;r=()=>n.source}else if(ut(r)||ct(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Ie(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++)Ie(t[n])&&(t[n]=Zt(t[n]));return Jt(...t)}var Jt=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},ct=r=>r?.[Symbol.asyncIterator]!=null,ut=r=>r?.[Symbol.iterator]!=null,Ie=r=>r==null?!1:r.sink!=null&&r.source!=null,Zt=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=O({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(ct(o))s=async function*(){yield*o,n.end()};else if(ut(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return it(n,s())}return r.source};function Ae(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 L(r=0){return new Uint8Array(r)}function A(r=0){return new Uint8Array(r)}function ue(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=A(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Te={};I(Te,{base10:()=>sr});var Ts=new Uint8Array(0);function ht(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 D(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 lt(r){return new TextEncoder().encode(r)}function dt(r){return new TextDecoder().decode(r)}function Yt(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 o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),m=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var b=0,h=0,g=0,x=d.length;g!==x&&d[g]===0;)g++,b++;for(var y=(x-g)*f+1>>>0,S=new Uint8Array(y);g!==x;){for(var v=d[g],N=0,_=y-1;(v!==0||N<h)&&_!==-1;_--,N++)v+=256*S[_]>>>0,S[_]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");h=N,g++}for(var T=y-h;T!==y&&S[T]===0;)T++;for(var ee=c.repeat(b);T<y;++T)ee+=r.charAt(S[T]);return ee}function w(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var b=0;if(d[b]!==" "){for(var h=0,g=0;d[b]===c;)h++,b++;for(var x=(d.length-b)*m+1>>>0,y=new Uint8Array(x);d[b];){var S=t[d.charCodeAt(b)];if(S===255)return;for(var v=0,N=x-1;(S!==0||v<g)&&N!==-1;N--,v++)S+=a*y[N]>>>0,y[N]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");g=v,b++}if(d[b]!==" "){for(var _=x-g;_!==x&&y[_]===0;)_++;for(var T=new Uint8Array(h+(x-_)),ee=h;_!==x;)T[ee++]=y[_++];return T}}}function U(d){var b=w(d);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:w,decode:U}}var er=Yt,tr=er,mt=tr;var ve=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")}},_e=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 pt(this,e)}},Ce=class{decoders;constructor(e){this.decoders=e}or(e){return pt(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 pt(r,e){return new Ce({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Re=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 ve(e,t,n),this.decoder=new _e(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function V({name:r,prefix:e,encode:t,decode:n}){return new Re(r,e,t,n)}function k({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=mt(t,r);return V({prefix:e,name:r,encode:n,decode:o=>D(s(o))})}function rr(r,e,t,n){let s={};for(let f=0;f<e.length;++f)s[e[f]]=f;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),a=0,c=0,m=0;for(let f=0;f<o;++f){let l=s[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[m++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function nr(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;o.length*t&7;)o+="=";return o}function p({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return V({prefix:e,name:r,encode(s){return nr(s,n,t)},decode(s){return rr(s,n,t,r)}})}var sr=k({prefix:"9",name:"base10",alphabet:"0123456789"});var Me={};I(Me,{base16:()=>or,base16upper:()=>ir});var or=p({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ir=p({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Le={};I(Le,{base2:()=>ar});var ar=p({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var De={};I(De,{base256emoji:()=>dr});var bt=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}"),cr=bt.reduce((r,e,t)=>(r[t]=e,r),[]),ur=bt.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function hr(r){return r.reduce((e,t)=>(e+=cr[t],e),"")}function lr(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=ur[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var dr=V({prefix:"\u{1F680}",name:"base256emoji",encode:hr,decode:lr});var Ue={};I(Ue,{base32:()=>B,base32hex:()=>br,base32hexpad:()=>yr,base32hexpadupper:()=>wr,base32hexupper:()=>gr,base32pad:()=>mr,base32padupper:()=>pr,base32upper:()=>fr,base32z:()=>xr});var B=p({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fr=p({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),mr=p({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pr=p({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),br=p({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gr=p({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yr=p({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wr=p({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xr=p({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ne={};I(Ne,{base36:()=>q,base36upper:()=>Er});var q=k({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Er=k({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Oe={};I(Oe,{base58btc:()=>C,base58flickr:()=>Sr});var C=k({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sr=k({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ke={};I(ke,{base64:()=>Ir,base64pad:()=>Ar,base64url:()=>vr,base64urlpad:()=>_r});var Ir=p({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ar=p({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vr=p({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_r=p({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Pe={};I(Pe,{base8:()=>Cr});var Cr=p({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Fe={};I(Fe,{identity:()=>Rr});var Rr=V({prefix:"\0",name:"identity",encode:r=>dt(r),decode:r=>lt(r)});var Ks=new TextEncoder,qs=new TextDecoder;var Ve={};I(Ve,{identity:()=>Zr});var Lr=wt,gt=128,Dr=127,Ur=~Dr,Nr=Math.pow(2,31);function wt(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Nr;)e[t++]=r&255|gt,r/=128;for(;r&Ur;)e[t++]=r&255|gt,r>>>=7;return e[t]=r|0,wt.bytes=t-n+1,e}var Or=ze,kr=128,yt=127;function ze(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ze.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&yt)<<s:(i&yt)*Math.pow(2,s),s+=7}while(i>=kr);return ze.bytes=o-n,t}var Pr=Math.pow(2,7),Fr=Math.pow(2,14),zr=Math.pow(2,21),Vr=Math.pow(2,28),Br=Math.pow(2,35),Wr=Math.pow(2,42),Gr=Math.pow(2,49),$r=Math.pow(2,56),Kr=Math.pow(2,63),qr=function(r){return r<Pr?1:r<Fr?2:r<zr?3:r<Vr?4:r<Br?5:r<Wr?6:r<Gr?7:r<$r?8:r<Kr?9:10},jr={encode:Lr,decode:Or,encodingLength:qr},Xr=jr,j=Xr;function X(r,e=0){return[j.decode(r,e),j.decode.bytes]}function W(r,e,t=0){return j.encode(r,e,t),e}function G(r){return j.encodingLength(r)}function P(r,e){let t=e.byteLength,n=G(r),s=n+G(t),o=new Uint8Array(s+t);return W(r,o,0),W(t,o,n),o.set(e,s),new $(r,t,e,o)}function xt(r){let e=D(r),[t,n]=X(e),[s,o]=X(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new $(t,s,i,e)}function Et(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ht(r.bytes,t.bytes)}}var $=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var St=0,Qr="identity",It=D;function Jr(r){return P(St,It(r))}var Zr={code:St,name:Qr,encode:It,digest:Jr};var Ge={};I(Ge,{sha256:()=>Hr,sha512:()=>Yr});function We({name:r,code:e,encode:t}){return new Be(r,e,t)}var Be=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?P(this.code,t):t.then(n=>P(this.code,n))}else throw Error("Unknown type, must be binary type")}};function vt(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Hr=We({name:"sha2-256",code:18,encode:vt("SHA-256")}),Yr=We({name:"sha2-512",code:19,encode:vt("SHA-512")});function _t(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return tn(t,$e(r),e??C.encoder);default:return rn(t,$e(r),e??B.encoder)}}var Ct=new WeakMap;function $e(r){let e=Ct.get(r);if(e==null){let t=new Map;return Ct.set(r,t),t}return e}var le=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!==J)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==nn)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=P(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&&Et(e.multihash,n.multihash)}toString(e){return _t(this,e)}toJSON(){return{"/":_t(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:o,bytes:i}=t;return new r(n,s,o,i??Rt(n,s,o.bytes))}else if(t[sn]===!0){let{version:n,multihash:s,code:o}=t,i=xt(s);return r.create(n,o,i)}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!==J)throw new Error(`Version 0 CID must use dag-pb (code: ${J}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Rt(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,J,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=D(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new $(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,w]=X(e.subarray(t));return t+=w,l},s=n(),o=J;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),m=t+c,f=m-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:m}}static parse(e,t){let[n,s]=en(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $e(o).set(n,e),o}};function en(r,e){switch(r[0]){case"Q":{let t=e??C;return[C.prefix,t.decode(`${C.prefix}${r}`)]}case C.prefix:{let t=e??C;return[C.prefix,t.decode(r)]}case B.prefix:{let t=e??B;return[B.prefix,t.decode(r)]}case q.prefix:{let t=e??q;return[q.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 tn(r,e,t){let{prefix:n}=t;if(n!==C.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function rn(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var J=112,nn=18;function Rt(r,e,t){let n=G(r),s=n+G(e),o=new Uint8Array(s+t.byteLength);return W(r,o,0),W(e,o,n),o.set(t,s),o}var sn=Symbol.for("@ipld/js-cid/CID");var Ke={...Fe,...Le,...Pe,...Te,...Me,...Ue,...Ne,...Oe,...ke,...De},po={...Ge,...Ve};function Mt(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Tt=Mt("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),qe=Mt("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=A(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),on={utf8:Tt,"utf-8":Tt,hex:Ke.base16,latin1:qe,ascii:qe,binary:qe,...Ke},de=on;function je(r,e="utf8"){let t=de[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Z(r,e="utf8"){let t=de[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Dt=Symbol.for("@achingbrain/uint8arraylist");function Lt(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 fe(r){return!!r?.[Dt]}var R=class r{bufs;length;[Dt]=!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(fe(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(fe(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=Lt(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Lt(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(fe(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 ue(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:ue(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_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 o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let m=e>=a&&e<c,f=t>a&&t<=c;if(m&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(m){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!fe(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 o=256,i=new Int32Array(o);for(let l=0;l<o;l++)i[l]=-1;for(let l=0;l<s;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,m=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let w=m;w>=0;w--){let U=this.get(l+w);if(n[w]!==U){f=Math.max(1,w-a[U]);break}}if(f===0)return l}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=A(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=L(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=L(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=L(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=A(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=L(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=L(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=L(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=L(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=L(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(!Ae(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,o)=>s+o.byteLength,0)),n.length=t,n}};var u;(function(r){r[r.NEW_STREAM=0]="NEW_STREAM",r[r.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",r[r.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",r[r.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",r[r.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",r[r.RESET_RECEIVER=5]="RESET_RECEIVER",r[r.RESET_INITIATOR=6]="RESET_INITIATOR"})(u||(u={}));var H=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Xe=Object.freeze({NEW_STREAM:u.NEW_STREAM,MESSAGE:u.MESSAGE_INITIATOR,CLOSE:u.CLOSE_INITIATOR,RESET:u.RESET_INITIATOR}),Ut=Object.freeze({MESSAGE:u.MESSAGE_RECEIVER,CLOSE:u.CLOSE_RECEIVER,RESET:u.RESET_RECEIVER});var Qe=1<<20,an=4<<20,me=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Qe,t=an){this._buffer=new R,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(e==null||e.length===0)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new K("Unprocessed message queue size too large!");let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(m){if(m.name==="InvalidMessageError")throw m;break}let{id:n,type:s,length:o,offset:i}=this._headerInfo;if(this._buffer.length-i<o)break;let c={id:n,type:s};(s===u.NEW_STREAM||s===u.MESSAGE_INITIATOR||s===u.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(i,i+o)),t.push(c),this._buffer.consume(i+o),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:n}=Ot(e),{value:s,offset:o}=Ot(e,n),i=t&7;if(H[i]==null)throw new Error(`Invalid type received: ${i}`);if(s>this._maxMessageSize)throw new K("Message size too large");return{id:t>>3,type:i,offset:n+o,length:s}}},cn=128,Nt=127;function Ot(r,e=0){let t=0,n=0,s=e,o,i=r.length;do{if(s>=i||n>49)throw e=0,new RangeError("Could not decode varint");o=r.get(s++),t+=n<28?(o&Nt)<<n:(o&Nt)*Math.pow(2,n),n+=7}while(o>=cn);return e=s-e,{value:t,offset:e}}var un=Math.pow(2,7),hn=Math.pow(2,14),ln=Math.pow(2,21),dn=Math.pow(2,28),fn=Math.pow(2,35),mn=Math.pow(2,42),pn=Math.pow(2,49),E=128;function F(r){if(r<un)return 1;if(r<hn)return 2;if(r<ln)return 3;if(r<dn)return 4;if(r<fn)return 5;if(r<mn)return 6;if(r<pn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function bn(r,e,t=0){switch(F(r)){case 8:e[t++]=r&255|E,r/=128;case 7:e[t++]=r&255|E,r/=128;case 6:e[t++]=r&255|E,r/=128;case 5:e[t++]=r&255|E,r/=128;case 4:e[t++]=r&255|E,r>>>=7;case 3:e[t++]=r&255|E,r>>>=7;case 2:e[t++]=r&255|E,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function gn(r,e,t=0){switch(F(r)){case 8:e.set(t++,r&255|E),r/=128;case 7:e.set(t++,r&255|E),r/=128;case 6:e.set(t++,r&255|E),r/=128;case 5:e.set(t++,r&255|E),r/=128;case 4:e.set(t++,r&255|E),r>>>=7;case 3:e.set(t++,r&255|E),r>>>=7;case 2:e.set(t++,r&255|E),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function pe(r,e,t=0){return e==null&&(e=A(F(r))),e instanceof Uint8Array?bn(r,e,t):gn(r,e,t)}var Je=10*1024,Ze=class{_pool;_poolOffset;constructor(){this._pool=A(Je),this._poolOffset=0}write(e,t){let n=this._pool,s=this._poolOffset;pe(e.id<<3|e.type,n,s),s+=F(e.id<<3|e.type),(e.type===u.NEW_STREAM||e.type===u.MESSAGE_INITIATOR||e.type===u.MESSAGE_RECEIVER)&&e.data!=null?(pe(e.data.length,n,s),s+=F(e.data.length)):(pe(0,n,s),s+=F(0));let o=n.subarray(this._poolOffset,s);Je-s<100?(this._pool=A(Je),this._poolOffset=0):this._poolOffset=s,t.append(o),(e.type===u.NEW_STREAM||e.type===u.MESSAGE_INITIATOR||e.type===u.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},wn=new Ze;async function*kt(r){for await(let e of r){let t=new R;wn.write(e,t),yield t}}var be=class extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}};var ge=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 Y(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new ge(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new ge(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var xn=5e3;function He(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ye=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=M(),this.closed=M(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??xn,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=O({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new ne(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let s=this.sendNewStream(t);He(s)&&await s}let n=()=>{oe(e,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let s of e){s=s instanceof Uint8Array?new R(s):s;let o=this.sendData(s,t);He(o)&&(this.sendingData=M(),await o,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await Y(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await Y(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Y(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Y(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();He(t)&&t.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new re("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};var Ye=class extends ye{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?Xe:Ut,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:Xe.NEW_STREAM,data:new R(je(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}};function Pt(r){let{id:e,name:t,send:n,onEnd:s,type:o="initiator",maxMsgSize:i=Qe}=r;return new Ye({id:o==="initiator"?`i${e}`:`r${e}`,streamId:e,name:`${t??e}`,direction:o==="initiator"?"outbound":"inbound",maxDataSize:i,onEnd:s,send:n,log:r.logger.forComponent(`libp2p:mplex:stream:${o}:${e}`)})}var En=1024,Sn=1024,In=1024*1024*4,An=5,vn=500;function Ft(r){let e={...r,type:`${H[r.type]} (${r.type})`};return r.type===u.NEW_STREAM&&(e.data=Z(r.data instanceof Uint8Array?r.data:r.data.subarray())),(r.type===u.MESSAGE_INITIATOR||r.type===u.MESSAGE_RECEIVER)&&(e.data=Z(r.data instanceof Uint8Array?r.data:r.data.subarray(),"base16")),e}var we=class{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??vn,this.sink=this._createSink(),this._source=O({objectMode:!0,onEnd:()=>{for(let n of this._streams.initiators.values())n.destroy();for(let n of this._streams.receivers.values())n.destroy()}}),this.source=at(this._source,n=>kt(n)),this.closeController=new AbortController,this.rateLimiter=new ae({points:t.disconnectThreshold??An,duration:1})}get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new te("Muxer already closed");let t=this._streamId++;e=e==null?t.toString():e.toString();let n=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:n})}async close(e){if(this.closeController.signal.aborted)return;let t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async n=>n.close({signal:t}))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(n){this.abort(n)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(t=>{t.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){let{id:t,name:n}=e,s=this._streams.receivers;return this._newStream({id:t,name:n,type:"receiver",registry:s})}_newStream(e){let{id:t,name:n,type:s,registry:o}=e;if(this.log("new %s stream %s",s,t),s==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??Sn))throw new se("Too many outbound streams open");if(o.has(t))throw new Error(`${s} stream ${t} already exists!`);let c=Pt({id:t,name:n,send:async m=>{this.log.enabled&&this.log.trace("%s stream %s send",s,t,Ft(m)),this._source.push(m)},type:s,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",s,t,c.protocol),o.delete(t),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return o.set(t,c),c}_createSink(){return async t=>{let n=()=>{oe(t,this.log)};this.closeController.signal.addEventListener("abort",n);try{let s=new me(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let o of t)for(let i of s.write(o))await this._handleIncoming(i);this._source.end()}catch(s){this.log("error in sink",s),this._source.end(s)}finally{this.closeController.signal.removeEventListener("abort",n)}}}async _handleIncoming(e){let{id:t,type:n}=e;if(this.log.enabled&&this.log.trace("incoming message",Ft(e)),e.type===u.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??En)){this.log("too many inbound streams open"),this._source.push({id:t,type:u.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}let a=this._newReceiverStream({id:t,name:Z(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let o=((n&1)===1?this._streams.initiators:this._streams.receivers).get(t);if(o==null){this.log("missing stream %s for message type %s",t,H[n]);try{await this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}let i=this._init.maxStreamBufferSize??In;try{switch(n){case u.MESSAGE_INITIATOR:case u.MESSAGE_RECEIVER:if(o.sourceReadableLength()>i)throw this._source.push({id:e.id,type:n===u.MESSAGE_INITIATOR?u.RESET_RECEIVER:u.RESET_INITIATOR}),new be("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");o.sourcePush(e.data);break;case u.CLOSE_INITIATOR:case u.CLOSE_RECEIVER:o.remoteCloseWrite();break;case u.RESET_INITIATOR:case u.RESET_RECEIVER:o.reset();break;default:this.log("unknown message type %s",n)}}catch(a){this.log.error("error while processing message",a),o.abort(a)}}};var et=class{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[tt]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new we(this.components,{...e,...this._init})}};function _n(r={}){return e=>new et(e,r)}return Gt(Cn);})();
3
3
  return Libp2PMplex}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/mplex",
3
- "version": "11.0.19-21088c519",
3
+ "version": "11.0.19-7a1665cd8",
4
4
  "description": "JavaScript implementation of https://github.com/libp2p/mplex",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/stream-multiplexer-mplex#readme",
@@ -62,8 +62,8 @@
62
62
  "test:electron-main": "aegir test -t electron-main"
63
63
  },
64
64
  "dependencies": {
65
- "@libp2p/interface": "2.4.1-21088c519",
66
- "@libp2p/utils": "6.5.0-21088c519",
65
+ "@libp2p/interface": "2.4.1-7a1665cd8",
66
+ "@libp2p/utils": "6.5.0-7a1665cd8",
67
67
  "it-pipe": "^3.0.1",
68
68
  "it-pushable": "^3.2.3",
69
69
  "it-stream-types": "^2.0.2",
@@ -72,8 +72,8 @@
72
72
  "uint8arrays": "^5.1.0"
73
73
  },
74
74
  "devDependencies": {
75
- "@libp2p/interface-compliance-tests": "6.2.5-21088c519",
76
- "@libp2p/logger": "5.1.7-21088c519",
75
+ "@libp2p/interface-compliance-tests": "6.2.5-7a1665cd8",
76
+ "@libp2p/logger": "5.1.7-7a1665cd8",
77
77
  "aegir": "^45.0.5",
78
78
  "benchmark": "^2.1.4",
79
79
  "cborg": "^4.2.6",