MessagePortChannel
MessagePortChannel enables communication via the MessagePort API, making it ideal for:
- Web Workers
- Node.js
worker_threads MessageChannelinstances- Electron IPC (via adapter)
Basic Usage
Section titled “Basic Usage”Create a MessageChannel and use its ports to connect two registries:
import { MessagePortChannel } from '@coralstack/cmd-ipc'
// Create a MessageChannel with paired portsconst { port1, port2 } = new MessageChannel()
// Main thread keeps port1const channel = new MessagePortChannel('worker', port1)await registry.registerChannel(channel)
// Send port2 to the workerworker.postMessage({ type: 'init' }, [port2])// In the worker - receive port2 and create channelself.onmessage = (event) => { if (event.data.type === 'init' && event.ports[0]) { const channel = new MessagePortChannel('main', event.ports[0]) registry.registerChannel(channel) channel.start() }}Constructor
Section titled “Constructor”new MessagePortChannel(id: string, port: MessagePort)| Parameter | Type | Description |
|---|---|---|
id | string | Unique identifier for this channel |
port | MessagePort | The MessagePort used for communication |
Performance Tips
Section titled “Performance Tips”- Minimize message size - Large messages are serialized/deserialized
- Use transferable objects - For ArrayBuffer, ImageBitmap, etc.
- Batch operations - Multiple small commands have overhead
- Keep handlers fast - Slow handlers block the worker
Debugging
Section titled “Debugging”Enable logging to see message flow:
const registry = new CommandRegistry({ id: 'main', logger: console, // Log all messages})Or use the TestLogger for testing:
import { TestLogger } from '@coralstack/cmd-ipc/testing'
const registry = new CommandRegistry({ id: 'test', logger: TestLogger,})