Skip to content

Channels Overview

Channels are the transport layer in cmd-ipc. They abstract away the underlying communication mechanism, allowing you to use the same command API regardless of whether you’re talking to a Web Worker, an HTTP server, or any other target.

A channel is a bidirectional communication pipe that:

  • Has a unique ID for identification
  • Sends and receives messages
  • Emits events when messages arrive or the connection closes
  • Can operate in client or server mode (depending on the channel type)

cmd-ipc includes three built-in channel implementations:

All channels implement the ICommandChannel interface. You can create custom channels for any transport (WebSocket, gRPC, etc.) by implementing this interface:

interface ICommandChannel {
readonly id: string
start(): Promise<void>
close(): Promise<void>
sendMessage(message: unknown): void
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'close', listener: () => void): void
}
MethodDescription
idUnique identifier for this channel
start()Initialize the channel (called automatically by registry)
close()Close the channel and clean up resources
sendMessage()Send a message through the channel
on('message')Subscribe to incoming messages
on('close')Subscribe to channel close events

Channels are registered with the CommandRegistry:

const channel = new MessagePortChannel('worker', workerPort)
await registry.registerChannel(channel)

When a channel is registered:

  1. The channel’s start() method is called
  2. For client-mode channels, remote commands are discovered
  3. The registry begins routing commands to/from the channel