Skip to content

API Reference

This section provides reference documentation for the cmd-ipc API.

The central hub for managing commands and channels. Supports a Hybrid Tree-Mesh architecture with optional routerChannel for command escalation.

import { CommandRegistry } from '@coralstack/cmd-ipc'
const registry = new CommandRegistry({
id: 'my-registry', // Optional: identifier for logging
schemas: { // Optional: enables strict mode with type safety
commands: CommandSchema,
events: EventSchema,
},
routerChannel: 'parent', // Optional: channel ID for escalating unknown commands
logger: console, // Optional: logging interface
requestTTL: 30000, // Optional: TTL for request handlers (default: 30000ms)
eventTTL: 5000, // Optional: TTL for event deduplication (default: 5000ms)
})
OptionTypeDefaultDescription
idstringundefinedIdentifier for logging
schemas{ commands?, events? }undefinedSchema maps for strict mode
routerChannelstringundefinedChannel ID for escalating unknown commands
loggerLoggerundefinedLogging interface (info, warn, error, debug)
requestTTLnumber30000Timeout for pending requests in milliseconds
eventTTLnumber5000TTL for event deduplication in milliseconds
MethodDescription
registerChannel(channel)Register a communication channel
listChannels()Get all registered channel IDs
registerCommand(id, handler)Register a local command handler
listCommands()Get all registered commands with metadata
executeCommand(id, ...args)Execute a command and return the result
emitEvent(eventId, ...args)Broadcast an event to all listeners
addEventListener(eventId, handler)Subscribe to an event, returns unsubscribe function
removeEventListener(eventId, handler)Unsubscribe from an event
dispose()Clean up all resources and close channels

Channel implementation for MessagePort-based communication. Works with Web Workers, Node.js worker_threads, and Electron IPC.

import { MessagePortChannel } from '@coralstack/cmd-ipc'
const { port1, port2 } = new MessageChannel()
const channel = new MessagePortChannel('worker', port1)
await registry.registerChannel(channel)
ParameterTypeDescription
idstringUnique identifier for this channel
portMessagePort | WorkerThe underlying communication port

Channel implementation for HTTP-based communication. Supports two modes: client mode for consuming remote APIs, and server mode for exposing commands via HTTP.

import { HTTPChannel } from '@coralstack/cmd-ipc'
// Client mode - connect to a remote server
const clientChannel = new HTTPChannel({
id: 'api',
baseUrl: 'https://api.example.com',
commandPrefix: 'api', // Remote 'user.create' becomes 'api.user.create'
timeout: 30000,
})
// Server mode - expose commands via HTTP
const serverChannel = new HTTPChannel({
id: 'http-server',
})
OptionTypeDefaultDescription
idstringRequiredUnique identifier
baseUrlstringundefinedClient mode only. Server URL (omit for server mode)
commandPrefixstringundefinedClient mode only. Prefix added to remote command IDs
timeoutnumber30000Request timeout in milliseconds
MethodDescription
start()Start the channel (client mode fetches remote commands)
close()Close the channel
sendMessage(message)Send a message through the channel
handleMessage(body)Server mode only. Handle incoming HTTP request and return response
on(event, listener)Subscribe to ‘message’ or ‘close’ events

Decorator to register a class method as a command handler.

import { Command, registerCommands } from '@coralstack/cmd-ipc'
class MathService {
@Command('math.add')
add({ a, b }: { a: number; b: number }): Promise<number> {
return Promise.resolve(a + b)
}
@Command('math.multiply')
multiply({ a, b }: { a: number; b: number }): Promise<number> {
return Promise.resolve(a * b)
}
}
// Register all decorated methods
registerCommands([new MathService()], registry)

Register command handlers from service class instances.

import { registerCommands } from '@coralstack/cmd-ipc'
// Pass class instances with @Command decorated methods
registerCommands([new MathService(), new UserService()], registry)

Helper function to create type-safe ID constants from a schema map. Converts dot-notation IDs to CONSTANT_CASE.

import { defineIds } from '@coralstack/cmd-ipc'
// For commands
const CommandIds = defineIds(CommandSchema)
// CommandIds.MATH_ADD = 'math.add'
// CommandIds.USER_GET = 'user.get'
// For events
const EventIds = defineIds(EventSchema)
// EventIds.USER_CREATED = 'user.created'
// EventIds.USER_DELETED = 'user.deleted'

Creates a schema document from a command registry for publishing at GET /cmds.json. This enables the CLI to generate TypeScript schemas for remote commands. Only public commands (those without isPrivate: true) are included.

import { publishSchemaDoc } from '@coralstack/cmd-ipc'
// In your HTTP server handler for GET /cmds.json
const schemaDoc = publishSchemaDoc(registry.listCommands())
// Returns: { cmdschema: '1.0.0', commands: [...] }
ParameterTypeDescription
commandsreadonly IListCommandDefinition[]Commands from registry.listCommands()
PropertyTypeDescription
cmdschemastringSchema version (currently '1.0.0')
commandsICommandDefinitionBase[]Array of public command definitions with id, description, and schema
// Express
app.get('/cmds.json', (req, res) => {
res.json(publishSchemaDoc(registry.listCommands()))
})
// Cloudflare Workers
if (request.method === 'GET' && url.pathname === '/cmds.json') {
return new Response(JSON.stringify(publishSchemaDoc(registry.listCommands())), {
headers: { 'Content-Type': 'application/json' }
})
}

Interface for defining command schemas with Valibot.

import type { CommandSchemaMap } from '@coralstack/cmd-ipc'
import * as v from 'valibot'
const CommandSchema = {
'math.add': {
description: 'Add two numbers',
request: v.object({ a: v.number(), b: v.number() }),
response: v.number(),
},
'user.get': {
description: 'Get user by ID',
request: v.object({ id: v.string() }),
response: v.object({ id: v.string(), name: v.string() }),
},
} as const satisfies CommandSchemaMap

Interface for defining event schemas with Valibot.

import type { EventSchemaMap } from '@coralstack/cmd-ipc'
import * as v from 'valibot'
const EventSchema = {
'user.created': v.object({ id: v.string(), name: v.string() }),
'user.deleted': v.object({ id: v.string() }),
} as const satisfies EventSchemaMap

Helper types to extract request/response types from schemas.

import type { CommandRequest, CommandResponse } from '@coralstack/cmd-ipc'
type AddRequest = CommandRequest<typeof CommandSchema, 'math.add'>
// { a: number; b: number }
type AddResponse = CommandResponse<typeof CommandSchema, 'math.add'>
// number

Interface for implementing custom channels.

import type { ICommandChannel } from '@coralstack/cmd-ipc'
class MyChannel implements ICommandChannel {
readonly id: string
constructor(id: string) {
this.id = id
}
async start(): Promise<void> {
// Initialize channel
}
async close(): Promise<void> {
// Cleanup resources
}
sendMessage(message: unknown): void {
// Send message to remote process
}
on(event: 'message', listener: (msg: unknown) => void): void
on(event: 'close', listener: () => void): void
on(event: 'message' | 'close', listener: Function): void {
// Register event listeners
}
}

Generate TypeScript schema from a remote server exposing commands via HTTPChannel.

Terminal window
cmd-ipc generate-schema \
--host <server-url> \
--output <output-file> \
[--prefix <command-prefix>]
OptionAliasDescription
--host-hHost URL without trailing slash (e.g., https://api.example.com)
--output-oOutput file path (e.g., ./src/schemas/remote-commands.ts)
--prefix-pOptional prefix for command IDs (e.g., cloud)
Terminal window
cmd-ipc generate-schema \
--host https://api.example.com \
--output ./src/schemas/cloud-commands.ts \
--prefix cloud

This generates a TypeScript file with Valibot schemas for all commands exposed by the remote server.

A logger that captures output for testing.

import { TestLogger } from '@coralstack/cmd-ipc/testing'
const registry = new CommandRegistry({
id: 'test',
logger: TestLogger,
})