@trpc/server
Version:
149 lines (148 loc) • 6.82 kB
text/typescript
import "../index-BhZ5IvGf.cjs";
import "../http-BelfYM7N.cjs";
import { An as BaseHandlerOptions, Ei as MaybePromise, n as jsonEncoder, rr as inferRouterContext, t as Encoder, ur as CreateContextCallback, zn as AnyRouter } from "../unstable-core-do-not-import-DdT8GdLp.cjs";
import { NodeHTTPCreateContextFnOptions } from "./node-http/index.cjs";
import { IncomingMessage } from "http";
import { RawData, WebSocket, WebSocketServer } from "ws";
/**
* The members of a connected client that the WebSocket adapter reads, so a
* server that is not `ws` can be served without a cast. A `ws` `WebSocket`
* satisfies them.
* @public
*/
export interface WSClient {
/** The ready state, compared against `OPEN` (1). */
readyState: number;
on(event: 'message', listener: (data: RawData, isBinary: boolean) => void): unknown;
on(event: 'close' | 'error', listener: (cause?: unknown) => void): unknown;
once(event: 'close', listener: () => void): unknown;
send(data: string | Uint8Array): void;
close(code?: number, reason?: string): void;
terminate(): void;
}
/**
* The members of a server that the WebSocket adapter reads: connection
* listeners and the connected clients. A `ws` `WebSocketServer` satisfies
* them.
* @public
*/
export interface WSServer<TClient extends WSClient = WSClient> {
clients: ReadonlySet<TClient>;
on(event: 'connection', listener: (client: TClient, request: IncomingMessage) => void): unknown;
}
type InferWSServerClient<TServer extends WSServer<WSClient>> = TServer['clients'] extends ReadonlySet<infer TClient extends WSClient> ? TClient : never;
/**
* What `createContext` gets in the WebSocket adapter: the upgrade request
* as `req`, the socket as `res`, and `info`. It's called once per
* connection.
* @see https://trpc.io/docs/server/websockets#creating-a-websocket-server
* @public
*/
export type CreateWSSContextFnOptions<TClient extends WSClient = WebSocket> = NodeHTTPCreateContextFnOptions<IncomingMessage, TClient>;
/**
* The `createContext` function the WebSocket adapter takes.
* @public
*/
export type CreateWSSContextFn<TRouter extends AnyRouter, TClient extends WSClient = WebSocket> = (opts: CreateWSSContextFnOptions<TClient>) => MaybePromise<inferRouterContext<TRouter>>;
/** The options of `getWSConnectionHandler`. */
export type WSConnectionHandlerOptions<TRouter extends AnyRouter, TClient extends WSClient = WebSocket> = BaseHandlerOptions<TRouter, IncomingMessage> & CreateContextCallback<inferRouterContext<TRouter>, CreateWSSContextFn<TRouter, TClient>>;
/**
* The options of `applyWSSHandler`.
* @see https://trpc.io/docs/server/websockets#creating-a-websocket-server
*/
type WSConnectionOptionsForServer<TRouter extends AnyRouter, TServer extends WSServer<WSClient>> = WSConnectionHandlerOptions<TRouter, InferWSServerClient<TServer>>;
export type WSSHandlerOptions<TRouter extends AnyRouter, TServer extends WSServer<WSClient> = WebSocketServer> = WSConnectionOptionsForServer<TRouter, TServer> & {
/** The WebSocket server to serve the router on. */
wss: TServer;
/** Only connections whose URL starts with this are served. */
prefix?: string;
/**
* Sends pings to each client and closes connections that stop
* answering.
*/
keepAlive?: {
/**
* Whether to send pings.
* @default false
*/
enabled: boolean;
/**
* How long a connection can be quiet before a ping, in milliseconds.
* @default 30_000
*/
pingMs?: number;
/**
* How long to wait for a pong before closing the connection, in
* milliseconds.
* @default 5_000
*/
pongWaitMs?: number;
};
/**
* Stops answering clients' pings. Meant for tests.
* @default false
*/
dangerouslyDisablePong?: boolean;
/**
* Encodes and decodes messages, for formats other than JSON.
* Experimental: it may change in any release.
* @default jsonEncoder
*/
experimental_encoder?: Encoder;
};
/**
* Returns a `ws` connection listener that serves a router. `applyWSSHandler`
* uses it; call it to attach tRPC to your own WebSocket server.
*/
export declare function getWSConnectionHandler<TRouter extends AnyRouter, TServer extends WSServer<WSClient> = WebSocketServer>(opts: WSSHandlerOptions<TRouter, TServer>): (client: InferWSServerClient<TServer>, req: IncomingMessage) => void;
export declare function getWSConnectionHandler<TRouter extends AnyRouter>(opts: WSSHandlerOptions<TRouter, WSServer>): (client: WSClient, req: IncomingMessage) => void;
export declare function getWSConnectionHandler<TRouter extends AnyRouter>(opts: WSSHandlerOptions<TRouter, WebSocketServer>): (client: WebSocket, req: IncomingMessage) => void;
/**
* Pings a client after `pingMs` of quiet, and closes the connection if no
* message comes within `pongWaitMs`.
*/
export declare function handleKeepAlive(client: WSClient, pingMs?: number, pongWaitMs?: number): void;
export interface WSSHandler {
/** Tells every connected client to reconnect. */
broadcastReconnectNotification: () => void;
}
/**
* Serves a router on a `ws` WebSocket server. Returns
* `broadcastReconnectNotification()`, which tells every client to
* reconnect, for example before a deploy.
* @example
* ```ts
* const wss = new WebSocketServer({ port: 3001 });
* const handler = applyWSSHandler({ wss, router: appRouter, createContext });
* process.on('SIGTERM', () => {
* handler.broadcastReconnectNotification();
* wss.close();
* });
* ```
* @see https://trpc.io/docs/server/websockets#creating-a-websocket-server
*/
export declare function applyWSSHandler<TRouter extends AnyRouter, TServer extends WSServer<WSClient> = WebSocketServer>(opts: WSSHandlerOptions<TRouter, TServer>): WSSHandler;
export declare function applyWSSHandler<TRouter extends AnyRouter>(opts: WSSHandlerOptions<TRouter, WSServer>): WSSHandler;
export declare function applyWSSHandler<TRouter extends AnyRouter>(opts: WSSHandlerOptions<TRouter, WebSocketServer>): WSSHandler;
/**
* Tells every open client of a WebSocket server to reconnect, for example
* before a deploy. Use it where you have the server but not the handler
* `applyWSSHandler` returns, such as `fastify.websocketServer` with the
* Fastify adapter. Every open client gets the message, including ones that
* tRPC doesn't serve.
* @example
* ```ts
* broadcastReconnectNotification(fastify.websocketServer);
* await fastify.close();
* ```
* @see https://trpc.io/docs/server/adapters/fastify#telling-clients-to-reconnect
*/
export declare function broadcastReconnectNotification(wss: Pick<WSServer, 'clients'>, opts?: {
/**
* The encoder the server was set up with, if not JSON.
* @default jsonEncoder
*/
experimental_encoder?: Encoder;
}): void;
export { type Encoder, jsonEncoder };
//# sourceMappingURL=ws.d.cts.map