Skip to content

comet ​

@c9up/comet: the JSON-RPC 2.0 protocol (envelopes, parsing, error codes) and a client that runs in the browser and in Node over a transport you inject. Guide: JSON-RPC clients.

Installation ​

bash
pnpm add @c9up/comet

No dependencies and no peer dependencies. The WebSocket transport uses the platform WebSocket (browser, Node 24 and later) unless you pass createSocket.

Entry points ​

ImportContents
@c9up/cometEverything below, and the errors namespace.
@c9up/comet/protocolEnvelope types, builders, parseRequest, RpcError, RpcRemoteError, RpcErrorCode.
@c9up/comet/clientcreateRpcClient and its types.
@c9up/comet/websocketcreateWebSocketTransport and its types.

Exports ​

@c9up/comet ​

ExportKindDescription
errorsnamespaceThe package's errors, one class per code, see Errors. Each is a flare Exception with a string code.

@c9up/comet/client ​

ExportKindDescription
createRpcClientfunctioncreateRpcClient(options: RpcClientOptions): RpcClient.
RpcClientinterfacecall, notify, batch.
RpcClientOptionsinterface{ transport: RpcTransport; url?: string }. url defaults to /rpc.
RpcTransporttype(url: string, body: unknown, options: { signal?: AbortSignal }) => Promise<unknown>. Sends the JSON body as application/json and resolves the parsed reply, or nothing for an empty one (a 204).
RpcCallOptionsinterface{ parse?: (data: unknown) => T; signal?: AbortSignal }.
RpcParsedCallOptionstypeRpcCallOptions<T> with parse required.
RpcCallinterfaceOne call of a batch: { method: string; params?: unknown; parse?: (data: unknown) => T; notify?: boolean }.
RpcResulttype{ ok: true; value: T } | { ok: false; error: RpcError }.

RpcClient ​

MemberSignatureDescription
callcall<T>(method: string, params: unknown, options: RpcParsedCallOptions<T>): Promise<T>The result, validated and typed by parse.
callcall(method: string, params?: unknown, options?: RpcCallOptions): Promise<unknown>Without parse, the result is unknown. Throws RpcRemoteError on a JSON-RPC error.
notifynotify(method: string, params?: unknown, options?: { signal?: AbortSignal }): Promise<void>A notification: no id, no answer. Rejects when the transport does, or when the server refused the envelope.
batchbatch(calls: RpcCall[], options?: { signal?: AbortSignal }): Promise<RpcResult[]>One settled entry per call, in request order. A notification's entry is { ok: true, value: undefined }. The signal aborts the whole batch.

@c9up/comet/protocol ​

ExportKindDescription
parseRequestfunctionparseRequest(request: unknown): ParsedRpcRequest: validates an incoming envelope (version, method, an id that is a string, number or null, params an array or an object).
isNotificationfunctionisNotification(request: unknown): boolean: the envelope has no id.
isReservedMethodNamefunctionisReservedMethodName(name: string): boolean: the name starts with rpc., which the protocol reserves.
buildRequestfunctionbuildRequest(method: string, params: unknown, id: JsonRpcId): JsonRpcRequest. An absent params is left out.
buildNotificationfunctionbuildNotification(method: string, params: unknown): JsonRpcNotification.
buildSuccessfunctionbuildSuccess(result: unknown, id: JsonRpcId): JsonRpcSuccessResponse.
buildErrorfunctionbuildError(code: number, message: string, id: JsonRpcId, data?: unknown): JsonRpcErrorResponse. An absent data is left out.
RpcErrorclassA JSON-RPC error. Throw it from a handler to answer the caller with its code and message.
RpcRemoteErrorclassExtends RpcError: every error the client raises, the server's answer or a reply it could not accept.
RpcErrorCodeconstParseError: -32700, InvalidRequest: -32600, MethodNotFound: -32601, InvalidParams: -32602, InternalError: -32603.
toRpcErrorfunctiontoRpcError(error: unknown): RpcError: reads an error member off the wire; a malformed one becomes an internal error.
isRpcErrorfunctionisRpcError(value: unknown): value is RpcError.
isRpcShapedErrorfunctionisRpcShapedError(err: unknown): err is { code: number; message?: unknown; data?: unknown }: a thrown value a server may answer the caller with.
isObjectfunctionisObject(value: unknown): value is Record<string, unknown>: non-null and not an array.
JsonRpcIdtypestring | number | null.
JsonRpcRequestinterface{ jsonrpc: '2.0'; method: string; params?: unknown; id: JsonRpcId }.
JsonRpcNotificationinterface{ jsonrpc: '2.0'; method: string; params?: unknown }.
JsonRpcSuccessResponseinterface{ jsonrpc: '2.0'; result: unknown; id: JsonRpcId }.
JsonRpcErrorResponseinterface{ jsonrpc: '2.0'; error: JsonRpcErrorObject; id: JsonRpcId }.
JsonRpcErrorObjectinterface{ code: number; message: string; data?: unknown }.
JsonRpcResponsetypeJsonRpcSuccessResponse | JsonRpcErrorResponse.
ParsedRpcRequesttype{ ok: true; method: string; params: unknown; id: JsonRpcId; notification: boolean } | { ok: false; response: JsonRpcErrorResponse }.

RpcError ​

MemberSignatureDescription
constructornew RpcError(code: number, message: string, data?: unknown, options?: ErrorOptions)code is an integer.
codereadonly code: number
datareadonly data?: unknown

isRpcShapedError accepts an RpcError and a plain object whose code is a negative integer. It refuses an RpcRemoteError, so an error from another JSON-RPC server is not forwarded to your caller by accident; to forward one, throw new RpcError(e.code, e.message).

@c9up/comet/websocket ​

ExportKindDescription
createWebSocketTransportfunctioncreateWebSocketTransport(options?: WebSocketTransportOptions): RpcWebSocketTransport.
RpcWebSocketTransporttypeRpcTransport & { close(): void }. close() closes every socket and fails what still waits with E_COMET_TRANSPORT_CLOSED.
WebSocketTransportOptionsinterfaceSee below.
RpcSocketinterfaceWhat the transport needs of a socket: readyState, bufferedAmount, send, close, addEventListener for open, message, close. The standard WebSocket fits.
RpcTransportErrorCodetypeThe E_COMET_* codes of a transport failure, below.

The transport opens one socket per URL, on the first call, and matches answers to callers by its own ids.

WebSocketTransportOptionsTypeDefaultDescription
createSocket(url: string) => RpcSocketthe platform WebSocketOpens a socket; replace it to pass headers in Node.
protocolsstring | string[]noneSubprotocols offered by the default createSocket.
timeoutnumber30000Milliseconds a call waits for its answer, connecting included. Infinity waits while the socket is open.
maxMessageBytesnumber1048576 (1 MiB)Largest message sent or accepted, in UTF-8 bytes.
maxBufferedBytesnumber4194304 (4 MiB)Unsent bytes allowed before a send is refused.
reconnectbooleantrueOpen a new socket on the next call after one closed.

Errors ​

CodeRaised when
E_COMET_CONNECTION_FAILEDThe socket could not be opened: refused handshake, bad URL or network.
E_COMET_CONNECTION_CLOSEDThe socket closed while the call waited, or stays closed (reconnect: false).
E_COMET_TRANSPORT_CLOSEDclose() was called on the transport.
E_COMET_TIMEOUTNo answer within the timeout.
E_COMET_MESSAGE_TOO_LARGEA message over maxMessageBytes, sent or received.
E_COMET_BACKPRESSUREMore than maxBufferedBytes already wait to be sent.
E_COMET_PROTOCOL_ERRORThe peer sent what no JSON-RPC server answers; the socket was closed.
E_COMET_INVALID_MESSAGEThe client handed over something that is not a JSON-RPC message, or not JSON.
E_COMET_INVALID_OPTIONcreateWebSocketTransport() was given a timeout, maxMessageBytes or maxBufferedBytes that is not a positive number, or a timeout past what a timer can wait.

A transport failure is an instance of errors.E_COMET_*, not an answer from the server. A JSON-RPC error the server answered is an RpcRemoteError carrying the server's numeric code.

Migration ​

  • RpcTransportError is gone: each code is its own class. Replace error instanceof RpcTransportError with a test on error.code (error.code === 'E_COMET_TIMEOUT') or with error instanceof errors.E_COMET_TIMEOUT, errors coming from @c9up/comet.
  • An invalid option of createWebSocketTransport() is errors.E_COMET_INVALID_OPTION, no longer a RangeError: catch it by its code.

See also ​