Skip to content

MessagePortChannel

MessagePortChannel enables communication via the MessagePort API, making it ideal for:

  • Web Workers
  • Node.js worker_threads
  • MessageChannel instances
  • Electron IPC (via adapter)

Create a MessageChannel and use its ports to connect two registries:

import { MessagePortChannel } from '@coralstack/cmd-ipc'
// Create a MessageChannel with paired ports
const { port1, port2 } = new MessageChannel()
// Main thread keeps port1
const channel = new MessagePortChannel('worker', port1)
await registry.registerChannel(channel)
// Send port2 to the worker
worker.postMessage({ type: 'init' }, [port2])
// In the worker - receive port2 and create channel
self.onmessage = (event) => {
if (event.data.type === 'init' && event.ports[0]) {
const channel = new MessagePortChannel('main', event.ports[0])
registry.registerChannel(channel)
channel.start()
}
}
new MessagePortChannel(id: string, port: MessagePort)
ParameterTypeDescription
idstringUnique identifier for this channel
portMessagePortThe MessagePort used for communication
  1. Minimize message size - Large messages are serialized/deserialized
  2. Use transferable objects - For ArrayBuffer, ImageBitmap, etc.
  3. Batch operations - Multiple small commands have overhead
  4. Keep handlers fast - Slow handlers block the worker

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,
})