@libp2p/yamux 8.0.1 → 8.0.2-5cb617ae2

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../../interface/src/errors.ts", "../../interface/src/events.ts", "../../../node_modules/main-event/src/index.ts", "../../interface/src/index.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arraylist/src/index.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/it-pushable/src/fifo.ts", "../../../node_modules/it-pushable/src/index.ts", "../../../node_modules/p-timeout/index.js", "../../../node_modules/p-event/index.js", "../../utils/src/debounce.ts", "../../utils/src/errors.ts", "../../../node_modules/race-signal/src/index.ts", "../../utils/src/abstract-message-stream.ts", "../../utils/src/is-promise.ts", "../../utils/src/abstract-stream-muxer.ts", "../../utils/src/abstract-stream.ts", "../../../node_modules/any-signal/src/index.ts", "../../utils/src/repeating-task.ts", "../src/frame.ts", "../src/errors.ts", "../src/constants.ts", "../src/config.ts", "../src/decode.ts", "../src/encode.ts", "../src/stream.ts", "../src/muxer.ts"],
4
- "sourcesContent": ["/**\n * @packageDocumentation\n *\n * This module is a JavaScript implementation of [Yamux from Hashicorp](https://github.com/hashicorp/yamux/blob/master/spec.md) designed to be used with [js-libp2p](https://github.com/libp2p/js-libp2p).\n *\n * @example Configure libp2p with Yamux\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { yamux } from '@libp2p/yamux'\n *\n * const node = await createLibp2p({\n * // ... other options\n * streamMuxers: [\n * yamux()\n * ]\n * })\n * ```\n *\n * @example Using the low-level API\n *\n * ```js\n * import { yamux } from '@libp2p/yamux'\n * import { pipe } from 'it-pipe'\n * import { duplexPair } from 'it-pair/duplex'\n * import all from 'it-all'\n *\n * // Connect two yamux muxers to demo basic stream multiplexing functionality\n *\n * const clientMuxer = yamux({\n * client: true,\n * onIncomingStream: stream => {\n * // echo data on incoming streams\n * pipe(stream, stream)\n * },\n * onStreamEnd: stream => {\n * // do nothing\n * }\n * })()\n *\n * const serverMuxer = yamux({\n * client: false,\n * onIncomingStream: stream => {\n * // echo data on incoming streams\n * pipe(stream, stream)\n * },\n * onStreamEnd: stream => {\n * // do nothing\n * }\n * })()\n *\n * // `p` is our \"connections\", what we use to connect the two sides\n * // In a real application, a connection is usually to a remote computer\n * const p = duplexPair()\n *\n * // connect the muxers together\n * pipe(p[0], clientMuxer, p[0])\n * pipe(p[1], serverMuxer, p[1])\n *\n * // now either side can open streams\n * const stream0 = clientMuxer.newStream()\n * const stream1 = serverMuxer.newStream()\n *\n * // Send some data to the other side\n * const encoder = new TextEncoder()\n * const data = [encoder.encode('hello'), encoder.encode('world')]\n * pipe(data, stream0)\n *\n * // Receive data back\n * const result = await pipe(stream0, all)\n *\n * // close a stream\n * stream1.close()\n *\n * // close the muxer\n * clientMuxer.close()\n * ```\n */\n\nimport { Yamux } from './muxer.js'\nimport type { YamuxMuxer, YamuxMuxerInit } from './muxer.js'\nimport type { StreamMuxerFactory } from '@libp2p/interface'\n\nexport { GoAwayCode } from './frame.js'\nexport type { FrameHeader, FrameType } from './frame.js'\nexport type { YamuxMuxerInit }\n\nexport function yamux (init: YamuxMuxerInit = {}): () => StreamMuxerFactory<YamuxMuxer> {\n return () => new Yamux(init)\n}\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError'\n\n constructor (message = 'The stream has been aborted') {\n super(message)\n this.name = 'StreamAbortedError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError'\n\n constructor (message = 'The stream buffer was full') {\n super(message)\n this.name = 'StreamBufferError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\n\n/**\n * A custom implementation of MessageEvent as the Undici version does too much\n * validation in it's constructor so is very slow.\n */\nexport class StreamMessageEvent extends Event {\n public data: Uint8Array | Uint8ArrayList\n\n constructor (data: Uint8Array | Uint8ArrayList, eventInitDict?: EventInit) {\n super('message', eventInitDict)\n\n this.data = data\n }\n}\n\n/**\n * An event dispatched when the stream is closed. The `error` property can be\n * inspected to discover if the closing was graceful or not, and the `remote`\n * property shows which end of the stream initiated the closure\n */\nexport class StreamCloseEvent extends Event {\n public error?: Error\n public local?: boolean\n\n constructor (local?: boolean, error?: Error, eventInitDict?: EventInit) {\n super('close', eventInitDict)\n\n this.error = error\n this.local = local\n }\n}\n\nexport class StreamAbortEvent extends StreamCloseEvent {\n constructor (error: Error, eventInitDict?: EventInit) {\n super(true, error, eventInitDict)\n }\n}\n\nexport class StreamResetEvent extends StreamCloseEvent {\n constructor (error: Error, eventInitDict?: EventInit) {\n super(false, error, eventInitDict)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Adds types to the EventTarget class.\n *\n * Hopefully this won't be necessary\n * forever:\n *\n * - https://github.com/microsoft/TypeScript/issues/28357\n * - https://github.com/microsoft/TypeScript/issues/43477\n * - https://github.com/microsoft/TypeScript/issues/299\n * - https://www.npmjs.com/package/typed-events\n * - https://www.npmjs.com/package/typed-event-emitter\n * - https://www.npmjs.com/package/typed-event-target\n * - etc\n *\n * In addition to types, a `safeDispatchEvent` method is available which\n * prevents dispatching events that aren't in the event map, and a\n * `listenerCount` method which reports the number of listeners that are\n * currently registered for a given event.\n *\n * @example\n *\n * ```ts\n * import { TypedEventEmitter } from 'main-event'\n * import type { TypedEventTarget } from 'main-event'\n *\n * interface EventTypes {\n * 'test': CustomEvent<string>\n * }\n *\n * const target = new TypedEventEmitter<EventTypes>()\n *\n * // it's a regular EventTarget\n * console.info(target instanceof EventTarget) // true\n *\n * // register listeners normally\n * target.addEventListener('test', (evt) => {\n * // evt is CustomEvent<string>\n * })\n *\n * // @ts-expect-error 'derp' is not in the event map\n * target.addEventListener('derp', () => {})\n *\n * // use normal dispatchEvent method\n * target.dispatchEvent(new CustomEvent('test', {\n * detail: 'hello'\n * }))\n *\n * // use type safe dispatch method\n * target.safeDispatchEvent('test', {\n * detail: 'world'\n * })\n *\n * // report listener count\n * console.info(target.listenerCount('test')) // 0\n *\n * // event emitters can be used purely as interfaces too\n * function acceptTarget (target: TypedEventTarget<EventTypes>) {\n * // ...\n * }\n * ```\n */\n\nimport { setMaxListeners } from './events.js'\n\nexport interface EventCallback<EventType> { (evt: EventType): void }\nexport interface EventObject<EventType> { handleEvent: EventCallback<EventType> }\nexport type EventHandler<EventType> = EventCallback<EventType> | EventObject<EventType>\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n *\n */\nexport interface TypedEventTarget <EventMap extends Record<string, any>> extends EventTarget {\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n\n listenerCount (type: string): number\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail?: CustomEventInit<Detail>): boolean\n}\n\n/**\n * An implementation of a typed event target\n */\nexport class TypedEventEmitter<EventMap extends Record<string, any>> extends EventTarget implements TypedEventTarget<EventMap> {\n readonly #listeners = new Map<any, Listener[]>()\n\n constructor () {\n super()\n\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this)\n }\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail: CustomEventInit<Detail> = {}): boolean {\n return this.dispatchEvent(new CustomEvent<Detail>(type as string, detail))\n }\n}\n\nexport { setMaxListeners }\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions } from './connection.js'\nimport type { ContentRouting } from './content-routing.js'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { Metrics } from './metrics.js'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { PeerRouting } from './peer-routing.js'\nimport type { Address, Peer, PeerStore } from './peer-store.js'\nimport type { Startable } from './startable.js'\nimport type { StreamHandler, StreamHandlerOptions, StreamMiddleware } from './stream-handler.js'\nimport type { Stream } from './stream.js'\nimport type { Topology } from './topology.js'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.js'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from '@libp2p/logger'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport interface MultiaddrResolveOptions extends AbortOptions, LoggerOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n}\n\n/**\n * `MultiaddrResolver`s perform resolution of multiaddr components that require\n * translation by external systems (for example DNSADDR to TXT records).\n */\nexport interface MultiaddrResolver {\n /**\n * Returns true if this resolver can resolve components of this multiaddr\n */\n canResolve (address: Multiaddr): boolean\n\n /**\n * Returns one or more multiaddrs with components resolved to other values\n */\n resolve (address: Multiaddr, options: MultiaddrResolveOptions): Promise<Multiaddr[]>\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n start: CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n stop: CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends NewStreamOptions {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: PeerId | Multiaddr | Multiaddr[], options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string, options?: AbortOptions): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology, options?: AbortOptions): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Registers one or more middleware implementations that will be invoked for\n * incoming and outgoing protocol streams that match the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {\n * // do something with stream and/or connection\n * next(stream, connection)\n * })\n * ```\n */\n use (protocol: string, middleware: StreamMiddleware | StreamMiddleware[]): void\n\n /**\n * Deregisters all middleware for the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unuse('/my/protocol/1.0.0')\n * // any previously registered middleware will no longer be invoked\n * ```\n */\n unuse (protocol: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.js'\nexport * from './connection-encrypter.js'\nexport * from './connection-gater.js'\nexport * from './connection-protector.js'\nexport * from './content-routing.js'\nexport * from './errors.js'\nexport * from './events.js'\nexport * from './keys.js'\nexport * from './message-stream.js'\nexport * from './metrics.js'\nexport * from './multiaddr-connection.js'\nexport * from './peer-discovery.js'\nexport * from './peer-id.js'\nexport * from './peer-info.js'\nexport * from './peer-routing.js'\nexport * from './peer-store.js'\nexport * from './record.js'\nexport * from './startable.js'\nexport * from './stream-handler.js'\nexport * from './stream-muxer.js'\nexport * from './stream.js'\nexport * from './topology.js'\nexport * from './transport.js'\n\nexport * from 'main-event'\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable<Uint8Array> {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nexport interface Next<T> {\n done?: boolean\n error?: Error\n value?: T\n}\n\nclass FixedFIFO<T> {\n public buffer: Array<Next<T> | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO<T> | null\n\n constructor (hwm: number) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two')\n }\n\n this.buffer = new Array(hwm)\n this.mask = hwm - 1\n this.top = 0\n this.btm = 0\n this.next = null\n }\n\n push (data: Next<T>): boolean {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift (): Next<T> | undefined {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty (): boolean {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO<T> {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO<T>\n private tail: FixedFIFO<T>\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO<T>(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next<T>): void {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\n\n if (!this.head.push(val)) {\n const prev = this.head\n this.head = prev.next = new FixedFIFO<T>(2 * this.head.buffer.length)\n this.head.push(val)\n }\n }\n\n shift (): Next<T> | undefined {\n let val = this.tail.shift()\n\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next\n this.tail.next = null\n this.tail = next\n val = this.tail.shift()\n }\n\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty (): boolean {\n return this.head.isEmpty()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { FIFO, type Next } from './fifo.js'\n\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\ninterface BasePushable<T> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error): this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T): this\n\n /**\n * Returns a promise that resolves when the underlying queue becomes empty (e.g.\n * this.readableLength === 0).\n *\n * If an AbortSignal is passed as an option and that signal aborts, it only\n * causes the returned promise to reject - it does not end the pushable.\n */\n onEmpty(options?: AbortOptions): Promise<void>\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable<T, R = void, N = unknown> extends AsyncGenerator<T, R, N>, BasePushable<T> {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV<T, R = void, N = unknown> extends AsyncGenerator<T[], R, N>, BasePushable<T> {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?(err?: Error): void\n}\n\nexport interface DoneResult { done: true }\nexport interface ValueResult<T> { done: false, value: T }\nexport type NextResult<T> = ValueResult<T> | DoneResult\n\ninterface getNext<T, V = T> { (buffer: FIFO<T>): NextResult<V> }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): Pushable<T>\nexport function pushable<T> (options: ObjectPushableOptions): Pushable<T>\nexport function pushable<T> (options: Options = {}): Pushable<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T> => {\n const next: Next<T> | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n }\n }\n\n return _pushable<T, T, Pushable<T>>(getNext, options)\n}\n\nexport function pushableV<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): PushableV<T>\nexport function pushableV<T> (options: ObjectPushableOptions): PushableV<T>\nexport function pushableV<T> (options: Options = {}): PushableV<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T[]> => {\n let next: Next<T> | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value)\n }\n }\n\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable<T, T[], PushableV<T>>(getNext, options)\n}\n\nfunction _pushable<PushType, ValueType, ReturnType> (getNext: getNext<PushType, ValueType>, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO<PushType>()\n let pushable: any\n let onNext: ((next: Next<PushType>) => ReturnType) | null\n let ended: boolean\n let drain = deferred()\n\n const waitNext = async (): Promise<NextResult<ValueType>> => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise<NextResult<ValueType>>((resolve, reject) => {\n onNext = (next: Next<PushType>) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\n }\n })\n } finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve()\n drain = deferred()\n })\n }\n }\n }\n\n const bufferNext = (next: Next<PushType>): ReturnType => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error): ReturnType => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType): ReturnType => {\n if (ended) {\n return pushable\n }\n\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value')\n }\n\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error): ReturnType => {\n if (ended) return pushable\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = (): DoneResult => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error): DoneResult => {\n end(err)\n\n return { done: true }\n }\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength (): number {\n return buffer.size\n },\n onEmpty: async (options?: AbortOptions) => {\n const signal = options?.signal\n signal?.throwIfAborted()\n\n if (buffer.isEmpty()) {\n return\n }\n\n let cancel: Promise<void> | undefined\n let listener: (() => void) | undefined\n\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError())\n }\n\n signal.addEventListener('abort', listener)\n })\n }\n\n try {\n await Promise.race([\n drain.promise,\n cancel\n ])\n } finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener)\n }\n }\n }\n }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n },\n onEmpty: (opts?: AbortOptions) => {\n return _pushable.onEmpty(opts)\n }\n }\n\n return pushable\n}\n", "export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && options.signal) {\n\t\t\toptions.signal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n", "import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.addEventListener || emitter.on || emitter.addListener;\n\tconst removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\trejectionMultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = async (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\tif (options.filter) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = (...arguments_) => {\n\t\t\tcancel();\n\t\t\treject(options.rejectionMultiArgs ? arguments_ : arguments_[0]);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\t// Only remove rejection handler if we actually registered it\n\t\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t// Skip registering rejection handler if we're already listening to this event\n\t\t\t// as the main event takes priority (as documented)\n\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener('abort', () => {\n\t\t\t\trejectHandler(options.signal.reason);\n\t\t\t}, {once: true});\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\t// When cancelling, also clear the timeout timer\n\t\ttimeout.cancel = () => {\n\t\t\tcancel();\n\t\t\ttimeout.clear();\n\t\t};\n\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\trejectionMultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.rejectionMultiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = async (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (options.filter) {\n\t\t\ttry {\n\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (filterError) {\n\t\t\t\tcancel();\n\t\t\t\tif (nextQueue.length > 0) {\n\t\t\t\t\tconst {reject} = nextQueue.shift();\n\t\t\t\t\treject(filterError);\n\t\t\t\t} else {\n\t\t\t\t\t// Store error for next iterator call\n\t\t\t\t\thasPendingError = true;\n\t\t\t\t\terror = filterError;\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\tif (options.signal) {\n\t\toptions.signal.addEventListener('abort', () => {\n\t\t\trejectHandler(options.signal.reason);\n\t\t}, {once: true});\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n", "import type { Startable } from '@libp2p/interface'\n\nexport interface DebouncedFunction extends Startable {\n (): void\n}\n\n/**\n * Returns a function wrapper that will only call the passed function once\n *\n * Important - the passed function should not throw or reject\n */\nexport function debounce (func: () => void | Promise<void>, wait: number): DebouncedFunction {\n let timeout: ReturnType<typeof setTimeout> | undefined\n\n const output = function (): void {\n const later = function (): void {\n timeout = undefined\n void func()\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n output.start = (): void => {}\n output.stop = (): void => {\n clearTimeout(timeout)\n }\n\n return output\n}\n", "import type { RateLimiterResult } from './rate-limiter.js'\n\n/**\n * A rate limit was hit\n */\nexport class RateLimitError extends Error {\n remainingPoints: number\n msBeforeNext: number\n consumedPoints: number\n isFirstInDuration: boolean\n\n constructor (message = 'Rate limit exceeded', props: RateLimiterResult) {\n super(message)\n this.name = 'RateLimitError'\n this.remainingPoints = props.remainingPoints\n this.msBeforeNext = props.msBeforeNext\n this.consumedPoints = props.consumedPoints\n this.isFirstInDuration = props.isFirstInDuration\n }\n}\n\nexport class QueueFullError extends Error {\n static name = 'QueueFullError'\n\n constructor (message: string = 'The queue was full') {\n super(message)\n this.name = 'QueueFullError'\n }\n}\n\nexport class UnexpectedEOFError extends Error {\n static name = 'UnexpectedEOFError'\n name = 'UnexpectedEOFError'\n}\n\nexport class MaxEarlyStreamsError extends Error {\n static name = 'MaxEarlyStreamsError'\n name = 'MaxEarlyStreamsError'\n}\n", "/**\n * @packageDocumentation\n *\n * Pass a promise and an abort signal and await the result.\n *\n * @example Basic usage\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws an AbortError\n * const resolve = await raceSignal(promise, controller.signal)\n * ```\n *\n * @example Overriding errors\n *\n * By default the thrown error is the `.reason` property of the signal but it's\n * possible to override this behaviour with the `translateError` option:\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws `Error('Oh no!')`\n * const resolve = await raceSignal(promise, controller.signal, {\n * translateError: (signal) => {\n * // use `signal`, or don't\n * return new Error('Oh no!')\n * }\n * })\n * ```\n */\n\nexport interface RaceSignalOptions {\n /**\n * By default the rejection reason will be taken from the `.reason` field of\n * the aborted signal.\n *\n * Passing a function here allows overriding the default error.\n */\n translateError?(signal: AbortSignal): Error\n}\n\nfunction defaultTranslate (signal: AbortSignal): Error {\n return signal.reason\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal, opts?: RaceSignalOptions): Promise<T> {\n if (signal == null) {\n return promise\n }\n\n const translateError = opts?.translateError ?? defaultTranslate\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(translateError(signal))\n }\n\n let listener\n\n try {\n return await Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(translateError(signal))\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n", "import { StreamResetError, TypedEventEmitter, StreamMessageEvent, StreamBufferError, StreamResetEvent, StreamAbortEvent, StreamCloseEvent, StreamStateError } from '@libp2p/interface'\nimport { pushable } from 'it-pushable'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { MessageStreamEvents, MessageStreamStatus, MessageStream, AbortOptions, MessageStreamTimeline, MessageStreamDirection, EventHandler, StreamOptions, MessageStreamReadStatus, MessageStreamWriteStatus } from '@libp2p/interface'\nimport type { Logger } from '@libp2p/logger'\n\nconst DEFAULT_MAX_READ_BUFFER_LENGTH = Math.pow(2, 20) * 4 // 4MB\n\nexport interface MessageStreamInit extends StreamOptions {\n /**\n * A Logger implementation used to log stream-specific information\n */\n log: Logger\n\n /**\n * The stream direction\n */\n direction?: MessageStreamDirection\n\n /**\n * By default all available bytes are passed to the `sendData` method of\n * extending classes, if smaller chunks are required, pass a value here.\n */\n maxMessageSize?: number\n}\n\nexport interface SendResult {\n /**\n * The number of bytes from the passed buffer that were sent\n */\n sentBytes: number\n\n /**\n * If the underlying resource can accept more data immediately. If `true`,\n * `sent` must equal the `.byteLength` of the buffer passed to `sendData`.\n */\n canSendMore: boolean\n}\n\nexport abstract class AbstractMessageStream<Timeline extends MessageStreamTimeline = MessageStreamTimeline> extends TypedEventEmitter<MessageStreamEvents> implements MessageStream {\n public status: MessageStreamStatus\n public readonly timeline: Timeline\n public inactivityTimeout: number\n public maxReadBufferLength: number\n public maxWriteBufferLength?: number\n public readonly log: Logger\n public direction: MessageStreamDirection\n public maxMessageSize?: number\n\n public readStatus: MessageStreamReadStatus\n public writeStatus: MessageStreamWriteStatus\n public remoteReadStatus: MessageStreamReadStatus\n public remoteWriteStatus: MessageStreamWriteStatus\n\n public writableNeedsDrain: boolean\n\n /**\n * Any data stored here is emitted before any new incoming data.\n *\n * This is used when the stream is paused or if data is pushed onto the stream\n */\n protected readonly readBuffer: Uint8ArrayList\n protected readonly writeBuffer: Uint8ArrayList\n protected sendingData: boolean\n\n constructor (init: MessageStreamInit) {\n super()\n\n this.status = 'open'\n this.log = init.log\n this.direction = init.direction ?? 'outbound'\n this.inactivityTimeout = init.inactivityTimeout ?? 120_000\n this.maxReadBufferLength = init.maxReadBufferLength ?? DEFAULT_MAX_READ_BUFFER_LENGTH\n this.maxWriteBufferLength = init.maxWriteBufferLength\n this.maxMessageSize = init.maxMessageSize\n this.readBuffer = new Uint8ArrayList()\n this.writeBuffer = new Uint8ArrayList()\n\n this.readStatus = 'readable'\n this.remoteReadStatus = 'readable'\n this.writeStatus = 'writable'\n this.remoteWriteStatus = 'writable'\n this.sendingData = false\n this.writableNeedsDrain = false\n\n // @ts-expect-error type could have required fields other than 'open'\n this.timeline = {\n open: Date.now()\n }\n\n this.processSendQueue = this.processSendQueue.bind(this)\n\n const continueSendingOnDrain = (): void => {\n if (this.writableNeedsDrain) {\n this.log.trace('drain event received, continue sending data')\n this.writableNeedsDrain = false\n this.processSendQueue()\n }\n }\n this.addEventListener('drain', continueSendingOnDrain)\n }\n\n async * [Symbol.asyncIterator] (): AsyncGenerator<Uint8Array | Uint8ArrayList> {\n if (this.readStatus !== 'readable' && this.readStatus !== 'paused') {\n return\n }\n\n const output = pushable<Uint8Array | Uint8ArrayList>()\n\n const streamAsyncIterableOnMessageListener = (evt: StreamMessageEvent): void => {\n output.push(evt.data)\n }\n this.addEventListener('message', streamAsyncIterableOnMessageListener)\n\n const streamAsyncIterableOnCloseListener = (evt: StreamCloseEvent): void => {\n output.end(evt.error)\n }\n this.addEventListener('close', streamAsyncIterableOnCloseListener)\n\n const streamAsyncIterableOnRemoteCloseWriteListener = (): void => {\n output.end()\n }\n this.addEventListener('remoteCloseWrite', streamAsyncIterableOnRemoteCloseWriteListener)\n\n try {\n yield * output\n } finally {\n this.removeEventListener('message', streamAsyncIterableOnMessageListener)\n this.removeEventListener('close', streamAsyncIterableOnCloseListener)\n this.removeEventListener('remoteCloseWrite', streamAsyncIterableOnRemoteCloseWriteListener)\n }\n }\n\n isReadable (): boolean {\n return this.status === 'open'\n }\n\n send (data: Uint8Array | Uint8ArrayList): boolean {\n if (this.writeStatus === 'closed' || this.writeStatus === 'closing') {\n throw new StreamStateError(`Cannot write to a stream that is ${this.writeStatus}`)\n }\n\n this.log.trace('append %d bytes to write buffer', data.byteLength)\n this.writeBuffer.append(data)\n\n return this.processSendQueue()\n }\n\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort (err: Error): void {\n if (this.status === 'aborted' || this.status === 'reset' || this.status === 'closed') {\n return\n }\n\n this.log.error('abort with error - %e', err)\n\n this.status = 'aborted'\n\n // throw away unread data\n if (this.readBuffer.byteLength > 0) {\n this.readBuffer.consume(this.readBuffer.byteLength)\n }\n\n // throw away unsent data\n if (this.writeBuffer.byteLength > 0) {\n this.writeBuffer.consume(this.writeBuffer.byteLength)\n this.safeDispatchEvent('idle')\n }\n\n this.writeStatus = 'closed'\n this.remoteWriteStatus = 'closed'\n\n this.readStatus = 'closed'\n this.remoteReadStatus = 'closed'\n this.timeline.close = Date.now()\n\n try {\n this.sendReset(err)\n } catch (err: any) {\n this.log('failed to send reset to remote - %e', err)\n }\n\n this.dispatchEvent(new StreamAbortEvent(err))\n }\n\n pause (): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError('Cannot pause a stream that is closing/closed')\n }\n\n if (this.readStatus === 'paused') {\n return\n }\n\n this.readStatus = 'paused'\n this.sendPause()\n }\n\n resume (): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError('Cannot resume a stream that is closing/closed')\n }\n\n if (this.readStatus === 'readable') {\n return\n }\n\n this.readStatus = 'readable'\n // emit any data that accumulated while we were paused\n this.dispatchReadBuffer()\n this.sendResume()\n }\n\n push (data: Uint8Array | Uint8ArrayList): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`)\n }\n\n if (data.byteLength === 0) {\n return\n }\n\n this.readBuffer.append(data)\n\n if (this.readStatus === 'paused' || this.listenerCount('message') === 0) {\n // abort if the read buffer is too large\n this.checkReadBufferLength()\n\n return\n }\n\n // TODO: use a microtask instead?\n setTimeout(() => {\n this.dispatchReadBuffer()\n }, 0)\n }\n\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n onData (data: Uint8Array | Uint8ArrayList): void {\n if (data.byteLength === 0) {\n // this.log('ignoring empty data')\n return\n }\n\n // discard the data if our readable end is closed\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('ignoring data - read status %s', this.readStatus)\n return\n }\n\n this.readBuffer.append(data)\n this.dispatchReadBuffer()\n }\n\n addEventListener<K extends keyof MessageStreamEvents>(type: K, listener: EventHandler<MessageStreamEvents[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void\n addEventListener (...args: any[]): void {\n // @ts-expect-error cannot ensure args has enough members\n super.addEventListener.apply(this, args)\n\n // if a 'message' listener is being added and we have queued data, dispatch\n // the data\n if (args[0] === 'message' && this.readBuffer.byteLength > 0) {\n // event listeners can be added in constructors and often use object\n // properties - if this the case we can access a class member before it\n // has been initialized so dispatch the message in the microtask queue\n queueMicrotask(() => {\n this.dispatchReadBuffer()\n })\n }\n }\n\n /**\n * Receive a reset message - close immediately for reading and writing (remote\n * error)\n */\n onRemoteReset (): void {\n this.log('remote reset')\n\n this.status = 'reset'\n this.writeStatus = 'closed'\n this.remoteWriteStatus = 'closed'\n this.remoteReadStatus = 'closed'\n this.timeline.close = Date.now()\n\n if (this.readBuffer.byteLength === 0) {\n this.readStatus = 'closed'\n }\n\n const err = new StreamResetError()\n this.dispatchEvent(new StreamResetEvent(err))\n }\n\n /**\n * The underlying resource or transport this stream uses has closed - it is\n * not possible to send any more messages though any data still in the read\n * buffer may still be read\n */\n onTransportClosed (err?: Error): void {\n this.log('transport closed')\n\n if (this.readStatus === 'readable' && this.readBuffer.byteLength === 0) {\n this.log('close readable end after transport closed and read buffer is empty')\n this.readStatus = 'closed'\n }\n\n if (this.remoteReadStatus !== 'closed') {\n this.remoteReadStatus = 'closed'\n }\n\n if (this.remoteWriteStatus !== 'closed') {\n this.remoteWriteStatus = 'closed'\n }\n\n if (this.writeStatus !== 'closed') {\n this.writeStatus = 'closed'\n }\n\n if (err != null) {\n this.abort(err)\n } else {\n if (this.status === 'open' || this.status === 'closing') {\n this.timeline.close = Date.now()\n this.status = 'closed'\n this.writeStatus = 'closed'\n this.remoteWriteStatus = 'closed'\n this.remoteReadStatus = 'closed'\n this.dispatchEvent(new StreamCloseEvent())\n }\n }\n }\n\n /**\n * Called by extending classes when the remote closes its writable end\n */\n onRemoteCloseWrite (): void {\n if (this.remoteWriteStatus === 'closed') {\n return\n }\n\n this.log.trace('on remote close write')\n\n this.remoteWriteStatus = 'closed'\n\n this.safeDispatchEvent('remoteCloseWrite')\n\n if (this.writeStatus === 'closed') {\n this.onTransportClosed()\n }\n }\n\n /**\n * Called by extending classes when the remote closes its readable end\n */\n onRemoteCloseRead (): void {\n this.log.trace('on remote close read')\n\n this.remoteReadStatus = 'closed'\n\n // throw away any unsent bytes if the remote closes it's readable end\n if (this.writeBuffer.byteLength > 0) {\n this.writeBuffer.consume(this.writeBuffer.byteLength)\n this.safeDispatchEvent('idle')\n }\n }\n\n protected processSendQueue (): boolean {\n // bail if the underlying transport is full\n if (this.writableNeedsDrain) {\n this.log.trace('not processing send queue as drain is required')\n this.checkWriteBufferLength()\n\n return false\n }\n\n // bail if there is no data to send\n if (this.writeBuffer.byteLength === 0) {\n this.log.trace('not processing send queue as no bytes to send')\n return true\n }\n\n // bail if we are already sending data\n if (this.sendingData) {\n this.log.trace('not processing send queue as already sending data')\n return true\n }\n\n this.sendingData = true\n\n this.log.trace('processing send queue with %d queued bytes', this.writeBuffer.byteLength)\n\n try {\n let canSendMore = true\n const totalBytes = this.writeBuffer.byteLength\n let sentBytes = 0\n\n // send as much data as possible while we have data to send and the\n // underlying muxer can still accept data\n while (this.writeBuffer.byteLength > 0) {\n const end = Math.min(this.maxMessageSize ?? this.writeBuffer.byteLength, this.writeBuffer.byteLength)\n\n // this can happen if a subclass changes the max message size dynamically\n if (end === 0) {\n canSendMore = false\n break\n }\n\n // chunk to send to the remote end\n const toSend = this.writeBuffer.sublist(0, end)\n\n // copy toSend in case the extending class modifies the list\n const willSend = new Uint8ArrayList(toSend)\n\n this.writeBuffer.consume(toSend.byteLength)\n\n // sending data can cause buffers to fill up, events to be emitted and\n // this method to be invoked again\n const sendResult = this.sendData(toSend)\n canSendMore = sendResult.canSendMore\n sentBytes += sendResult.sentBytes\n\n if (sendResult.sentBytes !== willSend.byteLength) {\n willSend.consume(sendResult.sentBytes)\n this.writeBuffer.prepend(willSend)\n }\n\n if (!canSendMore) {\n break\n }\n }\n\n if (!canSendMore) {\n this.log.trace('sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer', sentBytes, totalBytes, this.writeBuffer.byteLength)\n this.writableNeedsDrain = true\n this.checkWriteBufferLength()\n }\n\n // we processed all bytes in the queue, resolve the write queue idle promise\n if (this.writeBuffer.byteLength === 0) {\n this.safeDispatchEvent('idle')\n }\n\n return canSendMore\n } finally {\n this.sendingData = false\n }\n }\n\n protected dispatchReadBuffer (): void {\n try {\n if (this.listenerCount('message') === 0) {\n this.log.trace('not dispatching pause buffer as there are no listeners for the message event')\n return\n }\n\n if (this.readBuffer.byteLength === 0) {\n this.log.trace('not dispatching pause buffer as there is no data to dispatch')\n return\n }\n\n if (this.readStatus === 'paused') {\n this.log.trace('not dispatching pause buffer we are paused')\n return\n }\n\n // discard the pause buffer if our readable end is closed\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('dropping %d bytes because the readable end is %s', this.readBuffer.byteLength, this.readStatus)\n this.readBuffer.consume(this.readBuffer.byteLength)\n return\n }\n\n const buf = this.readBuffer.sublist()\n this.readBuffer.consume(buf.byteLength)\n\n this.dispatchEvent(new StreamMessageEvent(buf))\n } finally {\n if (this.readBuffer.byteLength === 0 && this.remoteWriteStatus === 'closed') {\n this.log('close readable end after dispatching read buffer and remote writable end is closed')\n this.readStatus = 'closed'\n }\n\n // abort if we failed to consume the read buffer and it is too large\n this.checkReadBufferLength()\n }\n }\n\n private checkReadBufferLength (): void {\n if (this.readBuffer.byteLength > this.maxReadBufferLength) {\n this.abort(new StreamBufferError(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))\n }\n }\n\n private checkWriteBufferLength (): void {\n if (this.maxWriteBufferLength == null) {\n return\n }\n\n if (this.writeBuffer.byteLength > this.maxWriteBufferLength) {\n this.abort(new StreamBufferError(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))\n }\n }\n\n public onMuxerNeedsDrain (): void {\n this.writableNeedsDrain = true\n }\n\n public onMuxerDrain (): void {\n this.safeDispatchEvent('drain')\n }\n\n /**\n * Send a data message to the remote end of the stream. Implementations of\n * this method should return the number of bytes from the passed buffer that\n * were sent successfully and if the underlying resource can accept more data.\n *\n * The implementation should always attempt to send the maximum amount of data\n * possible.\n *\n * Returning a result that means the data was only partially sent but that the\n * underlying resource can accept more data is invalid.\n */\n abstract sendData (data: Uint8ArrayList): SendResult\n\n /**\n * Send a reset message to the remote end of the stream\n */\n abstract sendReset (err: Error): void\n\n /**\n * If supported, instruct the remote end of the stream to temporarily stop\n * sending data messages\n */\n abstract sendPause (): void\n\n /**\n * If supported, inform the remote end of the stream they may resume sending\n * data messages\n */\n abstract sendResume (): void\n\n /**\n * Stop accepting new data to send and return a promise that resolves when any\n * unsent data has been written into the underlying resource.\n */\n abstract close (options?: AbortOptions): Promise<void>\n}\n", "export function isPromise <T = unknown> (thing: any): thing is Promise<T> {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n", "import { MuxerClosedError, TypedEventEmitter } from '@libp2p/interface'\nimport { raceSignal } from 'race-signal'\nimport { MaxEarlyStreamsError } from './errors.ts'\nimport { isPromise } from './is-promise.ts'\nimport type { AbstractStream } from './abstract-stream.ts'\nimport type { AbortOptions, CounterGroup, CreateStreamOptions, EventHandler, Logger, MessageStream, Stream, StreamCloseEvent, StreamMessageEvent, StreamMuxer, StreamMuxerEvents, StreamMuxerOptions, StreamMuxerStatus, StreamOptions } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface AbstractStreamMuxerInit extends StreamMuxerOptions {\n /**\n * The protocol name for the muxer\n */\n protocol: string\n\n /**\n * The name of the muxer, used to create a new logging scope from the passed\n * connection's logger\n */\n name: string\n\n /**\n * A counter for muxer metrics\n */\n metrics?: CounterGroup\n}\n\nexport abstract class AbstractStreamMuxer <MuxedStream extends AbstractStream = AbstractStream> extends TypedEventEmitter<StreamMuxerEvents<MuxedStream>> implements StreamMuxer<MuxedStream> {\n public streams: MuxedStream[]\n public protocol: string\n public status: StreamMuxerStatus\n\n protected log: Logger\n protected maConn: MessageStream\n protected streamOptions?: StreamOptions\n protected earlyStreams: MuxedStream[]\n protected maxEarlyStreams: number\n\n private readonly metrics?: CounterGroup\n\n constructor (maConn: MessageStream, init: AbstractStreamMuxerInit) {\n super()\n\n this.maConn = maConn\n this.protocol = init.protocol\n this.streams = []\n this.earlyStreams = []\n this.status = 'open'\n this.log = maConn.log.newScope(init.name)\n this.streamOptions = init.streamOptions\n this.maxEarlyStreams = init.maxEarlyStreams ?? 10\n this.metrics = init.metrics\n\n // read/write all data from/to underlying maConn\n const muxerMaConnOnMessage = (evt: StreamMessageEvent): void => {\n try {\n this.onData(evt.data)\n } catch (err: any) {\n this.abort(err)\n this.maConn.abort(err)\n }\n }\n this.maConn.addEventListener('message', muxerMaConnOnMessage)\n\n // signal stream writers when the underlying connection can accept more data\n const muxerMaConnOnDrain = (): void => {\n this.log('underlying stream drained, signal %d streams to continue writing', this.streams.length)\n\n this.streams.forEach(stream => {\n stream.onMuxerDrain()\n })\n }\n this.maConn.addEventListener('drain', muxerMaConnOnDrain)\n\n const muxerOnMaConnClose = (): void => {\n this.log('underlying stream closed with status %s and %d streams', this.status, this.streams.length)\n this.onTransportClosed()\n }\n this.maConn.addEventListener('close', muxerOnMaConnClose)\n }\n\n send (data: Uint8Array | Uint8ArrayList): boolean {\n const result = this.maConn.send(data)\n\n if (result === false) {\n this.log('underlying stream saturated, signal %d streams to pause writing', this.streams.length)\n\n this.streams.forEach(stream => {\n stream.onMuxerNeedsDrain()\n })\n }\n\n return result\n }\n\n async close (options?: AbortOptions): Promise<void> {\n if (this.status === 'closed' || this.status === 'closing') {\n return\n }\n\n this.status = 'closing'\n\n await raceSignal(Promise.all(\n [...this.streams].map(async s => {\n await s.close(options)\n })\n ), options?.signal)\n\n this.status = 'closed'\n }\n\n abort (err: Error): void {\n if (this.status === 'closed') {\n return\n }\n\n this.status = 'closing'\n\n ;[...this.streams].forEach(s => {\n s.abort(err)\n })\n\n this.status = 'closed'\n }\n\n onTransportClosed (err?: Error): void {\n this.status = 'closing'\n\n try {\n [...this.streams].forEach(stream => {\n stream.onTransportClosed(err)\n })\n } catch (err: any) {\n this.abort(err)\n }\n\n this.status = 'closed'\n }\n\n async createStream (options?: CreateStreamOptions): Promise<MuxedStream> {\n if (this.status !== 'open') {\n throw new MuxerClosedError()\n }\n\n let stream = this.onCreateStream({\n ...this.streamOptions,\n ...options\n })\n\n if (isPromise(stream)) {\n stream = await stream\n }\n\n this.streams.push(stream)\n this.cleanUpStream(stream)\n\n return stream\n }\n\n /**\n * Extending classes should invoke this method when a new stream was created\n * by the remote muxer\n */\n onRemoteStream (stream: MuxedStream): void {\n this.streams.push(stream)\n this.cleanUpStream(stream)\n\n if (this.listenerCount('stream') === 0) {\n // no listener has been added for the stream event yet, store the stream\n // to emit it later\n this.earlyStreams.push(stream)\n\n if (this.earlyStreams.length > this.maxEarlyStreams) {\n this.abort(new MaxEarlyStreamsError(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`))\n }\n\n return\n }\n\n this.safeDispatchEvent('stream', {\n detail: stream\n })\n }\n\n private cleanUpStream (stream: Stream): void {\n const muxerOnStreamEnd = (evt: StreamCloseEvent): void => {\n const index = this.streams.findIndex(s => s === stream)\n\n if (index !== -1) {\n this.streams.splice(index, 1)\n }\n\n if (evt.error != null) {\n if (evt.local) {\n this.metrics?.increment({ [`${stream.direction}_stream_reset`]: true })\n } else {\n this.metrics?.increment({ [`${stream.direction}_stream_abort`]: true })\n }\n } else {\n this.metrics?.increment({ [`${stream.direction}_stream_end`]: true })\n }\n }\n stream.addEventListener('close', muxerOnStreamEnd)\n\n this.metrics?.increment({ [`${stream.direction}_stream`]: true })\n }\n\n addEventListener<K extends keyof StreamMuxerEvents<MuxedStream>>(type: K, listener: EventHandler<StreamMuxerEvents<MuxedStream>[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void\n addEventListener (...args: any[]): void {\n // @ts-expect-error cannot ensure args has enough members\n super.addEventListener.apply(this, args)\n\n // if a 'stream' listener is being added and we have early streams, emit\n // them\n if (args[0] === 'stream' && this.earlyStreams.length > 0) {\n // event listeners can be added in constructors and often use object\n // properties - if this the case we can access a class member before it\n // has been initialized so dispatch the message in the microtask queue\n queueMicrotask(() => {\n this.earlyStreams.forEach(stream => {\n this.safeDispatchEvent('stream', {\n detail: stream\n })\n })\n this.earlyStreams = []\n })\n }\n }\n\n /**\n * A new outgoing stream needs to be created\n */\n abstract onCreateStream (options: CreateStreamOptions): MuxedStream | Promise<MuxedStream>\n\n /**\n * Multiplexed data was received from the remote muxer\n */\n abstract onData (data: Uint8Array | Uint8ArrayList): void\n}\n", "import { pEvent } from 'p-event'\nimport { AbstractMessageStream } from './abstract-message-stream.js'\nimport type { MessageStreamInit } from './abstract-message-stream.js'\nimport type { AbortOptions, Stream } from '@libp2p/interface'\n\nexport interface AbstractStreamInit extends MessageStreamInit {\n /**\n * A unique identifier for this stream\n */\n id: string\n\n /**\n * The protocol name for the stream, if it is known\n */\n protocol?: string\n}\n\nexport abstract class AbstractStream extends AbstractMessageStream implements Stream {\n public id: string\n public protocol: string\n\n constructor (init: AbstractStreamInit) {\n super(init)\n\n this.id = init.id\n this.protocol = init.protocol ?? ''\n }\n\n async close (options?: AbortOptions): Promise<void> {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n return\n }\n\n this.writeStatus = 'closing'\n\n // if we are currently sending data, wait for all the data to be written\n // into the underlying transport\n if (this.sendingData || this.writeBuffer.byteLength > 0) {\n this.log('waiting for write queue to become idle before closing writable end of stream, %d unsent bytes', this.writeBuffer.byteLength)\n await pEvent(this, 'idle', {\n ...options,\n rejectionEvents: [\n 'close'\n ]\n })\n }\n\n // now that the underlying transport has all the data, if the buffer is full\n // wait for it to be emptied\n if (this.writableNeedsDrain) {\n this.log('waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s', this.writeBuffer.byteLength, this.sendingData)\n await pEvent(this, 'drain', {\n ...options,\n rejectionEvents: [\n 'close'\n ]\n })\n this.log('write queue drained, closing writable end of stream, %d unsent bytes, sending %s', this.writeBuffer.byteLength, this.sendingData)\n }\n\n await this.sendCloseWrite(options)\n\n this.writeStatus = 'closed'\n\n this.log('closed writable end gracefully')\n\n if (this.remoteWriteStatus === 'closed') {\n this.onTransportClosed()\n }\n }\n\n async closeRead (options?: AbortOptions): Promise<void> {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n return\n }\n\n // throw away any unread data\n if (this.readBuffer.byteLength > 0) {\n this.readBuffer.consume(this.readBuffer.byteLength)\n }\n\n this.readStatus = 'closing'\n\n await this.sendCloseRead(options)\n\n this.readStatus = 'closed'\n\n this.log('closed readable end gracefully')\n }\n\n /**\n * Send a message to the remote end of the stream, informing them that we will\n * send no more data messages.\n */\n abstract sendCloseWrite (options?: AbortOptions): Promise<void>\n\n /**\n * If supported, send a message to the remote end of the stream, informing\n * them that we will read no more data messages.\n */\n abstract sendCloseRead (options?: AbortOptions): Promise<void>\n}\n", "\nexport interface ClearableSignal extends AbortSignal {\n clear: () => void\n}\n\n/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal (signals: Array<AbortSignal | undefined | null>): ClearableSignal {\n const controller = new globalThis.AbortController()\n\n function onAbort (): void {\n controller.abort()\n\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort()\n break\n }\n\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort)\n }\n }\n\n function clear (): void {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n const signal = controller.signal as ClearableSignal\n signal.clear = clear\n\n return signal\n}\n", "import { anySignal } from 'any-signal'\nimport { setMaxListeners } from 'main-event'\nimport { debounce } from './debounce.ts'\nimport type { AbortOptions } from '@libp2p/interface'\n\nexport interface RepeatingTask {\n /**\n * Update the interval after which the next iteration of the task will run.\n *\n * This is useful if, for example, you want to retry a task with a short rest\n * duration until it succeeds, then periodically after that.\n *\n * This only affects the next iteration of the task, if it is currently\n * running, that run will not be interrupted.\n *\n * Setting the interval to the current value has no effect.\n */\n setInterval(ms: number): void\n\n /**\n * Update the amount of time a task will run before the passed abort signal\n * will fire.\n *\n * This only affects the next iteration of the task, if it is currently\n * running, that run will not be interrupted.\n */\n setTimeout(ms: number): void\n\n /**\n * Schedule the task to be run immediately - if the task is not running it\n * will run after a short delay in order to debounce multiple `.run()`\n * invocations.\n */\n run(): void\n\n /**\n * Start the task running\n */\n start(): void\n\n /**\n * Stop the task running\n */\n stop(): void\n}\n\nexport interface RepeatingTaskOptions {\n /**\n * How long the task is allowed to run before the passed AbortSignal fires an\n * abort event\n */\n timeout?: number\n\n /**\n * Whether to schedule the task to run immediately\n *\n * @default false\n */\n runImmediately?: boolean\n\n /**\n * When `.run()` is called to run the task outside of the current interval,\n * debounce repeated calls to `.run()` by this amount.\n *\n * @default 100\n */\n debounce?: number\n}\n\nexport function repeatingTask (fn: (options?: AbortOptions) => void | Promise<void>, interval: number, options?: RepeatingTaskOptions): RepeatingTask {\n let timeout: ReturnType<typeof setTimeout>\n let shutdownController: AbortController\n let running = false\n\n function runTask (): void {\n const opts: AbortOptions = {\n signal: shutdownController.signal\n }\n\n if (options?.timeout != null) {\n const signal = anySignal([shutdownController.signal, AbortSignal.timeout(options.timeout)])\n setMaxListeners(Infinity, signal)\n\n opts.signal = signal\n }\n\n running = true\n\n Promise.resolve().then(async () => {\n await fn(opts)\n })\n .catch(() => {})\n .finally(() => {\n running = false\n\n if (shutdownController.signal.aborted) {\n // task has been cancelled, bail\n return\n }\n\n // reschedule\n timeout = setTimeout(runTask, interval)\n })\n }\n\n const runTaskDebounced = debounce(runTask, options?.debounce ?? 100)\n\n let started = false\n\n return {\n setInterval: (ms): void => {\n if (interval === ms) {\n // already running at this interval, nothing to do\n return\n }\n\n interval = ms\n\n // maybe reschedule\n if (timeout != null) {\n clearTimeout(timeout)\n timeout = setTimeout(runTask, interval)\n }\n },\n setTimeout: (ms): void => {\n options ??= {}\n options.timeout = ms\n },\n run: (): void => {\n if (running) {\n return\n }\n\n clearTimeout(timeout)\n runTaskDebounced()\n },\n start: (): void => {\n if (started) {\n return\n }\n\n started = true\n shutdownController = new AbortController()\n setMaxListeners(Infinity, shutdownController.signal)\n\n // run now\n if (options?.runImmediately === true) {\n queueMicrotask(() => {\n runTask()\n })\n } else {\n // run later\n timeout = setTimeout(runTask, interval)\n }\n },\n stop: (): void => {\n clearTimeout(timeout)\n shutdownController?.abort()\n started = false\n }\n }\n}\n", "export enum FrameType {\n /** Used to transmit data. May transmit zero length payloads depending on the flags. */\n Data = 0x0,\n /** Used to updated the senders receive window size. This is used to implement per-session flow control. */\n WindowUpdate = 0x1,\n /** Used to measure RTT. It can also be used to heart-beat and do keep-alive over TCP. */\n Ping = 0x2,\n /** Used to close a session. */\n GoAway = 0x3\n}\n\nexport enum Flag {\n /** Signals the start of a new stream. May be sent with a data or window update message. Also sent with a ping to indicate outbound. */\n SYN = 0x1,\n /** Acknowledges the start of a new stream. May be sent with a data or window update message. Also sent with a ping to indicate response. */\n ACK = 0x2,\n /** Performs a half-close of a stream. May be sent with a data message or window update. */\n FIN = 0x4,\n /** Reset a stream immediately. May be sent with a data or window update message. */\n RST = 0x8\n}\n\nconst flagCodes = Object.values(Flag).filter((x) => typeof x !== 'string') as Flag[]\n\nexport const YAMUX_VERSION = 0\n\nexport enum GoAwayCode {\n NormalTermination = 0x0,\n ProtocolError = 0x1,\n InternalError = 0x2\n}\n\nexport const HEADER_LENGTH = 12\n\nexport interface FrameHeader {\n /**\n * The version field is used for future backward compatibility.\n * At the current time, the field is always set to 0, to indicate the initial version.\n */\n version?: number\n /** The type field is used to switch the frame message type. */\n type: FrameType\n /** The flags field is used to provide additional information related to the message type. */\n flag: number\n /**\n * The StreamID field is used to identify the logical stream the frame is addressing.\n * The client side should use odd ID's, and the server even.\n * This prevents any collisions. Additionally, the 0 ID is reserved to represent the session.\n */\n streamID: number\n /**\n * The meaning of the length field depends on the message type:\n * Data - provides the length of bytes following the header\n * Window update - provides a delta update to the window size\n * Ping - Contains an opaque value, echoed back\n * Go Away - Contains an error code\n */\n length: number\n}\n\nexport function stringifyHeader (header: FrameHeader): string {\n const flags = flagCodes.filter(f => (header.flag & f) === f).map(f => Flag[f]).join('|')\n return `streamID=${header.streamID} type=${FrameType[header.type]} flag=${flags} length=${header.length}`\n}\n", "import { GoAwayCode } from './frame.ts'\n\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n public reason: GoAwayCode\n\n constructor (message: string, reason: GoAwayCode) {\n super(message)\n this.name = 'ProtocolError'\n this.reason = reason\n }\n}\n\nexport function isProtocolError (err?: any): err is ProtocolError {\n return err?.reason !== null\n}\n\nexport class InvalidFrameError extends ProtocolError {\n static name = 'InvalidFrameError'\n\n constructor (message = 'The frame was invalid') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'InvalidFrameError'\n }\n}\n\nexport class UnRequestedPingError extends ProtocolError {\n static name = 'UnRequestedPingError'\n\n constructor (message = 'Un-requested ping error') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'UnRequestedPingError'\n }\n}\n\nexport class NotMatchingPingError extends ProtocolError {\n static name = 'NotMatchingPingError'\n\n constructor (message = 'Not matching ping error') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'NotMatchingPingError'\n }\n}\n\nexport class InvalidStateError extends Error {\n static name = 'InvalidStateError'\n\n constructor (message = 'Invalid state') {\n super(message)\n this.name = 'InvalidStateError'\n }\n}\n\nexport class StreamAlreadyExistsError extends ProtocolError {\n static name = 'StreamAlreadyExistsError'\n\n constructor (message = 'Stream already exists') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'StreamAlreadyExistsError'\n }\n}\n\nexport class DecodeInvalidVersionError extends ProtocolError {\n static name = 'DecodeInvalidVersionError'\n\n constructor (message = 'Decode invalid version') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'DecodeInvalidVersionError'\n }\n}\n\nexport class BothClientsError extends ProtocolError {\n static name = 'BothClientsError'\n\n constructor (message = 'Both clients') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'BothClientsError'\n }\n}\n\nexport class ReceiveWindowExceededError extends ProtocolError {\n static name = 'ReceiveWindowExceededError'\n\n constructor (message = 'Receive window exceeded') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'ReceiveWindowExceededError'\n }\n}\n", "// Protocol violation errors\n\nimport { BothClientsError, DecodeInvalidVersionError, InvalidFrameError, NotMatchingPingError, ReceiveWindowExceededError, StreamAlreadyExistsError, UnRequestedPingError } from './errors.js'\n\nexport const PROTOCOL_ERRORS = new Set([\n InvalidFrameError.name,\n UnRequestedPingError.name,\n NotMatchingPingError.name,\n StreamAlreadyExistsError.name,\n DecodeInvalidVersionError.name,\n BothClientsError.name,\n ReceiveWindowExceededError.name\n])\n\n/**\n * INITIAL_STREAM_WINDOW is the initial stream window size.\n *\n * Not an implementation choice, this is defined in the specification\n */\nexport const INITIAL_STREAM_WINDOW = 256 * 1024\n\n/**\n * Default max stream window\n */\nexport const MAX_STREAM_WINDOW = 16 * 1024 * 1024\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { INITIAL_STREAM_WINDOW, MAX_STREAM_WINDOW } from './constants.js'\nimport type { StreamMuxerOptions, StreamOptions } from '@libp2p/interface'\n\nexport interface YamuxStreamOptions extends StreamOptions {\n /**\n * Used to control the initial window size that we allow for a stream.\n *\n * measured in bytes\n */\n initialStreamWindowSize?: number\n\n /**\n * Used to control the maximum window size that we allow for a stream.\n */\n maxStreamWindowSize?: number\n}\n\n// TODO use config items or delete them\nexport interface Config extends StreamMuxerOptions<YamuxStreamOptions> {\n /**\n * Used to do periodic keep alive messages using a ping\n */\n enableKeepAlive?: boolean\n\n /**\n * How often to perform the keep alive\n *\n * measured in milliseconds\n */\n keepAliveInterval?: number\n}\n\nexport const defaultConfig: Required<Config> & { streamOptions: Required<YamuxStreamOptions> } = {\n enableKeepAlive: true,\n keepAliveInterval: 30_000,\n maxInboundStreams: 1_000,\n maxOutboundStreams: 1_000,\n maxMessageSize: 64 * 1024,\n maxEarlyStreams: 10,\n streamOptions: {\n initialStreamWindowSize: INITIAL_STREAM_WINDOW,\n maxStreamWindowSize: MAX_STREAM_WINDOW,\n inactivityTimeout: 120_000,\n maxReadBufferLength: 4_194_304,\n maxWriteBufferLength: Infinity\n }\n}\n\nexport function verifyConfig (config: Config): void {\n if (config.keepAliveInterval != null && config.keepAliveInterval <= 0) {\n throw new InvalidParametersError('keep-alive interval must be positive')\n }\n if (config.maxInboundStreams != null && config.maxInboundStreams < 0) {\n throw new InvalidParametersError('max inbound streams must be larger or equal 0')\n }\n if (config.maxOutboundStreams != null && config.maxOutboundStreams < 0) {\n throw new InvalidParametersError('max outbound streams must be larger or equal 0')\n }\n if (config.maxMessageSize != null && config.maxMessageSize < 1024) {\n throw new InvalidParametersError('MaxMessageSize must be greater than a kilobyte')\n }\n if (config.streamOptions?.initialStreamWindowSize != null && config.streamOptions?.initialStreamWindowSize < INITIAL_STREAM_WINDOW) {\n throw new InvalidParametersError('InitialStreamWindowSize must be larger or equal 256 kB')\n }\n if (config.streamOptions?.maxStreamWindowSize != null && config.streamOptions?.initialStreamWindowSize != null && config.streamOptions?.maxStreamWindowSize < config.streamOptions?.initialStreamWindowSize) {\n throw new InvalidParametersError('MaxStreamWindowSize must be larger than the InitialStreamWindowSize')\n }\n if (config.streamOptions?.maxStreamWindowSize != null && config.streamOptions?.maxStreamWindowSize > 2 ** 32 - 1) {\n throw new InvalidParametersError('MaxStreamWindowSize must be less than equal MAX_UINT32')\n }\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport { InvalidFrameError } from './errors.js'\nimport { FrameType, HEADER_LENGTH, YAMUX_VERSION } from './frame.js'\nimport type { FrameHeader } from './frame.js'\n\nexport interface Frame {\n header: FrameHeader\n data?: Uint8ArrayList\n}\n\nexport interface DataFrame {\n header: FrameHeader\n data: Uint8ArrayList\n}\n\nexport function isDataFrame (frame: Frame): frame is DataFrame {\n return frame.header.type === FrameType.Data && frame.data !== null\n}\n\n// used to bit shift in decoding\n// native bit shift can overflow into a negative number, so we bit shift by\n// multiplying by a power of 2\nconst twoPow24 = 2 ** 24\n\n/**\n * Decode a header from the front of a buffer\n *\n * @param data - Assumed to have enough bytes for a header\n */\nexport function decodeHeader (data: Uint8Array): FrameHeader {\n if (data[0] !== YAMUX_VERSION) {\n throw new InvalidFrameError('Invalid frame version')\n }\n\n return {\n type: data[1],\n flag: (data[2] << 8) + data[3],\n streamID: (data[4] * twoPow24) + (data[5] << 16) + (data[6] << 8) + data[7],\n length: (data[8] * twoPow24) + (data[9] << 16) + (data[10] << 8) + data[11]\n }\n}\n\n/**\n * Decodes yamux frames from a source\n */\nexport class Decoder {\n /** Buffer for in-progress frames */\n private readonly buffer: Uint8ArrayList\n\n constructor () {\n this.buffer = new Uint8ArrayList()\n }\n\n /**\n * Emits frames from the decoder source.\n *\n * Note: If `readData` is emitted, it _must_ be called before the next iteration\n * Otherwise an error is thrown\n */\n * emitFrames (buf: Uint8Array | Uint8ArrayList): Generator<Frame> {\n this.buffer.append(buf)\n\n // Loop to consume as many bytes from the buffer as possible\n // Eg: when a single chunk contains several frames\n while (true) {\n const frame = this.readFrame()\n\n if (frame === undefined) {\n break\n }\n\n yield frame\n }\n }\n\n private readFrame (): Frame | undefined {\n let frameSize = HEADER_LENGTH\n\n if (this.buffer.byteLength < HEADER_LENGTH) {\n // not enough data yet\n return\n }\n\n // TODO: use sublist?\n const header = decodeHeader(this.buffer.subarray(0, HEADER_LENGTH))\n\n if (header.type === FrameType.Data) {\n frameSize += header.length\n\n if (this.buffer.byteLength < frameSize) {\n // not enough data yet\n return\n }\n\n const data = this.buffer.sublist(HEADER_LENGTH, frameSize)\n this.buffer.consume(frameSize)\n\n return { header, data }\n }\n\n this.buffer.consume(frameSize)\n\n return { header }\n }\n}\n", "import { HEADER_LENGTH } from './frame.js'\nimport type { FrameHeader } from './frame.js'\n\nexport function encodeHeader (header: FrameHeader): Uint8Array {\n const frame = new Uint8Array(HEADER_LENGTH)\n\n // always assume version 0\n // frameView.setUint8(0, header.version)\n\n frame[1] = header.type\n\n frame[2] = header.flag >>> 8\n frame[3] = header.flag\n\n frame[4] = header.streamID >>> 24\n frame[5] = header.streamID >>> 16\n frame[6] = header.streamID >>> 8\n frame[7] = header.streamID\n\n frame[8] = header.length >>> 24\n frame[9] = header.length >>> 16\n frame[10] = header.length >>> 8\n frame[11] = header.length\n\n return frame\n}\n", "import { AbstractStream } from '@libp2p/utils'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { INITIAL_STREAM_WINDOW, MAX_STREAM_WINDOW } from './constants.js'\nimport { isDataFrame } from './decode.ts'\nimport { InvalidFrameError, ReceiveWindowExceededError } from './errors.js'\nimport { Flag, FrameType, HEADER_LENGTH } from './frame.js'\nimport type { Frame } from './decode.ts'\nimport type { FrameHeader } from './frame.js'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { AbstractStreamInit, SendResult } from '@libp2p/utils'\n\nexport enum StreamState {\n Init,\n SYNSent,\n SYNReceived,\n Established,\n Finished,\n Paused\n}\n\nexport interface YamuxStreamInit extends AbstractStreamInit {\n streamId: number\n sendFrame(header: FrameHeader, body?: Uint8ArrayList): boolean\n getRTT(): number\n initialStreamWindowSize?: number\n maxMessageSize?: number\n maxStreamWindowSize?: number\n state: StreamState\n}\n\n/** YamuxStream is used to represent a logical stream within a session */\nexport class YamuxStream extends AbstractStream {\n streamId: number\n state: StreamState\n\n /** The number of available bytes to send */\n private sendWindowCapacity: number\n /** The number of bytes available to receive in a full window */\n private recvWindow: number\n /** The number of available bytes to receive */\n private recvWindowCapacity: number\n private maxStreamWindowSize: number\n\n /**\n * An 'epoch' is the time it takes to process and read data\n *\n * Used in conjunction with RTT to determine whether to increase the recvWindow\n */\n private epochStart: number\n private readonly getRTT: () => number\n\n private readonly sendFrame: (header: FrameHeader, body?: Uint8ArrayList) => boolean\n\n constructor (init: YamuxStreamInit) {\n const initialWindowSize = init.initialStreamWindowSize ?? INITIAL_STREAM_WINDOW\n\n super({\n ...init,\n maxMessageSize: initialWindowSize - HEADER_LENGTH\n })\n\n this.streamId = init.streamId\n this.state = init.state\n this.sendWindowCapacity = initialWindowSize\n this.recvWindow = initialWindowSize\n this.recvWindowCapacity = this.recvWindow\n this.maxStreamWindowSize = init.maxStreamWindowSize ?? MAX_STREAM_WINDOW\n this.epochStart = Date.now()\n this.getRTT = init.getRTT\n this.sendFrame = init.sendFrame\n\n const setStateToFinishedOnCloseListener = (): void => {\n this.state = StreamState.Finished\n }\n this.addEventListener('close', setStateToFinishedOnCloseListener)\n }\n\n /**\n * Send a data message to the remote muxer\n */\n sendData (buf: Uint8ArrayList): SendResult {\n const totalBytes = buf.byteLength\n let sentBytes = 0\n let canSendMore = true\n\n this.log?.trace('send window capacity is %d bytes', this.sendWindowCapacity)\n\n // send in chunks, waiting for window updates\n while (buf.byteLength > 0) {\n // we exhausted the send window, sending will resume later\n if (this.sendWindowCapacity === 0) {\n canSendMore = false\n this.log?.trace('sent %d/%d bytes, exhausted send window, waiting for window update', sentBytes, totalBytes)\n break\n }\n\n // send as much as we can\n const toSend = Math.min(this.sendWindowCapacity, buf.byteLength)\n const flags = this.getSendFlags()\n\n const data = buf.sublist(0, toSend)\n buf.consume(toSend)\n\n const muxerSendMore = this.sendFrame({\n type: FrameType.Data,\n flag: flags,\n streamID: this.streamId,\n length: toSend\n }, data)\n\n this.sendWindowCapacity -= toSend\n sentBytes += toSend\n\n if (!muxerSendMore) {\n canSendMore = muxerSendMore\n this.log.trace('sent %d/%d bytes, wait for muxer to have more send capacity', sentBytes, totalBytes)\n break\n }\n }\n\n return {\n sentBytes,\n canSendMore\n }\n }\n\n /**\n * Send a reset message to the remote muxer\n */\n async sendReset (): Promise<void> {\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: Flag.RST,\n streamID: this.streamId,\n length: 0\n })\n }\n\n /**\n * Send a message to the remote muxer, informing them no more data messages\n * will be sent by this end of the stream\n */\n async sendCloseWrite (): Promise<void> {\n const flags = this.getSendFlags() | Flag.FIN\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: flags,\n streamID: this.streamId,\n length: 0\n })\n }\n\n /**\n * Send a message to the remote muxer, informing them no more data messages\n * will be read by this end of the stream - this is a no-op on Yamux streams\n */\n async sendCloseRead (options?: AbortOptions): Promise<void> {\n options?.signal?.throwIfAborted()\n }\n\n /**\n * Stop sending window updates temporarily - in the interim the the remote\n * send window will exhaust and the remote will stop sending data\n */\n sendPause (): void {\n this.state = StreamState.Paused\n }\n\n /**\n * Start sending window updates as normal\n */\n sendResume (): void {\n this.state = StreamState.Established\n this.sendWindowUpdate()\n }\n\n /**\n * handleWindowUpdate is called when the stream receives a window update frame\n */\n handleWindowUpdate (frame: Frame): void {\n this.processFlags(frame.header.flag)\n\n // increase send window\n this.sendWindowCapacity += frame.header.length\n\n // change the chunk size the superclass uses\n this.maxMessageSize = this.sendWindowCapacity - HEADER_LENGTH\n\n if (this.maxMessageSize < 0) {\n this.maxMessageSize = 0\n }\n\n if (this.maxMessageSize === 0) {\n return\n }\n\n // if writing is paused and the update increases our send window, notify\n // writers that writing can resume\n if (this.writeBuffer.byteLength > 0) {\n this.log?.trace('window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s', frame.header.length, this.writeBuffer.byteLength, this.sendingData)\n this.safeDispatchEvent('drain')\n }\n }\n\n /**\n * handleData is called when the stream receives a data frame\n */\n handleData (frame: Frame): void {\n if (!isDataFrame(frame)) {\n throw new InvalidFrameError('Frame was not data frame')\n }\n\n this.processFlags(frame.header.flag)\n\n // check that our recv window is not exceeded\n if (this.recvWindowCapacity < frame.header.length) {\n throw new ReceiveWindowExceededError('Receive window exceeded')\n }\n\n this.recvWindowCapacity -= frame.header.length\n\n this.onData(frame.data)\n\n this.sendWindowUpdate()\n }\n\n /**\n * processFlags is used to update the state of the stream based on set flags, if any.\n */\n private processFlags (flags: number): void {\n if ((flags & Flag.ACK) === Flag.ACK) {\n if (this.state === StreamState.SYNSent) {\n this.state = StreamState.Established\n }\n }\n\n if ((flags & Flag.FIN) === Flag.FIN) {\n this.onRemoteCloseWrite()\n }\n\n if ((flags & Flag.RST) === Flag.RST) {\n this.onRemoteReset()\n }\n }\n\n /**\n * getSendFlags determines any flags that are appropriate\n * based on the current stream state.\n *\n * The state is updated as a side-effect.\n */\n private getSendFlags (): number {\n switch (this.state) {\n case StreamState.Init:\n this.state = StreamState.SYNSent\n return Flag.SYN\n case StreamState.SYNReceived:\n this.state = StreamState.Established\n return Flag.ACK\n default:\n return 0\n }\n }\n\n /**\n * Potentially sends a window update enabling further remote writes to take\n * place.\n */\n sendWindowUpdate (): void {\n if (this.state === StreamState.Paused) {\n // we don't want any more data from the remote right now - update the\n // epoch start as otherwise when we unpause we'd be looking at the epoch\n // start from before we were paused\n this.epochStart = Date.now()\n\n return\n }\n\n // determine the flags if any\n const flags = this.getSendFlags()\n\n // If the stream has already been established\n // and we've processed data within the time it takes for 4 round trips\n // then we (up to) double the recvWindow\n const now = Date.now()\n const rtt = this.getRTT()\n\n if (flags === 0 && rtt > -1 && (now - this.epochStart) <= (rtt * 4)) {\n // we've already validated that maxStreamWindowSize can't be more than MAX_UINT32\n this.recvWindow = Math.min(this.recvWindow * 2, this.maxStreamWindowSize)\n }\n\n if (this.recvWindowCapacity >= this.recvWindow && flags === 0) {\n // a window update isn't needed\n return\n }\n\n // update the receive window\n const delta = this.recvWindow - this.recvWindowCapacity\n this.recvWindowCapacity = this.recvWindow\n\n // update the epoch start\n this.epochStart = now\n\n // send window update\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: flags,\n streamID: this.streamId,\n length: delta\n })\n }\n}\n", "import { InvalidParametersError, MuxerClosedError, TooManyOutboundProtocolStreamsError, serviceCapabilities } from '@libp2p/interface'\nimport { AbstractStreamMuxer, repeatingTask } from '@libp2p/utils'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { defaultConfig, verifyConfig } from './config.js'\nimport { Decoder } from './decode.js'\nimport { encodeHeader } from './encode.js'\nimport { InvalidFrameError, isProtocolError, NotMatchingPingError, UnRequestedPingError } from './errors.js'\nimport { Flag, FrameType, GoAwayCode } from './frame.js'\nimport { StreamState, YamuxStream } from './stream.js'\nimport type { Config } from './config.js'\nimport type { Frame } from './decode.js'\nimport type { FrameHeader } from './frame.js'\nimport type { AbortOptions, MessageStream, StreamMuxerFactory } from '@libp2p/interface'\nimport type { RepeatingTask } from '@libp2p/utils'\n\nfunction debugFrame (header: FrameHeader): any {\n return {\n type: FrameType[header.type],\n flags: [\n (header.flag & Flag.SYN) === Flag.SYN ? 'SYN' : undefined,\n (header.flag & Flag.ACK) === Flag.ACK ? 'ACK' : undefined,\n (header.flag & Flag.FIN) === Flag.FIN ? 'FIN' : undefined,\n (header.flag & Flag.RST) === Flag.RST ? 'RST' : undefined\n ].filter(Boolean),\n streamID: header.streamID,\n length: header.length\n }\n}\n\nconst YAMUX_PROTOCOL_ID = '/yamux/1.0.0'\n\nexport interface YamuxMuxerInit extends Partial<Config> {\n}\n\nexport class Yamux implements StreamMuxerFactory {\n protocol = YAMUX_PROTOCOL_ID\n private readonly _init: Partial<Config>\n\n constructor (init: Partial<Config> = {}) {\n this._init = init\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/yamux'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/stream-multiplexing'\n ]\n\n createStreamMuxer (maConn: MessageStream): YamuxMuxer {\n return new YamuxMuxer(maConn, {\n ...this._init\n })\n }\n}\n\nexport interface CloseOptions extends AbortOptions {\n reason?: GoAwayCode\n}\n\nexport interface ActivePing extends PromiseWithResolvers<number> {\n id: number\n start: number\n}\n\nexport class YamuxMuxer extends AbstractStreamMuxer<YamuxStream> {\n /** The next stream id to be used when initiating a new stream */\n private nextStreamID: number\n\n /** The next ping id to be used when pinging */\n private nextPingID: number\n /** Tracking info for the currently active ping */\n private activePing?: ActivePing\n /** Round trip time */\n private rtt: number\n\n /** True if client, false if server */\n private client: boolean\n\n private localGoAway?: GoAwayCode\n private remoteGoAway?: GoAwayCode\n\n /** Number of tracked inbound streams */\n private numInboundStreams: number\n /** Number of tracked outbound streams */\n private numOutboundStreams: number\n\n private decoder: Decoder\n private keepAlive?: RepeatingTask\n\n private enableKeepAlive: boolean\n private keepAliveInterval: number\n private maxInboundStreams: number\n private maxOutboundStreams: number\n\n constructor (maConn: MessageStream, init: YamuxMuxerInit = {}) {\n super(maConn, {\n ...init,\n protocol: YAMUX_PROTOCOL_ID,\n name: 'yamux'\n })\n\n this.client = maConn.direction === 'outbound'\n verifyConfig(init)\n\n this.enableKeepAlive = init.enableKeepAlive ?? defaultConfig.enableKeepAlive\n this.keepAliveInterval = init.keepAliveInterval ?? defaultConfig.keepAliveInterval\n this.maxInboundStreams = init.maxInboundStreams ?? defaultConfig.maxInboundStreams\n this.maxOutboundStreams = init.maxOutboundStreams ?? defaultConfig.maxOutboundStreams\n\n this.decoder = new Decoder()\n\n this.numInboundStreams = 0\n this.numOutboundStreams = 0\n\n // client uses odd streamIDs, server uses even streamIDs\n this.nextStreamID = this.client ? 1 : 2\n\n this.nextPingID = 0\n this.rtt = -1\n\n this.log.trace('muxer created')\n\n if (this.enableKeepAlive) {\n this.log.trace('muxer keepalive enabled interval=%s', this.keepAliveInterval)\n this.keepAlive = repeatingTask(async (options) => {\n try {\n await this.ping(options)\n } catch (err: any) {\n // TODO: should abort here?\n this.log.error('ping error: %s', err)\n }\n }, this.keepAliveInterval, {\n // send an initial ping to establish RTT\n runImmediately: true\n })\n this.keepAlive.start()\n }\n }\n\n onData (buf: Uint8Array | Uint8ArrayList): void {\n for (const frame of this.decoder.emitFrames(buf)) {\n this.handleFrame(frame)\n }\n }\n\n onCreateStream (): YamuxStream {\n if (this.remoteGoAway !== undefined) {\n throw new MuxerClosedError('Muxer closed remotely')\n }\n\n if (this.localGoAway !== undefined) {\n throw new MuxerClosedError('Muxer closed locally')\n }\n\n const id = this.nextStreamID\n this.nextStreamID += 2\n\n // check against our configured maximum number of outbound streams\n if (this.numOutboundStreams >= this.maxOutboundStreams) {\n throw new TooManyOutboundProtocolStreamsError('max outbound streams exceeded')\n }\n\n this.log.trace('new outgoing stream id=%s', id)\n\n const stream = this._newStream(id, StreamState.Init, 'outbound')\n\n this.numOutboundStreams++\n\n // send a window update to open the stream on the receiver end. do this in a\n // microtask so the stream gets added to the streams array by the superclass\n // before we send the SYN flag, otherwise we create a race condition whereby\n // we can receive the ACK before the stream is added to the streams list\n queueMicrotask(() => {\n stream.sendWindowUpdate()\n })\n\n return stream\n }\n\n /**\n * Initiate a ping and wait for a response\n *\n * Note: only a single ping will be initiated at a time.\n * If a ping is already in progress, a new ping will not be initiated.\n *\n * @returns the round-trip-time in milliseconds\n */\n async ping (options?: AbortOptions): Promise<number> {\n if (this.remoteGoAway !== undefined) {\n throw new MuxerClosedError('Muxer closed remotely')\n }\n if (this.localGoAway !== undefined) {\n throw new MuxerClosedError('Muxer closed locally')\n }\n\n if (this.activePing != null) {\n // an active ping is already in progress, piggyback off that\n return raceSignal(this.activePing.promise, options?.signal)\n }\n\n // An active ping does not yet exist, handle the process here\n // create active ping\n this.activePing = Object.assign(Promise.withResolvers<number>(), {\n id: this.nextPingID++,\n start: Date.now()\n })\n // send ping\n this.sendPing(this.activePing.id)\n // await pong\n try {\n this.rtt = await raceSignal(this.activePing.promise, options?.signal)\n } finally {\n // clean-up active ping\n this.activePing = undefined\n }\n\n return this.rtt\n }\n\n /**\n * Get the ping round trip time\n *\n * Note: Will return 0 if no successful ping has yet been completed\n *\n * @returns the round-trip-time in milliseconds\n */\n getRTT (): number {\n return this.rtt\n }\n\n /**\n * Close the muxer\n */\n async close (options: CloseOptions = {}): Promise<void> {\n if (this.status !== 'open') {\n // already closed\n return\n }\n\n try {\n const reason = options?.reason ?? GoAwayCode.NormalTermination\n\n this.log.trace('muxer close reason=%s', GoAwayCode[reason])\n\n await super.close(options)\n\n // send reason to the other side, allow the other side to close gracefully\n this.sendGoAway(reason)\n } finally {\n this.keepAlive?.stop()\n }\n }\n\n abort (err: Error): void {\n if (this.status !== 'open') {\n // already closed\n return\n }\n\n try {\n super.abort(err)\n\n let reason = GoAwayCode.InternalError\n\n if (isProtocolError(err)) {\n reason = err.reason\n }\n\n // If reason was provided, use that, otherwise use the presence of `err` to determine the reason\n this.log.error('muxer abort reason=%s error=%s', reason, err)\n\n // send reason to the other side, allow the other side to close gracefully\n this.sendGoAway(reason)\n } finally {\n this.keepAlive?.stop()\n }\n }\n\n onTransportClosed (): void {\n try {\n super.onTransportClosed()\n } finally {\n this.keepAlive?.stop()\n }\n }\n\n /** Create a new stream */\n private _newStream (streamId: number, state: StreamState, direction: 'inbound' | 'outbound'): YamuxStream {\n if (this.streams.find(s => s.streamId === streamId) != null) {\n throw new InvalidParametersError('Stream already exists with that id')\n }\n\n const stream = new YamuxStream({\n ...this.streamOptions,\n id: `${streamId}`,\n streamId,\n state,\n direction,\n sendFrame: this.sendFrame.bind(this),\n log: this.log.newScope(`${direction}:${streamId}`),\n getRTT: this.getRTT.bind(this)\n })\n\n stream.addEventListener('close', () => {\n this.closeStream(streamId)\n }, {\n once: true\n })\n\n return stream\n }\n\n /**\n * closeStream is used to close a stream once both sides have\n * issued a close.\n */\n private closeStream (id: number): void {\n if (this.client === (id % 2 === 0)) {\n this.numInboundStreams--\n } else {\n this.numOutboundStreams--\n }\n }\n\n private handleFrame (frame: Frame): void {\n const {\n streamID,\n type,\n length\n } = frame.header\n\n this.log.trace('received frame %o', debugFrame(frame.header))\n\n if (streamID === 0) {\n switch (type) {\n case FrameType.Ping:\n { this.handlePing(frame.header); return }\n case FrameType.GoAway:\n { this.handleGoAway(length); return }\n default:\n // Invalid state\n throw new InvalidFrameError('Invalid frame type')\n }\n } else {\n switch (frame.header.type) {\n case FrameType.Data:\n case FrameType.WindowUpdate:\n { this.handleStreamMessage(frame); return }\n default:\n // Invalid state\n throw new InvalidFrameError('Invalid frame type')\n }\n }\n }\n\n private handlePing (header: FrameHeader): void {\n // If the ping is initiated by the sender, send a response\n if (header.flag === Flag.SYN) {\n this.log.trace('received ping request pingId=%s', header.length)\n this.sendPing(header.length, Flag.ACK)\n } else if (header.flag === Flag.ACK) {\n this.log.trace('received ping response pingId=%s', header.length)\n this.handlePingResponse(header.length)\n } else {\n // Invalid state\n throw new InvalidFrameError('Invalid frame flag')\n }\n }\n\n private handlePingResponse (pingId: number): void {\n if (this.activePing === undefined) {\n // this ping was not requested\n throw new UnRequestedPingError('ping not requested')\n }\n if (this.activePing.id !== pingId) {\n // this ping doesn't match our active ping request\n throw new NotMatchingPingError('ping doesn\\'t match our id')\n }\n\n // valid ping response\n this.activePing.resolve(Date.now() - this.activePing.start)\n }\n\n private handleGoAway (reason: GoAwayCode): void {\n this.log.trace('received GoAway reason=%s', GoAwayCode[reason] ?? 'unknown')\n this.remoteGoAway = reason\n\n if (reason === GoAwayCode.NormalTermination) {\n this.onTransportClosed()\n } else {\n // reset any streams that are still open and close the muxer\n this.abort(new Error('Remote sent GoAway'))\n }\n }\n\n private handleStreamMessage (frame: Frame): void {\n const { streamID, flag, type } = frame.header\n\n if ((flag & Flag.SYN) === Flag.SYN) {\n this.incomingStream(streamID)\n }\n\n const stream = this.streams.find(s => s.streamId === streamID)\n if (stream === undefined) {\n this.log.trace('frame for missing stream id=%s', streamID)\n\n return\n }\n\n switch (type) {\n case FrameType.WindowUpdate: {\n stream.handleWindowUpdate(frame); return\n }\n case FrameType.Data: {\n stream.handleData(frame); return\n }\n default:\n throw new Error('unreachable')\n }\n }\n\n private incomingStream (id: number): void {\n if (this.client !== (id % 2 === 0)) {\n throw new InvalidParametersError('Both endpoints are clients')\n }\n if (this.streams.find(s => s.streamId === id)) {\n return\n }\n\n this.log.trace('new incoming stream id=%s', id)\n\n if (this.localGoAway !== undefined) {\n // reject (reset) immediately if we are doing a go away\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: Flag.RST,\n streamID: id,\n length: 0\n })\n return\n }\n\n // check against our configured maximum number of inbound streams\n if (this.numInboundStreams >= this.maxInboundStreams) {\n this.log('maxIncomingStreams exceeded, forcing stream reset')\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: Flag.RST,\n streamID: id,\n length: 0\n })\n return\n }\n\n // allocate a new stream\n const stream = this._newStream(id, StreamState.SYNReceived, 'inbound')\n\n this.numInboundStreams++\n\n // the stream should now be tracked\n this.onRemoteStream(stream)\n }\n\n private sendFrame (header: FrameHeader, data?: Uint8ArrayList): boolean {\n let encoded: Uint8Array | Uint8ArrayList\n\n if (header.type === FrameType.Data) {\n if (data == null) {\n throw new InvalidFrameError('Invalid frame')\n }\n\n encoded = new Uint8ArrayList(encodeHeader(header), data)\n } else {\n encoded = encodeHeader(header)\n }\n\n this.log.trace('sending frame %o', debugFrame(header))\n\n return this.send(encoded)\n }\n\n private sendPing (pingId: number, flag: Flag = Flag.SYN): void {\n if (flag === Flag.SYN) {\n this.log.trace('sending ping request pingId=%s', pingId)\n } else {\n this.log.trace('sending ping response pingId=%s', pingId)\n }\n this.sendFrame({\n type: FrameType.Ping,\n flag,\n streamID: 0,\n length: pingId\n })\n }\n\n private sendGoAway (reason: GoAwayCode = GoAwayCode.NormalTermination): void {\n this.log('sending GoAway reason=%s', GoAwayCode[reason])\n this.localGoAway = reason\n this.sendFrame({\n type: FrameType.GoAway,\n flag: 0,\n streamID: 0,\n length: reason\n })\n }\n}\n"],
5
- "mappings": ";6cAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,gBAAAE,EAAA,UAAAC,KCyCM,IAAOC,EAAP,cAAsC,KAAK,CAC/C,OAAO,KAAO,yBAEd,YAAaC,EAAU,qBAAoB,CACzC,MAAMA,CAAO,EACb,KAAK,KAAO,wBACd,GA8EI,IAAOC,EAAP,cAAgC,KAAK,CACzC,OAAO,KAAO,mBAEd,YAAaC,EAAU,sBAAqB,CAC1C,MAAMA,CAAO,EACb,KAAK,KAAO,kBACd,GAMWC,EAAP,cAAgC,KAAK,CACzC,OAAO,KAAO,mBAEd,YAAaD,EAAU,4BAA2B,CAChD,MAAMA,CAAO,EACb,KAAK,KAAO,kBACd,GAkBI,IAAOE,EAAP,cAAgC,KAAK,CACzC,OAAO,KAAO,mBAEd,YAAaC,EAAU,oCAAmC,CACxD,MAAMA,CAAO,EACb,KAAK,KAAO,kBACd,GAMWC,EAAP,cAAiC,KAAK,CAC1C,OAAO,KAAO,oBAEd,YAAaD,EAAU,6BAA4B,CACjD,MAAMA,CAAO,EACb,KAAK,KAAO,mBACd,GA8LI,IAAOE,EAAP,cAAmD,KAAK,CAC5D,OAAO,KAAO,sCAEd,YAAaC,EAAU,qCAAoC,CACzD,MAAMA,CAAO,EACb,KAAK,KAAO,qCACd,GCjXI,IAAOC,EAAP,cAAkC,KAAK,CACpC,KAEP,YAAaC,EAAmCC,EAAyB,CACvE,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J,GAAI1C,EAAO,OAASC,EAAU,KAAM,CAClC,GAAIwC,GAAQ,KACV,MAAM,IAAIL,EAAkB,eAAe,EAG7CM,EAAU,IAAIC,EAAeC,GAAa5C,CAAM,EAAGyC,CAAI,CACzD,MACEC,EAAUE,GAAa5C,CAAM,EAG/B,YAAK,IAAI,MAAM,mBAAoBD,GAAWC,CAAM,CAAC,EAE9C,KAAK,KAAK0C,CAAO,CAC1B,CAEQ,SAAUL,EAAgBG,EAAatC,EAAK,IAAG,CACjDsC,IAAStC,EAAK,IAChB,KAAK,IAAI,MAAM,iCAAkCmC,CAAM,EAEvD,KAAK,IAAI,MAAM,kCAAmCA,CAAM,EAE1D,KAAK,UAAU,CACb,KAAMpC,EAAU,KAChB,KAAAuC,EACA,SAAU,EACV,OAAQH,EACT,CACH,CAEQ,WAAYb,EAAqBC,EAAW,kBAAiB,CACnE,KAAK,IAAI,2BAA4BA,EAAWD,CAAM,CAAC,EACvD,KAAK,YAAcA,EACnB,KAAK,UAAU,CACb,KAAMvB,EAAU,OAChB,KAAM,EACN,SAAU,EACV,OAAQuB,EACT,CACH,G9BlaI,SAAUqB,GAAOC,EAAuB,CAAA,EAAE,CAC9C,MAAO,IAAM,IAAIC,GAAMD,CAAI,CAC7B",
6
- "names": ["index_exports", "__export", "GoAwayCode", "yamux", "InvalidParametersError", "message", "MuxerClosedError", "message", "StreamResetError", "StreamStateError", "message", "StreamBufferError", "TooManyOutboundProtocolStreamsError", "message", "StreamMessageEvent", "data", "eventInitDict", "StreamCloseEvent", "local", "error", "StreamAbortEvent", "StreamResetEvent", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "options", "list", "callback", "event", "result", "once", "detail", "serviceCapabilities", "serviceDependencies", "equals", "a", "b", "i", "alloc", "size", "allocUnsafe", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "_Uint8ArrayList", "data", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "pDefer", "deferred", "resolve", "reject", "FixedFIFO", "hwm", "data", "last", "FIFO", "options", "obj", "val", "prev", "next", "AbortError", "message", "code", "pushable", "options", "_pushable", "buffer", "next", "_pushable", "getNext", "options", "onEnd", "buffer", "FIFO", "pushable", "onNext", "ended", "drain", "pDefer", "waitNext", "resolve", "reject", "next", "err", "bufferNext", "bufferError", "push", "value", "end", "_return", "_throw", "signal", "cancel", "listener", "AbortError", "opts", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "options", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "normalizeEmitter", "emitter", "addListener", "removeListener", "pEventMultiple", "event", "options", "cancel", "returnValue", "resolve", "reject", "events", "items", "onItem", "arguments_", "value", "error", "rejectHandler", "rejectionEvent", "timeout", "pTimeout", "pEvent", "arrayPromise", "promise", "array", "debounce", "func", "wait", "timeout", "output", "later", "MaxEarlyStreamsError", "defaultTranslate", "signal", "raceSignal", "promise", "opts", "translateError", "listener", "resolve", "reject", "DEFAULT_MAX_READ_BUFFER_LENGTH", "AbstractMessageStream", "TypedEventEmitter", "init", "Uint8ArrayList", "continueSendingOnDrain", "output", "pushable", "streamAsyncIterableOnMessageListener", "evt", "streamAsyncIterableOnCloseListener", "streamAsyncIterableOnRemoteCloseWriteListener", "data", "StreamStateError", "err", "StreamAbortEvent", "args", "StreamResetError", "StreamResetEvent", "StreamCloseEvent", "canSendMore", "totalBytes", "sentBytes", "end", "toSend", "willSend", "sendResult", "buf", "StreamMessageEvent", "StreamBufferError", "isPromise", "thing", "AbstractStreamMuxer", "TypedEventEmitter", "maConn", "init", "muxerMaConnOnMessage", "evt", "err", "muxerMaConnOnDrain", "stream", "muxerOnMaConnClose", "data", "result", "options", "raceSignal", "s", "MuxerClosedError", "isPromise", "MaxEarlyStreamsError", "muxerOnStreamEnd", "index", "args", "AbstractStream", "AbstractMessageStream", "init", "options", "pEvent", "anySignal", "signals", "controller", "onAbort", "signal", "clear", "repeatingTask", "fn", "interval", "options", "timeout", "shutdownController", "running", "runTask", "opts", "signal", "anySignal", "runTaskDebounced", "debounce", "started", "ms", "FrameType", "Flag", "flagCodes", "x", "YAMUX_VERSION", "GoAwayCode", "HEADER_LENGTH", "ProtocolError", "message", "reason", "isProtocolError", "err", "InvalidFrameError", "GoAwayCode", "UnRequestedPingError", "NotMatchingPingError", "StreamAlreadyExistsError", "ProtocolError", "message", "GoAwayCode", "DecodeInvalidVersionError", "BothClientsError", "ReceiveWindowExceededError", "PROTOCOL_ERRORS", "InvalidFrameError", "UnRequestedPingError", "NotMatchingPingError", "StreamAlreadyExistsError", "DecodeInvalidVersionError", "BothClientsError", "ReceiveWindowExceededError", "INITIAL_STREAM_WINDOW", "MAX_STREAM_WINDOW", "defaultConfig", "INITIAL_STREAM_WINDOW", "MAX_STREAM_WINDOW", "verifyConfig", "config", "InvalidParametersError", "isDataFrame", "frame", "FrameType", "twoPow24", "decodeHeader", "data", "YAMUX_VERSION", "InvalidFrameError", "Decoder", "Uint8ArrayList", "buf", "frameSize", "HEADER_LENGTH", "header", "encodeHeader", "header", "frame", "HEADER_LENGTH", "StreamState", "YamuxStream", "AbstractStream", "init", "initialWindowSize", "INITIAL_STREAM_WINDOW", "HEADER_LENGTH", "MAX_STREAM_WINDOW", "setStateToFinishedOnCloseListener", "buf", "totalBytes", "sentBytes", "canSendMore", "toSend", "flags", "data", "muxerSendMore", "FrameType", "Flag", "options", "frame", "isDataFrame", "InvalidFrameError", "ReceiveWindowExceededError", "now", "rtt", "delta", "debugFrame", "header", "FrameType", "Flag", "YAMUX_PROTOCOL_ID", "Yamux", "init", "serviceCapabilities", "maConn", "YamuxMuxer", "AbstractStreamMuxer", "verifyConfig", "defaultConfig", "Decoder", "repeatingTask", "options", "err", "buf", "frame", "MuxerClosedError", "id", "TooManyOutboundProtocolStreamsError", "stream", "StreamState", "raceSignal", "reason", "GoAwayCode", "isProtocolError", "streamId", "state", "direction", "s", "InvalidParametersError", "YamuxStream", "streamID", "type", "length", "InvalidFrameError", "pingId", "UnRequestedPingError", "NotMatchingPingError", "flag", "data", "encoded", "Uint8ArrayList", "encodeHeader", "yamux", "init", "Yamux"]
3
+ "sources": ["../src/index.ts", "../../interface/src/errors.ts", "../../interface/src/events.ts", "../../../node_modules/main-event/src/index.ts", "../../interface/src/index.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8arrays/src/util/as-uint8array.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/uint8arraylist/src/index.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/it-pushable/src/fifo.ts", "../../../node_modules/it-pushable/src/index.ts", "../../../node_modules/p-timeout/index.js", "../../../node_modules/p-event/index.js", "../../utils/src/debounce.ts", "../../utils/src/errors.ts", "../../../node_modules/race-signal/src/index.ts", "../../utils/src/abstract-message-stream.ts", "../../utils/src/is-promise.ts", "../../utils/src/abstract-stream-muxer.ts", "../../utils/src/abstract-stream.ts", "../../../node_modules/any-signal/src/index.ts", "../../utils/src/repeating-task.ts", "../src/frame.ts", "../src/errors.ts", "../src/constants.ts", "../src/config.ts", "../src/decode.ts", "../src/encode.ts", "../src/stream.ts", "../src/muxer.ts"],
4
+ "sourcesContent": ["/**\n * @packageDocumentation\n *\n * This module is a JavaScript implementation of [Yamux from Hashicorp](https://github.com/hashicorp/yamux/blob/master/spec.md) designed to be used with [js-libp2p](https://github.com/libp2p/js-libp2p).\n *\n * Formerly published as [`@chainsafe/libp2p-yamux`](https://www.npmjs.com/package/@chainsafe/libp2p-yamux).\n *\n * @example Configure libp2p with Yamux\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { yamux } from '@libp2p/yamux'\n *\n * const node = await createLibp2p({\n * // ... other options\n * streamMuxers: [\n * yamux()\n * ]\n * })\n * ```\n *\n * @example Using the low-level API\n *\n * ```typescript\n * import { yamux } from '@libp2p/yamux'\n * import { multiaddrConnectionPair } from '@libp2p/utils'\n *\n * // a pair of connected multiaddr connections - in a real application these\n * // would be the two ends of a network connection\n * const [outboundConnection, inboundConnection] = multiaddrConnectionPair()\n *\n * const clientMuxer = yamux()().createStreamMuxer(outboundConnection)\n * const serverMuxer = yamux()().createStreamMuxer(inboundConnection)\n *\n * // echo incoming data back on the server side\n * serverMuxer.addEventListener('stream', (evt) => {\n * const stream = evt.detail\n *\n * stream.addEventListener('message', (msg) => {\n * stream.send(msg.data)\n * })\n * })\n *\n * // open a stream from the client and send some data\n * const stream = await clientMuxer.createStream()\n *\n * const received = new Promise<string>((resolve) => {\n * stream.addEventListener('message', (msg) => {\n * resolve(new TextDecoder().decode(msg.data.subarray()))\n * })\n * })\n *\n * stream.send(new TextEncoder().encode('hello world'))\n *\n * console.info(await received)\n * // -> hello world\n *\n * await stream.close()\n * await clientMuxer.close()\n * await serverMuxer.close()\n * ```\n */\n\nimport { Yamux } from './muxer.ts'\nimport type { YamuxMuxer, YamuxMuxerInit } from './muxer.ts'\nimport type { StreamMuxerFactory } from '@libp2p/interface'\n\nexport { GoAwayCode } from './frame.ts'\nexport type { FrameHeader, FrameType } from './frame.ts'\nexport type { YamuxMuxerInit }\n\nexport function yamux (init: YamuxMuxerInit = {}): () => StreamMuxerFactory<YamuxMuxer> {\n return () => new Yamux(init)\n}\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError'\n\n constructor (message = 'The stream has been aborted') {\n super(message)\n this.name = 'StreamAbortedError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError'\n\n constructor (message = 'The stream buffer was full') {\n super(message)\n this.name = 'StreamBufferError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\n\n/**\n * A custom implementation of MessageEvent as the Undici version does too much\n * validation in it's constructor so is very slow.\n */\nexport class StreamMessageEvent extends Event {\n public data: Uint8Array | Uint8ArrayList\n\n constructor (data: Uint8Array | Uint8ArrayList, eventInitDict?: EventInit) {\n super('message', eventInitDict)\n\n this.data = data\n }\n}\n\n/**\n * An event dispatched when the stream is closed. The `error` property can be\n * inspected to discover if the closing was graceful or not, and the `local`\n * property shows which end of the stream initiated the closure\n */\nexport class StreamCloseEvent extends Event {\n public error?: Error\n public local?: boolean\n\n constructor (local?: boolean, error?: Error, eventInitDict?: EventInit) {\n super('close', eventInitDict)\n\n this.error = error\n this.local = local\n }\n}\n\nexport class StreamAbortEvent extends StreamCloseEvent {\n constructor (error: Error, eventInitDict?: EventInit) {\n super(true, error, eventInitDict)\n }\n}\n\nexport class StreamResetEvent extends StreamCloseEvent {\n constructor (error: Error, eventInitDict?: EventInit) {\n super(false, error, eventInitDict)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Adds types to the EventTarget class.\n *\n * Hopefully this won't be necessary\n * forever:\n *\n * - https://github.com/microsoft/TypeScript/issues/28357\n * - https://github.com/microsoft/TypeScript/issues/43477\n * - https://github.com/microsoft/TypeScript/issues/299\n * - https://www.npmjs.com/package/typed-events\n * - https://www.npmjs.com/package/typed-event-emitter\n * - https://www.npmjs.com/package/typed-event-target\n * - etc\n *\n * In addition to types, a `safeDispatchEvent` method is available which\n * prevents dispatching events that aren't in the event map, and a\n * `listenerCount` method which reports the number of listeners that are\n * currently registered for a given event.\n *\n * @example\n *\n * ```ts\n * import { TypedEventEmitter } from 'main-event'\n * import type { TypedEventTarget } from 'main-event'\n *\n * interface EventTypes {\n * 'test': CustomEvent<string>\n * }\n *\n * const target = new TypedEventEmitter<EventTypes>()\n *\n * // it's a regular EventTarget\n * console.info(target instanceof EventTarget) // true\n *\n * // register listeners normally\n * target.addEventListener('test', (evt) => {\n * // evt is CustomEvent<string>\n * })\n *\n * // @ts-expect-error 'derp' is not in the event map\n * target.addEventListener('derp', () => {})\n *\n * // use normal dispatchEvent method\n * target.dispatchEvent(new CustomEvent('test', {\n * detail: 'hello'\n * }))\n *\n * // use type safe dispatch method\n * target.safeDispatchEvent('test', {\n * detail: 'world'\n * })\n *\n * // report listener count\n * console.info(target.listenerCount('test')) // 0\n *\n * // event emitters can be used purely as interfaces too\n * function acceptTarget (target: TypedEventTarget<EventTypes>) {\n * // ...\n * }\n * ```\n */\n\nimport { setMaxListeners } from './events.ts'\n\nexport interface EventCallback<EventType> { (evt: EventType): void }\nexport interface EventObject<EventType> { handleEvent: EventCallback<EventType> }\nexport type EventHandler<EventType> = EventCallback<EventType> | EventObject<EventType>\n\ninterface Listener {\n /**\n * The original listener\n */\n callback: any\n\n /**\n * The function actually registered with the native EventTarget. `callback` is\n * never registered directly, so this is what has to be passed to\n * `super.removeEventListener` for the listener to be detached.\n */\n wrapper: EventCallback<Event>\n\n /**\n * Event listener options normalized according to https://dom.spec.whatwg.org/#event-flatten-more\n */\n options: AddEventListenerOptions\n\n /**\n * Callback function added to any passed signal\n */\n onAbort(): void\n}\n\n/**\n * An event target with a typed map of supported events\n */\nexport interface TypedEventTarget <EventMap extends Record<string, any>> extends EventTarget {\n /**\n * Add a listener for an event\n */\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n\n /**\n * Returns the number of listeners for the event type\n */\n listenerCount (type: string): number\n\n /**\n * Remove a listener previously registered for an event\n */\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void\n\n /**\n * Type-safe version of `EventTarget.dispatchEvent` - only events from the event map are supported.\n *\n * Attempting to dispatch an unsupported event results in a TypeScript compilation error.\n */\n safeDispatchEvent<Detail>(type: keyof EventMap, detail?: CustomEventInit<Detail>): boolean\n}\n\nfunction isEventObject <EventType> (obj?: any): obj is EventObject<EventType> {\n return typeof obj?.handleEvent === 'function'\n}\n\n/**\n * Returns true if the passed argument is a boolean value\n */\nfunction isBoolean (obj?: any): obj is boolean {\n return obj === true || obj === false\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#concept-flatten-options\n */\nfunction flattenOptions (options?: any): boolean {\n if (isBoolean(options)) {\n return options\n }\n\n return options?.capture ?? false\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#event-flatten-more\n */\nfunction flattenMoreOptions (options?: any): AddEventListenerOptions {\n const opts: AddEventListenerOptions = {\n capture: flattenOptions(options),\n once: Boolean(options?.once)\n }\n\n if (options?.passive != null) {\n opts.passive = options?.passive\n }\n\n if (options?.signal != null) {\n opts.signal = options?.signal\n }\n\n return opts\n}\n\n/**\n * Returns true if the capture/useCapture arg of each opts are equal\n */\nfunction captureIsEqual (optsA?: boolean | AddEventListenerOptions, optsB?: boolean | EventListenerOptions): boolean {\n return flattenMoreOptions(optsA).capture === flattenMoreOptions(optsB).capture\n}\n\n/**\n * An implementation of a typed event target\n */\nexport class TypedEventEmitter<EventMap extends Record<string, any>> extends EventTarget implements TypedEventTarget<EventMap> {\n readonly #listeners = new Map<any, Listener[]>()\n\n constructor () {\n super()\n\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this)\n }\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, opts?: boolean | AddEventListenerOptions): void {\n const options = flattenMoreOptions(opts)\n\n if (options?.signal?.aborted === true) {\n return\n }\n\n // the wrapper - and not `listener` - is what is registered with the native\n // EventTarget, so a reference to it must be kept in order to be able to\n // remove it again later\n const wrapper = (evt: Event): void => {\n if (options.once) {\n this.removeEventListener(type, listener, options)\n }\n\n if (isEventObject<Event>(listener)) {\n listener.handleEvent(evt)\n } else {\n listener(evt)\n }\n }\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n // if there is already an entry in the list for the same type, callback and\n // capture value, listening again is a no-op\n // @see https://dom.spec.whatwg.org/#add-an-event-listener\n const alreadyListening = list.some(entry => {\n if (entry.callback !== listener) {\n return false\n }\n\n // listener is already present, check capture options\n return captureIsEqual(entry.options, options)\n })\n\n if (alreadyListening) {\n return\n }\n\n super.addEventListener(type, wrapper, options)\n\n const onAbort = (): void => {\n this.removeEventListener(type, listener, options)\n }\n options.signal?.addEventListener('abort', onAbort)\n\n list.push({\n callback: listener,\n wrapper,\n options,\n onAbort\n })\n }\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void {\n const list = this.#listeners.get(type)\n\n if (list == null) {\n super.removeEventListener(type, listener ?? null, options)\n return\n }\n\n this.#listeners.set(type, list.filter(entry => {\n // listeners are the same so we need to check the capture argument\n if (entry.callback === listener && captureIsEqual(entry.options, options)) {\n super.removeEventListener(type, entry.wrapper, options)\n\n // remove abort signal abort event listener if set\n entry.options?.signal?.removeEventListener('abort', entry.onAbort)\n\n return false\n }\n\n return true\n }))\n }\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail: CustomEventInit<Detail> = {}): boolean {\n return this.dispatchEvent(new CustomEvent<Detail>(type as string, detail))\n }\n}\n\nexport { setMaxListeners }\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions, NewStreamProgressEvents } from './connection.ts'\nimport type { ContentRouting } from './content-routing.ts'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.ts'\nimport type { Metrics } from './metrics.ts'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.ts'\nimport type { PeerInfo } from './peer-info.ts'\nimport type { PeerRouting } from './peer-routing.ts'\nimport type { Address, Peer, PeerStore } from './peer-store.ts'\nimport type { Startable } from './startable.ts'\nimport type { StreamHandler, StreamHandlerOptions, StreamMiddleware } from './stream-handler.ts'\nimport type { Stream } from './stream.ts'\nimport type { Topology } from './topology.ts'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.ts'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * Things that libp2p can dial\n */\nexport type DialTarget = PeerId | Multiaddr | Multiaddr[]\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from '@libp2p/logger'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport interface MultiaddrResolveOptions extends AbortOptions, LoggerOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n}\n\n/**\n * `MultiaddrResolver`s perform resolution of multiaddr components that require\n * translation by external systems (for example DNSADDR to TXT records).\n */\nexport interface MultiaddrResolver {\n /**\n * Returns true if this resolver can resolve components of this multiaddr\n */\n canResolve (address: Multiaddr): boolean\n\n /**\n * Returns one or more multiaddrs with components resolved to other values\n */\n resolve (address: Multiaddr, options: MultiaddrResolveOptions): Promise<Multiaddr[]>\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n start: CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n stop: CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n ProgressEvent<'connection:open', DialTarget> |\n ProgressEvent<'connection:opened', Connection> |\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions<OpenConnectionProgressEvents> {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends Omit<DialOptions, 'onProgress'>, Omit<NewStreamOptions, 'onProgress'>, ProgressOptions<OpenConnectionProgressEvents | NewStreamProgressEvents> {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: DialTarget, options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: DialTarget, protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string, options?: AbortOptions): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology, options?: AbortOptions): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Registers one or more middleware implementations that will be invoked for\n * incoming and outgoing protocol streams that match the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {\n * // do something with stream and/or connection\n * next(stream, connection)\n * })\n * ```\n */\n use (protocol: string, middleware: StreamMiddleware | StreamMiddleware[]): void\n\n /**\n * Deregisters all middleware for the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unuse('/my/protocol/1.0.0')\n * // any previously registered middleware will no longer be invoked\n * ```\n */\n unuse (protocol: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.ts'\nexport * from './connection-encrypter.ts'\nexport * from './connection-gater.ts'\nexport * from './connection-protector.ts'\nexport * from './content-routing.ts'\nexport * from './errors.ts'\nexport * from './events.ts'\nexport * from './keys.ts'\nexport * from './message-stream.ts'\nexport * from './metrics.ts'\nexport * from './multiaddr-connection.ts'\nexport * from './peer-discovery.ts'\nexport * from './peer-id.ts'\nexport * from './peer-info.ts'\nexport * from './peer-routing.ts'\nexport * from './peer-store.ts'\nexport * from './record.ts'\nexport * from './startable.ts'\nexport * from './stream-handler.ts'\nexport * from './stream-muxer.ts'\nexport * from './stream.ts'\nexport * from './topology.ts'\nexport * from './transport.ts'\n\nexport * from 'main-event'\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array<ArrayBuffer> {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array<ArrayBuffer> {\n return new Uint8Array(size)\n}\n", "function isByteArrayWithArrayBuffer (b?: Uint8Array): b is Uint8Array<ArrayBuffer> {\n return b?.buffer instanceof ArrayBuffer\n}\n\n/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array<ArrayBuffer> {\n if (isByteArrayWithArrayBuffer(buf)) {\n return buf\n }\n\n const b = buf.slice()\n\n return new Uint8Array(b.buffer, 0, b.byteLength)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array<ArrayBuffer> {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable<T extends ArrayBufferLike = ArrayBuffer> = Uint8ArrayList<T> | Uint8Array<T>\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList <T extends ArrayBufferLike = ArrayBufferLike> implements Iterable<Uint8Array<T>> {\n private bufs: Uint8Array<T>[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable<T>[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array<T>> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable<T>[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable<T>[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n for (const chunk of buf.bufs) {\n this.bufs.push(chunk)\n }\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable<T>[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable<T>[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable<T | ArrayBuffer>, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array<ArrayBuffer> {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a section of the array from the given start and end element index.\n *\n * This is a no-copy operation where the data extracted data comes from a\n * single Uint8Array internally, otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array<T | ArrayBuffer> {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a new Uint8ArrayList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList<T> {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList<T>()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = bufs\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array<T>[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: [...this.bufs], length: this.length }\n }\n\n const bufs: Uint8Array<T>[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays <T extends ArrayBufferLike> (bufs: Uint8Array<T>[], length?: number): Uint8ArrayList<T> {\n const list = new Uint8ArrayList<T>()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nexport interface Next<T> {\n done?: boolean\n error?: Error\n value?: T\n}\n\nclass FixedFIFO<T> {\n public buffer: Array<Next<T> | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO<T> | null\n\n constructor (hwm: number) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two')\n }\n\n this.buffer = new Array(hwm)\n this.mask = hwm - 1\n this.top = 0\n this.btm = 0\n this.next = null\n }\n\n push (data: Next<T>): boolean {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift (): Next<T> | undefined {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty (): boolean {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO<T> {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO<T>\n private tail: FixedFIFO<T>\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO<T>(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next<T>): void {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\n\n if (!this.head.push(val)) {\n const prev = this.head\n this.head = prev.next = new FixedFIFO<T>(2 * this.head.buffer.length)\n this.head.push(val)\n }\n }\n\n shift (): Next<T> | undefined {\n let val = this.tail.shift()\n\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next\n this.tail.next = null\n this.tail = next\n val = this.tail.shift()\n }\n\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty (): boolean {\n return this.head.isEmpty()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { FIFO } from './fifo.ts'\nimport type { Next } from './fifo.ts'\n\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\ninterface BasePushable<T> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error): this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T): this\n\n /**\n * Returns a promise that resolves when the underlying queue becomes empty (e.g.\n * this.readableLength === 0).\n *\n * If an AbortSignal is passed as an option and that signal aborts, it only\n * causes the returned promise to reject - it does not end the pushable.\n */\n onEmpty(options?: AbortOptions): Promise<void>\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable<T, R = void, N = unknown> extends AsyncGenerator<T, R, N>, BasePushable<T> {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV<T, R = void, N = unknown> extends AsyncGenerator<T[], R, N>, BasePushable<T> {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?(err?: Error): void\n}\n\nexport interface DoneResult { done: true }\nexport interface ValueResult<T> { done: false, value: T }\nexport type NextResult<T> = ValueResult<T> | DoneResult\n\ninterface getNext<T, V = T> { (buffer: FIFO<T>): NextResult<V> }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): Pushable<T>\nexport function pushable<T> (options: ObjectPushableOptions): Pushable<T>\nexport function pushable<T> (options: Options = {}): Pushable<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T> => {\n const next: Next<T> | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n }\n }\n\n return _pushable<T, T, Pushable<T>>(getNext, options)\n}\n\nexport function pushableV<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): PushableV<T>\nexport function pushableV<T> (options: ObjectPushableOptions): PushableV<T>\nexport function pushableV<T> (options: Options = {}): PushableV<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T[]> => {\n let next: Next<T> | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value)\n }\n }\n\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable<T, T[], PushableV<T>>(getNext, options)\n}\n\nfunction _pushable<PushType, ValueType, ReturnType> (getNext: getNext<PushType, ValueType>, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO<PushType>()\n let pushable: any\n let onNext: ((next: Next<PushType>) => ReturnType) | null\n let ended: boolean\n let drain = deferred()\n\n const waitNext = async (): Promise<NextResult<ValueType>> => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise<NextResult<ValueType>>((resolve, reject) => {\n onNext = (next: Next<PushType>) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\n }\n })\n } finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve()\n drain = deferred()\n })\n }\n }\n }\n\n const bufferNext = (next: Next<PushType>): ReturnType => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error): ReturnType => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType): ReturnType => {\n if (ended) {\n return pushable\n }\n\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value')\n }\n\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error): ReturnType => {\n if (ended) { return pushable }\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = (): DoneResult => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error): DoneResult => {\n end(err)\n\n return { done: true }\n }\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength (): number {\n return buffer.size\n },\n onEmpty: async (options?: AbortOptions) => {\n const signal = options?.signal\n signal?.throwIfAborted()\n\n if (buffer.isEmpty()) {\n return\n }\n\n let cancel: Promise<void> | undefined\n let listener: (() => void) | undefined\n\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError())\n }\n\n signal.addEventListener('abort', listener)\n })\n }\n\n try {\n await Promise.race([\n drain.promise,\n cancel\n ])\n } finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener)\n }\n }\n }\n }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n },\n onEmpty: (opts?: AbortOptions) => {\n return _pushable.onEmpty(opts)\n }\n }\n\n return pushable\n}\n", "export class TimeoutError extends Error {\n\tname = 'TimeoutError';\n\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tError.captureStackTrace?.(this, TimeoutError);\n\t}\n}\n\nconst getAbortedReason = signal => signal.reason ?? new DOMException('This operation was aborted.', 'AbortError');\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t\tsignal,\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (signal?.aborted) {\n\t\t\treject(getAbortedReason(signal));\n\t\t\treturn;\n\t\t}\n\n\t\tif (signal) {\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\t// Use .then() instead of async IIFE to preserve stack traces\n\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-catch\n\t\tpromise.then(resolve, reject);\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\t});\n\n\t// eslint-disable-next-line promise/prefer-await-to-then\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && signal) {\n\t\t\tsignal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n", "import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.addEventListener || emitter.on || emitter.addListener;\n\tconst removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\trejectionMultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = async (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\tif (options.filter) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = (...arguments_) => {\n\t\t\tcancel();\n\t\t\treject(options.rejectionMultiArgs ? arguments_ : arguments_[0]);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\t// Only remove rejection handler if we actually registered it\n\t\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t// Skip registering rejection handler if we're already listening to this event\n\t\t\t// as the main event takes priority (as documented)\n\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener('abort', () => {\n\t\t\t\trejectHandler(options.signal.reason);\n\t\t\t}, {once: true});\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\t// When cancelling, also clear the timeout timer\n\t\ttimeout.cancel = () => {\n\t\t\tcancel();\n\t\t\ttimeout.clear();\n\t\t};\n\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\trejectionMultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.rejectionMultiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = async (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (options.filter) {\n\t\t\ttry {\n\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (filterError) {\n\t\t\t\tcancel();\n\t\t\t\tif (nextQueue.length > 0) {\n\t\t\t\t\tconst {reject} = nextQueue.shift();\n\t\t\t\t\treject(filterError);\n\t\t\t\t} else {\n\t\t\t\t\t// Store error for next iterator call\n\t\t\t\t\thasPendingError = true;\n\t\t\t\t\terror = filterError;\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\tif (options.signal) {\n\t\toptions.signal.addEventListener('abort', () => {\n\t\t\trejectHandler(options.signal.reason);\n\t\t}, {once: true});\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n", "import type { Startable } from '@libp2p/interface'\n\nexport interface DebouncedFunction extends Startable {\n (): void\n}\n\n/**\n * Returns a function wrapper that will only call the passed function once\n *\n * Important - the passed function should not throw or reject\n */\nexport function debounce (func: () => void | Promise<void>, wait: number): DebouncedFunction {\n let timeout: ReturnType<typeof setTimeout> | undefined\n\n const output = function (): void {\n const later = function (): void {\n timeout = undefined\n void func()\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n output.start = (): void => {}\n output.stop = (): void => {\n clearTimeout(timeout)\n }\n\n return output\n}\n", "import type { RateLimiterResult } from './rate-limiter.ts'\n\n/**\n * A rate limit was hit\n */\nexport class RateLimitError extends Error {\n remainingPoints: number\n msBeforeNext: number\n consumedPoints: number\n isFirstInDuration: boolean\n\n constructor (message = 'Rate limit exceeded', props: RateLimiterResult) {\n super(message)\n this.name = 'RateLimitError'\n this.remainingPoints = props.remainingPoints\n this.msBeforeNext = props.msBeforeNext\n this.consumedPoints = props.consumedPoints\n this.isFirstInDuration = props.isFirstInDuration\n }\n}\n\nexport class QueueFullError extends Error {\n static name = 'QueueFullError'\n\n constructor (message: string = 'The queue was full') {\n super(message)\n this.name = 'QueueFullError'\n }\n}\n\nexport class UnexpectedEOFError extends Error {\n static name = 'UnexpectedEOFError'\n name = 'UnexpectedEOFError'\n}\n\nexport class MaxEarlyStreamsError extends Error {\n static name = 'MaxEarlyStreamsError'\n name = 'MaxEarlyStreamsError'\n}\n\nexport class StreamClosedError extends Error {\n static name = 'StreamClosedError'\n name = 'StreamClosedError'\n}\n", "/**\n * @packageDocumentation\n *\n * Pass a promise and an abort signal and await the result.\n *\n * @example Basic usage\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws an AbortError\n * const resolve = await raceSignal(promise, controller.signal)\n * ```\n *\n * @example Overriding errors\n *\n * By default the thrown error is the `.reason` property of the signal but it's\n * possible to override this behaviour with the `translateError` option:\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws `Error('Oh no!')`\n * const resolve = await raceSignal(promise, controller.signal, {\n * translateError: (signal) => {\n * // use `signal`, or don't\n * return new Error('Oh no!')\n * }\n * })\n * ```\n */\n\nexport interface RaceSignalOptions {\n /**\n * By default the rejection reason will be taken from the `.reason` field of\n * the aborted signal.\n *\n * Passing a function here allows overriding the default error.\n */\n translateError?(signal: AbortSignal): Error\n}\n\nfunction defaultTranslate (signal: AbortSignal): Error {\n return signal.reason\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport function raceSignal <T> (promise: T, signal?: AbortSignal | null, opts?: RaceSignalOptions): T\nexport function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal | null, opts?: RaceSignalOptions): Promise<T>\nexport function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal | null, opts?: RaceSignalOptions): Promise<T> | T {\n if (signal == null || promise == null) {\n return promise\n }\n\n const translateError = opts?.translateError ?? defaultTranslate\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(translateError(signal))\n }\n\n let listener: EventListenerOrEventListenerObject | undefined\n\n return Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(translateError(signal))\n }\n signal.addEventListener('abort', listener)\n })\n ])\n .finally(() => {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n })\n}\n", "import { StreamResetError, TypedEventEmitter, StreamMessageEvent, StreamBufferError, StreamResetEvent, StreamAbortEvent, StreamCloseEvent, StreamStateError } from '@libp2p/interface'\nimport { pushable } from 'it-pushable'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { StreamClosedError } from './errors.ts'\nimport type { MessageStreamEvents, MessageStreamStatus, MessageStream, AbortOptions, MessageStreamTimeline, MessageStreamDirection, EventHandler, StreamOptions, MessageStreamReadStatus, MessageStreamWriteStatus } from '@libp2p/interface'\nimport type { Logger } from '@libp2p/logger'\n\nconst DEFAULT_MAX_READ_BUFFER_LENGTH = Math.pow(2, 20) * 4 // 4MB\n\nexport interface MessageStreamInit extends StreamOptions {\n /**\n * A Logger implementation used to log stream-specific information\n */\n log: Logger\n\n /**\n * The stream direction\n */\n direction?: MessageStreamDirection\n\n /**\n * By default all available bytes are passed to the `sendData` method of\n * extending classes, if smaller chunks are required, pass a value here.\n */\n maxMessageSize?: number\n}\n\nexport interface SendResult {\n /**\n * The number of bytes from the passed buffer that were sent\n */\n sentBytes: number\n\n /**\n * If the underlying resource can accept more data immediately. If `true`,\n * `sent` must equal the `.byteLength` of the buffer passed to `sendData`.\n */\n canSendMore: boolean\n}\n\nexport abstract class AbstractMessageStream<Timeline extends MessageStreamTimeline = MessageStreamTimeline> extends TypedEventEmitter<MessageStreamEvents> implements MessageStream {\n public status: MessageStreamStatus\n public readonly timeline: Timeline\n public inactivityTimeout: number\n public maxReadBufferLength: number\n public maxWriteBufferLength?: number\n public readonly log: Logger\n public direction: MessageStreamDirection\n public maxMessageSize?: number\n\n public readStatus: MessageStreamReadStatus\n public writeStatus: MessageStreamWriteStatus\n public remoteReadStatus: MessageStreamReadStatus\n public remoteWriteStatus: MessageStreamWriteStatus\n\n public writableNeedsDrain: boolean\n\n /**\n * Any data stored here is emitted before any new incoming data.\n *\n * This is used when the stream is paused or if data is pushed onto the stream\n */\n protected readonly readBuffer: Uint8ArrayList\n protected readonly writeBuffer: Uint8ArrayList\n protected sendingData: boolean\n\n #readableEnded = false\n\n private onDrainPromise?: PromiseWithResolvers<void>\n\n constructor (init: MessageStreamInit) {\n super()\n\n this.status = 'open'\n this.log = init.log\n this.direction = init.direction ?? 'outbound'\n this.inactivityTimeout = init.inactivityTimeout ?? 120_000\n this.maxReadBufferLength = init.maxReadBufferLength ?? DEFAULT_MAX_READ_BUFFER_LENGTH\n this.maxWriteBufferLength = init.maxWriteBufferLength\n this.maxMessageSize = init.maxMessageSize\n this.readBuffer = new Uint8ArrayList()\n this.writeBuffer = new Uint8ArrayList()\n\n this.readStatus = 'readable'\n this.remoteReadStatus = 'readable'\n this.writeStatus = 'writable'\n this.remoteWriteStatus = 'writable'\n this.sendingData = false\n this.writableNeedsDrain = false\n\n // @ts-expect-error type could have required fields other than 'open'\n this.timeline = {\n open: Date.now()\n }\n\n this.processSendQueue = this.processSendQueue.bind(this)\n\n const continueSendingOnDrain = (): void => {\n if (this.writableNeedsDrain) {\n this.log.trace('drain event received, continue sending data')\n this.writableNeedsDrain = false\n\n queueMicrotask(() => {\n try {\n this.processSendQueue()\n } catch (err) {\n this.log.error('processSendQueue threw - %e', err)\n }\n })\n }\n\n this.onDrainPromise?.resolve()\n }\n this.addEventListener('drain', continueSendingOnDrain)\n\n const rejectOnDrainOnClose = (evt: StreamCloseEvent): void => {\n this.onDrainPromise?.reject(evt.error ?? new StreamClosedError())\n }\n this.addEventListener('close', rejectOnDrainOnClose)\n }\n\n get readBufferLength (): number {\n return this.readBuffer.byteLength\n }\n\n get readableEnded (): boolean {\n return this.#readableEnded\n }\n\n get writeBufferLength (): number {\n return this.writeBuffer.byteLength\n }\n\n async onDrain (options?: AbortOptions): Promise<void> {\n if (this.writableNeedsDrain !== true) {\n return Promise.resolve()\n }\n\n if (this.onDrainPromise == null) {\n this.onDrainPromise = Promise.withResolvers()\n }\n\n return raceSignal(this.onDrainPromise.promise, options?.signal)\n }\n\n async * [Symbol.asyncIterator] (): AsyncGenerator<Uint8Array | Uint8ArrayList> {\n if (this.readStatus !== 'readable' && this.readStatus !== 'paused') {\n return\n }\n\n const output = pushable<Uint8Array | Uint8ArrayList>()\n\n const streamAsyncIterableOnMessageListener = (evt: StreamMessageEvent): void => {\n output.push(evt.data)\n }\n this.addEventListener('message', streamAsyncIterableOnMessageListener)\n\n const streamAsyncIterableOnCloseListener = (evt: StreamCloseEvent): void => {\n output.end(evt.error)\n }\n this.addEventListener('close', streamAsyncIterableOnCloseListener)\n\n const streamAsyncIterableOnRemoteCloseWriteListener = (): void => {\n output.end()\n }\n this.addEventListener('remoteCloseWrite', streamAsyncIterableOnRemoteCloseWriteListener)\n\n try {\n yield * output\n } finally {\n this.removeEventListener('message', streamAsyncIterableOnMessageListener)\n this.removeEventListener('close', streamAsyncIterableOnCloseListener)\n this.removeEventListener('remoteCloseWrite', streamAsyncIterableOnRemoteCloseWriteListener)\n }\n }\n\n isReadable (): boolean {\n return this.status === 'open'\n }\n\n send (data: Uint8Array | Uint8ArrayList): boolean {\n if (this.writeStatus === 'closed' || this.writeStatus === 'closing') {\n throw new StreamStateError(`Cannot write to a stream that is ${this.writeStatus}`)\n }\n\n this.log.trace('append %d bytes to write buffer', data.byteLength)\n this.writeBuffer.append(data)\n\n return this.processSendQueue()\n }\n\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort (err: Error): void {\n if (this.status === 'aborted' || this.status === 'reset' || this.status === 'closed') {\n return\n }\n\n this.log.error('abort with error - %e', err)\n\n this.status = 'aborted'\n\n // throw away unread data\n if (this.readBuffer.byteLength > 0) {\n this.readBuffer.consume(this.readBuffer.byteLength)\n }\n\n // throw away unsent data\n if (this.writeBuffer.byteLength > 0) {\n this.writeBuffer.consume(this.writeBuffer.byteLength)\n this.safeDispatchEvent('idle')\n }\n\n this.writeStatus = 'closed'\n this.remoteWriteStatus = 'closed'\n\n this.readStatus = 'closed'\n this.remoteReadStatus = 'closed'\n this.timeline.close = Date.now()\n this.maybeDispatchEnd()\n\n try {\n this.sendReset(err)\n } catch (err: any) {\n this.log.error('failed to send reset to remote - %e', err)\n }\n\n this.dispatchEvent(new StreamAbortEvent(err))\n }\n\n pause (): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError('Cannot pause a stream that is closing/closed')\n }\n\n if (this.readStatus === 'paused') {\n return\n }\n\n this.readStatus = 'paused'\n this.sendPause()\n }\n\n resume (): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError('Cannot resume a stream that is closing/closed')\n }\n\n if (this.readStatus === 'readable') {\n return\n }\n\n this.readStatus = 'readable'\n // emit any data that accumulated while we were paused\n this.dispatchReadBuffer()\n this.sendResume()\n }\n\n push (data: Uint8Array | Uint8ArrayList): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`)\n }\n\n if (data.byteLength === 0) {\n return\n }\n\n this.readBuffer.append(data)\n\n if (this.readStatus === 'paused' || this.listenerCount('message') === 0) {\n // abort if the read buffer is too large\n this.checkReadBufferLength()\n\n return\n }\n\n // TODO: use a microtask instead?\n setTimeout(() => {\n this.dispatchReadBuffer()\n }, 0)\n }\n\n unshift (data: Uint8Array | Uint8ArrayList): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`)\n }\n\n if (data.byteLength === 0) {\n return\n }\n\n this.readBuffer.prepend(data)\n\n if (this.readStatus === 'paused' || this.listenerCount('message') === 0) {\n // abort if the read buffer is too large\n this.checkReadBufferLength()\n\n return\n }\n\n // TODO: use a microtask instead?\n setTimeout(() => {\n this.dispatchReadBuffer()\n }, 0)\n }\n\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n onData (data: Uint8Array | Uint8ArrayList): void {\n if (data.byteLength === 0) {\n // this.log('ignoring empty data')\n return\n }\n\n // discard the data if our readable end is closed\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('ignoring data - read status %s', this.readStatus)\n return\n }\n\n this.readBuffer.append(data)\n this.dispatchReadBuffer()\n }\n\n addEventListener<K extends keyof MessageStreamEvents>(type: K, listener: EventHandler<MessageStreamEvents[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void\n addEventListener (...args: any[]): void {\n // @ts-expect-error cannot ensure args has enough members\n super.addEventListener.apply(this, args)\n\n // if a 'message' listener is being added and we have queued data, dispatch\n // the data\n if (args[0] === 'message' && this.readBuffer.byteLength > 0) {\n // event listeners can be added in constructors and often use object\n // properties - if this the case we can access a class member before it\n // has been initialized so dispatch the message in the microtask queue\n queueMicrotask(() => {\n this.dispatchReadBuffer()\n })\n }\n }\n\n /**\n * Receive a reset message - close immediately for reading and writing (remote\n * error)\n */\n onRemoteReset (): void {\n this.log('remote reset')\n\n this.status = 'reset'\n this.writeStatus = 'closed'\n this.remoteWriteStatus = 'closed'\n this.remoteReadStatus = 'closed'\n this.timeline.close = Date.now()\n\n if (this.readBuffer.byteLength === 0) {\n this.readStatus = 'closed'\n this.maybeDispatchEnd()\n }\n\n this.dispatchEvent(new StreamResetEvent(new StreamResetError()))\n }\n\n /**\n * The underlying resource or transport this stream uses has closed - it is\n * not possible to send any more messages though any data still in the read\n * buffer may still be read\n */\n onTransportClosed (err?: Error): void {\n this.log('transport closed')\n\n if (this.readStatus === 'readable' && this.readBuffer.byteLength === 0) {\n this.log('close readable end after transport closed and read buffer is empty')\n this.readStatus = 'closed'\n }\n\n if (this.remoteReadStatus !== 'closed') {\n this.remoteReadStatus = 'closed'\n }\n\n if (this.remoteWriteStatus !== 'closed') {\n this.remoteWriteStatus = 'closed'\n }\n\n if (this.writeStatus !== 'closed') {\n this.writeStatus = 'closed'\n }\n\n if (err != null) {\n // abort dispatches 'end' itself, once the stream is fully terminal\n this.abort(err)\n } else if (this.status === 'open' || this.status === 'closing') {\n this.timeline.close = Date.now()\n this.status = 'closed'\n\n // this may be the end even if the readable end was not closed above\n this.maybeDispatchEnd()\n this.dispatchEvent(new StreamCloseEvent())\n }\n }\n\n /**\n * Called by extending classes when the remote closes its writable end\n */\n onRemoteCloseWrite (): void {\n if (this.remoteWriteStatus === 'closed') {\n return\n }\n\n this.log.trace('on remote close write')\n\n this.remoteWriteStatus = 'closed'\n\n this.safeDispatchEvent('remoteCloseWrite')\n\n this.maybeDispatchEnd()\n\n if (this.writeStatus === 'closed') {\n this.onTransportClosed()\n }\n }\n\n /**\n * Called by extending classes when the remote closes its readable end\n */\n onRemoteCloseRead (): void {\n this.log.trace('on remote close read')\n\n this.remoteReadStatus = 'closed'\n\n // throw away any unsent bytes if the remote closes it's readable end\n if (this.writeBuffer.byteLength > 0) {\n this.writeBuffer.consume(this.writeBuffer.byteLength)\n this.safeDispatchEvent('idle')\n }\n }\n\n protected processSendQueue (): boolean {\n // bail if the underlying transport is full\n if (this.writableNeedsDrain) {\n this.log.trace('not processing send queue as drain is required')\n this.checkWriteBufferLength()\n\n return false\n }\n\n // bail if there is no data to send\n if (this.writeBuffer.byteLength === 0) {\n this.log.trace('not processing send queue as no bytes to send')\n return true\n }\n\n // bail if we are already sending data\n if (this.sendingData) {\n this.log.trace('not processing send queue as already sending data')\n return true\n }\n\n if (this.writeStatus !== 'writable' && this.writeStatus !== 'closing') {\n this.log.trace('not processing send queue as stream is %s', this.writeStatus)\n return false\n }\n\n this.sendingData = true\n\n this.log.trace('processing send queue with %d queued bytes', this.writeBuffer.byteLength)\n\n try {\n let canSendMore = true\n const totalBytes = this.writeBuffer.byteLength\n let sentBytes = 0\n\n // send as much data as possible while we have data to send and the\n // underlying muxer can still accept data\n while (this.writeBuffer.byteLength > 0) {\n const end = Math.min(this.maxMessageSize ?? this.writeBuffer.byteLength, this.writeBuffer.byteLength)\n\n // this can happen if a subclass changes the max message size dynamically\n if (end === 0) {\n canSendMore = false\n break\n }\n\n // chunk to send to the remote end\n const toSend = this.writeBuffer.sublist(0, end)\n\n // copy toSend in case the extending class modifies the list\n const willSend = new Uint8ArrayList(toSend)\n\n this.writeBuffer.consume(toSend.byteLength)\n\n // sending data can cause buffers to fill up, events to be emitted and\n // this method to be invoked again\n let sendResult: SendResult\n\n try {\n sendResult = this.sendData(toSend)\n } catch (err: any) {\n // restore the consumed chunk so abort() emits 'idle' for the drained\n // write buffer (normally emitted here on completion, but the send threw)\n this.writeBuffer.prepend(willSend)\n this.abort(err)\n throw err\n }\n\n canSendMore = sendResult.canSendMore\n sentBytes += sendResult.sentBytes\n\n if (sendResult.sentBytes !== willSend.byteLength) {\n willSend.consume(sendResult.sentBytes)\n this.writeBuffer.prepend(willSend)\n }\n\n if (!canSendMore) {\n break\n }\n }\n\n if (!canSendMore) {\n this.log.trace('sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer', sentBytes, totalBytes, this.writeBuffer.byteLength)\n this.writableNeedsDrain = true\n this.checkWriteBufferLength()\n }\n\n // we processed all bytes in the queue, resolve the write queue idle promise\n if (this.writeBuffer.byteLength === 0) {\n this.safeDispatchEvent('idle')\n }\n\n return canSendMore\n } finally {\n this.sendingData = false\n }\n }\n\n /**\n * Emit 'end' if nothing is buffered and no more data will be delivered.\n * Emits at most once\n */\n protected maybeDispatchEnd (): void {\n if (this.#readableEnded || this.readBuffer.byteLength > 0) {\n return\n }\n\n if (this.remoteWriteStatus !== 'closed' && this.readStatus !== 'closed') {\n return\n }\n\n this.#readableEnded = true\n this.safeDispatchEvent('end')\n }\n\n protected dispatchReadBuffer (): void {\n try {\n if (this.listenerCount('message') === 0) {\n this.log.trace('not dispatching pause buffer as there are no listeners for the message event')\n return\n }\n\n if (this.readBuffer.byteLength === 0) {\n this.log.trace('not dispatching pause buffer as there is no data to dispatch')\n return\n }\n\n if (this.readStatus === 'paused') {\n this.log.trace('not dispatching pause buffer we are paused')\n return\n }\n\n // discard the pause buffer if our readable end is closed\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('dropping %d bytes because the readable end is %s', this.readBuffer.byteLength, this.readStatus)\n this.readBuffer.consume(this.readBuffer.byteLength)\n return\n }\n\n const buf = this.readBuffer.sublist()\n this.readBuffer.consume(buf.byteLength)\n\n this.dispatchEvent(new StreamMessageEvent(buf))\n } finally {\n if (this.readBuffer.byteLength === 0 && this.remoteWriteStatus === 'closed') {\n this.log('close readable end after dispatching read buffer and remote writable end is closed')\n this.readStatus = 'closed'\n this.maybeDispatchEnd()\n }\n\n // abort if we failed to consume the read buffer and it is too large\n this.checkReadBufferLength()\n }\n }\n\n private checkReadBufferLength (): void {\n if (this.readBuffer.byteLength > this.maxReadBufferLength) {\n this.abort(new StreamBufferError(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))\n }\n }\n\n private checkWriteBufferLength (): void {\n if (this.maxWriteBufferLength == null) {\n return\n }\n\n if (this.writeBuffer.byteLength > this.maxWriteBufferLength) {\n this.abort(new StreamBufferError(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))\n }\n }\n\n public onMuxerNeedsDrain (): void {\n this.writableNeedsDrain = true\n }\n\n public onMuxerDrain (): void {\n this.safeDispatchEvent('drain')\n }\n\n /**\n * Send a data message to the remote end of the stream. Implementations of\n * this method should return the number of bytes from the passed buffer that\n * were sent successfully and if the underlying resource can accept more data.\n *\n * The implementation should always attempt to send the maximum amount of data\n * possible.\n *\n * Returning a result that means the data was only partially sent but that the\n * underlying resource can accept more data is invalid.\n */\n abstract sendData (data: Uint8ArrayList): SendResult\n\n /**\n * Send a reset message to the remote end of the stream\n */\n abstract sendReset (err: Error): void\n\n /**\n * If supported, instruct the remote end of the stream to temporarily stop\n * sending data messages\n */\n abstract sendPause (): void\n\n /**\n * If supported, inform the remote end of the stream they may resume sending\n * data messages\n */\n abstract sendResume (): void\n\n /**\n * Stop accepting new data to send and return a promise that resolves when any\n * unsent data has been written into the underlying resource.\n */\n abstract close (options?: AbortOptions): Promise<void>\n}\n", "export function isPromise <T = unknown> (thing: any): thing is Promise<T> {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n", "import { MuxerClosedError, TypedEventEmitter } from '@libp2p/interface'\nimport { raceSignal } from 'race-signal'\nimport { MaxEarlyStreamsError } from './errors.ts'\nimport { isPromise } from './is-promise.ts'\nimport type { AbstractStream } from './abstract-stream.ts'\nimport type { AbortOptions, CounterGroup, CreateStreamOptions, EventHandler, Logger, MessageStream, Stream, StreamCloseEvent, StreamMessageEvent, StreamMuxer, StreamMuxerEvents, StreamMuxerOptions, StreamMuxerStatus, StreamOptions } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface AbstractStreamMuxerInit extends StreamMuxerOptions {\n /**\n * The protocol name for the muxer\n */\n protocol: string\n\n /**\n * The name of the muxer, used to create a new logging scope from the passed\n * connection's logger\n */\n name: string\n\n /**\n * A counter for muxer metrics\n */\n metrics?: CounterGroup\n}\n\nexport abstract class AbstractStreamMuxer <MuxedStream extends AbstractStream = AbstractStream> extends TypedEventEmitter<StreamMuxerEvents<MuxedStream>> implements StreamMuxer<MuxedStream> {\n public streams: MuxedStream[]\n public protocol: string\n public status: StreamMuxerStatus\n\n protected log: Logger\n protected maConn: MessageStream\n protected streamOptions?: StreamOptions\n protected earlyStreams: MuxedStream[]\n protected maxEarlyStreams: number\n\n private readonly metrics?: CounterGroup\n\n constructor (maConn: MessageStream, init: AbstractStreamMuxerInit) {\n super()\n\n this.maConn = maConn\n this.protocol = init.protocol\n this.streams = []\n this.earlyStreams = []\n this.status = 'open'\n this.log = maConn.log.newScope(init.name)\n this.streamOptions = init.streamOptions\n this.maxEarlyStreams = init.maxEarlyStreams ?? 10\n this.metrics = init.metrics\n\n // read/write all data from/to underlying maConn\n const muxerMaConnOnMessage = (evt: StreamMessageEvent): void => {\n try {\n this.onData(evt.data)\n } catch (err: any) {\n this.abort(err)\n this.maConn.abort(err)\n }\n }\n this.maConn.addEventListener('message', muxerMaConnOnMessage)\n\n // signal stream writers when the underlying connection can accept more data\n const muxerMaConnOnDrain = (): void => {\n this.log('underlying stream drained, signal %d streams to continue writing', this.streams.length)\n\n this.streams.forEach(stream => {\n stream.onMuxerDrain()\n })\n }\n this.maConn.addEventListener('drain', muxerMaConnOnDrain)\n\n const muxerOnMaConnClose = (): void => {\n this.log('underlying stream closed with status %s and %d streams', this.status, this.streams.length)\n this.onTransportClosed()\n }\n this.maConn.addEventListener('close', muxerOnMaConnClose)\n }\n\n send (data: Uint8Array | Uint8ArrayList): boolean {\n const result = this.maConn.send(data)\n\n if (result === false) {\n this.log('underlying stream saturated, signal %d streams to pause writing', this.streams.length)\n\n this.streams.forEach(stream => {\n stream.onMuxerNeedsDrain()\n })\n }\n\n return result\n }\n\n async close (options?: AbortOptions): Promise<void> {\n if (this.status === 'closed' || this.status === 'closing') {\n return\n }\n\n this.status = 'closing'\n\n await raceSignal(Promise.all(\n [...this.streams].map(async s => {\n await s.close(options)\n })\n ), options?.signal)\n\n this.status = 'closed'\n }\n\n abort (err: Error): void {\n if (this.status === 'closed') {\n return\n }\n\n this.status = 'closing'\n\n ;[...this.streams].forEach(s => {\n s.abort(err)\n })\n\n this.status = 'closed'\n }\n\n onTransportClosed (err?: Error): void {\n this.status = 'closing'\n\n try {\n [...this.streams].forEach(stream => {\n stream.onTransportClosed(err)\n })\n } catch (err: any) {\n this.abort(err)\n }\n\n this.status = 'closed'\n }\n\n async createStream (options?: CreateStreamOptions): Promise<MuxedStream> {\n if (this.status !== 'open') {\n throw new MuxerClosedError()\n }\n\n let stream = this.onCreateStream({\n ...this.streamOptions,\n ...options\n })\n\n if (isPromise(stream)) {\n stream = await stream\n }\n\n this.streams.push(stream)\n this.cleanUpStream(stream)\n\n return stream\n }\n\n /**\n * Extending classes should invoke this method when a new stream was created\n * by the remote muxer\n */\n onRemoteStream (stream: MuxedStream): void {\n this.streams.push(stream)\n this.cleanUpStream(stream)\n\n if (this.listenerCount('stream') === 0) {\n // no listener has been added for the stream event yet, store the stream\n // to emit it later\n this.earlyStreams.push(stream)\n\n if (this.earlyStreams.length > this.maxEarlyStreams) {\n this.abort(new MaxEarlyStreamsError(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`))\n }\n\n return\n }\n\n this.safeDispatchEvent('stream', {\n detail: stream\n })\n }\n\n private cleanUpStream (stream: Stream): void {\n const muxerOnStreamEnd = (evt: StreamCloseEvent): void => {\n const index = this.streams.findIndex(s => s === stream)\n\n if (index !== -1) {\n this.streams.splice(index, 1)\n }\n\n if (evt.error != null) {\n if (evt.local) {\n this.metrics?.increment({ [`${stream.direction}_stream_reset`]: true })\n } else {\n this.metrics?.increment({ [`${stream.direction}_stream_abort`]: true })\n }\n } else {\n this.metrics?.increment({ [`${stream.direction}_stream_end`]: true })\n }\n }\n stream.addEventListener('close', muxerOnStreamEnd)\n\n this.metrics?.increment({ [`${stream.direction}_stream`]: true })\n }\n\n addEventListener<K extends keyof StreamMuxerEvents<MuxedStream>>(type: K, listener: EventHandler<StreamMuxerEvents<MuxedStream>[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void\n addEventListener (...args: any[]): void {\n // @ts-expect-error cannot ensure args has enough members\n super.addEventListener.apply(this, args)\n\n // if a 'stream' listener is being added and we have early streams, emit\n // them\n if (args[0] === 'stream' && this.earlyStreams.length > 0) {\n // event listeners can be added in constructors and often use object\n // properties - if this the case we can access a class member before it\n // has been initialized so dispatch the message in the microtask queue\n queueMicrotask(() => {\n this.earlyStreams.forEach(stream => {\n this.safeDispatchEvent('stream', {\n detail: stream\n })\n })\n this.earlyStreams = []\n })\n }\n }\n\n /**\n * A new outgoing stream needs to be created\n */\n abstract onCreateStream (options: CreateStreamOptions): MuxedStream | Promise<MuxedStream>\n\n /**\n * Multiplexed data was received from the remote muxer\n */\n abstract onData (data: Uint8Array | Uint8ArrayList): void\n}\n", "import { pEvent } from 'p-event'\nimport { AbstractMessageStream } from './abstract-message-stream.ts'\nimport type { MessageStreamInit } from './abstract-message-stream.ts'\nimport type { AbortOptions, Stream } from '@libp2p/interface'\n\nexport interface AbstractStreamInit extends MessageStreamInit {\n /**\n * A unique identifier for this stream\n */\n id: string\n\n /**\n * The protocol name for the stream, if it is known\n */\n protocol?: string\n}\n\nexport abstract class AbstractStream extends AbstractMessageStream implements Stream {\n public id: string\n public protocol: string\n\n constructor (init: AbstractStreamInit) {\n super(init)\n\n this.id = init.id\n this.protocol = init.protocol ?? ''\n }\n\n async close (options?: AbortOptions): Promise<void> {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n return\n }\n\n this.writeStatus = 'closing'\n\n // if we are currently sending data, wait for all the data to be written\n // into the underlying transport\n if (this.sendingData || this.writeBuffer.byteLength > 0) {\n this.log('waiting for write queue to become idle before closing writable end of stream, %d unsent bytes', this.writeBuffer.byteLength)\n await pEvent(this, 'idle', {\n ...options,\n rejectionEvents: [\n 'close'\n ]\n })\n }\n\n // now that the underlying transport has all the data, if the buffer is full\n // wait for it to be emptied\n if (this.writableNeedsDrain) {\n this.log('waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s', this.writeBuffer.byteLength, this.sendingData)\n await pEvent(this, 'drain', {\n ...options,\n rejectionEvents: [\n 'close'\n ]\n })\n this.log('write queue drained, closing writable end of stream, %d unsent bytes, sending %s', this.writeBuffer.byteLength, this.sendingData)\n }\n\n await this.sendCloseWrite(options)\n\n this.writeStatus = 'closed'\n\n this.log('closed writable end gracefully')\n\n if (this.remoteWriteStatus === 'closed') {\n this.onTransportClosed()\n }\n }\n\n async closeRead (options?: AbortOptions): Promise<void> {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n return\n }\n\n // throw away any unread data\n if (this.readBuffer.byteLength > 0) {\n this.readBuffer.consume(this.readBuffer.byteLength)\n }\n\n this.readStatus = 'closing'\n\n await this.sendCloseRead(options)\n\n this.readStatus = 'closed'\n this.maybeDispatchEnd()\n\n this.log('closed readable end gracefully')\n }\n\n /**\n * Send a message to the remote end of the stream, informing them that we will\n * send no more data messages.\n */\n abstract sendCloseWrite (options?: AbortOptions): Promise<void>\n\n /**\n * If supported, send a message to the remote end of the stream, informing\n * them that we will read no more data messages.\n */\n abstract sendCloseRead (options?: AbortOptions): Promise<void>\n}\n", "/**\n * @packageDocumentation\n *\n * Similar to [AbortSignal.any](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static)\n * except the returned promise has a `.clear` method that removes all event\n * listeners added to passed signals preventing memory leaks.\n *\n * At the time of writing at least, `AbortSignal.any` leaks memory in Node.js\n * and Deno environments:\n *\n * - https://github.com/nodejs/node/issues/54614\n * - https://github.com/denoland/deno/issues/24842\n *\n * @example\n *\n * ```js\n * import { anySignal } from 'any-signal'\n *\n * const userController = new AbortController()\n *\n * // Abort after 1 second\n * const timeoutSignal = AbortSignal.timeout(1000)\n *\n * const combinedSignal = anySignal([userController.signal, timeoutSignal])\n * combinedSignal.addEventListener('abort', () => console.log('Abort!'))\n *\n * try {\n * // The user or the timeout can now abort the action\n * await performSomeAction({ signal: combinedSignal })\n * } finally {\n * // Clear will clean up internal event handlers\n * combinedSignal.clear()\n * }\n * ```\n */\n\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal (signals: Array<AbortSignal | undefined | null>): ClearableSignal {\n const controller = new globalThis.AbortController()\n\n function onAbort (): void {\n const reason = signals\n .filter(s => s?.aborted === true)\n .map(s => s?.reason)\n .pop()\n\n controller.abort(reason)\n\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort()\n break\n }\n\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort)\n }\n }\n\n function clear (): void {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n const signal = controller.signal as ClearableSignal\n signal.clear = clear\n\n return signal\n}\n", "import { anySignal } from 'any-signal'\nimport { setMaxListeners } from 'main-event'\nimport { debounce } from './debounce.ts'\nimport type { AbortOptions } from '@libp2p/interface'\n\nexport interface RepeatingTask {\n /**\n * Update the interval after which the next iteration of the task will run.\n *\n * This is useful if, for example, you want to retry a task with a short rest\n * duration until it succeeds, then periodically after that.\n *\n * This only affects the next iteration of the task, if it is currently\n * running, that run will not be interrupted.\n *\n * Setting the interval to the current value has no effect.\n */\n setInterval(ms: number): void\n\n /**\n * Update the amount of time a task will run before the passed abort signal\n * will fire.\n *\n * This only affects the next iteration of the task, if it is currently\n * running, that run will not be interrupted.\n */\n setTimeout(ms: number): void\n\n /**\n * Schedule the task to be run immediately - if the task is not running it\n * will run after a short delay in order to debounce multiple `.run()`\n * invocations.\n */\n run(): void\n\n /**\n * Start the task running\n */\n start(): void\n\n /**\n * Stop the task running\n */\n stop(): void\n}\n\nexport interface RepeatingTaskOptions {\n /**\n * How long the task is allowed to run before the passed AbortSignal fires an\n * abort event\n */\n timeout?: number\n\n /**\n * Whether to schedule the task to run immediately\n *\n * @default false\n */\n runImmediately?: boolean\n\n /**\n * When `.run()` is called to run the task outside of the current interval,\n * debounce repeated calls to `.run()` by this amount.\n *\n * @default 100\n */\n debounce?: number\n}\n\nexport function repeatingTask (fn: (options?: AbortOptions) => void | Promise<void>, interval: number, options?: RepeatingTaskOptions): RepeatingTask {\n let timeout: ReturnType<typeof setTimeout>\n let shutdownController: AbortController\n let running = false\n\n function runTask (): void {\n const opts: AbortOptions = {\n signal: shutdownController.signal\n }\n\n let signal: ReturnType<typeof anySignal> | undefined\n\n if (options?.timeout != null) {\n signal = anySignal([shutdownController.signal, AbortSignal.timeout(options.timeout)])\n setMaxListeners(Infinity, signal)\n\n opts.signal = signal\n }\n\n running = true\n\n Promise.resolve().then(async () => {\n await fn(opts)\n })\n .catch(() => {})\n .finally(() => {\n if (signal != null) {\n if (signal.aborted) {\n signal.clear()\n } else {\n // Clear listeners once this per-run signal eventually aborts\n signal.addEventListener('abort', () => {\n signal.clear()\n }, { once: true })\n }\n }\n\n running = false\n\n if (shutdownController.signal.aborted) {\n // task has been cancelled, bail\n return\n }\n\n // reschedule\n timeout = setTimeout(runTask, interval)\n })\n }\n\n const runTaskDebounced = debounce(runTask, options?.debounce ?? 100)\n\n let started = false\n\n return {\n setInterval: (ms): void => {\n if (interval === ms) {\n // already running at this interval, nothing to do\n return\n }\n\n interval = ms\n\n // maybe reschedule\n if (timeout != null) {\n clearTimeout(timeout)\n timeout = setTimeout(runTask, interval)\n }\n },\n setTimeout: (ms): void => {\n options ??= {}\n options.timeout = ms\n },\n run: (): void => {\n if (running) {\n return\n }\n\n clearTimeout(timeout)\n runTaskDebounced()\n },\n start: (): void => {\n if (started) {\n return\n }\n\n started = true\n shutdownController = new AbortController()\n setMaxListeners(Infinity, shutdownController.signal)\n\n // run now\n if (options?.runImmediately === true) {\n queueMicrotask(() => {\n runTask()\n })\n } else {\n // run later\n timeout = setTimeout(runTask, interval)\n }\n },\n stop: (): void => {\n clearTimeout(timeout)\n shutdownController?.abort()\n started = false\n }\n }\n}\n", "export enum FrameType {\n /** Used to transmit data. May transmit zero length payloads depending on the flags. */\n Data = 0x0,\n /** Used to updated the senders receive window size. This is used to implement per-session flow control. */\n WindowUpdate = 0x1,\n /** Used to measure RTT. It can also be used to heart-beat and do keep-alive over TCP. */\n Ping = 0x2,\n /** Used to close a session. */\n GoAway = 0x3\n}\n\nexport enum Flag {\n /** Signals the start of a new stream. May be sent with a data or window update message. Also sent with a ping to indicate outbound. */\n SYN = 0x1,\n /** Acknowledges the start of a new stream. May be sent with a data or window update message. Also sent with a ping to indicate response. */\n ACK = 0x2,\n /** Performs a half-close of a stream. May be sent with a data message or window update. */\n FIN = 0x4,\n /** Reset a stream immediately. May be sent with a data or window update message. */\n RST = 0x8\n}\n\nconst flagCodes = Object.values(Flag).filter((x) => typeof x !== 'string') as Flag[]\n\nexport const YAMUX_VERSION = 0\n\nexport enum GoAwayCode {\n NormalTermination = 0x0,\n ProtocolError = 0x1,\n InternalError = 0x2\n}\n\nexport const HEADER_LENGTH = 12\n\nexport interface FrameHeader {\n /**\n * The version field is used for future backward compatibility.\n * At the current time, the field is always set to 0, to indicate the initial version.\n */\n version?: number\n /** The type field is used to switch the frame message type. */\n type: FrameType\n /** The flags field is used to provide additional information related to the message type. */\n flag: number\n /**\n * The StreamID field is used to identify the logical stream the frame is addressing.\n * The client side should use odd ID's, and the server even.\n * This prevents any collisions. Additionally, the 0 ID is reserved to represent the session.\n */\n streamID: number\n /**\n * The meaning of the length field depends on the message type:\n * Data - provides the length of bytes following the header\n * Window update - provides a delta update to the window size\n * Ping - Contains an opaque value, echoed back\n * Go Away - Contains an error code\n */\n length: number\n}\n\nexport function stringifyHeader (header: FrameHeader): string {\n const flags = flagCodes.filter(f => (header.flag & f) === f).map(f => Flag[f]).join('|')\n return `streamID=${header.streamID} type=${FrameType[header.type]} flag=${flags} length=${header.length}`\n}\n", "import { GoAwayCode } from './frame.ts'\n\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n public reason: GoAwayCode\n\n constructor (message: string, reason: GoAwayCode) {\n super(message)\n this.name = 'ProtocolError'\n this.reason = reason\n }\n}\n\nexport function isProtocolError (err?: any): err is ProtocolError {\n return err?.reason !== null\n}\n\nexport class InvalidFrameError extends ProtocolError {\n static name = 'InvalidFrameError'\n\n constructor (message = 'The frame was invalid') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'InvalidFrameError'\n }\n}\n\nexport class UnRequestedPingError extends ProtocolError {\n static name = 'UnRequestedPingError'\n\n constructor (message = 'Un-requested ping error') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'UnRequestedPingError'\n }\n}\n\nexport class NotMatchingPingError extends ProtocolError {\n static name = 'NotMatchingPingError'\n\n constructor (message = 'Not matching ping error') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'NotMatchingPingError'\n }\n}\n\nexport class InvalidStateError extends Error {\n static name = 'InvalidStateError'\n\n constructor (message = 'Invalid state') {\n super(message)\n this.name = 'InvalidStateError'\n }\n}\n\nexport class StreamAlreadyExistsError extends ProtocolError {\n static name = 'StreamAlreadyExistsError'\n\n constructor (message = 'Stream already exists') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'StreamAlreadyExistsError'\n }\n}\n\nexport class DecodeInvalidVersionError extends ProtocolError {\n static name = 'DecodeInvalidVersionError'\n\n constructor (message = 'Decode invalid version') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'DecodeInvalidVersionError'\n }\n}\n\nexport class BothClientsError extends ProtocolError {\n static name = 'BothClientsError'\n\n constructor (message = 'Both clients') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'BothClientsError'\n }\n}\n\nexport class ReceiveWindowExceededError extends ProtocolError {\n static name = 'ReceiveWindowExceededError'\n\n constructor (message = 'Receive window exceeded') {\n super(message, GoAwayCode.ProtocolError)\n this.name = 'ReceiveWindowExceededError'\n }\n}\n", "// Protocol violation errors\n\nimport { BothClientsError, DecodeInvalidVersionError, InvalidFrameError, NotMatchingPingError, ReceiveWindowExceededError, StreamAlreadyExistsError, UnRequestedPingError } from './errors.ts'\n\nexport const PROTOCOL_ERRORS = new Set([\n InvalidFrameError.name,\n UnRequestedPingError.name,\n NotMatchingPingError.name,\n StreamAlreadyExistsError.name,\n DecodeInvalidVersionError.name,\n BothClientsError.name,\n ReceiveWindowExceededError.name\n])\n\n/**\n * INITIAL_STREAM_WINDOW is the initial stream window size.\n *\n * Not an implementation choice, this is defined in the specification\n */\nexport const INITIAL_STREAM_WINDOW = 256 * 1024\n\n/**\n * Default max stream window\n */\nexport const MAX_STREAM_WINDOW = 16 * 1024 * 1024\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { INITIAL_STREAM_WINDOW, MAX_STREAM_WINDOW } from './constants.ts'\nimport type { StreamMuxerOptions, StreamOptions } from '@libp2p/interface'\n\nexport interface YamuxStreamOptions extends StreamOptions {\n /**\n * Used to control the initial window size that we allow for a stream.\n *\n * measured in bytes\n */\n initialStreamWindowSize?: number\n\n /**\n * Used to control the maximum window size that we allow for a stream.\n */\n maxStreamWindowSize?: number\n}\n\n// TODO use config items or delete them\nexport interface Config extends StreamMuxerOptions<YamuxStreamOptions> {\n /**\n * Used to do periodic keep alive messages using a ping\n */\n enableKeepAlive?: boolean\n\n /**\n * How often to perform the keep alive\n *\n * measured in milliseconds\n */\n keepAliveInterval?: number\n}\n\nexport const defaultConfig: Required<Config> & { streamOptions: Required<YamuxStreamOptions> } = {\n enableKeepAlive: true,\n keepAliveInterval: 30_000,\n maxInboundStreams: 1_000,\n maxOutboundStreams: 1_000,\n maxMessageSize: 64 * 1024,\n maxEarlyStreams: 10,\n streamOptions: {\n initialStreamWindowSize: INITIAL_STREAM_WINDOW,\n maxStreamWindowSize: MAX_STREAM_WINDOW,\n inactivityTimeout: 120_000,\n maxReadBufferLength: 4_194_304,\n maxWriteBufferLength: Infinity\n }\n}\n\nexport function verifyConfig (config: Config): void {\n if (config.keepAliveInterval != null && config.keepAliveInterval <= 0) {\n throw new InvalidParametersError('keep-alive interval must be positive')\n }\n if (config.maxInboundStreams != null && config.maxInboundStreams < 0) {\n throw new InvalidParametersError('max inbound streams must be larger or equal 0')\n }\n if (config.maxOutboundStreams != null && config.maxOutboundStreams < 0) {\n throw new InvalidParametersError('max outbound streams must be larger or equal 0')\n }\n if (config.maxMessageSize != null && config.maxMessageSize < 1024) {\n throw new InvalidParametersError('MaxMessageSize must be greater than a kilobyte')\n }\n if (config.streamOptions?.initialStreamWindowSize != null && config.streamOptions?.initialStreamWindowSize < INITIAL_STREAM_WINDOW) {\n throw new InvalidParametersError('InitialStreamWindowSize must be larger or equal 256 kB')\n }\n if (config.streamOptions?.maxStreamWindowSize != null && config.streamOptions?.initialStreamWindowSize != null && config.streamOptions?.maxStreamWindowSize < config.streamOptions?.initialStreamWindowSize) {\n throw new InvalidParametersError('MaxStreamWindowSize must be larger than the InitialStreamWindowSize')\n }\n if (config.streamOptions?.maxStreamWindowSize != null && config.streamOptions?.maxStreamWindowSize > 2 ** 32 - 1) {\n throw new InvalidParametersError('MaxStreamWindowSize must be less than equal MAX_UINT32')\n }\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport { InvalidFrameError } from './errors.ts'\nimport { FrameType, HEADER_LENGTH, YAMUX_VERSION } from './frame.ts'\nimport type { FrameHeader } from './frame.ts'\n\nexport interface Frame {\n header: FrameHeader\n data?: Uint8ArrayList\n}\n\nexport interface DataFrame {\n header: FrameHeader\n data: Uint8ArrayList\n}\n\nexport function isDataFrame (frame: Frame): frame is DataFrame {\n return frame.header.type === FrameType.Data && frame.data !== null\n}\n\n// used to bit shift in decoding\n// native bit shift can overflow into a negative number, so we bit shift by\n// multiplying by a power of 2\nconst twoPow24 = 2 ** 24\n\n/**\n * Decode a header from the front of a buffer\n *\n * @param data - Assumed to have enough bytes for a header\n */\nexport function decodeHeader (data: Uint8Array): FrameHeader {\n if (data[0] !== YAMUX_VERSION) {\n throw new InvalidFrameError('Invalid frame version')\n }\n\n return {\n type: data[1],\n flag: (data[2] << 8) + data[3],\n streamID: (data[4] * twoPow24) + (data[5] << 16) + (data[6] << 8) + data[7],\n length: (data[8] * twoPow24) + (data[9] << 16) + (data[10] << 8) + data[11]\n }\n}\n\n/**\n * Decodes yamux frames from a source\n */\nexport class Decoder {\n /** Buffer for in-progress frames */\n private readonly buffer: Uint8ArrayList\n\n constructor () {\n this.buffer = new Uint8ArrayList()\n }\n\n /**\n * Emits frames from the decoder source.\n *\n * Note: If `readData` is emitted, it _must_ be called before the next iteration\n * Otherwise an error is thrown\n */\n * emitFrames (buf: Uint8Array | Uint8ArrayList): Generator<Frame> {\n this.buffer.append(buf)\n\n // Loop to consume as many bytes from the buffer as possible\n // Eg: when a single chunk contains several frames\n while (true) {\n const frame = this.readFrame()\n\n if (frame === undefined) {\n break\n }\n\n yield frame\n }\n }\n\n private readFrame (): Frame | undefined {\n let frameSize = HEADER_LENGTH\n\n if (this.buffer.byteLength < HEADER_LENGTH) {\n // not enough data yet\n return\n }\n\n // TODO: use sublist?\n const header = decodeHeader(this.buffer.subarray(0, HEADER_LENGTH))\n\n if (header.type === FrameType.Data) {\n frameSize += header.length\n\n if (this.buffer.byteLength < frameSize) {\n // not enough data yet\n return\n }\n\n const data = this.buffer.sublist(HEADER_LENGTH, frameSize)\n this.buffer.consume(frameSize)\n\n return { header, data }\n }\n\n this.buffer.consume(frameSize)\n\n return { header }\n }\n}\n", "import { HEADER_LENGTH } from './frame.ts'\nimport type { FrameHeader } from './frame.ts'\n\nexport function encodeHeader (header: FrameHeader): Uint8Array {\n const frame = new Uint8Array(HEADER_LENGTH)\n\n // always assume version 0\n // frameView.setUint8(0, header.version)\n\n frame[1] = header.type\n\n frame[2] = header.flag >>> 8\n frame[3] = header.flag\n\n frame[4] = header.streamID >>> 24\n frame[5] = header.streamID >>> 16\n frame[6] = header.streamID >>> 8\n frame[7] = header.streamID\n\n frame[8] = header.length >>> 24\n frame[9] = header.length >>> 16\n frame[10] = header.length >>> 8\n frame[11] = header.length\n\n return frame\n}\n", "import { AbstractStream } from '@libp2p/utils'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { INITIAL_STREAM_WINDOW, MAX_STREAM_WINDOW } from './constants.ts'\nimport { isDataFrame } from './decode.ts'\nimport { InvalidFrameError, ReceiveWindowExceededError } from './errors.ts'\nimport { Flag, FrameType, HEADER_LENGTH } from './frame.ts'\nimport type { Frame } from './decode.ts'\nimport type { FrameHeader } from './frame.ts'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { AbstractStreamInit, SendResult } from '@libp2p/utils'\n\nexport enum StreamState {\n Init,\n SYNSent,\n SYNReceived,\n Established,\n Finished,\n Paused\n}\n\nexport interface YamuxStreamInit extends AbstractStreamInit {\n streamId: number\n sendFrame(header: FrameHeader, body?: Uint8ArrayList): boolean\n getRTT(): number\n initialStreamWindowSize?: number\n maxMessageSize?: number\n maxStreamWindowSize?: number\n state: StreamState\n}\n\n/** YamuxStream is used to represent a logical stream within a session */\nexport class YamuxStream extends AbstractStream {\n streamId: number\n state: StreamState\n\n /** The number of available bytes to send */\n private sendWindowCapacity: number\n /** The number of bytes available to receive in a full window */\n private recvWindow: number\n /** The number of available bytes to receive */\n private recvWindowCapacity: number\n private maxStreamWindowSize: number\n\n /**\n * An 'epoch' is the time it takes to process and read data\n *\n * Used in conjunction with RTT to determine whether to increase the recvWindow\n */\n private epochStart: number\n private readonly getRTT: () => number\n\n private readonly sendFrame: (header: FrameHeader, body?: Uint8ArrayList) => boolean\n\n constructor (init: YamuxStreamInit) {\n const initialWindowSize = init.initialStreamWindowSize ?? INITIAL_STREAM_WINDOW\n\n super({\n ...init,\n maxMessageSize: initialWindowSize - HEADER_LENGTH\n })\n\n this.streamId = init.streamId\n this.state = init.state\n this.sendWindowCapacity = initialWindowSize\n this.recvWindow = initialWindowSize\n this.recvWindowCapacity = this.recvWindow\n this.maxStreamWindowSize = init.maxStreamWindowSize ?? MAX_STREAM_WINDOW\n this.epochStart = Date.now()\n this.getRTT = init.getRTT\n this.sendFrame = init.sendFrame\n\n const setStateToFinishedOnCloseListener = (): void => {\n this.state = StreamState.Finished\n }\n this.addEventListener('close', setStateToFinishedOnCloseListener)\n }\n\n /**\n * Send a data message to the remote muxer\n */\n sendData (buf: Uint8ArrayList): SendResult {\n const totalBytes = buf.byteLength\n let sentBytes = 0\n let canSendMore = true\n\n this.log?.trace('send window capacity is %d bytes', this.sendWindowCapacity)\n\n // send in chunks, waiting for window updates\n while (buf.byteLength > 0) {\n // we exhausted the send window, sending will resume later\n if (this.sendWindowCapacity === 0) {\n canSendMore = false\n this.log?.trace('sent %d/%d bytes, exhausted send window, waiting for window update', sentBytes, totalBytes)\n break\n }\n\n // send as much as we can\n const toSend = Math.min(this.sendWindowCapacity, buf.byteLength)\n const flags = this.getSendFlags()\n\n const data = buf.sublist(0, toSend)\n buf.consume(toSend)\n\n const muxerSendMore = this.sendFrame({\n type: FrameType.Data,\n flag: flags,\n streamID: this.streamId,\n length: toSend\n }, data)\n\n this.sendWindowCapacity -= toSend\n sentBytes += toSend\n\n if (!muxerSendMore) {\n canSendMore = muxerSendMore\n this.log.trace('sent %d/%d bytes, wait for muxer to have more send capacity', sentBytes, totalBytes)\n break\n }\n }\n\n return {\n sentBytes,\n canSendMore\n }\n }\n\n /**\n * Send a reset message to the remote muxer\n */\n sendReset (): void {\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: Flag.RST,\n streamID: this.streamId,\n length: 0\n })\n }\n\n /**\n * Send a message to the remote muxer, informing them no more data messages\n * will be sent by this end of the stream\n */\n async sendCloseWrite (): Promise<void> {\n const flags = this.getSendFlags() | Flag.FIN\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: flags,\n streamID: this.streamId,\n length: 0\n })\n }\n\n /**\n * Send a message to the remote muxer, informing them no more data messages\n * will be read by this end of the stream - this is a no-op on Yamux streams\n */\n async sendCloseRead (options?: AbortOptions): Promise<void> {\n options?.signal?.throwIfAborted()\n }\n\n /**\n * Stop sending window updates temporarily - in the interim the the remote\n * send window will exhaust and the remote will stop sending data\n */\n sendPause (): void {\n this.state = StreamState.Paused\n }\n\n /**\n * Start sending window updates as normal\n */\n sendResume (): void {\n this.state = StreamState.Established\n this.sendWindowUpdate()\n }\n\n /**\n * handleWindowUpdate is called when the stream receives a window update frame\n */\n handleWindowUpdate (frame: Frame): void {\n this.processFlags(frame.header.flag)\n\n // increase send window\n this.sendWindowCapacity += frame.header.length\n\n // change the chunk size the superclass uses\n this.maxMessageSize = this.sendWindowCapacity - HEADER_LENGTH\n\n if (this.maxMessageSize < 0) {\n this.maxMessageSize = 0\n }\n\n if (this.maxMessageSize === 0) {\n return\n }\n\n // if writing is paused and the update increases our send window, notify\n // writers that writing can resume\n if (this.writeBuffer.byteLength > 0) {\n this.log?.trace('window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s', frame.header.length, this.writeBuffer.byteLength, this.sendingData)\n this.safeDispatchEvent('drain')\n }\n }\n\n /**\n * handleData is called when the stream receives a data frame\n */\n handleData (frame: Frame): void {\n if (!isDataFrame(frame)) {\n throw new InvalidFrameError('Frame was not data frame')\n }\n\n this.processFlags(frame.header.flag)\n\n // check that our recv window is not exceeded\n if (this.recvWindowCapacity < frame.header.length) {\n throw new ReceiveWindowExceededError('Receive window exceeded')\n }\n\n this.recvWindowCapacity -= frame.header.length\n\n this.onData(frame.data)\n\n this.sendWindowUpdate()\n }\n\n /**\n * processFlags is used to update the state of the stream based on set flags, if any.\n */\n private processFlags (flags: number): void {\n if ((flags & Flag.ACK) === Flag.ACK) {\n if (this.state === StreamState.SYNSent) {\n this.state = StreamState.Established\n }\n }\n\n if ((flags & Flag.FIN) === Flag.FIN) {\n this.onRemoteCloseWrite()\n }\n\n if ((flags & Flag.RST) === Flag.RST) {\n this.onRemoteReset()\n }\n }\n\n /**\n * getSendFlags determines any flags that are appropriate\n * based on the current stream state.\n *\n * The state is updated as a side-effect.\n */\n private getSendFlags (): number {\n switch (this.state) {\n case StreamState.Init:\n this.state = StreamState.SYNSent\n return Flag.SYN\n case StreamState.SYNReceived:\n this.state = StreamState.Established\n return Flag.ACK\n default:\n return 0\n }\n }\n\n /**\n * Potentially sends a window update enabling further remote writes to take\n * place.\n */\n sendWindowUpdate (): void {\n if (this.state === StreamState.Paused) {\n // we don't want any more data from the remote right now - update the\n // epoch start as otherwise when we unpause we'd be looking at the epoch\n // start from before we were paused\n this.epochStart = Date.now()\n\n return\n }\n\n // determine the flags if any\n const flags = this.getSendFlags()\n\n // If the stream has already been established\n // and we've processed data within the time it takes for 4 round trips\n // then we (up to) double the recvWindow\n const now = Date.now()\n const rtt = this.getRTT()\n\n if (flags === 0 && rtt > -1 && (now - this.epochStart) <= (rtt * 4)) {\n // we've already validated that maxStreamWindowSize can't be more than MAX_UINT32\n this.recvWindow = Math.min(this.recvWindow * 2, this.maxStreamWindowSize)\n }\n\n if (this.recvWindowCapacity >= this.recvWindow && flags === 0) {\n // a window update isn't needed\n return\n }\n\n // update the receive window\n const delta = this.recvWindow - this.recvWindowCapacity\n this.recvWindowCapacity = this.recvWindow\n\n // update the epoch start\n this.epochStart = now\n\n // send window update\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: flags,\n streamID: this.streamId,\n length: delta\n })\n }\n}\n", "import { InvalidParametersError, MuxerClosedError, TooManyOutboundProtocolStreamsError, serviceCapabilities } from '@libp2p/interface'\nimport { AbstractStreamMuxer, repeatingTask } from '@libp2p/utils'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { defaultConfig, verifyConfig } from './config.ts'\nimport { Decoder } from './decode.ts'\nimport { encodeHeader } from './encode.ts'\nimport { InvalidFrameError, isProtocolError, NotMatchingPingError, UnRequestedPingError } from './errors.ts'\nimport { Flag, FrameType, GoAwayCode } from './frame.ts'\nimport { StreamState, YamuxStream } from './stream.ts'\nimport type { Config } from './config.ts'\nimport type { Frame } from './decode.ts'\nimport type { FrameHeader } from './frame.ts'\nimport type { AbortOptions, MessageStream, StreamMuxerFactory } from '@libp2p/interface'\nimport type { RepeatingTask } from '@libp2p/utils'\n\nfunction debugFrame (header: FrameHeader): any {\n return {\n type: FrameType[header.type],\n flags: [\n (header.flag & Flag.SYN) === Flag.SYN ? 'SYN' : undefined,\n (header.flag & Flag.ACK) === Flag.ACK ? 'ACK' : undefined,\n (header.flag & Flag.FIN) === Flag.FIN ? 'FIN' : undefined,\n (header.flag & Flag.RST) === Flag.RST ? 'RST' : undefined\n ].filter(Boolean),\n streamID: header.streamID,\n length: header.length\n }\n}\n\nconst YAMUX_PROTOCOL_ID = '/yamux/1.0.0'\n\nexport interface YamuxMuxerInit extends Partial<Config> {\n}\n\nexport class Yamux implements StreamMuxerFactory {\n protocol = YAMUX_PROTOCOL_ID\n private readonly _init: Partial<Config>\n\n constructor (init: Partial<Config> = {}) {\n this._init = init\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/yamux'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/stream-multiplexing'\n ]\n\n createStreamMuxer (maConn: MessageStream): YamuxMuxer {\n return new YamuxMuxer(maConn, {\n ...this._init\n })\n }\n}\n\nexport interface CloseOptions extends AbortOptions {\n reason?: GoAwayCode\n}\n\nexport interface ActivePing extends PromiseWithResolvers<number> {\n id: number\n start: number\n}\n\nexport class YamuxMuxer extends AbstractStreamMuxer<YamuxStream> {\n /** The next stream id to be used when initiating a new stream */\n private nextStreamID: number\n\n /** The next ping id to be used when pinging */\n private nextPingID: number\n /** Tracking info for the currently active ping */\n private activePing?: ActivePing\n /** Round trip time */\n private rtt: number\n\n /** True if client, false if server */\n private client: boolean\n\n private localGoAway?: GoAwayCode\n private remoteGoAway?: GoAwayCode\n\n /** Number of tracked inbound streams */\n private numInboundStreams: number\n /** Number of tracked outbound streams */\n private numOutboundStreams: number\n\n private decoder: Decoder\n private keepAlive?: RepeatingTask\n\n private enableKeepAlive: boolean\n private keepAliveInterval: number\n private maxInboundStreams: number\n private maxOutboundStreams: number\n\n constructor (maConn: MessageStream, init: YamuxMuxerInit = {}) {\n super(maConn, {\n ...init,\n protocol: YAMUX_PROTOCOL_ID,\n name: 'yamux'\n })\n\n this.client = maConn.direction === 'outbound'\n verifyConfig(init)\n\n this.enableKeepAlive = init.enableKeepAlive ?? defaultConfig.enableKeepAlive\n this.keepAliveInterval = init.keepAliveInterval ?? defaultConfig.keepAliveInterval\n this.maxInboundStreams = init.maxInboundStreams ?? defaultConfig.maxInboundStreams\n this.maxOutboundStreams = init.maxOutboundStreams ?? defaultConfig.maxOutboundStreams\n\n this.decoder = new Decoder()\n\n this.numInboundStreams = 0\n this.numOutboundStreams = 0\n\n // client uses odd streamIDs, server uses even streamIDs\n this.nextStreamID = this.client ? 1 : 2\n\n this.nextPingID = 0\n this.rtt = -1\n\n this.log.trace('muxer created')\n\n if (this.enableKeepAlive) {\n this.log.trace('muxer keepalive enabled interval=%s', this.keepAliveInterval)\n this.keepAlive = repeatingTask(async (options) => {\n try {\n await this.ping(options)\n } catch (err: any) {\n // TODO: should abort here?\n this.log.error('ping error: %s', err)\n }\n }, this.keepAliveInterval, {\n // send an initial ping to establish RTT\n runImmediately: true\n })\n this.keepAlive.start()\n }\n }\n\n onData (buf: Uint8Array | Uint8ArrayList): void {\n for (const frame of this.decoder.emitFrames(buf)) {\n this.handleFrame(frame)\n }\n }\n\n onCreateStream (): YamuxStream {\n if (this.remoteGoAway !== undefined) {\n throw new MuxerClosedError('Muxer closed remotely')\n }\n\n if (this.localGoAway !== undefined) {\n throw new MuxerClosedError('Muxer closed locally')\n }\n\n const id = this.nextStreamID\n this.nextStreamID += 2\n\n // check against our configured maximum number of outbound streams\n if (this.numOutboundStreams >= this.maxOutboundStreams) {\n throw new TooManyOutboundProtocolStreamsError('max outbound streams exceeded')\n }\n\n this.log.trace('new outgoing stream id=%s', id)\n\n const stream = this._newStream(id, StreamState.Init, 'outbound')\n\n this.numOutboundStreams++\n\n // send a window update to open the stream on the receiver end. do this in a\n // microtask so the stream gets added to the streams array by the superclass\n // before we send the SYN flag, otherwise we create a race condition whereby\n // we can receive the ACK before the stream is added to the streams list\n queueMicrotask(() => {\n stream.sendWindowUpdate()\n })\n\n return stream\n }\n\n /**\n * Initiate a ping and wait for a response\n *\n * Note: only a single ping will be initiated at a time.\n * If a ping is already in progress, a new ping will not be initiated.\n *\n * @returns the round-trip-time in milliseconds\n */\n async ping (options?: AbortOptions): Promise<number> {\n if (this.remoteGoAway !== undefined) {\n throw new MuxerClosedError('Muxer closed remotely')\n }\n if (this.localGoAway !== undefined) {\n throw new MuxerClosedError('Muxer closed locally')\n }\n\n if (this.activePing != null) {\n // an active ping is already in progress, piggyback off that\n return raceSignal(this.activePing.promise, options?.signal)\n }\n\n // An active ping does not yet exist, handle the process here\n // create active ping\n this.activePing = Object.assign(Promise.withResolvers<number>(), {\n id: this.nextPingID++,\n start: Date.now()\n })\n // send ping\n this.sendPing(this.activePing.id)\n // await pong\n try {\n this.rtt = await raceSignal(this.activePing.promise, options?.signal)\n } finally {\n // clean-up active ping\n this.activePing = undefined\n }\n\n return this.rtt\n }\n\n /**\n * Get the ping round trip time\n *\n * Note: Will return 0 if no successful ping has yet been completed\n *\n * @returns the round-trip-time in milliseconds\n */\n getRTT (): number {\n return this.rtt\n }\n\n /**\n * Close the muxer\n */\n async close (options: CloseOptions = {}): Promise<void> {\n if (this.status !== 'open') {\n // already closed\n return\n }\n\n try {\n const reason = options?.reason ?? GoAwayCode.NormalTermination\n\n this.log.trace('muxer close reason=%s', GoAwayCode[reason])\n\n await super.close(options)\n\n // send reason to the other side, allow the other side to close gracefully\n this.sendGoAway(reason)\n } finally {\n this.keepAlive?.stop()\n }\n }\n\n abort (err: Error): void {\n if (this.status !== 'open') {\n // already closed\n return\n }\n\n try {\n super.abort(err)\n\n let reason = GoAwayCode.InternalError\n\n if (isProtocolError(err)) {\n reason = err.reason\n }\n\n // If reason was provided, use that, otherwise use the presence of `err` to determine the reason\n this.log.error('muxer abort reason=%s error=%s', reason, err)\n\n // send reason to the other side, allow the other side to close gracefully\n this.sendGoAway(reason)\n } finally {\n this.keepAlive?.stop()\n }\n }\n\n onTransportClosed (): void {\n try {\n super.onTransportClosed()\n } finally {\n this.keepAlive?.stop()\n }\n }\n\n /** Create a new stream */\n private _newStream (streamId: number, state: StreamState, direction: 'inbound' | 'outbound'): YamuxStream {\n if (this.streams.find(s => s.streamId === streamId) != null) {\n throw new InvalidParametersError('Stream already exists with that id')\n }\n\n const stream = new YamuxStream({\n ...this.streamOptions,\n id: `${streamId}`,\n streamId,\n state,\n direction,\n sendFrame: this.sendFrame.bind(this),\n log: this.log.newScope(`${direction}:${streamId}`),\n getRTT: this.getRTT.bind(this)\n })\n\n stream.addEventListener('close', () => {\n this.closeStream(streamId)\n }, {\n once: true\n })\n\n return stream\n }\n\n /**\n * closeStream is used to close a stream once both sides have\n * issued a close.\n */\n private closeStream (id: number): void {\n if (this.client === (id % 2 === 0)) {\n this.numInboundStreams--\n } else {\n this.numOutboundStreams--\n }\n }\n\n private handleFrame (frame: Frame): void {\n const {\n streamID,\n type,\n length\n } = frame.header\n\n this.log.trace('received frame %o', debugFrame(frame.header))\n\n if (streamID === 0) {\n switch (type) {\n case FrameType.Ping:\n { this.handlePing(frame.header); return }\n case FrameType.GoAway:\n { this.handleGoAway(length); return }\n default:\n // Invalid state\n throw new InvalidFrameError('Invalid frame type')\n }\n } else {\n switch (frame.header.type) {\n case FrameType.Data:\n case FrameType.WindowUpdate:\n { this.handleStreamMessage(frame); return }\n default:\n // Invalid state\n throw new InvalidFrameError('Invalid frame type')\n }\n }\n }\n\n private handlePing (header: FrameHeader): void {\n // If the ping is initiated by the sender, send a response\n if (header.flag === Flag.SYN) {\n this.log.trace('received ping request pingId=%s', header.length)\n this.sendPing(header.length, Flag.ACK)\n } else if (header.flag === Flag.ACK) {\n this.log.trace('received ping response pingId=%s', header.length)\n this.handlePingResponse(header.length)\n } else {\n // Invalid state\n throw new InvalidFrameError('Invalid frame flag')\n }\n }\n\n private handlePingResponse (pingId: number): void {\n if (this.activePing === undefined) {\n // this ping was not requested\n throw new UnRequestedPingError('ping not requested')\n }\n if (this.activePing.id !== pingId) {\n // this ping doesn't match our active ping request\n throw new NotMatchingPingError('ping doesn\\'t match our id')\n }\n\n // valid ping response\n this.activePing.resolve(Date.now() - this.activePing.start)\n }\n\n private handleGoAway (reason: GoAwayCode): void {\n this.log.trace('received GoAway reason=%s', GoAwayCode[reason] ?? 'unknown')\n this.remoteGoAway = reason\n\n if (reason === GoAwayCode.NormalTermination) {\n this.onTransportClosed()\n } else {\n // reset any streams that are still open and close the muxer\n this.abort(new Error('Remote sent GoAway'))\n }\n }\n\n private handleStreamMessage (frame: Frame): void {\n const { streamID, flag, type } = frame.header\n\n if ((flag & Flag.SYN) === Flag.SYN) {\n this.incomingStream(streamID)\n }\n\n const stream = this.streams.find(s => s.streamId === streamID)\n if (stream === undefined) {\n this.log.trace('frame for missing stream id=%s', streamID)\n\n return\n }\n\n switch (type) {\n case FrameType.WindowUpdate: {\n stream.handleWindowUpdate(frame); return\n }\n case FrameType.Data: {\n stream.handleData(frame); return\n }\n default:\n throw new Error('unreachable')\n }\n }\n\n private incomingStream (id: number): void {\n if (this.client !== (id % 2 === 0)) {\n throw new InvalidParametersError('Both endpoints are clients')\n }\n if (this.streams.find(s => s.streamId === id)) {\n return\n }\n\n this.log.trace('new incoming stream id=%s', id)\n\n if (this.localGoAway !== undefined) {\n // reject (reset) immediately if we are doing a go away\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: Flag.RST,\n streamID: id,\n length: 0\n })\n return\n }\n\n // check against our configured maximum number of inbound streams\n if (this.numInboundStreams >= this.maxInboundStreams) {\n this.log('maxIncomingStreams exceeded, forcing stream reset')\n this.sendFrame({\n type: FrameType.WindowUpdate,\n flag: Flag.RST,\n streamID: id,\n length: 0\n })\n return\n }\n\n // allocate a new stream\n const stream = this._newStream(id, StreamState.SYNReceived, 'inbound')\n\n this.numInboundStreams++\n\n // the stream should now be tracked\n this.onRemoteStream(stream)\n }\n\n private sendFrame (header: FrameHeader, data?: Uint8ArrayList): boolean {\n let encoded: Uint8Array | Uint8ArrayList\n\n if (header.type === FrameType.Data) {\n if (data == null) {\n throw new InvalidFrameError('Invalid frame')\n }\n\n encoded = new Uint8ArrayList(encodeHeader(header), data)\n } else {\n encoded = encodeHeader(header)\n }\n\n this.log.trace('sending frame %o', debugFrame(header))\n\n return this.send(encoded)\n }\n\n private sendPing (pingId: number, flag: Flag = Flag.SYN): void {\n if (flag === Flag.SYN) {\n this.log.trace('sending ping request pingId=%s', pingId)\n } else {\n this.log.trace('sending ping response pingId=%s', pingId)\n }\n this.sendFrame({\n type: FrameType.Ping,\n flag,\n streamID: 0,\n length: pingId\n })\n }\n\n private sendGoAway (reason: GoAwayCode = GoAwayCode.NormalTermination): void {\n this.log('sending GoAway reason=%s', GoAwayCode[reason])\n this.localGoAway = reason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AmCA,CAAM,EAE1D,KAAK,UAAU,CACb,KAAMpC,EAAU,KAChB,KAAAuC,EACA,SAAU,EACV,OAAQH,EACT,CACH,CAEQ,WAAYb,EAAqBC,EAAW,kBAAiB,CACnE,KAAK,IAAI,2BAA4BA,EAAWD,CAAM,CAAC,EACvD,KAAK,YAAcA,EACnB,KAAK,UAAU,CACb,KAAMvB,EAAU,OAChB,KAAM,EACN,SAAU,EACV,OAAQuB,EACT,CACH,G/BlbI,SAAUqB,GAAOC,EAAuB,CAAA,EAAE,CAC9C,MAAO,IAAM,IAAIC,GAAMD,CAAI,CAC7B",
6
+ "names": ["index_exports", "__export", "GoAwayCode", "yamux", "InvalidParametersError", "message", "MuxerClosedError", "message", "StreamResetError", "StreamStateError", "message", "StreamBufferError", "TooManyOutboundProtocolStreamsError", "message", "StreamMessageEvent", "data", "eventInitDict", "StreamCloseEvent", "local", "error", "StreamAbortEvent", "StreamResetEvent", "isEventObject", "obj", "isBoolean", "flattenOptions", "options", "flattenMoreOptions", "opts", "captureIsEqual", "optsA", "optsB", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "wrapper", "evt", "list", "entry", "onAbort", "detail", "serviceCapabilities", "alloc", "size", "allocUnsafe", "isByteArrayWithArrayBuffer", "b", "asUint8Array", "buf", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "asUint8Array", "equals", "a", "b", "i", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "_Uint8ArrayList", "data", "length", "chunk", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "pDefer", "deferred", "resolve", "reject", "FixedFIFO", "hwm", "data", "last", "FIFO", "options", "obj", "val", "prev", "next", "AbortError", "message", "code", "pushable", "options", "_pushable", "buffer", "next", "_pushable", "getNext", "options", "onEnd", "buffer", "FIFO", "pushable", "onNext", "ended", "drain", "pDefer", "waitNext", "resolve", "reject", "next", "err", "bufferNext", "bufferError", "push", "value", "end", "_return", "_throw", "signal", "cancel", "listener", "AbortError", "opts", "TimeoutError", "_TimeoutError", "message", "options", "getAbortedReason", "signal", "pTimeout", "promise", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "normalizeEmitter", "emitter", "addListener", "removeListener", "pEventMultiple", "event", "options", "cancel", "returnValue", "resolve", "reject", "events", "items", "onItem", "arguments_", "value", "error", "rejectHandler", "rejectionEvent", "timeout", "pTimeout", "pEvent", "arrayPromise", "promise", "array", "debounce", "func", "wait", "timeout", "output", "later", "MaxEarlyStreamsError", "StreamClosedError", "defaultTranslate", "signal", "raceSignal", "promise", "opts", "translateError", "listener", "resolve", "reject", "DEFAULT_MAX_READ_BUFFER_LENGTH", "AbstractMessageStream", "TypedEventEmitter", "#readableEnded", "init", "Uint8ArrayList", "continueSendingOnDrain", "err", "rejectOnDrainOnClose", "evt", "StreamClosedError", "options", "raceSignal", "output", "pushable", "streamAsyncIterableOnMessageListener", "streamAsyncIterableOnCloseListener", "streamAsyncIterableOnRemoteCloseWriteListener", "data", "StreamStateError", "StreamAbortEvent", "args", "StreamResetEvent", "StreamResetError", "StreamCloseEvent", "canSendMore", "totalBytes", "sentBytes", "end", "toSend", "willSend", "sendResult", "buf", "StreamMessageEvent", "StreamBufferError", "isPromise", "thing", "AbstractStreamMuxer", "TypedEventEmitter", "maConn", "init", "muxerMaConnOnMessage", "evt", "err", "muxerMaConnOnDrain", "stream", "muxerOnMaConnClose", "data", "result", "options", "raceSignal", "s", "MuxerClosedError", "isPromise", "MaxEarlyStreamsError", "muxerOnStreamEnd", "index", "args", "AbstractStream", "AbstractMessageStream", "init", "options", "pEvent", "anySignal", "signals", "controller", "onAbort", "reason", "s", "signal", "clear", "repeatingTask", "fn", "interval", "options", "timeout", "shutdownController", "running", "runTask", "opts", "signal", "anySignal", "runTaskDebounced", "debounce", "started", "ms", "FrameType", "Flag", "flagCodes", "x", "YAMUX_VERSION", "GoAwayCode", "HEADER_LENGTH", "ProtocolError", "message", "reason", "isProtocolError", "err", "InvalidFrameError", "GoAwayCode", "UnRequestedPingError", "NotMatchingPingError", "StreamAlreadyExistsError", "ProtocolError", "message", "GoAwayCode", "DecodeInvalidVersionError", "BothClientsError", "ReceiveWindowExceededError", "PROTOCOL_ERRORS", "InvalidFrameError", "UnRequestedPingError", "NotMatchingPingError", "StreamAlreadyExistsError", "DecodeInvalidVersionError", "BothClientsError", "ReceiveWindowExceededError", "INITIAL_STREAM_WINDOW", "MAX_STREAM_WINDOW", "defaultConfig", "INITIAL_STREAM_WINDOW", "MAX_STREAM_WINDOW", "verifyConfig", "config", "InvalidParametersError", "isDataFrame", "frame", "FrameType", "twoPow24", "decodeHeader", "data", "YAMUX_VERSION", "InvalidFrameError", "Decoder", "Uint8ArrayList", "buf", "frameSize", "HEADER_LENGTH", "header", "encodeHeader", "header", "frame", "HEADER_LENGTH", "StreamState", "YamuxStream", "AbstractStream", "init", "initialWindowSize", "INITIAL_STREAM_WINDOW", "HEADER_LENGTH", "MAX_STREAM_WINDOW", "setStateToFinishedOnCloseListener", "buf", "totalBytes", "sentBytes", "canSendMore", "toSend", "flags", "data", "muxerSendMore", "FrameType", "Flag", "options", "frame", "isDataFrame", "InvalidFrameError", "ReceiveWindowExceededError", "now", "rtt", "delta", "debugFrame", "header", "FrameType", "Flag", "YAMUX_PROTOCOL_ID", "Yamux", "init", "serviceCapabilities", "maConn", "YamuxMuxer", "AbstractStreamMuxer", "verifyConfig", "defaultConfig", "Decoder", "repeatingTask", "options", "err", "buf", "frame", "MuxerClosedError", "id", "TooManyOutboundProtocolStreamsError", "stream", "StreamState", "raceSignal", "reason", "GoAwayCode", "isProtocolError", "streamId", "state", "direction", "s", "InvalidParametersError", "YamuxStream", "streamID", "type", "length", "InvalidFrameError", "pingId", "UnRequestedPingError", "NotMatchingPingError", "flag", "data", "encoded", "Uint8ArrayList", "encodeHeader", "yamux", "init", "Yamux"]
7
7
  }