@libp2p/yamux 8.0.2 → 8.0.3-776cdedf6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +2 -2
- package/package.json +5 -5
- package/dist/typedoc-urls.json +0 -22
package/dist/index.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PYamux = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PYamux=(()=>{var le=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var ze=(r,e)=>{for(var t in e)le(r,t,{get:e[t],enumerable:!0})},qe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Fe(e))!_e.call(r,n)&&n!==t&&le(r,n,{get:()=>e[n],enumerable:!(s=ke(e,n))||s.enumerable});return r};var Ve=r=>qe(le({},"__esModule",{value:!0}),r);var tt={};ze(tt,{GoAwayCode:()=>w,yamux:()=>et});var y=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var S=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},V=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var A=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},k=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var G=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}};var Y=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},W=class extends Event{error;local;constructor(e,t,s){super("close",s),this.error=t,this.local=e}},j=class extends W{constructor(e,t){super(!0,e,t)}},$=class extends W{constructor(e,t){super(!1,e,t)}};function Ge(r){return typeof r?.handleEvent=="function"}function Ye(r){return r===!0||r===!1}function je(r){return Ye(r)?r:r?.capture??!1}function he(r){let e={capture:je(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function be(r,e){return he(r).capture===he(e).capture}var C=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,s){let n=he(s);if(n?.signal?.aborted===!0)return;let i=c=>{n.once&&this.removeEventListener(e,t,n),Ge(t)?t.handleEvent(c):t(c)},a=this.#e.get(e);if(a==null&&(a=[],this.#e.set(e,a)),a.some(c=>c.callback!==t?!1:be(c.options,n)))return;super.addEventListener(e,i,n);let u=()=>{this.removeEventListener(e,t,n)};n.signal?.addEventListener("abort",u),a.push({callback:t,wrapper:i,options:n,onAbort:u})}removeEventListener(e,t,s){let n=this.#e.get(e);if(n==null){super.removeEventListener(e,t??null,s);return}this.#e.set(e,n.filter(i=>i.callback===t&&be(i.options,s)?(super.removeEventListener(e,i.wrapper,s),i.options?.signal?.removeEventListener("abort",i.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ye=Symbol.for("@libp2p/service-capabilities");function L(r=0){return new Uint8Array(r)}function F(r=0){return new Uint8Array(r)}function $e(r){return r?.buffer instanceof ArrayBuffer}function xe(r){if($e(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function ce(r,e){e==null&&(e=r.reduce((n,i)=>n+i.length,0));let t=F(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return xe(t)}function Ee(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 Se=Symbol.for("@achingbrain/uint8arraylist");function ve(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let s of r){let n=t+s.byteLength;if(e<n)return{buf:s,index:e-t};t=n}throw new RangeError("index is out of bounds")}function K(r){return!!r?.[Se]}var E=class r{bufs;length;[Se]=!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 s of e)if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.push(s);else if(K(s)){t+=s.byteLength;for(let n of s.bufs)this.bufs.push(n)}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 s of e.reverse())if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.unshift(s);else if(K(s))t+=s.byteLength,this.bufs.unshift(...s.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=ve(this.bufs,e);return t.buf[t.index]}set(e,t){let s=ve(this.bufs,e);s.buf[s.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let s=0;s<e.length;s++)this.set(t+s,e[s]);else if(K(e))for(let s=0;s<e.length;s++)this.set(t+s,e.get(s));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:s,length:n}=this._subList(e,t);return ce(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:ce(s,n)}sublist(e,t){let{bufs:s,length:n}=this._subList(e,t),i=new r;return i.length=n,i.bufs=s,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let s=[],n=0;for(let i=0;i<this.bufs.length;i++){let a=this.bufs[i],o=n,u=o+a.byteLength;if(n=u,e>=u)continue;let c=e>=o&&e<u,d=t>o&&t<=u;if(c&&d){if(e===o&&t===u){s.push(a);break}let h=e-o;s.push(a.subarray(h,h+(t-e)));break}if(c){if(e===0){s.push(a);continue}s.push(a.subarray(e-o));continue}if(d){if(t===u){s.push(a);break}s.push(a.subarray(0,t-o));break}s.push(a)}return{bufs:s,length:t-e}}indexOf(e,t=0){if(!K(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let s=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 n=s.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,a=new Int32Array(i);for(let h=0;h<i;h++)a[h]=-1;for(let h=0;h<n;h++)a[s[h]]=h;let o=a,u=this.byteLength-s.byteLength,c=s.byteLength-1,d;for(let h=t;h<=u;h+=d){d=0;for(let g=c;g>=0;g--){let m=this.get(h+g);if(s[g]!==m){d=Math.max(1,g-o[m]);break}}if(d===0)return h}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 s=F(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt8(0,t),this.write(s,e)}getInt16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt16(0,t)}setInt16(e,t,s){let n=L(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,s),this.write(n,e)}getInt32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt32(0,t)}setInt32(e,t,s){let n=L(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,s),this.write(n,e)}getBigInt64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigInt64(0,t)}setBigInt64(e,t,s){let n=L(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,s),this.write(n,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 s=F(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint8(0,t),this.write(s,e)}getUint16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint16(0,t)}setUint16(e,t,s){let n=L(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,s),this.write(n,e)}getUint32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint32(0,t)}setUint32(e,t,s){let n=L(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,s),this.write(n,e)}getBigUint64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,t)}setBigUint64(e,t,s){let n=L(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,s),this.write(n,e)}getFloat32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat32(0,t)}setFloat32(e,t,s){let n=L(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,s),this.write(n,e)}getFloat64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat64(0,t)}setFloat64(e,t,s){let n=L(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,s),this.write(n,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(!Ee(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let s=new r;return s.bufs=e,t==null&&(t=e.reduce((n,i)=>n+i.byteLength,0)),s.length=t,s}};function H(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Q=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},N=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Q(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 Q(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 de=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Le(r={}){return Ke(t=>{let s=t.shift();if(s==null)return{done:!0};if(s.error!=null)throw s.error;return{done:s.done===!0,value:s.value}},r)}function Ke(r,e){e=e??{};let t=e.onEnd,s=new N,n,i,a,o=H(),u=async()=>{try{return s.isEmpty()?a?{done:!0}:await new Promise((f,T)=>{i=q=>{i=null,s.push(q);try{f(r(s))}catch(R){T(R)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=H()})}},c=f=>i!=null?i(f):(s.push(f),n),d=f=>(s=new N,i!=null?i({error:f}):(s.push({error:f}),n)),h=f=>{if(a)return n;if(e?.objectMode!==!0&&f?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:f})},g=f=>a?n:(a=!0,f!=null?d(f):c({done:!0})),m=()=>(s=new N,g(),{done:!0}),P=f=>(g(f),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:u,return:m,throw:P,push:h,end:g,get readableLength(){return s.size},onEmpty:async f=>{let T=f?.signal;if(T?.throwIfAborted(),s.isEmpty())return;let q,R;T!=null&&(q=new Promise((rt,Oe)=>{R=()=>{Oe(new de)},T.addEventListener("abort",R)}));try{await Promise.race([o.promise,q])}finally{R!=null&&T!=null&&T?.removeEventListener("abort",R)}}},t==null)return n;let D=n;return n={[Symbol.asyncIterator](){return this},next(){return D.next()},throw(f){return D.throw(f),t!=null&&(t(f),t=void 0),{done:!0}},return(){return D.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(f){return D.end(f),t!=null&&(t(f),t=void 0),n},get readableLength(){return D.readableLength},onEmpty:f=>D.onEmpty(f)},n}var fe=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Ie=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function me(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:i={setTimeout,clearTimeout},signal:a}=e,o,u,d=new Promise((h,g)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(a?.aborted){g(Ie(a));return}if(a&&(u=()=>{g(Ie(a))},a.addEventListener("abort",u,{once:!0})),r.then(h,g),t===Number.POSITIVE_INFINITY)return;let m=new fe;o=i.setTimeout.call(void 0,()=>{if(s){try{h(s())}catch(P){g(P)}return}typeof r.cancel=="function"&&r.cancel(),n===!1?h():n instanceof Error?g(n):(m.message=n??`Promise timed out after ${t} milliseconds`,g(m))},t)}).finally(()=>{d.clear(),u&&a&&a.removeEventListener("abort",u)});return d.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},d}var He=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Qe(r,e,t){let s,n=new Promise((i,a)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let o=[e].flat(),u=[],{addListener:c,removeListener:d}=He(r),h=async(...m)=>{let P=t.multiArgs?m:m[0];if(t.filter)try{if(!await t.filter(P))return}catch(D){s(),a(D);return}u.push(P),t.count===u.length&&(s(),i(u))},g=(...m)=>{s(),a(t.rejectionMultiArgs?m:m[0])};s=()=>{for(let m of o)d(m,h);for(let m of t.rejectionEvents)o.includes(m)||d(m,g)};for(let m of o)c(m,h);for(let m of t.rejectionEvents)o.includes(m)||c(m,g);t.signal&&t.signal.addEventListener("abort",()=>{g(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(u)});if(n.cancel=s,typeof t.timeout=="number"){let i=me(n,{milliseconds:t.timeout});return i.cancel=()=>{s(),i.clear()},i}return n}function pe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let s=Qe(r,e,t),n=s.then(i=>i[0]);return n.cancel=s.cancel,n}function De(r,e){let t,s=function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)};return s.start=()=>{},s.stop=()=>{clearTimeout(t)},s}var X=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},J=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Xe(r){return r.reason}function B(r,e,t){if(e==null||r==null)return r;let s=t?.translateError??Xe;if(e.aborted)return r.catch(()=>{}),Promise.reject(s(e));let n;return Promise.race([r,new Promise((i,a)=>{n=()=>{a(s(e))},e.addEventListener("abort",n)})]).finally(()=>{n!=null&&e.removeEventListener("abort",n)})}var Je=Math.pow(2,20)*4,Z=class extends C{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Je,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new E,this.writeBuffer=new E,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(n){this.log.error("processSendQueue threw - %e",n)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let s=n=>{this.onDrainPromise?.reject(n.error??new J)};this.addEventListener("close",s)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),B(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Le(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let s=i=>{e.end(i.error)};this.addEventListener("close",s);let n=()=>{e.end()};this.addEventListener("remoteCloseWrite",n);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",s),this.removeEventListener("remoteCloseWrite",n)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new A(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new j(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new $(new V))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new W))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,s=0;for(;this.writeBuffer.byteLength>0;){let n=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(n===0){e=!1;break}let i=this.writeBuffer.sublist(0,n),a=new E(i);this.writeBuffer.consume(i.byteLength);let o;try{o=this.sendData(i)}catch(u){throw this.writeBuffer.prepend(a),this.abort(u),u}if(e=o.canSendMore,s+=o.sentBytes,o.sentBytes!==a.byteLength&&(a.consume(o.sentBytes),this.writeBuffer.prepend(a)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",s,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Y(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new k(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new k(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};function Ae(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ee=class extends C{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let s=a=>{try{this.onData(a.data)}catch(o){this.abort(o),this.maConn.abort(o)}};this.maConn.addEventListener("message",s);let n=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(a=>{a.onMuxerDrain()})};this.maConn.addEventListener("drain",n);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await B(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new S;let t=this.onCreateStream({...this.streamOptions,...e});return Ae(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new X(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=s=>{let n=this.streams.findIndex(i=>i===e);n!==-1&&this.streams.splice(n,1),s.error!=null?s.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var te=class extends Z{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await pe(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await pe(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.maybeDispatchEnd(),this.log("closed readable end gracefully"))}};function Te(r){let e=new globalThis.AbortController;function t(){let i=r.filter(a=>a?.aborted===!0).map(a=>a?.reason).pop();e.abort(i);for(let a of r)a?.removeEventListener!=null&&a.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function s(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let n=e.signal;return n.clear=s,n}function Be(r,e,t){let s,n,i=!1;function a(){let c={signal:n.signal},d;t?.timeout!=null&&(d=Te([n.signal,AbortSignal.timeout(t.timeout)]),c.signal=d),i=!0,Promise.resolve().then(async()=>{await r(c)}).catch(()=>{}).finally(()=>{d!=null&&(d.aborted?d.clear():d.addEventListener("abort",()=>{d.clear()},{once:!0})),i=!1,!n.signal.aborted&&(s=setTimeout(a,e))})}let o=De(a,t?.debounce??100),u=!1;return{setInterval:c=>{e!==c&&(e=c,s!=null&&(clearTimeout(s),s=setTimeout(a,e)))},setTimeout:c=>{t??={},t.timeout=c},run:()=>{i||(clearTimeout(s),o())},start:()=>{u||(u=!0,n=new AbortController,n.signal,t?.runImmediately===!0?queueMicrotask(()=>{a()}):s=setTimeout(a,e))},stop:()=>{clearTimeout(s),n?.abort(),u=!1}}}var p;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(p||(p={}));var l;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(l||(l={}));var br=Object.values(l).filter(r=>typeof r!="string"),Pe=0,w;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(w||(w={}));var v=12;var I=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function Re(r){return r?.reason!==null}var x=class extends I{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,w.ProtocolError),this.name="InvalidFrameError"}},M=class extends I{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,w.ProtocolError),this.name="UnRequestedPingError"}},U=class extends I{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,w.ProtocolError),this.name="NotMatchingPingError"}};var re=class extends I{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,w.ProtocolError),this.name="StreamAlreadyExistsError"}},se=class extends I{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,w.ProtocolError),this.name="DecodeInvalidVersionError"}},ne=class extends I{static name="BothClientsError";constructor(e="Both clients"){super(e,w.ProtocolError),this.name="BothClientsError"}},O=class extends I{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,w.ProtocolError),this.name="ReceiveWindowExceededError"}};var Sr=new Set([x.name,M.name,U.name,re.name,se.name,ne.name,O.name]),_=256*1024,ie=16*1024*1024;var z={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:_,maxStreamWindowSize:ie,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function We(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new y("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new y("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new y("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new y("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<_)throw new y("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new y("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new y("MaxStreamWindowSize must be less than equal MAX_UINT32")}function Ne(r){return r.header.type===p.Data&&r.data!==null}var Ce=2**24;function Ze(r){if(r[0]!==Pe)throw new x("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*Ce+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*Ce+(r[9]<<16)+(r[10]<<8)+r[11]}}var ae=class{buffer;constructor(){this.buffer=new E}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=v;if(this.buffer.byteLength<v)return;let t=Ze(this.buffer.subarray(0,v));if(t.type===p.Data){if(e+=t.length,this.buffer.byteLength<e)return;let s=this.buffer.sublist(v,e);return this.buffer.consume(e),{header:t,data:s}}return this.buffer.consume(e),{header:t}}};function ge(r){let e=new Uint8Array(v);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var b;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(b||(b={}));var oe=class extends te{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??_;super({...e,maxMessageSize:t-v}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??ie,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let s=()=>{this.state=b.Finished};this.addEventListener("close",s)}sendData(e){let t=e.byteLength,s=0,n=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){n=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",s,t);break}let i=Math.min(this.sendWindowCapacity,e.byteLength),a=this.getSendFlags(),o=e.sublist(0,i);e.consume(i);let u=this.sendFrame({type:p.Data,flag:a,streamID:this.streamId,length:i},o);if(this.sendWindowCapacity-=i,s+=i,!u){n=u,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",s,t);break}}return{sentBytes:s,canSendMore:n}}sendReset(){this.sendFrame({type:p.WindowUpdate,flag:l.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|l.FIN;this.sendFrame({type:p.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=b.Paused}sendResume(){this.state=b.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-v,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!Ne(e))throw new x("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new O("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&l.ACK)===l.ACK&&this.state===b.SYNSent&&(this.state=b.Established),(e&l.FIN)===l.FIN&&this.onRemoteCloseWrite(),(e&l.RST)===l.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case b.Init:return this.state=b.SYNSent,l.SYN;case b.SYNReceived:return this.state=b.Established,l.ACK;default:return 0}}sendWindowUpdate(){if(this.state===b.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),s=this.getRTT();if(e===0&&s>-1&&t-this.epochStart<=s*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:p.WindowUpdate,flag:e,streamID:this.streamId,length:n})}};function Me(r){return{type:p[r.type],flags:[(r.flag&l.SYN)===l.SYN?"SYN":void 0,(r.flag&l.ACK)===l.ACK?"ACK":void 0,(r.flag&l.FIN)===l.FIN?"FIN":void 0,(r.flag&l.RST)===l.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var Ue="/yamux/1.0.0",ue=class{protocol=Ue;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/yamux";[ye]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new we(e,{...this._init})}},we=class extends ee{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:Ue,name:"yamux"}),this.client=e.direction==="outbound",We(t),this.enableKeepAlive=t.enableKeepAlive??z.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??z.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??z.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??z.maxOutboundStreams,this.decoder=new ae,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=Be(async s=>{try{await this.ping(s)}catch(n){this.log.error("ping error: %s",n)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new S("Muxer closed remotely");if(this.localGoAway!==void 0)throw new S("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new G("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,b.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new S("Muxer closed remotely");if(this.localGoAway!==void 0)throw new S("Muxer closed locally");if(this.activePing!=null)return B(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await B(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??w.NormalTermination;this.log.trace("muxer close reason=%s",w[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=w.InternalError;Re(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,s){if(this.streams.find(i=>i.streamId===e)!=null)throw new y("Stream already exists with that id");let n=new oe({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:s,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${s}:${e}`),getRTT:this.getRTT.bind(this)});return n.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),n}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:s,length:n}=e.header;if(this.log.trace("received frame %o",Me(e.header)),t===0)switch(s){case p.Ping:{this.handlePing(e.header);return}case p.GoAway:{this.handleGoAway(n);return}default:throw new x("Invalid frame type")}else switch(e.header.type){case p.Data:case p.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new x("Invalid frame type")}}handlePing(e){if(e.flag===l.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,l.ACK);else if(e.flag===l.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new x("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new M("ping not requested");if(this.activePing.id!==e)throw new U("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",w[e]??"unknown"),this.remoteGoAway=e,e===w.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:s,type:n}=e.header;(s&l.SYN)===l.SYN&&this.incomingStream(t);let i=this.streams.find(a=>a.streamId===t);if(i===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(n){case p.WindowUpdate:{i.handleWindowUpdate(e);return}case p.Data:{i.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new y("Both endpoints are clients");if(this.streams.find(s=>s.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:p.WindowUpdate,flag:l.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:p.WindowUpdate,flag:l.RST,streamID:e,length:0});return}let t=this._newStream(e,b.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let s;if(e.type===p.Data){if(t==null)throw new x("Invalid frame");s=new E(ge(e),t)}else s=ge(e);return this.log.trace("sending frame %o",Me(e)),this.send(s)}sendPing(e,t=l.SYN){t===l.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:p.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=w.NormalTermination){this.log("sending GoAway reason=%s",w[e]),this.localGoAway=e,this.sendFrame({type:p.GoAway,flag:0,streamID:0,length:e})}};function et(r={}){return()=>new ue(r)}return Ve(tt);})();
|
|
2
|
+
"use strict";var Libp2PYamux=(()=>{var le=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var ze=(r,e)=>{for(var t in e)le(r,t,{get:e[t],enumerable:!0})},qe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Fe(e))!_e.call(r,n)&&n!==t&&le(r,n,{get:()=>e[n],enumerable:!(s=ke(e,n))||s.enumerable});return r};var Ve=r=>qe(le({},"__esModule",{value:!0}),r);var tt={};ze(tt,{GoAwayCode:()=>w,yamux:()=>et});var y=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var S=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},V=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var A=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},k=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var G=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}};var Y=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},W=class extends Event{error;local;constructor(e,t,s){super("close",s),this.error=t,this.local=e}},$=class extends W{constructor(e,t){super(!0,e,t)}},j=class extends W{constructor(e,t){super(!1,e,t)}};function Ge(r){return typeof r?.handleEvent=="function"}function Ye(r){return r===!0||r===!1}function $e(r){return Ye(r)?r:r?.capture??!1}function he(r){let e={capture:$e(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function be(r,e){return he(r).capture===he(e).capture}var C=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,s){let n=he(s);if(n?.signal?.aborted===!0)return;let i=c=>{n.once&&this.removeEventListener(e,t,n),Ge(t)?t.handleEvent(c):t(c)},a=this.#e.get(e);if(a==null&&(a=[],this.#e.set(e,a)),a.some(c=>c.callback!==t?!1:be(c.options,n)))return;super.addEventListener(e,i,n);let u=()=>{this.removeEventListener(e,t,n)};n.signal?.addEventListener("abort",u),a.push({callback:t,wrapper:i,options:n,onAbort:u})}removeEventListener(e,t,s){let n=this.#e.get(e);if(n==null){super.removeEventListener(e,t??null,s);return}this.#e.set(e,n.filter(i=>i.callback===t&&be(i.options,s)?(super.removeEventListener(e,i.wrapper,s),i.options?.signal?.removeEventListener("abort",i.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ye=Symbol.for("@libp2p/service-capabilities");function L(r=0){return new Uint8Array(r)}function F(r=0){return new Uint8Array(r)}function je(r){return r?.buffer instanceof ArrayBuffer}function xe(r){if(je(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function ce(r,e){e==null&&(e=r.reduce((n,i)=>n+i.length,0));let t=F(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return xe(t)}function Ee(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 Se=Symbol.for("@achingbrain/uint8arraylist");function ve(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let s of r){let n=t+s.byteLength;if(e<n)return{buf:s,index:e-t};t=n}throw new RangeError("index is out of bounds")}function K(r){return!!r?.[Se]}var E=class r{bufs;length;[Se]=!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 s of e)if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.push(s);else if(K(s)){t+=s.byteLength;for(let n of s.bufs)this.bufs.push(n)}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 s of e.reverse())if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.unshift(s);else if(K(s))t+=s.byteLength,this.bufs.unshift(...s.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=ve(this.bufs,e);return t.buf[t.index]}set(e,t){let s=ve(this.bufs,e);s.buf[s.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let s=0;s<e.length;s++)this.set(t+s,e[s]);else if(K(e))for(let s=0;s<e.length;s++)this.set(t+s,e.get(s));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:s,length:n}=this._subList(e,t);return ce(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:ce(s,n)}sublist(e,t){let{bufs:s,length:n}=this._subList(e,t),i=new r;return i.length=n,i.bufs=s,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let s=[],n=0;for(let i=0;i<this.bufs.length;i++){let a=this.bufs[i],o=n,u=o+a.byteLength;if(n=u,e>=u)continue;let c=e>=o&&e<u,d=t>o&&t<=u;if(c&&d){if(e===o&&t===u){s.push(a);break}let h=e-o;s.push(a.subarray(h,h+(t-e)));break}if(c){if(e===0){s.push(a);continue}s.push(a.subarray(e-o));continue}if(d){if(t===u){s.push(a);break}s.push(a.subarray(0,t-o));break}s.push(a)}return{bufs:s,length:t-e}}indexOf(e,t=0){if(!K(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let s=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 n=s.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,a=new Int32Array(i);for(let h=0;h<i;h++)a[h]=-1;for(let h=0;h<n;h++)a[s[h]]=h;let o=a,u=this.byteLength-s.byteLength,c=s.byteLength-1,d;for(let h=t;h<=u;h+=d){d=0;for(let g=c;g>=0;g--){let m=this.get(h+g);if(s[g]!==m){d=Math.max(1,g-o[m]);break}}if(d===0)return h}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 s=F(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt8(0,t),this.write(s,e)}getInt16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt16(0,t)}setInt16(e,t,s){let n=L(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,s),this.write(n,e)}getInt32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt32(0,t)}setInt32(e,t,s){let n=L(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,s),this.write(n,e)}getBigInt64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigInt64(0,t)}setBigInt64(e,t,s){let n=L(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,s),this.write(n,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 s=F(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint8(0,t),this.write(s,e)}getUint16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint16(0,t)}setUint16(e,t,s){let n=L(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,s),this.write(n,e)}getUint32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint32(0,t)}setUint32(e,t,s){let n=L(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,s),this.write(n,e)}getBigUint64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,t)}setBigUint64(e,t,s){let n=L(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,s),this.write(n,e)}getFloat32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat32(0,t)}setFloat32(e,t,s){let n=L(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,s),this.write(n,e)}getFloat64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat64(0,t)}setFloat64(e,t,s){let n=L(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,s),this.write(n,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(!Ee(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let s=new r;return s.bufs=e,t==null&&(t=e.reduce((n,i)=>n+i.byteLength,0)),s.length=t,s}};function H(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Q=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},N=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Q(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 Q(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 de=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Le(r={}){return Ke(t=>{let s=t.shift();if(s==null)return{done:!0};if(s.error!=null)throw s.error;return{done:s.done===!0,value:s.value}},r)}function Ke(r,e){e=e??{};let t=e.onEnd,s=new N,n,i,a,o=H(),u=async()=>{try{return s.isEmpty()?a?{done:!0}:await new Promise((f,T)=>{i=q=>{i=null,s.push(q);try{f(r(s))}catch(R){T(R)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=H()})}},c=f=>i!=null?i(f):(s.push(f),n),d=f=>(s=new N,i!=null?i({error:f}):(s.push({error:f}),n)),h=f=>{if(a)return n;if(e?.objectMode!==!0&&f?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:f})},g=f=>a?n:(a=!0,f!=null?d(f):c({done:!0})),m=()=>(s=new N,g(),{done:!0}),P=f=>(g(f),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:u,return:m,throw:P,push:h,end:g,get readableLength(){return s.size},onEmpty:async f=>{let T=f?.signal;if(T?.throwIfAborted(),s.isEmpty())return;let q,R;T!=null&&(q=new Promise((rt,Oe)=>{R=()=>{Oe(new de)},T.addEventListener("abort",R)}));try{await Promise.race([o.promise,q])}finally{R!=null&&T!=null&&T?.removeEventListener("abort",R)}}},t==null)return n;let D=n;return n={[Symbol.asyncIterator](){return this},next(){return D.next()},throw(f){return D.throw(f),t!=null&&(t(f),t=void 0),{done:!0}},return(){return D.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(f){return D.end(f),t!=null&&(t(f),t=void 0),n},get readableLength(){return D.readableLength},onEmpty:f=>D.onEmpty(f)},n}var fe=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Ie=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function me(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:i={setTimeout,clearTimeout},signal:a}=e,o,u,d=new Promise((h,g)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(a?.aborted){g(Ie(a)),r.then(h,g);return}if(a&&(u=()=>{g(Ie(a))},a.addEventListener("abort",u,{once:!0})),r.then(h,g),t===Number.POSITIVE_INFINITY)return;let m=new fe;o=i.setTimeout.call(void 0,()=>{if(s){try{h(s())}catch(P){g(P)}return}typeof r.cancel=="function"&&r.cancel(),n===!1?h():n instanceof Error?g(n):(m.message=n??`Promise timed out after ${t} milliseconds`,g(m))},t)}).finally(()=>{d.clear(),u&&a&&a.removeEventListener("abort",u)});return d.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},d}var He=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Qe(r,e,t){let s,n=new Promise((i,a)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let o=[e].flat(),u=[],{addListener:c,removeListener:d}=He(r),h=async(...m)=>{let P=t.multiArgs?m:m[0];if(t.filter)try{if(!await t.filter(P))return}catch(D){s(),a(D);return}u.push(P),t.count===u.length&&(s(),i(u))},g=(...m)=>{s(),a(t.rejectionMultiArgs?m:m[0])};s=()=>{for(let m of o)d(m,h);for(let m of t.rejectionEvents)o.includes(m)||d(m,g)};for(let m of o)c(m,h);for(let m of t.rejectionEvents)o.includes(m)||c(m,g);t.signal&&t.signal.addEventListener("abort",()=>{g(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(u)});if(n.cancel=s,typeof t.timeout=="number"){let i=me(n,{milliseconds:t.timeout});return i.cancel=()=>{s(),i.clear()},i}return n}function pe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let s=Qe(r,e,t),n=s.then(i=>i[0]);return n.cancel=s.cancel,n}function De(r,e){let t,s=function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)};return s.start=()=>{},s.stop=()=>{clearTimeout(t)},s}var X=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},J=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Xe(r){return r.reason}function B(r,e,t){if(e==null||r==null)return r;let s=t?.translateError??Xe;if(e.aborted)return r.catch(()=>{}),Promise.reject(s(e));let n;return Promise.race([r,new Promise((i,a)=>{n=()=>{a(s(e))},e.addEventListener("abort",n)})]).finally(()=>{n!=null&&e.removeEventListener("abort",n)})}var Je=Math.pow(2,20)*4,Z=class extends C{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Je,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new E,this.writeBuffer=new E,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(n){this.log.error("processSendQueue threw - %e",n)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let s=n=>{this.onDrainPromise?.reject(n.error??new J)};this.addEventListener("close",s)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),B(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Le(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let s=i=>{e.end(i.error)};this.addEventListener("close",s);let n=()=>{e.end()};this.addEventListener("remoteCloseWrite",n);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",s),this.removeEventListener("remoteCloseWrite",n)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new A(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new $(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new j(new V))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new W))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,s=0;for(;this.writeBuffer.byteLength>0;){let n=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(n===0){e=!1;break}let i=this.writeBuffer.sublist(0,n),a=new E(i);this.writeBuffer.consume(i.byteLength);let o;try{o=this.sendData(i)}catch(u){throw this.writeBuffer.prepend(a),this.abort(u),u}if(e=o.canSendMore,s+=o.sentBytes,o.sentBytes!==a.byteLength&&(a.consume(o.sentBytes),this.writeBuffer.prepend(a)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",s,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Y(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new k(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new k(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};function Ae(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ee=class extends C{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let s=a=>{try{this.onData(a.data)}catch(o){this.abort(o),this.maConn.abort(o)}};this.maConn.addEventListener("message",s);let n=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(a=>{a.onMuxerDrain()})};this.maConn.addEventListener("drain",n);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await B(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new S;let t=this.onCreateStream({...this.streamOptions,...e});return Ae(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new X(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=s=>{let n=this.streams.findIndex(i=>i===e);n!==-1&&this.streams.splice(n,1),s.error!=null?s.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var te=class extends Z{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await pe(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await pe(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.maybeDispatchEnd(),this.log("closed readable end gracefully"))}};function Te(r){let e=new globalThis.AbortController;function t(){let i=r.filter(a=>a?.aborted===!0).map(a=>a?.reason).pop();e.abort(i);for(let a of r)a?.removeEventListener!=null&&a.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function s(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let n=e.signal;return n.clear=s,n}function Be(r,e,t){let s,n,i=!1;function a(){let c={signal:n.signal},d;t?.timeout!=null&&(d=Te([n.signal,AbortSignal.timeout(t.timeout)]),c.signal=d),i=!0,Promise.resolve().then(async()=>{await r(c)}).catch(()=>{}).finally(()=>{d!=null&&(d.aborted?d.clear():d.addEventListener("abort",()=>{d.clear()},{once:!0})),i=!1,!n.signal.aborted&&(s=setTimeout(a,e))})}let o=De(a,t?.debounce??100),u=!1;return{setInterval:c=>{e!==c&&(e=c,s!=null&&(clearTimeout(s),s=setTimeout(a,e)))},setTimeout:c=>{t??={},t.timeout=c},run:()=>{i||(clearTimeout(s),o())},start:()=>{u||(u=!0,n=new AbortController,n.signal,t?.runImmediately===!0?queueMicrotask(()=>{a()}):s=setTimeout(a,e))},stop:()=>{clearTimeout(s),n?.abort(),u=!1}}}var p;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(p||(p={}));var l;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(l||(l={}));var br=Object.values(l).filter(r=>typeof r!="string"),Pe=0,w;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(w||(w={}));var v=12;var I=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function Re(r){return r?.reason!==null}var x=class extends I{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,w.ProtocolError),this.name="InvalidFrameError"}},M=class extends I{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,w.ProtocolError),this.name="UnRequestedPingError"}},U=class extends I{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,w.ProtocolError),this.name="NotMatchingPingError"}};var re=class extends I{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,w.ProtocolError),this.name="StreamAlreadyExistsError"}},se=class extends I{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,w.ProtocolError),this.name="DecodeInvalidVersionError"}},ne=class extends I{static name="BothClientsError";constructor(e="Both clients"){super(e,w.ProtocolError),this.name="BothClientsError"}},O=class extends I{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,w.ProtocolError),this.name="ReceiveWindowExceededError"}};var Sr=new Set([x.name,M.name,U.name,re.name,se.name,ne.name,O.name]),_=256*1024,ie=16*1024*1024;var z={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:_,maxStreamWindowSize:ie,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function We(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new y("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new y("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new y("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new y("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<_)throw new y("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new y("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new y("MaxStreamWindowSize must be less than equal MAX_UINT32")}function Ne(r){return r.header.type===p.Data&&r.data!==null}var Ce=2**24;function Ze(r){if(r[0]!==Pe)throw new x("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*Ce+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*Ce+(r[9]<<16)+(r[10]<<8)+r[11]}}var ae=class{buffer;constructor(){this.buffer=new E}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=v;if(this.buffer.byteLength<v)return;let t=Ze(this.buffer.subarray(0,v));if(t.type===p.Data){if(e+=t.length,this.buffer.byteLength<e)return;let s=this.buffer.sublist(v,e);return this.buffer.consume(e),{header:t,data:s}}return this.buffer.consume(e),{header:t}}};function ge(r){let e=new Uint8Array(v);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var b;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(b||(b={}));var oe=class extends te{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??_;super({...e,maxMessageSize:t-v}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??ie,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let s=()=>{this.state=b.Finished};this.addEventListener("close",s)}sendData(e){let t=e.byteLength,s=0,n=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){n=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",s,t);break}let i=Math.min(this.sendWindowCapacity,e.byteLength),a=this.getSendFlags(),o=e.sublist(0,i);e.consume(i);let u=this.sendFrame({type:p.Data,flag:a,streamID:this.streamId,length:i},o);if(this.sendWindowCapacity-=i,s+=i,!u){n=u,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",s,t);break}}return{sentBytes:s,canSendMore:n}}sendReset(){this.sendFrame({type:p.WindowUpdate,flag:l.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|l.FIN;this.sendFrame({type:p.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=b.Paused}sendResume(){this.state=b.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-v,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!Ne(e))throw new x("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new O("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&l.ACK)===l.ACK&&this.state===b.SYNSent&&(this.state=b.Established),(e&l.FIN)===l.FIN&&this.onRemoteCloseWrite(),(e&l.RST)===l.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case b.Init:return this.state=b.SYNSent,l.SYN;case b.SYNReceived:return this.state=b.Established,l.ACK;default:return 0}}sendWindowUpdate(){if(this.state===b.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),s=this.getRTT();if(e===0&&s>-1&&t-this.epochStart<=s*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:p.WindowUpdate,flag:e,streamID:this.streamId,length:n})}};function Me(r){return{type:p[r.type],flags:[(r.flag&l.SYN)===l.SYN?"SYN":void 0,(r.flag&l.ACK)===l.ACK?"ACK":void 0,(r.flag&l.FIN)===l.FIN?"FIN":void 0,(r.flag&l.RST)===l.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var Ue="/yamux/1.0.0",ue=class{protocol=Ue;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/yamux";[ye]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new we(e,{...this._init})}},we=class extends ee{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:Ue,name:"yamux"}),this.client=e.direction==="outbound",We(t),this.enableKeepAlive=t.enableKeepAlive??z.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??z.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??z.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??z.maxOutboundStreams,this.decoder=new ae,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=Be(async s=>{try{await this.ping(s)}catch(n){this.log.error("ping error: %s",n)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new S("Muxer closed remotely");if(this.localGoAway!==void 0)throw new S("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new G("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,b.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new S("Muxer closed remotely");if(this.localGoAway!==void 0)throw new S("Muxer closed locally");if(this.activePing!=null)return B(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await B(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??w.NormalTermination;this.log.trace("muxer close reason=%s",w[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=w.InternalError;Re(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,s){if(this.streams.find(i=>i.streamId===e)!=null)throw new y("Stream already exists with that id");let n=new oe({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:s,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${s}:${e}`),getRTT:this.getRTT.bind(this)});return n.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),n}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:s,length:n}=e.header;if(this.log.trace("received frame %o",Me(e.header)),t===0)switch(s){case p.Ping:{this.handlePing(e.header);return}case p.GoAway:{this.handleGoAway(n);return}default:throw new x("Invalid frame type")}else switch(e.header.type){case p.Data:case p.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new x("Invalid frame type")}}handlePing(e){if(e.flag===l.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,l.ACK);else if(e.flag===l.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new x("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new M("ping not requested");if(this.activePing.id!==e)throw new U("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",w[e]??"unknown"),this.remoteGoAway=e,e===w.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:s,type:n}=e.header;(s&l.SYN)===l.SYN&&this.incomingStream(t);let i=this.streams.find(a=>a.streamId===t);if(i===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(n){case p.WindowUpdate:{i.handleWindowUpdate(e);return}case p.Data:{i.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new y("Both endpoints are clients");if(this.streams.find(s=>s.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:p.WindowUpdate,flag:l.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:p.WindowUpdate,flag:l.RST,streamID:e,length:0});return}let t=this._newStream(e,b.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let s;if(e.type===p.Data){if(t==null)throw new x("Invalid frame");s=new E(ge(e),t)}else s=ge(e);return this.log.trace("sending frame %o",Me(e)),this.send(s)}sendPing(e,t=l.SYN){t===l.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:p.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=w.NormalTermination){this.log("sending GoAway reason=%s",w[e]),this.localGoAway=e,this.sendFrame({type:p.GoAway,flag:0,streamID:0,length:e})}};function et(r={}){return()=>new ue(r)}return Ve(tt);})();
|
|
3
3
|
return Libp2PYamux}));
|
|
4
4
|
//# sourceMappingURL=index.min.js.map
|