diff --git a/packages/interface/src/errors.ts b/packages/interface/src/errors.ts index 81d572673f..993fd6cd6d 100644 --- a/packages/interface/src/errors.ts +++ b/packages/interface/src/errors.ts @@ -2,10 +2,24 @@ * When this error is thrown it means an operation was aborted, * usually in response to the `abort` event being emitted by an * AbortSignal. + * + * @example + * + * ```TypeScript + * throw new AbortError('The operation was aborted') + * ``` */ export class AbortError extends Error { + /** + * The name of the error. + */ static name = 'AbortError' + /** + * Creates a new AbortError instance. + * + * @param message - The message for the error. + */ constructor (message: string = 'The operation was aborted') { super(message) this.name = 'AbortError' @@ -14,10 +28,24 @@ export class AbortError extends Error { /** * Thrown when a remote Peer ID does not match the expected one + * + * @example + * + * ```TypeScript + * throw new UnexpectedPeerError('Unexpected peer') + * ``` */ export class UnexpectedPeerError extends Error { + /** + * The name of the error. + */ static name = 'UnexpectedPeerError' + /** + * Creates a new UnexpectedPeerError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Unexpected Peer') { super(message) this.name = 'UnexpectedPeerError' @@ -26,10 +54,24 @@ export class UnexpectedPeerError extends Error { /** * Thrown when a crypto exchange fails + * + * @example + * + * ```TypeScript + * throw new InvalidCryptoExchangeError('Invalid crypto exchange') + * ``` */ export class InvalidCryptoExchangeError extends Error { + /** + * The name of the error. + */ static name = 'InvalidCryptoExchangeError' + /** + * Creates a new InvalidCryptoExchangeError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Invalid crypto exchange') { super(message) this.name = 'InvalidCryptoExchangeError' @@ -38,10 +80,24 @@ export class InvalidCryptoExchangeError extends Error { /** * Thrown when invalid parameters are passed to a function or method call + * + * @example + * + * ```TypeScript + * throw new InvalidParametersError('Invalid parameters') + * ``` */ export class InvalidParametersError extends Error { + /** + * The name of the error. + */ static name = 'InvalidParametersError' + /** + * Creates a new InvalidParametersError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Invalid parameters') { super(message) this.name = 'InvalidParametersError' @@ -50,10 +106,24 @@ export class InvalidParametersError extends Error { /** * Thrown when a public key is invalid + * + * @example + * + * ```TypeScript + * throw new InvalidPublicKeyError('Invalid public key') + * ``` */ export class InvalidPublicKeyError extends Error { + /** + * The name of the error. + */ static name = 'InvalidPublicKeyError' + /** + * Creates a new InvalidPublicKeyError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Invalid public key') { super(message) this.name = 'InvalidPublicKeyError' @@ -62,10 +132,24 @@ export class InvalidPublicKeyError extends Error { /** * Thrown when a private key is invalid + * + * @example + * + * ```TypeScript + * throw new InvalidPrivateKeyError('Invalid private key') + * ``` */ export class InvalidPrivateKeyError extends Error { + /** + * The name of the error. + */ static name = 'InvalidPrivateKeyError' + /** + * Creates a new InvalidPrivateKeyError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Invalid private key') { super(message) this.name = 'InvalidPrivateKeyError' @@ -74,10 +158,24 @@ export class InvalidPrivateKeyError extends Error { /** * Thrown when a operation is unsupported + * + * @example + * + * ```TypeScript + * throw new UnsupportedOperationError('Unsupported operation') + * ``` */ export class UnsupportedOperationError extends Error { + /** + * The name of the error. + */ static name = 'UnsupportedOperationError' + /** + * Creates a new UnsupportedOperationError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Unsupported operation') { super(message) this.name = 'UnsupportedOperationError' @@ -86,10 +184,24 @@ export class UnsupportedOperationError extends Error { /** * Thrown when a connection is closing + * + * @example + * + * ```TypeScript + * throw new ConnectionClosingError('The connection is closing') + * ``` */ export class ConnectionClosingError extends Error { + /** + * The name of the error. + */ static name = 'ConnectionClosingError' + /** + * Creates a new ConnectionClosingError instance. + * + * @param message - The message for the error. + */ constructor (message = 'The connection is closing') { super(message) this.name = 'ConnectionClosingError' @@ -98,10 +210,24 @@ export class ConnectionClosingError extends Error { /** * Thrown when a connection is closed + * + * @example + * + * ```TypeScript + * throw new ConnectionClosedError('The connection is closed') + * ``` */ export class ConnectionClosedError extends Error { + /** + * The name of the error. + */ static name = 'ConnectionClosedError' + /** + * Creates a new ConnectionClosedError instance. + * + * @param message - The message for the error. + */ constructor (message = 'The connection is closed') { super(message) this.name = 'ConnectionClosedError' @@ -110,10 +236,24 @@ export class ConnectionClosedError extends Error { /** * Thrown when a connection fails + * + * @example + * + * ```TypeScript + * throw new ConnectionFailedError('Connection failed') + * ``` */ export class ConnectionFailedError extends Error { + /** + * The name of the error. + */ static name = 'ConnectionFailedError' + /** + * Creates a new ConnectionFailedError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Connection failed') { super(message) this.name = 'ConnectionFailedError' @@ -122,10 +262,24 @@ export class ConnectionFailedError extends Error { /** * Thrown when the muxer is closed and an attempt to open a stream occurs + * + * @example + * + * ```TypeScript + * throw new MuxerClosedError('The muxer is closed') + * ``` */ export class MuxerClosedError extends Error { + /** + * The name of the error. + */ static name = 'MuxerClosedError' + /** + * Creates a new MuxerClosedError instance. + * + * @param message - The message for the error. + */ constructor (message = 'The muxer is closed') { super(message) this.name = 'MuxerClosedError' @@ -134,10 +288,24 @@ export class MuxerClosedError extends Error { /** * Thrown when a protocol stream is reset by the remote muxer + * + * @example + * + * ```TypeScript + * throw new StreamResetError('The stream has been reset') + * ``` */ export class StreamResetError extends Error { + /** + * The name of the error. + */ static name = 'StreamResetError' + /** + * Creates a new StreamResetError instance. + * + * @param message - The message for the error. + */ constructor (message = 'The stream has been reset') { super(message) this.name = 'StreamResetError' @@ -146,10 +314,24 @@ export class StreamResetError extends Error { /** * Thrown when a stream is in an invalid state + * + * @example + * + * ```TypeScript + * throw new StreamStateError('The stream is in an invalid state') + * ``` */ export class StreamStateError extends Error { + /** + * The name of the error. + */ static name = 'StreamStateError' + /** + * Creates a new StreamStateError instance. + * + * @param message - The message for the error. + */ constructor (message = 'The stream is in an invalid state') { super(message) this.name = 'StreamStateError' @@ -158,10 +340,24 @@ export class StreamStateError extends Error { /** * Thrown when a value could not be found + * + * @example + * + * ```TypeScript + * throw new NotFoundError('Not found') + * ``` */ export class NotFoundError extends Error { + /** + * The name of the error. + */ static name = 'NotFoundError' + /** + * Creates a new NotFoundError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Not found') { super(message) this.name = 'NotFoundError' @@ -170,10 +366,24 @@ export class NotFoundError extends Error { /** * Thrown when an invalid peer ID is encountered + * + * @example + * + * ```TypeScript + * throw new InvalidPeerIdError('Invalid PeerID') + * ``` */ export class InvalidPeerIdError extends Error { + /** + * The name of the error. + */ static name = 'InvalidPeerIdError' + /** + * Creates a new InvalidPeerIdError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Invalid PeerID') { super(message) this.name = 'InvalidPeerIdError' @@ -182,10 +392,24 @@ export class InvalidPeerIdError extends Error { /** * Thrown when an invalid multiaddr is encountered + * + * @example + * + * ```TypeScript + * throw new InvalidMultiaddrError('Invalid multiaddr') + * ``` */ export class InvalidMultiaddrError extends Error { + /** + * The name of the error. + */ static name = 'InvalidMultiaddrError' + /** + * Creates a new InvalidMultiaddrError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Invalid multiaddr') { super(message) this.name = 'InvalidMultiaddrError' @@ -194,10 +418,24 @@ export class InvalidMultiaddrError extends Error { /** * Thrown when an invalid CID is encountered + * + * @example + * + * ```TypeScript + * throw new InvalidCIDError('Invalid CID') + * ``` */ export class InvalidCIDError extends Error { + /** + * The name of the error. + */ static name = 'InvalidCIDError' + /** + * Creates a new InvalidCIDError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Invalid CID') { super(message) this.name = 'InvalidCIDError' @@ -206,10 +444,24 @@ export class InvalidCIDError extends Error { /** * Thrown when an invalid multihash is encountered + * + * @example + * + * ```TypeScript + * throw new InvalidMultihashError('Invalid Multihash') + * ``` */ export class InvalidMultihashError extends Error { + /** + * The name of the error. + */ static name = 'InvalidMultihashError' + /** + * Creates a new InvalidMultihashError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Invalid Multihash') { super(message) this.name = 'InvalidMultihashError' @@ -218,10 +470,24 @@ export class InvalidMultihashError extends Error { /** * Thrown when a protocol is not supported + * + * @example + * + * ```TypeScript + * throw new UnsupportedProtocolError('Unsupported protocol error') + * ``` */ export class UnsupportedProtocolError extends Error { + /** + * The name of the error. + */ static name = 'UnsupportedProtocolError' + /** + * Creates a new UnsupportedProtocolError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Unsupported protocol error') { super(message) this.name = 'UnsupportedProtocolError' @@ -230,10 +496,24 @@ export class UnsupportedProtocolError extends Error { /** * An invalid or malformed message was encountered during a protocol exchange + * + * @example + * + * ```TypeScript + * throw new InvalidMessageError('Invalid message') + * ``` */ export class InvalidMessageError extends Error { + /** + * The name of the error. + */ static name = 'InvalidMessageError' + /** + * Creates a new InvalidMessageError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Invalid message') { super(message) this.name = 'InvalidMessageError' @@ -243,10 +523,24 @@ export class InvalidMessageError extends Error { /** * Thrown when a remote peer sends a structurally valid message that does not * comply with the protocol + * + * @example + * + * ```TypeScript + * throw new ProtocolError('Protocol error') + * ``` */ export class ProtocolError extends Error { + /** + * The name of the error. + */ static name = 'ProtocolError' + /** + * Creates a new ProtocolError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Protocol error') { super(message) this.name = 'ProtocolError' @@ -255,10 +549,24 @@ export class ProtocolError extends Error { /** * Throw when an operation times out + * + * @example + * + * ```TypeScript + * throw new TimeoutError('Timed out') + * ``` */ export class TimeoutError extends Error { + /** + * The name of the error. + */ static name = 'TimeoutError' + /** + * Creates a new TimeoutError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Timed out') { super(message) this.name = 'TimeoutError' @@ -268,10 +576,24 @@ export class TimeoutError extends Error { /** * Thrown when a startable component is interacted with but it has not been * started yet + * + * @example + * + * ```TypeScript + * throw new NotStartedError('Not started') + * ``` */ export class NotStartedError extends Error { + /** + * The name of the error. + */ static name = 'NotStartedError' + /** + * Creates a new NotStartedError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Not started') { super(message) this.name = 'NotStartedError' @@ -280,10 +602,24 @@ export class NotStartedError extends Error { /** * Thrown when a component is started that has already been started + * + * @example + * + * ```TypeScript + * throw new AlreadyStartedError('Already started') + * ``` */ export class AlreadyStartedError extends Error { + /** + * The name of the error. + */ static name = 'AlreadyStartedError' + /** + * Creates a new AlreadyStartedError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Already started') { super(message) this.name = 'AlreadyStartedError' @@ -292,10 +628,24 @@ export class AlreadyStartedError extends Error { /** * Thrown when dialing an address failed + * + * @example + * + * ```TypeScript + * throw new DialError('Dial error') + * ``` */ export class DialError extends Error { + /** + * The name of the error. + */ static name = 'DialError' + /** + * Creates a new DialError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Dial error') { super(message) this.name = 'DialError' @@ -304,10 +654,24 @@ export class DialError extends Error { /** * Thrown when listening on an address failed + * + * @example + * + * ```TypeScript + * throw new ListenError('Listen error') + * ``` */ export class ListenError extends Error { + /** + * The name of the error. + */ static name = 'ListenError' + /** + * Creates a new ListenError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Listen error') { super(message) this.name = 'ListenError' @@ -318,10 +682,24 @@ export class ListenError extends Error { * This error is thrown when a limited connection is encountered, i.e. if the * user tried to open a stream on a connection for a protocol that is not * configured to run over limited connections. + * + * @example + * + * ```TypeScript + * throw new LimitedConnectionError('Limited connection') + * ``` */ export class LimitedConnectionError extends Error { + /** + * The name of the error. + */ static name = 'LimitedConnectionError' + /** + * Creates a new LimitedConnectionError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Limited connection') { super(message) this.name = 'LimitedConnectionError' @@ -330,10 +708,24 @@ export class LimitedConnectionError extends Error { /** * This error is thrown where there are too many inbound protocols streams open + * + * @example + * + * ```TypeScript + * throw new TooManyInboundProtocolStreamsError('Too many inbound protocol streams') + * ``` */ export class TooManyInboundProtocolStreamsError extends Error { + /** + * The name of the error. + */ static name = 'TooManyInboundProtocolStreamsError' + /** + * Creates a new TooManyInboundProtocolStreamsError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Too many inbound protocol streams') { super(message) this.name = 'TooManyInboundProtocolStreamsError' @@ -342,10 +734,24 @@ export class TooManyInboundProtocolStreamsError extends Error { /** * This error is thrown where there are too many outbound protocols streams open + * + * @example + * + * ```TypeScript + * throw new TooManyOutboundProtocolStreamsError('Too many outbound protocol streams') + * ``` */ export class TooManyOutboundProtocolStreamsError extends Error { + /** + * The name of the error. + */ static name = 'TooManyOutboundProtocolStreamsError' + /** + * Creates a new TooManyOutboundProtocolStreamsError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Too many outbound protocol streams') { super(message) this.name = 'TooManyOutboundProtocolStreamsError' @@ -354,10 +760,24 @@ export class TooManyOutboundProtocolStreamsError extends Error { /** * Thrown when and attempt to operate on an unsupported key was made + * + * @example + * + * ```TypeScript + * throw new UnsupportedKeyTypeError('Unsupported key type') + * ``` */ export class UnsupportedKeyTypeError extends Error { + /** + * The name of the error. + */ static name = 'UnsupportedKeyTypeError' + /** + * Creates a new UnsupportedKeyTypeError instance. + * + * @param message - The message for the error. + */ constructor (message = 'Unsupported key type') { super(message) this.name = 'UnsupportedKeyTypeError' diff --git a/packages/interface/src/event-target.ts b/packages/interface/src/event-target.ts index 1771f42995..0672831677 100644 --- a/packages/interface/src/event-target.ts +++ b/packages/interface/src/event-target.ts @@ -4,8 +4,17 @@ export interface EventCallback { (evt: EventType): void } export interface EventObject { handleEvent: EventCallback } export type EventHandler = EventCallback | EventObject +/** + * A listener for an event. + */ interface Listener { + /** + * Whether the listener is a one-time listener. + */ once: boolean + /** + * The callback for the listener. + */ callback: any } @@ -16,26 +25,110 @@ interface Listener { * https://github.com/microsoft/TypeScript/issues/43477 * https://github.com/microsoft/TypeScript/issues/299 * etc + * + * @example + * + * ```TypeScript + * const eventTarget = new TypedEventTarget<{ myEvent: { detail: string } }>() + * ``` */ + export interface TypedEventTarget > extends EventTarget { + /** + * Adds an event listener to the event target. + * + * @param type - The type of event to listen for. + * @param listener - The callback to invoke when the event is triggered. + * @param options - Additional options for the event listener. + * @example + * + * ```TypeScript + * eventTarget.addEventListener('myEvent', (event) => { + * console.log('myEvent triggered', event) + * }) + * ``` + */ addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void + /** + * Returns the number of listeners for a specific event type. + * + * @param type - The type of event to check. + * @returns The number of listeners for the event type. + * @example + * + * ```TypeScript + * const count = eventTarget.listenerCount('myEvent') + * console.log('Number of listeners for myEvent:', count) + * ``` + */ listenerCount (type: string): number + /** + * Removes an event listener from the event target. + * + * @param type - The type of event to remove the listener from. + * @param listener - The callback to remove from the event target. + * @param options - Additional options for the event listener. + * @example + * + * ```TypeScript + * eventTarget.removeEventListener('myEvent', (event) => { + * console.log('removed listener for myEvent', event) + * }) + * ``` + */ removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void + /** + * Removes an event listener from the event target. + * + * @param type - The type of event to remove the listener from. + * @param listener - The callback to remove from the event target. + * @param options - Additional options for the event listener. + * @example + * + * ```TypeScript + * eventTarget.removeEventListener('myEvent', (event) => { + * console.log('removed listener for myEvent', event) + * }) + * ``` + */ removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void + /** + * Dispatches a custom event to the event target. + * + * @param type - The type of event to dispatch. + * @param detail - The detail for the event. + * @returns True if the event was successfully dispatched, false otherwise. + * @example + * + * ```TypeScript + * eventTarget.safeDispatchEvent('myEvent', { detail: 'myEvent detail' }) + * ``` + */ safeDispatchEvent(type: keyof EventMap, detail: CustomEventInit): boolean } /** * An implementation of a typed event target - * etc + * + * @example + * + * ```TypeScript + * const eventTarget = new TypedEventEmitter<{ myEvent: { detail: string } }>() + * ``` */ export class TypedEventEmitter> extends EventTarget implements TypedEventTarget { + /** + * A map of listeners for each event type. + */ readonly #listeners = new Map() + /** + * Creates a new TypedEventEmitter instance. + */ constructor () { super() @@ -44,6 +137,18 @@ export class TypedEventEmitter> extends Eve setMaxListeners(Infinity, this) } + /** + * Returns the number of listeners for a specific event type. + * + * @param type - The type of event to check. + * @returns The number of listeners for the event type. + * @example + * + * ```TypeScript + * const count = eventTarget.listenerCount('myEvent') + * console.log('Number of listeners for myEvent:', count) + * ``` + */ listenerCount (type: string): number { const listeners = this.#listeners.get(type) @@ -54,7 +159,36 @@ export class TypedEventEmitter> extends Eve return listeners.length } + /** + * Adds an event listener to the event target. + * + * @param type - The type of event to listen for. + * @param listener - The callback to invoke when the event is triggered. + * @param options - Additional options for the event listener. + * @example + * + * ```TypeScript + * eventTarget.addEventListener('myEvent', (event) => { + * console.log('myEvent triggered', event) + * }) + */ addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void + + /** + * Adds an event listener to the event target. + * + * @param type - The type of event to listen for. + * @param listener - The callback to invoke when the event is triggered. + * @param options - Additional options for the event listener. + * @example + * + * ```TypeScript + * eventTarget.addEventListener('myEvent', (event) => { + * console.log('myEvent triggered', event) + * }) + * ``` + */ + addEventListener (type: string, listener: EventHandler, options?: boolean | AddEventListenerOptions): void { super.addEventListener(type, listener, options) @@ -71,7 +205,38 @@ export class TypedEventEmitter> extends Eve }) } + /** + * Removes an event listener from the event target. + * + * @param type - The type of event to remove the listener from. + * @param listener - The callback to remove from the event target. + * @param options - Additional options for the event listener. + * @example + * + * ```TypeScript + * eventTarget.removeEventListener('myEvent', (event) => { + * console.log('removed listener for myEvent', event) + * }) + * ``` + */ + removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void + + /** + * Removes an event listener from the event target. + * + * @param type - The type of event to remove the listener from. + * @param listener - The callback to remove from the event target. + * @param options - Additional options for the event listener. + * @example + * + * ```TypeScript + * eventTarget.removeEventListener('myEvent', (event) => { + * console.log('removed listener for myEvent', event) + * }) + * ``` + */ + removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void { super.removeEventListener(type.toString(), listener ?? null, options) @@ -85,6 +250,17 @@ export class TypedEventEmitter> extends Eve this.#listeners.set(type, list) } + /** + * Dispatches an event to the event target. + * + * @param event - The event to dispatch. + * @returns True if the event was successfully dispatched, false otherwise. + * @example + * + * ```TypeScript + * eventTarget.dispatchEvent(new Event('myEvent')) + * ``` + */ dispatchEvent (event: Event): boolean { const result = super.dispatchEvent(event) @@ -100,6 +276,18 @@ export class TypedEventEmitter> extends Eve return result } + /** + * Dispatches a custom event to the event target. + * + * @param type - The type of event to dispatch. + * @param detail - The detail for the event. + * @returns True if the event was successfully dispatched, false otherwise. + * @example + * + * ```TypeScript + * eventTarget.safeDispatchEvent('myEvent', { detail: 'myEvent detail' }) + * ``` + */ safeDispatchEvent(type: keyof EventMap, detail: CustomEventInit = {}): boolean { return this.dispatchEvent(new CustomEvent(type as string, detail)) } diff --git a/packages/interface/src/events.ts b/packages/interface/src/events.ts index 2e3ea49db0..96169b7400 100644 --- a/packages/interface/src/events.ts +++ b/packages/interface/src/events.ts @@ -2,6 +2,9 @@ import { setMaxListeners as nodeSetMaxListeners } from 'node:events' /** * Create a setMaxListeners that doesn't break browser usage + * + * @param n - The maximum number of listeners. + * @param eventTargets - The event targets to set the maximum number of listeners for. */ export const setMaxListeners: typeof nodeSetMaxListeners = (n, ...eventTargets) => { try { diff --git a/packages/interface/src/index.ts b/packages/interface/src/index.ts index f49a87f0cc..eabf40ab6b 100644 --- a/packages/interface/src/index.ts +++ b/packages/interface/src/index.ts @@ -31,7 +31,8 @@ import type { Multiaddr } from '@multiformats/multiaddr' import type { ProgressOptions, ProgressEvent } from 'progress-events' /** - * Used by the connection manager to sort addresses into order before dialling + * Used by the connection manager to sort addresses before dialing. + * The function returns -1, 0, or 1 to determine order. */ export interface AddressSorter { (a: Address, b: Address): -1 | 0 | 1 @@ -41,18 +42,26 @@ export interface AddressSorter { * Event detail emitted when peer data changes */ export interface PeerUpdate { + /** The updated peer data */ peer: Peer + /** The previous state of the peer, if available. */ previous?: Peer } + /** * Peer data signed by the remote Peer's public key */ export interface SignedPeerRecord { + /** Peer network addresses */ addresses: Multiaddr[] + /** Sequence number for tracking updates */ seq: bigint } +/** + * TLS certificate and key pair in PEM format + */ export interface TLSCertificate { /** * The private key that corresponds to the certificate in PEM format @@ -121,18 +130,40 @@ export interface IdentifyResult { /** * Logger component for libp2p + * + * Provides methods for logging messages, errors, and traces. */ export interface Logger { + /** + * Logs a message with the formatter and arguments. + */ (formatter: any, ...args: any[]): void + + /** + * Logs an error with the formatter and arguments. + */ error(formatter: any, ...args: any[]): void + + /** + * Logs a trace with the formatter and arguments. + */ trace(formatter: any, ...args: any[]): void + + /** + * Flag to check if logging is enabled. + */ enabled: boolean } /** * Peer logger component for libp2p + * + * Provides a method to get a logger for a specific component. */ export interface ComponentLogger { + /** + * Gets a logger for a component. + */ forComponent(name: string): Logger } @@ -335,6 +366,10 @@ export interface Libp2pEvents { */ export type ServiceMap = Record +/** + * The status of a pending dial operation. + * Can be one of: 'queued', 'active', 'error', or 'success'. + */ export type PendingDialStatus = 'queued' | 'active' | 'error' | 'success' /** @@ -364,8 +399,15 @@ export interface PendingDial { multiaddrs: Multiaddr[] } +/** + * The status of a libp2p node. + * Can be one of: 'starting', 'started', 'stopping', or 'stopped'. + */ export type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped' +/** + * Options for checking if a multiaddr is dialable. + */ export interface IsDialableOptions extends AbortOptions { /** * If the dial attempt would open a protocol, and the multiaddr being dialed @@ -376,18 +418,48 @@ export interface IsDialableOptions extends AbortOptions { runOnLimitedConnection?: boolean } +/** + * Progress events for the transport manager. + */ export type TransportManagerDialProgressEvents = + /** + * Emitted when the selected transport is changed. + */ ProgressEvent<'transport-manager:selected-transport', string> +/** + * Progress events for the open connection process. + */ export type OpenConnectionProgressEvents = TransportManagerDialProgressEvents | + /** + * Emitted when the connection is already connected. + */ ProgressEvent<'dial-queue:already-connected'> | + /** + * Emitted when the connection is already in the dial queue. + */ ProgressEvent<'dial-queue:already-in-dial-queue'> | + /** + * Emitted when the connection is added to the dial queue. + */ ProgressEvent<'dial-queue:add-to-dial-queue'> | + /** + * Emitted when the dial starts. + */ ProgressEvent<'dial-queue:start-dial'> | + /** + * Emitted when the calculated addresses are available. + */ ProgressEvent<'dial-queue:calculated-addresses', Address[]> | + /** + * Emitted when the outbound connection upgrade starts. + */ OutboundConnectionUpgradeEvents +/** + * Options for dialing a peer. + */ export interface DialOptions extends AbortOptions, ProgressOptions { /** * If true, open a new connection to the remote even if one already exists @@ -395,6 +467,9 @@ export interface DialOptions extends AbortOptions, ProgressOptions { force?: boolean } +/** + * Options for dialing a peer with a specific protocol. + */ export interface DialProtocolOptions extends NewStreamOptions { } @@ -557,6 +632,14 @@ export interface Libp2p extends Startable, Ty /** * Return a list of all peers we currently have a connection open to + * + * @example + * + * ```TypeScript + * for (const peer of libp2p.getPeers()) { + * console.log(peer) + * } + * ``` */ getPeers(): PeerId[] diff --git a/packages/interface/src/startable.ts b/packages/interface/src/startable.ts index f5f4e7351f..23e5b4c8a6 100644 --- a/packages/interface/src/startable.ts +++ b/packages/interface/src/startable.ts @@ -45,11 +45,26 @@ export interface Startable { afterStop?(): void | Promise } +/** + * Checks if an object implements the Startable interface. + * + * @param obj - The object to check. + * @returns True if the object implements the Startable interface, false otherwise. + */ export function isStartable (obj: any): obj is Startable { return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function' } +/** + * Starts a list of startable objects. + * + * @param objs - The objects to start. + * @returns A promise that resolves when all objects have been started. + */ export async function start (...objs: any[]): Promise { + /** + * The list of startable objects. + */ const startables: Startable[] = [] for (const obj of objs) { @@ -81,7 +96,16 @@ export async function start (...objs: any[]): Promise { ) } +/** + * Stops a list of startable objects. + * + * @param objs - The objects to stop. + * @returns A promise that resolves when all objects have been stopped. + */ export async function stop (...objs: any[]): Promise { + /** + * The list of startable objects. + */ const startables: Startable[] = [] for (const obj of objs) { diff --git a/packages/interface/src/transport.ts b/packages/interface/src/transport.ts index 2d64a203fa..f587566a4c 100644 --- a/packages/interface/src/transport.ts +++ b/packages/interface/src/transport.ts @@ -5,6 +5,18 @@ import type { StreamMuxerFactory } from './stream-muxer.js' import type { Multiaddr } from '@multiformats/multiaddr' import type { ProgressOptions, ProgressEvent } from 'progress-events' +/** + * This defines the events that can be emitted by a listener. + * + * @example + * + * ```TypeScript + * const listener = transport.createListener() + * const event: ListenerEvents = listener.addEventListener('listening', () => { + * console.log('listening') + * }) + * ``` + */ export interface ListenerEvents { /** * This event signals to the transport manager that the listening addresses @@ -24,19 +36,54 @@ export interface ListenerEvents { 'close': CustomEvent } +/** + * This defines the listener object. + * + * @example + * ```TypeScript + * const listener = transport.createListener() + * await listener.listen(multiaddr) + * const addresses = listener.getAddrs() + * await listener.close() + * ``` + */ export interface Listener extends TypedEventTarget { /** * Start a listener + * + * @param multiaddr - The `Multiaddr` to listen on + * + * @returns A promise that resolves when the listener is started + * + * @example + * + * ```TypeScript + * await listener.listen(multiaddr) + * ``` */ listen(multiaddr: Multiaddr): Promise /** * Get listen addresses + * + * @returns The listen addresses + * + * @example + * + * ```TypeScript + * const addresses = listener.getAddrs() + * ``` */ getAddrs(): Multiaddr[] /** * Close listener - * - * @returns {Promise} + * + * @returns A promise that resolves when the listener is closed + * + * @example + * + * ```TypeScript + * await listener.close() + * ``` */ close(): Promise /** @@ -46,10 +93,45 @@ export interface Listener extends TypedEventTarget { updateAnnounceAddrs(addrs: Multiaddr[]): void } +/** + * This is the symbol for the transport. + */ export const transportSymbol = Symbol.for('@libp2p/transport') -export interface MultiaddrFilter { (multiaddrs: Multiaddr[]): Multiaddr[] } +/** + * A function type used for filtering an array of `Multiaddr` objects. + * + * This function takes an array of `Multiaddr` objects as input and returns a subset of them, + * based on specific filtering criteria (e.g., protocol type). + * + * @param multiaddrs - An array of `Multiaddr` objects to filter. + * @returns A filtered array of `Multiaddr` objects that match the criteria. + * + * @example + * + * ```TypeScript + * const filter: MultiaddrFilter = (multiaddrs) => + * multiaddrs.filter((ma) => ma.protoName === 'tcp') + * + * const filteredAddrs = filter(multiaddrs) + * console.log(filteredAddrs) + * // Output: Only Multiaddrs with 'protoName' === 'tcp' + * ``` + */ +export interface MultiaddrFilter { + (multiaddrs: Multiaddr[]): Multiaddr[] +} +/** + * This is the interface for the create listener options. + * + * @example + * + * ```TypeScript + * const listener = transport.createListener() + * const options: CreateListenerOptions = { upgrader: listener.upgrader } + * ``` + */ export interface CreateListenerOptions { /** * The upgrader turns a MultiaddrConnection into a Connection and notifies @@ -58,16 +140,39 @@ export interface CreateListenerOptions { upgrader: Upgrader } +/** + * This is the interface for the dial transport options. + * + * @example + * + * ```TypeScript + * const options: DialTransportOptions = { upgrader } + * ``` + */ export interface DialTransportOptions extends Required, ProgressOptions { /** * The upgrader turns a MultiaddrConnection into a Connection which should be * returned by the transport's dial method + * + * This object implements the `Upgrader` interface which provides methods to: + * - `upgradeInbound`: Upgrade an incoming connection. + * - `upgradeOutbound`: Upgrade an outgoing connection. + * + * See the `Upgrader` interface documentation for more details. */ upgrader: Upgrader } /** * A libp2p transport offers dial and listen methods to establish connections. + * + * @example + * + * ```TypeScript + * const transport: Transport = { listenFilter, dialFilter } + * await transport.dial(ma) + * const listener = transport.createListener({ upgrader }) + * ``` */ export interface Transport { /** @@ -82,11 +187,32 @@ export interface Transport { /** * Dial a given multiaddr. + * + * @param ma - The `Multiaddr` to dial + * @param options - The options for the dial. + * + * @returns A promise that resolves to the `Connection` + * + * @example + * + * ```TypeScript + * const connection = await transport.dial(multiaddr) + * ``` */ dial(ma: Multiaddr, options: DialTransportOptions): Promise /** * Create transport listeners. + * + * @param options - The options for the listener. + * + * @returns A promise that resolves to the `Listener` + * + * @example + * + * ```TypeScript + * const listener = transport.createListener({ upgrader }) + * ``` */ createListener(options: CreateListenerOptions): Listener @@ -103,6 +229,18 @@ export interface Transport { dialFilter: MultiaddrFilter } +/** + * This function checks if the given object is a transport. + * + * @param other - The object to check. + * @returns `true` if the object is a transport, `false` otherwise. + * + * @example + * + * ```TypeScript + * const isTransport = isTransport(transport) + * ``` + */ export function isTransport (other: any): other is Transport { return other != null && Boolean(other[transportSymbol]) } @@ -122,31 +260,92 @@ export enum FaultTolerance { NO_FATAL } +/** + * This is the interface for the upgrader options. + * + * @example + * + * ```TypeScript + * const upgraderOptions: UpgraderOptions = { skipEncryption: true, limits: { bytes: 1024, seconds: 10 } } + * ``` + */ export interface UpgraderOptions extends ProgressOptions, Required { skipEncryption?: boolean + /** + * Skips protection (optional) + */ skipProtection?: boolean + /** + * The muxer factory (optional) + */ muxerFactory?: StreamMuxerFactory + /** + * The connection limits (optional) + */ limits?: ConnectionLimits initiator?: boolean } +/** + * This is the type for the inbound connection upgrade events. + * + * @example + * + * ```TypeScript + * const events: InboundConnectionUpgradeEvents = { type: 'upgrader:encrypt-inbound-connection' } + */ export type InboundConnectionUpgradeEvents = ProgressEvent<'upgrader:encrypt-inbound-connection'> | ProgressEvent<'upgrader:multiplex-inbound-connection'> +/** + * This is the type for the outbound connection upgrade events. + * + * @example + * + * ```TypeScript + * const events: OutboundConnectionUpgradeEvents = { type: 'upgrader:encrypt-outbound-connection' } + */ export type OutboundConnectionUpgradeEvents = ProgressEvent<'upgrader:encrypt-outbound-connection'> | ProgressEvent<'upgrader:multiplex-outbound-connection'> +/** + * This is the interface for the upgrader. + * + * @example + * + * ```TypeScript + * const upgrader: Upgrader = { upgradeOutbound, upgradeInbound } + * ``` + */ export interface Upgrader { /** * Upgrades an outbound connection created by the `dial` method of a transport + * + * @param maConn - The `MultiaddrConnection` to upgrade. + * @param opts - The options for the upgrader. + * + * @example + * + * ```TypeScript + * const connection = await upgrader.upgradeOutbound(maConn) + * ``` */ upgradeOutbound(maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise /** * Upgrades an inbound connection received by a transport listener and * notifies other libp2p components about the new connection + * + * @param maConn - The `MultiaddrConnection` to upgrade. + * @param opts - The options for the upgrader. + * + * @example + * + * ```TypeScript + * await upgrader.upgradeInbound(maConn) + * ``` */ upgradeInbound(maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise