@libp2p/mplex 10.0.11-8bbd43628 → 10.0.12-08f6f607d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,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 pt=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var Pe=Object.prototype.hasOwnProperty;var A=(r,t)=>{for(var e in t)pt(r,e,{get:t[e],enumerable:!0})},Be=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ke(t))!Pe.call(r,o)&&o!==e&&pt(r,o,{get:()=>t[o],enumerable:!(n=Oe(t,o))||n.enumerable});return r};var Fe=r=>Be(pt({},"__esModule",{value:!0}),r);var In={};A(In,{mplex:()=>_n});var Tn=Symbol.for("@libp2p/connection");var Ln=Symbol.for("@libp2p/content-routing");var Dn=Symbol.for("@libp2p/peer-discovery");var Un=Symbol.for("@libp2p/peer-id");var kn=Symbol.for("@libp2p/peer-routing");var Jt;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(Jt||(Jt={}));var Vn=Symbol.for("@libp2p/transport");var Ht;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ht||(Ht={}));var T=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var mt=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},Wn=globalThis.CustomEvent??mt;function Zt(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 Yt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function tt(r,t){let e=Zt(r).return?.();Yt(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var te=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Ve=new WeakMap;function ze({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(te());let s,i,a,c=r??clearTimeout,p=()=>{c(s),a(te())},d=()=>{o&&o.removeEventListener("abort",p)},h=new Promise((y,U)=>{i=()=>{d(),y(n)},a=U,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",p,{once:!0}),Ve.set(h,()=>{c(s),s=null,i()}),h}}var Ge=ze(),ee=Ge;var et=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new bt}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new T("Rate limit exceeded","ERR_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 ee(a)}return i}penalty(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},bt=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function B(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var rt=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},z=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new rt(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new rt(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var gt=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function k(r={}){return We(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function We(r,t){t=t??{};let e=t.onEnd,n=new z,o,s,i,a=B(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((l,g)=>{s=E=>{s=null,n.push(E);try{l(r(n))}catch(w){g(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=B()})}},p=l=>s!=null?s(l):(n.push(l),o),d=l=>(n=new z,s!=null?s({error:l}):(n.push({error:l}),o)),h=l=>{if(i)return o;if(t?.objectMode!==!0&&l?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return p({done:!1,value:l})},y=l=>i?o:(i=!0,l!=null?d(l):p({done:!0})),U=()=>(n=new z,y(),{done:!0}),f=l=>(y(l),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:U,throw:f,push:h,end:y,get readableLength(){return n.size},onEmpty:async l=>{let g=l?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,w;g!=null&&(E=new Promise((S,I)=>{w=()=>{I(new gt)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,E])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},e==null)return o;let b=o;return o={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(l){return b.throw(l),e!=null&&(e(l),e=void 0),{done:!0}},return(){return b.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(l){return b.end(l),e!=null&&(e(l),e=void 0),o},get readableLength(){return b.readableLength},onEmpty:l=>b.onEmpty(l)},o}function $e(r){return r[Symbol.asyncIterator]!=null}function Ke(...r){let t=[];for(let e of r)$e(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=k({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var re=Ke;function ne(r,...t){if(r==null)throw new Error("Empty pipeline");if(wt(r)){let n=r;r=()=>n.source}else if(se(r)||oe(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&wt(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)wt(e[n])&&(e[n]=qe(e[n]));return je(...e)}var je=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},oe=r=>r?.[Symbol.asyncIterator]!=null,se=r=>r?.[Symbol.iterator]!=null,wt=r=>r==null?!1:r.sink!=null&&r.source!=null,qe=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=k({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(oe(s))o=async function*(){yield*s,n.end()};else if(se(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return re(n,o())}return r.source};function M(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function D(r=0){return globalThis.Buffer?.alloc!=null?M(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function _(r=0){return globalThis.Buffer?.allocUnsafe!=null?M(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function nt(r,t){if(globalThis.Buffer!=null)return M(globalThis.Buffer.concat(r,t));t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=_(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return M(e)}function yt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var _t={};A(_t,{base10:()=>Ye});var qo=new Uint8Array(0);function ie(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function N(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 ae(r){return new TextEncoder().encode(r)}function ce(r){return new TextDecoder().decode(r)}function Xe(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),p=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var b=0,l=0,g=0,E=f.length;g!==E&&f[g]===0;)g++,b++;for(var w=(E-g)*d+1>>>0,S=new Uint8Array(w);g!==E;){for(var I=f[g],O=0,R=w-1;(I!==0||O<l)&&R!==-1;R--,O++)I+=256*S[R]>>>0,S[R]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");l=O,g++}for(var C=w-l;C!==w&&S[C]===0;)C++;for(var Y=c.repeat(b);C<w;++C)Y+=r.charAt(S[C]);return Y}function y(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var b=0;if(f[b]!==" "){for(var l=0,g=0;f[b]===c;)l++,b++;for(var E=(f.length-b)*p+1>>>0,w=new Uint8Array(E);f[b];){var S=e[f.charCodeAt(b)];if(S===255)return;for(var I=0,O=E-1;(S!==0||I<g)&&O!==-1;O--,I++)S+=a*w[O]>>>0,w[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");g=I,b++}if(f[b]!==" "){for(var R=E-g;R!==E&&w[R]===0;)R++;for(var C=new Uint8Array(l+(E-R)),Y=l;R!==E;)C[Y++]=w[R++];return C}}}function U(f){var b=y(f);if(b)return b;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:y,decode:U}}var Qe=Xe,Je=Qe,le=Je;var Et=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},xt=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return he(this,t)}},St=class{decoders;constructor(t){this.decoders=t}or(t){return he(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function he(r,t){return new St({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var At=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Et(t,e,n),this.decoder=new xt(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function G({name:r,prefix:t,encode:e,decode:n}){return new At(r,t,e,n)}function P({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=le(e,r);return G({prefix:t,name:r,encode:n,decode:s=>N(o(s))})}function He(r,t,e,n){let o={};for(let d=0;d<t.length;++d)o[t[d]]=d;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,p=0;for(let d=0;d<s;++d){let h=o[r[d]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|h,a+=e,a>=8&&(a-=8,i[p++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Ze(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function m({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return G({prefix:t,name:r,encode(o){return Ze(o,n,e)},decode(o){return He(o,n,e,r)}})}var Ye=P({prefix:"9",name:"base10",alphabet:"0123456789"});var It={};A(It,{base16:()=>tr,base16upper:()=>er});var tr=m({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),er=m({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Rt={};A(Rt,{base2:()=>rr});var rr=m({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Tt={};A(Tt,{base256emoji:()=>ar});var fe=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}"),nr=fe.reduce((r,t,e)=>(r[e]=t,r),[]),or=fe.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function sr(r){return r.reduce((t,e)=>(t+=nr[e],t),"")}function ir(r){let t=[];for(let e of r){let n=or[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var ar=G({prefix:"\u{1F680}",name:"base256emoji",encode:sr,decode:ir});var vt={};A(vt,{base32:()=>W,base32hex:()=>hr,base32hexpad:()=>dr,base32hexpadupper:()=>pr,base32hexupper:()=>fr,base32pad:()=>ur,base32padupper:()=>lr,base32upper:()=>cr,base32z:()=>mr});var W=m({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),cr=m({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ur=m({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lr=m({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hr=m({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fr=m({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dr=m({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pr=m({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),mr=m({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Lt={};A(Lt,{base36:()=>br,base36upper:()=>gr});var br=P({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),gr=P({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ct={};A(Ct,{base58btc:()=>v,base58flickr:()=>wr});var v=P({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),wr=P({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mt={};A(Mt,{base64:()=>yr,base64pad:()=>Er,base64url:()=>xr,base64urlpad:()=>Sr});var yr=m({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Er=m({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xr=m({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Sr=m({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Dt={};A(Dt,{base8:()=>Ar});var Ar=m({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Nt={};A(Nt,{identity:()=>_r});var _r=G({prefix:"\0",name:"identity",encode:r=>ce(r),decode:r=>ae(r)});var us=new TextEncoder,ls=new TextDecoder;var Ot={};A(Ot,{identity:()=>qr});var Tr=me,de=128,vr=127,Lr=~vr,Cr=Math.pow(2,31);function me(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Cr;)t[e++]=r&255|de,r/=128;for(;r&Lr;)t[e++]=r&255|de,r>>>=7;return t[e]=r|0,me.bytes=e-n+1,t}var Mr=Ut,Dr=128,pe=127;function Ut(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ut.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&pe)<<o:(i&pe)*Math.pow(2,o),o+=7}while(i>=Dr);return Ut.bytes=s-n,e}var Nr=Math.pow(2,7),Ur=Math.pow(2,14),Or=Math.pow(2,21),kr=Math.pow(2,28),Pr=Math.pow(2,35),Br=Math.pow(2,42),Fr=Math.pow(2,49),Vr=Math.pow(2,56),zr=Math.pow(2,63),Gr=function(r){return r<Nr?1:r<Ur?2:r<Or?3:r<kr?4:r<Pr?5:r<Br?6:r<Fr?7:r<Vr?8:r<zr?9:10},Wr={encode:Tr,decode:Mr,encodingLength:Gr},$r=Wr,q=$r;function X(r,t=0){return[q.decode(r,t),q.decode.bytes]}function $(r,t,e=0){return q.encode(r,t,e),t}function K(r){return q.encodingLength(r)}function F(r,t){let e=t.byteLength,n=K(r),o=n+K(e),s=new Uint8Array(o+e);return $(r,s,0),$(e,s,n),s.set(t,o),new j(r,e,t,s)}function be(r){let t=N(r),[e,n]=X(t),[o,s]=X(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new j(e,o,i,t)}function ge(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ie(r.bytes,e.bytes)}}var j=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var we=0,Kr="identity",ye=N;function jr(r){return F(we,ye(r))}var qr={code:we,name:Kr,encode:ye,digest:jr};var Bt={};A(Bt,{sha256:()=>Xr,sha512:()=>Qr});function Pt({name:r,code:t,encode:e}){return new kt(r,t,e)}var kt=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?F(this.code,e):e.then(n=>F(this.code,n))}else throw Error("Unknown type, must be binary type")}};function xe(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Xr=Pt({name:"sha2-256",code:18,encode:xe("SHA-256")}),Qr=Pt({name:"sha2-512",code:19,encode:xe("SHA-512")});function Se(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Hr(e,Ft(r),t??v.encoder);default:return Zr(e,Ft(r),t??W.encoder)}}var Ae=new WeakMap;function Ft(r){let t=Ae.get(r);if(t==null){let e=new Map;return Ae.set(r,e),e}return t}var st=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==J)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Yr)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=F(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&ge(t.multihash,n.multihash)}toString(t){return Se(this,t)}toJSON(){return{"/":Se(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??_e(n,o,s.bytes))}else if(e[tn]===!0){let{version:n,multihash:o,code:s}=e,i=be(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==J)throw new Error(`Version 0 CID must use dag-pb (code: ${J}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=_e(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,J,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=N(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new j(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,y]=X(t.subarray(e));return e+=y,h},o=n(),s=J;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),p=e+c,d=p-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:p}}static parse(t,e){let[n,o]=Jr(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ft(s).set(n,t),s}};function Jr(r,t){switch(r[0]){case"Q":{let e=t??v;return[v.prefix,e.decode(`${v.prefix}${r}`)]}case v.prefix:{let e=t??v;return[v.prefix,e.decode(r)]}case W.prefix:{let e=t??W;return[W.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Hr(r,t,e){let{prefix:n}=e;if(n!==v.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Zr(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var J=112,Yr=18;function _e(r,t,e){let n=K(r),o=n+K(t),s=new Uint8Array(o+e.byteLength);return $(r,s,0),$(t,s,n),s.set(e,o),s}var tn=Symbol.for("@ipld/js-cid/CID");var Vt={...Nt,...Rt,...Dt,..._t,...It,...vt,...Lt,...Ct,...Mt,...Tt},Ms={...Bt,...Ot};function Re(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ie=Re("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),zt=Re("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=_(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),en={utf8:Ie,"utf-8":Ie,hex:Vt.base16,latin1:zt,ascii:zt,binary:zt,...Vt},it=en;function Gt(r,t="utf8"){let e=it[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?M(globalThis.Buffer.from(r,"utf-8")):e.decoder.decode(`${e.prefix}${r}`)}function H(r,t="utf8"){let e=it[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):e.encoder.encode(r).substring(1)}var ve=Symbol.for("@achingbrain/uint8arraylist");function Te(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function at(r){return!!r?.[ve]}var L=class r{bufs;length;[ve]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(at(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(at(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Te(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Te(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(at(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return nt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:nt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let p=t>=a&&t<c,d=e>a&&e<=c;if(p&&d){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(p){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(d){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!at(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,p=n.byteLength-1,d;for(let h=e;h<=c;h+=d){d=0;for(let y=p;y>=0;y--){let U=this.get(h+y);if(n[y]!==U){d=Math.max(1,y-a[U]);break}}if(d===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=_(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=D(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=D(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=D(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=_(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=D(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=D(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=D(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=D(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=D(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!yt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var 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 Z=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Wt=Object.freeze({NEW_STREAM:u.NEW_STREAM,MESSAGE:u.MESSAGE_INITIATOR,CLOSE:u.CLOSE_INITIATOR,RESET:u.RESET_INITIATOR}),Le=Object.freeze({MESSAGE:u.MESSAGE_RECEIVER,CLOSE:u.CLOSE_RECEIVER,RESET:u.RESET_RECEIVER});var $t=1<<20,rn=4<<20,ct=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(t=$t,e=rn){this._buffer=new L,this._headerInfo=null,this._maxMessageSize=t,this._maxUnprocessedMessageQueueSize=e}write(t){if(t==null||t.length===0)return[];if(this._buffer.append(t),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw Object.assign(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});let e=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(p){if(p.code==="ERR_MSG_TOO_BIG")throw p;break}let{id:n,type:o,length:s,offset:i}=this._headerInfo;if(this._buffer.length-i<s)break;let c={id:n,type:o};(o===u.NEW_STREAM||o===u.MESSAGE_INITIATOR||o===u.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(i,i+s)),e.push(c),this._buffer.consume(i+s),this._headerInfo=null}return e}_decodeHeader(t){let{value:e,offset:n}=Me(t),{value:o,offset:s}=Me(t,n),i=e&7;if(Z[i]==null)throw new Error(`Invalid type received: ${i}`);if(o>this._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:e>>3,type:i,offset:n+s,length:o}}},nn=128,Ce=127;function Me(r,t=0){let e=0,n=0,o=t,s,i=r.length;do{if(o>=i||n>49)throw t=0,new RangeError("Could not decode varint");s=r.get(o++),e+=n<28?(s&Ce)<<n:(s&Ce)*Math.pow(2,n),n+=7}while(s>=nn);return t=o-t,{value:e,offset:t}}var on=Math.pow(2,7),sn=Math.pow(2,14),an=Math.pow(2,21),cn=Math.pow(2,28),un=Math.pow(2,35),ln=Math.pow(2,42),hn=Math.pow(2,49),x=128;function V(r){if(r<on)return 1;if(r<sn)return 2;if(r<an)return 3;if(r<cn)return 4;if(r<un)return 5;if(r<ln)return 6;if(r<hn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function fn(r,t,e=0){switch(V(r)){case 8:t[e++]=r&255|x,r/=128;case 7:t[e++]=r&255|x,r/=128;case 6:t[e++]=r&255|x,r/=128;case 5:t[e++]=r&255|x,r/=128;case 4:t[e++]=r&255|x,r>>>=7;case 3:t[e++]=r&255|x,r>>>=7;case 2:t[e++]=r&255|x,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function dn(r,t,e=0){switch(V(r)){case 8:t.set(e++,r&255|x),r/=128;case 7:t.set(e++,r&255|x),r/=128;case 6:t.set(e++,r&255|x),r/=128;case 5:t.set(e++,r&255|x),r/=128;case 4:t.set(e++,r&255|x),r>>>=7;case 3:t.set(e++,r&255|x),r>>>=7;case 2:t.set(e++,r&255|x),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function ut(r,t,e=0){return t==null&&(t=_(V(r))),t instanceof Uint8Array?fn(r,t,e):dn(r,t,e)}var Kt=10*1024,jt=class{_pool;_poolOffset;constructor(){this._pool=_(Kt),this._poolOffset=0}write(t,e){let n=this._pool,o=this._poolOffset;ut(t.id<<3|t.type,n,o),o+=V(t.id<<3|t.type),(t.type===u.NEW_STREAM||t.type===u.MESSAGE_INITIATOR||t.type===u.MESSAGE_RECEIVER)&&t.data!=null?(ut(t.data.length,n,o),o+=V(t.data.length)):(ut(0,n,o),o+=V(0));let s=n.subarray(this._poolOffset,o);Kt-o<100?(this._pool=_(Kt),this._poolOffset=0):this._poolOffset=o,e.append(s),(t.type===u.NEW_STREAM||t.type===u.MESSAGE_INITIATOR||t.type===u.MESSAGE_RECEIVER)&&t.data!=null&&e.append(t.data)}},mn=new jt;async function*De(r){for await(let t of r){let e=new L;mn.write(t,e),yield e}}var lt=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function ht(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new lt(e?.errorMessage,e?.errorCode));let n,o=new lt(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var bn="ERR_STREAM_RESET",gn="ERR_SINK_INVALID_STATE",wn=5e3;function qt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ft=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;constructor(t){this.sinkController=new AbortController,this.sinkEnd=B(),this.closed=B(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??wn,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=k({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new T(`writable end state is "${this.writeStatus}" not "ready"`,gn);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);qt(o)&&await o}let n=()=>{tt(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new L(o):o;let s=this.sendData(o,e);qt(s)&&await s}}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(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),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(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),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(t){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(t),this.closeWrite(t)]),await ht(this.closed.promise,t?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=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(t)),e==="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(t={}){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 ht(this.sink([]),t.signal)),this.writeStatus==="writing"&&await new Promise((e,n)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),ht(this.sinkEnd.promise,t.signal).then(e,n)})}),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();qt(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new T("stream reset",bn);this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){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(t))}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(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};var Xt=class extends ft{name;streamId;send;types;maxDataSize;constructor(t){super(t),this.types=t.direction==="outbound"?Wt:Le,this.send=t.send,this.name=t.name,this.streamId=t.streamId,this.maxDataSize=t.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:Wt.NEW_STREAM,data:new L(Gt(this.name))})}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:t.sublist(0,e)}),t.consume(e)}}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 Ne(r){let{id:t,name:e,send:n,onEnd:o,type:s="initiator",maxMsgSize:i=$t}=r;return new Xt({id:s==="initiator"?`i${t}`:`r${t}`,streamId:t,name:`${e??t}`,direction:s==="initiator"?"outbound":"inbound",maxDataSize:i,onEnd:o,send:n,log:r.logger.forComponent(`libp2p:mplex:stream:${s}:${t}`)})}var yn=1024,En=1024,xn=1024*1024*4,Sn=5,An=500;function Ue(r){let t={...r,type:`${Z[r.type]} (${r.type})`};return r.type===u.NEW_STREAM&&(t.data=H(r.data instanceof Uint8Array?r.data:r.data.subarray())),(r.type===u.MESSAGE_INITIATOR||r.type===u.MESSAGE_RECEIVER)&&(t.data=H(r.data instanceof Uint8Array?r.data:r.data.subarray(),"base16")),t}var dt=class{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(t,e){e=e??{},this.log=t.logger.forComponent("libp2p:mplex"),this.logger=t.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=e,this.closeTimeout=e.closeTimeout??An,this.sink=this._createSink(),this._source=k({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=ne(this._source,n=>De(n)),this.closeController=new AbortController,this.rateLimiter=new et({points:e.disconnectThreshold??Sn,duration:1})}get streams(){let t=[];for(let e of this._streams.initiators.values())t.push(e);for(let e of this._streams.receivers.values())t.push(e);return t}newStream(t){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");let e=this._streamId++;t=t==null?e.toString():t.toString();let n=this._streams.initiators;return this._newStream({id:e,name:t,type:"initiator",registry:n})}async close(t){if(this.closeController.signal.aborted)return;let e=t?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async n=>n.close({signal:e}))),this._source.end(),await this._source.onEmpty({signal:e}),this.closeController.abort()}catch(n){this.abort(n)}}abort(t){this.closeController.signal.aborted||(this.streams.forEach(e=>{e.abort(t)}),this.closeController.abort(t))}_newReceiverStream(t){let{id:e,name:n}=t,o=this._streams.receivers;return this._newStream({id:e,name:n,type:"receiver",registry:o})}_newStream(t){let{id:e,name:n,type:o,registry:s}=t;if(this.log("new %s stream %s",o,e),o==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??En))throw new T("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(s.has(e))throw new Error(`${o} stream ${e} already exists!`);let c=Ne({id:e,name:n,send:async p=>{this.log.enabled&&this.log.trace("%s stream %s send",o,e,Ue(p)),this._source.push(p)},type:o,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",o,e,c.protocol),s.delete(e),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(e,c),c}_createSink(){return async e=>{let n=()=>{tt(e,this.log)};this.closeController.signal.addEventListener("abort",n);try{let o=new ct(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let s of e)for(let i of o.write(s))await this._handleIncoming(i);this._source.end()}catch(o){this.log("error in sink",o),this._source.end(o)}finally{this.closeController.signal.removeEventListener("abort",n)}}}async _handleIncoming(t){let{id:e,type:n}=t;if(this.log.enabled&&this.log.trace("incoming message",Ue(t)),t.type===u.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??yn)){this.log("too many inbound streams open"),this._source.push({id:e,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:e,name:H(t.data instanceof Uint8Array?t.data:t.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let s=((n&1)===1?this._streams.initiators:this._streams.receivers).get(e);if(s==null){this.log("missing stream %s for message type %s",e,Z[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??xn;try{switch(n){case u.MESSAGE_INITIATOR:case u.MESSAGE_RECEIVER:if(s.sourceReadableLength()>i)throw this._source.push({id:t.id,type:n===u.MESSAGE_INITIATOR?u.RESET_RECEIVER:u.RESET_INITIATOR}),new T("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");s.sourcePush(t.data);break;case u.CLOSE_INITIATOR:case u.CLOSE_RECEIVER:s.remoteCloseWrite();break;case u.RESET_INITIATOR:case u.RESET_RECEIVER:s.reset();break;default:this.log("unknown message type %s",n)}}catch(a){this.log.error("error while processing message",a),s.abort(a)}}};var Qt=class{protocol="/mplex/6.7.0";_init;components;constructor(t,e={}){this.components=t,this._init=e}createStreamMuxer(t={}){return new dt(this.components,{...t,...this._init})}};function _n(r={}){return t=>new Qt(t,r)}return Fe(In);})();
2
+ "use strict";var Libp2PMplex=(()=>{var pe=Object.defineProperty;var Dt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var Nt=Object.prototype.hasOwnProperty;var _=(r,e)=>{for(var t in e)pe(r,t,{get:e[t],enumerable:!0})},Ot=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ut(e))!Nt.call(r,s)&&s!==t&&pe(r,s,{get:()=>e[s],enumerable:!(n=Dt(e,s))||n.enumerable});return r};var kt=r=>Ot(pe({},"__esModule",{value:!0}),r);var Sn={};_(Sn,{mplex:()=>xn});var T=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};function Qe(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 Je(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function ee(r,e){let t=Qe(r).return?.();Je(t)&&t.catch(n=>{e.error("could not cause iterator to return",n)})}var He=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Pt=new WeakMap;function Bt({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(He());let o,i,a,c=r??clearTimeout,p=()=>{c(o),a(He())},d=()=>{s&&s.removeEventListener("abort",p)},l=new Promise((y,N)=>{i=()=>{d(),y(n)},a=N,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",p,{once:!0}),Pt.set(l,()=>{c(o),o=null,i()}),l}}var Ft=Bt(),Ze=Ft;var te=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 me}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 T("Rate limit exceeded","ERR_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 Ze(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)}},me=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 B(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var re=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 re(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 re(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 be=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function k(r={}){return Vt(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 Vt(r,e){e=e??{};let t=e.onEnd,n=new z,s,o,i,a=B(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((u,g)=>{o=E=>{o=null,n.push(E);try{u(r(n))}catch(w){g(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=B()})}},p=u=>o!=null?o(u):(n.push(u),s),d=u=>(n=new z,o!=null?o({error:u}):(n.push({error:u}),s)),l=u=>{if(i)return s;if(e?.objectMode!==!0&&u?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return p({done:!1,value:u})},y=u=>i?s:(i=!0,u!=null?d(u):p({done:!0})),N=()=>(n=new z,y(),{done:!0}),f=u=>(y(u),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:N,throw:f,push:l,end:y,get readableLength(){return n.size},onEmpty:async u=>{let g=u?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,w;g!=null&&(E=new Promise((S,I)=>{w=()=>{I(new be)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,E])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},t==null)return s;let b=s;return s={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(u){return b.throw(u),t!=null&&(t(u),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(u){return b.end(u),t!=null&&(t(u),t=void 0),s},get readableLength(){return b.readableLength},onEmpty:u=>b.onEmpty(u)},s}function zt(r){return r[Symbol.asyncIterator]!=null}function Gt(...r){let e=[];for(let t of r)zt(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=k({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 Ye=Gt;function et(r,...e){if(r==null)throw new Error("Empty pipeline");if(ge(r)){let n=r;r=()=>n.source}else if(rt(r)||tt(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&ge(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++)ge(t[n])&&(t[n]=$t(t[n]));return Wt(...t)}var Wt=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},tt=r=>r?.[Symbol.asyncIterator]!=null,rt=r=>r?.[Symbol.iterator]!=null,ge=r=>r==null?!1:r.sink!=null&&r.source!=null,$t=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=k({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(tt(o))s=async function*(){yield*o,n.end()};else if(rt(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ye(n,s())}return r.source};function L(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function D(r=0){return globalThis.Buffer?.alloc!=null?L(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function A(r=0){return globalThis.Buffer?.allocUnsafe!=null?L(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function ne(r,e){if(globalThis.Buffer!=null)return L(globalThis.Buffer.concat(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 L(t)}function we(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var _e={};_(_e,{base10:()=>Jt});var Zn=new Uint8Array(0);function nt(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 U(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 st(r){return new TextEncoder().encode(r)}function ot(r){return new TextDecoder().decode(r)}function Kt(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),p=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function l(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var b=0,u=0,g=0,E=f.length;g!==E&&f[g]===0;)g++,b++;for(var w=(E-g)*d+1>>>0,S=new Uint8Array(w);g!==E;){for(var I=f[g],O=0,R=w-1;(I!==0||O<u)&&R!==-1;R--,O++)I+=256*S[R]>>>0,S[R]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");u=O,g++}for(var M=w-u;M!==w&&S[M]===0;)M++;for(var Y=c.repeat(b);M<w;++M)Y+=r.charAt(S[M]);return Y}function y(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var b=0;if(f[b]!==" "){for(var u=0,g=0;f[b]===c;)u++,b++;for(var E=(f.length-b)*p+1>>>0,w=new Uint8Array(E);f[b];){var S=t[f.charCodeAt(b)];if(S===255)return;for(var I=0,O=E-1;(S!==0||I<g)&&O!==-1;O--,I++)S+=a*w[O]>>>0,w[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");g=I,b++}if(f[b]!==" "){for(var R=E-g;R!==E&&w[R]===0;)R++;for(var M=new Uint8Array(u+(E-R)),Y=u;R!==E;)M[Y++]=w[R++];return M}}}function N(f){var b=y(f);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:y,decode:N}}var qt=Kt,jt=qt,at=jt;var ye=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")}},Ee=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ct(this,e)}},xe=class{decoders;constructor(e){this.decoders=e}or(e){return ct(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 ct(r,e){return new xe({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Se=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 ye(e,t,n),this.decoder=new Ee(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function G({name:r,prefix:e,encode:t,decode:n}){return new Se(r,e,t,n)}function P({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=at(t,r);return G({prefix:e,name:r,encode:n,decode:o=>U(s(o))})}function Xt(r,e,t,n){let s={};for(let d=0;d<e.length;++d)s[e[d]]=d;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),a=0,c=0,p=0;for(let d=0;d<o;++d){let l=s[r[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[p++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Qt(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 m({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return G({prefix:e,name:r,encode(s){return Qt(s,n,t)},decode(s){return Xt(s,n,t,r)}})}var Jt=P({prefix:"9",name:"base10",alphabet:"0123456789"});var Ae={};_(Ae,{base16:()=>Ht,base16upper:()=>Zt});var Ht=m({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Zt=m({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ie={};_(Ie,{base2:()=>Yt});var Yt=m({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Re={};_(Re,{base256emoji:()=>sr});var ht=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}"),er=ht.reduce((r,e,t)=>(r[t]=e,r),[]),tr=ht.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function rr(r){return r.reduce((e,t)=>(e+=er[t],e),"")}function nr(r){let e=[];for(let t of r){let n=tr[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var sr=G({prefix:"\u{1F680}",name:"base256emoji",encode:rr,decode:nr});var Te={};_(Te,{base32:()=>W,base32hex:()=>cr,base32hexpad:()=>ur,base32hexpadupper:()=>lr,base32hexupper:()=>hr,base32pad:()=>ir,base32padupper:()=>ar,base32upper:()=>or,base32z:()=>fr});var W=m({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),or=m({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ir=m({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ar=m({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),cr=m({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),hr=m({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ur=m({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lr=m({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fr=m({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ve={};_(ve,{base36:()=>dr,base36upper:()=>pr});var dr=P({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),pr=P({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ce={};_(Ce,{base58btc:()=>v,base58flickr:()=>mr});var v=P({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mr=P({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Me={};_(Me,{base64:()=>br,base64pad:()=>gr,base64url:()=>wr,base64urlpad:()=>yr});var br=m({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),gr=m({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),wr=m({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),yr=m({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Le={};_(Le,{base8:()=>Er});var Er=m({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var De={};_(De,{identity:()=>xr});var xr=G({prefix:"\0",name:"identity",encode:r=>ot(r),decode:r=>st(r)});var ps=new TextEncoder,ms=new TextDecoder;var Ne={};_(Ne,{identity:()=>$r});var Ar=ft,ut=128,Ir=127,Rr=~Ir,Tr=Math.pow(2,31);function ft(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Tr;)e[t++]=r&255|ut,r/=128;for(;r&Rr;)e[t++]=r&255|ut,r>>>=7;return e[t]=r|0,ft.bytes=t-n+1,e}var vr=Ue,Cr=128,lt=127;function Ue(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ue.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&lt)<<s:(i&lt)*Math.pow(2,s),s+=7}while(i>=Cr);return Ue.bytes=o-n,t}var Mr=Math.pow(2,7),Lr=Math.pow(2,14),Dr=Math.pow(2,21),Ur=Math.pow(2,28),Nr=Math.pow(2,35),Or=Math.pow(2,42),kr=Math.pow(2,49),Pr=Math.pow(2,56),Br=Math.pow(2,63),Fr=function(r){return r<Mr?1:r<Lr?2:r<Dr?3:r<Ur?4:r<Nr?5:r<Or?6:r<kr?7:r<Pr?8:r<Br?9:10},Vr={encode:Ar,decode:vr,encodingLength:Fr},zr=Vr,j=zr;function X(r,e=0){return[j.decode(r,e),j.decode.bytes]}function $(r,e,t=0){return j.encode(r,e,t),e}function K(r){return j.encodingLength(r)}function F(r,e){let t=e.byteLength,n=K(r),s=n+K(t),o=new Uint8Array(s+t);return $(r,o,0),$(t,o,n),o.set(e,s),new q(r,t,e,o)}function dt(r){let e=U(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 q(t,s,i,e)}function pt(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&nt(r.bytes,t.bytes)}}var q=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var mt=0,Gr="identity",bt=U;function Wr(r){return F(mt,bt(r))}var $r={code:mt,name:Gr,encode:bt,digest:Wr};var Pe={};_(Pe,{sha256:()=>Kr,sha512:()=>qr});function ke({name:r,code:e,encode:t}){return new Oe(r,e,t)}var Oe=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?F(this.code,t):t.then(n=>F(this.code,n))}else throw Error("Unknown type, must be binary type")}};function wt(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Kr=ke({name:"sha2-256",code:18,encode:wt("SHA-256")}),qr=ke({name:"sha2-512",code:19,encode:wt("SHA-512")});function yt(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Xr(t,Be(r),e??v.encoder);default:return Qr(t,Be(r),e??W.encoder)}}var Et=new WeakMap;function Be(r){let e=Et.get(r);if(e==null){let t=new Map;return Et.set(r,t),t}return e}var oe=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!==Jr)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=F(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&&pt(e.multihash,n.multihash)}toString(e){return yt(this,e)}toJSON(){return{"/":yt(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??xt(n,s,o.bytes))}else if(t[Hr]===!0){let{version:n,multihash:s,code:o}=t,i=dt(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=xt(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=U(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 q(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,y]=X(e.subarray(t));return t+=y,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(),p=t+c,d=p-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:d,size:p}}static parse(e,t){let[n,s]=jr(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 Be(o).set(n,e),o}};function jr(r,e){switch(r[0]){case"Q":{let t=e??v;return[v.prefix,t.decode(`${v.prefix}${r}`)]}case v.prefix:{let t=e??v;return[v.prefix,t.decode(r)]}case W.prefix:{let t=e??W;return[W.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Xr(r,e,t){let{prefix:n}=t;if(n!==v.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 Qr(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,Jr=18;function xt(r,e,t){let n=K(r),s=n+K(e),o=new Uint8Array(s+t.byteLength);return $(r,o,0),$(e,o,n),o.set(t,s),o}var Hr=Symbol.for("@ipld/js-cid/CID");var Fe={...De,...Ie,...Le,..._e,...Ae,...Te,...ve,...Ce,...Me,...Re},ks={...Pe,...Ne};function _t(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var St=_t("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ve=_t("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}),Zr={utf8:St,"utf-8":St,hex:Fe.base16,latin1:Ve,ascii:Ve,binary:Ve,...Fe},ie=Zr;function ze(r,e="utf8"){let t=ie[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?L(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}function H(r,e="utf8"){let t=ie[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var It=Symbol.for("@achingbrain/uint8arraylist");function At(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 ae(r){return!!r?.[It]}var C=class r{bufs;length;[It]=!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(ae(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(ae(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=At(this.bufs,e);return t.buf[t.index]}set(e,t){let n=At(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(ae(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 ne(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:ne(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 p=e>=a&&e<c,d=t>a&&t<=c;if(p&&d){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(p){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(d){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(!ae(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,p=n.byteLength-1,d;for(let l=t;l<=c;l+=d){d=0;for(let y=p;y>=0;y--){let N=this.get(l+y);if(n[y]!==N){d=Math.max(1,y-a[N]);break}}if(d===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=D(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=D(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=D(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=D(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=D(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=D(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=D(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=D(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(!we(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var h;(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"})(h||(h={}));var Z=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Ge=Object.freeze({NEW_STREAM:h.NEW_STREAM,MESSAGE:h.MESSAGE_INITIATOR,CLOSE:h.CLOSE_INITIATOR,RESET:h.RESET_INITIATOR}),Rt=Object.freeze({MESSAGE:h.MESSAGE_RECEIVER,CLOSE:h.CLOSE_RECEIVER,RESET:h.RESET_RECEIVER});var We=1<<20,Yr=4<<20,ce=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=We,t=Yr){this._buffer=new C,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 Object.assign(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(p){if(p.code==="ERR_MSG_TOO_BIG")throw p;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===h.NEW_STREAM||s===h.MESSAGE_INITIATOR||s===h.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}=vt(e),{value:s,offset:o}=vt(e,n),i=t&7;if(Z[i]==null)throw new Error(`Invalid type received: ${i}`);if(s>this._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:i,offset:n+o,length:s}}},en=128,Tt=127;function vt(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&Tt)<<n:(o&Tt)*Math.pow(2,n),n+=7}while(o>=en);return e=s-e,{value:t,offset:e}}var tn=Math.pow(2,7),rn=Math.pow(2,14),nn=Math.pow(2,21),sn=Math.pow(2,28),on=Math.pow(2,35),an=Math.pow(2,42),cn=Math.pow(2,49),x=128;function V(r){if(r<tn)return 1;if(r<rn)return 2;if(r<nn)return 3;if(r<sn)return 4;if(r<on)return 5;if(r<an)return 6;if(r<cn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function hn(r,e,t=0){switch(V(r)){case 8:e[t++]=r&255|x,r/=128;case 7:e[t++]=r&255|x,r/=128;case 6:e[t++]=r&255|x,r/=128;case 5:e[t++]=r&255|x,r/=128;case 4:e[t++]=r&255|x,r>>>=7;case 3:e[t++]=r&255|x,r>>>=7;case 2:e[t++]=r&255|x,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function un(r,e,t=0){switch(V(r)){case 8:e.set(t++,r&255|x),r/=128;case 7:e.set(t++,r&255|x),r/=128;case 6:e.set(t++,r&255|x),r/=128;case 5:e.set(t++,r&255|x),r/=128;case 4:e.set(t++,r&255|x),r>>>=7;case 3:e.set(t++,r&255|x),r>>>=7;case 2:e.set(t++,r&255|x),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function he(r,e,t=0){return e==null&&(e=A(V(r))),e instanceof Uint8Array?hn(r,e,t):un(r,e,t)}var $e=10*1024,Ke=class{_pool;_poolOffset;constructor(){this._pool=A($e),this._poolOffset=0}write(e,t){let n=this._pool,s=this._poolOffset;he(e.id<<3|e.type,n,s),s+=V(e.id<<3|e.type),(e.type===h.NEW_STREAM||e.type===h.MESSAGE_INITIATOR||e.type===h.MESSAGE_RECEIVER)&&e.data!=null?(he(e.data.length,n,s),s+=V(e.data.length)):(he(0,n,s),s+=V(0));let o=n.subarray(this._poolOffset,s);$e-s<100?(this._pool=A($e),this._poolOffset=0):this._poolOffset=s,t.append(o),(e.type===h.NEW_STREAM||e.type===h.MESSAGE_INITIATOR||e.type===h.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},fn=new Ke;async function*Ct(r){for await(let e of r){let t=new C;fn.write(e,t),yield t}}var ue=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function le(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new ue(t?.errorMessage,t?.errorCode));let n,s=new ue(t?.errorMessage,t?.errorCode);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 dn="ERR_STREAM_RESET",pn="ERR_SINK_INVALID_STATE",mn=5e3;function qe(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var fe=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;constructor(e){this.sinkController=new AbortController,this.sinkEnd=B(),this.closed=B(),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??mn,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=k({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 T(`writable end state is "${this.writeStatus}" not "ready"`,pn);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let s=this.sendNewStream(t);qe(s)&&await s}let n=()=>{ee(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 C(s):s;let o=this.sendData(s,t);qe(o)&&await o}}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.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(e),this.closeWrite(e)]),await le(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 le(this.sink([]),e.signal)),this.writeStatus==="writing"&&await new Promise((t,n)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),le(this.sinkEnd.promise,e.signal).then(t,n)})}),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();qe(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 T("stream reset",dn);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 je=class extends fe{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?Ge:Rt,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:Ge.NEW_STREAM,data:new C(ze(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 Mt(r){let{id:e,name:t,send:n,onEnd:s,type:o="initiator",maxMsgSize:i=We}=r;return new je({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 bn=1024,gn=1024,wn=1024*1024*4,yn=5,En=500;function Lt(r){let e={...r,type:`${Z[r.type]} (${r.type})`};return r.type===h.NEW_STREAM&&(e.data=H(r.data instanceof Uint8Array?r.data:r.data.subarray())),(r.type===h.MESSAGE_INITIATOR||r.type===h.MESSAGE_RECEIVER)&&(e.data=H(r.data instanceof Uint8Array?r.data:r.data.subarray(),"base16")),e}var de=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??En,this.sink=this._createSink(),this._source=k({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=et(this._source,n=>Ct(n)),this.closeController=new AbortController,this.rateLimiter=new te({points:t.disconnectThreshold??yn,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 Error("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??gn))throw new T("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(o.has(t))throw new Error(`${s} stream ${t} already exists!`);let c=Mt({id:t,name:n,send:async p=>{this.log.enabled&&this.log.trace("%s stream %s send",s,t,Lt(p)),this._source.push(p)},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=()=>{ee(t,this.log)};this.closeController.signal.addEventListener("abort",n);try{let s=new ce(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",Lt(e)),e.type===h.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??bn)){this.log("too many inbound streams open"),this._source.push({id:t,type:h.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:H(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,Z[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??wn;try{switch(n){case h.MESSAGE_INITIATOR:case h.MESSAGE_RECEIVER:if(o.sourceReadableLength()>i)throw this._source.push({id:e.id,type:n===h.MESSAGE_INITIATOR?h.RESET_RECEIVER:h.RESET_INITIATOR}),new T("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");o.sourcePush(e.data);break;case h.CLOSE_INITIATOR:case h.CLOSE_RECEIVER:o.remoteCloseWrite();break;case h.RESET_INITIATOR:case h.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 Xe=class{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}createStreamMuxer(e={}){return new de(this.components,{...e,...this._init})}};function xn(r={}){return e=>new Xe(e,r)}return kt(Sn);})();
3
3
  return Libp2PMplex}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/mplex",
3
- "version": "10.0.11-8bbd43628",
3
+ "version": "10.0.12-08f6f607d",
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",
@@ -61,8 +61,8 @@
61
61
  "test:electron-main": "aegir test -t electron-main"
62
62
  },
63
63
  "dependencies": {
64
- "@libp2p/interface": "1.1.1-8bbd43628",
65
- "@libp2p/utils": "5.2.1-8bbd43628",
64
+ "@libp2p/interface": "1.1.2-08f6f607d",
65
+ "@libp2p/utils": "5.2.2-08f6f607d",
66
66
  "it-pipe": "^3.0.1",
67
67
  "it-pushable": "^3.2.3",
68
68
  "it-stream-types": "^2.0.1",
@@ -71,8 +71,8 @@
71
71
  "uint8arrays": "^5.0.0"
72
72
  },
73
73
  "devDependencies": {
74
- "@libp2p/interface-compliance-tests": "5.1.2-8bbd43628",
75
- "@libp2p/logger": "4.0.4-8bbd43628",
74
+ "@libp2p/interface-compliance-tests": "5.1.3-08f6f607d",
75
+ "@libp2p/logger": "4.0.5-08f6f607d",
76
76
  "aegir": "^42.0.0",
77
77
  "benchmark": "^2.1.4",
78
78
  "cborg": "^4.0.3",
@@ -85,5 +85,6 @@
85
85
  "it-pair": "^2.0.6",
86
86
  "p-defer": "^4.0.0",
87
87
  "random-int": "^3.0.0"
88
- }
88
+ },
89
+ "sideEffects": false
89
90
  }